Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/06/060094b757a1d25b14435b1cf4d989df6ece3c5abc64ad637a41ed100a0de13a/ast_parser.cpython-311.pyc +0 -0
- shared/package-files/06/0600bdcbbe66cf203999ac90486cc347c7a99610220618b0ae573fcc821fe099/test_polynomialring.cpython-311.pyc +0 -0
- shared/package-files/06/0601c9e6868e9c3cff3ea836c8099510ef5b1974c2e447585619c93a1326a5f0/test_groupby.cpython-311.pyc +0 -0
- shared/package-files/06/06043dbc1200bb751f07c4b7c24045e7738d16b55709ba31b3943a53f8d9c2e9/SegmentReduce.h +50 -0
- shared/package-files/06/0604deb1660cc3365ed6a84bba8139715d6afe30955559022e25e7544365e325/prune.py +1372 -0
- shared/package-files/06/0606ec3c5cdeaf9e772a86bc2f5675abc97a862012be42b5d5228bdb01b8e132/linear_ops.h +40 -0
- shared/package-files/06/061101b9748a06c3462430490ed60bd1c191237c17ff0fce2200390fe6312169/sm_20_intrinsics.hpp +221 -0
- shared/package-files/06/061c05003bc9c10a5a90dcbe70b111fa21bf559558deb35f20f4b8d756b1db6d/bam_mate.c.pysam.c +1252 -0
- shared/package-files/06/061f300ea91b48bfb2aff30342a1395d4a16cd96afe49fd5cc2f0b7efdc10650/test_ndarray_like.py +48 -0
- shared/package-files/06/0620689f239b0ac4ba1272d4208ff5903b5c84337b4eeaf44f818cce8528d3a3/pkgdata.py +33 -0
- shared/package-files/06/0624dc495f0084fa8167b834d09a44098fb0fdff8dcb5f0a4320b15602b04ac8/_embedding_bag_sparse_backward_native.h +21 -0
- shared/package-files/06/062c95ed30861d0f06883087f299fa0d7a1fd2e64e95a7c9b38085d1fe402572/test_sort_values.cpython-311.pyc +0 -0
- shared/package-files/06/062f6ebf5e41e4c5d437dfa1c940f21d90e4de3f82a3032c1b550eabbf90be52/fx_symbolic_graph_extractor.py +254 -0
- shared/package-files/06/06363bb2a8bd33adf787d66028d17c99bc1a030cf368a2048a9f087a8f4e02be/test_python.cpython-311.pyc +0 -0
- shared/package-files/06/0636f045562112f6e9f30d39b1877cdfc55f812e1d364b5bf13ee6d8f89c8c23/feather_format.py +143 -0
- shared/package-files/06/0639372bac40320c313cd4ca7e293b482e58db8c202acf0ecf9563bc5772d240/class.h +767 -0
- shared/package-files/06/0640d1e3e3a6c9d3f0c5df43e38de780e38904adbf87f9b1e8608366cf552414/special_psi.h +40 -0
- shared/package-files/06/0643726a604b3902e52b2ea607805274f46300a3f5821679c5cc900e452cfbfb/_conversions.py +119 -0
- shared/package-files/06/064806f0fa6a1892d858494e44382d2c9cf27e2b986a7140610f9bbd331692e8/hts_prog_cc_warnings.m4 +208 -0
- shared/package-files/06/0656ef4ad12ca223866c0f39a4ff61c3cb9f657aea8b18d38c6683ea6b0826e1/test_append.py +986 -0
- shared/package-files/06/0658667d3f0dbbc4c37b070863e78497ab0a8638c0a569170c0ea05a299b24bd/_cufft_get_plan_cache_size_native.h +21 -0
- shared/package-files/06/0658a0f240042117853b765ed9cd0f9c923a3515f6172e7e8142e55adc3cd608/sun.cpython-311.pyc +0 -0
- shared/package-files/06/0659cc7cb2a37602ddcdf6a45e4b03fbaf4fb3b36721ee782c862ec4b0359d1d/test_storage_v3.py +695 -0
- shared/package-files/06/065d8910135bd7c972b1ef8e31d68379fb41709f772ad4d0789acde63d6144e3/multidigraph.cpython-311.pyc +0 -0
- shared/package-files/06/065ec0fe53e8ba84bbb8af049f26eabed317a7a59ab48ed4f3d390c0c79c5956/test_analytics.py +349 -0
- shared/package-files/06/066c81b911f49e5598b2e87dfb479255d510566dd924aa93fd5a6add20976c9d/to_sparse_csr_ops.h +29 -0
- shared/package-files/06/066ed109d0c499f2a2a7921b77a783b12df960571d6d4a0ffdbd1ed18626ff59/chunk_native.h +22 -0
- shared/package-files/06/0673e3297b7562438e66345a6236554a77c4996cc05222c00a07f1db6e1f4d85/__init__.cpython-311.pyc +0 -0
- shared/package-files/06/0675df29e6744f7d3cf74a1d1914541bbc58ad9a356ae968becbda190443427f/miopen-wrapper.h +21 -0
- shared/package-files/06/067c5d6843ebd6f78ce0acad16f76d837dc8ead8360f8cb2f7595f673df3ea76/partitions_.cpython-311.pyc +0 -0
- shared/package-files/06/067cdb6f68dc14e79c7b002446e9c7ebdd8b1cf2203e76676f4bde3fd4084305/kai_ukernel_interface.h +144 -0
- shared/package-files/06/067ebb0bc1123126935f9a875c987589046a7f9ba72077bb4ca1521d7cfebfab/test_subscheck.cpython-311.pyc +0 -0
- shared/package-files/06/0687d2136038b7793c2af2430cf4b4e4e3bcad231462398e66fba772959436d1/_utils.py +47 -0
- shared/package-files/06/068a1600b0d6013bd9ba925a2fbf8615045060ea2d35efc5cb5d48e4d1a1d850/mma.h +761 -0
- shared/package-files/06/068a9409b5608306a8a86095cbfaf8d8c2151ee015f8fde038d155648956a235/fractionfield.py +181 -0
- shared/package-files/06/068c759e5e0cda01113978e09532a50dcd979e1b560fdc541ba20ebeae87300c/closure.py +135 -0
- shared/package-files/06/06907f46e852cea98bf4240fa02a6b453927085feb0758203af2d23d645dfc4a/log2_ops.h +51 -0
- shared/package-files/06/069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5/test_pipe.py +80 -0
- shared/package-files/06/0694aa8e6abdae0abf13d62b3765a2cb5042fcb516c5e344fad4281664a3a5c9/_utils.py +1092 -0
- shared/package-files/06/06956f6920f4f87fb0cf200576d1ae59a12459056ba015ded2b4c98ee68fec51/optimizer.cpython-311.pyc +0 -0
- shared/package-files/06/0699d0c4bb1c2f84de1d9c11e606461fa20d9980d6c575045724fc6ced2007a5/test_memmap.cpython-311.pyc +0 -0
- shared/package-files/06/069d05fc41c1970734e24011ffbbc6467d1b2065221582d6c8b194482bbaae74/is_coalesced_ops.h +29 -0
- shared/package-files/06/069e7437f7ba5cb0a7cc296008d1952d2a6182610f6bb9609d75c7660acf36aa/native_batch_norm_native.h +25 -0
- shared/package-files/06/06a35a654cc16c876b3f585bfbc36ce2a2126f0bc917e5ab1395ed5c215794ca/test_empty.cpython-311.pyc +0 -0
- shared/package-files/06/06a63aae3e1ba541e9ee22604fe402bcc9176f722f5f5ae6b0cf707eeb4ea6d0/basic.cpython-311.pyc +0 -0
- shared/package-files/06/06a68ea13cc90a1897aaccfe81d32887f3679645b26b8337a5dba0ce00f144d2/sqfreetools.cpython-311.pyc +0 -0
- shared/package-files/06/06a7eebedae33b73c47034350de70dcadd9387d629b3ac6e79dd6d118e32b2f9/utils.py +698 -0
- shared/package-files/06/06a8c47343d01f8756cb337580819f8636dfde737860de8993d70be10284e511/maximum.h +40 -0
- shared/package-files/06/06abfbd260d36cf6d6fdec37634c706d3c69cd9cae81902b6713ff414fe048f5/triu_indices_cuda_dispatch.h +24 -0
- shared/package-files/06/06b2e711f499620071a8632d05fde1269b89b218877ea24b1b3f8016609ae6b4/real_ops.h +29 -0
shared/package-files/06/060094b757a1d25b14435b1cf4d989df6ece3c5abc64ad637a41ed100a0de13a/ast_parser.cpython-311.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
shared/package-files/06/0600bdcbbe66cf203999ac90486cc347c7a99610220618b0ae573fcc821fe099/test_polynomialring.cpython-311.pyc
ADDED
|
Binary file (9.66 kB). View file
|
|
|
shared/package-files/06/0601c9e6868e9c3cff3ea836c8099510ef5b1974c2e447585619c93a1326a5f0/test_groupby.cpython-311.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
shared/package-files/06/06043dbc1200bb751f07c4b7c24045e7738d16b55709ba31b3943a53f8d9c2e9/SegmentReduce.h
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
#include <ATen/native/ReductionType.h>
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <optional>
|
| 7 |
+
|
| 8 |
+
namespace at {
|
| 9 |
+
class Tensor;
|
| 10 |
+
|
| 11 |
+
namespace native {
|
| 12 |
+
|
| 13 |
+
using segment_reduce_lengths_fn = Tensor (*)(
|
| 14 |
+
ReductionType,
|
| 15 |
+
const Tensor&,
|
| 16 |
+
const Tensor&,
|
| 17 |
+
int64_t,
|
| 18 |
+
const std::optional<Scalar>&);
|
| 19 |
+
DECLARE_DISPATCH(segment_reduce_lengths_fn, _segment_reduce_lengths_stub)
|
| 20 |
+
|
| 21 |
+
using segment_reduce_offsets_fn = Tensor (*)(
|
| 22 |
+
ReductionType,
|
| 23 |
+
const Tensor&,
|
| 24 |
+
const Tensor&,
|
| 25 |
+
int64_t,
|
| 26 |
+
const std::optional<Scalar>&);
|
| 27 |
+
DECLARE_DISPATCH(segment_reduce_offsets_fn, _segment_reduce_offsets_stub)
|
| 28 |
+
|
| 29 |
+
using segment_reduce_lengths_backward_fn = Tensor (*)(
|
| 30 |
+
const Tensor&,
|
| 31 |
+
const Tensor&,
|
| 32 |
+
const Tensor&,
|
| 33 |
+
ReductionType,
|
| 34 |
+
const Tensor&,
|
| 35 |
+
int64_t,
|
| 36 |
+
const std::optional<Scalar>&);
|
| 37 |
+
DECLARE_DISPATCH(segment_reduce_lengths_backward_fn, _segment_reduce_lengths_backward_stub)
|
| 38 |
+
|
| 39 |
+
using segment_reduce_offsets_backward_fn = Tensor (*)(
|
| 40 |
+
const Tensor&,
|
| 41 |
+
const Tensor&,
|
| 42 |
+
const Tensor&,
|
| 43 |
+
ReductionType,
|
| 44 |
+
const Tensor&,
|
| 45 |
+
int64_t,
|
| 46 |
+
const std::optional<Scalar>&);
|
| 47 |
+
DECLARE_DISPATCH(segment_reduce_offsets_backward_fn, _segment_reduce_offsets_backward_stub)
|
| 48 |
+
|
| 49 |
+
} // namespace native
|
| 50 |
+
} // namespace at
|
shared/package-files/06/0604deb1660cc3365ed6a84bba8139715d6afe30955559022e25e7544365e325/prune.py
ADDED
|
@@ -0,0 +1,1372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
r"""Pruning methods."""
|
| 3 |
+
import numbers
|
| 4 |
+
from abc import ABC, abstractmethod
|
| 5 |
+
from collections.abc import Iterable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BasePruningMethod(ABC):
|
| 11 |
+
r"""Abstract base class for creation of new pruning techniques.
|
| 12 |
+
|
| 13 |
+
Provides a skeleton for customization requiring the overriding of methods
|
| 14 |
+
such as :meth:`compute_mask` and :meth:`apply`.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
_tensor_name: str
|
| 18 |
+
|
| 19 |
+
def __call__(self, module, inputs):
|
| 20 |
+
r"""Multiply the mask into original tensor and store the result.
|
| 21 |
+
|
| 22 |
+
Multiplies the mask (stored in ``module[name + '_mask']``)
|
| 23 |
+
into the original tensor (stored in ``module[name + '_orig']``)
|
| 24 |
+
and stores the result into ``module[name]`` by using :meth:`apply_mask`.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
module (nn.Module): module containing the tensor to prune
|
| 28 |
+
inputs: not used.
|
| 29 |
+
"""
|
| 30 |
+
setattr(module, self._tensor_name, self.apply_mask(module))
|
| 31 |
+
|
| 32 |
+
@abstractmethod
|
| 33 |
+
def compute_mask(self, t, default_mask):
|
| 34 |
+
r"""Compute and returns a mask for the input tensor ``t``.
|
| 35 |
+
|
| 36 |
+
Starting from a base ``default_mask`` (which should be a mask of ones
|
| 37 |
+
if the tensor has not been pruned yet), generate a random mask to
|
| 38 |
+
apply on top of the ``default_mask`` according to the specific pruning
|
| 39 |
+
method recipe.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
t (torch.Tensor): tensor representing the importance scores of the
|
| 43 |
+
parameter to prune.
|
| 44 |
+
default_mask (torch.Tensor): Base mask from previous pruning
|
| 45 |
+
iterations, that need to be respected after the new mask is
|
| 46 |
+
applied. Same dims as ``t``.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def apply_mask(self, module):
|
| 53 |
+
r"""Simply handles the multiplication between the parameter being pruned and the generated mask.
|
| 54 |
+
|
| 55 |
+
Fetches the mask and the original tensor from the module
|
| 56 |
+
and returns the pruned version of the tensor.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
module (nn.Module): module containing the tensor to prune
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
pruned_tensor (torch.Tensor): pruned version of the input tensor
|
| 63 |
+
"""
|
| 64 |
+
# to carry out the multiplication, the mask needs to have been computed,
|
| 65 |
+
# so the pruning method must know what tensor it's operating on
|
| 66 |
+
assert (
|
| 67 |
+
self._tensor_name is not None
|
| 68 |
+
), f"Module {module} has to be pruned" # this gets set in apply()
|
| 69 |
+
mask = getattr(module, self._tensor_name + "_mask")
|
| 70 |
+
orig = getattr(module, self._tensor_name + "_orig")
|
| 71 |
+
pruned_tensor = mask.to(dtype=orig.dtype) * orig
|
| 72 |
+
return pruned_tensor
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def apply(cls, module, name, *args, importance_scores=None, **kwargs):
|
| 76 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 77 |
+
|
| 78 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 79 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 80 |
+
and the pruning mask.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
module (nn.Module): module containing the tensor to prune
|
| 84 |
+
name (str): parameter name within ``module`` on which pruning
|
| 85 |
+
will act.
|
| 86 |
+
args: arguments passed on to a subclass of
|
| 87 |
+
:class:`BasePruningMethod`
|
| 88 |
+
importance_scores (torch.Tensor): tensor of importance scores (of
|
| 89 |
+
same shape as module parameter) used to compute mask for pruning.
|
| 90 |
+
The values in this tensor indicate the importance of the
|
| 91 |
+
corresponding elements in the parameter being pruned.
|
| 92 |
+
If unspecified or None, the parameter will be used in its place.
|
| 93 |
+
kwargs: keyword arguments passed on to a subclass of a
|
| 94 |
+
:class:`BasePruningMethod`
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def _get_composite_method(cls, module, name, *args, **kwargs):
|
| 98 |
+
# Check if a pruning method has already been applied to
|
| 99 |
+
# `module[name]`. If so, store that in `old_method`.
|
| 100 |
+
old_method = None
|
| 101 |
+
found = 0
|
| 102 |
+
# there should technically be only 1 hook with hook.name == name
|
| 103 |
+
# assert this using `found`
|
| 104 |
+
hooks_to_remove = []
|
| 105 |
+
for k, hook in module._forward_pre_hooks.items():
|
| 106 |
+
# if it exists, take existing thing, remove hook, then
|
| 107 |
+
# go through normal thing
|
| 108 |
+
if isinstance(hook, BasePruningMethod) and hook._tensor_name == name:
|
| 109 |
+
old_method = hook
|
| 110 |
+
hooks_to_remove.append(k)
|
| 111 |
+
found += 1
|
| 112 |
+
assert (
|
| 113 |
+
found <= 1
|
| 114 |
+
), f"Avoid adding multiple pruning hooks to the\
|
| 115 |
+
same tensor {name} of module {module}. Use a PruningContainer."
|
| 116 |
+
|
| 117 |
+
for k in hooks_to_remove:
|
| 118 |
+
del module._forward_pre_hooks[k]
|
| 119 |
+
|
| 120 |
+
# Apply the new pruning method, either from scratch or on top of
|
| 121 |
+
# the previous one.
|
| 122 |
+
method = cls(*args, **kwargs) # new pruning
|
| 123 |
+
# Have the pruning method remember what tensor it's been applied to
|
| 124 |
+
method._tensor_name = name
|
| 125 |
+
|
| 126 |
+
# combine `methods` with `old_method`, if `old_method` exists
|
| 127 |
+
if old_method is not None: # meaning that there was a hook
|
| 128 |
+
# if the hook is already a pruning container, just add the
|
| 129 |
+
# new pruning method to the container
|
| 130 |
+
if isinstance(old_method, PruningContainer):
|
| 131 |
+
old_method.add_pruning_method(method)
|
| 132 |
+
method = old_method # rename old_method --> method
|
| 133 |
+
|
| 134 |
+
# if the hook is simply a single pruning method, create a
|
| 135 |
+
# container, add the old pruning method and the new one
|
| 136 |
+
elif isinstance(old_method, BasePruningMethod):
|
| 137 |
+
container = PruningContainer(old_method)
|
| 138 |
+
# Have the pruning method remember the name of its tensor
|
| 139 |
+
# setattr(container, '_tensor_name', name)
|
| 140 |
+
container.add_pruning_method(method)
|
| 141 |
+
method = container # rename container --> method
|
| 142 |
+
return method
|
| 143 |
+
|
| 144 |
+
method = _get_composite_method(cls, module, name, *args, **kwargs)
|
| 145 |
+
# at this point we have no forward_pre_hooks but we could have an
|
| 146 |
+
# active reparametrization of the tensor if another pruning method
|
| 147 |
+
# had been applied (in which case `method` would be a PruningContainer
|
| 148 |
+
# and not a simple pruning method).
|
| 149 |
+
|
| 150 |
+
# Pruning is to be applied to the module's tensor named `name`,
|
| 151 |
+
# starting from the state it is found in prior to this iteration of
|
| 152 |
+
# pruning. The pruning mask is calculated based on importances scores.
|
| 153 |
+
|
| 154 |
+
orig = getattr(module, name)
|
| 155 |
+
if importance_scores is not None:
|
| 156 |
+
assert (
|
| 157 |
+
importance_scores.shape == orig.shape
|
| 158 |
+
), f"importance_scores should have the same shape as parameter {name} of {module}"
|
| 159 |
+
else:
|
| 160 |
+
importance_scores = orig
|
| 161 |
+
|
| 162 |
+
# If this is the first time pruning is applied, take care of moving
|
| 163 |
+
# the original tensor to a new parameter called name + '_orig' and
|
| 164 |
+
# and deleting the original parameter
|
| 165 |
+
if not isinstance(method, PruningContainer):
|
| 166 |
+
# copy `module[name]` to `module[name + '_orig']`
|
| 167 |
+
module.register_parameter(name + "_orig", orig)
|
| 168 |
+
# temporarily delete `module[name]`
|
| 169 |
+
del module._parameters[name]
|
| 170 |
+
default_mask = torch.ones_like(orig) # temp
|
| 171 |
+
# If this is not the first time pruning is applied, all of the above
|
| 172 |
+
# has been done before in a previous pruning iteration, so we're good
|
| 173 |
+
# to go
|
| 174 |
+
else:
|
| 175 |
+
default_mask = (
|
| 176 |
+
getattr(module, name + "_mask")
|
| 177 |
+
.detach()
|
| 178 |
+
.clone(memory_format=torch.contiguous_format)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Use try/except because if anything goes wrong with the mask
|
| 182 |
+
# computation etc., you'd want to roll back.
|
| 183 |
+
try:
|
| 184 |
+
# get the final mask, computed according to the specific method
|
| 185 |
+
mask = method.compute_mask(importance_scores, default_mask=default_mask)
|
| 186 |
+
# reparameterize by saving mask to `module[name + '_mask']`...
|
| 187 |
+
module.register_buffer(name + "_mask", mask)
|
| 188 |
+
# ... and the new pruned tensor to `module[name]`
|
| 189 |
+
setattr(module, name, method.apply_mask(module))
|
| 190 |
+
# associate the pruning method to the module via a hook to
|
| 191 |
+
# compute the function before every forward() (compile by run)
|
| 192 |
+
module.register_forward_pre_hook(method)
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
if not isinstance(method, PruningContainer):
|
| 196 |
+
orig = getattr(module, name + "_orig")
|
| 197 |
+
module.register_parameter(name, orig)
|
| 198 |
+
del module._parameters[name + "_orig"]
|
| 199 |
+
raise e
|
| 200 |
+
|
| 201 |
+
return method
|
| 202 |
+
|
| 203 |
+
def prune(self, t, default_mask=None, importance_scores=None):
|
| 204 |
+
r"""Compute and returns a pruned version of input tensor ``t``.
|
| 205 |
+
|
| 206 |
+
According to the pruning rule specified in :meth:`compute_mask`.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
t (torch.Tensor): tensor to prune (of same dimensions as
|
| 210 |
+
``default_mask``).
|
| 211 |
+
importance_scores (torch.Tensor): tensor of importance scores (of
|
| 212 |
+
same shape as ``t``) used to compute mask for pruning ``t``.
|
| 213 |
+
The values in this tensor indicate the importance of the
|
| 214 |
+
corresponding elements in the ``t`` that is being pruned.
|
| 215 |
+
If unspecified or None, the tensor ``t`` will be used in its place.
|
| 216 |
+
default_mask (torch.Tensor, optional): mask from previous pruning
|
| 217 |
+
iteration, if any. To be considered when determining what
|
| 218 |
+
portion of the tensor that pruning should act on. If None,
|
| 219 |
+
default to a mask of ones.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
pruned version of tensor ``t``.
|
| 223 |
+
"""
|
| 224 |
+
if importance_scores is not None:
|
| 225 |
+
assert (
|
| 226 |
+
importance_scores.shape == t.shape
|
| 227 |
+
), "importance_scores should have the same shape as tensor t"
|
| 228 |
+
else:
|
| 229 |
+
importance_scores = t
|
| 230 |
+
default_mask = default_mask if default_mask is not None else torch.ones_like(t)
|
| 231 |
+
return t * self.compute_mask(importance_scores, default_mask=default_mask)
|
| 232 |
+
|
| 233 |
+
def remove(self, module):
|
| 234 |
+
r"""Remove the pruning reparameterization from a module.
|
| 235 |
+
|
| 236 |
+
The pruned parameter named ``name`` remains permanently pruned,
|
| 237 |
+
and the parameter named ``name+'_orig'`` is removed from the parameter list.
|
| 238 |
+
Similarly, the buffer named ``name+'_mask'`` is removed from the buffers.
|
| 239 |
+
|
| 240 |
+
Note:
|
| 241 |
+
Pruning itself is NOT undone or reversed!
|
| 242 |
+
"""
|
| 243 |
+
# before removing pruning from a tensor, it has to have been applied
|
| 244 |
+
assert (
|
| 245 |
+
self._tensor_name is not None
|
| 246 |
+
), f"Module {module} has to be pruned before pruning can be removed" # this gets set in apply()
|
| 247 |
+
|
| 248 |
+
# to update module[name] to latest trained weights
|
| 249 |
+
weight = self.apply_mask(module) # masked weights
|
| 250 |
+
|
| 251 |
+
# delete and reset
|
| 252 |
+
if hasattr(module, self._tensor_name):
|
| 253 |
+
delattr(module, self._tensor_name)
|
| 254 |
+
orig = module._parameters[self._tensor_name + "_orig"]
|
| 255 |
+
orig.data = weight.data
|
| 256 |
+
del module._parameters[self._tensor_name + "_orig"]
|
| 257 |
+
del module._buffers[self._tensor_name + "_mask"]
|
| 258 |
+
setattr(module, self._tensor_name, orig)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class PruningContainer(BasePruningMethod):
|
| 262 |
+
"""Container holding a sequence of pruning methods for iterative pruning.
|
| 263 |
+
|
| 264 |
+
Keeps track of the order in which pruning methods are applied and handles
|
| 265 |
+
combining successive pruning calls.
|
| 266 |
+
|
| 267 |
+
Accepts as argument an instance of a BasePruningMethod or an iterable of
|
| 268 |
+
them.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
def __init__(self, *args):
|
| 272 |
+
self._pruning_methods: tuple[BasePruningMethod, ...] = ()
|
| 273 |
+
if not isinstance(args, Iterable): # only 1 item
|
| 274 |
+
self._tensor_name = args._tensor_name
|
| 275 |
+
self.add_pruning_method(args)
|
| 276 |
+
elif len(args) == 1: # only 1 item in a tuple
|
| 277 |
+
self._tensor_name = args[0]._tensor_name
|
| 278 |
+
self.add_pruning_method(args[0])
|
| 279 |
+
else: # manual construction from list or other iterable (or no args)
|
| 280 |
+
for method in args:
|
| 281 |
+
self.add_pruning_method(method)
|
| 282 |
+
|
| 283 |
+
def add_pruning_method(self, method):
|
| 284 |
+
r"""Add a child pruning ``method`` to the container.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
method (subclass of BasePruningMethod): child pruning method
|
| 288 |
+
to be added to the container.
|
| 289 |
+
"""
|
| 290 |
+
# check that we're adding a pruning method to the container
|
| 291 |
+
if not isinstance(method, BasePruningMethod) and method is not None:
|
| 292 |
+
raise TypeError(f"{type(method)} is not a BasePruningMethod subclass")
|
| 293 |
+
elif method is not None and self._tensor_name != method._tensor_name:
|
| 294 |
+
raise ValueError(
|
| 295 |
+
"Can only add pruning methods acting on "
|
| 296 |
+
f"the parameter named '{self._tensor_name}' to PruningContainer {self}."
|
| 297 |
+
+ f" Found '{method._tensor_name}'"
|
| 298 |
+
)
|
| 299 |
+
# if all checks passed, add to _pruning_methods tuple
|
| 300 |
+
self._pruning_methods += (method,) # type: ignore[operator]
|
| 301 |
+
|
| 302 |
+
def __len__(self):
|
| 303 |
+
return len(self._pruning_methods)
|
| 304 |
+
|
| 305 |
+
def __iter__(self):
|
| 306 |
+
return iter(self._pruning_methods)
|
| 307 |
+
|
| 308 |
+
def __getitem__(self, idx):
|
| 309 |
+
return self._pruning_methods[idx]
|
| 310 |
+
|
| 311 |
+
def compute_mask(self, t, default_mask):
|
| 312 |
+
r"""Apply the latest ``method`` by computing the new partial masks and returning its combination with the ``default_mask``.
|
| 313 |
+
|
| 314 |
+
The new partial mask should be computed on the entries or channels
|
| 315 |
+
that were not zeroed out by the ``default_mask``.
|
| 316 |
+
Which portions of the tensor ``t`` the new mask will be calculated from
|
| 317 |
+
depends on the ``PRUNING_TYPE`` (handled by the type handler):
|
| 318 |
+
|
| 319 |
+
* for 'unstructured', the mask will be computed from the raveled
|
| 320 |
+
list of nonmasked entries;
|
| 321 |
+
|
| 322 |
+
* for 'structured', the mask will be computed from the nonmasked
|
| 323 |
+
channels in the tensor;
|
| 324 |
+
|
| 325 |
+
* for 'global', the mask will be computed across all entries.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 329 |
+
(of same dimensions as ``default_mask``).
|
| 330 |
+
default_mask (torch.Tensor): mask from previous pruning iteration.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
mask (torch.Tensor): new mask that combines the effects
|
| 334 |
+
of the ``default_mask`` and the new mask from the current
|
| 335 |
+
pruning ``method`` (of same dimensions as ``default_mask`` and
|
| 336 |
+
``t``).
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
def _combine_masks(method, t, mask):
|
| 340 |
+
r"""Combine the masks from all pruning methods and returns a new mask.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
method (a BasePruningMethod subclass): pruning method
|
| 344 |
+
currently being applied.
|
| 345 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 346 |
+
(of same dimensions as mask).
|
| 347 |
+
mask (torch.Tensor): mask from previous pruning iteration
|
| 348 |
+
|
| 349 |
+
Returns:
|
| 350 |
+
new_mask (torch.Tensor): new mask that combines the effects
|
| 351 |
+
of the old mask and the new mask from the current
|
| 352 |
+
pruning method (of same dimensions as mask and t).
|
| 353 |
+
"""
|
| 354 |
+
new_mask = mask # start off from existing mask
|
| 355 |
+
new_mask = new_mask.to(dtype=t.dtype)
|
| 356 |
+
|
| 357 |
+
# compute a slice of t onto which the new pruning method will operate
|
| 358 |
+
if method.PRUNING_TYPE == "unstructured":
|
| 359 |
+
# prune entries of t where the mask is 1
|
| 360 |
+
slc = mask == 1
|
| 361 |
+
|
| 362 |
+
# for struct pruning, exclude channels that have already been
|
| 363 |
+
# entirely pruned
|
| 364 |
+
elif method.PRUNING_TYPE == "structured":
|
| 365 |
+
if not hasattr(method, "dim"):
|
| 366 |
+
raise AttributeError(
|
| 367 |
+
"Pruning methods of PRUNING_TYPE "
|
| 368 |
+
'"structured" need to have the attribute `dim` defined.'
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
# find the channels to keep by removing the ones that have been
|
| 372 |
+
# zeroed out already (i.e. where sum(entries) == 0)
|
| 373 |
+
n_dims = t.dim() # "is this a 2D tensor? 3D? ..."
|
| 374 |
+
dim = method.dim
|
| 375 |
+
# convert negative indexing
|
| 376 |
+
if dim < 0:
|
| 377 |
+
dim = n_dims + dim
|
| 378 |
+
# if dim is still negative after subtracting it from n_dims
|
| 379 |
+
if dim < 0:
|
| 380 |
+
raise IndexError(
|
| 381 |
+
f"Index is out of bounds for tensor with dimensions {n_dims}"
|
| 382 |
+
)
|
| 383 |
+
# find channels along dim = dim that aren't already tots 0ed out
|
| 384 |
+
keep_channel = mask.sum(dim=[d for d in range(n_dims) if d != dim]) != 0
|
| 385 |
+
# create slice to identify what to prune
|
| 386 |
+
slc = [slice(None)] * n_dims
|
| 387 |
+
slc[dim] = keep_channel
|
| 388 |
+
|
| 389 |
+
elif method.PRUNING_TYPE == "global":
|
| 390 |
+
n_dims = len(t.shape) # "is this a 2D tensor? 3D? ..."
|
| 391 |
+
slc = [slice(None)] * n_dims
|
| 392 |
+
|
| 393 |
+
else:
|
| 394 |
+
raise ValueError(f"Unrecognized PRUNING_TYPE {method.PRUNING_TYPE}")
|
| 395 |
+
|
| 396 |
+
# compute the new mask on the unpruned slice of the tensor t
|
| 397 |
+
partial_mask = method.compute_mask(t[slc], default_mask=mask[slc])
|
| 398 |
+
new_mask[slc] = partial_mask.to(dtype=new_mask.dtype)
|
| 399 |
+
|
| 400 |
+
return new_mask
|
| 401 |
+
|
| 402 |
+
method = self._pruning_methods[-1]
|
| 403 |
+
mask = _combine_masks(method, t, default_mask)
|
| 404 |
+
return mask
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class Identity(BasePruningMethod):
|
| 408 |
+
r"""Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones."""
|
| 409 |
+
|
| 410 |
+
PRUNING_TYPE = "unstructured"
|
| 411 |
+
|
| 412 |
+
def compute_mask(self, t, default_mask):
|
| 413 |
+
mask = default_mask
|
| 414 |
+
return mask
|
| 415 |
+
|
| 416 |
+
@classmethod
|
| 417 |
+
def apply(cls, module, name):
|
| 418 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 419 |
+
|
| 420 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 421 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 422 |
+
and the pruning mask.
|
| 423 |
+
|
| 424 |
+
Args:
|
| 425 |
+
module (nn.Module): module containing the tensor to prune
|
| 426 |
+
name (str): parameter name within ``module`` on which pruning
|
| 427 |
+
will act.
|
| 428 |
+
"""
|
| 429 |
+
return super().apply(module, name)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class RandomUnstructured(BasePruningMethod):
|
| 433 |
+
r"""Prune (currently unpruned) units in a tensor at random.
|
| 434 |
+
|
| 435 |
+
Args:
|
| 436 |
+
name (str): parameter name within ``module`` on which pruning
|
| 437 |
+
will act.
|
| 438 |
+
amount (int or float): quantity of parameters to prune.
|
| 439 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 440 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 441 |
+
absolute number of parameters to prune.
|
| 442 |
+
"""
|
| 443 |
+
|
| 444 |
+
PRUNING_TYPE = "unstructured"
|
| 445 |
+
|
| 446 |
+
def __init__(self, amount):
|
| 447 |
+
# Check range of validity of pruning amount
|
| 448 |
+
_validate_pruning_amount_init(amount)
|
| 449 |
+
self.amount = amount
|
| 450 |
+
|
| 451 |
+
def compute_mask(self, t, default_mask):
|
| 452 |
+
# Check that the amount of units to prune is not > than the number of
|
| 453 |
+
# parameters in t
|
| 454 |
+
tensor_size = t.nelement()
|
| 455 |
+
# Compute number of units to prune: amount if int,
|
| 456 |
+
# else amount * tensor_size
|
| 457 |
+
nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
|
| 458 |
+
# This should raise an error if the number of units to prune is larger
|
| 459 |
+
# than the number of units in the tensor
|
| 460 |
+
_validate_pruning_amount(nparams_toprune, tensor_size)
|
| 461 |
+
|
| 462 |
+
mask = default_mask.clone(memory_format=torch.contiguous_format)
|
| 463 |
+
|
| 464 |
+
if nparams_toprune != 0: # k=0 not supported by torch.kthvalue
|
| 465 |
+
prob = torch.rand_like(t)
|
| 466 |
+
topk = torch.topk(prob.view(-1), k=nparams_toprune)
|
| 467 |
+
mask.view(-1)[topk.indices] = 0
|
| 468 |
+
|
| 469 |
+
return mask
|
| 470 |
+
|
| 471 |
+
@classmethod
|
| 472 |
+
def apply(cls, module, name, amount):
|
| 473 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 474 |
+
|
| 475 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 476 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 477 |
+
and the pruning mask.
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
module (nn.Module): module containing the tensor to prune
|
| 481 |
+
name (str): parameter name within ``module`` on which pruning
|
| 482 |
+
will act.
|
| 483 |
+
amount (int or float): quantity of parameters to prune.
|
| 484 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 485 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 486 |
+
absolute number of parameters to prune.
|
| 487 |
+
"""
|
| 488 |
+
return super().apply(module, name, amount=amount)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
class L1Unstructured(BasePruningMethod):
|
| 492 |
+
r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm.
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
amount (int or float): quantity of parameters to prune.
|
| 496 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 497 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 498 |
+
absolute number of parameters to prune.
|
| 499 |
+
"""
|
| 500 |
+
|
| 501 |
+
PRUNING_TYPE = "unstructured"
|
| 502 |
+
|
| 503 |
+
def __init__(self, amount):
|
| 504 |
+
# Check range of validity of pruning amount
|
| 505 |
+
_validate_pruning_amount_init(amount)
|
| 506 |
+
self.amount = amount
|
| 507 |
+
|
| 508 |
+
def compute_mask(self, t, default_mask):
|
| 509 |
+
# Check that the amount of units to prune is not > than the number of
|
| 510 |
+
# parameters in t
|
| 511 |
+
tensor_size = t.nelement()
|
| 512 |
+
# Compute number of units to prune: amount if int,
|
| 513 |
+
# else amount * tensor_size
|
| 514 |
+
nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
|
| 515 |
+
# This should raise an error if the number of units to prune is larger
|
| 516 |
+
# than the number of units in the tensor
|
| 517 |
+
_validate_pruning_amount(nparams_toprune, tensor_size)
|
| 518 |
+
|
| 519 |
+
mask = default_mask.clone(memory_format=torch.contiguous_format)
|
| 520 |
+
|
| 521 |
+
if nparams_toprune != 0: # k=0 not supported by torch.kthvalue
|
| 522 |
+
# largest=True --> top k; largest=False --> bottom k
|
| 523 |
+
# Prune the smallest k
|
| 524 |
+
topk = torch.topk(torch.abs(t).view(-1), k=nparams_toprune, largest=False)
|
| 525 |
+
# topk will have .indices and .values
|
| 526 |
+
mask.view(-1)[topk.indices] = 0
|
| 527 |
+
|
| 528 |
+
return mask
|
| 529 |
+
|
| 530 |
+
@classmethod
|
| 531 |
+
def apply(cls, module, name, amount, importance_scores=None):
|
| 532 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 533 |
+
|
| 534 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 535 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 536 |
+
and the pruning mask.
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
module (nn.Module): module containing the tensor to prune
|
| 540 |
+
name (str): parameter name within ``module`` on which pruning
|
| 541 |
+
will act.
|
| 542 |
+
amount (int or float): quantity of parameters to prune.
|
| 543 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 544 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 545 |
+
absolute number of parameters to prune.
|
| 546 |
+
importance_scores (torch.Tensor): tensor of importance scores (of same
|
| 547 |
+
shape as module parameter) used to compute mask for pruning.
|
| 548 |
+
The values in this tensor indicate the importance of the corresponding
|
| 549 |
+
elements in the parameter being pruned.
|
| 550 |
+
If unspecified or None, the module parameter will be used in its place.
|
| 551 |
+
"""
|
| 552 |
+
return super().apply(
|
| 553 |
+
module, name, amount=amount, importance_scores=importance_scores
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class RandomStructured(BasePruningMethod):
|
| 558 |
+
r"""Prune entire (currently unpruned) channels in a tensor at random.
|
| 559 |
+
|
| 560 |
+
Args:
|
| 561 |
+
amount (int or float): quantity of parameters to prune.
|
| 562 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 563 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 564 |
+
absolute number of parameters to prune.
|
| 565 |
+
dim (int, optional): index of the dim along which we define
|
| 566 |
+
channels to prune. Default: -1.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
PRUNING_TYPE = "structured"
|
| 570 |
+
|
| 571 |
+
def __init__(self, amount, dim=-1):
|
| 572 |
+
# Check range of validity of amount
|
| 573 |
+
_validate_pruning_amount_init(amount)
|
| 574 |
+
self.amount = amount
|
| 575 |
+
self.dim = dim
|
| 576 |
+
|
| 577 |
+
def compute_mask(self, t, default_mask):
|
| 578 |
+
r"""Compute and returns a mask for the input tensor ``t``.
|
| 579 |
+
|
| 580 |
+
Starting from a base ``default_mask`` (which should be a mask of ones
|
| 581 |
+
if the tensor has not been pruned yet), generate a random mask to
|
| 582 |
+
apply on top of the ``default_mask`` by randomly zeroing out channels
|
| 583 |
+
along the specified dim of the tensor.
|
| 584 |
+
|
| 585 |
+
Args:
|
| 586 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 587 |
+
default_mask (torch.Tensor): Base mask from previous pruning
|
| 588 |
+
iterations, that need to be respected after the new mask is
|
| 589 |
+
applied. Same dims as ``t``.
|
| 590 |
+
|
| 591 |
+
Returns:
|
| 592 |
+
mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
|
| 593 |
+
|
| 594 |
+
Raises:
|
| 595 |
+
IndexError: if ``self.dim >= len(t.shape)``
|
| 596 |
+
"""
|
| 597 |
+
# Check that tensor has structure (i.e. more than 1 dimension) such
|
| 598 |
+
# that the concept of "channels" makes sense
|
| 599 |
+
_validate_structured_pruning(t)
|
| 600 |
+
|
| 601 |
+
# Check that self.dim is a valid dim to index t, else raise IndexError
|
| 602 |
+
_validate_pruning_dim(t, self.dim)
|
| 603 |
+
|
| 604 |
+
# Check that the amount of channels to prune is not > than the number of
|
| 605 |
+
# channels in t along the dim to prune
|
| 606 |
+
tensor_size = t.shape[self.dim]
|
| 607 |
+
# Compute number of units to prune: amount if int,
|
| 608 |
+
# else amount * tensor_size
|
| 609 |
+
nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
|
| 610 |
+
# This should raise an error if the number of units to prune is larger
|
| 611 |
+
# than the number of units in the tensor
|
| 612 |
+
_validate_pruning_amount(nparams_toprune, tensor_size)
|
| 613 |
+
|
| 614 |
+
# Compute binary mask by initializing it to all 0s and then filling in
|
| 615 |
+
# 1s wherever topk.indices indicates, along self.dim.
|
| 616 |
+
# mask has the same shape as tensor t
|
| 617 |
+
def make_mask(t, dim, nchannels, nchannels_toprune):
|
| 618 |
+
# generate a random number in [0, 1] to associate to each channel
|
| 619 |
+
prob = torch.rand(nchannels)
|
| 620 |
+
# generate mask for each channel by 0ing out the channels that
|
| 621 |
+
# got assigned the k = nchannels_toprune lowest values in prob
|
| 622 |
+
threshold = torch.kthvalue(prob, k=nchannels_toprune).values
|
| 623 |
+
channel_mask = prob > threshold
|
| 624 |
+
|
| 625 |
+
mask = torch.zeros_like(t)
|
| 626 |
+
slc = [slice(None)] * len(t.shape)
|
| 627 |
+
slc[dim] = channel_mask
|
| 628 |
+
mask[slc] = 1
|
| 629 |
+
return mask
|
| 630 |
+
|
| 631 |
+
if nparams_toprune == 0: # k=0 not supported by torch.kthvalue
|
| 632 |
+
mask = default_mask
|
| 633 |
+
else:
|
| 634 |
+
# apply the new structured mask on top of prior (potentially
|
| 635 |
+
# unstructured) mask
|
| 636 |
+
mask = make_mask(t, self.dim, tensor_size, nparams_toprune)
|
| 637 |
+
mask *= default_mask.to(dtype=mask.dtype)
|
| 638 |
+
return mask
|
| 639 |
+
|
| 640 |
+
@classmethod
|
| 641 |
+
def apply(cls, module, name, amount, dim=-1):
|
| 642 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 643 |
+
|
| 644 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 645 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 646 |
+
and the pruning mask.
|
| 647 |
+
|
| 648 |
+
Args:
|
| 649 |
+
module (nn.Module): module containing the tensor to prune
|
| 650 |
+
name (str): parameter name within ``module`` on which pruning
|
| 651 |
+
will act.
|
| 652 |
+
amount (int or float): quantity of parameters to prune.
|
| 653 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 654 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 655 |
+
absolute number of parameters to prune.
|
| 656 |
+
dim (int, optional): index of the dim along which we define
|
| 657 |
+
channels to prune. Default: -1.
|
| 658 |
+
"""
|
| 659 |
+
return super().apply(module, name, amount=amount, dim=dim)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
class LnStructured(BasePruningMethod):
|
| 663 |
+
r"""Prune entire (currently unpruned) channels in a tensor based on their L\ ``n``-norm.
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
amount (int or float): quantity of channels to prune.
|
| 667 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 668 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 669 |
+
absolute number of parameters to prune.
|
| 670 |
+
n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
|
| 671 |
+
entries for argument ``p`` in :func:`torch.norm`.
|
| 672 |
+
dim (int, optional): index of the dim along which we define
|
| 673 |
+
channels to prune. Default: -1.
|
| 674 |
+
"""
|
| 675 |
+
|
| 676 |
+
PRUNING_TYPE = "structured"
|
| 677 |
+
|
| 678 |
+
def __init__(self, amount, n, dim=-1):
|
| 679 |
+
# Check range of validity of amount
|
| 680 |
+
_validate_pruning_amount_init(amount)
|
| 681 |
+
self.amount = amount
|
| 682 |
+
self.n = n
|
| 683 |
+
self.dim = dim
|
| 684 |
+
|
| 685 |
+
def compute_mask(self, t, default_mask):
|
| 686 |
+
r"""Compute and returns a mask for the input tensor ``t``.
|
| 687 |
+
|
| 688 |
+
Starting from a base ``default_mask`` (which should be a mask of ones
|
| 689 |
+
if the tensor has not been pruned yet), generate a mask to apply on
|
| 690 |
+
top of the ``default_mask`` by zeroing out the channels along the
|
| 691 |
+
specified dim with the lowest L\ ``n``-norm.
|
| 692 |
+
|
| 693 |
+
Args:
|
| 694 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 695 |
+
default_mask (torch.Tensor): Base mask from previous pruning
|
| 696 |
+
iterations, that need to be respected after the new mask is
|
| 697 |
+
applied. Same dims as ``t``.
|
| 698 |
+
|
| 699 |
+
Returns:
|
| 700 |
+
mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
|
| 701 |
+
|
| 702 |
+
Raises:
|
| 703 |
+
IndexError: if ``self.dim >= len(t.shape)``
|
| 704 |
+
"""
|
| 705 |
+
# Check that tensor has structure (i.e. more than 1 dimension) such
|
| 706 |
+
# that the concept of "channels" makes sense
|
| 707 |
+
_validate_structured_pruning(t)
|
| 708 |
+
# Check that self.dim is a valid dim to index t, else raise IndexError
|
| 709 |
+
_validate_pruning_dim(t, self.dim)
|
| 710 |
+
|
| 711 |
+
# Check that the amount of channels to prune is not > than the number of
|
| 712 |
+
# channels in t along the dim to prune
|
| 713 |
+
tensor_size = t.shape[self.dim]
|
| 714 |
+
# Compute number of units to prune: amount if int,
|
| 715 |
+
# else amount * tensor_size
|
| 716 |
+
nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
|
| 717 |
+
nparams_tokeep = tensor_size - nparams_toprune
|
| 718 |
+
# This should raise an error if the number of units to prune is larger
|
| 719 |
+
# than the number of units in the tensor
|
| 720 |
+
_validate_pruning_amount(nparams_toprune, tensor_size)
|
| 721 |
+
|
| 722 |
+
# Structured pruning prunes entire channels so we need to know the
|
| 723 |
+
# L_n norm along each channel to then find the topk based on this
|
| 724 |
+
# metric
|
| 725 |
+
norm = _compute_norm(t, self.n, self.dim)
|
| 726 |
+
# largest=True --> top k; largest=False --> bottom k
|
| 727 |
+
# Keep the largest k channels along dim=self.dim
|
| 728 |
+
topk = torch.topk(norm, k=nparams_tokeep, largest=True)
|
| 729 |
+
# topk will have .indices and .values
|
| 730 |
+
|
| 731 |
+
# Compute binary mask by initializing it to all 0s and then filling in
|
| 732 |
+
# 1s wherever topk.indices indicates, along self.dim.
|
| 733 |
+
# mask has the same shape as tensor t
|
| 734 |
+
def make_mask(t, dim, indices):
|
| 735 |
+
# init mask to 0
|
| 736 |
+
mask = torch.zeros_like(t)
|
| 737 |
+
# e.g.: slc = [None, None, None], if len(t.shape) = 3
|
| 738 |
+
slc = [slice(None)] * len(t.shape)
|
| 739 |
+
# replace a None at position=dim with indices
|
| 740 |
+
# e.g.: slc = [None, None, [0, 2, 3]] if dim=2 & indices=[0,2,3]
|
| 741 |
+
slc[dim] = indices
|
| 742 |
+
# use slc to slice mask and replace all its entries with 1s
|
| 743 |
+
# e.g.: mask[:, :, [0, 2, 3]] = 1
|
| 744 |
+
mask[slc] = 1
|
| 745 |
+
return mask
|
| 746 |
+
|
| 747 |
+
if nparams_toprune == 0: # k=0 not supported by torch.kthvalue
|
| 748 |
+
mask = default_mask
|
| 749 |
+
else:
|
| 750 |
+
mask = make_mask(t, self.dim, topk.indices)
|
| 751 |
+
mask *= default_mask.to(dtype=mask.dtype)
|
| 752 |
+
|
| 753 |
+
return mask
|
| 754 |
+
|
| 755 |
+
@classmethod
|
| 756 |
+
def apply(cls, module, name, amount, n, dim, importance_scores=None):
|
| 757 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 758 |
+
|
| 759 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 760 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 761 |
+
and the pruning mask.
|
| 762 |
+
|
| 763 |
+
Args:
|
| 764 |
+
module (nn.Module): module containing the tensor to prune
|
| 765 |
+
name (str): parameter name within ``module`` on which pruning
|
| 766 |
+
will act.
|
| 767 |
+
amount (int or float): quantity of parameters to prune.
|
| 768 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 769 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 770 |
+
absolute number of parameters to prune.
|
| 771 |
+
n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
|
| 772 |
+
entries for argument ``p`` in :func:`torch.norm`.
|
| 773 |
+
dim (int): index of the dim along which we define channels to
|
| 774 |
+
prune.
|
| 775 |
+
importance_scores (torch.Tensor): tensor of importance scores (of same
|
| 776 |
+
shape as module parameter) used to compute mask for pruning.
|
| 777 |
+
The values in this tensor indicate the importance of the corresponding
|
| 778 |
+
elements in the parameter being pruned.
|
| 779 |
+
If unspecified or None, the module parameter will be used in its place.
|
| 780 |
+
"""
|
| 781 |
+
return super().apply(
|
| 782 |
+
module,
|
| 783 |
+
name,
|
| 784 |
+
amount=amount,
|
| 785 |
+
n=n,
|
| 786 |
+
dim=dim,
|
| 787 |
+
importance_scores=importance_scores,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
class CustomFromMask(BasePruningMethod):
|
| 792 |
+
PRUNING_TYPE = "global"
|
| 793 |
+
|
| 794 |
+
def __init__(self, mask):
|
| 795 |
+
self.mask = mask
|
| 796 |
+
|
| 797 |
+
def compute_mask(self, t, default_mask):
|
| 798 |
+
assert default_mask.shape == self.mask.shape
|
| 799 |
+
mask = default_mask * self.mask.to(dtype=default_mask.dtype)
|
| 800 |
+
return mask
|
| 801 |
+
|
| 802 |
+
@classmethod
|
| 803 |
+
def apply(cls, module, name, mask):
|
| 804 |
+
r"""Add pruning on the fly and reparametrization of a tensor.
|
| 805 |
+
|
| 806 |
+
Adds the forward pre-hook that enables pruning on the fly and
|
| 807 |
+
the reparametrization of a tensor in terms of the original tensor
|
| 808 |
+
and the pruning mask.
|
| 809 |
+
|
| 810 |
+
Args:
|
| 811 |
+
module (nn.Module): module containing the tensor to prune
|
| 812 |
+
name (str): parameter name within ``module`` on which pruning
|
| 813 |
+
will act.
|
| 814 |
+
"""
|
| 815 |
+
return super().apply(module, name, mask=mask)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def identity(module, name):
|
| 819 |
+
r"""Apply pruning reparametrization without pruning any units.
|
| 820 |
+
|
| 821 |
+
Applies pruning reparametrization to the tensor corresponding to the
|
| 822 |
+
parameter called ``name`` in ``module`` without actually pruning any
|
| 823 |
+
units. Modifies module in place (and also return the modified module)
|
| 824 |
+
by:
|
| 825 |
+
|
| 826 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 827 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 828 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 829 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 830 |
+
``name+'_orig'``.
|
| 831 |
+
|
| 832 |
+
Note:
|
| 833 |
+
The mask is a tensor of ones.
|
| 834 |
+
|
| 835 |
+
Args:
|
| 836 |
+
module (nn.Module): module containing the tensor to prune.
|
| 837 |
+
name (str): parameter name within ``module`` on which pruning
|
| 838 |
+
will act.
|
| 839 |
+
|
| 840 |
+
Returns:
|
| 841 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 842 |
+
|
| 843 |
+
Examples:
|
| 844 |
+
>>> # xdoctest: +SKIP
|
| 845 |
+
>>> m = prune.identity(nn.Linear(2, 3), 'bias')
|
| 846 |
+
>>> print(m.bias_mask)
|
| 847 |
+
tensor([1., 1., 1.])
|
| 848 |
+
"""
|
| 849 |
+
Identity.apply(module, name)
|
| 850 |
+
return module
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def random_unstructured(module, name, amount):
|
| 854 |
+
r"""Prune tensor by removing random (currently unpruned) units.
|
| 855 |
+
|
| 856 |
+
Prunes tensor corresponding to parameter called ``name`` in ``module``
|
| 857 |
+
by removing the specified ``amount`` of (currently unpruned) units
|
| 858 |
+
selected at random.
|
| 859 |
+
Modifies module in place (and also return the modified module) by:
|
| 860 |
+
|
| 861 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 862 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 863 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 864 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 865 |
+
``name+'_orig'``.
|
| 866 |
+
|
| 867 |
+
Args:
|
| 868 |
+
module (nn.Module): module containing the tensor to prune
|
| 869 |
+
name (str): parameter name within ``module`` on which pruning
|
| 870 |
+
will act.
|
| 871 |
+
amount (int or float): quantity of parameters to prune.
|
| 872 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 873 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 874 |
+
absolute number of parameters to prune.
|
| 875 |
+
|
| 876 |
+
Returns:
|
| 877 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 878 |
+
|
| 879 |
+
Examples:
|
| 880 |
+
>>> # xdoctest: +SKIP
|
| 881 |
+
>>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1)
|
| 882 |
+
>>> torch.sum(m.weight_mask == 0)
|
| 883 |
+
tensor(1)
|
| 884 |
+
|
| 885 |
+
"""
|
| 886 |
+
RandomUnstructured.apply(module, name, amount)
|
| 887 |
+
return module
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def l1_unstructured(module, name, amount, importance_scores=None):
|
| 891 |
+
r"""Prune tensor by removing units with the lowest L1-norm.
|
| 892 |
+
|
| 893 |
+
Prunes tensor corresponding to parameter called ``name`` in ``module``
|
| 894 |
+
by removing the specified `amount` of (currently unpruned) units with the
|
| 895 |
+
lowest L1-norm.
|
| 896 |
+
Modifies module in place (and also return the modified module)
|
| 897 |
+
by:
|
| 898 |
+
|
| 899 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 900 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 901 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 902 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 903 |
+
``name+'_orig'``.
|
| 904 |
+
|
| 905 |
+
Args:
|
| 906 |
+
module (nn.Module): module containing the tensor to prune
|
| 907 |
+
name (str): parameter name within ``module`` on which pruning
|
| 908 |
+
will act.
|
| 909 |
+
amount (int or float): quantity of parameters to prune.
|
| 910 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 911 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 912 |
+
absolute number of parameters to prune.
|
| 913 |
+
importance_scores (torch.Tensor): tensor of importance scores (of same
|
| 914 |
+
shape as module parameter) used to compute mask for pruning.
|
| 915 |
+
The values in this tensor indicate the importance of the corresponding
|
| 916 |
+
elements in the parameter being pruned.
|
| 917 |
+
If unspecified or None, the module parameter will be used in its place.
|
| 918 |
+
|
| 919 |
+
Returns:
|
| 920 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 921 |
+
|
| 922 |
+
Examples:
|
| 923 |
+
>>> # xdoctest: +SKIP
|
| 924 |
+
>>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2)
|
| 925 |
+
>>> m.state_dict().keys()
|
| 926 |
+
odict_keys(['bias', 'weight_orig', 'weight_mask'])
|
| 927 |
+
"""
|
| 928 |
+
L1Unstructured.apply(
|
| 929 |
+
module, name, amount=amount, importance_scores=importance_scores
|
| 930 |
+
)
|
| 931 |
+
return module
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def random_structured(module, name, amount, dim):
|
| 935 |
+
r"""Prune tensor by removing random channels along the specified dimension.
|
| 936 |
+
|
| 937 |
+
Prunes tensor corresponding to parameter called ``name`` in ``module``
|
| 938 |
+
by removing the specified ``amount`` of (currently unpruned) channels
|
| 939 |
+
along the specified ``dim`` selected at random.
|
| 940 |
+
Modifies module in place (and also return the modified module)
|
| 941 |
+
by:
|
| 942 |
+
|
| 943 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 944 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 945 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 946 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 947 |
+
``name+'_orig'``.
|
| 948 |
+
|
| 949 |
+
Args:
|
| 950 |
+
module (nn.Module): module containing the tensor to prune
|
| 951 |
+
name (str): parameter name within ``module`` on which pruning
|
| 952 |
+
will act.
|
| 953 |
+
amount (int or float): quantity of parameters to prune.
|
| 954 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 955 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 956 |
+
absolute number of parameters to prune.
|
| 957 |
+
dim (int): index of the dim along which we define channels to prune.
|
| 958 |
+
|
| 959 |
+
Returns:
|
| 960 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 961 |
+
|
| 962 |
+
Examples:
|
| 963 |
+
>>> # xdoctest: +SKIP
|
| 964 |
+
>>> m = prune.random_structured(
|
| 965 |
+
... nn.Linear(5, 3), 'weight', amount=3, dim=1
|
| 966 |
+
... )
|
| 967 |
+
>>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0))
|
| 968 |
+
>>> print(columns_pruned)
|
| 969 |
+
3
|
| 970 |
+
"""
|
| 971 |
+
RandomStructured.apply(module, name, amount, dim)
|
| 972 |
+
return module
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def ln_structured(module, name, amount, n, dim, importance_scores=None):
|
| 976 |
+
r"""Prune tensor by removing channels with the lowest L\ ``n``-norm along the specified dimension.
|
| 977 |
+
|
| 978 |
+
Prunes tensor corresponding to parameter called ``name`` in ``module``
|
| 979 |
+
by removing the specified ``amount`` of (currently unpruned) channels
|
| 980 |
+
along the specified ``dim`` with the lowest L\ ``n``-norm.
|
| 981 |
+
Modifies module in place (and also return the modified module)
|
| 982 |
+
by:
|
| 983 |
+
|
| 984 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 985 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 986 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 987 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 988 |
+
``name+'_orig'``.
|
| 989 |
+
|
| 990 |
+
Args:
|
| 991 |
+
module (nn.Module): module containing the tensor to prune
|
| 992 |
+
name (str): parameter name within ``module`` on which pruning
|
| 993 |
+
will act.
|
| 994 |
+
amount (int or float): quantity of parameters to prune.
|
| 995 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 996 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 997 |
+
absolute number of parameters to prune.
|
| 998 |
+
n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
|
| 999 |
+
entries for argument ``p`` in :func:`torch.norm`.
|
| 1000 |
+
dim (int): index of the dim along which we define channels to prune.
|
| 1001 |
+
importance_scores (torch.Tensor): tensor of importance scores (of same
|
| 1002 |
+
shape as module parameter) used to compute mask for pruning.
|
| 1003 |
+
The values in this tensor indicate the importance of the corresponding
|
| 1004 |
+
elements in the parameter being pruned.
|
| 1005 |
+
If unspecified or None, the module parameter will be used in its place.
|
| 1006 |
+
|
| 1007 |
+
Returns:
|
| 1008 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 1009 |
+
|
| 1010 |
+
Examples:
|
| 1011 |
+
>>> from torch.nn.utils import prune
|
| 1012 |
+
>>> m = prune.ln_structured(
|
| 1013 |
+
... nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf')
|
| 1014 |
+
... )
|
| 1015 |
+
"""
|
| 1016 |
+
LnStructured.apply(
|
| 1017 |
+
module, name, amount, n, dim, importance_scores=importance_scores
|
| 1018 |
+
)
|
| 1019 |
+
return module
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs):
|
| 1023 |
+
r"""
|
| 1024 |
+
Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``.
|
| 1025 |
+
|
| 1026 |
+
Modifies modules in place by:
|
| 1027 |
+
|
| 1028 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 1029 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 1030 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 1031 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 1032 |
+
``name+'_orig'``.
|
| 1033 |
+
|
| 1034 |
+
Args:
|
| 1035 |
+
parameters (Iterable of (module, name) tuples): parameters of
|
| 1036 |
+
the model to prune in a global fashion, i.e. by aggregating all
|
| 1037 |
+
weights prior to deciding which ones to prune. module must be of
|
| 1038 |
+
type :class:`nn.Module`, and name must be a string.
|
| 1039 |
+
pruning_method (function): a valid pruning function from this module,
|
| 1040 |
+
or a custom one implemented by the user that satisfies the
|
| 1041 |
+
implementation guidelines and has ``PRUNING_TYPE='unstructured'``.
|
| 1042 |
+
importance_scores (dict): a dictionary mapping (module, name) tuples to
|
| 1043 |
+
the corresponding parameter's importance scores tensor. The tensor
|
| 1044 |
+
should be the same shape as the parameter, and is used for computing
|
| 1045 |
+
mask for pruning.
|
| 1046 |
+
If unspecified or None, the parameter will be used in place of its
|
| 1047 |
+
importance scores.
|
| 1048 |
+
kwargs: other keyword arguments such as:
|
| 1049 |
+
amount (int or float): quantity of parameters to prune across the
|
| 1050 |
+
specified parameters.
|
| 1051 |
+
If ``float``, should be between 0.0 and 1.0 and represent the
|
| 1052 |
+
fraction of parameters to prune. If ``int``, it represents the
|
| 1053 |
+
absolute number of parameters to prune.
|
| 1054 |
+
|
| 1055 |
+
Raises:
|
| 1056 |
+
TypeError: if ``PRUNING_TYPE != 'unstructured'``
|
| 1057 |
+
|
| 1058 |
+
Note:
|
| 1059 |
+
Since global structured pruning doesn't make much sense unless the
|
| 1060 |
+
norm is normalized by the size of the parameter, we now limit the
|
| 1061 |
+
scope of global pruning to unstructured methods.
|
| 1062 |
+
|
| 1063 |
+
Examples:
|
| 1064 |
+
>>> from torch.nn.utils import prune
|
| 1065 |
+
>>> from collections import OrderedDict
|
| 1066 |
+
>>> net = nn.Sequential(OrderedDict([
|
| 1067 |
+
... ('first', nn.Linear(10, 4)),
|
| 1068 |
+
... ('second', nn.Linear(4, 1)),
|
| 1069 |
+
... ]))
|
| 1070 |
+
>>> parameters_to_prune = (
|
| 1071 |
+
... (net.first, 'weight'),
|
| 1072 |
+
... (net.second, 'weight'),
|
| 1073 |
+
... )
|
| 1074 |
+
>>> prune.global_unstructured(
|
| 1075 |
+
... parameters_to_prune,
|
| 1076 |
+
... pruning_method=prune.L1Unstructured,
|
| 1077 |
+
... amount=10,
|
| 1078 |
+
... )
|
| 1079 |
+
>>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0))
|
| 1080 |
+
tensor(10)
|
| 1081 |
+
|
| 1082 |
+
"""
|
| 1083 |
+
# ensure parameters is a list or generator of tuples
|
| 1084 |
+
if not isinstance(parameters, Iterable):
|
| 1085 |
+
raise TypeError("global_unstructured(): parameters is not an Iterable")
|
| 1086 |
+
|
| 1087 |
+
importance_scores = importance_scores if importance_scores is not None else {}
|
| 1088 |
+
if not isinstance(importance_scores, dict):
|
| 1089 |
+
raise TypeError("global_unstructured(): importance_scores must be of type dict")
|
| 1090 |
+
|
| 1091 |
+
# flatten importance scores to consider them all at once in global pruning
|
| 1092 |
+
relevant_importance_scores = torch.nn.utils.parameters_to_vector(
|
| 1093 |
+
[
|
| 1094 |
+
importance_scores.get((module, name), getattr(module, name))
|
| 1095 |
+
for (module, name) in parameters
|
| 1096 |
+
]
|
| 1097 |
+
)
|
| 1098 |
+
# similarly, flatten the masks (if they exist), or use a flattened vector
|
| 1099 |
+
# of 1s of the same dimensions as t
|
| 1100 |
+
default_mask = torch.nn.utils.parameters_to_vector(
|
| 1101 |
+
[
|
| 1102 |
+
getattr(module, name + "_mask", torch.ones_like(getattr(module, name)))
|
| 1103 |
+
for (module, name) in parameters
|
| 1104 |
+
]
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
# use the canonical pruning methods to compute the new mask, even if the
|
| 1108 |
+
# parameter is now a flattened out version of `parameters`
|
| 1109 |
+
container = PruningContainer()
|
| 1110 |
+
container._tensor_name = "temp" # to make it match that of `method`
|
| 1111 |
+
method = pruning_method(**kwargs)
|
| 1112 |
+
method._tensor_name = "temp" # to make it match that of `container`
|
| 1113 |
+
if method.PRUNING_TYPE != "unstructured":
|
| 1114 |
+
raise TypeError(
|
| 1115 |
+
'Only "unstructured" PRUNING_TYPE supported for '
|
| 1116 |
+
f"the `pruning_method`. Found method {pruning_method} of type {method.PRUNING_TYPE}"
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
container.add_pruning_method(method)
|
| 1120 |
+
|
| 1121 |
+
# use the `compute_mask` method from `PruningContainer` to combine the
|
| 1122 |
+
# mask computed by the new method with the pre-existing mask
|
| 1123 |
+
final_mask = container.compute_mask(relevant_importance_scores, default_mask)
|
| 1124 |
+
|
| 1125 |
+
# Pointer for slicing the mask to match the shape of each parameter
|
| 1126 |
+
pointer = 0
|
| 1127 |
+
for module, name in parameters:
|
| 1128 |
+
param = getattr(module, name)
|
| 1129 |
+
# The length of the parameter
|
| 1130 |
+
num_param = param.numel()
|
| 1131 |
+
# Slice the mask, reshape it
|
| 1132 |
+
param_mask = final_mask[pointer : pointer + num_param].view_as(param)
|
| 1133 |
+
# Assign the correct pre-computed mask to each parameter and add it
|
| 1134 |
+
# to the forward_pre_hooks like any other pruning method
|
| 1135 |
+
custom_from_mask(module, name, mask=param_mask)
|
| 1136 |
+
|
| 1137 |
+
# Increment the pointer to continue slicing the final_mask
|
| 1138 |
+
pointer += num_param
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def custom_from_mask(module, name, mask):
|
| 1142 |
+
r"""Prune tensor corresponding to parameter called ``name`` in ``module`` by applying the pre-computed mask in ``mask``.
|
| 1143 |
+
|
| 1144 |
+
Modifies module in place (and also return the modified module) by:
|
| 1145 |
+
|
| 1146 |
+
1) adding a named buffer called ``name+'_mask'`` corresponding to the
|
| 1147 |
+
binary mask applied to the parameter ``name`` by the pruning method.
|
| 1148 |
+
2) replacing the parameter ``name`` by its pruned version, while the
|
| 1149 |
+
original (unpruned) parameter is stored in a new parameter named
|
| 1150 |
+
``name+'_orig'``.
|
| 1151 |
+
|
| 1152 |
+
Args:
|
| 1153 |
+
module (nn.Module): module containing the tensor to prune
|
| 1154 |
+
name (str): parameter name within ``module`` on which pruning
|
| 1155 |
+
will act.
|
| 1156 |
+
mask (Tensor): binary mask to be applied to the parameter.
|
| 1157 |
+
|
| 1158 |
+
Returns:
|
| 1159 |
+
module (nn.Module): modified (i.e. pruned) version of the input module
|
| 1160 |
+
|
| 1161 |
+
Examples:
|
| 1162 |
+
>>> from torch.nn.utils import prune
|
| 1163 |
+
>>> m = prune.custom_from_mask(
|
| 1164 |
+
... nn.Linear(5, 3), name='bias', mask=torch.tensor([0, 1, 0])
|
| 1165 |
+
... )
|
| 1166 |
+
>>> print(m.bias_mask)
|
| 1167 |
+
tensor([0., 1., 0.])
|
| 1168 |
+
|
| 1169 |
+
"""
|
| 1170 |
+
CustomFromMask.apply(module, name, mask)
|
| 1171 |
+
return module
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def remove(module, name):
|
| 1175 |
+
r"""Remove the pruning reparameterization from a module and the pruning method from the forward hook.
|
| 1176 |
+
|
| 1177 |
+
The pruned parameter named ``name`` remains permanently pruned, and the parameter
|
| 1178 |
+
named ``name+'_orig'`` is removed from the parameter list. Similarly,
|
| 1179 |
+
the buffer named ``name+'_mask'`` is removed from the buffers.
|
| 1180 |
+
|
| 1181 |
+
Note:
|
| 1182 |
+
Pruning itself is NOT undone or reversed!
|
| 1183 |
+
|
| 1184 |
+
Args:
|
| 1185 |
+
module (nn.Module): module containing the tensor to prune
|
| 1186 |
+
name (str): parameter name within ``module`` on which pruning
|
| 1187 |
+
will act.
|
| 1188 |
+
|
| 1189 |
+
Examples:
|
| 1190 |
+
>>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2)
|
| 1191 |
+
>>> m = remove(m, name='weight')
|
| 1192 |
+
"""
|
| 1193 |
+
for k, hook in module._forward_pre_hooks.items():
|
| 1194 |
+
if isinstance(hook, BasePruningMethod) and hook._tensor_name == name:
|
| 1195 |
+
hook.remove(module)
|
| 1196 |
+
del module._forward_pre_hooks[k]
|
| 1197 |
+
return module
|
| 1198 |
+
|
| 1199 |
+
raise ValueError(
|
| 1200 |
+
f"Parameter '{name}' of module {module} has to be pruned before pruning can be removed"
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
def is_pruned(module):
|
| 1205 |
+
r"""Check if a module is pruned by looking for pruning pre-hooks.
|
| 1206 |
+
|
| 1207 |
+
Check whether ``module`` is pruned by looking for
|
| 1208 |
+
``forward_pre_hooks`` in its modules that inherit from the
|
| 1209 |
+
:class:`BasePruningMethod`.
|
| 1210 |
+
|
| 1211 |
+
Args:
|
| 1212 |
+
module (nn.Module): object that is either pruned or unpruned
|
| 1213 |
+
|
| 1214 |
+
Returns:
|
| 1215 |
+
binary answer to whether ``module`` is pruned.
|
| 1216 |
+
|
| 1217 |
+
Examples:
|
| 1218 |
+
>>> from torch.nn.utils import prune
|
| 1219 |
+
>>> m = nn.Linear(5, 7)
|
| 1220 |
+
>>> print(prune.is_pruned(m))
|
| 1221 |
+
False
|
| 1222 |
+
>>> prune.random_unstructured(m, name='weight', amount=0.2)
|
| 1223 |
+
>>> print(prune.is_pruned(m))
|
| 1224 |
+
True
|
| 1225 |
+
"""
|
| 1226 |
+
for _, submodule in module.named_modules():
|
| 1227 |
+
for hook in submodule._forward_pre_hooks.values():
|
| 1228 |
+
if isinstance(hook, BasePruningMethod):
|
| 1229 |
+
return True
|
| 1230 |
+
return False
|
| 1231 |
+
|
| 1232 |
+
|
| 1233 |
+
def _validate_pruning_amount_init(amount):
|
| 1234 |
+
r"""Validate helper to check the range of amount at init.
|
| 1235 |
+
|
| 1236 |
+
Args:
|
| 1237 |
+
amount (int or float): quantity of parameters to prune.
|
| 1238 |
+
If float, should be between 0.0 and 1.0 and represent the
|
| 1239 |
+
fraction of parameters to prune. If int, it represents the
|
| 1240 |
+
absolute number of parameters to prune.
|
| 1241 |
+
|
| 1242 |
+
Raises:
|
| 1243 |
+
ValueError: if amount is a float not in [0, 1], or if it's a negative
|
| 1244 |
+
integer.
|
| 1245 |
+
TypeError: if amount is neither a float nor an integer.
|
| 1246 |
+
|
| 1247 |
+
Note:
|
| 1248 |
+
This does not take into account the number of parameters in the
|
| 1249 |
+
tensor to be pruned, which is known only at prune.
|
| 1250 |
+
"""
|
| 1251 |
+
if not isinstance(amount, numbers.Real):
|
| 1252 |
+
raise TypeError(f"Invalid type for amount: {amount}. Must be int or float.")
|
| 1253 |
+
|
| 1254 |
+
if (isinstance(amount, numbers.Integral) and amount < 0) or (
|
| 1255 |
+
not isinstance(amount, numbers.Integral) # so it's a float
|
| 1256 |
+
and (float(amount) > 1.0 or float(amount) < 0.0)
|
| 1257 |
+
):
|
| 1258 |
+
raise ValueError(
|
| 1259 |
+
f"amount={amount} should either be a float in the range [0, 1] or a non-negative integer"
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
def _validate_pruning_amount(amount, tensor_size):
|
| 1264 |
+
r"""Validate that the pruning amount is meaningful wrt to the size of the data.
|
| 1265 |
+
|
| 1266 |
+
Validation helper to check that the amount of parameters to prune
|
| 1267 |
+
is meaningful wrt to the size of the data (`tensor_size`).
|
| 1268 |
+
|
| 1269 |
+
Args:
|
| 1270 |
+
amount (int or float): quantity of parameters to prune.
|
| 1271 |
+
If float, should be between 0.0 and 1.0 and represent the
|
| 1272 |
+
fraction of parameters to prune. If int, it represents the
|
| 1273 |
+
absolute number of parameters to prune.
|
| 1274 |
+
tensor_size (int): absolute number of parameters in the tensor
|
| 1275 |
+
to prune.
|
| 1276 |
+
"""
|
| 1277 |
+
# TODO: consider removing this check and allowing users to specify
|
| 1278 |
+
# a number of units to prune that is greater than the number of units
|
| 1279 |
+
# left to prune. In this case, the tensor will just be fully pruned.
|
| 1280 |
+
|
| 1281 |
+
if isinstance(amount, numbers.Integral) and amount > tensor_size:
|
| 1282 |
+
raise ValueError(
|
| 1283 |
+
f"amount={amount} should be smaller than the number of parameters to prune={tensor_size}"
|
| 1284 |
+
)
|
| 1285 |
+
|
| 1286 |
+
|
| 1287 |
+
def _validate_structured_pruning(t):
|
| 1288 |
+
r"""Validate that the tensor to be pruned is at least 2-Dimensional.
|
| 1289 |
+
|
| 1290 |
+
Validation helper to check that the tensor to be pruned is multi-
|
| 1291 |
+
dimensional, such that the concept of "channels" is well-defined.
|
| 1292 |
+
|
| 1293 |
+
Args:
|
| 1294 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 1295 |
+
|
| 1296 |
+
Raises:
|
| 1297 |
+
ValueError: if the tensor `t` is not at least 2D.
|
| 1298 |
+
"""
|
| 1299 |
+
shape = t.shape
|
| 1300 |
+
if len(shape) <= 1:
|
| 1301 |
+
raise ValueError(
|
| 1302 |
+
"Structured pruning can only be applied to "
|
| 1303 |
+
"multidimensional tensors. Found tensor of shape "
|
| 1304 |
+
f"{shape} with {len(shape)} dims"
|
| 1305 |
+
)
|
| 1306 |
+
|
| 1307 |
+
|
| 1308 |
+
def _compute_nparams_toprune(amount, tensor_size):
|
| 1309 |
+
r"""Convert the pruning amount from a percentage to absolute value.
|
| 1310 |
+
|
| 1311 |
+
Since amount can be expressed either in absolute value or as a
|
| 1312 |
+
percentage of the number of units/channels in a tensor, this utility
|
| 1313 |
+
function converts the percentage to absolute value to standardize
|
| 1314 |
+
the handling of pruning.
|
| 1315 |
+
|
| 1316 |
+
Args:
|
| 1317 |
+
amount (int or float): quantity of parameters to prune.
|
| 1318 |
+
If float, should be between 0.0 and 1.0 and represent the
|
| 1319 |
+
fraction of parameters to prune. If int, it represents the
|
| 1320 |
+
absolute number of parameters to prune.
|
| 1321 |
+
tensor_size (int): absolute number of parameters in the tensor
|
| 1322 |
+
to prune.
|
| 1323 |
+
|
| 1324 |
+
Returns:
|
| 1325 |
+
int: the number of units to prune in the tensor
|
| 1326 |
+
"""
|
| 1327 |
+
# incorrect type already checked in _validate_pruning_amount_init
|
| 1328 |
+
if isinstance(amount, numbers.Integral):
|
| 1329 |
+
return amount
|
| 1330 |
+
else:
|
| 1331 |
+
return round(amount * tensor_size)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
def _validate_pruning_dim(t, dim):
|
| 1335 |
+
r"""Validate that the pruning dimension is within the bounds of the tensor dimension.
|
| 1336 |
+
|
| 1337 |
+
Args:
|
| 1338 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 1339 |
+
dim (int): index of the dim along which we define channels to prune
|
| 1340 |
+
"""
|
| 1341 |
+
if dim >= t.dim():
|
| 1342 |
+
raise IndexError(f"Invalid index {dim} for tensor of size {t.shape}")
|
| 1343 |
+
|
| 1344 |
+
|
| 1345 |
+
def _compute_norm(t, n, dim):
|
| 1346 |
+
r"""Compute the L_n-norm of a tensor along all dimensions except for the specified dimension.
|
| 1347 |
+
|
| 1348 |
+
The L_n-norm will be computed across all entries in tensor `t` along all dimension
|
| 1349 |
+
except for the one identified by dim.
|
| 1350 |
+
Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim),
|
| 1351 |
+
then norm will have Size [4], and each entry will represent the
|
| 1352 |
+
`L_n`-norm computed using the 3x2=6 entries for each of the 4 channels.
|
| 1353 |
+
|
| 1354 |
+
Args:
|
| 1355 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 1356 |
+
n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
|
| 1357 |
+
entries for argument p in torch.norm
|
| 1358 |
+
dim (int): dim identifying the channels to prune
|
| 1359 |
+
|
| 1360 |
+
Returns:
|
| 1361 |
+
norm (torch.Tensor): L_n norm computed across all dimensions except
|
| 1362 |
+
for `dim`. By construction, `norm.shape = t.shape[-1]`.
|
| 1363 |
+
"""
|
| 1364 |
+
# dims = all axes, except for the one identified by `dim`
|
| 1365 |
+
dims = list(range(t.dim()))
|
| 1366 |
+
# convert negative indexing
|
| 1367 |
+
if dim < 0:
|
| 1368 |
+
dim = dims[dim]
|
| 1369 |
+
dims.remove(dim)
|
| 1370 |
+
|
| 1371 |
+
norm = torch.norm(t, p=n, dim=dims)
|
| 1372 |
+
return norm
|
shared/package-files/06/0606ec3c5cdeaf9e772a86bc2f5675abc97a862012be42b5d5228bdb01b8e132/linear_ops.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API linear {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const ::std::optional<at::Tensor> &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::linear";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API linear_out {
|
| 30 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const ::std::optional<at::Tensor> &, at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::linear";
|
| 34 |
+
static constexpr const char* overload_name = "out";
|
| 35 |
+
static constexpr const char* schema_str = "linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!)";
|
| 36 |
+
static at::Tensor & call(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias, at::Tensor & out);
|
| 37 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias, at::Tensor & out);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/06/061101b9748a06c3462430490ed60bd1c191237c17ff0fce2200390fe6312169/sm_20_intrinsics.hpp
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
|
| 5 |
+
*
|
| 6 |
+
* This source code and/or documentation ("Licensed Deliverables") are
|
| 7 |
+
* subject to NVIDIA intellectual property rights under U.S. and
|
| 8 |
+
* international Copyright laws.
|
| 9 |
+
*
|
| 10 |
+
* These Licensed Deliverables contained herein is PROPRIETARY and
|
| 11 |
+
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
|
| 12 |
+
* conditions of a form of NVIDIA software license agreement by and
|
| 13 |
+
* between NVIDIA and Licensee ("License Agreement") or electronically
|
| 14 |
+
* accepted by Licensee. Notwithstanding any terms or conditions to
|
| 15 |
+
* the contrary in the License Agreement, reproduction or disclosure
|
| 16 |
+
* of the Licensed Deliverables to any third party without the express
|
| 17 |
+
* written consent of NVIDIA is prohibited.
|
| 18 |
+
*
|
| 19 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 20 |
+
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
|
| 21 |
+
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
|
| 22 |
+
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
|
| 23 |
+
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
|
| 24 |
+
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
|
| 25 |
+
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
|
| 26 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 27 |
+
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
|
| 28 |
+
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
|
| 29 |
+
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 30 |
+
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 31 |
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 32 |
+
* OF THESE LICENSED DELIVERABLES.
|
| 33 |
+
*
|
| 34 |
+
* U.S. Government End Users. These Licensed Deliverables are a
|
| 35 |
+
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
|
| 36 |
+
* 1995), consisting of "commercial computer software" and "commercial
|
| 37 |
+
* computer software documentation" as such terms are used in 48
|
| 38 |
+
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
|
| 39 |
+
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
|
| 40 |
+
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
|
| 41 |
+
* U.S. Government End Users acquire the Licensed Deliverables with
|
| 42 |
+
* only those rights set forth herein.
|
| 43 |
+
*
|
| 44 |
+
* Any use of the Licensed Deliverables in individual and commercial
|
| 45 |
+
* software must include, in the user documentation and internal
|
| 46 |
+
* comments to the code, the above Disclaimer and U.S. Government End
|
| 47 |
+
* Users Notice.
|
| 48 |
+
*/
|
| 49 |
+
|
| 50 |
+
#if !defined(__SM_20_INTRINSICS_HPP__)
|
| 51 |
+
#define __SM_20_INTRINSICS_HPP__
|
| 52 |
+
|
| 53 |
+
#if defined(__CUDACC_RTC__)
|
| 54 |
+
#define __SM_20_INTRINSICS_DECL__ __device__
|
| 55 |
+
#else /* __CUDACC_RTC__ */
|
| 56 |
+
#define __SM_20_INTRINSICS_DECL__ static __inline__ __device__
|
| 57 |
+
#endif /* __CUDACC_RTC__ */
|
| 58 |
+
|
| 59 |
+
#if defined(__cplusplus) && defined(__CUDACC__)
|
| 60 |
+
|
| 61 |
+
/*******************************************************************************
|
| 62 |
+
* *
|
| 63 |
+
* *
|
| 64 |
+
* *
|
| 65 |
+
*******************************************************************************/
|
| 66 |
+
|
| 67 |
+
#include "cuda_runtime_api.h"
|
| 68 |
+
|
| 69 |
+
/*******************************************************************************
|
| 70 |
+
* *
|
| 71 |
+
* *
|
| 72 |
+
* *
|
| 73 |
+
*******************************************************************************/
|
| 74 |
+
|
| 75 |
+
__SM_20_INTRINSICS_DECL__ unsigned int ballot(bool pred)
|
| 76 |
+
{
|
| 77 |
+
return __ballot((int)pred);
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
__SM_20_INTRINSICS_DECL__ int syncthreads_count(bool pred)
|
| 81 |
+
{
|
| 82 |
+
return __syncthreads_count((int)pred);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
__SM_20_INTRINSICS_DECL__ bool syncthreads_and(bool pred)
|
| 86 |
+
{
|
| 87 |
+
return (bool)__syncthreads_and((int)pred);
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
__SM_20_INTRINSICS_DECL__ bool syncthreads_or(bool pred)
|
| 91 |
+
{
|
| 92 |
+
return (bool)__syncthreads_or((int)pred);
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
extern "C" {
|
| 97 |
+
__device__ unsigned __nv_isGlobal_impl(const void *);
|
| 98 |
+
__device__ unsigned __nv_isShared_impl(const void *);
|
| 99 |
+
__device__ unsigned __nv_isConstant_impl(const void *);
|
| 100 |
+
__device__ unsigned __nv_isLocal_impl(const void *);
|
| 101 |
+
__device__ unsigned __nv_isGridConstant_impl(const void *);
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
__SM_20_INTRINSICS_DECL__ unsigned int __isGlobal(const void *ptr)
|
| 105 |
+
{
|
| 106 |
+
return __nv_isGlobal_impl(ptr);
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
__SM_20_INTRINSICS_DECL__ unsigned int __isShared(const void *ptr)
|
| 110 |
+
{
|
| 111 |
+
return __nv_isShared_impl(ptr);
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
__SM_20_INTRINSICS_DECL__ unsigned int __isConstant(const void *ptr)
|
| 115 |
+
{
|
| 116 |
+
return __nv_isConstant_impl(ptr);
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
__SM_20_INTRINSICS_DECL__ unsigned int __isLocal(const void *ptr)
|
| 120 |
+
{
|
| 121 |
+
return __nv_isLocal_impl(ptr);
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
#if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700)
|
| 125 |
+
__SM_20_INTRINSICS_DECL__ unsigned int __isGridConstant(const void *ptr)
|
| 126 |
+
{
|
| 127 |
+
return __nv_isGridConstant_impl(ptr);
|
| 128 |
+
}
|
| 129 |
+
#endif /* !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) */
|
| 130 |
+
|
| 131 |
+
extern "C" {
|
| 132 |
+
__device__ size_t __nv_cvta_generic_to_global_impl(const void *);
|
| 133 |
+
__device__ size_t __nv_cvta_generic_to_shared_impl(const void *);
|
| 134 |
+
__device__ size_t __nv_cvta_generic_to_constant_impl(const void *);
|
| 135 |
+
__device__ size_t __nv_cvta_generic_to_local_impl(const void *);
|
| 136 |
+
__device__ void * __nv_cvta_global_to_generic_impl(size_t);
|
| 137 |
+
__device__ void * __nv_cvta_shared_to_generic_impl(size_t);
|
| 138 |
+
__device__ void * __nv_cvta_constant_to_generic_impl(size_t);
|
| 139 |
+
__device__ void * __nv_cvta_local_to_generic_impl(size_t);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_global(const void *p)
|
| 143 |
+
{
|
| 144 |
+
return __nv_cvta_generic_to_global_impl(p);
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_shared(const void *p)
|
| 148 |
+
{
|
| 149 |
+
return __nv_cvta_generic_to_shared_impl(p);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_constant(const void *p)
|
| 153 |
+
{
|
| 154 |
+
return __nv_cvta_generic_to_constant_impl(p);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_local(const void *p)
|
| 158 |
+
{
|
| 159 |
+
return __nv_cvta_generic_to_local_impl(p);
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
__SM_20_INTRINSICS_DECL__ void * __cvta_global_to_generic(size_t rawbits)
|
| 163 |
+
{
|
| 164 |
+
return __nv_cvta_global_to_generic_impl(rawbits);
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
__SM_20_INTRINSICS_DECL__ void * __cvta_shared_to_generic(size_t rawbits)
|
| 168 |
+
{
|
| 169 |
+
return __nv_cvta_shared_to_generic_impl(rawbits);
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
__SM_20_INTRINSICS_DECL__ void * __cvta_constant_to_generic(size_t rawbits)
|
| 173 |
+
{
|
| 174 |
+
return __nv_cvta_constant_to_generic_impl(rawbits);
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
__SM_20_INTRINSICS_DECL__ void * __cvta_local_to_generic(size_t rawbits)
|
| 178 |
+
{
|
| 179 |
+
return __nv_cvta_local_to_generic_impl(rawbits);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
#if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700)
|
| 183 |
+
#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)
|
| 184 |
+
#define __CVTA_PTR_64 1
|
| 185 |
+
#endif
|
| 186 |
+
|
| 187 |
+
__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_grid_constant(const void *ptr)
|
| 188 |
+
{
|
| 189 |
+
#if __CVTA_PTR_64
|
| 190 |
+
unsigned long long ret;
|
| 191 |
+
asm("cvta.to.param.u64 %0, %1;" : "=l"(ret) : "l"(ptr));
|
| 192 |
+
#else /* !__CVTA_PTR_64 */
|
| 193 |
+
unsigned ret;
|
| 194 |
+
asm("cvta.to.param.u32 %0, %1;" : "=r"(ret) : "r"(ptr));
|
| 195 |
+
#endif /* __CVTA_PTR_64 */
|
| 196 |
+
return (size_t)ret;
|
| 197 |
+
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
__SM_20_INTRINSICS_DECL__ void * __cvta_grid_constant_to_generic(size_t rawbits)
|
| 201 |
+
{
|
| 202 |
+
void *ret;
|
| 203 |
+
#if __CVTA_PTR_64
|
| 204 |
+
unsigned long long in = rawbits;
|
| 205 |
+
asm("cvta.param.u64 %0, %1;" : "=l"(ret) : "l"(in));
|
| 206 |
+
#else /* !__CVTA_PTR_64 */
|
| 207 |
+
unsigned in = rawbits;
|
| 208 |
+
asm("cvta.param.u32 %0, %1;" : "=r"(ret) : "r"(in));
|
| 209 |
+
#endif /* __CVTA_PTR_64 */
|
| 210 |
+
return ret;
|
| 211 |
+
}
|
| 212 |
+
#undef __CVTA_PTR_64
|
| 213 |
+
#endif /* !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) */
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
#endif /* __cplusplus && __CUDACC__ */
|
| 217 |
+
|
| 218 |
+
#undef __SM_20_INTRINSICS_DECL__
|
| 219 |
+
|
| 220 |
+
#endif /* !__SM_20_INTRINSICS_HPP__ */
|
| 221 |
+
|
shared/package-files/06/061c05003bc9c10a5a90dcbe70b111fa21bf559558deb35f20f4b8d756b1db6d/bam_mate.c.pysam.c
ADDED
|
@@ -0,0 +1,1252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "samtools.pysam.h"
|
| 2 |
+
|
| 3 |
+
/* bam_mate.c -- fix mate pairing information and clean up flags.
|
| 4 |
+
|
| 5 |
+
Copyright (C) 2009, 2011-2017, 2019, 2022, 2024 Genome Research Ltd.
|
| 6 |
+
Portions copyright (C) 2011 Broad Institute.
|
| 7 |
+
Portions copyright (C) 2012 Peter Cock, The James Hutton Institute.
|
| 8 |
+
|
| 9 |
+
Author: Heng Li <lh3@sanger.ac.uk>
|
| 10 |
+
|
| 11 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 12 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 13 |
+
in the Software without restriction, including without limitation the rights
|
| 14 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 15 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 16 |
+
furnished to do so, subject to the following conditions:
|
| 17 |
+
|
| 18 |
+
The above copyright notices and this permission notice shall be included in
|
| 19 |
+
all copies or substantial portions of the Software.
|
| 20 |
+
|
| 21 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 22 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 23 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
| 24 |
+
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 25 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 26 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 27 |
+
DEALINGS IN THE SOFTWARE. */
|
| 28 |
+
|
| 29 |
+
#include <config.h>
|
| 30 |
+
|
| 31 |
+
#include <assert.h>
|
| 32 |
+
#include <stdbool.h>
|
| 33 |
+
#include <stdlib.h>
|
| 34 |
+
#include <string.h>
|
| 35 |
+
#include <unistd.h>
|
| 36 |
+
#include <ctype.h>
|
| 37 |
+
#include "htslib/thread_pool.h"
|
| 38 |
+
#include "sam_opts.h"
|
| 39 |
+
#include "htslib/kstring.h"
|
| 40 |
+
#include "htslib/sam.h"
|
| 41 |
+
#include "samtools.h"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
#define MD_MIN_QUALITY 15
|
| 45 |
+
|
| 46 |
+
/*
|
| 47 |
+
* This function calculates ct tag for two bams, it assumes they are from the same template and
|
| 48 |
+
* writes the tag to the first read in position terms.
|
| 49 |
+
*/
|
| 50 |
+
static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str)
|
| 51 |
+
{
|
| 52 |
+
bam1_t *swap;
|
| 53 |
+
int i;
|
| 54 |
+
hts_pos_t end;
|
| 55 |
+
uint32_t *cigar;
|
| 56 |
+
str->l = 0;
|
| 57 |
+
if (b1->core.tid != b2->core.tid || b1->core.tid < 0 || b1->core.pos < 0 || b2->core.pos < 0 || b1->core.flag&BAM_FUNMAP || b2->core.flag&BAM_FUNMAP) return; // coordinateless or not on the same chr; skip
|
| 58 |
+
if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate
|
| 59 |
+
kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
|
| 60 |
+
kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
|
| 61 |
+
for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) {
|
| 62 |
+
kputw(bam_cigar_oplen(cigar[i]), str);
|
| 63 |
+
kputc(bam_cigar_opchr(cigar[i]), str);
|
| 64 |
+
}
|
| 65 |
+
end = bam_endpos(b1);
|
| 66 |
+
kputw(b2->core.pos - end, str);
|
| 67 |
+
kputc('T', str);
|
| 68 |
+
kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
|
| 69 |
+
kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
|
| 70 |
+
for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) {
|
| 71 |
+
kputw(bam_cigar_oplen(cigar[i]), str);
|
| 72 |
+
kputc(bam_cigar_opchr(cigar[i]), str);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
uint8_t* data;
|
| 76 |
+
if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data);
|
| 77 |
+
if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data);
|
| 78 |
+
|
| 79 |
+
bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s);
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/*
|
| 83 |
+
* What This Program is Supposed To Do:
|
| 84 |
+
* Fill in mate coordinates, ISIZE and mate related flags from a name-sorted
|
| 85 |
+
* alignment.
|
| 86 |
+
*
|
| 87 |
+
* How We Handle Input
|
| 88 |
+
*
|
| 89 |
+
* Secondary and supplementary Reads:
|
| 90 |
+
* -write to output unchanged
|
| 91 |
+
* All Reads:
|
| 92 |
+
* -if pos == 0 (1 based), tid == -1 set UNMAPPED flag
|
| 93 |
+
* single Reads:
|
| 94 |
+
* -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0,
|
| 95 |
+
* tid = -1
|
| 96 |
+
* -clear bad flags (MREVERSE, PROPER_PAIR)
|
| 97 |
+
* -set mpos = 0 (1 based), mtid = -1 and isize = 0
|
| 98 |
+
* -write to output
|
| 99 |
+
* Paired Reads:
|
| 100 |
+
* -if read is unmapped and mate is not, set pos and tid to equal that of mate
|
| 101 |
+
* -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid
|
| 102 |
+
* -recalculate ISIZE if possible, otherwise set it to 0
|
| 103 |
+
* -optionally clear PROPER_PAIR flag from reads where mapping or orientation
|
| 104 |
+
* indicate this is not possible (Illumina orientation only)
|
| 105 |
+
* -calculate ct and apply to lowest positioned read
|
| 106 |
+
* -write to output
|
| 107 |
+
* Limitations
|
| 108 |
+
* -Does not handle tandem reads
|
| 109 |
+
* -Should mark supplementary reads the same as primary.
|
| 110 |
+
* Notes
|
| 111 |
+
* -CT definition appears to be something else in spec, this was in here before
|
| 112 |
+
* I started tampering with it, anyone know what is going on here? To work
|
| 113 |
+
* around this I have demoted the CT this tool generates to ct.
|
| 114 |
+
*/
|
| 115 |
+
|
| 116 |
+
static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) {
|
| 117 |
+
if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) {
|
| 118 |
+
// Set unmapped read's RNAME and POS to those of its mapped mate
|
| 119 |
+
// (recommended best practice, ensures if coord sort will be together)
|
| 120 |
+
dest->core.tid = src->core.tid;
|
| 121 |
+
dest->core.pos = src->core.pos;
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
static void sync_mate_inner(bam1_t* src, bam1_t* dest)
|
| 126 |
+
{
|
| 127 |
+
// sync mate pos information
|
| 128 |
+
dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos;
|
| 129 |
+
// sync flag info
|
| 130 |
+
if (src->core.flag&BAM_FREVERSE)
|
| 131 |
+
dest->core.flag |= BAM_FMREVERSE;
|
| 132 |
+
else
|
| 133 |
+
dest->core.flag &= ~BAM_FMREVERSE;
|
| 134 |
+
if (src->core.flag & BAM_FUNMAP) {
|
| 135 |
+
dest->core.flag |= BAM_FMUNMAP;
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// Is it plausible that these reads are properly paired?
|
| 140 |
+
// Can't really give definitive answer without checking isize
|
| 141 |
+
static bool plausibly_properly_paired(bam1_t* a, bam1_t* b)
|
| 142 |
+
{
|
| 143 |
+
if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false;
|
| 144 |
+
assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly
|
| 145 |
+
|
| 146 |
+
if (a->core.tid != b->core.tid) return false;
|
| 147 |
+
|
| 148 |
+
bam1_t* first = a;
|
| 149 |
+
bam1_t* second = b;
|
| 150 |
+
hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos;
|
| 151 |
+
hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos;
|
| 152 |
+
if (a_pos > b_pos) {
|
| 153 |
+
first = b;
|
| 154 |
+
second = a;
|
| 155 |
+
} else {
|
| 156 |
+
first = a;
|
| 157 |
+
second = b;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE))
|
| 161 |
+
return true;
|
| 162 |
+
else
|
| 163 |
+
return false;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
// Returns 0 on success, -1 on failure.
|
| 167 |
+
static int bam_format_cigar(const bam1_t* b, kstring_t* str)
|
| 168 |
+
{
|
| 169 |
+
// An empty cigar is a special case return "*" rather than ""
|
| 170 |
+
if (b->core.n_cigar == 0) {
|
| 171 |
+
return (kputc('*', str) == EOF) ? -1 : 0;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
const uint32_t *cigar = bam_get_cigar(b);
|
| 175 |
+
uint32_t i;
|
| 176 |
+
|
| 177 |
+
for (i = 0; i < b->core.n_cigar; ++i) {
|
| 178 |
+
if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1;
|
| 179 |
+
if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
return 0;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
// Returns 0 on success, -1 on failure.
|
| 186 |
+
static int sync_mq_mc(bam1_t* src, bam1_t* dest)
|
| 187 |
+
{
|
| 188 |
+
if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped
|
| 189 |
+
// Copy Mate Mapping Quality
|
| 190 |
+
uint32_t mq = src->core.qual;
|
| 191 |
+
uint8_t* data;
|
| 192 |
+
if ((data = bam_aux_get(dest,"MQ")) != NULL) {
|
| 193 |
+
bam_aux_del(dest, data);
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq);
|
| 197 |
+
}
|
| 198 |
+
// Copy mate cigar if either read is mapped
|
| 199 |
+
if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) {
|
| 200 |
+
uint8_t* data_mc;
|
| 201 |
+
if ((data_mc = bam_aux_get(dest,"MC")) != NULL) {
|
| 202 |
+
bam_aux_del(dest, data_mc);
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
// Convert cigar to string
|
| 206 |
+
kstring_t mc = { 0, 0, NULL };
|
| 207 |
+
if (bam_format_cigar(src, &mc) < 0) return -1;
|
| 208 |
+
|
| 209 |
+
bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc));
|
| 210 |
+
free(mc.s);
|
| 211 |
+
}
|
| 212 |
+
return 0;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
// Copy flags.
|
| 216 |
+
// Returns 0 on success, -1 on failure.
|
| 217 |
+
static int sync_mate(bam1_t* a, bam1_t* b)
|
| 218 |
+
{
|
| 219 |
+
sync_unmapped_pos_inner(a,b);
|
| 220 |
+
sync_unmapped_pos_inner(b,a);
|
| 221 |
+
sync_mate_inner(a,b);
|
| 222 |
+
sync_mate_inner(b,a);
|
| 223 |
+
if (sync_mq_mc(a,b) < 0) return -1;
|
| 224 |
+
if (sync_mq_mc(b,a) < 0) return -1;
|
| 225 |
+
return 0;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
static uint32_t calc_mate_score(bam1_t *b)
|
| 230 |
+
{
|
| 231 |
+
uint32_t score = 0;
|
| 232 |
+
uint8_t *qual = bam_get_qual(b);
|
| 233 |
+
int i;
|
| 234 |
+
|
| 235 |
+
for (i = 0; i < b->core.l_qseq; i++) {
|
| 236 |
+
if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
return score;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
static int add_mate_score(bam1_t *src, bam1_t *dest)
|
| 244 |
+
{
|
| 245 |
+
uint8_t *data_ms;
|
| 246 |
+
uint32_t mate_score = calc_mate_score(src);
|
| 247 |
+
|
| 248 |
+
if ((data_ms = bam_aux_get(dest, "ms")) != NULL) {
|
| 249 |
+
bam_aux_del(dest, data_ms);
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) {
|
| 253 |
+
return -1;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
return 0;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// Completely delete the CIGAR field
|
| 260 |
+
static void clear_cigar(bam1_t *b) {
|
| 261 |
+
memmove(bam_get_cigar(b), bam_get_seq(b),
|
| 262 |
+
b->data + b->l_data - bam_get_seq(b));
|
| 263 |
+
b->l_data -= 4*b->core.n_cigar;
|
| 264 |
+
b->core.n_cigar = 0;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
// Trim a CIGAR field to end on reference position "end". Remaining bases
|
| 268 |
+
// are turned to soft clips.
|
| 269 |
+
static int bam_trim(bam1_t *b, hts_pos_t end) {
|
| 270 |
+
hts_pos_t pos = b->core.pos;
|
| 271 |
+
int n_cigar = b->core.n_cigar, i;
|
| 272 |
+
uint32_t new_cigar_a[1024];
|
| 273 |
+
uint32_t *new_cigar = new_cigar_a;
|
| 274 |
+
uint32_t *cigar = bam_get_cigar(b);
|
| 275 |
+
|
| 276 |
+
// Find end of alignment or end of ref
|
| 277 |
+
int op = 0, oplen = 0;
|
| 278 |
+
for (i = 0; i < n_cigar; i++) {
|
| 279 |
+
op = bam_cigar_op(cigar[i]);
|
| 280 |
+
oplen = bam_cigar_oplen(cigar[i]);
|
| 281 |
+
if (!(bam_cigar_type(op) & 2))
|
| 282 |
+
continue;
|
| 283 |
+
pos += oplen;
|
| 284 |
+
if (pos > end)
|
| 285 |
+
break;
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
if (i == n_cigar)
|
| 289 |
+
// looks fine already
|
| 290 |
+
return 0;
|
| 291 |
+
|
| 292 |
+
int old_i = i, j = 0;
|
| 293 |
+
// At worst we grow by 1 element (eg 100M -> 70M30S)
|
| 294 |
+
if (n_cigar-i >= 1024-1) {
|
| 295 |
+
new_cigar = malloc(4*(n_cigar-i+1));
|
| 296 |
+
if (!new_cigar)
|
| 297 |
+
return -1;
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
// We fill out to new_cigar from here on.
|
| 301 |
+
if (pos-oplen < end) {
|
| 302 |
+
// Partial CIGAR op? Split existing tag.
|
| 303 |
+
cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op);
|
| 304 |
+
new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP);
|
| 305 |
+
} else if (pos > end) {
|
| 306 |
+
// entirely off the chromosome; this will trigger CIGAR *, MQUAL 0
|
| 307 |
+
b->core.flag |= BAM_FUNMAP;
|
| 308 |
+
b->core.flag &= ~BAM_FPROPER_PAIR;
|
| 309 |
+
} else {
|
| 310 |
+
// CIGAR op started on the trim junction
|
| 311 |
+
new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP);
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
// Replace trailing elements.
|
| 315 |
+
for (i++; i < n_cigar; i++) {
|
| 316 |
+
op = bam_cigar_op(cigar[i]);
|
| 317 |
+
oplen = bam_cigar_oplen(cigar[i]);
|
| 318 |
+
if (op == BAM_CHARD_CLIP) {
|
| 319 |
+
new_cigar[j++] = cigar[i];
|
| 320 |
+
} else {
|
| 321 |
+
new_cigar[j-1] =
|
| 322 |
+
bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen,
|
| 323 |
+
BAM_CSOFT_CLIP);
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
// We now have cigar[0..old_i-1] for existing CIGAR
|
| 328 |
+
// and new_cigar[0..j-1] for new CIGAR trailing component.
|
| 329 |
+
|
| 330 |
+
if (old_i+j == n_cigar) {
|
| 331 |
+
// Fits and no data move needed
|
| 332 |
+
memcpy(&cigar[old_i], new_cigar, j*4);
|
| 333 |
+
} else {
|
| 334 |
+
uint8_t *seq_old = bam_get_seq(b);
|
| 335 |
+
uint8_t *aux_end = b->data + b->l_data;
|
| 336 |
+
int nshift;
|
| 337 |
+
if (old_i+j < n_cigar) {
|
| 338 |
+
// Smaller, and can move data down
|
| 339 |
+
nshift = -4*(n_cigar - (old_i+j));
|
| 340 |
+
} else {
|
| 341 |
+
// Bigger, so grow BAM and move data up
|
| 342 |
+
nshift = 4*(old_i+j - n_cigar);
|
| 343 |
+
// FIXME: make htslib's sam_realloc_bam_data public
|
| 344 |
+
if (b->l_data + nshift > b->m_data) {
|
| 345 |
+
uint8_t *new_data = realloc(b->data, b->l_data + nshift);
|
| 346 |
+
if (!new_data) {
|
| 347 |
+
if (new_cigar != new_cigar_a)
|
| 348 |
+
free(new_cigar);
|
| 349 |
+
return -1;
|
| 350 |
+
}
|
| 351 |
+
b->m_data = b->l_data + nshift;
|
| 352 |
+
if (b->data != new_data) {
|
| 353 |
+
b->data = new_data;
|
| 354 |
+
seq_old = bam_get_seq(b);
|
| 355 |
+
aux_end = b->data + b->l_data;
|
| 356 |
+
cigar = bam_get_cigar(b);
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
memmove(seq_old+nshift, seq_old, aux_end - seq_old);
|
| 361 |
+
b->l_data += nshift;
|
| 362 |
+
memcpy(&cigar[old_i], new_cigar, j*4);
|
| 363 |
+
b->core.n_cigar = old_i+j;
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
if (new_cigar != new_cigar_a)
|
| 367 |
+
free(new_cigar);
|
| 368 |
+
|
| 369 |
+
return 0;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
// Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux"
|
| 373 |
+
// keywords for the bam sanitizer.
|
| 374 |
+
int bam_sanitize_options(const char *str) {
|
| 375 |
+
int opt = 0;
|
| 376 |
+
|
| 377 |
+
while (str && *str) {
|
| 378 |
+
const char *str_start;
|
| 379 |
+
while(*str && *str == ',')
|
| 380 |
+
str++;
|
| 381 |
+
|
| 382 |
+
for (str_start = str; *str && *str != ','; str++);
|
| 383 |
+
int len = str - str_start;
|
| 384 |
+
if (strncmp(str_start, "all", 3) == 0 || *str_start == '*')
|
| 385 |
+
opt = FIX_ALL;
|
| 386 |
+
else if (strncmp(str_start, "none", 4) == 0 ||
|
| 387 |
+
strncmp(str_start, "off", 3) == 0)
|
| 388 |
+
opt = 0;
|
| 389 |
+
else if (strncmp(str_start, "on", 2) == 0)
|
| 390 |
+
// default for position sorted data
|
| 391 |
+
opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX;
|
| 392 |
+
else if (strncmp(str_start, "pos", 3) == 0)
|
| 393 |
+
opt |= FIX_POS;
|
| 394 |
+
else if (strncmp(str_start, "mqual", 5) == 0)
|
| 395 |
+
opt |= FIX_MQUAL;
|
| 396 |
+
else if (strncmp(str_start, "unmap", 5) == 0)
|
| 397 |
+
opt |= FIX_UNMAP;
|
| 398 |
+
else if (strncmp(str_start, "cigar", 5) == 0)
|
| 399 |
+
opt |= FIX_CIGAR;
|
| 400 |
+
else if (strncmp(str_start, "aux", 3) == 0)
|
| 401 |
+
opt |= FIX_AUX;
|
| 402 |
+
else {
|
| 403 |
+
print_error("sanitize", "Unrecognised keyword %.*s\n",
|
| 404 |
+
len, str_start);
|
| 405 |
+
return -1;
|
| 406 |
+
}
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
return opt;
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) {
|
| 413 |
+
if ((flags & FIX_POS) && b->core.tid < 0) {
|
| 414 |
+
// RNAME * => pos 0. NB can break alignment chr/pos sort order
|
| 415 |
+
b->core.pos = -1;
|
| 416 |
+
if (flags & FIX_UNMAP)
|
| 417 |
+
b->core.flag |= BAM_FUNMAP;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) {
|
| 421 |
+
// Mapped => unmapped correction
|
| 422 |
+
if (b->core.pos < 0 && (flags & FIX_UNMAP)) {
|
| 423 |
+
b->core.flag |= BAM_FUNMAP;
|
| 424 |
+
} else {
|
| 425 |
+
hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid);
|
| 426 |
+
if (b->core.pos >= rlen && (flags & FIX_UNMAP)) {
|
| 427 |
+
b->core.flag |= BAM_FUNMAP;
|
| 428 |
+
if (flags & FIX_POS)
|
| 429 |
+
b->core.tid = b->core.pos = -1;
|
| 430 |
+
} else if ((cur_end = bam_endpos(b)) > rlen) {
|
| 431 |
+
if (bam_trim(b, rlen) < 0)
|
| 432 |
+
return -1;
|
| 433 |
+
}
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
if (b->core.flag & BAM_FUNMAP) {
|
| 438 |
+
// Unmapped -> cigar/qual correctoins
|
| 439 |
+
if ((flags & FIX_CIGAR) && b->core.n_cigar > 0)
|
| 440 |
+
clear_cigar(b);
|
| 441 |
+
|
| 442 |
+
if (flags & FIX_MQUAL)
|
| 443 |
+
b->core.qual = 0;
|
| 444 |
+
|
| 445 |
+
// Remove NM, MD, CG, SM tags.
|
| 446 |
+
if (flags & FIX_AUX) {
|
| 447 |
+
uint8_t *from = bam_aux_first(b);
|
| 448 |
+
uint8_t *end = b->data + b->l_data;
|
| 449 |
+
uint8_t *to = from ? from-2 : end;
|
| 450 |
+
|
| 451 |
+
#define XTAG(a) (((a)[0]<<8) + (a)[1])
|
| 452 |
+
while (from) {
|
| 453 |
+
uint8_t *next = bam_aux_next(b, from);
|
| 454 |
+
if (!next && errno != ENOENT)
|
| 455 |
+
return -1;
|
| 456 |
+
|
| 457 |
+
// Keep tag unless one of a specific set.
|
| 458 |
+
// NB "to" always points to an aux tag start, while
|
| 459 |
+
// "from" is after key.
|
| 460 |
+
from -= 2;
|
| 461 |
+
int key = (int)from[0]<<8 | from[1];
|
| 462 |
+
if (key != XTAG("NM") && key != XTAG("MD") &&
|
| 463 |
+
key != XTAG("CG") && key != XTAG("SM")) {
|
| 464 |
+
ptrdiff_t len = (next ? next-2 : end) - from;
|
| 465 |
+
if (from != to)
|
| 466 |
+
memmove(to, from, len);
|
| 467 |
+
to += len;
|
| 468 |
+
}
|
| 469 |
+
from = next;
|
| 470 |
+
}
|
| 471 |
+
b->l_data = to - b->data;
|
| 472 |
+
}
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
return 0;
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
// Look for 3 tags in one pass, for efficiencies sake.
|
| 479 |
+
// We also convert the draft tags Mm and Ml to MM and ML here.
|
| 480 |
+
static inline void find_tags(bam1_t *b,
|
| 481 |
+
char *t1, uint8_t **t1p,
|
| 482 |
+
char *t2, uint8_t **t2p,
|
| 483 |
+
char *t3, uint8_t **t3p) {
|
| 484 |
+
*t1p = *t2p = *t3p = NULL;
|
| 485 |
+
uint8_t *aux = bam_aux_first(b);
|
| 486 |
+
|
| 487 |
+
while (aux) {
|
| 488 |
+
if (aux[-2] == t1[0] && toupper(aux[-1]) == t1[1]) {
|
| 489 |
+
*t1p = aux;
|
| 490 |
+
if (islower(aux[-1]))
|
| 491 |
+
aux[-1] = t1[1];
|
| 492 |
+
} else if (aux[-2] == t2[0] && toupper(aux[-1]) == t2[1]) {
|
| 493 |
+
*t2p = aux;
|
| 494 |
+
if (islower(aux[-1]))
|
| 495 |
+
aux[-1] = t2[1];
|
| 496 |
+
} else if (aux[-2] == t3[0] && toupper(aux[-1]) == t3[1]) {
|
| 497 |
+
*t3p = aux;
|
| 498 |
+
if (islower(aux[-1]))
|
| 499 |
+
aux[-1] = t3[1];
|
| 500 |
+
}
|
| 501 |
+
aux = bam_aux_next(b, aux);
|
| 502 |
+
}
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
// Return 5' and 3' CIGAR hard-clip counts
|
| 506 |
+
static inline void hard_clips(bam1_t *b, int *end5, int *end3) {
|
| 507 |
+
uint32_t *cigar = bam_get_cigar(b);
|
| 508 |
+
int ncigar = b->core.n_cigar;
|
| 509 |
+
int endL = 0, endR = 0, nh = 0;
|
| 510 |
+
|
| 511 |
+
if (ncigar && bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP)
|
| 512 |
+
endL = bam_cigar_oplen(cigar[0]), nh=1;
|
| 513 |
+
if (ncigar > nh && bam_cigar_op(cigar[ncigar-1]) == BAM_CHARD_CLIP)
|
| 514 |
+
endR = bam_cigar_oplen(cigar[ncigar-1]);
|
| 515 |
+
|
| 516 |
+
if (b->core.flag & BAM_FREVERSE) {
|
| 517 |
+
*end5 = endR;
|
| 518 |
+
*end3 = endL;
|
| 519 |
+
} else {
|
| 520 |
+
*end5 = endL;
|
| 521 |
+
*end3 = endR;
|
| 522 |
+
}
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
// Get MM, ML and MN tags, and 5' and 3' hard-clip lengths.
|
| 526 |
+
// MNi is integer copy of MN, or -1 if absent/invalid
|
| 527 |
+
void get_mod_info(bam1_t *b, uint8_t **MM, uint8_t **ML, uint8_t **MN,
|
| 528 |
+
int *MNi, int *end5, int *end3) {
|
| 529 |
+
find_tags(b, "MM", MM, "ML", ML, "MN", MN);
|
| 530 |
+
if (*MN) {
|
| 531 |
+
int save_errno = errno;
|
| 532 |
+
errno = 0;
|
| 533 |
+
*MNi = bam_aux2i(*MN);
|
| 534 |
+
if (errno == EINVAL)
|
| 535 |
+
*MNi = -1;
|
| 536 |
+
errno = save_errno;
|
| 537 |
+
} else {
|
| 538 |
+
*MNi = -1;
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
if (*MM)
|
| 542 |
+
hard_clips(b, end5, end3);
|
| 543 |
+
else
|
| 544 |
+
*end5 = *end3 = 0; // don't need if MM not found
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
typedef struct MM_state {
|
| 548 |
+
// tags found on "pre" BAM
|
| 549 |
+
uint8_t *MM, *ML, *MN;
|
| 550 |
+
} MM_state;
|
| 551 |
+
|
| 552 |
+
uint8_t *MN_enc(uint8_t *tag, uint32_t n) {
|
| 553 |
+
if (n > UINT16_MAX) {
|
| 554 |
+
tag[0] = 'I';
|
| 555 |
+
i32_to_le(n, tag+1);
|
| 556 |
+
tag += 5;
|
| 557 |
+
} else if (n > UINT8_MAX) {
|
| 558 |
+
tag[0] = 'S';
|
| 559 |
+
i16_to_le(n, tag+1);
|
| 560 |
+
tag += 3;
|
| 561 |
+
} else {
|
| 562 |
+
*tag++ = 'C';
|
| 563 |
+
*tag++ = n;
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
return tag;
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
// Trim 5'/3' bases off MM and ML tags, using a previous sequence as a guide.
|
| 570 |
+
int trim_MM(bam1_t *pre, bam1_t *cur, int end5, int end3,
|
| 571 |
+
uint8_t *MM, uint8_t *ML, uint8_t *MN) {
|
| 572 |
+
// Count number of bases
|
| 573 |
+
int counts5[16] = {0}, counts3[16] = {0};
|
| 574 |
+
|
| 575 |
+
uint8_t *seq = bam_get_seq(pre);
|
| 576 |
+
int i;
|
| 577 |
+
for (i = 0; i < end5; i++)
|
| 578 |
+
counts5[bam_seqi(seq, i)]++;
|
| 579 |
+
memcpy(counts3, counts5, 16 * sizeof(*counts3));
|
| 580 |
+
for (; i < pre->core.l_qseq - end3; i++)
|
| 581 |
+
counts3[bam_seqi(seq, i)]++;
|
| 582 |
+
|
| 583 |
+
// "p" is position in pre.
|
| 584 |
+
// "q" is position in cur.
|
| 585 |
+
// Hence move up "p" to start and copy from there to "q".
|
| 586 |
+
uint8_t *MMp, *MLp, *MMq = NULL, *MLq = NULL;
|
| 587 |
+
if (ML && ML[0] == 'B' && ML[1] == 'C') {
|
| 588 |
+
MLp = ML+6;
|
| 589 |
+
} else {
|
| 590 |
+
ML = MLp = NULL;
|
| 591 |
+
}
|
| 592 |
+
MMq = MM+1;
|
| 593 |
+
MLq = MLp;
|
| 594 |
+
for (MMp = MM+1; *MMp; ) {
|
| 595 |
+
int fundamental = seq_nt16_table[*MMp];
|
| 596 |
+
while (*MMp && *MMp != ',')
|
| 597 |
+
*MMq++ = *MMp++;
|
| 598 |
+
if (*MMp)
|
| 599 |
+
*MMq++ = *MMp++;
|
| 600 |
+
|
| 601 |
+
// Now on comma separated list for MM and BC array for ML. Skip
|
| 602 |
+
int n = 0;
|
| 603 |
+
while (*MMp != ';' && n < counts5[fundamental]) {
|
| 604 |
+
char *endptr;
|
| 605 |
+
long delta = strtol((char *)MMp, &endptr, 10);
|
| 606 |
+
if (counts5[fundamental] - n > delta) {
|
| 607 |
+
// Skip entire delta in MM and ML.
|
| 608 |
+
// Eg counts[]=10, MM=3,10 ML=<10><20> => MM=10 ML=<20>
|
| 609 |
+
n += delta+1;
|
| 610 |
+
if(ML) MLp++;
|
| 611 |
+
} else if (counts3[fundamental] > counts5[fundamental]) {
|
| 612 |
+
// Shrink delta, writing MM and ML is unchanged.
|
| 613 |
+
// Eg counts[]=3, MM=10,4 ML=<10><20> => MM=7,4 ML=<10><20>
|
| 614 |
+
char num[50];
|
| 615 |
+
int l = sprintf(num, "%ld",
|
| 616 |
+
delta - (counts5[fundamental]-n));
|
| 617 |
+
memcpy((char *)MMq, num, l);
|
| 618 |
+
MMq += l;
|
| 619 |
+
*MMq++ = *endptr;
|
| 620 |
+
n += delta+1;
|
| 621 |
+
if (ML)
|
| 622 |
+
*MLq++ = *MLp++;
|
| 623 |
+
} else {
|
| 624 |
+
// next base mod is on boundary of 3' clip point
|
| 625 |
+
break;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
MMp = (uint8_t *)endptr;
|
| 629 |
+
if (*MMp != ',')
|
| 630 |
+
// error? if not ; also?
|
| 631 |
+
break;
|
| 632 |
+
MMp++;
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
// Copy
|
| 636 |
+
while (*MMp != ';' && n < counts3[fundamental]) {
|
| 637 |
+
char *endptr;
|
| 638 |
+
long delta = strtol((char *)MMp, &endptr, 10);
|
| 639 |
+
if (counts3[fundamental] - n > delta) {
|
| 640 |
+
// Copy entire delta in MM and ML including [,;]
|
| 641 |
+
memmove(MMq, MMp, (uint8_t *)endptr - MMp + 1);
|
| 642 |
+
MMq += (uint8_t *)endptr - MMp + 1;
|
| 643 |
+
n += delta+1;
|
| 644 |
+
if (ML)
|
| 645 |
+
*MLq++ = *MLp++;
|
| 646 |
+
} else {
|
| 647 |
+
// Next mod is into 3' cutoff, so can terminate MM/ML now
|
| 648 |
+
n = counts3[fundamental];
|
| 649 |
+
if (ML)
|
| 650 |
+
MLp++;
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
MMp = (uint8_t *)endptr;
|
| 654 |
+
if (*MMp != ',')
|
| 655 |
+
break;
|
| 656 |
+
MMp++;
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
// Skip
|
| 660 |
+
while (*MMp && *MMp != ';') {
|
| 661 |
+
while (*MMp && *MMp != ',' && *MMp != ';')
|
| 662 |
+
MMp++;
|
| 663 |
+
if (*MMp == ',')
|
| 664 |
+
MMp++;
|
| 665 |
+
|
| 666 |
+
if (ML)
|
| 667 |
+
MLp++;
|
| 668 |
+
}
|
| 669 |
+
MMq[-1] = ';'; // replaces , with ; if clipping right
|
| 670 |
+
if (*MMp)
|
| 671 |
+
MMp++;
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
MMp++; // skip nul
|
| 675 |
+
*MMq++ = 0;
|
| 676 |
+
|
| 677 |
+
// Adjust ML B array length
|
| 678 |
+
if (ML)
|
| 679 |
+
u32_to_le(MLq-(ML+6), ML+2);
|
| 680 |
+
|
| 681 |
+
// Move MM and ML down to include their MM:Z and ML:B bits
|
| 682 |
+
if (MM) MM-=2;
|
| 683 |
+
if (ML) ML-=2;
|
| 684 |
+
|
| 685 |
+
// Now MM/ML are start of tags, MMq/MLq are ends of edited tags,
|
| 686 |
+
// and MMp/MLp are ends of original tags. Walk through tags taking up
|
| 687 |
+
// any gaps
|
| 688 |
+
//
|
| 689 |
+
// Eg XXXXXXmmmmm--YYYlllll-ZZ (m and l are edited MM and ML tags)
|
| 690 |
+
// => XXXXXXmmmmmYYYlllllZZ
|
| 691 |
+
|
| 692 |
+
uint8_t *tag = bam_get_aux(cur), *tag_end = cur->data + cur->l_data;
|
| 693 |
+
uint8_t *to = tag;
|
| 694 |
+
while (tag && tag < tag_end) {
|
| 695 |
+
if (tag[0] == 'M' && (tag[1] == 'M' || tag[1] == 'm')) {
|
| 696 |
+
// Slow but easy
|
| 697 |
+
memmove(to, MM, MMq-MM); // length of new tag
|
| 698 |
+
to += MMq-MM;
|
| 699 |
+
tag = MMp; // size of old tag
|
| 700 |
+
} else if (tag[0] == 'M' && (tag[1] == 'L' || tag[1] == 'l')) {
|
| 701 |
+
memmove(to, ML, MLq-ML);
|
| 702 |
+
to += MLq-ML;
|
| 703 |
+
tag = MLp;
|
| 704 |
+
} else if (tag[0] == 'M' && tag[1] == 'N') {
|
| 705 |
+
tag = bam_aux_next(cur, tag+2);
|
| 706 |
+
// Skip it as we'll overwrite this later, although this
|
| 707 |
+
// does change the tag order. Instead we could do:
|
| 708 |
+
//
|
| 709 |
+
// *to++ = 'M';
|
| 710 |
+
// *to++ = 'N';
|
| 711 |
+
// to = MN_enc(to, cur->core.l_qseq);
|
| 712 |
+
} else {
|
| 713 |
+
// Want aux_skip, but it's private.
|
| 714 |
+
// So we use bam_aux_next with work-arounds. :(
|
| 715 |
+
uint8_t *from = tag;
|
| 716 |
+
tag = bam_aux_next(cur, tag+2);
|
| 717 |
+
tag = tag ? tag-2 : tag_end;
|
| 718 |
+
memmove(to, from, tag-from);
|
| 719 |
+
to += tag-from;
|
| 720 |
+
}
|
| 721 |
+
}
|
| 722 |
+
cur->l_data = to - cur->data;
|
| 723 |
+
|
| 724 |
+
return 0;
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
// Removes base modification tags: MM, ML and MN.
|
| 728 |
+
// This is more efficient than a series of bam_aux_remove and
|
| 729 |
+
// bam_aux_find calls, as the previous removes shuffle the tags we've
|
| 730 |
+
// previously found. However it's still not optimal.
|
| 731 |
+
void delete_mod_tags(bam1_t *b) {
|
| 732 |
+
uint8_t *tag = bam_aux_first(b), *next;
|
| 733 |
+
uint8_t *to = tag;
|
| 734 |
+
while (tag) {
|
| 735 |
+
next = bam_aux_next(b, tag);
|
| 736 |
+
if (tag[-2] == 'M' &&
|
| 737 |
+
(tag[-1] == 'M' || tag[-1] == 'm' ||
|
| 738 |
+
tag[-1] == 'L' || tag[-1] == 'l' ||
|
| 739 |
+
tag[-1] == 'N')) {
|
| 740 |
+
// Skip. Equivalent to bam_aux_remove without multiple passes
|
| 741 |
+
} else {
|
| 742 |
+
// Copy. All these +/-2s are an annoyance caused by the
|
| 743 |
+
// tag iterator pointing to the byte after the 2-letter code
|
| 744 |
+
uint8_t *end = next ? next : b->data + b->l_data + 2;
|
| 745 |
+
if (tag != to)
|
| 746 |
+
memmove(to-2, tag-2, end-tag);
|
| 747 |
+
to += end-tag;
|
| 748 |
+
}
|
| 749 |
+
tag = next;
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
b->l_data = (to-2) - b->data;
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
int validate_MM(bam1_t *b, hts_base_mod_state *state) {
|
| 756 |
+
hts_base_mod mods[10];
|
| 757 |
+
int n, pos;
|
| 758 |
+
while ((n = bam_next_basemod(b, state, mods, 10, &pos)) > 0) {
|
| 759 |
+
// bam_next_basemod will trigger MM out-of-bound checks
|
| 760 |
+
}
|
| 761 |
+
return n;
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
// Fix base modification tags MM, ML and MN.
|
| 765 |
+
// For supplementary-style alignments we may have hard-clipped the sequence
|
| 766 |
+
// and just duplicated the MM/ML tags. Use the primary alignment to get the
|
| 767 |
+
// clipped sequence so we can trim MM/ML accordingly.
|
| 768 |
+
//
|
| 769 |
+
// We call this first on primary reads with pre == NULL. This caches
|
| 770 |
+
// MM and ML data into MM_state.
|
| 771 |
+
//
|
| 772 |
+
// We then call it again on secondary and/or supplementary data with
|
| 773 |
+
// pre == the primary record and pass in the associated state. This then
|
| 774 |
+
// validates MM/ML/MN match, and if not adjusts them if they have hard-clips
|
| 775 |
+
// which yields consistent data.
|
| 776 |
+
//
|
| 777 |
+
// TODO: add sanity check on counts of base types and MM tag to ensure it's
|
| 778 |
+
// possible. We can do this post-trimming, so we sanitize everything.
|
| 779 |
+
//
|
| 780 |
+
// Returns 0 on success,
|
| 781 |
+
// -1 on failure
|
| 782 |
+
int fix_MM(bam1_t *pre, bam1_t *cur, MM_state *state) {
|
| 783 |
+
int end5, end3;
|
| 784 |
+
int MNi = 0; // MN of -1 is used as indicator for no valid mods
|
| 785 |
+
|
| 786 |
+
if (!pre && state) {
|
| 787 |
+
// First time we've see this name.
|
| 788 |
+
// Look for base modification tags and sanity check.
|
| 789 |
+
get_mod_info(cur, &state->MM, &state->ML, &state->MN, &MNi,
|
| 790 |
+
&end5, &end3);
|
| 791 |
+
if (!state->MM) {
|
| 792 |
+
delete_mod_tags(cur);
|
| 793 |
+
return 0;
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
if (!end5 && !end3 && MNi <= 0) {
|
| 797 |
+
// No MN tag, but also no clipping. Assume MM is valid
|
| 798 |
+
if (cur->core.l_qseq)
|
| 799 |
+
if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0)
|
| 800 |
+
return -1;
|
| 801 |
+
} else if ((end3 || end5) && cur->core.l_qseq != MNi) {
|
| 802 |
+
// We have hard clips and MN tag, but the MN tag doesn't match
|
| 803 |
+
// observed sequence length so it appears the hard-clipping
|
| 804 |
+
// happened after base-mods called without updating.
|
| 805 |
+
// Fail as this is a primary read.
|
| 806 |
+
delete_mod_tags(cur);
|
| 807 |
+
}
|
| 808 |
+
// Otherwise we assume the base modifications are correct
|
| 809 |
+
|
| 810 |
+
} else if (state) {
|
| 811 |
+
// A supplementary or secondary alignment with known primary
|
| 812 |
+
uint8_t *cur_MM = NULL, *cur_ML = NULL, *cur_MN = NULL;
|
| 813 |
+
MNi = -1;
|
| 814 |
+
get_mod_info(cur, &cur_MM, &cur_ML, &cur_MN, &MNi, &end5, &end3);
|
| 815 |
+
|
| 816 |
+
if (!cur_MM) {
|
| 817 |
+
delete_mod_tags(cur);
|
| 818 |
+
return 0;
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
// Does MN match seq length? If so, we believe it's already valid
|
| 822 |
+
if (MNi == cur->core.l_qseq)
|
| 823 |
+
goto validate;
|
| 824 |
+
|
| 825 |
+
// Length mismatch and/or no known length, so check vs full seq.
|
| 826 |
+
if (pre->core.l_qseq != cur->core.l_qseq + end3 + end5) {
|
| 827 |
+
delete_mod_tags(cur);
|
| 828 |
+
return 0;
|
| 829 |
+
} else if (end5 || end3) {
|
| 830 |
+
if (MNi < 0 || MNi == pre->core.l_qseq)
|
| 831 |
+
trim_MM(pre, cur, end5, end3, cur_MM, cur_ML, cur_MN);
|
| 832 |
+
} // else no hard clips so MM is already valid
|
| 833 |
+
|
| 834 |
+
// Set MN so we've validated it, provided seq isn't "*".
|
| 835 |
+
// inefficient, but minimal compared to everything else
|
| 836 |
+
if (cur->core.l_qseq)
|
| 837 |
+
if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0)
|
| 838 |
+
return -1;
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
validate:
|
| 842 |
+
;
|
| 843 |
+
|
| 844 |
+
// Also validate MM length matches sequence length. This mirrors the
|
| 845 |
+
// logic in htslib/sam_mods.c.
|
| 846 |
+
// For now we take the inefficient approach of using bam_parse_basemod2.
|
| 847 |
+
// Inefficient, but robust.
|
| 848 |
+
hts_base_mod_state *mst = hts_base_mod_state_alloc();
|
| 849 |
+
if (!mst)
|
| 850 |
+
return -1;
|
| 851 |
+
|
| 852 |
+
enum htsLogLevel lvl = hts_get_log_level();
|
| 853 |
+
hts_set_log_level(HTS_LOG_OFF);
|
| 854 |
+
if (bam_parse_basemod(cur, mst) < 0)
|
| 855 |
+
// Maybe we want hts_log_warning still though?
|
| 856 |
+
delete_mod_tags(cur);
|
| 857 |
+
if (validate_MM(cur, mst) < 0)
|
| 858 |
+
delete_mod_tags(cur);
|
| 859 |
+
hts_set_log_level(lvl);
|
| 860 |
+
hts_base_mod_state_free(mst);
|
| 861 |
+
|
| 862 |
+
return 0;
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
// Ensure the b[] array is at least n.
|
| 866 |
+
// Returns 0 on success,
|
| 867 |
+
// -1 on failure
|
| 868 |
+
static int grow_b_array(bam1_t **b, int *ba, int n) {
|
| 869 |
+
if (n < *ba)
|
| 870 |
+
return 0;
|
| 871 |
+
|
| 872 |
+
bam1_t *bnew = realloc(*b, (n+=10) * sizeof(**b));
|
| 873 |
+
if (!bnew)
|
| 874 |
+
return -1;
|
| 875 |
+
*b = bnew;
|
| 876 |
+
|
| 877 |
+
// bam_init1 equivalent
|
| 878 |
+
int i;
|
| 879 |
+
for (i = *ba; i < n; i++)
|
| 880 |
+
memset(&(*b)[i], 0, sizeof(bam1_t));
|
| 881 |
+
|
| 882 |
+
*b = bnew;
|
| 883 |
+
*ba = n;
|
| 884 |
+
|
| 885 |
+
return 0;
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
// We have b[0]..b[bn-1] entries all from the same template (qname)
|
| 889 |
+
typedef struct {
|
| 890 |
+
bam1_t *b;
|
| 891 |
+
int n, ba; // number used and number allocated
|
| 892 |
+
int b_next; // b[b_next] for start of next set, -1 if unset
|
| 893 |
+
int eof; // marker for having seen eof
|
| 894 |
+
} bam_set;
|
| 895 |
+
|
| 896 |
+
// Fetches a new batch of BAM records all containing the same name.
|
| 897 |
+
// NB: we cache the last (non-matching) name in b[n], so we can use it to
|
| 898 |
+
// start the next batch.
|
| 899 |
+
// Returns the number of records on success,
|
| 900 |
+
// <0 on failure or EOF (sam_read1 return vals)
|
| 901 |
+
static int next_template(samFile *in, sam_hdr_t *header, bam_set *bs,
|
| 902 |
+
int sanitize_flags) {
|
| 903 |
+
int result;
|
| 904 |
+
|
| 905 |
+
if (bs->eof)
|
| 906 |
+
return -1;
|
| 907 |
+
|
| 908 |
+
// First time through, prime the template name
|
| 909 |
+
if (bs->b_next < 0) {
|
| 910 |
+
if (grow_b_array(&bs->b, &bs->ba, 1) < 0)
|
| 911 |
+
return -2;
|
| 912 |
+
result = sam_read1(in, header, &bs->b[0]);
|
| 913 |
+
if (result < 0)
|
| 914 |
+
return result;
|
| 915 |
+
if (bam_sanitize(header, &bs->b[0], sanitize_flags) < 0)
|
| 916 |
+
return -2;
|
| 917 |
+
} else {
|
| 918 |
+
// Otherwise use the previous template name read
|
| 919 |
+
bam1_t btmp = bs->b[0];
|
| 920 |
+
bs->b[0] = bs->b[bs->b_next];
|
| 921 |
+
bs->b[bs->b_next] = btmp; // For ->{,l_,m_}data
|
| 922 |
+
}
|
| 923 |
+
bs->n = 1;
|
| 924 |
+
|
| 925 |
+
// Now keep reading until we find a read that mismatches or we hit eof.
|
| 926 |
+
char *name = bam_get_qname(&bs->b[0]);
|
| 927 |
+
for (;;) {
|
| 928 |
+
if (grow_b_array(&bs->b, &bs->ba, bs->n+1) < 0)
|
| 929 |
+
return -2;
|
| 930 |
+
|
| 931 |
+
result = sam_read1(in, header, &bs->b[bs->n]);
|
| 932 |
+
if (result < -1)
|
| 933 |
+
return result;
|
| 934 |
+
|
| 935 |
+
if (result < 0) {
|
| 936 |
+
bs->eof = 1;
|
| 937 |
+
bs->b_next = -1;
|
| 938 |
+
break;
|
| 939 |
+
} else {
|
| 940 |
+
if (bam_sanitize(header, &bs->b[bs->n], sanitize_flags) < 0)
|
| 941 |
+
return -2;
|
| 942 |
+
|
| 943 |
+
bs->b_next = bs->n;
|
| 944 |
+
if (strcmp(name, bam_get_qname(&bs->b[bs->n])) != 0)
|
| 945 |
+
break;
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
bs->n++;
|
| 949 |
+
}
|
| 950 |
+
|
| 951 |
+
return bs->n;
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
// currently, this function ONLY works if each read has one hit
|
| 955 |
+
//
|
| 956 |
+
// Returns 0 on success,
|
| 957 |
+
// >0 on failure
|
| 958 |
+
static int bam_mating_core(samFile *in, samFile *out, int remove_reads,
|
| 959 |
+
int proper_pair_check, int add_ct,
|
| 960 |
+
int do_mate_scoring, char *arg_list, int no_pg,
|
| 961 |
+
int sanitize_flags, int base_mods)
|
| 962 |
+
{
|
| 963 |
+
sam_hdr_t *header;
|
| 964 |
+
int result, n;
|
| 965 |
+
kstring_t str = KS_INITIALIZE;
|
| 966 |
+
bam_set bs = {NULL, 0, 0, -1, 0};
|
| 967 |
+
|
| 968 |
+
header = sam_hdr_read(in);
|
| 969 |
+
if (header == NULL) {
|
| 970 |
+
fprintf(samtools_stderr, "[bam_mating_core] ERROR: Couldn't read header\n");
|
| 971 |
+
return 1;
|
| 972 |
+
}
|
| 973 |
+
|
| 974 |
+
// Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted.
|
| 975 |
+
if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) {
|
| 976 |
+
fprintf(samtools_stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n");
|
| 977 |
+
goto fail;
|
| 978 |
+
}
|
| 979 |
+
ks_free(&str);
|
| 980 |
+
|
| 981 |
+
if (!no_pg && sam_hdr_add_pg(header, "samtools",
|
| 982 |
+
"VN", samtools_version(),
|
| 983 |
+
arg_list ? "CL": NULL,
|
| 984 |
+
arg_list ? arg_list : NULL,
|
| 985 |
+
NULL))
|
| 986 |
+
goto fail;
|
| 987 |
+
|
| 988 |
+
if (sam_hdr_write(out, header) < 0) goto write_fail;
|
| 989 |
+
|
| 990 |
+
// Iterate template by template fetching bs->n records at a time
|
| 991 |
+
while ((result = next_template(in, header, &bs, sanitize_flags)) >= 0) {
|
| 992 |
+
bam1_t *cur = NULL, *pre = NULL, *rnum[2] = {NULL, NULL};
|
| 993 |
+
int prev = -1, curr = -1;
|
| 994 |
+
hts_pos_t pre_end = 0, cur_end = 0;
|
| 995 |
+
|
| 996 |
+
// Find and fix up primary alignments
|
| 997 |
+
MM_state state[2];
|
| 998 |
+
for (n = 0; n < bs.n; n++) {
|
| 999 |
+
int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0;
|
| 1000 |
+
if (bs.b[n].core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY))
|
| 1001 |
+
continue;
|
| 1002 |
+
|
| 1003 |
+
if (base_mods)
|
| 1004 |
+
if (fix_MM(NULL, &bs.b[n], &state[is_r2]) < 0)
|
| 1005 |
+
goto fail;
|
| 1006 |
+
|
| 1007 |
+
if (!pre) {
|
| 1008 |
+
pre = &bs.b[prev = n];
|
| 1009 |
+
rnum[(pre->core.flag & BAM_FREAD2) != 0] = pre;
|
| 1010 |
+
|
| 1011 |
+
pre_end = (pre->core.flag & BAM_FUNMAP) == 0
|
| 1012 |
+
? bam_endpos(pre) : 0;
|
| 1013 |
+
continue;
|
| 1014 |
+
}
|
| 1015 |
+
|
| 1016 |
+
// Note, more than 2 primary alignments will use 'curr' as last
|
| 1017 |
+
cur = &bs.b[curr = n];
|
| 1018 |
+
rnum[(cur->core.flag & BAM_FREAD2) != 0] = cur;
|
| 1019 |
+
cur_end = (cur->core.flag & BAM_FUNMAP) == 0
|
| 1020 |
+
? bam_endpos(cur) : 0;
|
| 1021 |
+
|
| 1022 |
+
pre->core.flag |= BAM_FPAIRED;
|
| 1023 |
+
cur->core.flag |= BAM_FPAIRED;
|
| 1024 |
+
if (sync_mate(pre, cur))
|
| 1025 |
+
goto fail;
|
| 1026 |
+
|
| 1027 |
+
// If safe set TLEN/ISIZE
|
| 1028 |
+
if (pre->core.tid == cur->core.tid
|
| 1029 |
+
&& !(cur->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))
|
| 1030 |
+
&& !(pre->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))) {
|
| 1031 |
+
hts_pos_t cur5, pre5;
|
| 1032 |
+
cur5 = (cur->core.flag & BAM_FREVERSE)
|
| 1033 |
+
? cur_end
|
| 1034 |
+
: cur->core.pos;
|
| 1035 |
+
pre5 = (pre->core.flag & BAM_FREVERSE)
|
| 1036 |
+
? pre_end
|
| 1037 |
+
: pre->core.pos;
|
| 1038 |
+
cur->core.isize = pre5 - cur5;
|
| 1039 |
+
pre->core.isize = cur5 - pre5;
|
| 1040 |
+
} else {
|
| 1041 |
+
cur->core.isize = pre->core.isize = 0;
|
| 1042 |
+
}
|
| 1043 |
+
|
| 1044 |
+
if (add_ct)
|
| 1045 |
+
bam_template_cigar(pre, cur, &str);
|
| 1046 |
+
|
| 1047 |
+
// TODO: Add code to properly check if read is in a proper
|
| 1048 |
+
// pair based on ISIZE distribution
|
| 1049 |
+
if (proper_pair_check && !plausibly_properly_paired(pre,cur)) {
|
| 1050 |
+
pre->core.flag &= ~BAM_FPROPER_PAIR;
|
| 1051 |
+
cur->core.flag &= ~BAM_FPROPER_PAIR;
|
| 1052 |
+
}
|
| 1053 |
+
|
| 1054 |
+
if (do_mate_scoring) {
|
| 1055 |
+
if ((add_mate_score(pre, cur) == -1) ||
|
| 1056 |
+
(add_mate_score(cur, pre) == -1)) {
|
| 1057 |
+
fprintf(samtools_stderr, "[bam_mating_core] ERROR: "
|
| 1058 |
+
"unable to add mate score.\n");
|
| 1059 |
+
goto fail;
|
| 1060 |
+
}
|
| 1061 |
+
}
|
| 1062 |
+
|
| 1063 |
+
// If we have to remove reads make sure we do it in a way that
|
| 1064 |
+
// doesn't create orphans with bad flags
|
| 1065 |
+
if (remove_reads) {
|
| 1066 |
+
if (pre->core.flag&BAM_FUNMAP)
|
| 1067 |
+
cur->core.flag &=
|
| 1068 |
+
~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
|
| 1069 |
+
if (cur->core.flag&BAM_FUNMAP)
|
| 1070 |
+
pre->core.flag &=
|
| 1071 |
+
~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
|
| 1072 |
+
}
|
| 1073 |
+
}
|
| 1074 |
+
|
| 1075 |
+
// Handle unpaired primary data
|
| 1076 |
+
if (!cur && pre) {
|
| 1077 |
+
pre->core.mtid = -1;
|
| 1078 |
+
pre->core.mpos = -1;
|
| 1079 |
+
pre->core.isize = 0;
|
| 1080 |
+
pre->core.flag &= ~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
|
| 1081 |
+
}
|
| 1082 |
+
|
| 1083 |
+
// Now process secondary and supplementary alignments
|
| 1084 |
+
for (n = 0; n < bs.n; n++) {
|
| 1085 |
+
if (!(bs.b[n].core.flag & (BAM_FSECONDARY|BAM_FSUPPLEMENTARY))) {
|
| 1086 |
+
// primary
|
| 1087 |
+
continue;
|
| 1088 |
+
}
|
| 1089 |
+
|
| 1090 |
+
// Secondary or supplementary
|
| 1091 |
+
int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0;
|
| 1092 |
+
bam1_t *primary = rnum[is_r2];
|
| 1093 |
+
if (primary) {
|
| 1094 |
+
if (base_mods)
|
| 1095 |
+
fix_MM(primary, &bs.b[n], &state[is_r2]);
|
| 1096 |
+
} else {
|
| 1097 |
+
// Record with base modifications but no known primary
|
| 1098 |
+
//fprintf(samtools_stderr, "Unpaired secondary or supplementary\n");
|
| 1099 |
+
if (base_mods)
|
| 1100 |
+
fix_MM(NULL, &bs.b[n], NULL);
|
| 1101 |
+
}
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
// Finally having curated everything, write out all records in their
|
| 1105 |
+
// original ordering
|
| 1106 |
+
for (n = 0; n < bs.n; n++) {
|
| 1107 |
+
bam1_t *cur = &bs.b[n];
|
| 1108 |
+
// We may remove unmapped and secondary alignments
|
| 1109 |
+
if (remove_reads && (cur->core.flag & (BAM_FSECONDARY|BAM_FUNMAP)))
|
| 1110 |
+
continue;
|
| 1111 |
+
|
| 1112 |
+
if (sam_write1(out, header, cur) < 0)
|
| 1113 |
+
goto write_fail;
|
| 1114 |
+
}
|
| 1115 |
+
}
|
| 1116 |
+
if (result < -1)
|
| 1117 |
+
goto read_fail;
|
| 1118 |
+
|
| 1119 |
+
sam_hdr_destroy(header);
|
| 1120 |
+
|
| 1121 |
+
for (n = 0; n < bs.ba; n++)
|
| 1122 |
+
free(bs.b[n].data);
|
| 1123 |
+
free(bs.b);
|
| 1124 |
+
ks_free(&str);
|
| 1125 |
+
return 0;
|
| 1126 |
+
|
| 1127 |
+
read_fail:
|
| 1128 |
+
print_error("fixmate", "Couldn't read from input file");
|
| 1129 |
+
goto fail;
|
| 1130 |
+
|
| 1131 |
+
write_fail:
|
| 1132 |
+
print_error_errno("fixmate", "Couldn't write to output file");
|
| 1133 |
+
fail:
|
| 1134 |
+
sam_hdr_destroy(header);
|
| 1135 |
+
for (n = 0; n < bs.ba; n++)
|
| 1136 |
+
free(bs.b[n].data);
|
| 1137 |
+
free(bs.b);
|
| 1138 |
+
ks_free(&str);
|
| 1139 |
+
return 1;
|
| 1140 |
+
}
|
| 1141 |
+
|
| 1142 |
+
void usage(FILE* where)
|
| 1143 |
+
{
|
| 1144 |
+
fprintf(where,
|
| 1145 |
+
"Usage: samtools fixmate <in.nameSrt.bam> <out.nameSrt.bam>\n"
|
| 1146 |
+
"Options:\n"
|
| 1147 |
+
" -r Remove unmapped reads and secondary alignments\n"
|
| 1148 |
+
" -p Disable FR proper pair check\n"
|
| 1149 |
+
" -c Add template cigar ct tag\n"
|
| 1150 |
+
" -m Add mate score tag\n"
|
| 1151 |
+
" -u Uncompressed output\n"
|
| 1152 |
+
" -z, --sanitize FLAG[,FLAG]\n"
|
| 1153 |
+
" Sanitize alignment fields [defaults to all types]\n"
|
| 1154 |
+
" -M Fix base modification tags (MM/ML/MN)\n"
|
| 1155 |
+
" --no-PG do not add a PG line\n");
|
| 1156 |
+
|
| 1157 |
+
sam_global_opt_help(where, "-.O..@-.");
|
| 1158 |
+
|
| 1159 |
+
fprintf(where,
|
| 1160 |
+
"\n"
|
| 1161 |
+
"As elsewhere in samtools, use '-' as the filename for stdin/samtools_stdout. The input\n"
|
| 1162 |
+
"file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n"
|
| 1163 |
+
"input is not accepted.\n");
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
int bam_mating(int argc, char *argv[])
|
| 1167 |
+
{
|
| 1168 |
+
htsThreadPool p = {NULL, 0};
|
| 1169 |
+
samFile *in = NULL, *out = NULL;
|
| 1170 |
+
int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1,
|
| 1171 |
+
mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL, base_mods = 0;
|
| 1172 |
+
sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
|
| 1173 |
+
char wmode[4] = {'w', 'b', 0, 0};
|
| 1174 |
+
static const struct option lopts[] = {
|
| 1175 |
+
SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
|
| 1176 |
+
{"no-PG", no_argument, NULL, 1},
|
| 1177 |
+
{ NULL, 0, NULL, 0 }
|
| 1178 |
+
};
|
| 1179 |
+
char *arg_list = NULL;
|
| 1180 |
+
|
| 1181 |
+
// parse args
|
| 1182 |
+
if (argc == 1) { usage(samtools_stdout); return 0; }
|
| 1183 |
+
while ((c = getopt_long(argc, argv, "rpcmMO:@:uz:", lopts, NULL)) >= 0) {
|
| 1184 |
+
switch (c) {
|
| 1185 |
+
case 'r': remove_reads = 1; break;
|
| 1186 |
+
case 'p': proper_pair_check = 0; break;
|
| 1187 |
+
case 'c': add_ct = 1; break;
|
| 1188 |
+
case 'm': mate_score = 1; break;
|
| 1189 |
+
case 'M': base_mods = 1; break;
|
| 1190 |
+
case 'u': wmode[2] = '0'; break;
|
| 1191 |
+
case 1: no_pg = 1; break;
|
| 1192 |
+
default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
|
| 1193 |
+
/* else fall-through */
|
| 1194 |
+
case '?': usage(samtools_stderr); goto fail;
|
| 1195 |
+
case 'z':
|
| 1196 |
+
if ((sanitize_flags = bam_sanitize_options(optarg)) < 0)
|
| 1197 |
+
samtools_exit(1);
|
| 1198 |
+
break;
|
| 1199 |
+
}
|
| 1200 |
+
}
|
| 1201 |
+
if (optind+1 >= argc) { usage(samtools_stderr); goto fail; }
|
| 1202 |
+
|
| 1203 |
+
if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
|
| 1204 |
+
goto fail;
|
| 1205 |
+
|
| 1206 |
+
// init
|
| 1207 |
+
if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
|
| 1208 |
+
print_error_errno("fixmate", "cannot open input file");
|
| 1209 |
+
goto fail;
|
| 1210 |
+
}
|
| 1211 |
+
sam_open_mode(wmode+1, argv[optind+1], NULL);
|
| 1212 |
+
if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) {
|
| 1213 |
+
print_error_errno("fixmate", "cannot open output file");
|
| 1214 |
+
goto fail;
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
if (ga.nthreads > 0) {
|
| 1218 |
+
if (!(p.pool = hts_tpool_init(ga.nthreads))) {
|
| 1219 |
+
fprintf(samtools_stderr, "Error creating thread pool\n");
|
| 1220 |
+
goto fail;
|
| 1221 |
+
}
|
| 1222 |
+
hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
|
| 1223 |
+
hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
|
| 1224 |
+
}
|
| 1225 |
+
|
| 1226 |
+
// run
|
| 1227 |
+
res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct,
|
| 1228 |
+
mate_score, arg_list, no_pg, sanitize_flags,
|
| 1229 |
+
base_mods);
|
| 1230 |
+
|
| 1231 |
+
// cleanup
|
| 1232 |
+
sam_close(in);
|
| 1233 |
+
if (sam_close(out) < 0) {
|
| 1234 |
+
fprintf(samtools_stderr, "[bam_mating] error while closing output file\n");
|
| 1235 |
+
res = 1;
|
| 1236 |
+
}
|
| 1237 |
+
|
| 1238 |
+
if (p.pool) hts_tpool_destroy(p.pool);
|
| 1239 |
+
free(arg_list);
|
| 1240 |
+
sam_global_args_free(&ga);
|
| 1241 |
+
return res;
|
| 1242 |
+
|
| 1243 |
+
fail:
|
| 1244 |
+
if (in) sam_close(in);
|
| 1245 |
+
if (out) sam_close(out);
|
| 1246 |
+
if (p.pool) hts_tpool_destroy(p.pool);
|
| 1247 |
+
free(arg_list);
|
| 1248 |
+
sam_global_args_free(&ga);
|
| 1249 |
+
return 1;
|
| 1250 |
+
}
|
| 1251 |
+
|
| 1252 |
+
|
shared/package-files/06/061f300ea91b48bfb2aff30342a1395d4a16cd96afe49fd5cc2f0b7efdc10650/test_ndarray_like.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from numcodecs.ndarray_like import DType, FlagsObj, NDArrayLike
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@pytest.mark.parametrize("module", ["numpy", "cupy"])
|
| 7 |
+
def test_is_ndarray_like(module):
|
| 8 |
+
m = pytest.importorskip(module)
|
| 9 |
+
a = m.arange(10)
|
| 10 |
+
assert isinstance(a, NDArrayLike)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_is_not_ndarray_like():
|
| 14 |
+
assert not isinstance([1, 2, 3], NDArrayLike)
|
| 15 |
+
assert not isinstance(b"1,2,3", NDArrayLike)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize("module", ["numpy", "cupy"])
|
| 19 |
+
def test_is_dtype_like(module):
|
| 20 |
+
m = pytest.importorskip(module)
|
| 21 |
+
d = m.dtype("u8")
|
| 22 |
+
assert isinstance(d, DType)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_is_not_dtype_like():
|
| 26 |
+
assert not isinstance([1, 2, 3], DType)
|
| 27 |
+
assert not isinstance(b"1,2,3", DType)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.parametrize("module", ["numpy", "cupy"])
|
| 31 |
+
def test_is_flags_like(module):
|
| 32 |
+
m = pytest.importorskip(module)
|
| 33 |
+
d = m.arange(10).flags
|
| 34 |
+
assert isinstance(d, FlagsObj)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_is_not_flags_like():
|
| 38 |
+
assert not isinstance([1, 2, 3], FlagsObj)
|
| 39 |
+
assert not isinstance(b"1,2,3", FlagsObj)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize("module", ["numpy", "cupy"])
|
| 43 |
+
def test_cached_isinstance_check(module):
|
| 44 |
+
m = pytest.importorskip(module)
|
| 45 |
+
a = m.arange(10)
|
| 46 |
+
assert isinstance(a, NDArrayLike)
|
| 47 |
+
assert not isinstance(a, DType)
|
| 48 |
+
assert not isinstance(a, FlagsObj)
|
shared/package-files/06/0620689f239b0ac4ba1272d4208ff5903b5c84337b4eeaf44f818cce8528d3a3/pkgdata.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This module is deprecated and will be removed.
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import os
|
| 5 |
+
from io import StringIO
|
| 6 |
+
|
| 7 |
+
from sympy.utilities.decorator import deprecated
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@deprecated(
|
| 11 |
+
"""
|
| 12 |
+
The sympy.utilities.pkgdata module and its get_resource function are
|
| 13 |
+
deprecated. Use the stdlib importlib.resources module instead.
|
| 14 |
+
""",
|
| 15 |
+
deprecated_since_version="1.12",
|
| 16 |
+
active_deprecations_target="pkgdata",
|
| 17 |
+
)
|
| 18 |
+
def get_resource(identifier, pkgname=__name__):
|
| 19 |
+
|
| 20 |
+
mod = sys.modules[pkgname]
|
| 21 |
+
fn = getattr(mod, '__file__', None)
|
| 22 |
+
if fn is None:
|
| 23 |
+
raise OSError("%r has no __file__!")
|
| 24 |
+
path = os.path.join(os.path.dirname(fn), identifier)
|
| 25 |
+
loader = getattr(mod, '__loader__', None)
|
| 26 |
+
if loader is not None:
|
| 27 |
+
try:
|
| 28 |
+
data = loader.get_data(path)
|
| 29 |
+
except (OSError, AttributeError):
|
| 30 |
+
pass
|
| 31 |
+
else:
|
| 32 |
+
return StringIO(data.decode('utf-8'))
|
| 33 |
+
return open(os.path.normpath(path), 'rb')
|
shared/package-files/06/0624dc495f0084fa8167b834d09a44098fb0fdff8dcb5f0a4320b15602b04ac8/_embedding_bag_sparse_backward_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor _embedding_bag_sparse_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/06/062c95ed30861d0f06883087f299fa0d7a1fd2e64e95a7c9b38085d1fe402572/test_sort_values.cpython-311.pyc
ADDED
|
Binary file (50.2 kB). View file
|
|
|
shared/package-files/06/062f6ebf5e41e4c5d437dfa1c940f21d90e4de3f82a3032c1b550eabbf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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import functools
|
| 5 |
+
from typing import Any, Callable, TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.fx
|
| 9 |
+
import torch.onnx
|
| 10 |
+
import torch.onnx._internal.fx.passes as passes
|
| 11 |
+
from torch.onnx._internal import _exporter_legacy, io_adapter
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from collections.abc import Mapping, Sequence
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Functions directly wrapped to produce torch.fx.Proxy so that symbolic
|
| 19 |
+
# data can flow through those functions. Python functions (e.g., `torch.arange`)
|
| 20 |
+
# not defined by pybind11 in C++ do not go though Python dispatcher, so
|
| 21 |
+
# they are not automatically patched by FX's Python dispatcher.
|
| 22 |
+
# The list below means `torch.arange`, `torch.tensor`, and so on will be
|
| 23 |
+
# patched.
|
| 24 |
+
_TORCH_METHODS_TO_PATCH: tuple[str, ...] = (
|
| 25 |
+
"arange",
|
| 26 |
+
"tensor",
|
| 27 |
+
"finfo",
|
| 28 |
+
"full",
|
| 29 |
+
"empty",
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ModuleExpansionTracer(torch.fx._symbolic_trace.Tracer):
|
| 34 |
+
"""Tracer to create ONNX-exporting friendly FX graph.
|
| 35 |
+
|
| 36 |
+
This tracer traces models into operators. That is,
|
| 37 |
+
the traced graph mostly contains call_function nodes and
|
| 38 |
+
has no call_module nodes. The call_module nodes
|
| 39 |
+
are problematic to the use of make_fx(...) in ONNX
|
| 40 |
+
exporter.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def is_leaf_module(
|
| 44 |
+
self, module: torch.nn.Module, module_qualified_name: str
|
| 45 |
+
) -> bool:
|
| 46 |
+
# This returns False so that all sub-modules are considered as not leaves
|
| 47 |
+
# and therefore expanded into operators in
|
| 48 |
+
# torch.fx._symbolic_trace.Tracer.call_module.
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
def to_bool(self, obj: torch.fx.Proxy) -> bool:
|
| 52 |
+
# FIXME: This is a hack to tracing through if-else Python blocks.
|
| 53 |
+
# It may generate incorrect ONNX graphs if the if-else block
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _wrap_for_symbolic_trace(target: Callable) -> tuple[Callable, Callable]:
|
| 58 |
+
"""This function wraps ```target`` for symbolic tracing.
|
| 59 |
+
|
| 60 |
+
This function wraps ```target``` so that its wrapper produces
|
| 61 |
+
torch.fx.Proxy in symbolic computation. The returned values are
|
| 62 |
+
the wrapper and then the original function. Per `_TORCH_METHODS_TO_PATCH`,
|
| 63 |
+
this function shall receive `torch.arange`, `torch.tensor`, etc. as inputs.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
@functools.wraps(target)
|
| 67 |
+
def wrapper(*args, **kwargs):
|
| 68 |
+
proxy = None
|
| 69 |
+
|
| 70 |
+
def check_has_proxy(v):
|
| 71 |
+
if isinstance(v, torch.fx.Proxy):
|
| 72 |
+
nonlocal proxy
|
| 73 |
+
proxy = v
|
| 74 |
+
|
| 75 |
+
torch.fx.node.map_aggregate(args, check_has_proxy)
|
| 76 |
+
torch.fx.node.map_aggregate(kwargs, check_has_proxy)
|
| 77 |
+
|
| 78 |
+
if proxy is not None:
|
| 79 |
+
return proxy.tracer.create_proxy("call_function", target, args, kwargs)
|
| 80 |
+
else:
|
| 81 |
+
return target(*args, **kwargs)
|
| 82 |
+
|
| 83 |
+
return wrapper, target
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _module_expansion_symbolic_trace(
|
| 87 |
+
root: torch.nn.Module | Callable[..., Any],
|
| 88 |
+
concrete_args: dict[str, Any] | None = None,
|
| 89 |
+
) -> torch.fx.GraphModule:
|
| 90 |
+
"""Trace a callable into FX graph.
|
| 91 |
+
|
| 92 |
+
When "root" is torch.nn.Module, calls to its submodule (type: torch.nn.Module) will be
|
| 93 |
+
expanded into operators (e.g., torch.matmul, torch.add, +, and -) to simplify graph
|
| 94 |
+
structure.
|
| 95 |
+
"""
|
| 96 |
+
# For functions doesn't support symbolic tracing, create wrappers
|
| 97 |
+
# which produce symbolic results during tracing.
|
| 98 |
+
patched_torch_methods = {
|
| 99 |
+
target_name: _wrap_for_symbolic_trace(getattr(torch, target_name))
|
| 100 |
+
for target_name in _TORCH_METHODS_TO_PATCH
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
# Set the symbolic-tracing friendly functions so that `tracer.trace` below
|
| 104 |
+
# can work.
|
| 105 |
+
for name, (wrapper, _) in patched_torch_methods.items():
|
| 106 |
+
setattr(torch, name, wrapper)
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
# Set up a tracer.
|
| 110 |
+
tracer = ModuleExpansionTracer()
|
| 111 |
+
# Trace the model.
|
| 112 |
+
graph = tracer.trace(root, concrete_args)
|
| 113 |
+
name = (
|
| 114 |
+
root.__class__.__name__
|
| 115 |
+
if isinstance(root, torch.nn.Module)
|
| 116 |
+
else root.__name__
|
| 117 |
+
)
|
| 118 |
+
return torch.fx.GraphModule(tracer.root, graph, name)
|
| 119 |
+
finally:
|
| 120 |
+
# Revert the patches for symbolic tracing.
|
| 121 |
+
for name, (_, wrapped) in patched_torch_methods.items():
|
| 122 |
+
# wrapped is the original version of `torch.name`.
|
| 123 |
+
setattr(torch, name, wrapped)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# TODO: Migrate to `DynamoExporter` after fake model tracing is supported.
|
| 127 |
+
# Proposal at https://github.com/pytorch/pytorch/issues/95900.
|
| 128 |
+
class FXSymbolicTracer(_exporter_legacy.FXGraphExtractor):
|
| 129 |
+
"""Generates a FX GraphModule using torch.fx.symbolic_trace API
|
| 130 |
+
Args:
|
| 131 |
+
concrete_args: Inputs to be partially specialized
|
| 132 |
+
It can be used to remove control flow or data structures.
|
| 133 |
+
For example::
|
| 134 |
+
def f(a, b):
|
| 135 |
+
if b == True:
|
| 136 |
+
return a
|
| 137 |
+
else:
|
| 138 |
+
return a*2
|
| 139 |
+
FX can typically not trace through this due to the presence of control
|
| 140 |
+
flow. However, we can use `concrete_args` to specialize on the value of
|
| 141 |
+
`b` to trace through this::
|
| 142 |
+
f = fx.symbolic_trace(f, concrete_args={'b': False})
|
| 143 |
+
assert f(3, False) == 6
|
| 144 |
+
Note that although you can still pass in different values of `b`, they will be ignored.
|
| 145 |
+
It can also be used to eliminate data-structure handling from
|
| 146 |
+
our function. This will use pytrees to flatten your input. To avoid
|
| 147 |
+
overspecializing, pass in `fx.PH` for values that shouldn't be
|
| 148 |
+
specialized. For example::
|
| 149 |
+
def f(x):
|
| 150 |
+
out = 0
|
| 151 |
+
for v in x.values():
|
| 152 |
+
out += v
|
| 153 |
+
return out
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
f = fx.symbolic_trace(
|
| 157 |
+
f,
|
| 158 |
+
concrete_args={"x": {"a": fx.PH, "b": fx.PH, "c": fx.PH}},
|
| 159 |
+
)
|
| 160 |
+
assert f({"a": 1, "b": 2, "c": 4}) == 7
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
def __init__(self, concrete_args: dict[str, Any] | None = None):
|
| 164 |
+
super().__init__()
|
| 165 |
+
# TODO: plumb ``concrete_args`` to symbolic_trace call at ``generate_fx``
|
| 166 |
+
self.concrete_args = concrete_args
|
| 167 |
+
|
| 168 |
+
def _trace_into_fx_graph_via_fx_symbolic_trace(
|
| 169 |
+
self, model, model_args, model_kwargs
|
| 170 |
+
) -> torch.fx.GraphModule:
|
| 171 |
+
# Bind model args and kwargs with model signature to retrieve default values
|
| 172 |
+
# of unprovided arguments. These are then used to construct ``concrete_args``.
|
| 173 |
+
bind_input_step = io_adapter.BindInputStep(
|
| 174 |
+
torch.onnx.utils.model_signature(model)
|
| 175 |
+
)
|
| 176 |
+
self.input_adapter.append_step(bind_input_step)
|
| 177 |
+
_, named_args = bind_input_step.apply(model_args, model_kwargs, model=model)
|
| 178 |
+
|
| 179 |
+
# Create inputs to call symbolic trace (torch.fx.symbolic_trace)
|
| 180 |
+
# Example content of concrete_args:
|
| 181 |
+
# concrete_args["x"] = torch.fx._symbolic_trace.PH
|
| 182 |
+
# concrete_args["b"] = 1
|
| 183 |
+
# where "x" and "b" are argument names in "signature".
|
| 184 |
+
concrete_args = {}
|
| 185 |
+
for param_name, param_value in named_args.items():
|
| 186 |
+
if isinstance(param_value, torch.Tensor):
|
| 187 |
+
# param_value can be, e.g., a real tensor or a fake tensor.
|
| 188 |
+
# param_value is treated as substitutable tensor symbol (aka placeholder).
|
| 189 |
+
concrete_args[param_name] = torch.fx._symbolic_trace.PH
|
| 190 |
+
else:
|
| 191 |
+
concrete_args[param_name] = param_value
|
| 192 |
+
|
| 193 |
+
# Merge kwargs back into args since that is the format FX graph expects.
|
| 194 |
+
merge_kwargs_step = io_adapter.MergeKwargsIntoArgsInputStep()
|
| 195 |
+
self.input_adapter.append_step(merge_kwargs_step)
|
| 196 |
+
return _module_expansion_symbolic_trace(model, concrete_args=concrete_args)
|
| 197 |
+
|
| 198 |
+
def generate_fx(
|
| 199 |
+
self,
|
| 200 |
+
options: _exporter_legacy.ResolvedExportOptions,
|
| 201 |
+
model: torch.nn.Module | Callable,
|
| 202 |
+
model_args: Sequence[Any],
|
| 203 |
+
model_kwargs: Mapping[str, Any],
|
| 204 |
+
) -> torch.fx.GraphModule:
|
| 205 |
+
diagnostic_context = options.diagnostic_context
|
| 206 |
+
graph_module = self._trace_into_fx_graph_via_fx_symbolic_trace(
|
| 207 |
+
model, model_args, model_kwargs
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Make sure all placeholder nodes are executed before get_attr nodes.
|
| 211 |
+
# Otherwise, inputs can interleave with initializers in the final ModeoProto.graph.input.
|
| 212 |
+
# Basically, we want
|
| 213 |
+
# ModeoProto.graph.input =
|
| 214 |
+
# [input_0, input_1, ..., input_n, weight_0, weight_1, ..., weight_m]
|
| 215 |
+
# and we don't want
|
| 216 |
+
# ModeoProto.graph.input =
|
| 217 |
+
# [input_0, weight_0, input_1, weight_1, ..., input_n, weight_0, weight_1, ..., weight_m]
|
| 218 |
+
graph_module = passes.MovePlaceholderToFront(
|
| 219 |
+
diagnostic_context, graph_module
|
| 220 |
+
).run()
|
| 221 |
+
# To save memory, move get_attr to input so that the generated model doesn't
|
| 222 |
+
# have weigh tensors. "replaced_attrs" are a tuple of replaced weight tensors.
|
| 223 |
+
replace_get_attr_with_placeholder_pass = passes.ReplaceGetAttrWithPlaceholder(
|
| 224 |
+
diagnostic_context, graph_module
|
| 225 |
+
)
|
| 226 |
+
graph_module = replace_get_attr_with_placeholder_pass.run()
|
| 227 |
+
replaced_attrs = replace_get_attr_with_placeholder_pass.replaced_attrs
|
| 228 |
+
append_extra_input_step = io_adapter.LiftParametersAndBuffersIntoArgsInputStep(
|
| 229 |
+
replaced_attrs
|
| 230 |
+
)
|
| 231 |
+
self.input_adapter.append_step(append_extra_input_step)
|
| 232 |
+
# Move all newly created placeholder nodes to the front of the graph.
|
| 233 |
+
graph_module = passes.MovePlaceholderToFront(
|
| 234 |
+
diagnostic_context, graph_module
|
| 235 |
+
).run()
|
| 236 |
+
# Finalize the graph editing.
|
| 237 |
+
graph_module.recompile()
|
| 238 |
+
|
| 239 |
+
updated_model_args = self.input_adapter.apply(
|
| 240 |
+
*model_args, model=model, **model_kwargs
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return self.pre_export_passes(options, model, graph_module, updated_model_args) # type: ignore[return-value]
|
| 244 |
+
|
| 245 |
+
def pre_export_passes(
|
| 246 |
+
self,
|
| 247 |
+
options: _exporter_legacy.ResolvedExportOptions,
|
| 248 |
+
original_model: torch.nn.Module | Callable,
|
| 249 |
+
fx_module: torch.fx.GraphModule,
|
| 250 |
+
fx_module_args: Sequence[Any],
|
| 251 |
+
):
|
| 252 |
+
return _exporter_legacy.common_pre_export_passes(
|
| 253 |
+
options, original_model, fx_module, fx_module_args
|
| 254 |
+
)
|
shared/package-files/06/06363bb2a8bd33adf787d66028d17c99bc1a030cf368a2048a9f087a8f4e02be/test_python.cpython-311.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
shared/package-files/06/0636f045562112f6e9f30d39b1877cdfc55f812e1d364b5bf13ee6d8f89c8c23/feather_format.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" feather-format compat """
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import (
|
| 5 |
+
TYPE_CHECKING,
|
| 6 |
+
Any,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
from pandas._config import using_pyarrow_string_dtype
|
| 10 |
+
|
| 11 |
+
from pandas._libs import lib
|
| 12 |
+
from pandas.compat._optional import import_optional_dependency
|
| 13 |
+
from pandas.util._decorators import doc
|
| 14 |
+
from pandas.util._validators import check_dtype_backend
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
from pandas.core.api import DataFrame
|
| 18 |
+
from pandas.core.shared_docs import _shared_docs
|
| 19 |
+
|
| 20 |
+
from pandas.io._util import arrow_string_types_mapper
|
| 21 |
+
from pandas.io.common import get_handle
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from collections.abc import (
|
| 25 |
+
Hashable,
|
| 26 |
+
Sequence,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from pandas._typing import (
|
| 30 |
+
DtypeBackend,
|
| 31 |
+
FilePath,
|
| 32 |
+
ReadBuffer,
|
| 33 |
+
StorageOptions,
|
| 34 |
+
WriteBuffer,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@doc(storage_options=_shared_docs["storage_options"])
|
| 39 |
+
def to_feather(
|
| 40 |
+
df: DataFrame,
|
| 41 |
+
path: FilePath | WriteBuffer[bytes],
|
| 42 |
+
storage_options: StorageOptions | None = None,
|
| 43 |
+
**kwargs: Any,
|
| 44 |
+
) -> None:
|
| 45 |
+
"""
|
| 46 |
+
Write a DataFrame to the binary Feather format.
|
| 47 |
+
|
| 48 |
+
Parameters
|
| 49 |
+
----------
|
| 50 |
+
df : DataFrame
|
| 51 |
+
path : str, path object, or file-like object
|
| 52 |
+
{storage_options}
|
| 53 |
+
**kwargs :
|
| 54 |
+
Additional keywords passed to `pyarrow.feather.write_feather`.
|
| 55 |
+
|
| 56 |
+
"""
|
| 57 |
+
import_optional_dependency("pyarrow")
|
| 58 |
+
from pyarrow import feather
|
| 59 |
+
|
| 60 |
+
if not isinstance(df, DataFrame):
|
| 61 |
+
raise ValueError("feather only support IO with DataFrames")
|
| 62 |
+
|
| 63 |
+
with get_handle(
|
| 64 |
+
path, "wb", storage_options=storage_options, is_text=False
|
| 65 |
+
) as handles:
|
| 66 |
+
feather.write_feather(df, handles.handle, **kwargs)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@doc(storage_options=_shared_docs["storage_options"])
|
| 70 |
+
def read_feather(
|
| 71 |
+
path: FilePath | ReadBuffer[bytes],
|
| 72 |
+
columns: Sequence[Hashable] | None = None,
|
| 73 |
+
use_threads: bool = True,
|
| 74 |
+
storage_options: StorageOptions | None = None,
|
| 75 |
+
dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
|
| 76 |
+
) -> DataFrame:
|
| 77 |
+
"""
|
| 78 |
+
Load a feather-format object from the file path.
|
| 79 |
+
|
| 80 |
+
Parameters
|
| 81 |
+
----------
|
| 82 |
+
path : str, path object, or file-like object
|
| 83 |
+
String, path object (implementing ``os.PathLike[str]``), or file-like
|
| 84 |
+
object implementing a binary ``read()`` function. The string could be a URL.
|
| 85 |
+
Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is
|
| 86 |
+
expected. A local file could be: ``file://localhost/path/to/table.feather``.
|
| 87 |
+
columns : sequence, default None
|
| 88 |
+
If not provided, all columns are read.
|
| 89 |
+
use_threads : bool, default True
|
| 90 |
+
Whether to parallelize reading using multiple threads.
|
| 91 |
+
{storage_options}
|
| 92 |
+
|
| 93 |
+
dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable'
|
| 94 |
+
Back-end data type applied to the resultant :class:`DataFrame`
|
| 95 |
+
(still experimental). Behaviour is as follows:
|
| 96 |
+
|
| 97 |
+
* ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
|
| 98 |
+
(default).
|
| 99 |
+
* ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
|
| 100 |
+
DataFrame.
|
| 101 |
+
|
| 102 |
+
.. versionadded:: 2.0
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
type of object stored in file
|
| 107 |
+
|
| 108 |
+
Examples
|
| 109 |
+
--------
|
| 110 |
+
>>> df = pd.read_feather("path/to/file.feather") # doctest: +SKIP
|
| 111 |
+
"""
|
| 112 |
+
import_optional_dependency("pyarrow")
|
| 113 |
+
from pyarrow import feather
|
| 114 |
+
|
| 115 |
+
# import utils to register the pyarrow extension types
|
| 116 |
+
import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401
|
| 117 |
+
|
| 118 |
+
check_dtype_backend(dtype_backend)
|
| 119 |
+
|
| 120 |
+
with get_handle(
|
| 121 |
+
path, "rb", storage_options=storage_options, is_text=False
|
| 122 |
+
) as handles:
|
| 123 |
+
if dtype_backend is lib.no_default and not using_pyarrow_string_dtype():
|
| 124 |
+
return feather.read_feather(
|
| 125 |
+
handles.handle, columns=columns, use_threads=bool(use_threads)
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
pa_table = feather.read_table(
|
| 129 |
+
handles.handle, columns=columns, use_threads=bool(use_threads)
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if dtype_backend == "numpy_nullable":
|
| 133 |
+
from pandas.io._util import _arrow_dtype_mapping
|
| 134 |
+
|
| 135 |
+
return pa_table.to_pandas(types_mapper=_arrow_dtype_mapping().get)
|
| 136 |
+
|
| 137 |
+
elif dtype_backend == "pyarrow":
|
| 138 |
+
return pa_table.to_pandas(types_mapper=pd.ArrowDtype)
|
| 139 |
+
|
| 140 |
+
elif using_pyarrow_string_dtype():
|
| 141 |
+
return pa_table.to_pandas(types_mapper=arrow_string_types_mapper())
|
| 142 |
+
else:
|
| 143 |
+
raise NotImplementedError
|
shared/package-files/06/0639372bac40320c313cd4ca7e293b482e58db8c202acf0ecf9563bc5772d240/class.h
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 <pybind11/attr.h>
|
| 13 |
+
#include <pybind11/options.h>
|
| 14 |
+
|
| 15 |
+
#include "exception_translation.h"
|
| 16 |
+
|
| 17 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
| 18 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 19 |
+
|
| 20 |
+
#if !defined(PYPY_VERSION)
|
| 21 |
+
# define PYBIND11_BUILTIN_QUALNAME
|
| 22 |
+
# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
|
| 23 |
+
#else
|
| 24 |
+
// In PyPy, we still set __qualname__ so that we can produce reliable function type
|
| 25 |
+
// signatures; in CPython this macro expands to nothing:
|
| 26 |
+
# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
|
| 27 |
+
setattr((PyObject *) obj, "__qualname__", nameobj)
|
| 28 |
+
#endif
|
| 29 |
+
|
| 30 |
+
inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
|
| 31 |
+
#if !defined(PYPY_VERSION)
|
| 32 |
+
return type->tp_name;
|
| 33 |
+
#else
|
| 34 |
+
auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
|
| 35 |
+
if (module_name == PYBIND11_BUILTINS_MODULE)
|
| 36 |
+
return type->tp_name;
|
| 37 |
+
else
|
| 38 |
+
return std::move(module_name) + "." + type->tp_name;
|
| 39 |
+
#endif
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
inline PyTypeObject *type_incref(PyTypeObject *type) {
|
| 43 |
+
Py_INCREF(type);
|
| 44 |
+
return type;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
#if !defined(PYPY_VERSION)
|
| 48 |
+
|
| 49 |
+
/// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
|
| 50 |
+
extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
|
| 51 |
+
return PyProperty_Type.tp_descr_get(self, cls, cls);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
/// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
|
| 55 |
+
extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
|
| 56 |
+
PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
|
| 57 |
+
return PyProperty_Type.tp_descr_set(self, cls, value);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// Forward declaration to use in `make_static_property_type()`
|
| 61 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
|
| 62 |
+
|
| 63 |
+
/** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
|
| 64 |
+
methods are modified to always use the object type instead of a concrete instance.
|
| 65 |
+
Return value: New reference. */
|
| 66 |
+
inline PyTypeObject *make_static_property_type() {
|
| 67 |
+
constexpr auto *name = "pybind11_static_property";
|
| 68 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
| 69 |
+
|
| 70 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 71 |
+
issue no Python C API calls which could potentially invoke the
|
| 72 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 73 |
+
turn find the newly constructed type in an invalid state) */
|
| 74 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
| 75 |
+
if (!heap_type) {
|
| 76 |
+
pybind11_fail("make_static_property_type(): error allocating type!");
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
| 80 |
+
# ifdef PYBIND11_BUILTIN_QUALNAME
|
| 81 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
| 82 |
+
# endif
|
| 83 |
+
|
| 84 |
+
auto *type = &heap_type->ht_type;
|
| 85 |
+
type->tp_name = name;
|
| 86 |
+
type->tp_base = type_incref(&PyProperty_Type);
|
| 87 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
| 88 |
+
type->tp_descr_get = pybind11_static_get;
|
| 89 |
+
type->tp_descr_set = pybind11_static_set;
|
| 90 |
+
|
| 91 |
+
# if PY_VERSION_HEX >= 0x030C0000
|
| 92 |
+
// Since Python-3.12 property-derived types are required to
|
| 93 |
+
// have dynamic attributes (to set `__doc__`)
|
| 94 |
+
enable_dynamic_attributes(heap_type);
|
| 95 |
+
# endif
|
| 96 |
+
|
| 97 |
+
if (PyType_Ready(type) < 0) {
|
| 98 |
+
pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 102 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 103 |
+
|
| 104 |
+
return type;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
#else // PYPY
|
| 108 |
+
|
| 109 |
+
/** PyPy has some issues with the above C API, so we evaluate Python code instead.
|
| 110 |
+
This function will only be called once so performance isn't really a concern.
|
| 111 |
+
Return value: New reference. */
|
| 112 |
+
inline PyTypeObject *make_static_property_type() {
|
| 113 |
+
auto d = dict();
|
| 114 |
+
PyObject *result = PyRun_String(R"(\
|
| 115 |
+
class pybind11_static_property(property):
|
| 116 |
+
def __get__(self, obj, cls):
|
| 117 |
+
return property.__get__(self, cls, cls)
|
| 118 |
+
|
| 119 |
+
def __set__(self, obj, value):
|
| 120 |
+
cls = obj if isinstance(obj, type) else type(obj)
|
| 121 |
+
property.__set__(self, cls, value)
|
| 122 |
+
)",
|
| 123 |
+
Py_file_input,
|
| 124 |
+
d.ptr(),
|
| 125 |
+
d.ptr());
|
| 126 |
+
if (result == nullptr)
|
| 127 |
+
throw error_already_set();
|
| 128 |
+
Py_DECREF(result);
|
| 129 |
+
return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
#endif // PYPY
|
| 133 |
+
|
| 134 |
+
/** Types with static properties need to handle `Type.static_prop = x` in a specific way.
|
| 135 |
+
By default, Python replaces the `static_property` itself, but for wrapped C++ types
|
| 136 |
+
we need to call `static_property.__set__()` in order to propagate the new value to
|
| 137 |
+
the underlying C++ data structure. */
|
| 138 |
+
extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
|
| 139 |
+
// Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
|
| 140 |
+
// descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
|
| 141 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
| 142 |
+
|
| 143 |
+
// The following assignment combinations are possible:
|
| 144 |
+
// 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
|
| 145 |
+
// 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
|
| 146 |
+
// 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
|
| 147 |
+
auto *const static_prop = (PyObject *) get_internals().static_property_type;
|
| 148 |
+
const auto call_descr_set = (descr != nullptr) && (value != nullptr)
|
| 149 |
+
&& (PyObject_IsInstance(descr, static_prop) != 0)
|
| 150 |
+
&& (PyObject_IsInstance(value, static_prop) == 0);
|
| 151 |
+
if (call_descr_set) {
|
| 152 |
+
// Call `static_property.__set__()` instead of replacing the `static_property`.
|
| 153 |
+
#if !defined(PYPY_VERSION)
|
| 154 |
+
return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
|
| 155 |
+
#else
|
| 156 |
+
if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
|
| 157 |
+
Py_DECREF(result);
|
| 158 |
+
return 0;
|
| 159 |
+
} else {
|
| 160 |
+
return -1;
|
| 161 |
+
}
|
| 162 |
+
#endif
|
| 163 |
+
} else {
|
| 164 |
+
// Replace existing attribute.
|
| 165 |
+
return PyType_Type.tp_setattro(obj, name, value);
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
/**
|
| 170 |
+
* Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
|
| 171 |
+
* methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
|
| 172 |
+
* when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
|
| 173 |
+
* to do a special case bypass for PyInstanceMethod_Types.
|
| 174 |
+
*/
|
| 175 |
+
extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
|
| 176 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
| 177 |
+
if (descr && PyInstanceMethod_Check(descr)) {
|
| 178 |
+
Py_INCREF(descr);
|
| 179 |
+
return descr;
|
| 180 |
+
}
|
| 181 |
+
return PyType_Type.tp_getattro(obj, name);
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
/// metaclass `__call__` function that is used to create all pybind11 objects.
|
| 185 |
+
extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
|
| 186 |
+
|
| 187 |
+
// use the default metaclass call to create/initialize the object
|
| 188 |
+
PyObject *self = PyType_Type.tp_call(type, args, kwargs);
|
| 189 |
+
if (self == nullptr) {
|
| 190 |
+
return nullptr;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// Ensure that the base __init__ function(s) were called
|
| 194 |
+
values_and_holders vhs(self);
|
| 195 |
+
for (const auto &vh : vhs) {
|
| 196 |
+
if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
|
| 197 |
+
PyErr_Format(PyExc_TypeError,
|
| 198 |
+
"%.200s.__init__() must be called when overriding __init__",
|
| 199 |
+
get_fully_qualified_tp_name(vh.type->type).c_str());
|
| 200 |
+
Py_DECREF(self);
|
| 201 |
+
return nullptr;
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
return self;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
/// Cleanup the type-info for a pybind11-registered type.
|
| 209 |
+
extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
|
| 210 |
+
with_internals([obj](internals &internals) {
|
| 211 |
+
auto *type = (PyTypeObject *) obj;
|
| 212 |
+
|
| 213 |
+
// A pybind11-registered type will:
|
| 214 |
+
// 1) be found in internals.registered_types_py
|
| 215 |
+
// 2) have exactly one associated `detail::type_info`
|
| 216 |
+
auto found_type = internals.registered_types_py.find(type);
|
| 217 |
+
if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
|
| 218 |
+
&& found_type->second[0]->type == type) {
|
| 219 |
+
|
| 220 |
+
auto *tinfo = found_type->second[0];
|
| 221 |
+
auto tindex = std::type_index(*tinfo->cpptype);
|
| 222 |
+
internals.direct_conversions.erase(tindex);
|
| 223 |
+
|
| 224 |
+
if (tinfo->module_local) {
|
| 225 |
+
get_local_internals().registered_types_cpp.erase(tindex);
|
| 226 |
+
} else {
|
| 227 |
+
internals.registered_types_cpp.erase(tindex);
|
| 228 |
+
}
|
| 229 |
+
internals.registered_types_py.erase(tinfo->type);
|
| 230 |
+
|
| 231 |
+
// Actually just `std::erase_if`, but that's only available in C++20
|
| 232 |
+
auto &cache = internals.inactive_override_cache;
|
| 233 |
+
for (auto it = cache.begin(), last = cache.end(); it != last;) {
|
| 234 |
+
if (it->first == (PyObject *) tinfo->type) {
|
| 235 |
+
it = cache.erase(it);
|
| 236 |
+
} else {
|
| 237 |
+
++it;
|
| 238 |
+
}
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
delete tinfo;
|
| 242 |
+
}
|
| 243 |
+
});
|
| 244 |
+
|
| 245 |
+
PyType_Type.tp_dealloc(obj);
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
/** This metaclass is assigned by default to all pybind11 types and is required in order
|
| 249 |
+
for static properties to function correctly. Users may override this using `py::metaclass`.
|
| 250 |
+
Return value: New reference. */
|
| 251 |
+
inline PyTypeObject *make_default_metaclass() {
|
| 252 |
+
constexpr auto *name = "pybind11_type";
|
| 253 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
| 254 |
+
|
| 255 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 256 |
+
issue no Python C API calls which could potentially invoke the
|
| 257 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 258 |
+
turn find the newly constructed type in an invalid state) */
|
| 259 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
| 260 |
+
if (!heap_type) {
|
| 261 |
+
pybind11_fail("make_default_metaclass(): error allocating metaclass!");
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
| 265 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 266 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
| 267 |
+
#endif
|
| 268 |
+
|
| 269 |
+
auto *type = &heap_type->ht_type;
|
| 270 |
+
type->tp_name = name;
|
| 271 |
+
type->tp_base = type_incref(&PyType_Type);
|
| 272 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
| 273 |
+
|
| 274 |
+
type->tp_call = pybind11_meta_call;
|
| 275 |
+
|
| 276 |
+
type->tp_setattro = pybind11_meta_setattro;
|
| 277 |
+
type->tp_getattro = pybind11_meta_getattro;
|
| 278 |
+
|
| 279 |
+
type->tp_dealloc = pybind11_meta_dealloc;
|
| 280 |
+
|
| 281 |
+
if (PyType_Ready(type) < 0) {
|
| 282 |
+
pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 286 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 287 |
+
|
| 288 |
+
return type;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
/// For multiple inheritance types we need to recursively register/deregister base pointers for any
|
| 292 |
+
/// base classes with pointers that are difference from the instance value pointer so that we can
|
| 293 |
+
/// correctly recognize an offset base class pointer. This calls a function with any offset base
|
| 294 |
+
/// ptrs.
|
| 295 |
+
inline void traverse_offset_bases(void *valueptr,
|
| 296 |
+
const detail::type_info *tinfo,
|
| 297 |
+
instance *self,
|
| 298 |
+
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
|
| 299 |
+
for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
|
| 300 |
+
if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
|
| 301 |
+
for (auto &c : parent_tinfo->implicit_casts) {
|
| 302 |
+
if (c.first == tinfo->cpptype) {
|
| 303 |
+
auto *parentptr = c.second(valueptr);
|
| 304 |
+
if (parentptr != valueptr) {
|
| 305 |
+
f(parentptr, self);
|
| 306 |
+
}
|
| 307 |
+
traverse_offset_bases(parentptr, parent_tinfo, self, f);
|
| 308 |
+
break;
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
inline bool register_instance_impl(void *ptr, instance *self) {
|
| 316 |
+
with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
|
| 317 |
+
return true; // unused, but gives the same signature as the deregister func
|
| 318 |
+
}
|
| 319 |
+
inline bool deregister_instance_impl(void *ptr, instance *self) {
|
| 320 |
+
return with_instance_map(ptr, [&](instance_map &instances) {
|
| 321 |
+
auto range = instances.equal_range(ptr);
|
| 322 |
+
for (auto it = range.first; it != range.second; ++it) {
|
| 323 |
+
if (self == it->second) {
|
| 324 |
+
instances.erase(it);
|
| 325 |
+
return true;
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
return false;
|
| 329 |
+
});
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
|
| 333 |
+
register_instance_impl(valptr, self);
|
| 334 |
+
if (!tinfo->simple_ancestors) {
|
| 335 |
+
traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
|
| 340 |
+
bool ret = deregister_instance_impl(valptr, self);
|
| 341 |
+
if (!tinfo->simple_ancestors) {
|
| 342 |
+
traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
|
| 343 |
+
}
|
| 344 |
+
return ret;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
/// Instance creation function for all pybind11 types. It allocates the internal instance layout
|
| 348 |
+
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
|
| 349 |
+
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
|
| 350 |
+
inline PyObject *make_new_instance(PyTypeObject *type) {
|
| 351 |
+
#if defined(PYPY_VERSION)
|
| 352 |
+
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
|
| 353 |
+
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
|
| 354 |
+
ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
|
| 355 |
+
if (type->tp_basicsize < instance_size) {
|
| 356 |
+
type->tp_basicsize = instance_size;
|
| 357 |
+
}
|
| 358 |
+
#endif
|
| 359 |
+
PyObject *self = type->tp_alloc(type, 0);
|
| 360 |
+
auto *inst = reinterpret_cast<instance *>(self);
|
| 361 |
+
// Allocate the value/holder internals:
|
| 362 |
+
inst->allocate_layout();
|
| 363 |
+
|
| 364 |
+
return self;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
/// Instance creation function for all pybind11 types. It only allocates space for the
|
| 368 |
+
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
|
| 369 |
+
extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
|
| 370 |
+
return make_new_instance(type);
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
/// An `__init__` function constructs the C++ object. Users should provide at least one
|
| 374 |
+
/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
|
| 375 |
+
/// following default function will be used which simply throws an exception.
|
| 376 |
+
extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
|
| 377 |
+
PyTypeObject *type = Py_TYPE(self);
|
| 378 |
+
std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
|
| 379 |
+
set_error(PyExc_TypeError, msg.c_str());
|
| 380 |
+
return -1;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
inline void add_patient(PyObject *nurse, PyObject *patient) {
|
| 384 |
+
auto *instance = reinterpret_cast<detail::instance *>(nurse);
|
| 385 |
+
instance->has_patients = true;
|
| 386 |
+
Py_INCREF(patient);
|
| 387 |
+
|
| 388 |
+
with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
inline void clear_patients(PyObject *self) {
|
| 392 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
| 393 |
+
std::vector<PyObject *> patients;
|
| 394 |
+
|
| 395 |
+
with_internals([&](internals &internals) {
|
| 396 |
+
auto pos = internals.patients.find(self);
|
| 397 |
+
|
| 398 |
+
if (pos == internals.patients.end()) {
|
| 399 |
+
pybind11_fail(
|
| 400 |
+
"FATAL: Internal consistency check failed: Invalid clear_patients() call.");
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
// Clearing the patients can cause more Python code to run, which
|
| 404 |
+
// can invalidate the iterator. Extract the vector of patients
|
| 405 |
+
// from the unordered_map first.
|
| 406 |
+
patients = std::move(pos->second);
|
| 407 |
+
internals.patients.erase(pos);
|
| 408 |
+
});
|
| 409 |
+
|
| 410 |
+
instance->has_patients = false;
|
| 411 |
+
for (PyObject *&patient : patients) {
|
| 412 |
+
Py_CLEAR(patient);
|
| 413 |
+
}
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
/// Clears all internal data from the instance and removes it from registered instances in
|
| 417 |
+
/// preparation for deallocation.
|
| 418 |
+
inline void clear_instance(PyObject *self) {
|
| 419 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
| 420 |
+
|
| 421 |
+
// Deallocate any values/holders, if present:
|
| 422 |
+
for (auto &v_h : values_and_holders(instance)) {
|
| 423 |
+
if (v_h) {
|
| 424 |
+
|
| 425 |
+
// We have to deregister before we call dealloc because, for virtual MI types, we still
|
| 426 |
+
// need to be able to get the parent pointers.
|
| 427 |
+
if (v_h.instance_registered()
|
| 428 |
+
&& !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
|
| 429 |
+
pybind11_fail(
|
| 430 |
+
"pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
if (instance->owned || v_h.holder_constructed()) {
|
| 434 |
+
v_h.type->dealloc(v_h);
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
// Deallocate the value/holder layout internals:
|
| 439 |
+
instance->deallocate_layout();
|
| 440 |
+
|
| 441 |
+
if (instance->weakrefs) {
|
| 442 |
+
PyObject_ClearWeakRefs(self);
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
PyObject **dict_ptr = _PyObject_GetDictPtr(self);
|
| 446 |
+
if (dict_ptr) {
|
| 447 |
+
Py_CLEAR(*dict_ptr);
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
if (instance->has_patients) {
|
| 451 |
+
clear_patients(self);
|
| 452 |
+
}
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
|
| 456 |
+
/// to destroy the C++ object itself, while the rest is Python bookkeeping.
|
| 457 |
+
extern "C" inline void pybind11_object_dealloc(PyObject *self) {
|
| 458 |
+
auto *type = Py_TYPE(self);
|
| 459 |
+
|
| 460 |
+
// If this is a GC tracked object, untrack it first
|
| 461 |
+
// Note that the track call is implicitly done by the
|
| 462 |
+
// default tp_alloc, which we never override.
|
| 463 |
+
if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
|
| 464 |
+
PyObject_GC_UnTrack(self);
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
clear_instance(self);
|
| 468 |
+
|
| 469 |
+
type->tp_free(self);
|
| 470 |
+
|
| 471 |
+
#if PY_VERSION_HEX < 0x03080000
|
| 472 |
+
// `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
|
| 473 |
+
// as part of a derived type's dealloc, in which case we're not allowed to decref
|
| 474 |
+
// the type here. For cross-module compatibility, we shouldn't compare directly
|
| 475 |
+
// with `pybind11_object_dealloc`, but with the common one stashed in internals.
|
| 476 |
+
auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
|
| 477 |
+
if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
|
| 478 |
+
Py_DECREF(type);
|
| 479 |
+
#else
|
| 480 |
+
// This was not needed before Python 3.8 (Python issue 35810)
|
| 481 |
+
// https://github.com/pybind/pybind11/issues/1946
|
| 482 |
+
Py_DECREF(type);
|
| 483 |
+
#endif
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
std::string error_string();
|
| 487 |
+
|
| 488 |
+
/** Create the type which can be used as a common base for all classes. This is
|
| 489 |
+
needed in order to satisfy Python's requirements for multiple inheritance.
|
| 490 |
+
Return value: New reference. */
|
| 491 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
|
| 492 |
+
constexpr auto *name = "pybind11_object";
|
| 493 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
| 494 |
+
|
| 495 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 496 |
+
issue no Python C API calls which could potentially invoke the
|
| 497 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 498 |
+
turn find the newly constructed type in an invalid state) */
|
| 499 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
| 500 |
+
if (!heap_type) {
|
| 501 |
+
pybind11_fail("make_object_base_type(): error allocating type!");
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
| 505 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 506 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
| 507 |
+
#endif
|
| 508 |
+
|
| 509 |
+
auto *type = &heap_type->ht_type;
|
| 510 |
+
type->tp_name = name;
|
| 511 |
+
type->tp_base = type_incref(&PyBaseObject_Type);
|
| 512 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
| 513 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
| 514 |
+
|
| 515 |
+
type->tp_new = pybind11_object_new;
|
| 516 |
+
type->tp_init = pybind11_object_init;
|
| 517 |
+
type->tp_dealloc = pybind11_object_dealloc;
|
| 518 |
+
|
| 519 |
+
/* Support weak references (needed for the keep_alive feature) */
|
| 520 |
+
type->tp_weaklistoffset = offsetof(instance, weakrefs);
|
| 521 |
+
|
| 522 |
+
if (PyType_Ready(type) < 0) {
|
| 523 |
+
pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 527 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 528 |
+
|
| 529 |
+
assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
| 530 |
+
return (PyObject *) heap_type;
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
|
| 534 |
+
extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
|
| 535 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
| 536 |
+
PyObject_VisitManagedDict(self, visit, arg);
|
| 537 |
+
#else
|
| 538 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
| 539 |
+
Py_VISIT(dict);
|
| 540 |
+
#endif
|
| 541 |
+
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
|
| 542 |
+
#if PY_VERSION_HEX >= 0x03090000
|
| 543 |
+
Py_VISIT(Py_TYPE(self));
|
| 544 |
+
#endif
|
| 545 |
+
return 0;
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
/// dynamic_attr: Allow the GC to clear the dictionary.
|
| 549 |
+
extern "C" inline int pybind11_clear(PyObject *self) {
|
| 550 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
| 551 |
+
PyObject_ClearManagedDict(self);
|
| 552 |
+
#else
|
| 553 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
| 554 |
+
Py_CLEAR(dict);
|
| 555 |
+
#endif
|
| 556 |
+
return 0;
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
/// Give instances of this type a `__dict__` and opt into garbage collection.
|
| 560 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
|
| 561 |
+
auto *type = &heap_type->ht_type;
|
| 562 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
| 563 |
+
#if PY_VERSION_HEX < 0x030B0000
|
| 564 |
+
type->tp_dictoffset = type->tp_basicsize; // place dict at the end
|
| 565 |
+
type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
|
| 566 |
+
#else
|
| 567 |
+
type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
|
| 568 |
+
#endif
|
| 569 |
+
type->tp_traverse = pybind11_traverse;
|
| 570 |
+
type->tp_clear = pybind11_clear;
|
| 571 |
+
|
| 572 |
+
static PyGetSetDef getset[]
|
| 573 |
+
= {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
|
| 574 |
+
{nullptr, nullptr, nullptr, nullptr, nullptr}};
|
| 575 |
+
type->tp_getset = getset;
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// buffer_protocol: Fill in the view as specified by flags.
|
| 579 |
+
extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
|
| 580 |
+
// Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
|
| 581 |
+
type_info *tinfo = nullptr;
|
| 582 |
+
for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
|
| 583 |
+
tinfo = get_type_info((PyTypeObject *) type.ptr());
|
| 584 |
+
if (tinfo && tinfo->get_buffer) {
|
| 585 |
+
break;
|
| 586 |
+
}
|
| 587 |
+
}
|
| 588 |
+
if (view == nullptr || !tinfo || !tinfo->get_buffer) {
|
| 589 |
+
if (view) {
|
| 590 |
+
view->obj = nullptr;
|
| 591 |
+
}
|
| 592 |
+
set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
|
| 593 |
+
return -1;
|
| 594 |
+
}
|
| 595 |
+
std::memset(view, 0, sizeof(Py_buffer));
|
| 596 |
+
buffer_info *info = nullptr;
|
| 597 |
+
try {
|
| 598 |
+
info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
|
| 599 |
+
} catch (...) {
|
| 600 |
+
try_translate_exceptions();
|
| 601 |
+
raise_from(PyExc_BufferError, "Error getting buffer");
|
| 602 |
+
return -1;
|
| 603 |
+
}
|
| 604 |
+
if (info == nullptr) {
|
| 605 |
+
pybind11_fail("FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr.");
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
|
| 609 |
+
delete info;
|
| 610 |
+
// view->obj = nullptr; // Was just memset to 0, so not necessary
|
| 611 |
+
set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
|
| 612 |
+
return -1;
|
| 613 |
+
}
|
| 614 |
+
view->obj = obj;
|
| 615 |
+
view->ndim = 1;
|
| 616 |
+
view->internal = info;
|
| 617 |
+
view->buf = info->ptr;
|
| 618 |
+
view->itemsize = info->itemsize;
|
| 619 |
+
view->len = view->itemsize;
|
| 620 |
+
for (auto s : info->shape) {
|
| 621 |
+
view->len *= s;
|
| 622 |
+
}
|
| 623 |
+
view->readonly = static_cast<int>(info->readonly);
|
| 624 |
+
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
|
| 625 |
+
view->format = const_cast<char *>(info->format.c_str());
|
| 626 |
+
}
|
| 627 |
+
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
|
| 628 |
+
view->ndim = (int) info->ndim;
|
| 629 |
+
view->strides = info->strides.data();
|
| 630 |
+
view->shape = info->shape.data();
|
| 631 |
+
}
|
| 632 |
+
Py_INCREF(view->obj);
|
| 633 |
+
return 0;
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
/// buffer_protocol: Release the resources of the buffer.
|
| 637 |
+
extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
|
| 638 |
+
delete (buffer_info *) view->internal;
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
/// Give this type a buffer interface.
|
| 642 |
+
inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
|
| 643 |
+
heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
|
| 644 |
+
|
| 645 |
+
heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
|
| 646 |
+
heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
/** Create a brand new Python type according to the `type_record` specification.
|
| 650 |
+
Return value: New reference. */
|
| 651 |
+
inline PyObject *make_new_python_type(const type_record &rec) {
|
| 652 |
+
auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
|
| 653 |
+
|
| 654 |
+
auto qualname = name;
|
| 655 |
+
if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
|
| 656 |
+
qualname = reinterpret_steal<object>(
|
| 657 |
+
PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
object module_;
|
| 661 |
+
if (rec.scope) {
|
| 662 |
+
if (hasattr(rec.scope, "__module__")) {
|
| 663 |
+
module_ = rec.scope.attr("__module__");
|
| 664 |
+
} else if (hasattr(rec.scope, "__name__")) {
|
| 665 |
+
module_ = rec.scope.attr("__name__");
|
| 666 |
+
}
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
const auto *full_name = c_str(
|
| 670 |
+
#if !defined(PYPY_VERSION)
|
| 671 |
+
module_ ? str(module_).cast<std::string>() + "." + rec.name :
|
| 672 |
+
#endif
|
| 673 |
+
rec.name);
|
| 674 |
+
|
| 675 |
+
char *tp_doc = nullptr;
|
| 676 |
+
if (rec.doc && options::show_user_defined_docstrings()) {
|
| 677 |
+
/* Allocate memory for docstring (Python will free this later on) */
|
| 678 |
+
size_t size = std::strlen(rec.doc) + 1;
|
| 679 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
| 680 |
+
tp_doc = (char *) PyMem_MALLOC(size);
|
| 681 |
+
#else
|
| 682 |
+
tp_doc = (char *) PyObject_MALLOC(size);
|
| 683 |
+
#endif
|
| 684 |
+
std::memcpy((void *) tp_doc, rec.doc, size);
|
| 685 |
+
}
|
| 686 |
+
|
| 687 |
+
auto &internals = get_internals();
|
| 688 |
+
auto bases = tuple(rec.bases);
|
| 689 |
+
auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
|
| 690 |
+
|
| 691 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 692 |
+
issue no Python C API calls which could potentially invoke the
|
| 693 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 694 |
+
turn find the newly constructed type in an invalid state) */
|
| 695 |
+
auto *metaclass
|
| 696 |
+
= rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
|
| 697 |
+
|
| 698 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
| 699 |
+
if (!heap_type) {
|
| 700 |
+
pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
heap_type->ht_name = name.release().ptr();
|
| 704 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 705 |
+
heap_type->ht_qualname = qualname.inc_ref().ptr();
|
| 706 |
+
#endif
|
| 707 |
+
|
| 708 |
+
auto *type = &heap_type->ht_type;
|
| 709 |
+
type->tp_name = full_name;
|
| 710 |
+
type->tp_doc = tp_doc;
|
| 711 |
+
type->tp_base = type_incref((PyTypeObject *) base);
|
| 712 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
| 713 |
+
if (!bases.empty()) {
|
| 714 |
+
type->tp_bases = bases.release().ptr();
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
/* Don't inherit base __init__ */
|
| 718 |
+
type->tp_init = pybind11_object_init;
|
| 719 |
+
|
| 720 |
+
/* Supported protocols */
|
| 721 |
+
type->tp_as_number = &heap_type->as_number;
|
| 722 |
+
type->tp_as_sequence = &heap_type->as_sequence;
|
| 723 |
+
type->tp_as_mapping = &heap_type->as_mapping;
|
| 724 |
+
type->tp_as_async = &heap_type->as_async;
|
| 725 |
+
|
| 726 |
+
/* Flags */
|
| 727 |
+
type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
|
| 728 |
+
if (!rec.is_final) {
|
| 729 |
+
type->tp_flags |= Py_TPFLAGS_BASETYPE;
|
| 730 |
+
}
|
| 731 |
+
|
| 732 |
+
if (rec.dynamic_attr) {
|
| 733 |
+
enable_dynamic_attributes(heap_type);
|
| 734 |
+
}
|
| 735 |
+
|
| 736 |
+
if (rec.buffer_protocol) {
|
| 737 |
+
enable_buffer_protocol(heap_type);
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
if (rec.custom_type_setup_callback) {
|
| 741 |
+
rec.custom_type_setup_callback(heap_type);
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
if (PyType_Ready(type) < 0) {
|
| 745 |
+
pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
| 749 |
+
|
| 750 |
+
/* Register type with the parent scope */
|
| 751 |
+
if (rec.scope) {
|
| 752 |
+
setattr(rec.scope, rec.name, (PyObject *) type);
|
| 753 |
+
} else {
|
| 754 |
+
Py_INCREF(type); // Keep it alive forever (reference leak)
|
| 755 |
+
}
|
| 756 |
+
|
| 757 |
+
if (module_) { // Needed by pydoc
|
| 758 |
+
setattr((PyObject *) type, "__module__", module_);
|
| 759 |
+
}
|
| 760 |
+
|
| 761 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
|
| 762 |
+
|
| 763 |
+
return (PyObject *) type;
|
| 764 |
+
}
|
| 765 |
+
|
| 766 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 767 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
shared/package-files/06/0640d1e3e3a6c9d3f0c5df43e38de780e38904adbf87f9b1e8608366cf552414/special_psi.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/special_psi_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::special_psi(Tensor self) -> Tensor
|
| 27 |
+
inline at::Tensor special_psi(const at::Tensor & self) {
|
| 28 |
+
return at::_ops::special_psi::call(self);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & special_psi_out(at::Tensor & out, const at::Tensor & self) {
|
| 33 |
+
return at::_ops::special_psi_out::call(self, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & special_psi_outf(const at::Tensor & self, at::Tensor & out) {
|
| 37 |
+
return at::_ops::special_psi_out::call(self, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/06/0643726a604b3902e52b2ea607805274f46300a3f5821679c5cc900e452cfbfb/_conversions.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch._prims_common as utils
|
| 4 |
+
|
| 5 |
+
# Utilities should come BEFORE this import
|
| 6 |
+
from torch._decomp import register_decomposition
|
| 7 |
+
from torch._prims_common import TensorLikeType
|
| 8 |
+
from torch._prims_common.wrappers import out_wrapper
|
| 9 |
+
from torch._refs import _broadcast_shapes
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Data conversion references.
|
| 13 |
+
#
|
| 14 |
+
# Note: this module breaks the usual _refs to torch naming scheme where
|
| 15 |
+
# _refs.foo.bar is a ref for torch.foo.bar. The following definitions are not
|
| 16 |
+
# part of _refs/__init__.py to avoid name clashes with Python builtin types
|
| 17 |
+
# (like int).
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
# dtypes
|
| 21 |
+
"bfloat16",
|
| 22 |
+
"bool",
|
| 23 |
+
"byte",
|
| 24 |
+
"cdouble",
|
| 25 |
+
"cfloat",
|
| 26 |
+
"chalf",
|
| 27 |
+
"char",
|
| 28 |
+
"double",
|
| 29 |
+
"float",
|
| 30 |
+
"half",
|
| 31 |
+
"int",
|
| 32 |
+
"long",
|
| 33 |
+
"short",
|
| 34 |
+
# misc
|
| 35 |
+
"complex",
|
| 36 |
+
"polar",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _make_conversion_method(name: str, dtype: torch.dtype):
|
| 41 |
+
def fn(
|
| 42 |
+
self: TensorLikeType, memory_format: torch.memory_format = torch.preserve_format
|
| 43 |
+
) -> TensorLikeType:
|
| 44 |
+
return self.to(dtype, memory_format=memory_format) # type: ignore[call-overload]
|
| 45 |
+
|
| 46 |
+
fn.__name__ = name
|
| 47 |
+
return fn
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
bfloat16 = _make_conversion_method("bfloat16", torch.bfloat16)
|
| 51 |
+
|
| 52 |
+
bool = _make_conversion_method("bool", torch.bool)
|
| 53 |
+
|
| 54 |
+
byte = _make_conversion_method("byte", torch.uint8)
|
| 55 |
+
|
| 56 |
+
cdouble = _make_conversion_method("cdouble", torch.cdouble)
|
| 57 |
+
|
| 58 |
+
cfloat = _make_conversion_method("cfloat", torch.cfloat)
|
| 59 |
+
|
| 60 |
+
chalf = _make_conversion_method("chalf", torch.complex32)
|
| 61 |
+
|
| 62 |
+
char = _make_conversion_method("char", torch.int8)
|
| 63 |
+
|
| 64 |
+
double = _make_conversion_method("double", torch.double)
|
| 65 |
+
|
| 66 |
+
float = _make_conversion_method("float", torch.float)
|
| 67 |
+
|
| 68 |
+
half = _make_conversion_method("half", torch.half)
|
| 69 |
+
|
| 70 |
+
int = _make_conversion_method("int", torch.int)
|
| 71 |
+
|
| 72 |
+
long = _make_conversion_method("long", torch.long)
|
| 73 |
+
|
| 74 |
+
short = _make_conversion_method("short", torch.short)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@register_decomposition(torch._ops.ops.aten.complex)
|
| 78 |
+
# Note: complex has type promotion tests disabled due to different semantics.
|
| 79 |
+
# exact_dtype is for compat with complex_check_dtype from core.
|
| 80 |
+
@out_wrapper(exact_dtype=True)
|
| 81 |
+
def complex(real: TensorLikeType, imag: TensorLikeType) -> TensorLikeType:
|
| 82 |
+
allowed_dtypes = (torch.float32, torch.float64, torch.float16)
|
| 83 |
+
torch._check(
|
| 84 |
+
real.dtype in allowed_dtypes and imag.dtype in allowed_dtypes,
|
| 85 |
+
lambda: (
|
| 86 |
+
f"Expected both inputs to be Half, Float or Double tensors but got "
|
| 87 |
+
f"{real.dtype} and {imag.dtype}"
|
| 88 |
+
),
|
| 89 |
+
)
|
| 90 |
+
torch._check(
|
| 91 |
+
real.dtype == imag.dtype,
|
| 92 |
+
lambda: (
|
| 93 |
+
f"Expected object of scalar type {real.dtype} but got "
|
| 94 |
+
f"scalar type {imag.dtype} for second argument"
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
result_dtype = utils.corresponding_complex_dtype(real.dtype) # type: ignore[arg-type]
|
| 98 |
+
common_shape = _broadcast_shapes(real.shape, imag.shape)
|
| 99 |
+
result = real.new_empty(
|
| 100 |
+
common_shape,
|
| 101 |
+
dtype=result_dtype,
|
| 102 |
+
layout=real.layout,
|
| 103 |
+
device=real.device,
|
| 104 |
+
# pin_memory=real.is_pinned(), # NYI
|
| 105 |
+
)
|
| 106 |
+
result.real = real
|
| 107 |
+
result.imag = imag
|
| 108 |
+
return result
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@register_decomposition(torch._ops.ops.aten.polar)
|
| 112 |
+
# Note: polar has type promotion tests disabled due to different semantics.
|
| 113 |
+
# exact_dtype is for compat with complex_check_dtype from core.
|
| 114 |
+
@out_wrapper(exact_dtype=True)
|
| 115 |
+
def polar(abs: TensorLikeType, angle: TensorLikeType) -> TensorLikeType:
|
| 116 |
+
result = torch.complex(abs, angle)
|
| 117 |
+
result.real = abs * torch.cos(angle)
|
| 118 |
+
result.imag = abs * torch.sin(angle)
|
| 119 |
+
return result
|
shared/package-files/06/064806f0fa6a1892d858494e44382d2c9cf27e2b986a7140610f9bbd331692e8/hts_prog_cc_warnings.m4
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
dnl Enables a reasonable set of warnings for the C compiler.
|
| 7 |
+
dnl Optionally, if the first argument is nonempty, turns on flags which
|
| 8 |
+
dnl enforce and/or enable proper ANSI C if such are known with the
|
| 9 |
+
dnl compiler used.
|
| 10 |
+
dnl
|
| 11 |
+
dnl Currently this macro knows about GCC, Solaris C compiler, Digital
|
| 12 |
+
dnl Unix C compiler, C for AIX Compiler, HP-UX C compiler, IRIX C
|
| 13 |
+
dnl compiler, NEC SX-5 (Super-UX 10) C compiler, and Cray J90 (Unicos
|
| 14 |
+
dnl 10.0.0.8) C compiler.
|
| 15 |
+
dnl
|
| 16 |
+
dnl @category C
|
| 17 |
+
dnl @author Ville Laurikari <vl@iki.fi>
|
| 18 |
+
dnl Updated by Rob Davies <rmd@sanger.ac.uk> for HTSlib
|
| 19 |
+
dnl @license AllPermissive
|
| 20 |
+
dnl Copying and distribution of this file, with or without modification,
|
| 21 |
+
dnl are permitted in any medium without royalty provided the copyright notice
|
| 22 |
+
dnl and this notice are preserved. Users of this software should generally
|
| 23 |
+
dnl follow the principles of the MIT License including its disclaimer.
|
| 24 |
+
dnl Original Copyright (c) Ville Laurikari 2002
|
| 25 |
+
dnl Modifications Copyright (c) Genome Research Limited 2015,2017
|
| 26 |
+
|
| 27 |
+
AC_DEFUN([HTS_PROG_CC_WARNINGS], [
|
| 28 |
+
AC_ARG_ENABLE([warnings],
|
| 29 |
+
[AS_HELP_STRING([--disable-warnings], [turn off compiler warnings])],
|
| 30 |
+
[],
|
| 31 |
+
[enable_warnings=yes])
|
| 32 |
+
|
| 33 |
+
AS_IF([test "x$enable_warnings" != xno],[
|
| 34 |
+
AC_REQUIRE([AC_PROG_GREP])
|
| 35 |
+
|
| 36 |
+
ansi="$1"
|
| 37 |
+
AS_IF([test "x$ansi" = "x"],
|
| 38 |
+
[msg="for C compiler warning flags"],
|
| 39 |
+
[msg="for C compiler warning and ANSI conformance flags"])
|
| 40 |
+
|
| 41 |
+
AC_MSG_CHECKING($msg)
|
| 42 |
+
AC_CACHE_VAL(hts_cv_prog_cc_warnings, [dnl
|
| 43 |
+
hts_cv_prog_cc_warnings=""
|
| 44 |
+
AS_IF([test "x$CC" != "x"],[
|
| 45 |
+
cat > conftest.c <<EOF
|
| 46 |
+
int main(int argc, char **argv) { return 0; }
|
| 47 |
+
EOF
|
| 48 |
+
|
| 49 |
+
dnl Most compilers print some kind of a version string with some command
|
| 50 |
+
dnl line options (often "-V"). The version string should be checked
|
| 51 |
+
dnl before doing a test compilation run with compiler-specific flags.
|
| 52 |
+
dnl This is because some compilers (like the Cray compiler) only
|
| 53 |
+
dnl produce a warning message for unknown flags instead of returning
|
| 54 |
+
dnl an error, resulting in a false positive. Also, compilers may do
|
| 55 |
+
dnl erratic things when invoked with flags meant for a different
|
| 56 |
+
dnl compiler.
|
| 57 |
+
|
| 58 |
+
dnl We attempt to strip out any flags that are already on CFLAGS.
|
| 59 |
+
dnl If an option needs more than one word (e.g. see Cray below) then
|
| 60 |
+
dnl they should be separated by hash signs (#), which will be converted
|
| 61 |
+
dnl to spaces before comparing and possibly adding to CFLAGS.
|
| 62 |
+
dnl This separator will need to be changed if a new compiler ever needs
|
| 63 |
+
dnl an option that includes a hash sign...
|
| 64 |
+
|
| 65 |
+
# Tests for flags to enable C compiler warnings
|
| 66 |
+
# GCC compatible
|
| 67 |
+
AS_IF([test "x$GCC" = "xyes" &&
|
| 68 |
+
"$CC" -c -Wall conftest.c > /dev/null 2>&1 &&
|
| 69 |
+
test -f conftest.o],[dnl
|
| 70 |
+
AS_IF([test "x$ansi" = "x"],
|
| 71 |
+
[hts_cv_prog_cc_warnings="-Wall"],
|
| 72 |
+
[hts_cv_prog_cc_warnings="-Wall -ansi -pedantic"])
|
| 73 |
+
],
|
| 74 |
+
# Sun Studio or Solaris C compiler
|
| 75 |
+
["$CC" -V 2>&1 | $GREP -i -E "WorkShop|Sun C" > /dev/null 2>&1 &&
|
| 76 |
+
"$CC" -c -v -Xc conftest.c > /dev/null 2>&1 &&
|
| 77 |
+
test -f conftest.o],[dnl
|
| 78 |
+
AS_IF([test "x$ansi" = "x"],
|
| 79 |
+
[hts_cv_prog_cc_warnings="-v"],
|
| 80 |
+
[hts_cv_prog_cc_warnings="-v -Xc"])
|
| 81 |
+
],
|
| 82 |
+
# Digital Unix C compiler
|
| 83 |
+
["$CC" -V 2>&1 | $GREP -i "Digital UNIX Compiler" > /dev/null 2>&1 &&
|
| 84 |
+
"$CC" -c -verbose -w0 -warnprotos -std1 conftest.c > /dev/null 2>&1 &&
|
| 85 |
+
test -f conftest.o], [dnl
|
| 86 |
+
AS_IF([test "x$ansi" = "x"],
|
| 87 |
+
[hts_cv_prog_cc_warnings="-verbose -w0 -warnprotos"],
|
| 88 |
+
[hts_cv_prog_cc_warnings="-verbose -w0 -warnprotos -std1"])
|
| 89 |
+
],
|
| 90 |
+
# C for AIX Compiler
|
| 91 |
+
["$CC" 2>&1 | $GREP -i "C for AIX Compiler" > /dev/null 2>&1 &&
|
| 92 |
+
"$CC" -c -qlanglvl=ansi -qinfo=all conftest.c > /dev/null 2>&1 &&
|
| 93 |
+
test -f conftest.o],[dnl
|
| 94 |
+
AS_IF([test "x$ansi" = "x"],
|
| 95 |
+
[hts_cv_prog_cc_warnings="-qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd"],
|
| 96 |
+
[hts_cv_prog_cc_warnings="-qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd -qlanglvl=ansi"])
|
| 97 |
+
],
|
| 98 |
+
# IRIX C compiler
|
| 99 |
+
["$CC" -version 2>&1 | $GREP -i "MIPSpro Compilers" > /dev/null 2>&1 &&
|
| 100 |
+
"$CC" -c -fullwarn -ansi -ansiE conftest.c > /dev/null 2>&1 &&
|
| 101 |
+
test -f conftest.o],[dnl
|
| 102 |
+
AS_IF([test "x$ansi" = "x"],
|
| 103 |
+
[hts_cv_prog_cc_warnings="-fullwarn"],
|
| 104 |
+
[hts_cv_prog_cc_warnings="-fullwarn -ansi -ansiE"])
|
| 105 |
+
],
|
| 106 |
+
# HP-UX C compiler
|
| 107 |
+
[what "$CC" 2>&1 | $GREP -i "HP C Compiler" > /dev/null 2>&1 &&
|
| 108 |
+
"$CC" -c -Aa +w1 conftest.c > /dev/null 2>&1 &&
|
| 109 |
+
test -f conftest.o],[dnl
|
| 110 |
+
AS_IF([test "x$ansi" = "x"],
|
| 111 |
+
[hts_cv_prog_cc_warnings="+w1"],
|
| 112 |
+
[hts_cv_prog_cc_warnings="+w1 -Aa"])
|
| 113 |
+
],
|
| 114 |
+
# The NEC SX series (Super-UX 10) C compiler
|
| 115 |
+
["$CC" -V 2>&1 | $GREP "/SX" > /dev/null 2>&1 &&
|
| 116 |
+
"$CC" -c -pvctl[,]fullmsg -Xc conftest.c > /dev/null 2>&1 &&
|
| 117 |
+
test -f conftest.o],[
|
| 118 |
+
AS_IF([test "x$ansi" = "x"],
|
| 119 |
+
[hts_cv_prog_cc_warnings="-pvctl[,]fullmsg"],
|
| 120 |
+
[hts_cv_prog_cc_warnings="-pvctl[,]fullmsg -Xc"])
|
| 121 |
+
],
|
| 122 |
+
# The Cray C compiler (Unicos)
|
| 123 |
+
["$CC" -V 2>&1 | $GREP -i "Cray" > /dev/null 2>&1 &&
|
| 124 |
+
"$CC" -c -h msglevel_2 conftest.c > /dev/null 2>&1 &&
|
| 125 |
+
test -f conftest.o],[dnl
|
| 126 |
+
AS_IF([test "x$ansi" = "x"],
|
| 127 |
+
[hts_cv_prog_cc_warnings="-h#msglevel_2"],
|
| 128 |
+
[hts_cv_prog_cc_warnings="-h#msglevel_2,conform"])
|
| 129 |
+
],
|
| 130 |
+
# The Tiny C Compiler
|
| 131 |
+
["$CC" -v 2>&1 | $GREP "tcc version" > /dev/null &&
|
| 132 |
+
"$CC" -Wall -c conftest.c > /dev/null 2>&1 &&
|
| 133 |
+
test -f conftest.o],[dnl
|
| 134 |
+
hts_cv_prog_cc_warnings="-Wall"
|
| 135 |
+
])
|
| 136 |
+
rm -f conftest.*
|
| 137 |
+
])
|
| 138 |
+
])
|
| 139 |
+
|
| 140 |
+
AS_IF([test "x$hts_cv_prog_cc_warnings" != "x"],[
|
| 141 |
+
dnl Print result, with underscores as spaces
|
| 142 |
+
ac_arg_result=`echo "$hts_cv_prog_cc_warnings" | tr '#' ' '`
|
| 143 |
+
AC_MSG_RESULT($ac_arg_result)
|
| 144 |
+
|
| 145 |
+
dnl Add options to CFLAGS only if they are not already present
|
| 146 |
+
ac_arg_needed=""
|
| 147 |
+
for ac_arg in $hts_cv_prog_cc_warnings
|
| 148 |
+
do
|
| 149 |
+
ac_arg_sp=`echo "$ac_arg" | tr '#' ' '`
|
| 150 |
+
AS_CASE([" $CFLAGS "],
|
| 151 |
+
[*" $ac_arg_sp "*], [],
|
| 152 |
+
[ac_arg_needed="$ac_arg_all $ac_arg_sp"])
|
| 153 |
+
done
|
| 154 |
+
CFLAGS="$ac_arg_needed $CFLAGS"],[dnl
|
| 155 |
+
AC_MSG_RESULT(unknown)
|
| 156 |
+
])
|
| 157 |
+
])
|
| 158 |
+
])dnl HTS_PROG_CC_WARNINGS
|
| 159 |
+
|
| 160 |
+
# SYNOPSIS
|
| 161 |
+
#
|
| 162 |
+
# HTS_PROG_CC_WERROR(FLAGS_VAR)
|
| 163 |
+
#
|
| 164 |
+
# Set FLAGS_VAR to the flags needed to make the C compiler treat warnings
|
| 165 |
+
# as errors.
|
| 166 |
+
|
| 167 |
+
AC_DEFUN([HTS_PROG_CC_WERROR], [
|
| 168 |
+
AC_ARG_ENABLE([werror],
|
| 169 |
+
[AS_HELP_STRING([--enable-werror], [change warnings into errors, where supported])],
|
| 170 |
+
[],
|
| 171 |
+
[enable_werror=no])
|
| 172 |
+
|
| 173 |
+
AS_IF([test "x$enable_werror" != xno],[
|
| 174 |
+
AC_MSG_CHECKING([for C compiler flags to error on warnings])
|
| 175 |
+
AC_CACHE_VAL(hts_cv_prog_cc_werror, [dnl
|
| 176 |
+
hts_cv_prog_cc_werror=""
|
| 177 |
+
AS_IF([test "x$CC" != "x"],[
|
| 178 |
+
cat > conftest.c <<EOF
|
| 179 |
+
int main(int argc, char **argv) { return 0; }
|
| 180 |
+
EOF
|
| 181 |
+
|
| 182 |
+
AS_IF(dnl
|
| 183 |
+
# Tests for flags to make the C compiler treat warnings as errors
|
| 184 |
+
# GCC compatible
|
| 185 |
+
[test "x$GCC" = "xyes" &&
|
| 186 |
+
"$CC" -c -Werror conftest.c > /dev/null 2>&1 &&
|
| 187 |
+
test -f conftest.o],[hts_cv_prog_cc_werror="-Werror"],
|
| 188 |
+
# Sun Studio or Solaris C compiler
|
| 189 |
+
["$CC" -V 2>&1 | $GREP -i -E "WorkShop|Sun C" > /dev/null 2>&1 &&
|
| 190 |
+
"$CC" -c -errwarn=%all conftest.c > /dev/null 2>&1 &&
|
| 191 |
+
test -f conftest.o],[hts_cv_prog_cc_werror="-errwarn=%all"],
|
| 192 |
+
# The Tiny C Compiler
|
| 193 |
+
["$CC" -v 2>&1 | $GREP "tcc version" > /dev/null &&
|
| 194 |
+
"$CC" -Wall -c conftest.c > /dev/null 2>&1 &&
|
| 195 |
+
test -f conftest.o],[hts_cv_prog_cc_werror="-Werror"]
|
| 196 |
+
dnl TODO: Add more compilers
|
| 197 |
+
)
|
| 198 |
+
rm -f conftest.*
|
| 199 |
+
])
|
| 200 |
+
])
|
| 201 |
+
AS_IF([test "x$hts_cv_prog_cc_werror" != x],[
|
| 202 |
+
AC_MSG_RESULT($hts_cv_prog_cc_werror)
|
| 203 |
+
AS_IF([test "x$1" != x],[eval AS_TR_SH([$1])="$hts_cv_prog_cc_werror"])
|
| 204 |
+
],[dnl
|
| 205 |
+
AC_MSG_RESULT(unknown)
|
| 206 |
+
])
|
| 207 |
+
])
|
| 208 |
+
])dnl HTS_PROG_CC_WERROR
|
shared/package-files/06/0656ef4ad12ca223866c0f39a4ff61c3cb9f657aea8b18d38c6683ea6b0826e1/test_append.py
ADDED
|
@@ -0,0 +1,986 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
from datetime import timedelta
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from pandas._libs.tslibs import Timestamp
|
| 9 |
+
import pandas.util._test_decorators as td
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from pandas import (
|
| 13 |
+
DataFrame,
|
| 14 |
+
Index,
|
| 15 |
+
Series,
|
| 16 |
+
_testing as tm,
|
| 17 |
+
concat,
|
| 18 |
+
date_range,
|
| 19 |
+
read_hdf,
|
| 20 |
+
)
|
| 21 |
+
from pandas.tests.io.pytables.common import (
|
| 22 |
+
_maybe_remove,
|
| 23 |
+
ensure_clean_store,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
pytestmark = pytest.mark.single_cpu
|
| 27 |
+
|
| 28 |
+
tables = pytest.importorskip("tables")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@pytest.mark.filterwarnings("ignore::tables.NaturalNameWarning")
|
| 32 |
+
def test_append(setup_path):
|
| 33 |
+
with ensure_clean_store(setup_path) as store:
|
| 34 |
+
# this is allowed by almost always don't want to do it
|
| 35 |
+
# tables.NaturalNameWarning):
|
| 36 |
+
df = DataFrame(
|
| 37 |
+
np.random.default_rng(2).standard_normal((20, 4)),
|
| 38 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 39 |
+
index=date_range("2000-01-01", periods=20, freq="B"),
|
| 40 |
+
)
|
| 41 |
+
_maybe_remove(store, "df1")
|
| 42 |
+
store.append("df1", df[:10])
|
| 43 |
+
store.append("df1", df[10:])
|
| 44 |
+
tm.assert_frame_equal(store["df1"], df)
|
| 45 |
+
|
| 46 |
+
_maybe_remove(store, "df2")
|
| 47 |
+
store.put("df2", df[:10], format="table")
|
| 48 |
+
store.append("df2", df[10:])
|
| 49 |
+
tm.assert_frame_equal(store["df2"], df)
|
| 50 |
+
|
| 51 |
+
_maybe_remove(store, "df3")
|
| 52 |
+
store.append("/df3", df[:10])
|
| 53 |
+
store.append("/df3", df[10:])
|
| 54 |
+
tm.assert_frame_equal(store["df3"], df)
|
| 55 |
+
|
| 56 |
+
# this is allowed by almost always don't want to do it
|
| 57 |
+
# tables.NaturalNameWarning
|
| 58 |
+
_maybe_remove(store, "/df3 foo")
|
| 59 |
+
store.append("/df3 foo", df[:10])
|
| 60 |
+
store.append("/df3 foo", df[10:])
|
| 61 |
+
tm.assert_frame_equal(store["df3 foo"], df)
|
| 62 |
+
|
| 63 |
+
# dtype issues - mizxed type in a single object column
|
| 64 |
+
df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]])
|
| 65 |
+
df["mixed_column"] = "testing"
|
| 66 |
+
df.loc[2, "mixed_column"] = np.nan
|
| 67 |
+
_maybe_remove(store, "df")
|
| 68 |
+
store.append("df", df)
|
| 69 |
+
tm.assert_frame_equal(store["df"], df)
|
| 70 |
+
|
| 71 |
+
# uints - test storage of uints
|
| 72 |
+
uint_data = DataFrame(
|
| 73 |
+
{
|
| 74 |
+
"u08": Series(
|
| 75 |
+
np.random.default_rng(2).integers(0, high=255, size=5),
|
| 76 |
+
dtype=np.uint8,
|
| 77 |
+
),
|
| 78 |
+
"u16": Series(
|
| 79 |
+
np.random.default_rng(2).integers(0, high=65535, size=5),
|
| 80 |
+
dtype=np.uint16,
|
| 81 |
+
),
|
| 82 |
+
"u32": Series(
|
| 83 |
+
np.random.default_rng(2).integers(0, high=2**30, size=5),
|
| 84 |
+
dtype=np.uint32,
|
| 85 |
+
),
|
| 86 |
+
"u64": Series(
|
| 87 |
+
[2**58, 2**59, 2**60, 2**61, 2**62],
|
| 88 |
+
dtype=np.uint64,
|
| 89 |
+
),
|
| 90 |
+
},
|
| 91 |
+
index=np.arange(5),
|
| 92 |
+
)
|
| 93 |
+
_maybe_remove(store, "uints")
|
| 94 |
+
store.append("uints", uint_data)
|
| 95 |
+
tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True)
|
| 96 |
+
|
| 97 |
+
# uints - test storage of uints in indexable columns
|
| 98 |
+
_maybe_remove(store, "uints")
|
| 99 |
+
# 64-bit indices not yet supported
|
| 100 |
+
store.append("uints", uint_data, data_columns=["u08", "u16", "u32"])
|
| 101 |
+
tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_append_series(setup_path):
|
| 105 |
+
with ensure_clean_store(setup_path) as store:
|
| 106 |
+
# basic
|
| 107 |
+
ss = Series(range(20), dtype=np.float64, index=[f"i_{i}" for i in range(20)])
|
| 108 |
+
ts = Series(
|
| 109 |
+
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
|
| 110 |
+
)
|
| 111 |
+
ns = Series(np.arange(100))
|
| 112 |
+
|
| 113 |
+
store.append("ss", ss)
|
| 114 |
+
result = store["ss"]
|
| 115 |
+
tm.assert_series_equal(result, ss)
|
| 116 |
+
assert result.name is None
|
| 117 |
+
|
| 118 |
+
store.append("ts", ts)
|
| 119 |
+
result = store["ts"]
|
| 120 |
+
tm.assert_series_equal(result, ts)
|
| 121 |
+
assert result.name is None
|
| 122 |
+
|
| 123 |
+
ns.name = "foo"
|
| 124 |
+
store.append("ns", ns)
|
| 125 |
+
result = store["ns"]
|
| 126 |
+
tm.assert_series_equal(result, ns)
|
| 127 |
+
assert result.name == ns.name
|
| 128 |
+
|
| 129 |
+
# select on the values
|
| 130 |
+
expected = ns[ns > 60]
|
| 131 |
+
result = store.select("ns", "foo>60")
|
| 132 |
+
tm.assert_series_equal(result, expected)
|
| 133 |
+
|
| 134 |
+
# select on the index and values
|
| 135 |
+
expected = ns[(ns > 70) & (ns.index < 90)]
|
| 136 |
+
result = store.select("ns", "foo>70 and index<90")
|
| 137 |
+
tm.assert_series_equal(result, expected, check_index_type=True)
|
| 138 |
+
|
| 139 |
+
# multi-index
|
| 140 |
+
mi = DataFrame(np.random.default_rng(2).standard_normal((5, 1)), columns=["A"])
|
| 141 |
+
mi["B"] = np.arange(len(mi))
|
| 142 |
+
mi["C"] = "foo"
|
| 143 |
+
mi.loc[3:5, "C"] = "bar"
|
| 144 |
+
mi.set_index(["C", "B"], inplace=True)
|
| 145 |
+
s = mi.stack(future_stack=True)
|
| 146 |
+
s.index = s.index.droplevel(2)
|
| 147 |
+
store.append("mi", s)
|
| 148 |
+
tm.assert_series_equal(store["mi"], s, check_index_type=True)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_append_some_nans(setup_path):
|
| 152 |
+
with ensure_clean_store(setup_path) as store:
|
| 153 |
+
df = DataFrame(
|
| 154 |
+
{
|
| 155 |
+
"A": Series(np.random.default_rng(2).standard_normal(20)).astype(
|
| 156 |
+
"int32"
|
| 157 |
+
),
|
| 158 |
+
"A1": np.random.default_rng(2).standard_normal(20),
|
| 159 |
+
"A2": np.random.default_rng(2).standard_normal(20),
|
| 160 |
+
"B": "foo",
|
| 161 |
+
"C": "bar",
|
| 162 |
+
"D": Timestamp("2001-01-01").as_unit("ns"),
|
| 163 |
+
"E": Timestamp("2001-01-02").as_unit("ns"),
|
| 164 |
+
},
|
| 165 |
+
index=np.arange(20),
|
| 166 |
+
)
|
| 167 |
+
# some nans
|
| 168 |
+
_maybe_remove(store, "df1")
|
| 169 |
+
df.loc[0:15, ["A1", "B", "D", "E"]] = np.nan
|
| 170 |
+
store.append("df1", df[:10])
|
| 171 |
+
store.append("df1", df[10:])
|
| 172 |
+
tm.assert_frame_equal(store["df1"], df, check_index_type=True)
|
| 173 |
+
|
| 174 |
+
# first column
|
| 175 |
+
df1 = df.copy()
|
| 176 |
+
df1["A1"] = np.nan
|
| 177 |
+
_maybe_remove(store, "df1")
|
| 178 |
+
store.append("df1", df1[:10])
|
| 179 |
+
store.append("df1", df1[10:])
|
| 180 |
+
tm.assert_frame_equal(store["df1"], df1, check_index_type=True)
|
| 181 |
+
|
| 182 |
+
# 2nd column
|
| 183 |
+
df2 = df.copy()
|
| 184 |
+
df2["A2"] = np.nan
|
| 185 |
+
_maybe_remove(store, "df2")
|
| 186 |
+
store.append("df2", df2[:10])
|
| 187 |
+
store.append("df2", df2[10:])
|
| 188 |
+
tm.assert_frame_equal(store["df2"], df2, check_index_type=True)
|
| 189 |
+
|
| 190 |
+
# datetimes
|
| 191 |
+
df3 = df.copy()
|
| 192 |
+
df3["E"] = np.nan
|
| 193 |
+
_maybe_remove(store, "df3")
|
| 194 |
+
store.append("df3", df3[:10])
|
| 195 |
+
store.append("df3", df3[10:])
|
| 196 |
+
tm.assert_frame_equal(store["df3"], df3, check_index_type=True)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_append_all_nans(setup_path):
|
| 200 |
+
with ensure_clean_store(setup_path) as store:
|
| 201 |
+
df = DataFrame(
|
| 202 |
+
{
|
| 203 |
+
"A1": np.random.default_rng(2).standard_normal(20),
|
| 204 |
+
"A2": np.random.default_rng(2).standard_normal(20),
|
| 205 |
+
},
|
| 206 |
+
index=np.arange(20),
|
| 207 |
+
)
|
| 208 |
+
df.loc[0:15, :] = np.nan
|
| 209 |
+
|
| 210 |
+
# nan some entire rows (dropna=True)
|
| 211 |
+
_maybe_remove(store, "df")
|
| 212 |
+
store.append("df", df[:10], dropna=True)
|
| 213 |
+
store.append("df", df[10:], dropna=True)
|
| 214 |
+
tm.assert_frame_equal(store["df"], df[-4:], check_index_type=True)
|
| 215 |
+
|
| 216 |
+
# nan some entire rows (dropna=False)
|
| 217 |
+
_maybe_remove(store, "df2")
|
| 218 |
+
store.append("df2", df[:10], dropna=False)
|
| 219 |
+
store.append("df2", df[10:], dropna=False)
|
| 220 |
+
tm.assert_frame_equal(store["df2"], df, check_index_type=True)
|
| 221 |
+
|
| 222 |
+
# tests the option io.hdf.dropna_table
|
| 223 |
+
with pd.option_context("io.hdf.dropna_table", False):
|
| 224 |
+
_maybe_remove(store, "df3")
|
| 225 |
+
store.append("df3", df[:10])
|
| 226 |
+
store.append("df3", df[10:])
|
| 227 |
+
tm.assert_frame_equal(store["df3"], df)
|
| 228 |
+
|
| 229 |
+
with pd.option_context("io.hdf.dropna_table", True):
|
| 230 |
+
_maybe_remove(store, "df4")
|
| 231 |
+
store.append("df4", df[:10])
|
| 232 |
+
store.append("df4", df[10:])
|
| 233 |
+
tm.assert_frame_equal(store["df4"], df[-4:])
|
| 234 |
+
|
| 235 |
+
# nan some entire rows (string are still written!)
|
| 236 |
+
df = DataFrame(
|
| 237 |
+
{
|
| 238 |
+
"A1": np.random.default_rng(2).standard_normal(20),
|
| 239 |
+
"A2": np.random.default_rng(2).standard_normal(20),
|
| 240 |
+
"B": "foo",
|
| 241 |
+
"C": "bar",
|
| 242 |
+
},
|
| 243 |
+
index=np.arange(20),
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
df.loc[0:15, :] = np.nan
|
| 247 |
+
|
| 248 |
+
_maybe_remove(store, "df")
|
| 249 |
+
store.append("df", df[:10], dropna=True)
|
| 250 |
+
store.append("df", df[10:], dropna=True)
|
| 251 |
+
tm.assert_frame_equal(store["df"], df, check_index_type=True)
|
| 252 |
+
|
| 253 |
+
_maybe_remove(store, "df2")
|
| 254 |
+
store.append("df2", df[:10], dropna=False)
|
| 255 |
+
store.append("df2", df[10:], dropna=False)
|
| 256 |
+
tm.assert_frame_equal(store["df2"], df, check_index_type=True)
|
| 257 |
+
|
| 258 |
+
# nan some entire rows (but since we have dates they are still
|
| 259 |
+
# written!)
|
| 260 |
+
df = DataFrame(
|
| 261 |
+
{
|
| 262 |
+
"A1": np.random.default_rng(2).standard_normal(20),
|
| 263 |
+
"A2": np.random.default_rng(2).standard_normal(20),
|
| 264 |
+
"B": "foo",
|
| 265 |
+
"C": "bar",
|
| 266 |
+
"D": Timestamp("2001-01-01").as_unit("ns"),
|
| 267 |
+
"E": Timestamp("2001-01-02").as_unit("ns"),
|
| 268 |
+
},
|
| 269 |
+
index=np.arange(20),
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
df.loc[0:15, :] = np.nan
|
| 273 |
+
|
| 274 |
+
_maybe_remove(store, "df")
|
| 275 |
+
store.append("df", df[:10], dropna=True)
|
| 276 |
+
store.append("df", df[10:], dropna=True)
|
| 277 |
+
tm.assert_frame_equal(store["df"], df, check_index_type=True)
|
| 278 |
+
|
| 279 |
+
_maybe_remove(store, "df2")
|
| 280 |
+
store.append("df2", df[:10], dropna=False)
|
| 281 |
+
store.append("df2", df[10:], dropna=False)
|
| 282 |
+
tm.assert_frame_equal(store["df2"], df, check_index_type=True)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_append_frame_column_oriented(setup_path):
|
| 286 |
+
with ensure_clean_store(setup_path) as store:
|
| 287 |
+
# column oriented
|
| 288 |
+
df = DataFrame(
|
| 289 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 290 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 291 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 292 |
+
)
|
| 293 |
+
df.index = df.index._with_freq(None) # freq doesn't round-trip
|
| 294 |
+
|
| 295 |
+
_maybe_remove(store, "df1")
|
| 296 |
+
store.append("df1", df.iloc[:, :2], axes=["columns"])
|
| 297 |
+
store.append("df1", df.iloc[:, 2:])
|
| 298 |
+
tm.assert_frame_equal(store["df1"], df)
|
| 299 |
+
|
| 300 |
+
result = store.select("df1", "columns=A")
|
| 301 |
+
expected = df.reindex(columns=["A"])
|
| 302 |
+
tm.assert_frame_equal(expected, result)
|
| 303 |
+
|
| 304 |
+
# selection on the non-indexable
|
| 305 |
+
result = store.select("df1", ("columns=A", "index=df.index[0:4]"))
|
| 306 |
+
expected = df.reindex(columns=["A"], index=df.index[0:4])
|
| 307 |
+
tm.assert_frame_equal(expected, result)
|
| 308 |
+
|
| 309 |
+
# this isn't supported
|
| 310 |
+
msg = re.escape(
|
| 311 |
+
"passing a filterable condition to a non-table indexer "
|
| 312 |
+
"[Filter: Not Initialized]"
|
| 313 |
+
)
|
| 314 |
+
with pytest.raises(TypeError, match=msg):
|
| 315 |
+
store.select("df1", "columns=A and index>df.index[4]")
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def test_append_with_different_block_ordering(setup_path):
|
| 319 |
+
# GH 4096; using same frames, but different block orderings
|
| 320 |
+
with ensure_clean_store(setup_path) as store:
|
| 321 |
+
for i in range(10):
|
| 322 |
+
df = DataFrame(
|
| 323 |
+
np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")
|
| 324 |
+
)
|
| 325 |
+
df["index"] = range(10)
|
| 326 |
+
df["index"] += i * 10
|
| 327 |
+
df["int64"] = Series([1] * len(df), dtype="int64")
|
| 328 |
+
df["int16"] = Series([1] * len(df), dtype="int16")
|
| 329 |
+
|
| 330 |
+
if i % 2 == 0:
|
| 331 |
+
del df["int64"]
|
| 332 |
+
df["int64"] = Series([1] * len(df), dtype="int64")
|
| 333 |
+
if i % 3 == 0:
|
| 334 |
+
a = df.pop("A")
|
| 335 |
+
df["A"] = a
|
| 336 |
+
|
| 337 |
+
df.set_index("index", inplace=True)
|
| 338 |
+
|
| 339 |
+
store.append("df", df)
|
| 340 |
+
|
| 341 |
+
# test a different ordering but with more fields (like invalid
|
| 342 |
+
# combinations)
|
| 343 |
+
with ensure_clean_store(setup_path) as store:
|
| 344 |
+
df = DataFrame(
|
| 345 |
+
np.random.default_rng(2).standard_normal((10, 2)),
|
| 346 |
+
columns=list("AB"),
|
| 347 |
+
dtype="float64",
|
| 348 |
+
)
|
| 349 |
+
df["int64"] = Series([1] * len(df), dtype="int64")
|
| 350 |
+
df["int16"] = Series([1] * len(df), dtype="int16")
|
| 351 |
+
store.append("df", df)
|
| 352 |
+
|
| 353 |
+
# store additional fields in different blocks
|
| 354 |
+
df["int16_2"] = Series([1] * len(df), dtype="int16")
|
| 355 |
+
msg = re.escape(
|
| 356 |
+
"cannot match existing table structure for [int16] on appending data"
|
| 357 |
+
)
|
| 358 |
+
with pytest.raises(ValueError, match=msg):
|
| 359 |
+
store.append("df", df)
|
| 360 |
+
|
| 361 |
+
# store multiple additional fields in different blocks
|
| 362 |
+
df["float_3"] = Series([1.0] * len(df), dtype="float64")
|
| 363 |
+
msg = re.escape(
|
| 364 |
+
"cannot match existing table structure for [A,B] on appending data"
|
| 365 |
+
)
|
| 366 |
+
with pytest.raises(ValueError, match=msg):
|
| 367 |
+
store.append("df", df)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def test_append_with_strings(setup_path):
|
| 371 |
+
with ensure_clean_store(setup_path) as store:
|
| 372 |
+
|
| 373 |
+
def check_col(key, name, size):
|
| 374 |
+
assert (
|
| 375 |
+
getattr(store.get_storer(key).table.description, name).itemsize == size
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# avoid truncation on elements
|
| 379 |
+
df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]])
|
| 380 |
+
store.append("df_big", df)
|
| 381 |
+
tm.assert_frame_equal(store.select("df_big"), df)
|
| 382 |
+
check_col("df_big", "values_block_1", 15)
|
| 383 |
+
|
| 384 |
+
# appending smaller string ok
|
| 385 |
+
df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]])
|
| 386 |
+
store.append("df_big", df2)
|
| 387 |
+
expected = concat([df, df2])
|
| 388 |
+
tm.assert_frame_equal(store.select("df_big"), expected)
|
| 389 |
+
check_col("df_big", "values_block_1", 15)
|
| 390 |
+
|
| 391 |
+
# avoid truncation on elements
|
| 392 |
+
df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]])
|
| 393 |
+
store.append("df_big2", df, min_itemsize={"values": 50})
|
| 394 |
+
tm.assert_frame_equal(store.select("df_big2"), df)
|
| 395 |
+
check_col("df_big2", "values_block_1", 50)
|
| 396 |
+
|
| 397 |
+
# bigger string on next append
|
| 398 |
+
store.append("df_new", df)
|
| 399 |
+
df_new = DataFrame([[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]])
|
| 400 |
+
msg = (
|
| 401 |
+
r"Trying to store a string with len \[26\] in "
|
| 402 |
+
r"\[values_block_1\] column but\n"
|
| 403 |
+
r"this column has a limit of \[15\]!\n"
|
| 404 |
+
"Consider using min_itemsize to preset the sizes on these "
|
| 405 |
+
"columns"
|
| 406 |
+
)
|
| 407 |
+
with pytest.raises(ValueError, match=msg):
|
| 408 |
+
store.append("df_new", df_new)
|
| 409 |
+
|
| 410 |
+
# min_itemsize on Series index (GH 11412)
|
| 411 |
+
df = DataFrame(
|
| 412 |
+
{
|
| 413 |
+
"A": [0.0, 1.0, 2.0, 3.0, 4.0],
|
| 414 |
+
"B": [0.0, 1.0, 0.0, 1.0, 0.0],
|
| 415 |
+
"C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object),
|
| 416 |
+
"D": date_range("20130101", periods=5),
|
| 417 |
+
}
|
| 418 |
+
).set_index("C")
|
| 419 |
+
store.append("ss", df["B"], min_itemsize={"index": 4})
|
| 420 |
+
tm.assert_series_equal(store.select("ss"), df["B"])
|
| 421 |
+
|
| 422 |
+
# same as above, with data_columns=True
|
| 423 |
+
store.append("ss2", df["B"], data_columns=True, min_itemsize={"index": 4})
|
| 424 |
+
tm.assert_series_equal(store.select("ss2"), df["B"])
|
| 425 |
+
|
| 426 |
+
# min_itemsize in index without appending (GH 10381)
|
| 427 |
+
store.put("ss3", df, format="table", min_itemsize={"index": 6})
|
| 428 |
+
# just make sure there is a longer string:
|
| 429 |
+
df2 = df.copy().reset_index().assign(C="longer").set_index("C")
|
| 430 |
+
store.append("ss3", df2)
|
| 431 |
+
tm.assert_frame_equal(store.select("ss3"), concat([df, df2]))
|
| 432 |
+
|
| 433 |
+
# same as above, with a Series
|
| 434 |
+
store.put("ss4", df["B"], format="table", min_itemsize={"index": 6})
|
| 435 |
+
store.append("ss4", df2["B"])
|
| 436 |
+
tm.assert_series_equal(store.select("ss4"), concat([df["B"], df2["B"]]))
|
| 437 |
+
|
| 438 |
+
# with nans
|
| 439 |
+
_maybe_remove(store, "df")
|
| 440 |
+
df = DataFrame(
|
| 441 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 442 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 443 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 444 |
+
)
|
| 445 |
+
df["string"] = "foo"
|
| 446 |
+
df.loc[df.index[1:4], "string"] = np.nan
|
| 447 |
+
df["string2"] = "bar"
|
| 448 |
+
df.loc[df.index[4:8], "string2"] = np.nan
|
| 449 |
+
df["string3"] = "bah"
|
| 450 |
+
df.loc[df.index[1:], "string3"] = np.nan
|
| 451 |
+
store.append("df", df)
|
| 452 |
+
result = store.select("df")
|
| 453 |
+
tm.assert_frame_equal(result, df)
|
| 454 |
+
|
| 455 |
+
with ensure_clean_store(setup_path) as store:
|
| 456 |
+
df = DataFrame({"A": "foo", "B": "bar"}, index=range(10))
|
| 457 |
+
|
| 458 |
+
# a min_itemsize that creates a data_column
|
| 459 |
+
_maybe_remove(store, "df")
|
| 460 |
+
store.append("df", df, min_itemsize={"A": 200})
|
| 461 |
+
check_col("df", "A", 200)
|
| 462 |
+
assert store.get_storer("df").data_columns == ["A"]
|
| 463 |
+
|
| 464 |
+
# a min_itemsize that creates a data_column2
|
| 465 |
+
_maybe_remove(store, "df")
|
| 466 |
+
store.append("df", df, data_columns=["B"], min_itemsize={"A": 200})
|
| 467 |
+
check_col("df", "A", 200)
|
| 468 |
+
assert store.get_storer("df").data_columns == ["B", "A"]
|
| 469 |
+
|
| 470 |
+
# a min_itemsize that creates a data_column2
|
| 471 |
+
_maybe_remove(store, "df")
|
| 472 |
+
store.append("df", df, data_columns=["B"], min_itemsize={"values": 200})
|
| 473 |
+
check_col("df", "B", 200)
|
| 474 |
+
check_col("df", "values_block_0", 200)
|
| 475 |
+
assert store.get_storer("df").data_columns == ["B"]
|
| 476 |
+
|
| 477 |
+
# infer the .typ on subsequent appends
|
| 478 |
+
_maybe_remove(store, "df")
|
| 479 |
+
store.append("df", df[:5], min_itemsize=200)
|
| 480 |
+
store.append("df", df[5:], min_itemsize=200)
|
| 481 |
+
tm.assert_frame_equal(store["df"], df)
|
| 482 |
+
|
| 483 |
+
# invalid min_itemsize keys
|
| 484 |
+
df = DataFrame(["foo", "foo", "foo", "barh", "barh", "barh"], columns=["A"])
|
| 485 |
+
_maybe_remove(store, "df")
|
| 486 |
+
msg = re.escape(
|
| 487 |
+
"min_itemsize has the key [foo] which is not an axis or data_column"
|
| 488 |
+
)
|
| 489 |
+
with pytest.raises(ValueError, match=msg):
|
| 490 |
+
store.append("df", df, min_itemsize={"foo": 20, "foobar": 20})
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def test_append_with_empty_string(setup_path):
|
| 494 |
+
with ensure_clean_store(setup_path) as store:
|
| 495 |
+
# with all empty strings (GH 12242)
|
| 496 |
+
df = DataFrame({"x": ["a", "b", "c", "d", "e", "f", ""]})
|
| 497 |
+
store.append("df", df[:-1], min_itemsize={"x": 1})
|
| 498 |
+
store.append("df", df[-1:], min_itemsize={"x": 1})
|
| 499 |
+
tm.assert_frame_equal(store.select("df"), df)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def test_append_with_data_columns(setup_path):
|
| 503 |
+
with ensure_clean_store(setup_path) as store:
|
| 504 |
+
df = DataFrame(
|
| 505 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 506 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 507 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 508 |
+
)
|
| 509 |
+
df.iloc[0, df.columns.get_loc("B")] = 1.0
|
| 510 |
+
_maybe_remove(store, "df")
|
| 511 |
+
store.append("df", df[:2], data_columns=["B"])
|
| 512 |
+
store.append("df", df[2:])
|
| 513 |
+
tm.assert_frame_equal(store["df"], df)
|
| 514 |
+
|
| 515 |
+
# check that we have indices created
|
| 516 |
+
assert store._handle.root.df.table.cols.index.is_indexed is True
|
| 517 |
+
assert store._handle.root.df.table.cols.B.is_indexed is True
|
| 518 |
+
|
| 519 |
+
# data column searching
|
| 520 |
+
result = store.select("df", "B>0")
|
| 521 |
+
expected = df[df.B > 0]
|
| 522 |
+
tm.assert_frame_equal(result, expected)
|
| 523 |
+
|
| 524 |
+
# data column searching (with an indexable and a data_columns)
|
| 525 |
+
result = store.select("df", "B>0 and index>df.index[3]")
|
| 526 |
+
df_new = df.reindex(index=df.index[4:])
|
| 527 |
+
expected = df_new[df_new.B > 0]
|
| 528 |
+
tm.assert_frame_equal(result, expected)
|
| 529 |
+
|
| 530 |
+
# data column selection with a string data_column
|
| 531 |
+
df_new = df.copy()
|
| 532 |
+
df_new["string"] = "foo"
|
| 533 |
+
df_new.loc[df_new.index[1:4], "string"] = np.nan
|
| 534 |
+
df_new.loc[df_new.index[5:6], "string"] = "bar"
|
| 535 |
+
_maybe_remove(store, "df")
|
| 536 |
+
store.append("df", df_new, data_columns=["string"])
|
| 537 |
+
result = store.select("df", "string='foo'")
|
| 538 |
+
expected = df_new[df_new.string == "foo"]
|
| 539 |
+
tm.assert_frame_equal(result, expected)
|
| 540 |
+
|
| 541 |
+
# using min_itemsize and a data column
|
| 542 |
+
def check_col(key, name, size):
|
| 543 |
+
assert (
|
| 544 |
+
getattr(store.get_storer(key).table.description, name).itemsize == size
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
with ensure_clean_store(setup_path) as store:
|
| 548 |
+
_maybe_remove(store, "df")
|
| 549 |
+
store.append("df", df_new, data_columns=["string"], min_itemsize={"string": 30})
|
| 550 |
+
check_col("df", "string", 30)
|
| 551 |
+
_maybe_remove(store, "df")
|
| 552 |
+
store.append("df", df_new, data_columns=["string"], min_itemsize=30)
|
| 553 |
+
check_col("df", "string", 30)
|
| 554 |
+
_maybe_remove(store, "df")
|
| 555 |
+
store.append("df", df_new, data_columns=["string"], min_itemsize={"values": 30})
|
| 556 |
+
check_col("df", "string", 30)
|
| 557 |
+
|
| 558 |
+
with ensure_clean_store(setup_path) as store:
|
| 559 |
+
df_new["string2"] = "foobarbah"
|
| 560 |
+
df_new["string_block1"] = "foobarbah1"
|
| 561 |
+
df_new["string_block2"] = "foobarbah2"
|
| 562 |
+
_maybe_remove(store, "df")
|
| 563 |
+
store.append(
|
| 564 |
+
"df",
|
| 565 |
+
df_new,
|
| 566 |
+
data_columns=["string", "string2"],
|
| 567 |
+
min_itemsize={"string": 30, "string2": 40, "values": 50},
|
| 568 |
+
)
|
| 569 |
+
check_col("df", "string", 30)
|
| 570 |
+
check_col("df", "string2", 40)
|
| 571 |
+
check_col("df", "values_block_1", 50)
|
| 572 |
+
|
| 573 |
+
with ensure_clean_store(setup_path) as store:
|
| 574 |
+
# multiple data columns
|
| 575 |
+
df_new = df.copy()
|
| 576 |
+
df_new.iloc[0, df_new.columns.get_loc("A")] = 1.0
|
| 577 |
+
df_new.iloc[0, df_new.columns.get_loc("B")] = -1.0
|
| 578 |
+
df_new["string"] = "foo"
|
| 579 |
+
|
| 580 |
+
sl = df_new.columns.get_loc("string")
|
| 581 |
+
df_new.iloc[1:4, sl] = np.nan
|
| 582 |
+
df_new.iloc[5:6, sl] = "bar"
|
| 583 |
+
|
| 584 |
+
df_new["string2"] = "foo"
|
| 585 |
+
sl = df_new.columns.get_loc("string2")
|
| 586 |
+
df_new.iloc[2:5, sl] = np.nan
|
| 587 |
+
df_new.iloc[7:8, sl] = "bar"
|
| 588 |
+
_maybe_remove(store, "df")
|
| 589 |
+
store.append("df", df_new, data_columns=["A", "B", "string", "string2"])
|
| 590 |
+
result = store.select("df", "string='foo' and string2='foo' and A>0 and B<0")
|
| 591 |
+
expected = df_new[
|
| 592 |
+
(df_new.string == "foo")
|
| 593 |
+
& (df_new.string2 == "foo")
|
| 594 |
+
& (df_new.A > 0)
|
| 595 |
+
& (df_new.B < 0)
|
| 596 |
+
]
|
| 597 |
+
tm.assert_frame_equal(result, expected, check_freq=False)
|
| 598 |
+
# FIXME: 2020-05-07 freq check randomly fails in the CI
|
| 599 |
+
|
| 600 |
+
# yield an empty frame
|
| 601 |
+
result = store.select("df", "string='foo' and string2='cool'")
|
| 602 |
+
expected = df_new[(df_new.string == "foo") & (df_new.string2 == "cool")]
|
| 603 |
+
tm.assert_frame_equal(result, expected)
|
| 604 |
+
|
| 605 |
+
with ensure_clean_store(setup_path) as store:
|
| 606 |
+
# doc example
|
| 607 |
+
df_dc = df.copy()
|
| 608 |
+
df_dc["string"] = "foo"
|
| 609 |
+
df_dc.loc[df_dc.index[4:6], "string"] = np.nan
|
| 610 |
+
df_dc.loc[df_dc.index[7:9], "string"] = "bar"
|
| 611 |
+
df_dc["string2"] = "cool"
|
| 612 |
+
df_dc["datetime"] = Timestamp("20010102").as_unit("ns")
|
| 613 |
+
df_dc.loc[df_dc.index[3:5], ["A", "B", "datetime"]] = np.nan
|
| 614 |
+
|
| 615 |
+
_maybe_remove(store, "df_dc")
|
| 616 |
+
store.append(
|
| 617 |
+
"df_dc", df_dc, data_columns=["B", "C", "string", "string2", "datetime"]
|
| 618 |
+
)
|
| 619 |
+
result = store.select("df_dc", "B>0")
|
| 620 |
+
|
| 621 |
+
expected = df_dc[df_dc.B > 0]
|
| 622 |
+
tm.assert_frame_equal(result, expected)
|
| 623 |
+
|
| 624 |
+
result = store.select("df_dc", ["B > 0", "C > 0", "string == foo"])
|
| 625 |
+
expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")]
|
| 626 |
+
tm.assert_frame_equal(result, expected, check_freq=False)
|
| 627 |
+
# FIXME: 2020-12-07 intermittent build failures here with freq of
|
| 628 |
+
# None instead of BDay(4)
|
| 629 |
+
|
| 630 |
+
with ensure_clean_store(setup_path) as store:
|
| 631 |
+
# doc example part 2
|
| 632 |
+
|
| 633 |
+
index = date_range("1/1/2000", periods=8)
|
| 634 |
+
df_dc = DataFrame(
|
| 635 |
+
np.random.default_rng(2).standard_normal((8, 3)),
|
| 636 |
+
index=index,
|
| 637 |
+
columns=["A", "B", "C"],
|
| 638 |
+
)
|
| 639 |
+
df_dc["string"] = "foo"
|
| 640 |
+
df_dc.loc[df_dc.index[4:6], "string"] = np.nan
|
| 641 |
+
df_dc.loc[df_dc.index[7:9], "string"] = "bar"
|
| 642 |
+
df_dc[["B", "C"]] = df_dc[["B", "C"]].abs()
|
| 643 |
+
df_dc["string2"] = "cool"
|
| 644 |
+
|
| 645 |
+
# on-disk operations
|
| 646 |
+
store.append("df_dc", df_dc, data_columns=["B", "C", "string", "string2"])
|
| 647 |
+
|
| 648 |
+
result = store.select("df_dc", "B>0")
|
| 649 |
+
expected = df_dc[df_dc.B > 0]
|
| 650 |
+
tm.assert_frame_equal(result, expected)
|
| 651 |
+
|
| 652 |
+
result = store.select("df_dc", ["B > 0", "C > 0", 'string == "foo"'])
|
| 653 |
+
expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")]
|
| 654 |
+
tm.assert_frame_equal(result, expected)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def test_append_hierarchical(tmp_path, setup_path, multiindex_dataframe_random_data):
|
| 658 |
+
df = multiindex_dataframe_random_data
|
| 659 |
+
df.columns.name = None
|
| 660 |
+
|
| 661 |
+
with ensure_clean_store(setup_path) as store:
|
| 662 |
+
store.append("mi", df)
|
| 663 |
+
result = store.select("mi")
|
| 664 |
+
tm.assert_frame_equal(result, df)
|
| 665 |
+
|
| 666 |
+
# GH 3748
|
| 667 |
+
result = store.select("mi", columns=["A", "B"])
|
| 668 |
+
expected = df.reindex(columns=["A", "B"])
|
| 669 |
+
tm.assert_frame_equal(result, expected)
|
| 670 |
+
|
| 671 |
+
path = tmp_path / "test.hdf"
|
| 672 |
+
df.to_hdf(path, key="df", format="table")
|
| 673 |
+
result = read_hdf(path, "df", columns=["A", "B"])
|
| 674 |
+
expected = df.reindex(columns=["A", "B"])
|
| 675 |
+
tm.assert_frame_equal(result, expected)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def test_append_misc(setup_path):
|
| 679 |
+
with ensure_clean_store(setup_path) as store:
|
| 680 |
+
df = DataFrame(
|
| 681 |
+
1.1 * np.arange(120).reshape((30, 4)),
|
| 682 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 683 |
+
index=Index([f"i-{i}" for i in range(30)], dtype=object),
|
| 684 |
+
)
|
| 685 |
+
store.append("df", df, chunksize=1)
|
| 686 |
+
result = store.select("df")
|
| 687 |
+
tm.assert_frame_equal(result, df)
|
| 688 |
+
|
| 689 |
+
store.append("df1", df, expectedrows=10)
|
| 690 |
+
result = store.select("df1")
|
| 691 |
+
tm.assert_frame_equal(result, df)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@pytest.mark.parametrize("chunksize", [10, 200, 1000])
|
| 695 |
+
def test_append_misc_chunksize(setup_path, chunksize):
|
| 696 |
+
# more chunksize in append tests
|
| 697 |
+
df = DataFrame(
|
| 698 |
+
1.1 * np.arange(120).reshape((30, 4)),
|
| 699 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 700 |
+
index=Index([f"i-{i}" for i in range(30)], dtype=object),
|
| 701 |
+
)
|
| 702 |
+
df["string"] = "foo"
|
| 703 |
+
df["float322"] = 1.0
|
| 704 |
+
df["float322"] = df["float322"].astype("float32")
|
| 705 |
+
df["bool"] = df["float322"] > 0
|
| 706 |
+
df["time1"] = Timestamp("20130101").as_unit("ns")
|
| 707 |
+
df["time2"] = Timestamp("20130102").as_unit("ns")
|
| 708 |
+
with ensure_clean_store(setup_path, mode="w") as store:
|
| 709 |
+
store.append("obj", df, chunksize=chunksize)
|
| 710 |
+
result = store.select("obj")
|
| 711 |
+
tm.assert_frame_equal(result, df)
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def test_append_misc_empty_frame(setup_path):
|
| 715 |
+
# empty frame, GH4273
|
| 716 |
+
with ensure_clean_store(setup_path) as store:
|
| 717 |
+
# 0 len
|
| 718 |
+
df_empty = DataFrame(columns=list("ABC"))
|
| 719 |
+
store.append("df", df_empty)
|
| 720 |
+
with pytest.raises(KeyError, match="'No object named df in the file'"):
|
| 721 |
+
store.select("df")
|
| 722 |
+
|
| 723 |
+
# repeated append of 0/non-zero frames
|
| 724 |
+
df = DataFrame(np.random.default_rng(2).random((10, 3)), columns=list("ABC"))
|
| 725 |
+
store.append("df", df)
|
| 726 |
+
tm.assert_frame_equal(store.select("df"), df)
|
| 727 |
+
store.append("df", df_empty)
|
| 728 |
+
tm.assert_frame_equal(store.select("df"), df)
|
| 729 |
+
|
| 730 |
+
# store
|
| 731 |
+
df = DataFrame(columns=list("ABC"))
|
| 732 |
+
store.put("df2", df)
|
| 733 |
+
tm.assert_frame_equal(store.select("df2"), df)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
# TODO(ArrayManager) currently we rely on falling back to BlockManager, but
|
| 737 |
+
# the conversion from AM->BM converts the invalid object dtype column into
|
| 738 |
+
# a datetime64 column no longer raising an error
|
| 739 |
+
@td.skip_array_manager_not_yet_implemented
|
| 740 |
+
def test_append_raise(setup_path):
|
| 741 |
+
with ensure_clean_store(setup_path) as store:
|
| 742 |
+
# test append with invalid input to get good error messages
|
| 743 |
+
|
| 744 |
+
# list in column
|
| 745 |
+
df = DataFrame(
|
| 746 |
+
1.1 * np.arange(120).reshape((30, 4)),
|
| 747 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 748 |
+
index=Index([f"i-{i}" for i in range(30)], dtype=object),
|
| 749 |
+
)
|
| 750 |
+
df["invalid"] = [["a"]] * len(df)
|
| 751 |
+
assert df.dtypes["invalid"] == np.object_
|
| 752 |
+
msg = re.escape(
|
| 753 |
+
"""Cannot serialize the column [invalid]
|
| 754 |
+
because its data contents are not [string] but [mixed] object dtype"""
|
| 755 |
+
)
|
| 756 |
+
with pytest.raises(TypeError, match=msg):
|
| 757 |
+
store.append("df", df)
|
| 758 |
+
|
| 759 |
+
# multiple invalid columns
|
| 760 |
+
df["invalid2"] = [["a"]] * len(df)
|
| 761 |
+
df["invalid3"] = [["a"]] * len(df)
|
| 762 |
+
with pytest.raises(TypeError, match=msg):
|
| 763 |
+
store.append("df", df)
|
| 764 |
+
|
| 765 |
+
# datetime with embedded nans as object
|
| 766 |
+
df = DataFrame(
|
| 767 |
+
1.1 * np.arange(120).reshape((30, 4)),
|
| 768 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 769 |
+
index=Index([f"i-{i}" for i in range(30)], dtype=object),
|
| 770 |
+
)
|
| 771 |
+
s = Series(datetime.datetime(2001, 1, 2), index=df.index)
|
| 772 |
+
s = s.astype(object)
|
| 773 |
+
s[0:5] = np.nan
|
| 774 |
+
df["invalid"] = s
|
| 775 |
+
assert df.dtypes["invalid"] == np.object_
|
| 776 |
+
msg = "too many timezones in this block, create separate data columns"
|
| 777 |
+
with pytest.raises(TypeError, match=msg):
|
| 778 |
+
store.append("df", df)
|
| 779 |
+
|
| 780 |
+
# directly ndarray
|
| 781 |
+
msg = "value must be None, Series, or DataFrame"
|
| 782 |
+
with pytest.raises(TypeError, match=msg):
|
| 783 |
+
store.append("df", np.arange(10))
|
| 784 |
+
|
| 785 |
+
# series directly
|
| 786 |
+
msg = re.escape(
|
| 787 |
+
"cannot properly create the storer for: "
|
| 788 |
+
"[group->df,value-><class 'pandas.core.series.Series'>]"
|
| 789 |
+
)
|
| 790 |
+
with pytest.raises(TypeError, match=msg):
|
| 791 |
+
store.append("df", Series(np.arange(10)))
|
| 792 |
+
|
| 793 |
+
# appending an incompatible table
|
| 794 |
+
df = DataFrame(
|
| 795 |
+
1.1 * np.arange(120).reshape((30, 4)),
|
| 796 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 797 |
+
index=Index([f"i-{i}" for i in range(30)], dtype=object),
|
| 798 |
+
)
|
| 799 |
+
store.append("df", df)
|
| 800 |
+
|
| 801 |
+
df["foo"] = "foo"
|
| 802 |
+
msg = re.escape(
|
| 803 |
+
"invalid combination of [non_index_axes] on appending data "
|
| 804 |
+
"[(1, ['A', 'B', 'C', 'D', 'foo'])] vs current table "
|
| 805 |
+
"[(1, ['A', 'B', 'C', 'D'])]"
|
| 806 |
+
)
|
| 807 |
+
with pytest.raises(ValueError, match=msg):
|
| 808 |
+
store.append("df", df)
|
| 809 |
+
|
| 810 |
+
# incompatible type (GH 41897)
|
| 811 |
+
_maybe_remove(store, "df")
|
| 812 |
+
df["foo"] = Timestamp("20130101")
|
| 813 |
+
store.append("df", df)
|
| 814 |
+
df["foo"] = "bar"
|
| 815 |
+
msg = re.escape(
|
| 816 |
+
"invalid combination of [values_axes] on appending data "
|
| 817 |
+
"[name->values_block_1,cname->values_block_1,"
|
| 818 |
+
"dtype->bytes24,kind->string,shape->(1, 30)] "
|
| 819 |
+
"vs current table "
|
| 820 |
+
"[name->values_block_1,cname->values_block_1,"
|
| 821 |
+
"dtype->datetime64[s],kind->datetime64[s],shape->None]"
|
| 822 |
+
)
|
| 823 |
+
with pytest.raises(ValueError, match=msg):
|
| 824 |
+
store.append("df", df)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def test_append_with_timedelta(setup_path):
|
| 828 |
+
# GH 3577
|
| 829 |
+
# append timedelta
|
| 830 |
+
|
| 831 |
+
ts = Timestamp("20130101").as_unit("ns")
|
| 832 |
+
df = DataFrame(
|
| 833 |
+
{
|
| 834 |
+
"A": ts,
|
| 835 |
+
"B": [ts + timedelta(days=i, seconds=10) for i in range(10)],
|
| 836 |
+
}
|
| 837 |
+
)
|
| 838 |
+
df["C"] = df["A"] - df["B"]
|
| 839 |
+
df.loc[3:5, "C"] = np.nan
|
| 840 |
+
|
| 841 |
+
with ensure_clean_store(setup_path) as store:
|
| 842 |
+
# table
|
| 843 |
+
_maybe_remove(store, "df")
|
| 844 |
+
store.append("df", df, data_columns=True)
|
| 845 |
+
result = store.select("df")
|
| 846 |
+
tm.assert_frame_equal(result, df)
|
| 847 |
+
|
| 848 |
+
result = store.select("df", where="C<100000")
|
| 849 |
+
tm.assert_frame_equal(result, df)
|
| 850 |
+
|
| 851 |
+
result = store.select("df", where="C<pd.Timedelta('-3D')")
|
| 852 |
+
tm.assert_frame_equal(result, df.iloc[3:])
|
| 853 |
+
|
| 854 |
+
result = store.select("df", "C<'-3D'")
|
| 855 |
+
tm.assert_frame_equal(result, df.iloc[3:])
|
| 856 |
+
|
| 857 |
+
# a bit hacky here as we don't really deal with the NaT properly
|
| 858 |
+
|
| 859 |
+
result = store.select("df", "C<'-500000s'")
|
| 860 |
+
result = result.dropna(subset=["C"])
|
| 861 |
+
tm.assert_frame_equal(result, df.iloc[6:])
|
| 862 |
+
|
| 863 |
+
result = store.select("df", "C<'-3.5D'")
|
| 864 |
+
result = result.iloc[1:]
|
| 865 |
+
tm.assert_frame_equal(result, df.iloc[4:])
|
| 866 |
+
|
| 867 |
+
# fixed
|
| 868 |
+
_maybe_remove(store, "df2")
|
| 869 |
+
store.put("df2", df)
|
| 870 |
+
result = store.select("df2")
|
| 871 |
+
tm.assert_frame_equal(result, df)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def test_append_to_multiple(setup_path):
|
| 875 |
+
df1 = DataFrame(
|
| 876 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 877 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 878 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 879 |
+
)
|
| 880 |
+
df2 = df1.copy().rename(columns="{}_2".format)
|
| 881 |
+
df2["foo"] = "bar"
|
| 882 |
+
df = concat([df1, df2], axis=1)
|
| 883 |
+
|
| 884 |
+
with ensure_clean_store(setup_path) as store:
|
| 885 |
+
# exceptions
|
| 886 |
+
msg = "append_to_multiple requires a selector that is in passed dict"
|
| 887 |
+
with pytest.raises(ValueError, match=msg):
|
| 888 |
+
store.append_to_multiple(
|
| 889 |
+
{"df1": ["A", "B"], "df2": None}, df, selector="df3"
|
| 890 |
+
)
|
| 891 |
+
|
| 892 |
+
with pytest.raises(ValueError, match=msg):
|
| 893 |
+
store.append_to_multiple({"df1": None, "df2": None}, df, selector="df3")
|
| 894 |
+
|
| 895 |
+
msg = (
|
| 896 |
+
"append_to_multiple must have a dictionary specified as the way to "
|
| 897 |
+
"split the value"
|
| 898 |
+
)
|
| 899 |
+
with pytest.raises(ValueError, match=msg):
|
| 900 |
+
store.append_to_multiple("df1", df, "df1")
|
| 901 |
+
|
| 902 |
+
# regular operation
|
| 903 |
+
store.append_to_multiple({"df1": ["A", "B"], "df2": None}, df, selector="df1")
|
| 904 |
+
result = store.select_as_multiple(
|
| 905 |
+
["df1", "df2"], where=["A>0", "B>0"], selector="df1"
|
| 906 |
+
)
|
| 907 |
+
expected = df[(df.A > 0) & (df.B > 0)]
|
| 908 |
+
tm.assert_frame_equal(result, expected)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def test_append_to_multiple_dropna(setup_path):
|
| 912 |
+
df1 = DataFrame(
|
| 913 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 914 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 915 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 916 |
+
)
|
| 917 |
+
df2 = DataFrame(
|
| 918 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 919 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 920 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 921 |
+
).rename(columns="{}_2".format)
|
| 922 |
+
df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan
|
| 923 |
+
df = concat([df1, df2], axis=1)
|
| 924 |
+
|
| 925 |
+
with ensure_clean_store(setup_path) as store:
|
| 926 |
+
# dropna=True should guarantee rows are synchronized
|
| 927 |
+
store.append_to_multiple(
|
| 928 |
+
{"df1": ["A", "B"], "df2": None}, df, selector="df1", dropna=True
|
| 929 |
+
)
|
| 930 |
+
result = store.select_as_multiple(["df1", "df2"])
|
| 931 |
+
expected = df.dropna()
|
| 932 |
+
tm.assert_frame_equal(result, expected, check_index_type=True)
|
| 933 |
+
tm.assert_index_equal(store.select("df1").index, store.select("df2").index)
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def test_append_to_multiple_dropna_false(setup_path):
|
| 937 |
+
df1 = DataFrame(
|
| 938 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 939 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 940 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 941 |
+
)
|
| 942 |
+
df2 = df1.copy().rename(columns="{}_2".format)
|
| 943 |
+
df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan
|
| 944 |
+
df = concat([df1, df2], axis=1)
|
| 945 |
+
|
| 946 |
+
with ensure_clean_store(setup_path) as store, pd.option_context(
|
| 947 |
+
"io.hdf.dropna_table", True
|
| 948 |
+
):
|
| 949 |
+
# dropna=False shouldn't synchronize row indexes
|
| 950 |
+
store.append_to_multiple(
|
| 951 |
+
{"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False
|
| 952 |
+
)
|
| 953 |
+
|
| 954 |
+
msg = "all tables must have exactly the same nrows!"
|
| 955 |
+
with pytest.raises(ValueError, match=msg):
|
| 956 |
+
store.select_as_multiple(["df1a", "df2a"])
|
| 957 |
+
|
| 958 |
+
assert not store.select("df1a").index.equals(store.select("df2a").index)
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def test_append_to_multiple_min_itemsize(setup_path):
|
| 962 |
+
# GH 11238
|
| 963 |
+
df = DataFrame(
|
| 964 |
+
{
|
| 965 |
+
"IX": np.arange(1, 21),
|
| 966 |
+
"Num": np.arange(1, 21),
|
| 967 |
+
"BigNum": np.arange(1, 21) * 88,
|
| 968 |
+
"Str": ["a" for _ in range(20)],
|
| 969 |
+
"LongStr": ["abcde" for _ in range(20)],
|
| 970 |
+
}
|
| 971 |
+
)
|
| 972 |
+
expected = df.iloc[[0]]
|
| 973 |
+
|
| 974 |
+
with ensure_clean_store(setup_path) as store:
|
| 975 |
+
store.append_to_multiple(
|
| 976 |
+
{
|
| 977 |
+
"index": ["IX"],
|
| 978 |
+
"nums": ["Num", "BigNum"],
|
| 979 |
+
"strs": ["Str", "LongStr"],
|
| 980 |
+
},
|
| 981 |
+
df.iloc[[0]],
|
| 982 |
+
"index",
|
| 983 |
+
min_itemsize={"Str": 10, "LongStr": 100, "Num": 2},
|
| 984 |
+
)
|
| 985 |
+
result = store.select_as_multiple(["index", "nums", "strs"])
|
| 986 |
+
tm.assert_frame_equal(result, expected, check_index_type=True)
|
shared/package-files/06/0658667d3f0dbbc4c37b070863e78497ab0a8638c0a569170c0ea05a299b24bd/_cufft_get_plan_cache_size_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API int64_t _cufft_get_plan_cache_size(at::DeviceIndex device_index);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/06/0658a0f240042117853b765ed9cd0f9c923a3515f6172e7e8142e55adc3cd608/sun.cpython-311.pyc
ADDED
|
Binary file (2.79 kB). View file
|
|
|
shared/package-files/06/0659cc7cb2a37602ddcdf6a45e4b03fbaf4fb3b36721ee782c862ec4b0359d1d/test_storage_v3.py
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import array
|
| 2 |
+
import atexit
|
| 3 |
+
import copy
|
| 4 |
+
import inspect
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
import zarr
|
| 13 |
+
from zarr._storage.store import (
|
| 14 |
+
_get_hierarchy_metadata,
|
| 15 |
+
assert_zarr_v3_api_available,
|
| 16 |
+
v3_api_available,
|
| 17 |
+
StorageTransformer,
|
| 18 |
+
)
|
| 19 |
+
from zarr._storage.v3_storage_transformers import ShardingStorageTransformer, v3_sharding_available
|
| 20 |
+
from zarr.core import Array
|
| 21 |
+
from zarr.meta import _default_entry_point_metadata_v3
|
| 22 |
+
from zarr.storage import (
|
| 23 |
+
atexit_rmglob,
|
| 24 |
+
atexit_rmtree,
|
| 25 |
+
data_root,
|
| 26 |
+
default_compressor,
|
| 27 |
+
getsize,
|
| 28 |
+
init_array,
|
| 29 |
+
meta_root,
|
| 30 |
+
normalize_store_arg,
|
| 31 |
+
)
|
| 32 |
+
from zarr._storage.v3 import (
|
| 33 |
+
ABSStoreV3,
|
| 34 |
+
ConsolidatedMetadataStoreV3,
|
| 35 |
+
DBMStoreV3,
|
| 36 |
+
DirectoryStoreV3,
|
| 37 |
+
FSStoreV3,
|
| 38 |
+
KVStore,
|
| 39 |
+
KVStoreV3,
|
| 40 |
+
LMDBStoreV3,
|
| 41 |
+
LRUStoreCacheV3,
|
| 42 |
+
MemoryStoreV3,
|
| 43 |
+
MongoDBStoreV3,
|
| 44 |
+
RedisStoreV3,
|
| 45 |
+
SQLiteStoreV3,
|
| 46 |
+
StoreV3,
|
| 47 |
+
ZipStoreV3,
|
| 48 |
+
)
|
| 49 |
+
from zarr.tests.util import CountingDictV3, have_fsspec, skip_test_env_var, mktemp
|
| 50 |
+
|
| 51 |
+
# pytest will fail to run if the following fixtures aren't imported here
|
| 52 |
+
from .test_storage import StoreTests as _StoreTests
|
| 53 |
+
from .test_storage import TestABSStore as _TestABSStore
|
| 54 |
+
from .test_storage import TestConsolidatedMetadataStore as _TestConsolidatedMetadataStore
|
| 55 |
+
from .test_storage import TestDBMStore as _TestDBMStore
|
| 56 |
+
from .test_storage import TestDBMStoreDumb as _TestDBMStoreDumb
|
| 57 |
+
from .test_storage import TestDBMStoreGnu as _TestDBMStoreGnu
|
| 58 |
+
from .test_storage import TestDBMStoreNDBM as _TestDBMStoreNDBM
|
| 59 |
+
from .test_storage import TestDirectoryStore as _TestDirectoryStore
|
| 60 |
+
from .test_storage import TestFSStore as _TestFSStore
|
| 61 |
+
from .test_storage import TestLMDBStore as _TestLMDBStore
|
| 62 |
+
from .test_storage import TestLRUStoreCache as _TestLRUStoreCache
|
| 63 |
+
from .test_storage import TestMemoryStore as _TestMemoryStore
|
| 64 |
+
from .test_storage import TestSQLiteStore as _TestSQLiteStore
|
| 65 |
+
from .test_storage import TestSQLiteStoreInMemory as _TestSQLiteStoreInMemory
|
| 66 |
+
from .test_storage import TestZipStore as _TestZipStore
|
| 67 |
+
from .test_storage import dimension_separator_fixture, s3, skip_if_nested_chunks # noqa
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
pytestmark = pytest.mark.skipif(not v3_api_available, reason="v3 api is not available")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@pytest.fixture(
|
| 74 |
+
params=[
|
| 75 |
+
(None, "/"),
|
| 76 |
+
(".", "."),
|
| 77 |
+
("/", "/"),
|
| 78 |
+
]
|
| 79 |
+
)
|
| 80 |
+
def dimension_separator_fixture_v3(request):
|
| 81 |
+
return request.param
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class DummyStore:
|
| 85 |
+
# contains all methods expected of Mutable Mapping
|
| 86 |
+
|
| 87 |
+
def keys(self):
|
| 88 |
+
"""keys"""
|
| 89 |
+
|
| 90 |
+
def values(self):
|
| 91 |
+
"""values"""
|
| 92 |
+
|
| 93 |
+
def get(self, value, default=None):
|
| 94 |
+
"""get"""
|
| 95 |
+
|
| 96 |
+
def __setitem__(self, key, value):
|
| 97 |
+
"""__setitem__"""
|
| 98 |
+
|
| 99 |
+
def __getitem__(self, key):
|
| 100 |
+
"""__getitem__"""
|
| 101 |
+
|
| 102 |
+
def __delitem__(self, key):
|
| 103 |
+
"""__delitem__"""
|
| 104 |
+
|
| 105 |
+
def __contains__(self, key):
|
| 106 |
+
"""__contains__"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class InvalidDummyStore:
|
| 110 |
+
# does not contain expected methods of a MutableMapping
|
| 111 |
+
|
| 112 |
+
def keys(self):
|
| 113 |
+
"""keys"""
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class DummyStorageTransfomer(StorageTransformer):
|
| 117 |
+
TEST_CONSTANT = "test1234"
|
| 118 |
+
|
| 119 |
+
extension_uri = "https://purl.org/zarr/spec/storage_transformers/dummy/1.0"
|
| 120 |
+
valid_types = ["dummy_type"]
|
| 121 |
+
|
| 122 |
+
def __init__(self, _type, test_value) -> None:
|
| 123 |
+
super().__init__(_type)
|
| 124 |
+
assert test_value == self.TEST_CONSTANT
|
| 125 |
+
self.test_value = test_value
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_ensure_store_v3():
|
| 129 |
+
class InvalidStore:
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
with pytest.raises(ValueError):
|
| 133 |
+
StoreV3._ensure_store(InvalidStore())
|
| 134 |
+
|
| 135 |
+
# cannot initialize with a store from a different Zarr version
|
| 136 |
+
with pytest.raises(ValueError):
|
| 137 |
+
StoreV3._ensure_store(KVStore(dict()))
|
| 138 |
+
|
| 139 |
+
assert StoreV3._ensure_store(None) is None
|
| 140 |
+
|
| 141 |
+
# class with all methods of a MutableMapping will become a KVStoreV3
|
| 142 |
+
assert isinstance(StoreV3._ensure_store(DummyStore), KVStoreV3)
|
| 143 |
+
|
| 144 |
+
with pytest.raises(ValueError):
|
| 145 |
+
# does not have the methods expected of a MutableMapping
|
| 146 |
+
StoreV3._ensure_store(InvalidDummyStore)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_valid_key():
|
| 150 |
+
store = KVStoreV3(dict)
|
| 151 |
+
|
| 152 |
+
# only ascii keys are valid
|
| 153 |
+
assert not store._valid_key(5)
|
| 154 |
+
assert not store._valid_key(2.8)
|
| 155 |
+
|
| 156 |
+
for key in store._valid_key_characters:
|
| 157 |
+
assert store._valid_key(key)
|
| 158 |
+
|
| 159 |
+
# other characters not in store._valid_key_characters are not allowed
|
| 160 |
+
assert not store._valid_key("*")
|
| 161 |
+
assert not store._valid_key("~")
|
| 162 |
+
assert not store._valid_key("^")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_validate_key():
|
| 166 |
+
store = KVStoreV3(dict)
|
| 167 |
+
|
| 168 |
+
# zarr.json is a valid key
|
| 169 |
+
store._validate_key("zarr.json")
|
| 170 |
+
# but other keys not starting with meta/ or data/ are not
|
| 171 |
+
with pytest.raises(ValueError):
|
| 172 |
+
store._validate_key("zar.json")
|
| 173 |
+
|
| 174 |
+
# valid ascii keys
|
| 175 |
+
for valid in [
|
| 176 |
+
meta_root + "arr1.array.json",
|
| 177 |
+
data_root + "arr1.array.json",
|
| 178 |
+
meta_root + "subfolder/item_1-0.group.json",
|
| 179 |
+
]:
|
| 180 |
+
store._validate_key(valid)
|
| 181 |
+
# but otherwise valid keys cannot end in /
|
| 182 |
+
with pytest.raises(ValueError):
|
| 183 |
+
assert store._validate_key(valid + "/")
|
| 184 |
+
|
| 185 |
+
for invalid in [0, "*", "~", "^", "&"]:
|
| 186 |
+
with pytest.raises(ValueError):
|
| 187 |
+
store._validate_key(invalid)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class StoreV3Tests(_StoreTests):
|
| 191 |
+
version = 3
|
| 192 |
+
root = meta_root
|
| 193 |
+
|
| 194 |
+
def test_getsize(self):
|
| 195 |
+
# TODO: determine proper getsize() behavior for v3
|
| 196 |
+
# Currently returns the combined size of entries under
|
| 197 |
+
# meta/root/path and data/root/path.
|
| 198 |
+
# Any path not under meta/root/ or data/root/ (including zarr.json)
|
| 199 |
+
# returns size 0.
|
| 200 |
+
|
| 201 |
+
store = self.create_store()
|
| 202 |
+
if isinstance(store, dict) or hasattr(store, "getsize"):
|
| 203 |
+
assert 0 == getsize(store, "zarr.json")
|
| 204 |
+
store[meta_root + "foo/a"] = b"x"
|
| 205 |
+
assert 1 == getsize(store)
|
| 206 |
+
assert 1 == getsize(store, "foo")
|
| 207 |
+
store[meta_root + "foo/b"] = b"x"
|
| 208 |
+
assert 2 == getsize(store, "foo")
|
| 209 |
+
assert 1 == getsize(store, "foo/b")
|
| 210 |
+
store[meta_root + "bar/a"] = b"yy"
|
| 211 |
+
assert 2 == getsize(store, "bar")
|
| 212 |
+
store[data_root + "bar/a"] = b"zzz"
|
| 213 |
+
assert 5 == getsize(store, "bar")
|
| 214 |
+
store[data_root + "baz/a"] = b"zzz"
|
| 215 |
+
assert 3 == getsize(store, "baz")
|
| 216 |
+
assert 10 == getsize(store)
|
| 217 |
+
store[data_root + "quux"] = array.array("B", b"zzzz")
|
| 218 |
+
assert 14 == getsize(store)
|
| 219 |
+
assert 4 == getsize(store, "quux")
|
| 220 |
+
store[data_root + "spong"] = np.frombuffer(b"zzzzz", dtype="u1")
|
| 221 |
+
assert 19 == getsize(store)
|
| 222 |
+
assert 5 == getsize(store, "spong")
|
| 223 |
+
store.close()
|
| 224 |
+
|
| 225 |
+
def test_init_array(self, dimension_separator_fixture_v3):
|
| 226 |
+
pass_dim_sep, want_dim_sep = dimension_separator_fixture_v3
|
| 227 |
+
|
| 228 |
+
store = self.create_store()
|
| 229 |
+
path = "arr1"
|
| 230 |
+
transformer = DummyStorageTransfomer(
|
| 231 |
+
"dummy_type", test_value=DummyStorageTransfomer.TEST_CONSTANT
|
| 232 |
+
)
|
| 233 |
+
init_array(
|
| 234 |
+
store,
|
| 235 |
+
path=path,
|
| 236 |
+
shape=1000,
|
| 237 |
+
chunks=100,
|
| 238 |
+
dimension_separator=pass_dim_sep,
|
| 239 |
+
storage_transformers=[transformer],
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# check metadata
|
| 243 |
+
mkey = meta_root + path + ".array.json"
|
| 244 |
+
assert mkey in store
|
| 245 |
+
meta = store._metadata_class.decode_array_metadata(store[mkey])
|
| 246 |
+
assert (1000,) == meta["shape"]
|
| 247 |
+
assert (100,) == meta["chunk_grid"]["chunk_shape"]
|
| 248 |
+
assert np.dtype(None) == meta["data_type"]
|
| 249 |
+
assert default_compressor == meta["compressor"]
|
| 250 |
+
assert meta["fill_value"] is None
|
| 251 |
+
# Missing MUST be assumed to be "/"
|
| 252 |
+
assert meta["chunk_grid"]["separator"] is want_dim_sep
|
| 253 |
+
assert len(meta["storage_transformers"]) == 1
|
| 254 |
+
assert isinstance(meta["storage_transformers"][0], DummyStorageTransfomer)
|
| 255 |
+
assert meta["storage_transformers"][0].test_value == DummyStorageTransfomer.TEST_CONSTANT
|
| 256 |
+
store.close()
|
| 257 |
+
|
| 258 |
+
def test_list_prefix(self):
|
| 259 |
+
store = self.create_store()
|
| 260 |
+
path = "arr1"
|
| 261 |
+
init_array(store, path=path, shape=1000, chunks=100)
|
| 262 |
+
|
| 263 |
+
expected = [meta_root + "arr1.array.json", "zarr.json"]
|
| 264 |
+
assert sorted(store.list_prefix("")) == expected
|
| 265 |
+
|
| 266 |
+
expected = [meta_root + "arr1.array.json"]
|
| 267 |
+
assert sorted(store.list_prefix(meta_root.rstrip("/"))) == expected
|
| 268 |
+
|
| 269 |
+
# cannot start prefix with '/'
|
| 270 |
+
with pytest.raises(ValueError):
|
| 271 |
+
store.list_prefix(prefix="/" + meta_root.rstrip("/"))
|
| 272 |
+
|
| 273 |
+
def test_equal(self):
|
| 274 |
+
store = self.create_store()
|
| 275 |
+
assert store == store
|
| 276 |
+
|
| 277 |
+
def test_rename_nonexisting(self):
|
| 278 |
+
store = self.create_store()
|
| 279 |
+
if store.is_erasable():
|
| 280 |
+
with pytest.raises(ValueError):
|
| 281 |
+
store.rename("a", "b")
|
| 282 |
+
else:
|
| 283 |
+
with pytest.raises(NotImplementedError):
|
| 284 |
+
store.rename("a", "b")
|
| 285 |
+
|
| 286 |
+
def test_get_partial_values(self):
|
| 287 |
+
store = self.create_store()
|
| 288 |
+
assert store.supports_efficient_get_partial_values in [True, False]
|
| 289 |
+
store[data_root + "foo"] = b"abcdefg"
|
| 290 |
+
store[data_root + "baz"] = b"z"
|
| 291 |
+
assert [b"a"] == store.get_partial_values([(data_root + "foo", (0, 1))])
|
| 292 |
+
assert [
|
| 293 |
+
b"d",
|
| 294 |
+
b"b",
|
| 295 |
+
b"z",
|
| 296 |
+
b"abc",
|
| 297 |
+
b"defg",
|
| 298 |
+
b"defg",
|
| 299 |
+
b"g",
|
| 300 |
+
b"ef",
|
| 301 |
+
] == store.get_partial_values(
|
| 302 |
+
[
|
| 303 |
+
(data_root + "foo", (3, 1)),
|
| 304 |
+
(data_root + "foo", (1, 1)),
|
| 305 |
+
(data_root + "baz", (0, 1)),
|
| 306 |
+
(data_root + "foo", (0, 3)),
|
| 307 |
+
(data_root + "foo", (3, 4)),
|
| 308 |
+
(data_root + "foo", (3, None)),
|
| 309 |
+
(data_root + "foo", (-1, None)),
|
| 310 |
+
(data_root + "foo", (-3, 2)),
|
| 311 |
+
]
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def test_set_partial_values(self):
|
| 315 |
+
store = self.create_store()
|
| 316 |
+
store.supports_efficient_set_partial_values()
|
| 317 |
+
store[data_root + "foo"] = b"abcdefg"
|
| 318 |
+
store.set_partial_values([(data_root + "foo", 0, b"hey")])
|
| 319 |
+
assert store[data_root + "foo"] == b"heydefg"
|
| 320 |
+
|
| 321 |
+
store.set_partial_values([(data_root + "baz", 0, b"z")])
|
| 322 |
+
assert store[data_root + "baz"] == b"z"
|
| 323 |
+
store.set_partial_values(
|
| 324 |
+
[
|
| 325 |
+
(data_root + "foo", 1, b"oo"),
|
| 326 |
+
(data_root + "baz", 1, b"zzz"),
|
| 327 |
+
(data_root + "baz", 4, b"aaaa"),
|
| 328 |
+
(data_root + "foo", 6, b"done"),
|
| 329 |
+
]
|
| 330 |
+
)
|
| 331 |
+
assert store[data_root + "foo"] == b"hoodefdone"
|
| 332 |
+
assert store[data_root + "baz"] == b"zzzzaaaa"
|
| 333 |
+
store.set_partial_values(
|
| 334 |
+
[
|
| 335 |
+
(data_root + "foo", -2, b"NE"),
|
| 336 |
+
(data_root + "baz", -5, b"q"),
|
| 337 |
+
]
|
| 338 |
+
)
|
| 339 |
+
assert store[data_root + "foo"] == b"hoodefdoNE"
|
| 340 |
+
assert store[data_root + "baz"] == b"zzzq"
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TestMappingStoreV3(StoreV3Tests):
|
| 344 |
+
def create_store(self, **kwargs):
|
| 345 |
+
return KVStoreV3(dict())
|
| 346 |
+
|
| 347 |
+
def test_set_invalid_content(self):
|
| 348 |
+
# Generic mappings support non-buffer types
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class TestMemoryStoreV3(_TestMemoryStore, StoreV3Tests):
|
| 353 |
+
def create_store(self, **kwargs):
|
| 354 |
+
skip_if_nested_chunks(**kwargs)
|
| 355 |
+
return MemoryStoreV3(**kwargs)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class TestDirectoryStoreV3(_TestDirectoryStore, StoreV3Tests):
|
| 359 |
+
def create_store(self, normalize_keys=False, **kwargs):
|
| 360 |
+
# For v3, don't have to skip if nested.
|
| 361 |
+
# skip_if_nested_chunks(**kwargs)
|
| 362 |
+
|
| 363 |
+
path = tempfile.mkdtemp()
|
| 364 |
+
atexit.register(atexit_rmtree, path)
|
| 365 |
+
store = DirectoryStoreV3(path, normalize_keys=normalize_keys, **kwargs)
|
| 366 |
+
return store
|
| 367 |
+
|
| 368 |
+
def test_rename_nonexisting(self):
|
| 369 |
+
store = self.create_store()
|
| 370 |
+
with pytest.raises(FileNotFoundError):
|
| 371 |
+
store.rename(meta_root + "a", meta_root + "b")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec")
|
| 375 |
+
class TestFSStoreV3(_TestFSStore, StoreV3Tests):
|
| 376 |
+
def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs):
|
| 377 |
+
if path is None:
|
| 378 |
+
path = tempfile.mkdtemp()
|
| 379 |
+
atexit.register(atexit_rmtree, path)
|
| 380 |
+
|
| 381 |
+
store = FSStoreV3(
|
| 382 |
+
path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs
|
| 383 |
+
)
|
| 384 |
+
return store
|
| 385 |
+
|
| 386 |
+
def test_init_array(self):
|
| 387 |
+
store = self.create_store()
|
| 388 |
+
path = "arr1"
|
| 389 |
+
init_array(store, path=path, shape=1000, chunks=100)
|
| 390 |
+
|
| 391 |
+
# check metadata
|
| 392 |
+
mkey = meta_root + path + ".array.json"
|
| 393 |
+
assert mkey in store
|
| 394 |
+
meta = store._metadata_class.decode_array_metadata(store[mkey])
|
| 395 |
+
assert (1000,) == meta["shape"]
|
| 396 |
+
assert (100,) == meta["chunk_grid"]["chunk_shape"]
|
| 397 |
+
assert np.dtype(None) == meta["data_type"]
|
| 398 |
+
assert meta["chunk_grid"]["separator"] == "/"
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec")
|
| 402 |
+
class TestFSStoreV3WithKeySeparator(StoreV3Tests):
|
| 403 |
+
def create_store(self, normalize_keys=False, key_separator=".", **kwargs):
|
| 404 |
+
# Since the user is passing key_separator, that will take priority.
|
| 405 |
+
skip_if_nested_chunks(**kwargs)
|
| 406 |
+
|
| 407 |
+
path = tempfile.mkdtemp()
|
| 408 |
+
atexit.register(atexit_rmtree, path)
|
| 409 |
+
return FSStoreV3(path, normalize_keys=normalize_keys, key_separator=key_separator)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# TODO: enable once N5StoreV3 has been implemented
|
| 413 |
+
# @pytest.mark.skipif(True, reason="N5StoreV3 not yet fully implemented")
|
| 414 |
+
# class TestN5StoreV3(_TestN5Store, TestDirectoryStoreV3, StoreV3Tests):
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TestZipStoreV3(_TestZipStore, StoreV3Tests):
|
| 418 |
+
ZipStoreClass = ZipStoreV3
|
| 419 |
+
|
| 420 |
+
def create_store(self, **kwargs):
|
| 421 |
+
path = mktemp(suffix=".zip")
|
| 422 |
+
atexit.register(os.remove, path)
|
| 423 |
+
store = ZipStoreV3(path, mode="w", **kwargs)
|
| 424 |
+
return store
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class TestDBMStoreV3(_TestDBMStore, StoreV3Tests):
|
| 428 |
+
def create_store(self, dimension_separator=None):
|
| 429 |
+
path = mktemp(suffix=".anydbm")
|
| 430 |
+
atexit.register(atexit_rmglob, path + "*")
|
| 431 |
+
# create store using default dbm implementation
|
| 432 |
+
store = DBMStoreV3(path, flag="n", dimension_separator=dimension_separator)
|
| 433 |
+
return store
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class TestDBMStoreV3Dumb(_TestDBMStoreDumb, StoreV3Tests):
|
| 437 |
+
def create_store(self, **kwargs):
|
| 438 |
+
path = mktemp(suffix=".dumbdbm")
|
| 439 |
+
atexit.register(atexit_rmglob, path + "*")
|
| 440 |
+
|
| 441 |
+
import dbm.dumb as dumbdbm
|
| 442 |
+
|
| 443 |
+
store = DBMStoreV3(path, flag="n", open=dumbdbm.open, **kwargs)
|
| 444 |
+
return store
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class TestDBMStoreV3Gnu(_TestDBMStoreGnu, StoreV3Tests):
|
| 448 |
+
def create_store(self, **kwargs):
|
| 449 |
+
gdbm = pytest.importorskip("dbm.gnu")
|
| 450 |
+
path = mktemp(suffix=".gdbm") # pragma: no cover
|
| 451 |
+
atexit.register(os.remove, path) # pragma: no cover
|
| 452 |
+
store = DBMStoreV3(
|
| 453 |
+
path, flag="n", open=gdbm.open, write_lock=False, **kwargs
|
| 454 |
+
) # pragma: no cover
|
| 455 |
+
return store # pragma: no cover
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class TestDBMStoreV3NDBM(_TestDBMStoreNDBM, StoreV3Tests):
|
| 459 |
+
def create_store(self, **kwargs):
|
| 460 |
+
ndbm = pytest.importorskip("dbm.ndbm")
|
| 461 |
+
path = mktemp(suffix=".ndbm") # pragma: no cover
|
| 462 |
+
atexit.register(atexit_rmglob, path + "*") # pragma: no cover
|
| 463 |
+
store = DBMStoreV3(path, flag="n", open=ndbm.open, **kwargs) # pragma: no cover
|
| 464 |
+
return store # pragma: no cover
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class TestLMDBStoreV3(_TestLMDBStore, StoreV3Tests):
|
| 468 |
+
def create_store(self, **kwargs):
|
| 469 |
+
pytest.importorskip("lmdb")
|
| 470 |
+
path = mktemp(suffix=".lmdb")
|
| 471 |
+
atexit.register(atexit_rmtree, path)
|
| 472 |
+
buffers = True
|
| 473 |
+
store = LMDBStoreV3(path, buffers=buffers, **kwargs)
|
| 474 |
+
return store
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class TestSQLiteStoreV3(_TestSQLiteStore, StoreV3Tests):
|
| 478 |
+
def create_store(self, **kwargs):
|
| 479 |
+
pytest.importorskip("sqlite3")
|
| 480 |
+
path = mktemp(suffix=".db")
|
| 481 |
+
atexit.register(atexit_rmtree, path)
|
| 482 |
+
store = SQLiteStoreV3(path, **kwargs)
|
| 483 |
+
return store
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class TestSQLiteStoreV3InMemory(_TestSQLiteStoreInMemory, StoreV3Tests):
|
| 487 |
+
def create_store(self, **kwargs):
|
| 488 |
+
pytest.importorskip("sqlite3")
|
| 489 |
+
store = SQLiteStoreV3(":memory:", **kwargs)
|
| 490 |
+
return store
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@skip_test_env_var("ZARR_TEST_MONGO")
|
| 494 |
+
class TestMongoDBStoreV3(StoreV3Tests):
|
| 495 |
+
def create_store(self, **kwargs):
|
| 496 |
+
pytest.importorskip("pymongo")
|
| 497 |
+
store = MongoDBStoreV3(
|
| 498 |
+
host="127.0.0.1", database="zarr_tests", collection="zarr_tests", **kwargs
|
| 499 |
+
)
|
| 500 |
+
# start with an empty store
|
| 501 |
+
store.clear()
|
| 502 |
+
return store
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@skip_test_env_var("ZARR_TEST_REDIS")
|
| 506 |
+
class TestRedisStoreV3(StoreV3Tests):
|
| 507 |
+
def create_store(self, **kwargs):
|
| 508 |
+
# TODO: this is the default host for Redis on Travis,
|
| 509 |
+
# we probably want to generalize this though
|
| 510 |
+
pytest.importorskip("redis")
|
| 511 |
+
store = RedisStoreV3(host="localhost", port=6379, **kwargs)
|
| 512 |
+
# start with an empty store
|
| 513 |
+
store.clear()
|
| 514 |
+
return store
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
@pytest.mark.skipif(not v3_sharding_available, reason="sharding is disabled")
|
| 518 |
+
class TestStorageTransformerV3(TestMappingStoreV3):
|
| 519 |
+
def create_store(self, **kwargs):
|
| 520 |
+
inner_store = super().create_store(**kwargs)
|
| 521 |
+
dummy_transformer = DummyStorageTransfomer(
|
| 522 |
+
"dummy_type", test_value=DummyStorageTransfomer.TEST_CONSTANT
|
| 523 |
+
)
|
| 524 |
+
sharding_transformer = ShardingStorageTransformer(
|
| 525 |
+
"indexed",
|
| 526 |
+
chunks_per_shard=2,
|
| 527 |
+
)
|
| 528 |
+
path = "bla"
|
| 529 |
+
init_array(
|
| 530 |
+
inner_store,
|
| 531 |
+
path=path,
|
| 532 |
+
shape=1000,
|
| 533 |
+
chunks=100,
|
| 534 |
+
dimension_separator=".",
|
| 535 |
+
storage_transformers=[dummy_transformer, sharding_transformer],
|
| 536 |
+
)
|
| 537 |
+
store = Array(store=inner_store, path=path).chunk_store
|
| 538 |
+
store.erase_prefix("data/root/bla/")
|
| 539 |
+
store.clear()
|
| 540 |
+
return store
|
| 541 |
+
|
| 542 |
+
def test_method_forwarding(self):
|
| 543 |
+
store = self.create_store()
|
| 544 |
+
inner_store = store.inner_store.inner_store
|
| 545 |
+
assert store.list() == inner_store.list()
|
| 546 |
+
assert store.list_dir(data_root) == inner_store.list_dir(data_root)
|
| 547 |
+
|
| 548 |
+
assert store.is_readable()
|
| 549 |
+
assert store.is_writeable()
|
| 550 |
+
assert store.is_listable()
|
| 551 |
+
inner_store._readable = False
|
| 552 |
+
inner_store._writeable = False
|
| 553 |
+
inner_store._listable = False
|
| 554 |
+
assert not store.is_readable()
|
| 555 |
+
assert not store.is_writeable()
|
| 556 |
+
assert not store.is_listable()
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class TestLRUStoreCacheV3(_TestLRUStoreCache, StoreV3Tests):
|
| 560 |
+
CountingClass = CountingDictV3
|
| 561 |
+
LRUStoreClass = LRUStoreCacheV3
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
@skip_test_env_var("ZARR_TEST_ABS")
|
| 565 |
+
class TestABSStoreV3(_TestABSStore, StoreV3Tests):
|
| 566 |
+
ABSStoreClass = ABSStoreV3
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def test_normalize_store_arg_v3(tmpdir):
|
| 570 |
+
fn = tmpdir.join("store.zip")
|
| 571 |
+
store = normalize_store_arg(str(fn), zarr_version=3, mode="w")
|
| 572 |
+
assert isinstance(store, ZipStoreV3)
|
| 573 |
+
assert "zarr.json" in store
|
| 574 |
+
|
| 575 |
+
# can't pass storage_options to non-fsspec store
|
| 576 |
+
with pytest.raises(ValueError):
|
| 577 |
+
normalize_store_arg(str(fn), zarr_version=3, mode="w", storage_options={"some": "kwargs"})
|
| 578 |
+
|
| 579 |
+
if have_fsspec:
|
| 580 |
+
import fsspec
|
| 581 |
+
|
| 582 |
+
path = tempfile.mkdtemp()
|
| 583 |
+
store = normalize_store_arg("file://" + path, zarr_version=3, mode="w")
|
| 584 |
+
assert isinstance(store, FSStoreV3)
|
| 585 |
+
assert "zarr.json" in store
|
| 586 |
+
|
| 587 |
+
store = normalize_store_arg(fsspec.get_mapper("file://" + path), zarr_version=3)
|
| 588 |
+
assert isinstance(store, FSStoreV3)
|
| 589 |
+
|
| 590 |
+
# regression for https://github.com/zarr-developers/zarr-python/issues/1382
|
| 591 |
+
# contents of zarr.json are not important for this test
|
| 592 |
+
out = {"version": 1, "refs": {"zarr.json": "{...}"}}
|
| 593 |
+
store = normalize_store_arg(
|
| 594 |
+
"reference://", storage_options={"fo": out, "remote_protocol": "memory"}, zarr_version=3
|
| 595 |
+
)
|
| 596 |
+
assert isinstance(store, FSStoreV3)
|
| 597 |
+
|
| 598 |
+
fn = tmpdir.join("store.n5")
|
| 599 |
+
with pytest.raises(NotImplementedError):
|
| 600 |
+
normalize_store_arg(str(fn), zarr_version=3, mode="w")
|
| 601 |
+
|
| 602 |
+
# error on zarr_version=3 with a v2 store
|
| 603 |
+
with pytest.raises(ValueError):
|
| 604 |
+
normalize_store_arg(KVStore(dict()), zarr_version=3, mode="w")
|
| 605 |
+
|
| 606 |
+
# error on zarr_version=2 with a v3 store
|
| 607 |
+
with pytest.raises(ValueError):
|
| 608 |
+
normalize_store_arg(KVStoreV3(dict()), zarr_version=2, mode="w")
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
class TestConsolidatedMetadataStoreV3(_TestConsolidatedMetadataStore):
|
| 612 |
+
version = 3
|
| 613 |
+
ConsolidatedMetadataClass = ConsolidatedMetadataStoreV3
|
| 614 |
+
|
| 615 |
+
@property
|
| 616 |
+
def metadata_key(self):
|
| 617 |
+
return meta_root + "consolidated/.zmetadata"
|
| 618 |
+
|
| 619 |
+
def test_bad_store_version(self):
|
| 620 |
+
with pytest.raises(ValueError):
|
| 621 |
+
self.ConsolidatedMetadataClass(KVStore(dict()))
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def test_get_hierarchy_metadata():
|
| 625 |
+
store = KVStoreV3({})
|
| 626 |
+
|
| 627 |
+
# error raised if 'jarr.json' is not in the store
|
| 628 |
+
with pytest.raises(ValueError):
|
| 629 |
+
_get_hierarchy_metadata(store)
|
| 630 |
+
|
| 631 |
+
store["zarr.json"] = _default_entry_point_metadata_v3
|
| 632 |
+
assert _get_hierarchy_metadata(store) == _default_entry_point_metadata_v3
|
| 633 |
+
|
| 634 |
+
# ValueError if only a subset of keys are present
|
| 635 |
+
store["zarr.json"] = {"zarr_format": "https://purl.org/zarr/spec/protocol/core/3.0"}
|
| 636 |
+
with pytest.raises(ValueError):
|
| 637 |
+
_get_hierarchy_metadata(store)
|
| 638 |
+
|
| 639 |
+
# ValueError if any unexpected keys are present
|
| 640 |
+
extra_metadata = copy.copy(_default_entry_point_metadata_v3)
|
| 641 |
+
extra_metadata["extra_key"] = "value"
|
| 642 |
+
store["zarr.json"] = extra_metadata
|
| 643 |
+
with pytest.raises(ValueError):
|
| 644 |
+
_get_hierarchy_metadata(store)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def test_top_level_imports():
|
| 648 |
+
for store_name in [
|
| 649 |
+
"ABSStoreV3",
|
| 650 |
+
"DBMStoreV3",
|
| 651 |
+
"KVStoreV3",
|
| 652 |
+
"DirectoryStoreV3",
|
| 653 |
+
"LMDBStoreV3",
|
| 654 |
+
"LRUStoreCacheV3",
|
| 655 |
+
"MemoryStoreV3",
|
| 656 |
+
"MongoDBStoreV3",
|
| 657 |
+
"RedisStoreV3",
|
| 658 |
+
"SQLiteStoreV3",
|
| 659 |
+
"ZipStoreV3",
|
| 660 |
+
]:
|
| 661 |
+
if v3_api_available:
|
| 662 |
+
assert hasattr(zarr, store_name) # pragma: no cover
|
| 663 |
+
else:
|
| 664 |
+
assert not hasattr(zarr, store_name) # pragma: no cover
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def test_assert_zarr_v3_api_available_warns_once():
|
| 668 |
+
import zarr._storage.store
|
| 669 |
+
|
| 670 |
+
zarr._storage.store._has_warned_about_v3 = False
|
| 671 |
+
warnings.resetwarnings()
|
| 672 |
+
with pytest.warns() as record:
|
| 673 |
+
assert_zarr_v3_api_available()
|
| 674 |
+
assert_zarr_v3_api_available()
|
| 675 |
+
assert len(record) == 1
|
| 676 |
+
assert "The experimental Zarr V3 implementation" in str(record[0].message)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _get_public_and_dunder_methods(some_class):
|
| 680 |
+
return set(
|
| 681 |
+
name
|
| 682 |
+
for name, _ in inspect.getmembers(some_class, predicate=inspect.isfunction)
|
| 683 |
+
if not name.startswith("_") or name.startswith("__")
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def test_storage_transformer_interface():
|
| 688 |
+
store_v3_methods = _get_public_and_dunder_methods(StoreV3)
|
| 689 |
+
store_v3_methods.discard("__init__")
|
| 690 |
+
# Note, getitems() isn't mandatory when get_partial_values() is available
|
| 691 |
+
store_v3_methods.discard("getitems")
|
| 692 |
+
storage_transformer_methods = _get_public_and_dunder_methods(StorageTransformer)
|
| 693 |
+
storage_transformer_methods.discard("__init__")
|
| 694 |
+
storage_transformer_methods.discard("get_config")
|
| 695 |
+
assert storage_transformer_methods == store_v3_methods
|
shared/package-files/06/065d8910135bd7c972b1ef8e31d68379fb41709f772ad4d0789acde63d6144e3/multidigraph.cpython-311.pyc
ADDED
|
Binary file (41.3 kB). View file
|
|
|
shared/package-files/06/065ec0fe53e8ba84bbb8af049f26eabed317a7a59ab48ed4f3d390c0c79c5956/test_analytics.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas.compat import PYPY
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
Categorical,
|
| 11 |
+
CategoricalDtype,
|
| 12 |
+
DataFrame,
|
| 13 |
+
Index,
|
| 14 |
+
NaT,
|
| 15 |
+
Series,
|
| 16 |
+
date_range,
|
| 17 |
+
)
|
| 18 |
+
import pandas._testing as tm
|
| 19 |
+
from pandas.api.types import is_scalar
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestCategoricalAnalytics:
|
| 23 |
+
@pytest.mark.parametrize("aggregation", ["min", "max"])
|
| 24 |
+
def test_min_max_not_ordered_raises(self, aggregation):
|
| 25 |
+
# unordered cats have no min/max
|
| 26 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=False)
|
| 27 |
+
msg = f"Categorical is not ordered for operation {aggregation}"
|
| 28 |
+
agg_func = getattr(cat, aggregation)
|
| 29 |
+
|
| 30 |
+
with pytest.raises(TypeError, match=msg):
|
| 31 |
+
agg_func()
|
| 32 |
+
|
| 33 |
+
ufunc = np.minimum if aggregation == "min" else np.maximum
|
| 34 |
+
with pytest.raises(TypeError, match=msg):
|
| 35 |
+
ufunc.reduce(cat)
|
| 36 |
+
|
| 37 |
+
def test_min_max_ordered(self, index_or_series_or_array):
|
| 38 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=True)
|
| 39 |
+
obj = index_or_series_or_array(cat)
|
| 40 |
+
_min = obj.min()
|
| 41 |
+
_max = obj.max()
|
| 42 |
+
assert _min == "a"
|
| 43 |
+
assert _max == "d"
|
| 44 |
+
|
| 45 |
+
assert np.minimum.reduce(obj) == "a"
|
| 46 |
+
assert np.maximum.reduce(obj) == "d"
|
| 47 |
+
# TODO: raises if we pass axis=0 (on Index and Categorical, not Series)
|
| 48 |
+
|
| 49 |
+
cat = Categorical(
|
| 50 |
+
["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True
|
| 51 |
+
)
|
| 52 |
+
obj = index_or_series_or_array(cat)
|
| 53 |
+
_min = obj.min()
|
| 54 |
+
_max = obj.max()
|
| 55 |
+
assert _min == "d"
|
| 56 |
+
assert _max == "a"
|
| 57 |
+
assert np.minimum.reduce(obj) == "d"
|
| 58 |
+
assert np.maximum.reduce(obj) == "a"
|
| 59 |
+
|
| 60 |
+
def test_min_max_reduce(self):
|
| 61 |
+
# GH52788
|
| 62 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=True)
|
| 63 |
+
df = DataFrame(cat)
|
| 64 |
+
|
| 65 |
+
result_max = df.agg("max")
|
| 66 |
+
expected_max = Series(Categorical(["d"], dtype=cat.dtype))
|
| 67 |
+
tm.assert_series_equal(result_max, expected_max)
|
| 68 |
+
|
| 69 |
+
result_min = df.agg("min")
|
| 70 |
+
expected_min = Series(Categorical(["a"], dtype=cat.dtype))
|
| 71 |
+
tm.assert_series_equal(result_min, expected_min)
|
| 72 |
+
|
| 73 |
+
@pytest.mark.parametrize(
|
| 74 |
+
"categories,expected",
|
| 75 |
+
[
|
| 76 |
+
(list("ABC"), np.nan),
|
| 77 |
+
([1, 2, 3], np.nan),
|
| 78 |
+
pytest.param(
|
| 79 |
+
Series(date_range("2020-01-01", periods=3), dtype="category"),
|
| 80 |
+
NaT,
|
| 81 |
+
marks=pytest.mark.xfail(
|
| 82 |
+
reason="https://github.com/pandas-dev/pandas/issues/29962"
|
| 83 |
+
),
|
| 84 |
+
),
|
| 85 |
+
],
|
| 86 |
+
)
|
| 87 |
+
@pytest.mark.parametrize("aggregation", ["min", "max"])
|
| 88 |
+
def test_min_max_ordered_empty(self, categories, expected, aggregation):
|
| 89 |
+
# GH 30227
|
| 90 |
+
cat = Categorical([], categories=categories, ordered=True)
|
| 91 |
+
|
| 92 |
+
agg_func = getattr(cat, aggregation)
|
| 93 |
+
result = agg_func()
|
| 94 |
+
assert result is expected
|
| 95 |
+
|
| 96 |
+
@pytest.mark.parametrize(
|
| 97 |
+
"values, categories",
|
| 98 |
+
[(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])],
|
| 99 |
+
)
|
| 100 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 101 |
+
@pytest.mark.parametrize("function", ["min", "max"])
|
| 102 |
+
def test_min_max_with_nan(self, values, categories, function, skipna):
|
| 103 |
+
# GH 25303
|
| 104 |
+
cat = Categorical(values, categories=categories, ordered=True)
|
| 105 |
+
result = getattr(cat, function)(skipna=skipna)
|
| 106 |
+
|
| 107 |
+
if skipna is False:
|
| 108 |
+
assert result is np.nan
|
| 109 |
+
else:
|
| 110 |
+
expected = categories[0] if function == "min" else categories[2]
|
| 111 |
+
assert result == expected
|
| 112 |
+
|
| 113 |
+
@pytest.mark.parametrize("function", ["min", "max"])
|
| 114 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 115 |
+
def test_min_max_only_nan(self, function, skipna):
|
| 116 |
+
# https://github.com/pandas-dev/pandas/issues/33450
|
| 117 |
+
cat = Categorical([np.nan], categories=[1, 2], ordered=True)
|
| 118 |
+
result = getattr(cat, function)(skipna=skipna)
|
| 119 |
+
assert result is np.nan
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 122 |
+
def test_numeric_only_min_max_raises(self, method):
|
| 123 |
+
# GH 25303
|
| 124 |
+
cat = Categorical(
|
| 125 |
+
[np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True
|
| 126 |
+
)
|
| 127 |
+
with pytest.raises(TypeError, match=".* got an unexpected keyword"):
|
| 128 |
+
getattr(cat, method)(numeric_only=True)
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 131 |
+
def test_numpy_min_max_raises(self, method):
|
| 132 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=False)
|
| 133 |
+
msg = (
|
| 134 |
+
f"Categorical is not ordered for operation {method}\n"
|
| 135 |
+
"you can use .as_ordered() to change the Categorical to an ordered one"
|
| 136 |
+
)
|
| 137 |
+
method = getattr(np, method)
|
| 138 |
+
with pytest.raises(TypeError, match=re.escape(msg)):
|
| 139 |
+
method(cat)
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize("kwarg", ["axis", "out", "keepdims"])
|
| 142 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 143 |
+
def test_numpy_min_max_unsupported_kwargs_raises(self, method, kwarg):
|
| 144 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=True)
|
| 145 |
+
msg = (
|
| 146 |
+
f"the '{kwarg}' parameter is not supported in the pandas implementation "
|
| 147 |
+
f"of {method}"
|
| 148 |
+
)
|
| 149 |
+
if kwarg == "axis":
|
| 150 |
+
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
|
| 151 |
+
kwargs = {kwarg: 42}
|
| 152 |
+
method = getattr(np, method)
|
| 153 |
+
with pytest.raises(ValueError, match=msg):
|
| 154 |
+
method(cat, **kwargs)
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("method, expected", [("min", "a"), ("max", "c")])
|
| 157 |
+
def test_numpy_min_max_axis_equals_none(self, method, expected):
|
| 158 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=True)
|
| 159 |
+
method = getattr(np, method)
|
| 160 |
+
result = method(cat, axis=None)
|
| 161 |
+
assert result == expected
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize(
|
| 164 |
+
"values,categories,exp_mode",
|
| 165 |
+
[
|
| 166 |
+
([1, 1, 2, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5]),
|
| 167 |
+
([1, 1, 1, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5, 1]),
|
| 168 |
+
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1]),
|
| 169 |
+
([np.nan, np.nan, np.nan, 4, 5], [5, 4, 3, 2, 1], [5, 4]),
|
| 170 |
+
([np.nan, np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),
|
| 171 |
+
([np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),
|
| 172 |
+
],
|
| 173 |
+
)
|
| 174 |
+
def test_mode(self, values, categories, exp_mode):
|
| 175 |
+
cat = Categorical(values, categories=categories, ordered=True)
|
| 176 |
+
res = Series(cat).mode()._values
|
| 177 |
+
exp = Categorical(exp_mode, categories=categories, ordered=True)
|
| 178 |
+
tm.assert_categorical_equal(res, exp)
|
| 179 |
+
|
| 180 |
+
def test_searchsorted(self, ordered):
|
| 181 |
+
# https://github.com/pandas-dev/pandas/issues/8420
|
| 182 |
+
# https://github.com/pandas-dev/pandas/issues/14522
|
| 183 |
+
|
| 184 |
+
cat = Categorical(
|
| 185 |
+
["cheese", "milk", "apple", "bread", "bread"],
|
| 186 |
+
categories=["cheese", "milk", "apple", "bread"],
|
| 187 |
+
ordered=ordered,
|
| 188 |
+
)
|
| 189 |
+
ser = Series(cat)
|
| 190 |
+
|
| 191 |
+
# Searching for single item argument, side='left' (default)
|
| 192 |
+
res_cat = cat.searchsorted("apple")
|
| 193 |
+
assert res_cat == 2
|
| 194 |
+
assert is_scalar(res_cat)
|
| 195 |
+
|
| 196 |
+
res_ser = ser.searchsorted("apple")
|
| 197 |
+
assert res_ser == 2
|
| 198 |
+
assert is_scalar(res_ser)
|
| 199 |
+
|
| 200 |
+
# Searching for single item array, side='left' (default)
|
| 201 |
+
res_cat = cat.searchsorted(["bread"])
|
| 202 |
+
res_ser = ser.searchsorted(["bread"])
|
| 203 |
+
exp = np.array([3], dtype=np.intp)
|
| 204 |
+
tm.assert_numpy_array_equal(res_cat, exp)
|
| 205 |
+
tm.assert_numpy_array_equal(res_ser, exp)
|
| 206 |
+
|
| 207 |
+
# Searching for several items array, side='right'
|
| 208 |
+
res_cat = cat.searchsorted(["apple", "bread"], side="right")
|
| 209 |
+
res_ser = ser.searchsorted(["apple", "bread"], side="right")
|
| 210 |
+
exp = np.array([3, 5], dtype=np.intp)
|
| 211 |
+
tm.assert_numpy_array_equal(res_cat, exp)
|
| 212 |
+
tm.assert_numpy_array_equal(res_ser, exp)
|
| 213 |
+
|
| 214 |
+
# Searching for a single value that is not from the Categorical
|
| 215 |
+
with pytest.raises(TypeError, match="cucumber"):
|
| 216 |
+
cat.searchsorted("cucumber")
|
| 217 |
+
with pytest.raises(TypeError, match="cucumber"):
|
| 218 |
+
ser.searchsorted("cucumber")
|
| 219 |
+
|
| 220 |
+
# Searching for multiple values one of each is not from the Categorical
|
| 221 |
+
msg = (
|
| 222 |
+
"Cannot setitem on a Categorical with a new category, "
|
| 223 |
+
"set the categories first"
|
| 224 |
+
)
|
| 225 |
+
with pytest.raises(TypeError, match=msg):
|
| 226 |
+
cat.searchsorted(["bread", "cucumber"])
|
| 227 |
+
with pytest.raises(TypeError, match=msg):
|
| 228 |
+
ser.searchsorted(["bread", "cucumber"])
|
| 229 |
+
|
| 230 |
+
def test_unique(self, ordered):
|
| 231 |
+
# GH38140
|
| 232 |
+
dtype = CategoricalDtype(["a", "b", "c"], ordered=ordered)
|
| 233 |
+
|
| 234 |
+
# categories are reordered based on value when ordered=False
|
| 235 |
+
cat = Categorical(["a", "b", "c"], dtype=dtype)
|
| 236 |
+
res = cat.unique()
|
| 237 |
+
tm.assert_categorical_equal(res, cat)
|
| 238 |
+
|
| 239 |
+
cat = Categorical(["a", "b", "a", "a"], dtype=dtype)
|
| 240 |
+
res = cat.unique()
|
| 241 |
+
tm.assert_categorical_equal(res, Categorical(["a", "b"], dtype=dtype))
|
| 242 |
+
|
| 243 |
+
cat = Categorical(["c", "a", "b", "a", "a"], dtype=dtype)
|
| 244 |
+
res = cat.unique()
|
| 245 |
+
exp_cat = Categorical(["c", "a", "b"], dtype=dtype)
|
| 246 |
+
tm.assert_categorical_equal(res, exp_cat)
|
| 247 |
+
|
| 248 |
+
# nan must be removed
|
| 249 |
+
cat = Categorical(["b", np.nan, "b", np.nan, "a"], dtype=dtype)
|
| 250 |
+
res = cat.unique()
|
| 251 |
+
exp_cat = Categorical(["b", np.nan, "a"], dtype=dtype)
|
| 252 |
+
tm.assert_categorical_equal(res, exp_cat)
|
| 253 |
+
|
| 254 |
+
def test_unique_index_series(self, ordered):
|
| 255 |
+
# GH38140
|
| 256 |
+
dtype = CategoricalDtype([3, 2, 1], ordered=ordered)
|
| 257 |
+
|
| 258 |
+
c = Categorical([3, 1, 2, 2, 1], dtype=dtype)
|
| 259 |
+
# Categorical.unique sorts categories by appearance order
|
| 260 |
+
# if ordered=False
|
| 261 |
+
exp = Categorical([3, 1, 2], dtype=dtype)
|
| 262 |
+
tm.assert_categorical_equal(c.unique(), exp)
|
| 263 |
+
|
| 264 |
+
tm.assert_index_equal(Index(c).unique(), Index(exp))
|
| 265 |
+
tm.assert_categorical_equal(Series(c).unique(), exp)
|
| 266 |
+
|
| 267 |
+
c = Categorical([1, 1, 2, 2], dtype=dtype)
|
| 268 |
+
exp = Categorical([1, 2], dtype=dtype)
|
| 269 |
+
tm.assert_categorical_equal(c.unique(), exp)
|
| 270 |
+
tm.assert_index_equal(Index(c).unique(), Index(exp))
|
| 271 |
+
tm.assert_categorical_equal(Series(c).unique(), exp)
|
| 272 |
+
|
| 273 |
+
def test_shift(self):
|
| 274 |
+
# GH 9416
|
| 275 |
+
cat = Categorical(["a", "b", "c", "d", "a"])
|
| 276 |
+
|
| 277 |
+
# shift forward
|
| 278 |
+
sp1 = cat.shift(1)
|
| 279 |
+
xp1 = Categorical([np.nan, "a", "b", "c", "d"])
|
| 280 |
+
tm.assert_categorical_equal(sp1, xp1)
|
| 281 |
+
tm.assert_categorical_equal(cat[:-1], sp1[1:])
|
| 282 |
+
|
| 283 |
+
# shift back
|
| 284 |
+
sn2 = cat.shift(-2)
|
| 285 |
+
xp2 = Categorical(
|
| 286 |
+
["c", "d", "a", np.nan, np.nan], categories=["a", "b", "c", "d"]
|
| 287 |
+
)
|
| 288 |
+
tm.assert_categorical_equal(sn2, xp2)
|
| 289 |
+
tm.assert_categorical_equal(cat[2:], sn2[:-2])
|
| 290 |
+
|
| 291 |
+
# shift by zero
|
| 292 |
+
tm.assert_categorical_equal(cat, cat.shift(0))
|
| 293 |
+
|
| 294 |
+
def test_nbytes(self):
|
| 295 |
+
cat = Categorical([1, 2, 3])
|
| 296 |
+
exp = 3 + 3 * 8 # 3 int8s for values + 3 int64s for categories
|
| 297 |
+
assert cat.nbytes == exp
|
| 298 |
+
|
| 299 |
+
def test_memory_usage(self):
|
| 300 |
+
cat = Categorical([1, 2, 3])
|
| 301 |
+
|
| 302 |
+
# .categories is an index, so we include the hashtable
|
| 303 |
+
assert 0 < cat.nbytes <= cat.memory_usage()
|
| 304 |
+
assert 0 < cat.nbytes <= cat.memory_usage(deep=True)
|
| 305 |
+
|
| 306 |
+
cat = Categorical(["foo", "foo", "bar"])
|
| 307 |
+
assert cat.memory_usage(deep=True) > cat.nbytes
|
| 308 |
+
|
| 309 |
+
if not PYPY:
|
| 310 |
+
# sys.getsizeof will call the .memory_usage with
|
| 311 |
+
# deep=True, and add on some GC overhead
|
| 312 |
+
diff = cat.memory_usage(deep=True) - sys.getsizeof(cat)
|
| 313 |
+
assert abs(diff) < 100
|
| 314 |
+
|
| 315 |
+
def test_map(self):
|
| 316 |
+
c = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)
|
| 317 |
+
result = c.map(lambda x: x.lower(), na_action=None)
|
| 318 |
+
exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)
|
| 319 |
+
tm.assert_categorical_equal(result, exp)
|
| 320 |
+
|
| 321 |
+
c = Categorical(list("ABABC"), categories=list("ABC"), ordered=False)
|
| 322 |
+
result = c.map(lambda x: x.lower(), na_action=None)
|
| 323 |
+
exp = Categorical(list("ababc"), categories=list("abc"), ordered=False)
|
| 324 |
+
tm.assert_categorical_equal(result, exp)
|
| 325 |
+
|
| 326 |
+
result = c.map(lambda x: 1, na_action=None)
|
| 327 |
+
# GH 12766: Return an index not an array
|
| 328 |
+
tm.assert_index_equal(result, Index(np.array([1] * 5, dtype=np.int64)))
|
| 329 |
+
|
| 330 |
+
@pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
|
| 331 |
+
def test_validate_inplace_raises(self, value):
|
| 332 |
+
cat = Categorical(["A", "B", "B", "C", "A"])
|
| 333 |
+
msg = (
|
| 334 |
+
'For argument "inplace" expected type bool, '
|
| 335 |
+
f"received type {type(value).__name__}"
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
with pytest.raises(ValueError, match=msg):
|
| 339 |
+
cat.sort_values(inplace=value)
|
| 340 |
+
|
| 341 |
+
def test_quantile_empty(self):
|
| 342 |
+
# make sure we have correct itemsize on resulting codes
|
| 343 |
+
cat = Categorical(["A", "B"])
|
| 344 |
+
idx = Index([0.0, 0.5])
|
| 345 |
+
result = cat[:0]._quantile(idx, interpolation="linear")
|
| 346 |
+
assert result._codes.dtype == np.int8
|
| 347 |
+
|
| 348 |
+
expected = cat.take([-1, -1], allow_fill=True)
|
| 349 |
+
tm.assert_extension_array_equal(result, expected)
|
shared/package-files/06/066c81b911f49e5598b2e87dfb479255d510566dd924aa93fd5a6add20976c9d/to_sparse_csr_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API to_sparse_csr {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, ::std::optional<int64_t>);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::to_sparse_csr";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self, ::std::optional<int64_t> dense_dim);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional<int64_t> dense_dim);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/06/066ed109d0c499f2a2a7921b77a783b12df960571d6d4a0ffdbd1ed18626ff59/chunk_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API ::std::vector<at::Tensor> chunk(const at::Tensor & self, int64_t chunks, int64_t dim=0);
|
| 20 |
+
TORCH_API ::std::vector<at::Tensor> chunk_nested_tensor(const at::Tensor & self, int64_t chunks, int64_t dim=0);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/06/0673e3297b7562438e66345a6236554a77c4996cc05222c00a07f1db6e1f4d85/__init__.cpython-311.pyc
ADDED
|
Binary file (477 Bytes). View file
|
|
|
shared/package-files/06/0675df29e6744f7d3cf74a1d1914541bbc58ad9a356ae968becbda190443427f/miopen-wrapper.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <miopen/miopen.h>
|
| 4 |
+
#include <miopen/version.h>
|
| 5 |
+
|
| 6 |
+
#if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4)
|
| 7 |
+
// miopen 3.4 moved find mode from private header to public header
|
| 8 |
+
#else
|
| 9 |
+
// from miopen_internal.h
|
| 10 |
+
extern "C" {
|
| 11 |
+
|
| 12 |
+
typedef enum
|
| 13 |
+
{
|
| 14 |
+
miopenConvolutionFindModeNormal = 1, /*!< Normal mode */
|
| 15 |
+
} miopenConvolutionFindMode_t;
|
| 16 |
+
|
| 17 |
+
miopenStatus_t miopenSetConvolutionFindMode(
|
| 18 |
+
miopenConvolutionDescriptor_t convDesc,
|
| 19 |
+
miopenConvolutionFindMode_t findMode);
|
| 20 |
+
}
|
| 21 |
+
#endif
|
shared/package-files/06/067c5d6843ebd6f78ce0acad16f76d837dc8ead8360f8cb2f7595f673df3ea76/partitions_.cpython-311.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
shared/package-files/06/067cdb6f68dc14e79c7b002446e9c7ebdd8b1cf2203e76676f4bde3fd4084305/kai_ukernel_interface.h
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <ATen/Config.h>
|
| 3 |
+
#include <unordered_map>
|
| 4 |
+
#if AT_KLEIDIAI_ENABLED()
|
| 5 |
+
|
| 6 |
+
#include <kai_common.h>
|
| 7 |
+
#include <kai_lhs_quant_pack_qai8dxp_f32.h>
|
| 8 |
+
#include <kai_matmul_clamp_f32_qai8dxp1x8_qsi4c32p8x8_1x8x32_neon_dotprod.h>
|
| 9 |
+
#include <kai_matmul_clamp_f32_qai8dxp1x8_qsi4cxp8x8_1x8x32_neon_dotprod.h>
|
| 10 |
+
#include <kai_matmul_clamp_f32_qai8dxp4x8_qsi4c32p8x8_4x8x32_neon_i8mm.h>
|
| 11 |
+
#include <kai_matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm.h>
|
| 12 |
+
#include <kai_matmul_clamp_f32_qai8dxp_qsi4c32p_interface.h>
|
| 13 |
+
#include <kai_matmul_clamp_f32_qai8dxp_qsi4cxp_interface.h>
|
| 14 |
+
#include <kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0.h>
|
| 15 |
+
#include <kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0.h>
|
| 16 |
+
|
| 17 |
+
namespace at::native::kleidiai {
|
| 18 |
+
|
| 19 |
+
enum class kai_kernel_id {
|
| 20 |
+
matmul_clamp_f32_qai8dxp1x8_qsi4c32p8x8_1x8x32_neon_dotprod =
|
| 21 |
+
0, // Groupwise 4 bit GEMV
|
| 22 |
+
matmul_clamp_f32_qai8dxp4x8_qsi4c32p4x8_4x8x32_neon_i8mm =
|
| 23 |
+
1, // Groupwise 4 bit GEMM
|
| 24 |
+
matmul_clamp_f32_qai8dxp1x8_qsi4cxp8x8_1x8x32_neon_dotprod =
|
| 25 |
+
2, // Channelwise 4 bit GEMV
|
| 26 |
+
matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm =
|
| 27 |
+
3 // Channelwise 4 bit GEMM
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
// Channelwise Kernel mapping
|
| 31 |
+
struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp {
|
| 32 |
+
struct kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel ukernel;
|
| 33 |
+
struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params rhs_pack_params;
|
| 34 |
+
size_t (*kai_get_lhs_packed_size)(
|
| 35 |
+
size_t m,
|
| 36 |
+
size_t k,
|
| 37 |
+
size_t mr,
|
| 38 |
+
size_t kr,
|
| 39 |
+
size_t sr);
|
| 40 |
+
size_t (*kai_get_rhs_packed_size)(
|
| 41 |
+
size_t n,
|
| 42 |
+
size_t k,
|
| 43 |
+
size_t nr,
|
| 44 |
+
size_t kr,
|
| 45 |
+
size_t sr);
|
| 46 |
+
void (*kai_run_lhs_quant_pack)(
|
| 47 |
+
size_t m,
|
| 48 |
+
size_t k,
|
| 49 |
+
size_t mr,
|
| 50 |
+
size_t kr,
|
| 51 |
+
size_t sr,
|
| 52 |
+
size_t m_idx_start,
|
| 53 |
+
const float* lhs,
|
| 54 |
+
size_t lhs_stride,
|
| 55 |
+
void* lhs_packed);
|
| 56 |
+
void (*kai_run_rhs_pack)(
|
| 57 |
+
size_t num_groups,
|
| 58 |
+
size_t n,
|
| 59 |
+
size_t k,
|
| 60 |
+
size_t nr,
|
| 61 |
+
size_t kr,
|
| 62 |
+
size_t sr,
|
| 63 |
+
const uint8_t* rhs,
|
| 64 |
+
const float* bias,
|
| 65 |
+
const float* scale,
|
| 66 |
+
void* rhs_packed,
|
| 67 |
+
size_t extra_bytes,
|
| 68 |
+
const struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params* params);
|
| 69 |
+
|
| 70 |
+
kai_matmul_ukernel_f32_qa8dxp_qs4cxp(
|
| 71 |
+
const kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel& kernel)
|
| 72 |
+
: ukernel(kernel),
|
| 73 |
+
kai_get_lhs_packed_size(
|
| 74 |
+
&kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32),
|
| 75 |
+
kai_get_rhs_packed_size(
|
| 76 |
+
&kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qs4cxs1s0),
|
| 77 |
+
kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32),
|
| 78 |
+
kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4cxp_qs4cxs1s0) {}
|
| 79 |
+
};
|
| 80 |
+
|
| 81 |
+
struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp
|
| 82 |
+
kai_select_channelwise_matmul_ukernel(const kai_kernel_id id);
|
| 83 |
+
|
| 84 |
+
// Groupwise Kernel mapping
|
| 85 |
+
struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p {
|
| 86 |
+
struct kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel ukernel;
|
| 87 |
+
struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params rhs_pack_params;
|
| 88 |
+
size_t (*kai_get_lhs_packed_size)(
|
| 89 |
+
size_t m,
|
| 90 |
+
size_t k,
|
| 91 |
+
size_t mr,
|
| 92 |
+
size_t kr,
|
| 93 |
+
size_t sr);
|
| 94 |
+
size_t (*kai_get_rhs_packed_size)(
|
| 95 |
+
size_t n,
|
| 96 |
+
size_t k,
|
| 97 |
+
size_t nr,
|
| 98 |
+
size_t kr,
|
| 99 |
+
size_t sr,
|
| 100 |
+
size_t bl,
|
| 101 |
+
enum kai_datatype scale_dt);
|
| 102 |
+
void (*kai_run_lhs_quant_pack)(
|
| 103 |
+
size_t m,
|
| 104 |
+
size_t k,
|
| 105 |
+
size_t mr,
|
| 106 |
+
size_t kr,
|
| 107 |
+
size_t sr,
|
| 108 |
+
size_t m_idx_start,
|
| 109 |
+
const float* lhs,
|
| 110 |
+
size_t lhs_stride,
|
| 111 |
+
void* lhs_packed);
|
| 112 |
+
void (*kai_run_rhs_pack)(
|
| 113 |
+
size_t num_groups,
|
| 114 |
+
size_t n,
|
| 115 |
+
size_t k,
|
| 116 |
+
size_t nr,
|
| 117 |
+
size_t kr,
|
| 118 |
+
size_t sr,
|
| 119 |
+
size_t bl,
|
| 120 |
+
const uint8_t* rhs,
|
| 121 |
+
size_t rhs_stride,
|
| 122 |
+
const float* bias,
|
| 123 |
+
const void* scale,
|
| 124 |
+
size_t scale_stride,
|
| 125 |
+
void* rhs_packed,
|
| 126 |
+
size_t extra_bytes,
|
| 127 |
+
const struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params* params);
|
| 128 |
+
|
| 129 |
+
kai_matmul_ukernel_f32_qa8dxp_qs4c32p(
|
| 130 |
+
const kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel& kernel)
|
| 131 |
+
: ukernel(kernel),
|
| 132 |
+
kai_get_lhs_packed_size(
|
| 133 |
+
&kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32),
|
| 134 |
+
kai_get_rhs_packed_size(
|
| 135 |
+
&kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0),
|
| 136 |
+
kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32),
|
| 137 |
+
kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0) {}
|
| 138 |
+
};
|
| 139 |
+
|
| 140 |
+
struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p kai_select_groupwise_matmul_ukernel(
|
| 141 |
+
const kai_kernel_id id);
|
| 142 |
+
|
| 143 |
+
} // namespace at::native::kleidiai
|
| 144 |
+
#endif
|
shared/package-files/06/067ebb0bc1123126935f9a875c987589046a7f9ba72077bb4ca1521d7cfebfab/test_subscheck.cpython-311.pyc
ADDED
|
Binary file (47.5 kB). View file
|
|
|
shared/package-files/06/0687d2136038b7793c2af2430cf4b4e4e3bcad231462398e66fba772959436d1/_utils.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from typing import cast
|
| 5 |
+
|
| 6 |
+
from . import api, TensorPipeAgent
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@contextmanager
|
| 13 |
+
def _group_membership_management(store, name, is_join):
|
| 14 |
+
token_key = "RpcGroupManagementToken"
|
| 15 |
+
join_or_leave = "join" if is_join else "leave"
|
| 16 |
+
my_token = f"Token_for_{name}_{join_or_leave}"
|
| 17 |
+
while True:
|
| 18 |
+
# Retrieve token from store to signal start of rank join/leave critical section
|
| 19 |
+
returned = store.compare_set(token_key, "", my_token).decode()
|
| 20 |
+
if returned == my_token:
|
| 21 |
+
# Yield to the function this context manager wraps
|
| 22 |
+
yield
|
| 23 |
+
# Finished, now exit and release token
|
| 24 |
+
# Update from store to signal end of rank join/leave critical section
|
| 25 |
+
store.set(token_key, "")
|
| 26 |
+
# Other will wait for this token to be set before they execute
|
| 27 |
+
store.set(my_token, "Done")
|
| 28 |
+
break
|
| 29 |
+
else:
|
| 30 |
+
# Store will wait for the token to be released
|
| 31 |
+
try:
|
| 32 |
+
store.wait([returned])
|
| 33 |
+
except RuntimeError:
|
| 34 |
+
logger.error(
|
| 35 |
+
"Group membership token %s timed out waiting for %s to be released.",
|
| 36 |
+
my_token,
|
| 37 |
+
returned,
|
| 38 |
+
)
|
| 39 |
+
raise
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _update_group_membership(worker_info, my_devices, reverse_device_map, is_join):
|
| 43 |
+
agent = cast(TensorPipeAgent, api._get_current_rpc_agent())
|
| 44 |
+
ret = agent._update_group_membership(
|
| 45 |
+
worker_info, my_devices, reverse_device_map, is_join
|
| 46 |
+
)
|
| 47 |
+
return ret
|
shared/package-files/06/068a1600b0d6013bd9ba925a2fbf8615045060ea2d35efc5cb5d48e4d1a1d850/mma.h
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* NOTICE TO LICENSEE:
|
| 5 |
+
*
|
| 6 |
+
* This source code and/or documentation ("Licensed Deliverables") are
|
| 7 |
+
* subject to NVIDIA intellectual property rights under U.S. and
|
| 8 |
+
* international Copyright laws.
|
| 9 |
+
*
|
| 10 |
+
* These Licensed Deliverables contained herein is PROPRIETARY and
|
| 11 |
+
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
|
| 12 |
+
* conditions of a form of NVIDIA software license agreement by and
|
| 13 |
+
* between NVIDIA and Licensee ("License Agreement") or electronically
|
| 14 |
+
* accepted by Licensee. Notwithstanding any terms or conditions to
|
| 15 |
+
* the contrary in the License Agreement, reproduction or disclosure
|
| 16 |
+
* of the Licensed Deliverables to any third party without the express
|
| 17 |
+
* written consent of NVIDIA is prohibited.
|
| 18 |
+
*
|
| 19 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 20 |
+
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
|
| 21 |
+
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
|
| 22 |
+
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
|
| 23 |
+
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
|
| 24 |
+
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
|
| 25 |
+
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
|
| 26 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 27 |
+
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
|
| 28 |
+
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
|
| 29 |
+
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 30 |
+
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 31 |
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 32 |
+
* OF THESE LICENSED DELIVERABLES.
|
| 33 |
+
*
|
| 34 |
+
* U.S. Government End Users. These Licensed Deliverables are a
|
| 35 |
+
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
|
| 36 |
+
* 1995), consisting of "commercial computer software" and "commercial
|
| 37 |
+
* computer software documentation" as such terms are used in 48
|
| 38 |
+
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
|
| 39 |
+
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
|
| 40 |
+
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
|
| 41 |
+
* U.S. Government End Users acquire the Licensed Deliverables with
|
| 42 |
+
* only those rights set forth herein.
|
| 43 |
+
*
|
| 44 |
+
* Any use of the Licensed Deliverables in individual and commercial
|
| 45 |
+
* software must include, in the user documentation and internal
|
| 46 |
+
* comments to the code, the above Disclaimer and U.S. Government End
|
| 47 |
+
* Users Notice.
|
| 48 |
+
*/
|
| 49 |
+
|
| 50 |
+
#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__)
|
| 51 |
+
#if defined(_MSC_VER)
|
| 52 |
+
#pragma message("crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead.")
|
| 53 |
+
#else
|
| 54 |
+
#warning "crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead."
|
| 55 |
+
#endif
|
| 56 |
+
#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__
|
| 57 |
+
#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__
|
| 58 |
+
#endif
|
| 59 |
+
|
| 60 |
+
#if !defined(__CUDA_MMA_H__)
|
| 61 |
+
#define __CUDA_MMA_H__
|
| 62 |
+
|
| 63 |
+
#include <cuda_fp16.h>
|
| 64 |
+
#include <cuda_bf16.h>
|
| 65 |
+
|
| 66 |
+
#define __CUDA_MMA_DEVICE_DECL__ static __device__ __inline__
|
| 67 |
+
|
| 68 |
+
#if defined(__cplusplus) && defined(__CUDACC__)
|
| 69 |
+
|
| 70 |
+
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA)
|
| 74 |
+
#define __DEF_IF_HOST { }
|
| 75 |
+
#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */
|
| 76 |
+
#define __DEF_IF_HOST ;
|
| 77 |
+
#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */
|
| 78 |
+
|
| 79 |
+
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720
|
| 80 |
+
#define __CUDA_IMMA__ 1
|
| 81 |
+
#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 */
|
| 82 |
+
|
| 83 |
+
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730
|
| 84 |
+
#define __CUDA_SUBBYTE_IMMA__ 1
|
| 85 |
+
#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 */
|
| 86 |
+
|
| 87 |
+
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
|
| 88 |
+
#define __CUDA_AMPERE_MMA__ 1
|
| 89 |
+
#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 */
|
| 90 |
+
|
| 91 |
+
namespace nvcuda {
|
| 92 |
+
namespace wmma {
|
| 93 |
+
|
| 94 |
+
// utility functions
|
| 95 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 96 |
+
inline __device__ float __float_to_tf32(float in)
|
| 97 |
+
{
|
| 98 |
+
float ret;
|
| 99 |
+
asm("{\n .reg .b32 __$1;"
|
| 100 |
+
"\n cvt.rna.tf32.f32 __$1, %1;"
|
| 101 |
+
"\n mov.b32 %0, __$1;\n}\n" : "=f"(ret) : "f"(in) );
|
| 102 |
+
return ret;
|
| 103 |
+
}
|
| 104 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 105 |
+
|
| 106 |
+
//
|
| 107 |
+
// tags
|
| 108 |
+
//
|
| 109 |
+
struct row_major;
|
| 110 |
+
struct col_major;
|
| 111 |
+
struct matrix_a;
|
| 112 |
+
struct matrix_b;
|
| 113 |
+
struct accumulator;
|
| 114 |
+
|
| 115 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 116 |
+
namespace precision {
|
| 117 |
+
struct tf32;
|
| 118 |
+
}
|
| 119 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 120 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 121 |
+
namespace experimental {
|
| 122 |
+
namespace precision {
|
| 123 |
+
struct u4; // 4-bit unsigned
|
| 124 |
+
struct s4; // 4-bit signed
|
| 125 |
+
struct b1; // 1-bit
|
| 126 |
+
}
|
| 127 |
+
enum bmmaBitOp { bmmaBitOpXOR = 1
|
| 128 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 129 |
+
, bmmaBitOpAND = 2
|
| 130 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 131 |
+
};
|
| 132 |
+
enum bmmaAccumulateOp { bmmaAccumulateOpPOPC = 1 };
|
| 133 |
+
}
|
| 134 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 135 |
+
|
| 136 |
+
//
|
| 137 |
+
// layout
|
| 138 |
+
//
|
| 139 |
+
enum layout_t {
|
| 140 |
+
mem_row_major, mem_col_major
|
| 141 |
+
};
|
| 142 |
+
|
| 143 |
+
template <typename T>
|
| 144 |
+
struct helper_traits {
|
| 145 |
+
typedef T element_type;
|
| 146 |
+
typedef T storage_element_type;
|
| 147 |
+
typedef T fill_argument_type;
|
| 148 |
+
};
|
| 149 |
+
|
| 150 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 151 |
+
template<> struct helper_traits<experimental::precision::u4> {
|
| 152 |
+
typedef experimental::precision::u4 element_type;
|
| 153 |
+
typedef unsigned int storage_element_type;
|
| 154 |
+
typedef unsigned int fill_argument_type;
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
+
template<> struct helper_traits<experimental::precision::s4> {
|
| 158 |
+
typedef experimental::precision::s4 element_type;
|
| 159 |
+
typedef int storage_element_type;
|
| 160 |
+
typedef int fill_argument_type;
|
| 161 |
+
};
|
| 162 |
+
|
| 163 |
+
template<> struct helper_traits<experimental::precision::b1> {
|
| 164 |
+
typedef experimental::precision::b1 element_type;
|
| 165 |
+
typedef unsigned int storage_element_type;
|
| 166 |
+
typedef unsigned int fill_argument_type;
|
| 167 |
+
};
|
| 168 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 169 |
+
|
| 170 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 171 |
+
template<> struct helper_traits<precision::tf32> {
|
| 172 |
+
typedef precision::tf32 element_type;
|
| 173 |
+
typedef float storage_element_type;
|
| 174 |
+
typedef float fill_argument_type;
|
| 175 |
+
};
|
| 176 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 177 |
+
|
| 178 |
+
#if defined(_MSC_VER)
|
| 179 |
+
#pragma warning(push)
|
| 180 |
+
#pragma warning(disable:4324)
|
| 181 |
+
#endif
|
| 182 |
+
//
|
| 183 |
+
// The base fragment type
|
| 184 |
+
//
|
| 185 |
+
/* note: alignment required for compiler implementation */
|
| 186 |
+
template <typename T, int size, int packed_size = size>
|
| 187 |
+
struct __align__(8) __frag_base {
|
| 188 |
+
|
| 189 |
+
/* Number of elements in the fragment */
|
| 190 |
+
enum {num_elements = size};
|
| 191 |
+
|
| 192 |
+
/* Number of storage elements in the fragment.
|
| 193 |
+
|
| 194 |
+
The elements of the fragment are packed together when the
|
| 195 |
+
fragment element type is experimental::precision::u4,
|
| 196 |
+
experimental::precision::s4 or experimental::precision::b1.
|
| 197 |
+
When elements are packed, num_storage_elements
|
| 198 |
+
will be smaller than num_elements.
|
| 199 |
+
*/
|
| 200 |
+
enum {num_storage_elements = packed_size};
|
| 201 |
+
|
| 202 |
+
/* element type of the fragment */
|
| 203 |
+
typedef T element_type;
|
| 204 |
+
|
| 205 |
+
/* element type of the storage representation.
|
| 206 |
+
|
| 207 |
+
The mapping from element_type to storage_element_type is as follows:
|
| 208 |
+
experimental::precision::u4 -> unsigned (8 elements in 1 storage element)
|
| 209 |
+
experimental::precision::s4 -> int (8 elements in 1 storage element)
|
| 210 |
+
experimental::precision::b1 -> unsigned (32 elements in 1 storage element)
|
| 211 |
+
precision::tf32 -> float (1 element in 1 storage element)
|
| 212 |
+
all other types T -> T
|
| 213 |
+
*/
|
| 214 |
+
typedef typename helper_traits<T>::storage_element_type storage_element_type;
|
| 215 |
+
|
| 216 |
+
/* Storage for the (possibly packed) fragment elements. */
|
| 217 |
+
storage_element_type x[num_storage_elements];
|
| 218 |
+
};
|
| 219 |
+
#if defined(_MSC_VER)
|
| 220 |
+
#pragma warning(pop)
|
| 221 |
+
#endif
|
| 222 |
+
|
| 223 |
+
template <typename FragEleType, typename StorageType, typename ArgType>
|
| 224 |
+
static inline __device__ StorageType __get_storage_value(ArgType in) { return in; }
|
| 225 |
+
|
| 226 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 227 |
+
template<>
|
| 228 |
+
__device__ inline unsigned
|
| 229 |
+
__get_storage_value<experimental::precision::u4, unsigned, unsigned>(unsigned in)
|
| 230 |
+
{
|
| 231 |
+
/* For experimental::precision::u4 fragment element type, pack 8 elements into a single
|
| 232 |
+
32-bit unsigned int storage element */
|
| 233 |
+
unsigned val = in & 0xf;
|
| 234 |
+
return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) |
|
| 235 |
+
(val << 20) | (val << 24) | (val << 28));
|
| 236 |
+
};
|
| 237 |
+
|
| 238 |
+
template<>
|
| 239 |
+
__device__ inline int
|
| 240 |
+
__get_storage_value<experimental::precision::s4, int, int>(int in)
|
| 241 |
+
{
|
| 242 |
+
/* For experimental::precision::s4 fragment element type, pack 8 elements into a single
|
| 243 |
+
32-bit signed int storage element */
|
| 244 |
+
int val = in & 0xf;
|
| 245 |
+
return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) |
|
| 246 |
+
(val << 20) | (val << 24) | (val << 28));
|
| 247 |
+
};
|
| 248 |
+
|
| 249 |
+
template<>
|
| 250 |
+
__device__ inline unsigned
|
| 251 |
+
__get_storage_value<experimental::precision::b1, unsigned, unsigned>(unsigned in)
|
| 252 |
+
{
|
| 253 |
+
/* For experimental::precision::b1 fragment element type, pack 32 elements into a
|
| 254 |
+
single 32-bit unsigned int storage element */
|
| 255 |
+
return (in & 0x1) ? 0xFFFFFFFFU : 0;
|
| 256 |
+
}
|
| 257 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 258 |
+
|
| 259 |
+
template <typename FragEleType, int size, int packed_size>
|
| 260 |
+
__CUDA_MMA_DEVICE_DECL__ void fill_fragment(__frag_base<FragEleType, size, packed_size>& f,
|
| 261 |
+
/* The mapping from fragment element type (FragEleType) to fill_argument_type is:
|
| 262 |
+
experimental::precision::u4 -> unsigned (only lower 4 bits taken)
|
| 263 |
+
experimental::precision::s4 -> int (only lower 4 bits taken)
|
| 264 |
+
experimental::precision::b1 -> unsigned (only lowest 1 bit taken)
|
| 265 |
+
precision::tf32 -> float
|
| 266 |
+
all other types T -> T
|
| 267 |
+
*/
|
| 268 |
+
const typename helper_traits<FragEleType>::fill_argument_type & in) {
|
| 269 |
+
|
| 270 |
+
/* get the (possibly packed) storage element value. See the specializations above for fragment
|
| 271 |
+
element types where the storage representation is packed */
|
| 272 |
+
typedef typename helper_traits<FragEleType>::storage_element_type storage_type;
|
| 273 |
+
storage_type v = __get_storage_value<FragEleType, storage_type>(in);
|
| 274 |
+
#pragma unroll
|
| 275 |
+
for (int i=0; i< f.num_storage_elements; i++)
|
| 276 |
+
f.x[i] = v;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
//
|
| 280 |
+
// Fragment template
|
| 281 |
+
//
|
| 282 |
+
template<typename Use, int m, int n, int k, typename T, typename Layout=void> class fragment;
|
| 283 |
+
|
| 284 |
+
//
|
| 285 |
+
// Fragments for 16x16x16
|
| 286 |
+
//
|
| 287 |
+
template<> class fragment<matrix_a, 16, 16, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 288 |
+
template<> class fragment<matrix_a, 16, 16, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 289 |
+
template<> class fragment<matrix_b, 16, 16, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 290 |
+
template<> class fragment<matrix_b, 16, 16, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 291 |
+
template<> class fragment<accumulator, 16, 16, 16, __half> : public __frag_base<__half, 8> {};
|
| 292 |
+
template<> class fragment<accumulator, 16, 16, 16, float> : public __frag_base<float, 8> {};
|
| 293 |
+
|
| 294 |
+
#ifdef __CUDA_IMMA__
|
| 295 |
+
template<> class fragment<matrix_a, 16, 16, 16, signed char, row_major> : public __frag_base<signed char, 8> {};
|
| 296 |
+
template<> class fragment<matrix_a, 16, 16, 16, signed char, col_major> : public __frag_base<signed char, 8> {};
|
| 297 |
+
template<> class fragment<matrix_a, 16, 16, 16, unsigned char, row_major> : public __frag_base<unsigned char, 8> {};
|
| 298 |
+
template<> class fragment<matrix_a, 16, 16, 16, unsigned char, col_major> : public __frag_base<unsigned char, 8> {};
|
| 299 |
+
template<> class fragment<matrix_b, 16, 16, 16, signed char, row_major> : public __frag_base<signed char, 8> {};
|
| 300 |
+
template<> class fragment<matrix_b, 16, 16, 16, signed char, col_major> : public __frag_base<signed char, 8> {};
|
| 301 |
+
template<> class fragment<matrix_b, 16, 16, 16, unsigned char, row_major> : public __frag_base<unsigned char, 8> {};
|
| 302 |
+
template<> class fragment<matrix_b, 16, 16, 16, unsigned char, col_major> : public __frag_base<unsigned char, 8> {};
|
| 303 |
+
template<> class fragment<accumulator, 16, 16, 16, int> : public __frag_base<int, 8> {};
|
| 304 |
+
#endif /* __CUDA_IMMA__ */
|
| 305 |
+
|
| 306 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 307 |
+
template<> class fragment<matrix_a, 16, 16, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 8> {};
|
| 308 |
+
template<> class fragment<matrix_a, 16, 16, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 8> {};
|
| 309 |
+
template<> class fragment<matrix_b, 16, 16, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 8> {};
|
| 310 |
+
template<> class fragment<matrix_b, 16, 16, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 8> {};
|
| 311 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 312 |
+
|
| 313 |
+
//
|
| 314 |
+
// Fragments for 32x8x16
|
| 315 |
+
//
|
| 316 |
+
template<> class fragment<matrix_a, 32, 8, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 317 |
+
template<> class fragment<matrix_a, 32, 8, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 318 |
+
template<> class fragment<matrix_b, 32, 8, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 319 |
+
template<> class fragment<matrix_b, 32, 8, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 320 |
+
template<> class fragment<accumulator, 32, 8, 16, __half> : public __frag_base<__half, 8> {};
|
| 321 |
+
template<> class fragment<accumulator, 32, 8, 16, float> : public __frag_base<float, 8> {};
|
| 322 |
+
|
| 323 |
+
#ifdef __CUDA_IMMA__
|
| 324 |
+
template<> class fragment<matrix_a, 32, 8, 16, signed char, row_major> : public __frag_base<signed char, 16> {};
|
| 325 |
+
template<> class fragment<matrix_a, 32, 8, 16, signed char, col_major> : public __frag_base<signed char, 16> {};
|
| 326 |
+
template<> class fragment<matrix_a, 32, 8, 16, unsigned char, row_major> : public __frag_base<unsigned char, 16> {};
|
| 327 |
+
template<> class fragment<matrix_a, 32, 8, 16, unsigned char, col_major> : public __frag_base<unsigned char, 16> {};
|
| 328 |
+
template<> class fragment<matrix_b, 32, 8, 16, signed char, row_major> : public __frag_base<signed char, 4> {};
|
| 329 |
+
template<> class fragment<matrix_b, 32, 8, 16, signed char, col_major> : public __frag_base<signed char, 4> {};
|
| 330 |
+
template<> class fragment<matrix_b, 32, 8, 16, unsigned char, row_major> : public __frag_base<unsigned char, 4> {};
|
| 331 |
+
template<> class fragment<matrix_b, 32, 8, 16, unsigned char, col_major> : public __frag_base<unsigned char, 4> {};
|
| 332 |
+
template<> class fragment<accumulator, 32, 8, 16, int> : public __frag_base<int, 8> {};
|
| 333 |
+
#endif /* __CUDA_IMMA__ */
|
| 334 |
+
|
| 335 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 336 |
+
template<> class fragment<matrix_a, 32, 8, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 16> {};
|
| 337 |
+
template<> class fragment<matrix_a, 32, 8, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 16> {};
|
| 338 |
+
template<> class fragment<matrix_b, 32, 8, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 4> {};
|
| 339 |
+
template<> class fragment<matrix_b, 32, 8, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 4> {};
|
| 340 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 341 |
+
|
| 342 |
+
//
|
| 343 |
+
// Fragments for 8x32x16
|
| 344 |
+
//
|
| 345 |
+
template<> class fragment<matrix_a, 8, 32, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 346 |
+
template<> class fragment<matrix_a, 8, 32, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 347 |
+
template<> class fragment<matrix_b, 8, 32, 16, __half, row_major> : public __frag_base<__half, 16> {};
|
| 348 |
+
template<> class fragment<matrix_b, 8, 32, 16, __half, col_major> : public __frag_base<__half, 16> {};
|
| 349 |
+
template<> class fragment<accumulator, 8, 32, 16, __half> : public __frag_base<__half, 8> {};
|
| 350 |
+
template<> class fragment<accumulator, 8, 32, 16, float> : public __frag_base<float, 8> {};
|
| 351 |
+
|
| 352 |
+
#ifdef __CUDA_IMMA__
|
| 353 |
+
template<> class fragment<matrix_a, 8, 32, 16, signed char, row_major> : public __frag_base<signed char, 4> {};
|
| 354 |
+
template<> class fragment<matrix_a, 8, 32, 16, signed char, col_major> : public __frag_base<signed char, 4> {};
|
| 355 |
+
template<> class fragment<matrix_a, 8, 32, 16, unsigned char, row_major> : public __frag_base<unsigned char, 4> {};
|
| 356 |
+
template<> class fragment<matrix_a, 8, 32, 16, unsigned char, col_major> : public __frag_base<unsigned char, 4> {};
|
| 357 |
+
template<> class fragment<matrix_b, 8, 32, 16, signed char, row_major> : public __frag_base<signed char, 16> {};
|
| 358 |
+
template<> class fragment<matrix_b, 8, 32, 16, signed char, col_major> : public __frag_base<signed char, 16> {};
|
| 359 |
+
template<> class fragment<matrix_b, 8, 32, 16, unsigned char, row_major> : public __frag_base<unsigned char, 16> {};
|
| 360 |
+
template<> class fragment<matrix_b, 8, 32, 16, unsigned char, col_major> : public __frag_base<unsigned char, 16> {};
|
| 361 |
+
template<> class fragment<accumulator, 8, 32, 16, int> : public __frag_base<int, 8> {};
|
| 362 |
+
#endif /* __CUDA_IMMA__ */
|
| 363 |
+
|
| 364 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 365 |
+
template<> class fragment<matrix_a, 8, 32, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 4> {};
|
| 366 |
+
template<> class fragment<matrix_a, 8, 32, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 4> {};
|
| 367 |
+
template<> class fragment<matrix_b, 8, 32, 16, __nv_bfloat16, row_major> : public __frag_base<__nv_bfloat16, 16> {};
|
| 368 |
+
template<> class fragment<matrix_b, 8, 32, 16, __nv_bfloat16, col_major> : public __frag_base<__nv_bfloat16, 16> {};
|
| 369 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 370 |
+
|
| 371 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 372 |
+
//
|
| 373 |
+
// Fragments for 8x8x32
|
| 374 |
+
//
|
| 375 |
+
template<> class fragment<matrix_a, 8, 8, 32, experimental::precision::u4, row_major> : public __frag_base<experimental::precision::u4, 8, 1> {};
|
| 376 |
+
template<> class fragment<matrix_a, 8, 8, 32, experimental::precision::s4, row_major> : public __frag_base<experimental::precision::s4, 8, 1> {};
|
| 377 |
+
template<> class fragment<matrix_b, 8, 8, 32, experimental::precision::u4, col_major> : public __frag_base<experimental::precision::u4, 8, 1> {};
|
| 378 |
+
template<> class fragment<matrix_b, 8, 8, 32, experimental::precision::s4, col_major> : public __frag_base<experimental::precision::s4, 8, 1> {};
|
| 379 |
+
template<> class fragment<accumulator, 8, 8, 32, int> : public __frag_base<int, 2> {};
|
| 380 |
+
|
| 381 |
+
//
|
| 382 |
+
// Fragments for 8x8x128
|
| 383 |
+
//
|
| 384 |
+
template<> class fragment<matrix_a, 8, 8, 128, experimental::precision::b1, row_major> : public __frag_base<experimental::precision::b1, 32, 1> {};
|
| 385 |
+
template<> class fragment<matrix_b, 8, 8, 128, experimental::precision::b1, col_major> : public __frag_base<experimental::precision::b1, 32, 1> {};
|
| 386 |
+
template<> class fragment<accumulator, 8, 8, 128, int> : public __frag_base<int, 2> {};
|
| 387 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 388 |
+
|
| 389 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 390 |
+
//
|
| 391 |
+
// Fragments for 16x16x8
|
| 392 |
+
//
|
| 393 |
+
template<> class fragment<matrix_a, 16, 16, 8, precision::tf32, row_major> : public __frag_base<precision::tf32, 4> {};
|
| 394 |
+
template<> class fragment<matrix_a, 16, 16, 8, precision::tf32, col_major> : public __frag_base<precision::tf32, 4> {};
|
| 395 |
+
template<> class fragment<matrix_b, 16, 16, 8, precision::tf32, row_major> : public __frag_base<precision::tf32, 4> {};
|
| 396 |
+
template<> class fragment<matrix_b, 16, 16, 8, precision::tf32, col_major> : public __frag_base<precision::tf32, 4> {};
|
| 397 |
+
template<> class fragment<accumulator, 16, 16, 8, float> : public __frag_base<float, 8> {};
|
| 398 |
+
|
| 399 |
+
//
|
| 400 |
+
// Fragments for 8x8x4
|
| 401 |
+
//
|
| 402 |
+
template<> class fragment<matrix_a, 8, 8, 4, double, row_major> : public __frag_base<double, 1> {};
|
| 403 |
+
template<> class fragment<matrix_a, 8, 8, 4, double, col_major> : public __frag_base<double, 1> {};
|
| 404 |
+
template<> class fragment<matrix_b, 8, 8, 4, double, row_major> : public __frag_base<double, 1> {};
|
| 405 |
+
template<> class fragment<matrix_b, 8, 8, 4, double, col_major> : public __frag_base<double, 1> {};
|
| 406 |
+
template<> class fragment<accumulator, 8, 8, 4, double> : public __frag_base<double, 2> {};
|
| 407 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
//
|
| 411 |
+
// Load functions for frags of shape m16n16k16
|
| 412 |
+
//
|
| 413 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 414 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 415 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 416 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 417 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 16, 16, 16, __half>& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 418 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 16, 16, 16, float>& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 419 |
+
|
| 420 |
+
#ifdef __CUDA_IMMA__
|
| 421 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 422 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 423 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 424 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 425 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 426 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 427 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 428 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 429 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 16, 16, 16, int>& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 430 |
+
#endif /* __CUDA_IMMA__ */
|
| 431 |
+
|
| 432 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 433 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 434 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 435 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 436 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 437 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 438 |
+
|
| 439 |
+
//
|
| 440 |
+
// Load functions for frags of shape m32n8k16
|
| 441 |
+
//
|
| 442 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 443 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 444 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 445 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 446 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 32, 8, 16, __half>& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 447 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 32, 8, 16, float>& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 448 |
+
|
| 449 |
+
#ifdef __CUDA_IMMA__
|
| 450 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 451 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 452 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 453 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 454 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 455 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 456 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 457 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 458 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 32, 8, 16, int>& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 459 |
+
#endif /* __CUDA_IMMA__ */
|
| 460 |
+
|
| 461 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 462 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 463 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 32, 8, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 464 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 465 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 32, 8, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 466 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 467 |
+
|
| 468 |
+
//
|
| 469 |
+
// Load functions for frags of shape m8n32k16
|
| 470 |
+
//
|
| 471 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 472 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 473 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, __half, row_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 474 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, __half, col_major>& a, const __half* p, unsigned ldm) __DEF_IF_HOST
|
| 475 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 32, 16, __half>& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 476 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 32, 16, float>& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 477 |
+
|
| 478 |
+
#ifdef __CUDA_IMMA__
|
| 479 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 480 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 481 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 482 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 483 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, signed char, row_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 484 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, signed char, col_major>& a, const signed char* p, unsigned ldm) __DEF_IF_HOST
|
| 485 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, unsigned char, row_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 486 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, unsigned char, col_major>& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST
|
| 487 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 32, 16, int>& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 488 |
+
#endif /* __CUDA_IMMA__ */
|
| 489 |
+
|
| 490 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 491 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 492 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 32, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 493 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, __nv_bfloat16, row_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 494 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 32, 16, __nv_bfloat16, col_major>& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST
|
| 495 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 496 |
+
|
| 497 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 498 |
+
//
|
| 499 |
+
// Load functions for frags of shape m8n8k32
|
| 500 |
+
//
|
| 501 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 8, 32, experimental::precision::s4, row_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 502 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 8, 32, experimental::precision::u4, row_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 503 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 8, 32, experimental::precision::s4, col_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 504 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 8, 32, experimental::precision::u4, col_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 505 |
+
|
| 506 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 8, 32, int>& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 507 |
+
|
| 508 |
+
//
|
| 509 |
+
// Load functions for frags of shape m8n8k128
|
| 510 |
+
//
|
| 511 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 8, 128, experimental::precision::b1, row_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 512 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 8, 128, experimental::precision::b1, col_major>& a, const void* p, unsigned ldm) __DEF_IF_HOST
|
| 513 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 8, 128, int>& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 514 |
+
|
| 515 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 519 |
+
//
|
| 520 |
+
// Load functions for frags of shape m16n16k8
|
| 521 |
+
//
|
| 522 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 8, precision::tf32, row_major>& a, const float* p, unsigned ldm) __DEF_IF_HOST
|
| 523 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 16, 16, 8, precision::tf32, col_major>& a, const float* p, unsigned ldm) __DEF_IF_HOST
|
| 524 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 8, precision::tf32, row_major>& a, const float* p, unsigned ldm) __DEF_IF_HOST
|
| 525 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 16, 16, 8, precision::tf32, col_major>& a, const float* p, unsigned ldm) __DEF_IF_HOST
|
| 526 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 16, 16, 8, float>& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 527 |
+
|
| 528 |
+
//
|
| 529 |
+
// Load functions for frags of shape m8n8k4
|
| 530 |
+
//
|
| 531 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 8, 4, double, row_major>& a, const double* p, unsigned ldm) __DEF_IF_HOST
|
| 532 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_a, 8, 8, 4, double, col_major>& a, const double* p, unsigned ldm) __DEF_IF_HOST
|
| 533 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 8, 4, double, row_major>& a, const double* p, unsigned ldm) __DEF_IF_HOST
|
| 534 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<matrix_b, 8, 8, 4, double, col_major>& a, const double* p, unsigned ldm) __DEF_IF_HOST
|
| 535 |
+
__CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment<accumulator, 8, 8, 4, double>& a, const double* p, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 536 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 537 |
+
|
| 538 |
+
//
|
| 539 |
+
// Store functions for frags of shape m16n16k16
|
| 540 |
+
//
|
| 541 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment<accumulator, 16, 16, 16, __half>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 542 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment<accumulator, 16, 16, 16, float>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 543 |
+
#ifdef __CUDA_IMMA__
|
| 544 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment<accumulator, 16, 16, 16, int>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 545 |
+
#endif /* __CUDA_IMMA__ */
|
| 546 |
+
|
| 547 |
+
//
|
| 548 |
+
// Store functions for frags of shape m32n8k16
|
| 549 |
+
//
|
| 550 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment<accumulator, 32, 8, 16, __half>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 551 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment<accumulator, 32, 8, 16, float>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 552 |
+
#ifdef __CUDA_IMMA__
|
| 553 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment<accumulator, 32, 8, 16, int>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 554 |
+
#endif /* __CUDA_IMMA__ */
|
| 555 |
+
|
| 556 |
+
//
|
| 557 |
+
// Store functions for frags of shape m8n32k16
|
| 558 |
+
//
|
| 559 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment<accumulator, 8, 32, 16, __half>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 560 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment<accumulator, 8, 32, 16, float>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 561 |
+
#ifdef __CUDA_IMMA__
|
| 562 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment<accumulator, 8, 32, 16, int>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 563 |
+
#endif /* __CUDA_IMMA__ */
|
| 564 |
+
|
| 565 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 566 |
+
//
|
| 567 |
+
// Store functions for frags of shape m8n8k32
|
| 568 |
+
//
|
| 569 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment<accumulator, 8, 8, 32, int>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 570 |
+
|
| 571 |
+
//
|
| 572 |
+
// Store functions for frags of shape m8n8k128
|
| 573 |
+
//
|
| 574 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment<accumulator, 8, 8, 128, int>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 575 |
+
|
| 576 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 577 |
+
|
| 578 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 579 |
+
//
|
| 580 |
+
// Store functions for frags of shape m16n16k8
|
| 581 |
+
//
|
| 582 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment<accumulator, 16, 16, 8, float>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 583 |
+
|
| 584 |
+
//
|
| 585 |
+
// Store functions for frags of shape m8n8k4
|
| 586 |
+
//
|
| 587 |
+
__CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(double *p, const fragment<accumulator, 8, 8, 4, double>& a, unsigned ldm, layout_t layout) __DEF_IF_HOST
|
| 588 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 589 |
+
|
| 590 |
+
//
|
| 591 |
+
// MMA functions for shape m16n16k16
|
| 592 |
+
//
|
| 593 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 594 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 595 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 596 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 597 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 598 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 599 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 600 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, __half>& c) __DEF_IF_HOST
|
| 601 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 602 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 603 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 604 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 605 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 606 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 607 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, row_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 608 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, __half>& d, const fragment<matrix_a, 16, 16, 16, __half, col_major>& a, const fragment<matrix_b,16, 16, 16, __half, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 609 |
+
|
| 610 |
+
#ifdef __CUDA_IMMA__
|
| 611 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, signed char, row_major>& a, const fragment<matrix_b,16, 16, 16, signed char, col_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 612 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, signed char, col_major>& a, const fragment<matrix_b,16, 16, 16, signed char, col_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 613 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, signed char, row_major>& a, const fragment<matrix_b,16, 16, 16, signed char, row_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 614 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, signed char, col_major>& a, const fragment<matrix_b,16, 16, 16, signed char, row_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 615 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, unsigned char, row_major>& a, const fragment<matrix_b,16, 16, 16, unsigned char, col_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 616 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, unsigned char, col_major>& a, const fragment<matrix_b,16, 16, 16, unsigned char, col_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 617 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, unsigned char, row_major>& a, const fragment<matrix_b,16, 16, 16, unsigned char, row_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 618 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, int>& d, const fragment<matrix_a, 16, 16, 16, unsigned char, col_major>& a, const fragment<matrix_b,16, 16, 16, unsigned char, row_major>& b, const fragment<accumulator,16, 16, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 619 |
+
#endif /* __CUDA_IMMA__ */
|
| 620 |
+
|
| 621 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 622 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b,16, 16, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 623 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b,16, 16, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 624 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b,16, 16, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 625 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator,16, 16, 16, float>& d, const fragment<matrix_a, 16, 16, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b,16, 16, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator,16, 16, 16, float>& c) __DEF_IF_HOST
|
| 626 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 627 |
+
|
| 628 |
+
//
|
| 629 |
+
// MMA functions for shape m32n8k16
|
| 630 |
+
//
|
| 631 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 632 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 633 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 634 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 635 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 636 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 637 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 638 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, __half>& c) __DEF_IF_HOST
|
| 639 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 640 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 641 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 642 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 643 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 644 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 645 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, row_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 646 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, __half>& d, const fragment<matrix_a, 32, 8, 16, __half, col_major>& a, const fragment<matrix_b, 32, 8, 16, __half, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 647 |
+
|
| 648 |
+
#ifdef __CUDA_IMMA__
|
| 649 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, signed char, row_major>& a, const fragment<matrix_b, 32, 8, 16, signed char, col_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 650 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, signed char, col_major>& a, const fragment<matrix_b, 32, 8, 16, signed char, col_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 651 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, signed char, row_major>& a, const fragment<matrix_b, 32, 8, 16, signed char, row_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 652 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, signed char, col_major>& a, const fragment<matrix_b, 32, 8, 16, signed char, row_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 653 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, unsigned char, row_major>& a, const fragment<matrix_b, 32, 8, 16, unsigned char, col_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 654 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, unsigned char, col_major>& a, const fragment<matrix_b, 32, 8, 16, unsigned char, col_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 655 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, unsigned char, row_major>& a, const fragment<matrix_b, 32, 8, 16, unsigned char, row_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 656 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, int>& d, const fragment<matrix_a, 32, 8, 16, unsigned char, col_major>& a, const fragment<matrix_b, 32, 8, 16, unsigned char, row_major>& b, const fragment<accumulator, 32, 8, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 657 |
+
#endif /* __CUDA_IMMA__ */
|
| 658 |
+
|
| 659 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 660 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b, 32, 8, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 661 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b, 32, 8, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 662 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b, 32, 8, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 663 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 32, 8, 16, float>& d, const fragment<matrix_a, 32, 8, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b, 32, 8, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator, 32, 8, 16, float>& c) __DEF_IF_HOST
|
| 664 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 665 |
+
|
| 666 |
+
//
|
| 667 |
+
// MMA functions for shape m8n32k16
|
| 668 |
+
//
|
| 669 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 670 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 671 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 672 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 673 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 674 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 675 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 676 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, __half>& c) __DEF_IF_HOST
|
| 677 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 678 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 679 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 680 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 681 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 682 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 683 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, row_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 684 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, __half>& d, const fragment<matrix_a, 8, 32, 16, __half, col_major>& a, const fragment<matrix_b, 8, 32, 16, __half, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 685 |
+
|
| 686 |
+
#ifdef __CUDA_IMMA__
|
| 687 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, signed char, row_major>& a, const fragment<matrix_b, 8, 32, 16, signed char, col_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 688 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, signed char, col_major>& a, const fragment<matrix_b, 8, 32, 16, signed char, col_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 689 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, signed char, row_major>& a, const fragment<matrix_b, 8, 32, 16, signed char, row_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 690 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, signed char, col_major>& a, const fragment<matrix_b, 8, 32, 16, signed char, row_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 691 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, unsigned char, row_major>& a, const fragment<matrix_b, 8, 32, 16, unsigned char, col_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 692 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, unsigned char, col_major>& a, const fragment<matrix_b, 8, 32, 16, unsigned char, col_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 693 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, unsigned char, row_major>& a, const fragment<matrix_b, 8, 32, 16, unsigned char, row_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 694 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, int>& d, const fragment<matrix_a, 8, 32, 16, unsigned char, col_major>& a, const fragment<matrix_b, 8, 32, 16, unsigned char, row_major>& b, const fragment<accumulator, 8, 32, 16, int>& c, bool satf=false) __DEF_IF_HOST
|
| 695 |
+
#endif /* __CUDA_IMMA__ */
|
| 696 |
+
|
| 697 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 698 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b, 8, 32, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 699 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b, 8, 32, 16, __nv_bfloat16, col_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 700 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __nv_bfloat16, row_major>& a, const fragment<matrix_b, 8, 32, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 701 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 32, 16, float>& d, const fragment<matrix_a, 8, 32, 16, __nv_bfloat16, col_major>& a, const fragment<matrix_b, 8, 32, 16, __nv_bfloat16, row_major>& b, const fragment<accumulator, 8, 32, 16, float>& c) __DEF_IF_HOST
|
| 702 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 703 |
+
|
| 704 |
+
#ifdef __CUDA_SUBBYTE_IMMA__
|
| 705 |
+
//
|
| 706 |
+
// MMA functions for shape m8n8k32
|
| 707 |
+
//
|
| 708 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 32, int>& d, const fragment<matrix_a, 8, 8, 32, experimental::precision::s4, row_major>& a, const fragment<matrix_b, 8, 8, 32, experimental::precision::s4, col_major>& b, const fragment<accumulator, 8, 8, 32, int>& c, bool satf=false) __DEF_IF_HOST
|
| 709 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 32, int>& d, const fragment<matrix_a, 8, 8, 32, experimental::precision::u4, row_major>& a, const fragment<matrix_b, 8, 8, 32, experimental::precision::u4, col_major>& b, const fragment<accumulator, 8, 8, 32, int>& c, bool satf=false) __DEF_IF_HOST
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
//
|
| 713 |
+
// MMA functions for shape m8n8k128
|
| 714 |
+
//
|
| 715 |
+
__CUDA_MMA_DEVICE_DECL__ void bmma_sync(fragment<accumulator, 8, 8, 128, int>& d, const fragment<matrix_a, 8, 8, 128, experimental::precision::b1, row_major>& a, const fragment<matrix_b, 8, 8, 128, experimental::precision::b1, col_major>& b, const fragment<accumulator, 8, 8, 128, int>& c,
|
| 716 |
+
experimental::bmmaBitOp = experimental::bmmaBitOpXOR,
|
| 717 |
+
experimental::bmmaAccumulateOp = experimental::bmmaAccumulateOpPOPC) __DEF_IF_HOST
|
| 718 |
+
|
| 719 |
+
#endif /* __CUDA_SUBBYTE_IMMA__ */
|
| 720 |
+
|
| 721 |
+
#ifdef __CUDA_AMPERE_MMA__
|
| 722 |
+
//
|
| 723 |
+
// MMA functions for shape m16n16k8
|
| 724 |
+
//
|
| 725 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 16, 16, 8, float>& d, const fragment<matrix_a, 16, 16, 8, precision::tf32, row_major>& a, const fragment<matrix_b, 16, 16, 8, precision::tf32, col_major>& b, const fragment<accumulator, 16, 16, 8, float>& c) __DEF_IF_HOST
|
| 726 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 16, 16, 8, float>& d, const fragment<matrix_a, 16, 16, 8, precision::tf32, col_major>& a, const fragment<matrix_b, 16, 16, 8, precision::tf32, col_major>& b, const fragment<accumulator, 16, 16, 8, float>& c) __DEF_IF_HOST
|
| 727 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 16, 16, 8, float>& d, const fragment<matrix_a, 16, 16, 8, precision::tf32, row_major>& a, const fragment<matrix_b, 16, 16, 8, precision::tf32, row_major>& b, const fragment<accumulator, 16, 16, 8, float>& c) __DEF_IF_HOST
|
| 728 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 16, 16, 8, float>& d, const fragment<matrix_a, 16, 16, 8, precision::tf32, col_major>& a, const fragment<matrix_b, 16, 16, 8, precision::tf32, row_major>& b, const fragment<accumulator, 16, 16, 8, float>& c) __DEF_IF_HOST
|
| 729 |
+
|
| 730 |
+
//
|
| 731 |
+
// MMA functions for shape m8n8k4
|
| 732 |
+
//
|
| 733 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 4, double>& d, const fragment<matrix_a, 8, 8, 4, double, row_major>& a, const fragment<matrix_b, 8, 8, 4, double, col_major>& b, const fragment<accumulator, 8, 8, 4, double>& c) __DEF_IF_HOST
|
| 734 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 4, double>& d, const fragment<matrix_a, 8, 8, 4, double, col_major>& a, const fragment<matrix_b, 8, 8, 4, double, col_major>& b, const fragment<accumulator, 8, 8, 4, double>& c) __DEF_IF_HOST
|
| 735 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 4, double>& d, const fragment<matrix_a, 8, 8, 4, double, row_major>& a, const fragment<matrix_b, 8, 8, 4, double, row_major>& b, const fragment<accumulator, 8, 8, 4, double>& c) __DEF_IF_HOST
|
| 736 |
+
__CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment<accumulator, 8, 8, 4, double>& d, const fragment<matrix_a, 8, 8, 4, double, col_major>& a, const fragment<matrix_b, 8, 8, 4, double, row_major>& b, const fragment<accumulator, 8, 8, 4, double>& c) __DEF_IF_HOST
|
| 737 |
+
#endif /* __CUDA_AMPERE_MMA__ */
|
| 738 |
+
};
|
| 739 |
+
};
|
| 740 |
+
|
| 741 |
+
#undef __DEF_IF_HOST
|
| 742 |
+
#undef __CUDA_IMMA__
|
| 743 |
+
#undef __CUDA_SUBBYTE_IMMA__
|
| 744 |
+
#undef __CUDA_AMPERE_MMA__
|
| 745 |
+
#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */
|
| 746 |
+
|
| 747 |
+
#endif /* __cplusplus && __CUDACC__ */
|
| 748 |
+
|
| 749 |
+
#undef __CUDA_MMA_DEVICE_DECL__
|
| 750 |
+
|
| 751 |
+
#if defined(__CUDA_ARCH__)
|
| 752 |
+
#include "mma.hpp"
|
| 753 |
+
#endif /* defined(__CUDA_ARCH__) */
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
#endif /* !__CUDA_MMA_H__ */
|
| 757 |
+
|
| 758 |
+
#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__)
|
| 759 |
+
#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__
|
| 760 |
+
#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADER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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implementation of :class:`FractionField` class. """
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
from sympy.polys.domains.compositedomain import CompositeDomain
|
| 5 |
+
from sympy.polys.domains.field import Field
|
| 6 |
+
from sympy.polys.polyerrors import CoercionFailed, GeneratorsError
|
| 7 |
+
from sympy.utilities import public
|
| 8 |
+
|
| 9 |
+
@public
|
| 10 |
+
class FractionField(Field, CompositeDomain):
|
| 11 |
+
"""A class for representing multivariate rational function fields. """
|
| 12 |
+
|
| 13 |
+
is_FractionField = is_Frac = True
|
| 14 |
+
|
| 15 |
+
has_assoc_Ring = True
|
| 16 |
+
has_assoc_Field = True
|
| 17 |
+
|
| 18 |
+
def __init__(self, domain_or_field, symbols=None, order=None):
|
| 19 |
+
from sympy.polys.fields import FracField
|
| 20 |
+
|
| 21 |
+
if isinstance(domain_or_field, FracField) and symbols is None and order is None:
|
| 22 |
+
field = domain_or_field
|
| 23 |
+
else:
|
| 24 |
+
field = FracField(symbols, domain_or_field, order)
|
| 25 |
+
|
| 26 |
+
self.field = field
|
| 27 |
+
self.dtype = field.dtype
|
| 28 |
+
|
| 29 |
+
self.gens = field.gens
|
| 30 |
+
self.ngens = field.ngens
|
| 31 |
+
self.symbols = field.symbols
|
| 32 |
+
self.domain = field.domain
|
| 33 |
+
|
| 34 |
+
# TODO: remove this
|
| 35 |
+
self.dom = self.domain
|
| 36 |
+
|
| 37 |
+
def new(self, element):
|
| 38 |
+
return self.field.field_new(element)
|
| 39 |
+
|
| 40 |
+
def of_type(self, element):
|
| 41 |
+
"""Check if ``a`` is of type ``dtype``. """
|
| 42 |
+
return self.field.is_element(element)
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def zero(self):
|
| 46 |
+
return self.field.zero
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def one(self):
|
| 50 |
+
return self.field.one
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def order(self):
|
| 54 |
+
return self.field.order
|
| 55 |
+
|
| 56 |
+
def __str__(self):
|
| 57 |
+
return str(self.domain) + '(' + ','.join(map(str, self.symbols)) + ')'
|
| 58 |
+
|
| 59 |
+
def __hash__(self):
|
| 60 |
+
return hash((self.__class__.__name__, self.field, self.domain, self.symbols))
|
| 61 |
+
|
| 62 |
+
def __eq__(self, other):
|
| 63 |
+
"""Returns ``True`` if two domains are equivalent. """
|
| 64 |
+
if not isinstance(other, FractionField):
|
| 65 |
+
return NotImplemented
|
| 66 |
+
return self.field == other.field
|
| 67 |
+
|
| 68 |
+
def to_sympy(self, a):
|
| 69 |
+
"""Convert ``a`` to a SymPy object. """
|
| 70 |
+
return a.as_expr()
|
| 71 |
+
|
| 72 |
+
def from_sympy(self, a):
|
| 73 |
+
"""Convert SymPy's expression to ``dtype``. """
|
| 74 |
+
return self.field.from_expr(a)
|
| 75 |
+
|
| 76 |
+
def from_ZZ(K1, a, K0):
|
| 77 |
+
"""Convert a Python ``int`` object to ``dtype``. """
|
| 78 |
+
return K1(K1.domain.convert(a, K0))
|
| 79 |
+
|
| 80 |
+
def from_ZZ_python(K1, a, K0):
|
| 81 |
+
"""Convert a Python ``int`` object to ``dtype``. """
|
| 82 |
+
return K1(K1.domain.convert(a, K0))
|
| 83 |
+
|
| 84 |
+
def from_QQ(K1, a, K0):
|
| 85 |
+
"""Convert a Python ``Fraction`` object to ``dtype``. """
|
| 86 |
+
dom = K1.domain
|
| 87 |
+
conv = dom.convert_from
|
| 88 |
+
if dom.is_ZZ:
|
| 89 |
+
return K1(conv(K0.numer(a), K0)) / K1(conv(K0.denom(a), K0))
|
| 90 |
+
else:
|
| 91 |
+
return K1(conv(a, K0))
|
| 92 |
+
|
| 93 |
+
def from_QQ_python(K1, a, K0):
|
| 94 |
+
"""Convert a Python ``Fraction`` object to ``dtype``. """
|
| 95 |
+
return K1(K1.domain.convert(a, K0))
|
| 96 |
+
|
| 97 |
+
def from_ZZ_gmpy(K1, a, K0):
|
| 98 |
+
"""Convert a GMPY ``mpz`` object to ``dtype``. """
|
| 99 |
+
return K1(K1.domain.convert(a, K0))
|
| 100 |
+
|
| 101 |
+
def from_QQ_gmpy(K1, a, K0):
|
| 102 |
+
"""Convert a GMPY ``mpq`` object to ``dtype``. """
|
| 103 |
+
return K1(K1.domain.convert(a, K0))
|
| 104 |
+
|
| 105 |
+
def from_GaussianRationalField(K1, a, K0):
|
| 106 |
+
"""Convert a ``GaussianRational`` object to ``dtype``. """
|
| 107 |
+
return K1(K1.domain.convert(a, K0))
|
| 108 |
+
|
| 109 |
+
def from_GaussianIntegerRing(K1, a, K0):
|
| 110 |
+
"""Convert a ``GaussianInteger`` object to ``dtype``. """
|
| 111 |
+
return K1(K1.domain.convert(a, K0))
|
| 112 |
+
|
| 113 |
+
def from_RealField(K1, a, K0):
|
| 114 |
+
"""Convert a mpmath ``mpf`` object to ``dtype``. """
|
| 115 |
+
return K1(K1.domain.convert(a, K0))
|
| 116 |
+
|
| 117 |
+
def from_ComplexField(K1, a, K0):
|
| 118 |
+
"""Convert a mpmath ``mpf`` object to ``dtype``. """
|
| 119 |
+
return K1(K1.domain.convert(a, K0))
|
| 120 |
+
|
| 121 |
+
def from_AlgebraicField(K1, a, K0):
|
| 122 |
+
"""Convert an algebraic number to ``dtype``. """
|
| 123 |
+
if K1.domain != K0:
|
| 124 |
+
a = K1.domain.convert_from(a, K0)
|
| 125 |
+
if a is not None:
|
| 126 |
+
return K1.new(a)
|
| 127 |
+
|
| 128 |
+
def from_PolynomialRing(K1, a, K0):
|
| 129 |
+
"""Convert a polynomial to ``dtype``. """
|
| 130 |
+
if a.is_ground:
|
| 131 |
+
return K1.convert_from(a.coeff(1), K0.domain)
|
| 132 |
+
try:
|
| 133 |
+
return K1.new(a.set_ring(K1.field.ring))
|
| 134 |
+
except (CoercionFailed, GeneratorsError):
|
| 135 |
+
# XXX: We get here if K1=ZZ(x,y) and K0=QQ[x,y]
|
| 136 |
+
# and the poly a in K0 has non-integer coefficients.
|
| 137 |
+
# It seems that K1.new can handle this but K1.new doesn't work
|
| 138 |
+
# when K0.domain is an algebraic field...
|
| 139 |
+
try:
|
| 140 |
+
return K1.new(a)
|
| 141 |
+
except (CoercionFailed, GeneratorsError):
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
def from_FractionField(K1, a, K0):
|
| 145 |
+
"""Convert a rational function to ``dtype``. """
|
| 146 |
+
try:
|
| 147 |
+
return a.set_field(K1.field)
|
| 148 |
+
except (CoercionFailed, GeneratorsError):
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
def get_ring(self):
|
| 152 |
+
"""Returns a field associated with ``self``. """
|
| 153 |
+
return self.field.to_ring().to_domain()
|
| 154 |
+
|
| 155 |
+
def is_positive(self, a):
|
| 156 |
+
"""Returns True if ``LC(a)`` is positive. """
|
| 157 |
+
return self.domain.is_positive(a.numer.LC)
|
| 158 |
+
|
| 159 |
+
def is_negative(self, a):
|
| 160 |
+
"""Returns True if ``LC(a)`` is negative. """
|
| 161 |
+
return self.domain.is_negative(a.numer.LC)
|
| 162 |
+
|
| 163 |
+
def is_nonpositive(self, a):
|
| 164 |
+
"""Returns True if ``LC(a)`` is non-positive. """
|
| 165 |
+
return self.domain.is_nonpositive(a.numer.LC)
|
| 166 |
+
|
| 167 |
+
def is_nonnegative(self, a):
|
| 168 |
+
"""Returns True if ``LC(a)`` is non-negative. """
|
| 169 |
+
return self.domain.is_nonnegative(a.numer.LC)
|
| 170 |
+
|
| 171 |
+
def numer(self, a):
|
| 172 |
+
"""Returns numerator of ``a``. """
|
| 173 |
+
return a.numer
|
| 174 |
+
|
| 175 |
+
def denom(self, a):
|
| 176 |
+
"""Returns denominator of ``a``. """
|
| 177 |
+
return a.denom
|
| 178 |
+
|
| 179 |
+
def factorial(self, a):
|
| 180 |
+
"""Returns factorial of ``a``. """
|
| 181 |
+
return self.dtype(self.domain.factorial(a))
|
shared/package-files/06/068c759e5e0cda01113978e09532a50dcd979e1b560fdc541ba20ebeae87300c/closure.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import os
|
| 3 |
+
import threading
|
| 4 |
+
from queue import Empty as EmptyQueue, Queue
|
| 5 |
+
|
| 6 |
+
from torch._lazy.device_context import get_device_context
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ClosureHandler:
|
| 10 |
+
def __init__(self) -> None:
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
def run(self, closure):
|
| 14 |
+
"""Run closure function
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
closure: callable function to run
|
| 18 |
+
"""
|
| 19 |
+
closure()
|
| 20 |
+
|
| 21 |
+
def __call__(self, closures):
|
| 22 |
+
for closure in closures:
|
| 23 |
+
self.run(closure)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AsyncClosureHandler(ClosureHandler):
|
| 27 |
+
"""Handler for Asynchronous Step Closures
|
| 28 |
+
Args:
|
| 29 |
+
max_queue_size: The maximum length of the closure queue after which
|
| 30 |
+
the training loop will block until closures are evaluated.
|
| 31 |
+
By default, a reasonable limit of a maximum of 100 on the queue.
|
| 32 |
+
This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment
|
| 33 |
+
variable.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, max_queue_size=100):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self._closure_queue: Queue = Queue(
|
| 39 |
+
int(os.environ.get("LTC_MAX_ASYNC_QUEUE", max_queue_size))
|
| 40 |
+
)
|
| 41 |
+
self._closure_exception: Queue = Queue()
|
| 42 |
+
self._closure_lock = threading.Lock()
|
| 43 |
+
self._closure_event_loop_finished = threading.Event()
|
| 44 |
+
self._closure_event_loop = None
|
| 45 |
+
|
| 46 |
+
def start_event_loop(self):
|
| 47 |
+
"""Start closure event loop if not started"""
|
| 48 |
+
if self._closure_event_loop is None:
|
| 49 |
+
|
| 50 |
+
def event_loop():
|
| 51 |
+
# Run loop until closure event is set and closure queue is empty
|
| 52 |
+
while True:
|
| 53 |
+
try:
|
| 54 |
+
closure = self._closure_queue.get(block=True, timeout=3)
|
| 55 |
+
closure()
|
| 56 |
+
self._closure_queue.task_done()
|
| 57 |
+
except EmptyQueue:
|
| 58 |
+
with self._closure_lock:
|
| 59 |
+
if self._closure_queue.empty():
|
| 60 |
+
self._closure_event_loop_finished.set()
|
| 61 |
+
return
|
| 62 |
+
except Exception as e:
|
| 63 |
+
self._closure_exception.put(e)
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
self._closure_event_loop = threading.Thread(target=event_loop)
|
| 67 |
+
self._closure_event_loop.start()
|
| 68 |
+
|
| 69 |
+
def run(self, closure):
|
| 70 |
+
with self._closure_lock:
|
| 71 |
+
self._closure_queue.put(closure, block=True)
|
| 72 |
+
if (
|
| 73 |
+
self._closure_event_loop is None
|
| 74 |
+
or not self._closure_event_loop.is_alive()
|
| 75 |
+
):
|
| 76 |
+
try:
|
| 77 |
+
e = self._closure_exception.get(block=False)
|
| 78 |
+
raise RuntimeError(
|
| 79 |
+
"Cannot run asynchronous closure due to previously raised exception"
|
| 80 |
+
) from e
|
| 81 |
+
except EmptyQueue:
|
| 82 |
+
self._closure_event_loop = None
|
| 83 |
+
self.start_event_loop()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def add_step_closure(closure, args=(), run_async=False):
|
| 87 |
+
"""Adds a closure to the list of the ones to be run at the end of the step.
|
| 88 |
+
Many times during model training there is the need to print/report (print to
|
| 89 |
+
console, post to tensorboard, etc...) information which require the content of
|
| 90 |
+
intermediary tensors to be inspected.
|
| 91 |
+
Inspecting different tensors content in different points of the model code
|
| 92 |
+
requires many executions and typically causes performance issues.
|
| 93 |
+
Adding a step closure will ensure that it will be run after the barrier, when
|
| 94 |
+
all the live tensors will be already materialized to device data.
|
| 95 |
+
Live tensors which will include the ones captured by the closure arguments.
|
| 96 |
+
So using `add_step_closure()` will ensure a single execution will be
|
| 97 |
+
performed, even when multiple closures are queued, requiring multiple tensors
|
| 98 |
+
to be inspected.
|
| 99 |
+
Step closures will be run sequentially in the order they have been queued.
|
| 100 |
+
Note that even though using this API the execution will be optimized, it is
|
| 101 |
+
advised to throttle the printing/reporting events once every N steps.
|
| 102 |
+
Args:
|
| 103 |
+
closure (callable): The function to be called.
|
| 104 |
+
args (tuple): The arguments to be passed to the closure.
|
| 105 |
+
run_async: If True, run the closure asynchronously.
|
| 106 |
+
"""
|
| 107 |
+
devctx = get_device_context()
|
| 108 |
+
closures_type = "async_step_closures" if run_async else "step_closures"
|
| 109 |
+
step_closures = getattr(devctx, closures_type, None)
|
| 110 |
+
if step_closures is None:
|
| 111 |
+
step_closures = []
|
| 112 |
+
setattr(devctx, closures_type, step_closures)
|
| 113 |
+
step_closures.append(lambda a=args: closure(*a))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def run_step_closures():
|
| 117 |
+
devctx = get_device_context()
|
| 118 |
+
async_step_closures = getattr(devctx, "async_step_closures", None)
|
| 119 |
+
if async_step_closures is not None:
|
| 120 |
+
devctx.async_step_closures = [] # type: ignore[attr-defined]
|
| 121 |
+
async_closure_handler = getattr(devctx, "async_closure_handler", None)
|
| 122 |
+
if async_closure_handler is None:
|
| 123 |
+
async_closure_handler = AsyncClosureHandler()
|
| 124 |
+
devctx.async_closure_handler = async_closure_handler # type: ignore[attr-defined]
|
| 125 |
+
async_closure_handler(async_step_closures)
|
| 126 |
+
|
| 127 |
+
step_closures = getattr(devctx, "step_closures", None)
|
| 128 |
+
if step_closures is not None:
|
| 129 |
+
devctx.step_closures = [] # type: ignore[attr-defined]
|
| 130 |
+
closure_handler = getattr(devctx, "closure_handler", None)
|
| 131 |
+
if closure_handler is None:
|
| 132 |
+
closure_handler = ClosureHandler()
|
| 133 |
+
devctx.closure_handler = closure_handler # type: ignore[attr-defined]
|
| 134 |
+
closure_handler(step_closures)
|
| 135 |
+
return devctx
|
shared/package-files/06/06907f46e852cea98bf4240fa02a6b453927085feb0758203af2d23d645dfc4a/log2_ops.h
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API log2 {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::log2";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "log2(Tensor self) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API log2_ {
|
| 30 |
+
using schema = at::Tensor & (at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::log2_";
|
| 34 |
+
static constexpr const char* overload_name = "";
|
| 35 |
+
static constexpr const char* schema_str = "log2_(Tensor(a!) self) -> Tensor(a!)";
|
| 36 |
+
static at::Tensor & call(at::Tensor & self);
|
| 37 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
struct TORCH_API log2_out {
|
| 41 |
+
using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
|
| 42 |
+
using ptr_schema = schema*;
|
| 43 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 44 |
+
static constexpr const char* name = "aten::log2";
|
| 45 |
+
static constexpr const char* overload_name = "out";
|
| 46 |
+
static constexpr const char* schema_str = "log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)";
|
| 47 |
+
static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
|
| 48 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
}} // namespace at::_ops
|
shared/package-files/06/069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5/test_pipe.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from pandas import (
|
| 5 |
+
DataFrame,
|
| 6 |
+
Index,
|
| 7 |
+
)
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_pipe():
|
| 12 |
+
# Test the pipe method of DataFrameGroupBy.
|
| 13 |
+
# Issue #17871
|
| 14 |
+
|
| 15 |
+
random_state = np.random.default_rng(2)
|
| 16 |
+
|
| 17 |
+
df = DataFrame(
|
| 18 |
+
{
|
| 19 |
+
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
|
| 20 |
+
"B": random_state.standard_normal(8),
|
| 21 |
+
"C": random_state.standard_normal(8),
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def f(dfgb):
|
| 26 |
+
return dfgb.B.max() - dfgb.C.min().min()
|
| 27 |
+
|
| 28 |
+
def square(srs):
|
| 29 |
+
return srs**2
|
| 30 |
+
|
| 31 |
+
# Note that the transformations are
|
| 32 |
+
# GroupBy -> Series
|
| 33 |
+
# Series -> Series
|
| 34 |
+
# This then chains the GroupBy.pipe and the
|
| 35 |
+
# NDFrame.pipe methods
|
| 36 |
+
result = df.groupby("A").pipe(f).pipe(square)
|
| 37 |
+
|
| 38 |
+
index = Index(["bar", "foo"], dtype="object", name="A")
|
| 39 |
+
expected = pd.Series([3.749306591013693, 6.717707873081384], name="B", index=index)
|
| 40 |
+
|
| 41 |
+
tm.assert_series_equal(expected, result)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_pipe_args():
|
| 45 |
+
# Test passing args to the pipe method of DataFrameGroupBy.
|
| 46 |
+
# Issue #17871
|
| 47 |
+
|
| 48 |
+
df = DataFrame(
|
| 49 |
+
{
|
| 50 |
+
"group": ["A", "A", "B", "B", "C"],
|
| 51 |
+
"x": [1.0, 2.0, 3.0, 2.0, 5.0],
|
| 52 |
+
"y": [10.0, 100.0, 1000.0, -100.0, -1000.0],
|
| 53 |
+
}
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def f(dfgb, arg1):
|
| 57 |
+
filtered = dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False)
|
| 58 |
+
return filtered.groupby("group")
|
| 59 |
+
|
| 60 |
+
def g(dfgb, arg2):
|
| 61 |
+
return dfgb.sum() / dfgb.sum().sum() + arg2
|
| 62 |
+
|
| 63 |
+
def h(df, arg3):
|
| 64 |
+
return df.x + df.y - arg3
|
| 65 |
+
|
| 66 |
+
result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100)
|
| 67 |
+
|
| 68 |
+
# Assert the results here
|
| 69 |
+
index = Index(["A", "B"], name="group")
|
| 70 |
+
expected = pd.Series([-79.5160891089, -78.4839108911], index=index)
|
| 71 |
+
|
| 72 |
+
tm.assert_series_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
# test SeriesGroupby.pipe
|
| 75 |
+
ser = pd.Series([1, 1, 2, 2, 3, 3])
|
| 76 |
+
result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count())
|
| 77 |
+
|
| 78 |
+
expected = pd.Series([4, 8, 12], index=Index([1, 2, 3], dtype=np.int64))
|
| 79 |
+
|
| 80 |
+
tm.assert_series_equal(result, expected)
|
shared/package-files/06/0694aa8e6abdae0abf13d62b3765a2cb5042fcb516c5e344fad4281664a3a5c9/_utils.py
ADDED
|
@@ -0,0 +1,1092 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copyreg
|
| 3 |
+
import functools
|
| 4 |
+
import importlib
|
| 5 |
+
import logging
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
import warnings
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from types import ModuleType
|
| 11 |
+
from typing import Any, Callable, Generic, Optional, TYPE_CHECKING
|
| 12 |
+
from typing_extensions import deprecated, ParamSpec
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _type(self, dtype=None, non_blocking=False, **kwargs):
|
| 18 |
+
"""Returns the type if `dtype` is not provided, else casts this object to
|
| 19 |
+
the specified type.
|
| 20 |
+
|
| 21 |
+
If this is already of the correct type, no copy is performed and the
|
| 22 |
+
original object is returned.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
dtype (type or string): The desired type
|
| 26 |
+
non_blocking (bool): If ``True``, and the source is in pinned memory
|
| 27 |
+
and destination is on the GPU or vice versa, the copy is performed
|
| 28 |
+
asynchronously with respect to the host. Otherwise, the argument
|
| 29 |
+
has no effect.
|
| 30 |
+
**kwargs: For compatibility, may contain the key ``async`` in place of
|
| 31 |
+
the ``non_blocking`` argument. The ``async`` arg is deprecated.
|
| 32 |
+
"""
|
| 33 |
+
non_blocking = _get_async_or_non_blocking("type", non_blocking, kwargs)
|
| 34 |
+
if dtype is None:
|
| 35 |
+
return self.__module__ + "." + self.__class__.__name__
|
| 36 |
+
|
| 37 |
+
if isinstance(dtype, str):
|
| 38 |
+
dtype = _import_dotted_name(dtype)
|
| 39 |
+
if dtype == type(self):
|
| 40 |
+
return self
|
| 41 |
+
if self.is_sparse:
|
| 42 |
+
if not dtype.is_sparse:
|
| 43 |
+
raise RuntimeError("Cannot cast sparse tensor to dense tensor")
|
| 44 |
+
new_module_name = dtype.__module__.replace(".sparse", "")
|
| 45 |
+
new_values_type_name = new_module_name + "." + dtype.__name__
|
| 46 |
+
new_values = torch.Tensor._values(self).type(new_values_type_name, non_blocking)
|
| 47 |
+
new_indices_type_name = new_module_name + ".LongTensor"
|
| 48 |
+
new_indices = torch.Tensor._indices(self).type(
|
| 49 |
+
new_indices_type_name, non_blocking
|
| 50 |
+
)
|
| 51 |
+
return dtype(new_indices, new_values, self.size())
|
| 52 |
+
if dtype.is_sparse:
|
| 53 |
+
raise RuntimeError("Cannot cast dense tensor to sparse tensor")
|
| 54 |
+
return dtype(self.size()).copy_(self, non_blocking)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _to(self, device, non_blocking=False):
|
| 58 |
+
"""Returns a copy of this object in device memory.
|
| 59 |
+
|
| 60 |
+
If this object is already on the correct device, then no copy is performed
|
| 61 |
+
and the original object is returned.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
device (int): The destination device.
|
| 65 |
+
non_blocking (bool): If ``True`` and the source is in pinned memory,
|
| 66 |
+
the copy will be asynchronous with respect to the host. Otherwise,
|
| 67 |
+
the argument has no effect.
|
| 68 |
+
"""
|
| 69 |
+
if self.device == device:
|
| 70 |
+
return self
|
| 71 |
+
|
| 72 |
+
if device.type == "cpu":
|
| 73 |
+
pin_memory = non_blocking and self.device.type in (
|
| 74 |
+
"cuda",
|
| 75 |
+
torch._C._get_privateuse1_backend_name(),
|
| 76 |
+
)
|
| 77 |
+
untyped_storage = torch.empty(
|
| 78 |
+
self.nbytes(), dtype=torch.uint8, device=device, pin_memory=pin_memory
|
| 79 |
+
).untyped_storage()
|
| 80 |
+
untyped_storage.copy_(self, non_blocking)
|
| 81 |
+
return untyped_storage
|
| 82 |
+
|
| 83 |
+
device_module = getattr(torch, device.type, None)
|
| 84 |
+
assert device_module is not None, (
|
| 85 |
+
f"{device.type.upper()} device module is not loaded"
|
| 86 |
+
)
|
| 87 |
+
with device_module.device(device):
|
| 88 |
+
if self.is_sparse and hasattr(device_module, "sparse"):
|
| 89 |
+
new_type = getattr(device_module.sparse, self.__class__.__name__)
|
| 90 |
+
indices = getattr(torch.Tensor._indices(self), device.type)(
|
| 91 |
+
device, non_blocking
|
| 92 |
+
)
|
| 93 |
+
values = getattr(torch.Tensor._values(self), device.type)(
|
| 94 |
+
device, non_blocking
|
| 95 |
+
)
|
| 96 |
+
return new_type(indices, values, self.size())
|
| 97 |
+
else:
|
| 98 |
+
assert not self.is_sparse, (
|
| 99 |
+
f"sparse storage is not supported for {device.type.upper()} tensors"
|
| 100 |
+
)
|
| 101 |
+
untyped_storage = torch.UntypedStorage(self.size(), device=device)
|
| 102 |
+
untyped_storage.copy_(self, non_blocking)
|
| 103 |
+
return untyped_storage
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _get_async_or_non_blocking(function_name, non_blocking, kwargs):
|
| 107 |
+
"""Return the non-blocking flag given the function name and kwargs.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
function_name (str): the name of the function being used.
|
| 111 |
+
non_blocking (bool): the default value.
|
| 112 |
+
**kwargs (dict): the kwargs passed to the function.
|
| 113 |
+
"""
|
| 114 |
+
if not kwargs:
|
| 115 |
+
return non_blocking
|
| 116 |
+
if len(kwargs) != 1 or "async" not in kwargs:
|
| 117 |
+
message = "{}() got an unexpected keyword argument '{}'"
|
| 118 |
+
argument = list(kwargs.keys()).pop()
|
| 119 |
+
raise TypeError(message.format(function_name, argument))
|
| 120 |
+
warnings.warn("'async' is deprecated; use 'non_blocking'")
|
| 121 |
+
return kwargs["async"]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _get_restore_location(device):
|
| 125 |
+
"""Return the map_location location.
|
| 126 |
+
|
| 127 |
+
Used for rebuild functions where the tensor device is distinct from the storage
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
map_location = torch.serialization._serialization_tls.map_location
|
| 131 |
+
if map_location is None:
|
| 132 |
+
return device
|
| 133 |
+
else:
|
| 134 |
+
if isinstance(map_location, dict):
|
| 135 |
+
return map_location.get(device, device)
|
| 136 |
+
elif isinstance(map_location, (str, torch.device)):
|
| 137 |
+
return map_location
|
| 138 |
+
else:
|
| 139 |
+
assert callable(map_location)
|
| 140 |
+
raise RuntimeError(
|
| 141 |
+
"Callable map_location not supported with _rebuild_wrapper_subclass "
|
| 142 |
+
"or _rebuild_device_tensor_from_numpy"
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# Note [Don't serialize hooks]
|
| 147 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 148 |
+
# Since time immemorial, we have serialized the backward hooks associated with
|
| 149 |
+
# variables. This kind of half-worked--Python can pickle global functions
|
| 150 |
+
# (but not closures!)--but there were problems.
|
| 151 |
+
#
|
| 152 |
+
# - It's fragile. If you serialize a backward hook into a saved
|
| 153 |
+
# model, and then you rename the function associated with the hook,
|
| 154 |
+
# now your saved model is broken and you can't load it anymore.
|
| 155 |
+
#
|
| 156 |
+
# - It's not actually used. The standard recommendation is to
|
| 157 |
+
# serialize the *state_dict* of a model, not the model itself
|
| 158 |
+
# (since this is more stable to code changes affecting the model
|
| 159 |
+
# serialization), and the state dict saves "data" only, thus
|
| 160 |
+
# stripping the backward hooks. In some cases, hooks are
|
| 161 |
+
# essential to the well-functioning of a model (e.g., DDP),
|
| 162 |
+
# but DDP already manages readding the hooks!
|
| 163 |
+
#
|
| 164 |
+
# - We didn't serialize them in many cases. Prior to #10220, we
|
| 165 |
+
# were dropping backward hooks in ForkingPickler. We "fixed" this
|
| 166 |
+
# to be convenient with other serialization sites, but lack of
|
| 167 |
+
# serializing backward hooks wasn't actually the root cause of
|
| 168 |
+
# the bug.
|
| 169 |
+
#
|
| 170 |
+
# With these cases in mind, we have decided that a better strategy
|
| 171 |
+
# is to just NOT serialize hooks at all.
|
| 172 |
+
#
|
| 173 |
+
# Since this is a BC-breaking change, we should warn when we previously
|
| 174 |
+
# serialized a hook, but no longer do so. This will be done by adding a special
|
| 175 |
+
# sentinel property to hooks will be used to suppress this warning. If a hook
|
| 176 |
+
# has the property _torch_serialize_ignore, we will not emit a warning if we
|
| 177 |
+
# attempt to serialize a Tensor with this hook attached to it.
|
| 178 |
+
#
|
| 179 |
+
# By the way, when _backward_hooks is skipped, we must give an EMPTY
|
| 180 |
+
# OrderedDict(), if you pass a None you'll run afoul #12219.
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# TODO: Once we decide to break serialization FC, `storage` no longer needs to
|
| 184 |
+
# be a TypedStorage
|
| 185 |
+
def _rebuild_tensor(storage, storage_offset, size, stride):
|
| 186 |
+
# first construct a tensor with the correct dtype/device
|
| 187 |
+
t = torch.empty((0,), dtype=storage.dtype, device=storage._untyped_storage.device)
|
| 188 |
+
return t.set_(storage._untyped_storage, storage_offset, size, stride)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def get_tensor_metadata(tensor):
|
| 192 |
+
# Tensor's Metadata for serializing.
|
| 193 |
+
# Currently, this only returns a dict[string, bool] specifing whether
|
| 194 |
+
# `conj` or `neg` bit is set.
|
| 195 |
+
assert isinstance(tensor, torch.Tensor)
|
| 196 |
+
return torch._C._get_tensor_metadata(tensor) # type: ignore[attr-defined]
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def set_tensor_metadata(tensor, metadata):
|
| 200 |
+
# See `get_tensor_metadata` above
|
| 201 |
+
assert isinstance(metadata, dict)
|
| 202 |
+
assert isinstance(tensor, torch.Tensor)
|
| 203 |
+
torch._C._set_tensor_metadata(tensor, metadata) # type: ignore[attr-defined]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _restore_device_fake_mode(tensor):
|
| 207 |
+
if torch._guards.detect_fake_mode(None) is not None:
|
| 208 |
+
if tensor.untyped_storage()._fake_device is not None:
|
| 209 |
+
device = _get_restore_location(tensor.untyped_storage()._fake_device)
|
| 210 |
+
if not isinstance(device, torch.device):
|
| 211 |
+
device = torch.device(device)
|
| 212 |
+
tensor.fake_device = torch.device(device)
|
| 213 |
+
return tensor
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _rebuild_tensor_v2(
|
| 217 |
+
storage,
|
| 218 |
+
storage_offset,
|
| 219 |
+
size,
|
| 220 |
+
stride,
|
| 221 |
+
requires_grad,
|
| 222 |
+
backward_hooks,
|
| 223 |
+
metadata=None,
|
| 224 |
+
):
|
| 225 |
+
tensor = _rebuild_tensor(storage, storage_offset, size, stride)
|
| 226 |
+
tensor.requires_grad = requires_grad
|
| 227 |
+
if metadata:
|
| 228 |
+
set_tensor_metadata(tensor, metadata)
|
| 229 |
+
|
| 230 |
+
# NB: This line exists only for backwards compatibility; the
|
| 231 |
+
# general expectation is that backward_hooks is an empty
|
| 232 |
+
# OrderedDict. See Note [Don't serialize hooks]
|
| 233 |
+
tensor._backward_hooks = backward_hooks
|
| 234 |
+
|
| 235 |
+
tensor = _restore_device_fake_mode(tensor)
|
| 236 |
+
return tensor
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _rebuild_tensor_v3(
|
| 240 |
+
storage,
|
| 241 |
+
storage_offset,
|
| 242 |
+
size,
|
| 243 |
+
stride,
|
| 244 |
+
requires_grad,
|
| 245 |
+
backward_hooks,
|
| 246 |
+
dtype,
|
| 247 |
+
metadata=None,
|
| 248 |
+
):
|
| 249 |
+
t = torch.empty(
|
| 250 |
+
(0,),
|
| 251 |
+
dtype=dtype,
|
| 252 |
+
device=storage._untyped_storage.device,
|
| 253 |
+
requires_grad=requires_grad,
|
| 254 |
+
)
|
| 255 |
+
t.set_(storage._untyped_storage, storage_offset, size, stride)
|
| 256 |
+
if metadata:
|
| 257 |
+
set_tensor_metadata(t, metadata)
|
| 258 |
+
t._backward_hooks = backward_hooks
|
| 259 |
+
t = _restore_device_fake_mode(t)
|
| 260 |
+
return t
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
_sparse_tensors_to_validate: list["torch.Tensor"] = []
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# In _legacy_load() in serialization.py we unpickle storages after the sparse
|
| 267 |
+
# tensors have been already unpickled. Those storages contain data necessary for
|
| 268 |
+
# validating sparse tensors: indices and values. That's why sparse tensors are
|
| 269 |
+
# first unpickled without any validation, and then this function is called just
|
| 270 |
+
# before _legacy_load() returns, so that all the sparse tensors can be validated
|
| 271 |
+
# in bulk.
|
| 272 |
+
#
|
| 273 |
+
# The same procedure must be followed by _load() in serialization.py because due
|
| 274 |
+
# to Pickler semantics, we have to use the same (non-validating) function for
|
| 275 |
+
# unpickling sparse tensors, regardless of the caller.
|
| 276 |
+
def _validate_loaded_sparse_tensors():
|
| 277 |
+
try:
|
| 278 |
+
for t in _sparse_tensors_to_validate:
|
| 279 |
+
if t.layout is torch.sparse_coo:
|
| 280 |
+
torch._validate_sparse_coo_tensor_args(
|
| 281 |
+
t._indices(), t._values(), t.size(), t.is_coalesced()
|
| 282 |
+
)
|
| 283 |
+
elif t.layout in {
|
| 284 |
+
torch.sparse_csr,
|
| 285 |
+
torch.sparse_csc,
|
| 286 |
+
torch.sparse_bsr,
|
| 287 |
+
torch.sparse_bsc,
|
| 288 |
+
}:
|
| 289 |
+
# TODO: Validation currently involves an expensive traversal
|
| 290 |
+
# on CPU, which may include a device transfer.
|
| 291 |
+
if t.layout in {torch.sparse_csr, torch.sparse_bsr}:
|
| 292 |
+
compressed_indices, plain_indices = (
|
| 293 |
+
t.crow_indices(),
|
| 294 |
+
t.col_indices(),
|
| 295 |
+
)
|
| 296 |
+
else:
|
| 297 |
+
compressed_indices, plain_indices = (
|
| 298 |
+
t.ccol_indices(),
|
| 299 |
+
t.row_indices(),
|
| 300 |
+
)
|
| 301 |
+
torch._validate_sparse_compressed_tensor_args(
|
| 302 |
+
compressed_indices, plain_indices, t.values(), t.size(), t.layout
|
| 303 |
+
)
|
| 304 |
+
else:
|
| 305 |
+
raise NotImplementedError(
|
| 306 |
+
f"_validate_loaded_sparse_tensors for layout `{t.layout}`"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
finally:
|
| 310 |
+
_sparse_tensors_to_validate.clear()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _rebuild_sparse_tensor(layout, data):
|
| 314 |
+
"""
|
| 315 |
+
Rebuilds a sparse tensor from its sparse storage representation.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
layout (str): The sparse storage layout of the tensor.
|
| 319 |
+
data (tuple): The tensor's sparse storage representation.
|
| 320 |
+
"""
|
| 321 |
+
if layout == torch.sparse_coo:
|
| 322 |
+
if len(data) == 3:
|
| 323 |
+
# For BC:
|
| 324 |
+
indices, values, size = data
|
| 325 |
+
is_coalesced = None
|
| 326 |
+
else:
|
| 327 |
+
indices, values, size, is_coalesced = data
|
| 328 |
+
result = torch.sparse_coo_tensor(
|
| 329 |
+
indices, values, size, check_invariants=False, is_coalesced=is_coalesced
|
| 330 |
+
)
|
| 331 |
+
_sparse_tensors_to_validate.append(result)
|
| 332 |
+
return result
|
| 333 |
+
|
| 334 |
+
elif layout in {
|
| 335 |
+
torch.sparse_csr,
|
| 336 |
+
torch.sparse_csc,
|
| 337 |
+
torch.sparse_bsr,
|
| 338 |
+
torch.sparse_bsc,
|
| 339 |
+
}:
|
| 340 |
+
compressed_indices, plain_indices, values, size = data
|
| 341 |
+
result = torch.sparse_compressed_tensor(
|
| 342 |
+
compressed_indices,
|
| 343 |
+
plain_indices,
|
| 344 |
+
values,
|
| 345 |
+
size,
|
| 346 |
+
layout=layout,
|
| 347 |
+
check_invariants=False,
|
| 348 |
+
)
|
| 349 |
+
_sparse_tensors_to_validate.append(result)
|
| 350 |
+
return result
|
| 351 |
+
|
| 352 |
+
raise NotImplementedError(f"rebuilding sparse tensor for layout {layout}")
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _rebuild_nested_tensor(buffer, sizes, strides, storage_offsets):
|
| 356 |
+
return torch._nested_view_from_buffer(buffer, sizes, strides, storage_offsets)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _rebuild_device_tensor_from_cpu_tensor(data, dtype, device, requires_grad):
|
| 360 |
+
device = _get_restore_location(device)
|
| 361 |
+
tensor = data.to(dtype=dtype, device=device)
|
| 362 |
+
tensor.requires_grad = requires_grad
|
| 363 |
+
return tensor
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _rebuild_device_tensor_from_numpy(data, dtype, device, requires_grad):
|
| 367 |
+
device = _get_restore_location(device)
|
| 368 |
+
tensor = torch.from_numpy(data).to(dtype=dtype, device=device)
|
| 369 |
+
tensor.requires_grad = requires_grad
|
| 370 |
+
return tensor
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# Should not be used, only here to be able to load Tensors serialized with older versions of pytorch
|
| 374 |
+
_rebuild_xla_tensor = _rebuild_device_tensor_from_numpy
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _rebuild_meta_tensor_no_storage(dtype, size, stride, requires_grad):
|
| 378 |
+
return torch.empty_strided(
|
| 379 |
+
size, stride, dtype=dtype, device="meta", requires_grad=requires_grad
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _rebuild_wrapper_subclass(
|
| 384 |
+
cls,
|
| 385 |
+
dtype,
|
| 386 |
+
size,
|
| 387 |
+
stride,
|
| 388 |
+
storage_offset,
|
| 389 |
+
layout,
|
| 390 |
+
device,
|
| 391 |
+
requires_grad,
|
| 392 |
+
):
|
| 393 |
+
device = _get_restore_location(device)
|
| 394 |
+
return torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined]
|
| 395 |
+
cls,
|
| 396 |
+
size,
|
| 397 |
+
strides=stride,
|
| 398 |
+
dtype=dtype,
|
| 399 |
+
storage_offset=storage_offset,
|
| 400 |
+
layout=layout,
|
| 401 |
+
device=device,
|
| 402 |
+
requires_grad=requires_grad,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
# TODO: Once we decide to break serialization FC, `storage` no longer needs to
|
| 407 |
+
# be a TypedStorage
|
| 408 |
+
def _rebuild_qtensor(
|
| 409 |
+
storage,
|
| 410 |
+
storage_offset,
|
| 411 |
+
size,
|
| 412 |
+
stride,
|
| 413 |
+
quantizer_params,
|
| 414 |
+
requires_grad,
|
| 415 |
+
backward_hooks,
|
| 416 |
+
):
|
| 417 |
+
qscheme = quantizer_params[0]
|
| 418 |
+
if qscheme == torch.per_tensor_affine:
|
| 419 |
+
_, scale, zero_point = quantizer_params
|
| 420 |
+
tensor = torch._empty_affine_quantized(
|
| 421 |
+
size,
|
| 422 |
+
scale=scale,
|
| 423 |
+
zero_point=zero_point,
|
| 424 |
+
dtype=storage.dtype,
|
| 425 |
+
device=storage.device,
|
| 426 |
+
)
|
| 427 |
+
elif qscheme in (torch.per_channel_affine, torch.per_channel_affine_float_qparams):
|
| 428 |
+
_, scales, zero_points, axis = quantizer_params
|
| 429 |
+
if type(scales) is list and type(zero_points) is list:
|
| 430 |
+
if qscheme == torch.per_channel_affine:
|
| 431 |
+
scales = torch.tensor(scales, dtype=torch.double, device=storage.device)
|
| 432 |
+
zero_points = torch.tensor(
|
| 433 |
+
zero_points, dtype=torch.long, device=storage.device
|
| 434 |
+
)
|
| 435 |
+
else:
|
| 436 |
+
scales = torch.tensor(scales, dtype=torch.float, device=storage.device)
|
| 437 |
+
zero_points = torch.tensor(
|
| 438 |
+
zero_points, dtype=torch.float, device=storage.device
|
| 439 |
+
)
|
| 440 |
+
tensor = torch._empty_per_channel_affine_quantized(
|
| 441 |
+
size,
|
| 442 |
+
scales=scales,
|
| 443 |
+
zero_points=zero_points,
|
| 444 |
+
axis=axis,
|
| 445 |
+
dtype=storage.dtype,
|
| 446 |
+
device=storage.device,
|
| 447 |
+
)
|
| 448 |
+
else:
|
| 449 |
+
raise RuntimeError(f"Can't deserialize quantized tensor with qscheme {qscheme}")
|
| 450 |
+
tensor.set_(storage, storage_offset, size, stride)
|
| 451 |
+
tensor.requires_grad = requires_grad
|
| 452 |
+
# NB: This line exists only for backwards compatibility; the
|
| 453 |
+
# general expectation is that backward_hooks is an empty
|
| 454 |
+
# OrderedDict. See Note [Don't serialize hooks]
|
| 455 |
+
tensor._backward_hooks = backward_hooks
|
| 456 |
+
return tensor
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _rebuild_parameter(data, requires_grad, backward_hooks):
|
| 460 |
+
param = torch.nn.Parameter(data, requires_grad)
|
| 461 |
+
# NB: This line exists only for backwards compatibility; the
|
| 462 |
+
# general expectation is that backward_hooks is an empty
|
| 463 |
+
# OrderedDict. See Note [Don't serialize hooks]
|
| 464 |
+
param._backward_hooks = backward_hooks
|
| 465 |
+
|
| 466 |
+
return param
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _rebuild_parameter_with_state(data, requires_grad, backward_hooks, state):
|
| 470 |
+
param = torch.nn.Parameter(data, requires_grad)
|
| 471 |
+
# NB: This line exists only for backwards compatibility; the
|
| 472 |
+
# general expectation is that backward_hooks is an empty
|
| 473 |
+
# OrderedDict. See Note [Don't serialize hooks]
|
| 474 |
+
param._backward_hooks = backward_hooks
|
| 475 |
+
|
| 476 |
+
# Restore state on Parameter like python attr.
|
| 477 |
+
param = _set_obj_state(param, state)
|
| 478 |
+
return param
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def _get_obj_state(obj):
|
| 482 |
+
# Get the state of the python subclass
|
| 483 |
+
# This loosely mimicks the function on the object class but since Tensor do not inherit
|
| 484 |
+
# from it, we cannot call that function directly
|
| 485 |
+
# https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891
|
| 486 |
+
# Note that starting with Python 3.11, this `__getstate__` is always defined and thus
|
| 487 |
+
# the else branch will never be taken.
|
| 488 |
+
getstate_fn = getattr(obj, "__getstate__", None)
|
| 489 |
+
if getstate_fn:
|
| 490 |
+
state = getstate_fn()
|
| 491 |
+
else:
|
| 492 |
+
slots_to_save = copyreg._slotnames(obj.__class__) # type: ignore[attr-defined]
|
| 493 |
+
if slots_to_save:
|
| 494 |
+
state = (
|
| 495 |
+
obj.__dict__,
|
| 496 |
+
{
|
| 497 |
+
name: getattr(obj, name)
|
| 498 |
+
for name in slots_to_save
|
| 499 |
+
if hasattr(obj, name)
|
| 500 |
+
},
|
| 501 |
+
)
|
| 502 |
+
else:
|
| 503 |
+
state = obj.__dict__
|
| 504 |
+
|
| 505 |
+
return state
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def _set_obj_state(obj, state):
|
| 509 |
+
if isinstance(state, tuple):
|
| 510 |
+
if not len(state) == 2:
|
| 511 |
+
raise RuntimeError(f"Invalid serialized state: {state}")
|
| 512 |
+
dict_state = state[0]
|
| 513 |
+
slots_state = state[1]
|
| 514 |
+
else:
|
| 515 |
+
dict_state = state
|
| 516 |
+
slots_state = None
|
| 517 |
+
|
| 518 |
+
# Starting with Python 3.11, the __dict__ attribute is lazily created
|
| 519 |
+
# and is serialized as None when not needed.
|
| 520 |
+
if dict_state:
|
| 521 |
+
for k, v in dict_state.items():
|
| 522 |
+
setattr(obj, k, v)
|
| 523 |
+
|
| 524 |
+
if slots_state:
|
| 525 |
+
for k, v in slots_state.items():
|
| 526 |
+
setattr(obj, k, v)
|
| 527 |
+
return obj
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _import_dotted_name(name):
|
| 531 |
+
components = name.split(".")
|
| 532 |
+
obj = __import__(components[0])
|
| 533 |
+
for component in components[1:]:
|
| 534 |
+
obj = getattr(obj, component)
|
| 535 |
+
return obj
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _flatten_dense_tensors(tensors):
|
| 539 |
+
"""Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of
|
| 540 |
+
same dense type.
|
| 541 |
+
|
| 542 |
+
Since inputs are dense, the resulting tensor will be a concatenated 1D
|
| 543 |
+
buffer. Element-wise operation on this buffer will be equivalent to
|
| 544 |
+
operating individually.
|
| 545 |
+
|
| 546 |
+
Args:
|
| 547 |
+
tensors (Iterable[Tensor]): dense tensors to flatten.
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
A contiguous 1D buffer containing input tensors.
|
| 551 |
+
"""
|
| 552 |
+
return torch._C._nn.flatten_dense_tensors(tensors)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def _flatten_sparse_tensors(tensors):
|
| 556 |
+
"""Flatten sparse tensors into two contiguous 1D buffers, one of indices and
|
| 557 |
+
one of values. Assume tensors are of same sparse type.
|
| 558 |
+
|
| 559 |
+
Args:
|
| 560 |
+
tensors (Iterable[Tensor]): sparse tensors to flatten.
|
| 561 |
+
|
| 562 |
+
Returns:
|
| 563 |
+
A tuple of two contiguous 1D buffers, one containing input tensors'
|
| 564 |
+
indices and the other containing the values.
|
| 565 |
+
"""
|
| 566 |
+
flat_indices = torch._C._nn.flatten_dense_tensors(
|
| 567 |
+
[torch.Tensor._indices(t) for t in tensors]
|
| 568 |
+
)
|
| 569 |
+
flat_values = torch._C._nn.flatten_dense_tensors(
|
| 570 |
+
[torch.Tensor._values(t) for t in tensors]
|
| 571 |
+
)
|
| 572 |
+
return flat_indices, flat_values
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _unflatten_dense_tensors(flat, tensors):
|
| 576 |
+
"""View a flat buffer using the sizes of tensors. Assume that tensors are of
|
| 577 |
+
same dense type, and that flat is given by _flatten_dense_tensors.
|
| 578 |
+
|
| 579 |
+
Args:
|
| 580 |
+
flat (Tensor): flattened dense tensors to unflatten.
|
| 581 |
+
tensors (Iterable[Tensor]): dense tensors whose sizes will be used to
|
| 582 |
+
unflatten flat.
|
| 583 |
+
|
| 584 |
+
Returns:
|
| 585 |
+
Unflattened dense tensors with sizes same as tensors and values from
|
| 586 |
+
flat.
|
| 587 |
+
"""
|
| 588 |
+
return torch._C._nn.unflatten_dense_tensors(flat, tensors)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def _unflatten_sparse_tensors(flat, tensors):
|
| 592 |
+
"""View flat buffer (containing indices and values) using the sizes of
|
| 593 |
+
tensors. Assume that tensors are of same sparse type, and that flat is given
|
| 594 |
+
by _flatten_sparse_tensors.
|
| 595 |
+
|
| 596 |
+
Args:
|
| 597 |
+
flat (tuple(Tensor, Tensor)): flattened indices and values of sparse
|
| 598 |
+
tensors to unflatten.
|
| 599 |
+
tensors (Iterable[Tensor]): sparse tensors whose sizes will be used to
|
| 600 |
+
unflatten flat.
|
| 601 |
+
|
| 602 |
+
Returns:
|
| 603 |
+
Unflattened sparse tensors with sizes same as tensors and values from
|
| 604 |
+
flat.
|
| 605 |
+
"""
|
| 606 |
+
flat_indices, flat_values = flat
|
| 607 |
+
indices = torch._C._nn.unflatten_dense_tensors(
|
| 608 |
+
flat_indices, [torch.Tensor._indices(t) for t in tensors]
|
| 609 |
+
)
|
| 610 |
+
values = torch._C._nn.unflatten_dense_tensors(
|
| 611 |
+
flat_values, [torch.Tensor._values(t) for t in tensors]
|
| 612 |
+
)
|
| 613 |
+
outputs = []
|
| 614 |
+
for t, i, v in zip(tensors, indices, values):
|
| 615 |
+
outputs.append(t.new(i, v, t.size()))
|
| 616 |
+
return tuple(outputs)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def _reorder_tensors_as(tensors, ordered_tensors):
|
| 620 |
+
"""Assume that tensors are of same order as ordered_tensors within their
|
| 621 |
+
types, e.g., from _take_tensors. Reorder them to be of same order as
|
| 622 |
+
ordered_tensors.
|
| 623 |
+
|
| 624 |
+
Args:
|
| 625 |
+
tensors (Iterable[Tensor]): tensors to be reordered. They should be of
|
| 626 |
+
the same order as ordered_tensors within their own types.
|
| 627 |
+
ordered_tensors (Iterable[Tensor]): tensors whose order will be the
|
| 628 |
+
reference.
|
| 629 |
+
|
| 630 |
+
Returns:
|
| 631 |
+
Ordered tuple of tensors with contents from tensors and order of
|
| 632 |
+
ordered_tensors.
|
| 633 |
+
"""
|
| 634 |
+
type_dict = defaultdict(list)
|
| 635 |
+
for tensor in tensors:
|
| 636 |
+
type_dict[tensor.type()].append(tensor)
|
| 637 |
+
type_dict_ = {t: iter(coll) for t, coll in type_dict.items()}
|
| 638 |
+
return tuple(next(type_dict_[tensor.type()]) for tensor in ordered_tensors)
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def _take_tensors(tensors, size_limit):
|
| 642 |
+
"""Group tensors into chunks. This generator yields a chunk at each time,
|
| 643 |
+
each containing tensors of same type up to certain byte limit in total size.
|
| 644 |
+
|
| 645 |
+
Args:
|
| 646 |
+
tensors (Sequence): A sequence of tensors to be separated into chunks.
|
| 647 |
+
size_limit (int): The limit of each chunk in bytes.
|
| 648 |
+
|
| 649 |
+
Yields:
|
| 650 |
+
Blocks of tensors of same type and within size_limit. The yielded
|
| 651 |
+
tensors are only ordered as the original sequence within its types.
|
| 652 |
+
"""
|
| 653 |
+
buf_dict: defaultdict[str, list] = defaultdict(lambda: [[], 0])
|
| 654 |
+
for tensor in tensors:
|
| 655 |
+
t = tensor.type()
|
| 656 |
+
if tensor.is_sparse:
|
| 657 |
+
indices = torch.Tensor._indices(tensor)
|
| 658 |
+
values = torch.Tensor._values(tensor)
|
| 659 |
+
size = (
|
| 660 |
+
indices.numel() * indices.element_size()
|
| 661 |
+
+ values.numel() * values.element_size()
|
| 662 |
+
)
|
| 663 |
+
else:
|
| 664 |
+
size = tensor.numel() * tensor.element_size()
|
| 665 |
+
buf_and_size = buf_dict[t]
|
| 666 |
+
if buf_and_size[1] + size > size_limit and buf_and_size[1] > 0:
|
| 667 |
+
yield buf_and_size[0]
|
| 668 |
+
buf_and_size = buf_dict[t] = [[], 0]
|
| 669 |
+
buf_and_size[0].append(tensor)
|
| 670 |
+
buf_and_size[1] += size
|
| 671 |
+
for buf, _ in buf_dict.values():
|
| 672 |
+
if len(buf) > 0:
|
| 673 |
+
yield buf
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
# annotation decorator to get annotations in a way that is compatible
|
| 677 |
+
# with both Python 2 and 3
|
| 678 |
+
def annotate(ret, **kwargs):
|
| 679 |
+
def dec(fun):
|
| 680 |
+
fun.__annotations__ = dict(kwargs)
|
| 681 |
+
fun.__annotations__["return"] = ret
|
| 682 |
+
return fun
|
| 683 |
+
|
| 684 |
+
return dec
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def render_call(fn, args, kwargs):
|
| 688 |
+
str_fn = torch.overrides.resolve_name(fn)
|
| 689 |
+
if str_fn is None:
|
| 690 |
+
str_fn = str(fn)
|
| 691 |
+
|
| 692 |
+
str_args: list[str] = []
|
| 693 |
+
with torch._tensor_str.printoptions(threshold=0, edgeitems=0):
|
| 694 |
+
str_args.extend(repr(a) for a in args)
|
| 695 |
+
str_args.extend(f"{k}={repr(v)}" for k, v in kwargs.items())
|
| 696 |
+
r = f"{str_fn}({', '.join(str_args)})"
|
| 697 |
+
return r
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
# NOTE [ Python Traceback Reference Cycle Problem ]
|
| 701 |
+
#
|
| 702 |
+
# When using sys.exc_info(), it is important to **not** store the exc_info[2],
|
| 703 |
+
# which is the traceback, because otherwise you will run into the traceback
|
| 704 |
+
# reference cycle problem, i.e., the traceback holding reference to the frame,
|
| 705 |
+
# and the frame (which holds reference to all the object in its temporary scope)
|
| 706 |
+
# holding reference the traceback.
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class KeyErrorMessage(str):
|
| 710 |
+
r"""str subclass that returns itself in repr"""
|
| 711 |
+
|
| 712 |
+
__slots__ = ()
|
| 713 |
+
|
| 714 |
+
def __repr__(self):
|
| 715 |
+
return self
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
class ExceptionWrapper:
|
| 719 |
+
r"""Wraps an exception plus traceback to communicate across threads"""
|
| 720 |
+
|
| 721 |
+
def __init__(self, exc_info=None, where="in background"):
|
| 722 |
+
# It is important that we don't store exc_info, see
|
| 723 |
+
# NOTE [ Python Traceback Reference Cycle Problem ]
|
| 724 |
+
if exc_info is None:
|
| 725 |
+
exc_info = sys.exc_info()
|
| 726 |
+
self.exc_type = exc_info[0]
|
| 727 |
+
self.exc_msg = "".join(traceback.format_exception(*exc_info))
|
| 728 |
+
self.where = where
|
| 729 |
+
|
| 730 |
+
def reraise(self):
|
| 731 |
+
r"""Reraises the wrapped exception in the current thread"""
|
| 732 |
+
# Format a message such as: "Caught ValueError in DataLoader worker
|
| 733 |
+
# process 2. Original Traceback:", followed by the traceback.
|
| 734 |
+
msg = f"Caught {self.exc_type.__name__} {self.where}.\nOriginal {self.exc_msg}"
|
| 735 |
+
if self.exc_type == KeyError:
|
| 736 |
+
# KeyError calls repr() on its argument (usually a dict key). This
|
| 737 |
+
# makes stack traces unreadable. It will not be changed in Python
|
| 738 |
+
# (https://bugs.python.org/issue2651), so we work around it.
|
| 739 |
+
msg = KeyErrorMessage(msg)
|
| 740 |
+
elif getattr(self.exc_type, "message", None):
|
| 741 |
+
# Some exceptions have first argument as non-str but explicitly
|
| 742 |
+
# have message field
|
| 743 |
+
raise self.exc_type(message=msg)
|
| 744 |
+
try:
|
| 745 |
+
exception = self.exc_type(msg)
|
| 746 |
+
except Exception:
|
| 747 |
+
# If the exception takes multiple arguments or otherwise can't
|
| 748 |
+
# be constructed, don't try to instantiate since we don't know how to
|
| 749 |
+
raise RuntimeError(msg) from None
|
| 750 |
+
raise exception
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def _get_available_device_type():
|
| 754 |
+
if torch.cuda.is_available():
|
| 755 |
+
return "cuda"
|
| 756 |
+
if torch.backends.mps.is_available():
|
| 757 |
+
return "mps"
|
| 758 |
+
if hasattr(torch, "xpu") and torch.xpu.is_available(): # type: ignore[attr-defined]
|
| 759 |
+
return "xpu"
|
| 760 |
+
if hasattr(torch, "mtia") and torch.mtia.is_available():
|
| 761 |
+
return "mtia"
|
| 762 |
+
custom_backend_name = torch._C._get_privateuse1_backend_name()
|
| 763 |
+
custom_device_mod = getattr(torch, custom_backend_name, None)
|
| 764 |
+
if custom_device_mod and custom_device_mod.is_available():
|
| 765 |
+
return custom_backend_name
|
| 766 |
+
# add more available device types here
|
| 767 |
+
return None
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _get_device_attr(get_member):
|
| 771 |
+
device_type = _get_available_device_type()
|
| 772 |
+
if device_type and device_type.lower() == "cuda":
|
| 773 |
+
return get_member(torch.cuda)
|
| 774 |
+
if device_type and device_type.lower() == "mps":
|
| 775 |
+
return get_member(torch.mps)
|
| 776 |
+
if device_type and device_type.lower() == "xpu":
|
| 777 |
+
return get_member(torch.xpu) # type: ignore[attr-defined]
|
| 778 |
+
if device_type and device_type.lower() == "mtia":
|
| 779 |
+
return get_member(torch.mtia)
|
| 780 |
+
if device_type == torch._C._get_privateuse1_backend_name():
|
| 781 |
+
return get_member(getattr(torch, device_type))
|
| 782 |
+
# add more available device types here
|
| 783 |
+
return None
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def _get_current_device_index():
|
| 787 |
+
# current device index
|
| 788 |
+
return _get_device_attr(lambda m: m.current_device())
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _get_all_device_indices():
|
| 792 |
+
# all device index
|
| 793 |
+
return _get_device_attr(lambda m: list(range(m.device_count())))
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def _get_devices_properties(device_ids):
|
| 797 |
+
# all device properties
|
| 798 |
+
return [_get_device_attr(lambda m: m.get_device_properties(i)) for i in device_ids]
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def get_current_device_index() -> int:
|
| 802 |
+
r"""Checks if there are CUDA devices available and
|
| 803 |
+
returns the device index of the current default CUDA device.
|
| 804 |
+
Returns -1 in case there are no CUDA devices available.
|
| 805 |
+
Arguments: ``None``
|
| 806 |
+
"""
|
| 807 |
+
if torch.cuda.device_count() > 0:
|
| 808 |
+
return torch.cuda.current_device()
|
| 809 |
+
return -1
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def _get_device_index(
|
| 813 |
+
device: Any,
|
| 814 |
+
optional: bool = False,
|
| 815 |
+
allow_cpu: bool = False,
|
| 816 |
+
) -> int:
|
| 817 |
+
r"""Gets the device index from :attr:`device`, which can be a torch.device
|
| 818 |
+
object, a Python integer, or ``None``.
|
| 819 |
+
|
| 820 |
+
If :attr:`device` is a torch.device object, returns the device index if it
|
| 821 |
+
has index. Note that for a device without a specified index,
|
| 822 |
+
i.e., ``torch.device('xxx')``, this will return the current default
|
| 823 |
+
device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
|
| 824 |
+
CPU devices will be accepted and ``-1`` will be returned in this case.
|
| 825 |
+
|
| 826 |
+
If :attr:`device` is a Python integer, it is returned as is.
|
| 827 |
+
|
| 828 |
+
If :attr:`device` is ``None``, this will return the current default
|
| 829 |
+
device of the supported runtime platform if :attr:`optional` is ``True``.
|
| 830 |
+
i.e., the current default CUDA device will be returned if CUDA runtime is supported.
|
| 831 |
+
"""
|
| 832 |
+
if isinstance(device, str):
|
| 833 |
+
device = torch.device(device)
|
| 834 |
+
device_idx: Optional[int] = None
|
| 835 |
+
if isinstance(device, torch.device):
|
| 836 |
+
if not allow_cpu and device.type == "cpu":
|
| 837 |
+
raise ValueError(f"Expected a non cpu device, but got: {device}")
|
| 838 |
+
device_idx = -1 if device.type == "cpu" else device.index
|
| 839 |
+
if isinstance(device, int):
|
| 840 |
+
device_idx = device
|
| 841 |
+
if device_idx is None:
|
| 842 |
+
if optional:
|
| 843 |
+
# The eager API _get_current_device_index uses `lambda` functions which are
|
| 844 |
+
# not supported in JIT and hence not scriptable. The JIT equivalent API to get
|
| 845 |
+
# the current device index is `get_current_device_index()` which can
|
| 846 |
+
# be scripted. We use is_scripting to check the mode we are in and call the
|
| 847 |
+
# appropriate API.
|
| 848 |
+
if torch.jit.is_scripting():
|
| 849 |
+
device_idx = get_current_device_index()
|
| 850 |
+
else:
|
| 851 |
+
device_idx = _get_current_device_index()
|
| 852 |
+
else:
|
| 853 |
+
raise ValueError(
|
| 854 |
+
f"Expected a torch.device with a specified index or an integer, but got:{device}"
|
| 855 |
+
)
|
| 856 |
+
return device_idx
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def _handle_complex(tensor):
|
| 860 |
+
"""
|
| 861 |
+
Returns a real view of a tensor if complex dtype else just the tensor
|
| 862 |
+
need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule
|
| 863 |
+
"""
|
| 864 |
+
return (
|
| 865 |
+
torch.view_as_real(tensor)
|
| 866 |
+
if not isinstance(tensor, torch.nn.UninitializedParameter)
|
| 867 |
+
and tensor.is_complex()
|
| 868 |
+
else tensor
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def _element_size(dtype):
|
| 873 |
+
"""
|
| 874 |
+
Returns the element size for a dtype, in bytes
|
| 875 |
+
"""
|
| 876 |
+
if not isinstance(dtype, torch.dtype):
|
| 877 |
+
raise RuntimeError(f"expected torch.dtype, but got {type(dtype)}")
|
| 878 |
+
|
| 879 |
+
if dtype.is_complex:
|
| 880 |
+
return torch.finfo(dtype).bits >> 2
|
| 881 |
+
elif dtype.is_floating_point:
|
| 882 |
+
return torch.finfo(dtype).bits >> 3
|
| 883 |
+
elif dtype == torch.bool:
|
| 884 |
+
# NOTE: torch.bool is not supported in torch.iinfo()
|
| 885 |
+
return 1
|
| 886 |
+
else:
|
| 887 |
+
return torch.iinfo(dtype).bits >> 3
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
class _ClassPropertyDescriptor:
|
| 891 |
+
def __init__(self, fget, fset=None):
|
| 892 |
+
self.fget = fget
|
| 893 |
+
|
| 894 |
+
def __get__(self, instance, owner=None):
|
| 895 |
+
if owner is None:
|
| 896 |
+
owner = type(instance)
|
| 897 |
+
return self.fget.__get__(instance, owner)()
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
def classproperty(func):
|
| 901 |
+
if not isinstance(func, (classmethod, staticmethod)):
|
| 902 |
+
func = classmethod(func)
|
| 903 |
+
return _ClassPropertyDescriptor(func)
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
if TYPE_CHECKING:
|
| 907 |
+
# TorchScript does not support `@deprecated`
|
| 908 |
+
# This is a workaround to avoid breaking TorchScript
|
| 909 |
+
@deprecated(
|
| 910 |
+
"`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.",
|
| 911 |
+
category=FutureWarning,
|
| 912 |
+
)
|
| 913 |
+
def is_compiling() -> bool:
|
| 914 |
+
return torch.compiler.is_compiling()
|
| 915 |
+
|
| 916 |
+
else:
|
| 917 |
+
|
| 918 |
+
def is_compiling() -> bool:
|
| 919 |
+
"""
|
| 920 |
+
Indicates whether we are tracing/compiling with torch.compile() or torch.export().
|
| 921 |
+
"""
|
| 922 |
+
warnings.warn( # use `warnings.warn` instead of `@deprecated`
|
| 923 |
+
"`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.",
|
| 924 |
+
# FutureWarning, # TorchScript does not support Warning type
|
| 925 |
+
stacklevel=2,
|
| 926 |
+
)
|
| 927 |
+
return torch.compiler.is_compiling()
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def _functionalize_sync(t):
|
| 931 |
+
# This code lives in python instead of C++ since conditioning on a certain python subclass
|
| 932 |
+
# is much more of a pain in C++.
|
| 933 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 934 |
+
|
| 935 |
+
if isinstance(t, FunctionalTensor):
|
| 936 |
+
# If a FunctionalTensorMode is active while syncing, we don't want it to intercept any ops that get called
|
| 937 |
+
# when we sync our inner tensor.
|
| 938 |
+
# Why?
|
| 939 |
+
# (1) If there are input mutations in the graph, then they will be re-applied during
|
| 940 |
+
# AOTAutograd when we call _sync() from inside of our functionalization kernels.
|
| 941 |
+
# (2) _sync() causes us to regenerate our updated the tensor from the updated base,
|
| 942 |
+
# which dispatches to a bunch of view ops
|
| 943 |
+
# (3) The input to these view ops is our inner FunctionalTensorWrapper
|
| 944 |
+
# (since the sync was called from C++), not the python FunctionalTensor
|
| 945 |
+
# (4) if a python FunctionalTensorMode is active, it will complain when it intercepts
|
| 946 |
+
# the view op, since it will see an input that is a C++ FunctionalTensorWrapper
|
| 947 |
+
# (aka a normal torch.Tensor) instead of a python `FunctionalTensor).
|
| 948 |
+
maybe_functional_mode = torch._C._unset_dispatch_mode(
|
| 949 |
+
torch._C._TorchDispatchModeKey.FUNCTIONAL
|
| 950 |
+
)
|
| 951 |
+
try:
|
| 952 |
+
torch._functionalize_sync(t.elem) # type: ignore[attr-defined]
|
| 953 |
+
finally:
|
| 954 |
+
if maybe_functional_mode is not None:
|
| 955 |
+
torch._C._set_dispatch_mode(maybe_functional_mode)
|
| 956 |
+
else:
|
| 957 |
+
torch._functionalize_sync(t) # type: ignore[attr-defined]
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
@functools.lru_cache(2)
|
| 961 |
+
def _get_device_module(device_type: str):
|
| 962 |
+
device_module = getattr(torch, device_type, None)
|
| 963 |
+
if device_module is None:
|
| 964 |
+
raise RuntimeError(
|
| 965 |
+
f"Device '{device_type}' does not have a corresponding module registered as 'torch.{device_type}'."
|
| 966 |
+
)
|
| 967 |
+
return device_module
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def _dummy_type(name: str) -> type:
|
| 971 |
+
def get_err_fn(is_init: bool):
|
| 972 |
+
def err_fn(obj, *args, **kwargs):
|
| 973 |
+
if is_init:
|
| 974 |
+
class_name = obj.__class__.__name__
|
| 975 |
+
else:
|
| 976 |
+
class_name = obj.__name__
|
| 977 |
+
raise RuntimeError(f"Tried to instantiate dummy base class {class_name}")
|
| 978 |
+
|
| 979 |
+
return err_fn
|
| 980 |
+
|
| 981 |
+
return type(
|
| 982 |
+
name, (object,), {"__init__": get_err_fn(True), "__new__": get_err_fn(False)}
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
class _LazySeedTracker:
|
| 987 |
+
# Since seeding is memory-less, only track the latest seed.
|
| 988 |
+
# Note: `manual_seed_all` followed by `manual_seed` overwrites
|
| 989 |
+
# the seed on current device. We track the order of **latest**
|
| 990 |
+
# calls between these two API.
|
| 991 |
+
def __init__(self):
|
| 992 |
+
self.manual_seed_all_cb = None
|
| 993 |
+
self.manual_seed_cb = None
|
| 994 |
+
self.call_order = []
|
| 995 |
+
|
| 996 |
+
def queue_seed_all(self, cb, traceback):
|
| 997 |
+
self.manual_seed_all_cb = (cb, traceback)
|
| 998 |
+
# update seed_all to be latest
|
| 999 |
+
self.call_order = [self.manual_seed_cb, self.manual_seed_all_cb]
|
| 1000 |
+
|
| 1001 |
+
def queue_seed(self, cb, traceback):
|
| 1002 |
+
self.manual_seed_cb = (cb, traceback)
|
| 1003 |
+
# update seed to be latest
|
| 1004 |
+
self.call_order = [self.manual_seed_all_cb, self.manual_seed_cb]
|
| 1005 |
+
|
| 1006 |
+
def get_calls(self) -> list:
|
| 1007 |
+
return self.call_order
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
logger = logging.getLogger(__name__)
|
| 1011 |
+
P = ParamSpec("P")
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
class CallbackRegistry(Generic[P]):
|
| 1015 |
+
def __init__(self, name: str):
|
| 1016 |
+
self.name = name
|
| 1017 |
+
self.callback_list: list[Callable[P, None]] = []
|
| 1018 |
+
|
| 1019 |
+
def add_callback(self, cb: Callable[P, None]) -> None:
|
| 1020 |
+
self.callback_list.append(cb)
|
| 1021 |
+
|
| 1022 |
+
def fire_callbacks(self, *args: P.args, **kwargs: P.kwargs) -> None:
|
| 1023 |
+
for cb in self.callback_list:
|
| 1024 |
+
try:
|
| 1025 |
+
cb(*args, **kwargs)
|
| 1026 |
+
except Exception:
|
| 1027 |
+
logger.exception(
|
| 1028 |
+
"Exception in callback for %s registered with gpu trace", self.name
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def try_import(module_name: str) -> Optional[ModuleType]:
|
| 1033 |
+
# Implementation based on
|
| 1034 |
+
# https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported
|
| 1035 |
+
if (module := sys.modules.get(module_name, None)) is not None:
|
| 1036 |
+
return module
|
| 1037 |
+
|
| 1038 |
+
if (spec := importlib.util.find_spec(module_name)) is not None:
|
| 1039 |
+
module = importlib.util.module_from_spec(spec)
|
| 1040 |
+
sys.modules[module_name] = module
|
| 1041 |
+
|
| 1042 |
+
# https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.loader
|
| 1043 |
+
# "The finder should always set this attribute"
|
| 1044 |
+
assert spec.loader is not None, "The loader attribute should always be set"
|
| 1045 |
+
spec.loader.exec_module(module)
|
| 1046 |
+
return module
|
| 1047 |
+
|
| 1048 |
+
return None
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
# IMPORT_MAPPING and NAME_MAPPING are adapted from https://github.com/python/cpython/blob/main/Lib/_compat_pickle.py
|
| 1052 |
+
# for use in the weights_only Unpickler.
|
| 1053 |
+
|
| 1054 |
+
IMPORT_MAPPING = {
|
| 1055 |
+
"__builtin__": "builtins",
|
| 1056 |
+
"copy_reg": "copyreg",
|
| 1057 |
+
"Queue": "queue",
|
| 1058 |
+
"repr": "reprlib",
|
| 1059 |
+
"_abcoll": "collections.abc",
|
| 1060 |
+
# Non-mutual mappings.
|
| 1061 |
+
"UserDict": "collections",
|
| 1062 |
+
"UserList": "collections",
|
| 1063 |
+
"UserString": "collections",
|
| 1064 |
+
"whichdb": "dbm",
|
| 1065 |
+
"StringIO": "io",
|
| 1066 |
+
"cStringIO": "io",
|
| 1067 |
+
}
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
# This contains rename rules that are easy to handle. We ignore the more
|
| 1071 |
+
# complex stuff (e.g. mapping the names in the urllib and types modules).
|
| 1072 |
+
# These rules should be run before import names are fixed.
|
| 1073 |
+
NAME_MAPPING = {
|
| 1074 |
+
("__builtin__", "xrange"): ("builtins", "range"),
|
| 1075 |
+
("__builtin__", "reduce"): ("functools", "reduce"),
|
| 1076 |
+
("__builtin__", "intern"): ("sys", "intern"),
|
| 1077 |
+
("__builtin__", "unichr"): ("builtins", "chr"),
|
| 1078 |
+
("__builtin__", "unicode"): ("builtins", "str"),
|
| 1079 |
+
("__builtin__", "long"): ("builtins", "int"),
|
| 1080 |
+
("itertools", "izip"): ("builtins", "zip"),
|
| 1081 |
+
("itertools", "imap"): ("builtins", "map"),
|
| 1082 |
+
("itertools", "ifilter"): ("builtins", "filter"),
|
| 1083 |
+
("itertools", "ifilterfalse"): ("itertools", "filterfalse"),
|
| 1084 |
+
("itertools", "izip_longest"): ("itertools", "zip_longest"),
|
| 1085 |
+
("UserDict", "IterableUserDict"): ("collections", "UserDict"),
|
| 1086 |
+
("UserList", "UserList"): ("collections", "UserList"),
|
| 1087 |
+
("UserString", "UserString"): ("collections", "UserString"),
|
| 1088 |
+
# Non-mutual mappings.
|
| 1089 |
+
("__builtin__", "basestring"): ("builtins", "str"),
|
| 1090 |
+
("exceptions", "StandardError"): ("builtins", "Exception"),
|
| 1091 |
+
("UserDict", "UserDict"): ("collections", "UserDict"),
|
| 1092 |
+
}
|
shared/package-files/06/06956f6920f4f87fb0cf200576d1ae59a12459056ba015ded2b4c98ee68fec51/optimizer.cpython-311.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
shared/package-files/06/0699d0c4bb1c2f84de1d9c11e606461fa20d9980d6c575045724fc6ced2007a5/test_memmap.cpython-311.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
shared/package-files/06/069d05fc41c1970734e24011ffbbc6467d1b2065221582d6c8b194482bbaae74/is_coalesced_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API is_coalesced {
|
| 19 |
+
using schema = bool (const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::is_coalesced";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "is_coalesced(Tensor self) -> bool";
|
| 25 |
+
static bool call(const at::Tensor & self);
|
| 26 |
+
static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/06/069e7437f7ba5cb0a7cc296008d1952d2a6182610f6bb9609d75c7660acf36aa/native_batch_norm_native.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> batch_norm_cpu(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, bool training, double momentum, double eps);
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> batch_norm_cpu_out(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> batch_norm_cuda(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, bool training, double momentum, double eps);
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> batch_norm_cuda_out(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd);
|
| 23 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> mkldnn_batch_norm(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, bool training, double momentum, double eps);
|
| 24 |
+
} // namespace native
|
| 25 |
+
} // namespace at
|
shared/package-files/06/06a35a654cc16c876b3f585bfbc36ce2a2126f0bc917e5ab1395ed5c215794ca/test_empty.cpython-311.pyc
ADDED
|
Binary file (8.27 kB). View file
|
|
|
shared/package-files/06/06a63aae3e1ba541e9ee22604fe402bcc9176f722f5f5ae6b0cf707eeb4ea6d0/basic.cpython-311.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
shared/package-files/06/06a68ea13cc90a1897aaccfe81d32887f3679645b26b8337a5dba0ce00f144d2/sqfreetools.cpython-311.pyc
ADDED
|
Binary file (27 kB). View file
|
|
|
shared/package-files/06/06a7eebedae33b73c47034350de70dcadd9387d629b3ac6e79dd6d118e32b2f9/utils.py
ADDED
|
@@ -0,0 +1,698 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
**Contains**
|
| 3 |
+
|
| 4 |
+
* refraction_angle
|
| 5 |
+
* fresnel_coefficients
|
| 6 |
+
* deviation
|
| 7 |
+
* brewster_angle
|
| 8 |
+
* critical_angle
|
| 9 |
+
* lens_makers_formula
|
| 10 |
+
* mirror_formula
|
| 11 |
+
* lens_formula
|
| 12 |
+
* hyperfocal_distance
|
| 13 |
+
* transverse_magnification
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
__all__ = ['refraction_angle',
|
| 17 |
+
'deviation',
|
| 18 |
+
'fresnel_coefficients',
|
| 19 |
+
'brewster_angle',
|
| 20 |
+
'critical_angle',
|
| 21 |
+
'lens_makers_formula',
|
| 22 |
+
'mirror_formula',
|
| 23 |
+
'lens_formula',
|
| 24 |
+
'hyperfocal_distance',
|
| 25 |
+
'transverse_magnification'
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
from sympy.core.numbers import (Float, I, oo, pi, zoo)
|
| 29 |
+
from sympy.core.singleton import S
|
| 30 |
+
from sympy.core.symbol import Symbol
|
| 31 |
+
from sympy.core.sympify import sympify
|
| 32 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 33 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan)
|
| 34 |
+
from sympy.matrices.dense import Matrix
|
| 35 |
+
from sympy.polys.polytools import cancel
|
| 36 |
+
from sympy.series.limits import Limit
|
| 37 |
+
from sympy.geometry.line import Ray3D
|
| 38 |
+
from sympy.geometry.util import intersection
|
| 39 |
+
from sympy.geometry.plane import Plane
|
| 40 |
+
from sympy.utilities.iterables import is_sequence
|
| 41 |
+
from .medium import Medium
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def refractive_index_of_medium(medium):
|
| 45 |
+
"""
|
| 46 |
+
Helper function that returns refractive index, given a medium
|
| 47 |
+
"""
|
| 48 |
+
if isinstance(medium, Medium):
|
| 49 |
+
n = medium.refractive_index
|
| 50 |
+
else:
|
| 51 |
+
n = sympify(medium)
|
| 52 |
+
return n
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
|
| 56 |
+
"""
|
| 57 |
+
This function calculates transmitted vector after refraction at planar
|
| 58 |
+
surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
|
| 59 |
+
If ``incident`` is a number then treated as angle of incidence (in radians)
|
| 60 |
+
in which case refraction angle is returned.
|
| 61 |
+
|
| 62 |
+
If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
|
| 63 |
+
of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
|
| 64 |
+
plane of separation is not provided and normal is an instance of `Ray3D`,
|
| 65 |
+
``normal`` will be assumed to be intersecting incident ray at the plane of
|
| 66 |
+
separation. This will not be the case when `normal` is a `Matrix` or
|
| 67 |
+
any other sequence.
|
| 68 |
+
If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
|
| 69 |
+
and ``normal`` is not `Ray3D`, output will be a `Matrix`.
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
==========
|
| 73 |
+
|
| 74 |
+
incident : Matrix, Ray3D, sequence or a number
|
| 75 |
+
Incident vector or angle of incidence
|
| 76 |
+
medium1 : sympy.physics.optics.medium.Medium or sympifiable
|
| 77 |
+
Medium 1 or its refractive index
|
| 78 |
+
medium2 : sympy.physics.optics.medium.Medium or sympifiable
|
| 79 |
+
Medium 2 or its refractive index
|
| 80 |
+
normal : Matrix, Ray3D, or sequence
|
| 81 |
+
Normal vector
|
| 82 |
+
plane : Plane
|
| 83 |
+
Plane of separation of the two media.
|
| 84 |
+
|
| 85 |
+
Returns
|
| 86 |
+
=======
|
| 87 |
+
|
| 88 |
+
Returns an angle of refraction or a refracted ray depending on inputs.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy.physics.optics import refraction_angle
|
| 94 |
+
>>> from sympy.geometry import Point3D, Ray3D, Plane
|
| 95 |
+
>>> from sympy.matrices import Matrix
|
| 96 |
+
>>> from sympy import symbols, pi
|
| 97 |
+
>>> n = Matrix([0, 0, 1])
|
| 98 |
+
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
| 99 |
+
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
| 100 |
+
>>> refraction_angle(r1, 1, 1, n)
|
| 101 |
+
Matrix([
|
| 102 |
+
[ 1],
|
| 103 |
+
[ 1],
|
| 104 |
+
[-1]])
|
| 105 |
+
>>> refraction_angle(r1, 1, 1, plane=P)
|
| 106 |
+
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
|
| 107 |
+
|
| 108 |
+
With different index of refraction of the two media
|
| 109 |
+
|
| 110 |
+
>>> n1, n2 = symbols('n1, n2')
|
| 111 |
+
>>> refraction_angle(r1, n1, n2, n)
|
| 112 |
+
Matrix([
|
| 113 |
+
[ n1/n2],
|
| 114 |
+
[ n1/n2],
|
| 115 |
+
[-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
|
| 116 |
+
>>> refraction_angle(r1, n1, n2, plane=P)
|
| 117 |
+
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
|
| 118 |
+
>>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
|
| 119 |
+
0.41152
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
n1 = refractive_index_of_medium(medium1)
|
| 123 |
+
n2 = refractive_index_of_medium(medium2)
|
| 124 |
+
|
| 125 |
+
# check if an incidence angle was supplied instead of a ray
|
| 126 |
+
try:
|
| 127 |
+
angle_of_incidence = float(incident)
|
| 128 |
+
except TypeError:
|
| 129 |
+
angle_of_incidence = None
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
critical_angle_ = critical_angle(medium1, medium2)
|
| 133 |
+
except (ValueError, TypeError):
|
| 134 |
+
critical_angle_ = None
|
| 135 |
+
|
| 136 |
+
if angle_of_incidence is not None:
|
| 137 |
+
if normal is not None or plane is not None:
|
| 138 |
+
raise ValueError('Normal/plane not allowed if incident is an angle')
|
| 139 |
+
|
| 140 |
+
if not 0.0 <= angle_of_incidence < pi*0.5:
|
| 141 |
+
raise ValueError('Angle of incidence not in range [0:pi/2)')
|
| 142 |
+
|
| 143 |
+
if critical_angle_ and angle_of_incidence > critical_angle_:
|
| 144 |
+
raise ValueError('Ray undergoes total internal reflection')
|
| 145 |
+
return asin(n1*sin(angle_of_incidence)/n2)
|
| 146 |
+
|
| 147 |
+
# Treat the incident as ray below
|
| 148 |
+
# A flag to check whether to return Ray3D or not
|
| 149 |
+
return_ray = False
|
| 150 |
+
|
| 151 |
+
if plane is not None and normal is not None:
|
| 152 |
+
raise ValueError("Either plane or normal is acceptable.")
|
| 153 |
+
|
| 154 |
+
if not isinstance(incident, Matrix):
|
| 155 |
+
if is_sequence(incident):
|
| 156 |
+
_incident = Matrix(incident)
|
| 157 |
+
elif isinstance(incident, Ray3D):
|
| 158 |
+
_incident = Matrix(incident.direction_ratio)
|
| 159 |
+
else:
|
| 160 |
+
raise TypeError(
|
| 161 |
+
"incident should be a Matrix, Ray3D, or sequence")
|
| 162 |
+
else:
|
| 163 |
+
_incident = incident
|
| 164 |
+
|
| 165 |
+
# If plane is provided, get direction ratios of the normal
|
| 166 |
+
# to the plane from the plane else go with `normal` param.
|
| 167 |
+
if plane is not None:
|
| 168 |
+
if not isinstance(plane, Plane):
|
| 169 |
+
raise TypeError("plane should be an instance of geometry.plane.Plane")
|
| 170 |
+
# If we have the plane, we can get the intersection
|
| 171 |
+
# point of incident ray and the plane and thus return
|
| 172 |
+
# an instance of Ray3D.
|
| 173 |
+
if isinstance(incident, Ray3D):
|
| 174 |
+
return_ray = True
|
| 175 |
+
intersection_pt = plane.intersection(incident)[0]
|
| 176 |
+
_normal = Matrix(plane.normal_vector)
|
| 177 |
+
else:
|
| 178 |
+
if not isinstance(normal, Matrix):
|
| 179 |
+
if is_sequence(normal):
|
| 180 |
+
_normal = Matrix(normal)
|
| 181 |
+
elif isinstance(normal, Ray3D):
|
| 182 |
+
_normal = Matrix(normal.direction_ratio)
|
| 183 |
+
if isinstance(incident, Ray3D):
|
| 184 |
+
intersection_pt = intersection(incident, normal)
|
| 185 |
+
if len(intersection_pt) == 0:
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"Normal isn't concurrent with the incident ray.")
|
| 188 |
+
else:
|
| 189 |
+
return_ray = True
|
| 190 |
+
intersection_pt = intersection_pt[0]
|
| 191 |
+
else:
|
| 192 |
+
raise TypeError(
|
| 193 |
+
"Normal should be a Matrix, Ray3D, or sequence")
|
| 194 |
+
else:
|
| 195 |
+
_normal = normal
|
| 196 |
+
|
| 197 |
+
eta = n1/n2 # Relative index of refraction
|
| 198 |
+
# Calculating magnitude of the vectors
|
| 199 |
+
mag_incident = sqrt(sum(i**2 for i in _incident))
|
| 200 |
+
mag_normal = sqrt(sum(i**2 for i in _normal))
|
| 201 |
+
# Converting vectors to unit vectors by dividing
|
| 202 |
+
# them with their magnitudes
|
| 203 |
+
_incident /= mag_incident
|
| 204 |
+
_normal /= mag_normal
|
| 205 |
+
c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
|
| 206 |
+
cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
|
| 207 |
+
if cs2.is_negative: # This is the case of total internal reflection(TIR).
|
| 208 |
+
return S.Zero
|
| 209 |
+
drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
|
| 210 |
+
# Multiplying unit vector by its magnitude
|
| 211 |
+
drs = drs*mag_incident
|
| 212 |
+
if not return_ray:
|
| 213 |
+
return drs
|
| 214 |
+
else:
|
| 215 |
+
return Ray3D(intersection_pt, direction_ratio=drs)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def fresnel_coefficients(angle_of_incidence, medium1, medium2):
|
| 219 |
+
"""
|
| 220 |
+
This function uses Fresnel equations to calculate reflection and
|
| 221 |
+
transmission coefficients. Those are obtained for both polarisations
|
| 222 |
+
when the electric field vector is in the plane of incidence (labelled 'p')
|
| 223 |
+
and when the electric field vector is perpendicular to the plane of
|
| 224 |
+
incidence (labelled 's'). There are four real coefficients unless the
|
| 225 |
+
incident ray reflects in total internal in which case there are two complex
|
| 226 |
+
ones. Angle of incidence is the angle between the incident ray and the
|
| 227 |
+
surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
|
| 228 |
+
sympifiable object.
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
==========
|
| 232 |
+
|
| 233 |
+
angle_of_incidence : sympifiable
|
| 234 |
+
|
| 235 |
+
medium1 : Medium or sympifiable
|
| 236 |
+
Medium 1 or its refractive index
|
| 237 |
+
|
| 238 |
+
medium2 : Medium or sympifiable
|
| 239 |
+
Medium 2 or its refractive index
|
| 240 |
+
|
| 241 |
+
Returns
|
| 242 |
+
=======
|
| 243 |
+
|
| 244 |
+
Returns a list with four real Fresnel coefficients:
|
| 245 |
+
[reflection p (TM), reflection s (TE),
|
| 246 |
+
transmission p (TM), transmission s (TE)]
|
| 247 |
+
If the ray is undergoes total internal reflection then returns a
|
| 248 |
+
list of two complex Fresnel coefficients:
|
| 249 |
+
[reflection p (TM), reflection s (TE)]
|
| 250 |
+
|
| 251 |
+
Examples
|
| 252 |
+
========
|
| 253 |
+
|
| 254 |
+
>>> from sympy.physics.optics import fresnel_coefficients
|
| 255 |
+
>>> fresnel_coefficients(0.3, 1, 2)
|
| 256 |
+
[0.317843553417859, -0.348645229818821,
|
| 257 |
+
0.658921776708929, 0.651354770181179]
|
| 258 |
+
>>> fresnel_coefficients(0.6, 2, 1)
|
| 259 |
+
[-0.235625382192159 - 0.971843958291041*I,
|
| 260 |
+
0.816477005968898 - 0.577377951366403*I]
|
| 261 |
+
|
| 262 |
+
References
|
| 263 |
+
==========
|
| 264 |
+
|
| 265 |
+
.. [1] https://en.wikipedia.org/wiki/Fresnel_equations
|
| 266 |
+
"""
|
| 267 |
+
if not 0 <= 2*angle_of_incidence < pi:
|
| 268 |
+
raise ValueError('Angle of incidence not in range [0:pi/2)')
|
| 269 |
+
|
| 270 |
+
n1 = refractive_index_of_medium(medium1)
|
| 271 |
+
n2 = refractive_index_of_medium(medium2)
|
| 272 |
+
|
| 273 |
+
angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
|
| 274 |
+
try:
|
| 275 |
+
angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
|
| 276 |
+
except ValueError:
|
| 277 |
+
angle_of_total_internal_reflection_onset = None
|
| 278 |
+
|
| 279 |
+
if angle_of_total_internal_reflection_onset is None or\
|
| 280 |
+
angle_of_total_internal_reflection_onset > angle_of_incidence:
|
| 281 |
+
R_s = -sin(angle_of_incidence - angle_of_refraction)\
|
| 282 |
+
/sin(angle_of_incidence + angle_of_refraction)
|
| 283 |
+
R_p = tan(angle_of_incidence - angle_of_refraction)\
|
| 284 |
+
/tan(angle_of_incidence + angle_of_refraction)
|
| 285 |
+
T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
|
| 286 |
+
/sin(angle_of_incidence + angle_of_refraction)
|
| 287 |
+
T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
|
| 288 |
+
/(sin(angle_of_incidence + angle_of_refraction)\
|
| 289 |
+
*cos(angle_of_incidence - angle_of_refraction))
|
| 290 |
+
return [R_p, R_s, T_p, T_s]
|
| 291 |
+
else:
|
| 292 |
+
n = n2/n1
|
| 293 |
+
R_s = cancel((cos(angle_of_incidence)-\
|
| 294 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
|
| 295 |
+
/(cos(angle_of_incidence)+\
|
| 296 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
|
| 297 |
+
R_p = cancel((n**2*cos(angle_of_incidence)-\
|
| 298 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
|
| 299 |
+
/(n**2*cos(angle_of_incidence)+\
|
| 300 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
|
| 301 |
+
return [R_p, R_s]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def deviation(incident, medium1, medium2, normal=None, plane=None):
|
| 305 |
+
"""
|
| 306 |
+
This function calculates the angle of deviation of a ray
|
| 307 |
+
due to refraction at planar surface.
|
| 308 |
+
|
| 309 |
+
Parameters
|
| 310 |
+
==========
|
| 311 |
+
|
| 312 |
+
incident : Matrix, Ray3D, sequence or float
|
| 313 |
+
Incident vector or angle of incidence
|
| 314 |
+
medium1 : sympy.physics.optics.medium.Medium or sympifiable
|
| 315 |
+
Medium 1 or its refractive index
|
| 316 |
+
medium2 : sympy.physics.optics.medium.Medium or sympifiable
|
| 317 |
+
Medium 2 or its refractive index
|
| 318 |
+
normal : Matrix, Ray3D, or sequence
|
| 319 |
+
Normal vector
|
| 320 |
+
plane : Plane
|
| 321 |
+
Plane of separation of the two media.
|
| 322 |
+
|
| 323 |
+
Returns angular deviation between incident and refracted rays
|
| 324 |
+
|
| 325 |
+
Examples
|
| 326 |
+
========
|
| 327 |
+
|
| 328 |
+
>>> from sympy.physics.optics import deviation
|
| 329 |
+
>>> from sympy.geometry import Point3D, Ray3D, Plane
|
| 330 |
+
>>> from sympy.matrices import Matrix
|
| 331 |
+
>>> from sympy import symbols
|
| 332 |
+
>>> n1, n2 = symbols('n1, n2')
|
| 333 |
+
>>> n = Matrix([0, 0, 1])
|
| 334 |
+
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
| 335 |
+
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
| 336 |
+
>>> deviation(r1, 1, 1, n)
|
| 337 |
+
0
|
| 338 |
+
>>> deviation(r1, n1, n2, plane=P)
|
| 339 |
+
-acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
|
| 340 |
+
>>> round(deviation(0.1, 1.2, 1.5), 5)
|
| 341 |
+
-0.02005
|
| 342 |
+
"""
|
| 343 |
+
refracted = refraction_angle(incident,
|
| 344 |
+
medium1,
|
| 345 |
+
medium2,
|
| 346 |
+
normal=normal,
|
| 347 |
+
plane=plane)
|
| 348 |
+
try:
|
| 349 |
+
angle_of_incidence = Float(incident)
|
| 350 |
+
except TypeError:
|
| 351 |
+
angle_of_incidence = None
|
| 352 |
+
|
| 353 |
+
if angle_of_incidence is not None:
|
| 354 |
+
return float(refracted) - angle_of_incidence
|
| 355 |
+
|
| 356 |
+
if refracted != 0:
|
| 357 |
+
if isinstance(refracted, Ray3D):
|
| 358 |
+
refracted = Matrix(refracted.direction_ratio)
|
| 359 |
+
|
| 360 |
+
if not isinstance(incident, Matrix):
|
| 361 |
+
if is_sequence(incident):
|
| 362 |
+
_incident = Matrix(incident)
|
| 363 |
+
elif isinstance(incident, Ray3D):
|
| 364 |
+
_incident = Matrix(incident.direction_ratio)
|
| 365 |
+
else:
|
| 366 |
+
raise TypeError(
|
| 367 |
+
"incident should be a Matrix, Ray3D, or sequence")
|
| 368 |
+
else:
|
| 369 |
+
_incident = incident
|
| 370 |
+
|
| 371 |
+
if plane is None:
|
| 372 |
+
if not isinstance(normal, Matrix):
|
| 373 |
+
if is_sequence(normal):
|
| 374 |
+
_normal = Matrix(normal)
|
| 375 |
+
elif isinstance(normal, Ray3D):
|
| 376 |
+
_normal = Matrix(normal.direction_ratio)
|
| 377 |
+
else:
|
| 378 |
+
raise TypeError(
|
| 379 |
+
"normal should be a Matrix, Ray3D, or sequence")
|
| 380 |
+
else:
|
| 381 |
+
_normal = normal
|
| 382 |
+
else:
|
| 383 |
+
_normal = Matrix(plane.normal_vector)
|
| 384 |
+
|
| 385 |
+
mag_incident = sqrt(sum(i**2 for i in _incident))
|
| 386 |
+
mag_normal = sqrt(sum(i**2 for i in _normal))
|
| 387 |
+
mag_refracted = sqrt(sum(i**2 for i in refracted))
|
| 388 |
+
_incident /= mag_incident
|
| 389 |
+
_normal /= mag_normal
|
| 390 |
+
refracted /= mag_refracted
|
| 391 |
+
i = acos(_incident.dot(_normal))
|
| 392 |
+
r = acos(refracted.dot(_normal))
|
| 393 |
+
return i - r
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def brewster_angle(medium1, medium2):
|
| 397 |
+
"""
|
| 398 |
+
This function calculates the Brewster's angle of incidence to Medium 2 from
|
| 399 |
+
Medium 1 in radians.
|
| 400 |
+
|
| 401 |
+
Parameters
|
| 402 |
+
==========
|
| 403 |
+
|
| 404 |
+
medium 1 : Medium or sympifiable
|
| 405 |
+
Refractive index of Medium 1
|
| 406 |
+
medium 2 : Medium or sympifiable
|
| 407 |
+
Refractive index of Medium 1
|
| 408 |
+
|
| 409 |
+
Examples
|
| 410 |
+
========
|
| 411 |
+
|
| 412 |
+
>>> from sympy.physics.optics import brewster_angle
|
| 413 |
+
>>> brewster_angle(1, 1.33)
|
| 414 |
+
0.926093295503462
|
| 415 |
+
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
n1 = refractive_index_of_medium(medium1)
|
| 419 |
+
n2 = refractive_index_of_medium(medium2)
|
| 420 |
+
|
| 421 |
+
return atan2(n2, n1)
|
| 422 |
+
|
| 423 |
+
def critical_angle(medium1, medium2):
|
| 424 |
+
"""
|
| 425 |
+
This function calculates the critical angle of incidence (marking the onset
|
| 426 |
+
of total internal) to Medium 2 from Medium 1 in radians.
|
| 427 |
+
|
| 428 |
+
Parameters
|
| 429 |
+
==========
|
| 430 |
+
|
| 431 |
+
medium 1 : Medium or sympifiable
|
| 432 |
+
Refractive index of Medium 1.
|
| 433 |
+
medium 2 : Medium or sympifiable
|
| 434 |
+
Refractive index of Medium 1.
|
| 435 |
+
|
| 436 |
+
Examples
|
| 437 |
+
========
|
| 438 |
+
|
| 439 |
+
>>> from sympy.physics.optics import critical_angle
|
| 440 |
+
>>> critical_angle(1.33, 1)
|
| 441 |
+
0.850908514477849
|
| 442 |
+
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
n1 = refractive_index_of_medium(medium1)
|
| 446 |
+
n2 = refractive_index_of_medium(medium2)
|
| 447 |
+
|
| 448 |
+
if n2 > n1:
|
| 449 |
+
raise ValueError('Total internal reflection impossible for n1 < n2')
|
| 450 |
+
else:
|
| 451 |
+
return asin(n2/n1)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):
|
| 456 |
+
"""
|
| 457 |
+
This function calculates focal length of a lens.
|
| 458 |
+
It follows cartesian sign convention.
|
| 459 |
+
|
| 460 |
+
Parameters
|
| 461 |
+
==========
|
| 462 |
+
|
| 463 |
+
n_lens : Medium or sympifiable
|
| 464 |
+
Index of refraction of lens.
|
| 465 |
+
n_surr : Medium or sympifiable
|
| 466 |
+
Index of reflection of surrounding.
|
| 467 |
+
r1 : sympifiable
|
| 468 |
+
Radius of curvature of first surface.
|
| 469 |
+
r2 : sympifiable
|
| 470 |
+
Radius of curvature of second surface.
|
| 471 |
+
d : sympifiable, optional
|
| 472 |
+
Thickness of lens, default value is 0.
|
| 473 |
+
|
| 474 |
+
Examples
|
| 475 |
+
========
|
| 476 |
+
|
| 477 |
+
>>> from sympy.physics.optics import lens_makers_formula
|
| 478 |
+
>>> from sympy import S
|
| 479 |
+
>>> lens_makers_formula(1.33, 1, 10, -10)
|
| 480 |
+
15.1515151515151
|
| 481 |
+
>>> lens_makers_formula(1.2, 1, 10, S.Infinity)
|
| 482 |
+
50.0000000000000
|
| 483 |
+
>>> lens_makers_formula(1.33, 1, 10, -10, d=1)
|
| 484 |
+
15.3418463277618
|
| 485 |
+
|
| 486 |
+
"""
|
| 487 |
+
|
| 488 |
+
if isinstance(n_lens, Medium):
|
| 489 |
+
n_lens = n_lens.refractive_index
|
| 490 |
+
else:
|
| 491 |
+
n_lens = sympify(n_lens)
|
| 492 |
+
if isinstance(n_surr, Medium):
|
| 493 |
+
n_surr = n_surr.refractive_index
|
| 494 |
+
else:
|
| 495 |
+
n_surr = sympify(n_surr)
|
| 496 |
+
d = sympify(d)
|
| 497 |
+
|
| 498 |
+
focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))
|
| 499 |
+
|
| 500 |
+
if focal_length == zoo:
|
| 501 |
+
return S.Infinity
|
| 502 |
+
return focal_length
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def mirror_formula(focal_length=None, u=None, v=None):
|
| 506 |
+
"""
|
| 507 |
+
This function provides one of the three parameters
|
| 508 |
+
when two of them are supplied.
|
| 509 |
+
This is valid only for paraxial rays.
|
| 510 |
+
|
| 511 |
+
Parameters
|
| 512 |
+
==========
|
| 513 |
+
|
| 514 |
+
focal_length : sympifiable
|
| 515 |
+
Focal length of the mirror.
|
| 516 |
+
u : sympifiable
|
| 517 |
+
Distance of object from the pole on
|
| 518 |
+
the principal axis.
|
| 519 |
+
v : sympifiable
|
| 520 |
+
Distance of the image from the pole
|
| 521 |
+
on the principal axis.
|
| 522 |
+
|
| 523 |
+
Examples
|
| 524 |
+
========
|
| 525 |
+
|
| 526 |
+
>>> from sympy.physics.optics import mirror_formula
|
| 527 |
+
>>> from sympy.abc import f, u, v
|
| 528 |
+
>>> mirror_formula(focal_length=f, u=u)
|
| 529 |
+
f*u/(-f + u)
|
| 530 |
+
>>> mirror_formula(focal_length=f, v=v)
|
| 531 |
+
f*v/(-f + v)
|
| 532 |
+
>>> mirror_formula(u=u, v=v)
|
| 533 |
+
u*v/(u + v)
|
| 534 |
+
|
| 535 |
+
"""
|
| 536 |
+
if focal_length and u and v:
|
| 537 |
+
raise ValueError("Please provide only two parameters")
|
| 538 |
+
|
| 539 |
+
focal_length = sympify(focal_length)
|
| 540 |
+
u = sympify(u)
|
| 541 |
+
v = sympify(v)
|
| 542 |
+
if u is oo:
|
| 543 |
+
_u = Symbol('u')
|
| 544 |
+
if v is oo:
|
| 545 |
+
_v = Symbol('v')
|
| 546 |
+
if focal_length is oo:
|
| 547 |
+
_f = Symbol('f')
|
| 548 |
+
if focal_length is None:
|
| 549 |
+
if u is oo and v is oo:
|
| 550 |
+
return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
|
| 551 |
+
if u is oo:
|
| 552 |
+
return Limit(v*_u/(v + _u), _u, oo).doit()
|
| 553 |
+
if v is oo:
|
| 554 |
+
return Limit(_v*u/(_v + u), _v, oo).doit()
|
| 555 |
+
return v*u/(v + u)
|
| 556 |
+
if u is None:
|
| 557 |
+
if v is oo and focal_length is oo:
|
| 558 |
+
return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
|
| 559 |
+
if v is oo:
|
| 560 |
+
return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
|
| 561 |
+
if focal_length is oo:
|
| 562 |
+
return Limit(v*_f/(v - _f), _f, oo).doit()
|
| 563 |
+
return v*focal_length/(v - focal_length)
|
| 564 |
+
if v is None:
|
| 565 |
+
if u is oo and focal_length is oo:
|
| 566 |
+
return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
|
| 567 |
+
if u is oo:
|
| 568 |
+
return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
|
| 569 |
+
if focal_length is oo:
|
| 570 |
+
return Limit(u*_f/(u - _f), _f, oo).doit()
|
| 571 |
+
return u*focal_length/(u - focal_length)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def lens_formula(focal_length=None, u=None, v=None):
|
| 575 |
+
"""
|
| 576 |
+
This function provides one of the three parameters
|
| 577 |
+
when two of them are supplied.
|
| 578 |
+
This is valid only for paraxial rays.
|
| 579 |
+
|
| 580 |
+
Parameters
|
| 581 |
+
==========
|
| 582 |
+
|
| 583 |
+
focal_length : sympifiable
|
| 584 |
+
Focal length of the mirror.
|
| 585 |
+
u : sympifiable
|
| 586 |
+
Distance of object from the optical center on
|
| 587 |
+
the principal axis.
|
| 588 |
+
v : sympifiable
|
| 589 |
+
Distance of the image from the optical center
|
| 590 |
+
on the principal axis.
|
| 591 |
+
|
| 592 |
+
Examples
|
| 593 |
+
========
|
| 594 |
+
|
| 595 |
+
>>> from sympy.physics.optics import lens_formula
|
| 596 |
+
>>> from sympy.abc import f, u, v
|
| 597 |
+
>>> lens_formula(focal_length=f, u=u)
|
| 598 |
+
f*u/(f + u)
|
| 599 |
+
>>> lens_formula(focal_length=f, v=v)
|
| 600 |
+
f*v/(f - v)
|
| 601 |
+
>>> lens_formula(u=u, v=v)
|
| 602 |
+
u*v/(u - v)
|
| 603 |
+
|
| 604 |
+
"""
|
| 605 |
+
if focal_length and u and v:
|
| 606 |
+
raise ValueError("Please provide only two parameters")
|
| 607 |
+
|
| 608 |
+
focal_length = sympify(focal_length)
|
| 609 |
+
u = sympify(u)
|
| 610 |
+
v = sympify(v)
|
| 611 |
+
if u is oo:
|
| 612 |
+
_u = Symbol('u')
|
| 613 |
+
if v is oo:
|
| 614 |
+
_v = Symbol('v')
|
| 615 |
+
if focal_length is oo:
|
| 616 |
+
_f = Symbol('f')
|
| 617 |
+
if focal_length is None:
|
| 618 |
+
if u is oo and v is oo:
|
| 619 |
+
return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
|
| 620 |
+
if u is oo:
|
| 621 |
+
return Limit(v*_u/(_u - v), _u, oo).doit()
|
| 622 |
+
if v is oo:
|
| 623 |
+
return Limit(_v*u/(u - _v), _v, oo).doit()
|
| 624 |
+
return v*u/(u - v)
|
| 625 |
+
if u is None:
|
| 626 |
+
if v is oo and focal_length is oo:
|
| 627 |
+
return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
|
| 628 |
+
if v is oo:
|
| 629 |
+
return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
|
| 630 |
+
if focal_length is oo:
|
| 631 |
+
return Limit(v*_f/(_f - v), _f, oo).doit()
|
| 632 |
+
return v*focal_length/(focal_length - v)
|
| 633 |
+
if v is None:
|
| 634 |
+
if u is oo and focal_length is oo:
|
| 635 |
+
return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
|
| 636 |
+
if u is oo:
|
| 637 |
+
return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
|
| 638 |
+
if focal_length is oo:
|
| 639 |
+
return Limit(u*_f/(u + _f), _f, oo).doit()
|
| 640 |
+
return u*focal_length/(u + focal_length)
|
| 641 |
+
|
| 642 |
+
def hyperfocal_distance(f, N, c):
|
| 643 |
+
"""
|
| 644 |
+
|
| 645 |
+
Parameters
|
| 646 |
+
==========
|
| 647 |
+
|
| 648 |
+
f: sympifiable
|
| 649 |
+
Focal length of a given lens.
|
| 650 |
+
|
| 651 |
+
N: sympifiable
|
| 652 |
+
F-number of a given lens.
|
| 653 |
+
|
| 654 |
+
c: sympifiable
|
| 655 |
+
Circle of Confusion (CoC) of a given image format.
|
| 656 |
+
|
| 657 |
+
Example
|
| 658 |
+
=======
|
| 659 |
+
|
| 660 |
+
>>> from sympy.physics.optics import hyperfocal_distance
|
| 661 |
+
>>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
|
| 662 |
+
9.47
|
| 663 |
+
"""
|
| 664 |
+
|
| 665 |
+
f = sympify(f)
|
| 666 |
+
N = sympify(N)
|
| 667 |
+
c = sympify(c)
|
| 668 |
+
|
| 669 |
+
return (1/(N * c))*(f**2)
|
| 670 |
+
|
| 671 |
+
def transverse_magnification(si, so):
|
| 672 |
+
"""
|
| 673 |
+
|
| 674 |
+
Calculates the transverse magnification upon reflection in a mirror,
|
| 675 |
+
which is the ratio of the image size to the object size.
|
| 676 |
+
|
| 677 |
+
Parameters
|
| 678 |
+
==========
|
| 679 |
+
|
| 680 |
+
so: sympifiable
|
| 681 |
+
Lens-object distance.
|
| 682 |
+
|
| 683 |
+
si: sympifiable
|
| 684 |
+
Lens-image distance.
|
| 685 |
+
|
| 686 |
+
Example
|
| 687 |
+
=======
|
| 688 |
+
|
| 689 |
+
>>> from sympy.physics.optics import transverse_magnification
|
| 690 |
+
>>> transverse_magnification(30, 15)
|
| 691 |
+
-2
|
| 692 |
+
|
| 693 |
+
"""
|
| 694 |
+
|
| 695 |
+
si = sympify(si)
|
| 696 |
+
so = sympify(so)
|
| 697 |
+
|
| 698 |
+
return (-(si/so))
|
shared/package-files/06/06a8c47343d01f8756cb337580819f8636dfde737860de8993d70be10284e511/maximum.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/maximum_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::maximum(Tensor self, Tensor other) -> Tensor
|
| 27 |
+
inline at::Tensor maximum(const at::Tensor & self, const at::Tensor & other) {
|
| 28 |
+
return at::_ops::maximum::call(self, other);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & maximum_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) {
|
| 33 |
+
return at::_ops::maximum_out::call(self, other, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & maximum_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) {
|
| 37 |
+
return at::_ops::maximum_out::call(self, other, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/06/06abfbd260d36cf6d6fdec37634c706d3c69cd9cae81902b6713ff414fe048f5/triu_indices_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset=0, at::TensorOptions options=at::kLong);
|
| 21 |
+
TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory);
|
| 22 |
+
|
| 23 |
+
} // namespace cuda
|
| 24 |
+
} // namespace at
|
shared/package-files/06/06b2e711f499620071a8632d05fde1269b89b218877ea24b1b3f8016609ae6b4/real_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API real {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::real";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "real(Tensor(a) self) -> Tensor(a)";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|