diff --git a/shared/package-files/06/060094b757a1d25b14435b1cf4d989df6ece3c5abc64ad637a41ed100a0de13a/ast_parser.cpython-311.pyc b/shared/package-files/06/060094b757a1d25b14435b1cf4d989df6ece3c5abc64ad637a41ed100a0de13a/ast_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..776a71d76ac2f6d9caa65ecbb933c18310b7dfed Binary files /dev/null and b/shared/package-files/06/060094b757a1d25b14435b1cf4d989df6ece3c5abc64ad637a41ed100a0de13a/ast_parser.cpython-311.pyc differ diff --git a/shared/package-files/06/0600bdcbbe66cf203999ac90486cc347c7a99610220618b0ae573fcc821fe099/test_polynomialring.cpython-311.pyc b/shared/package-files/06/0600bdcbbe66cf203999ac90486cc347c7a99610220618b0ae573fcc821fe099/test_polynomialring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e2348ab78f8ba6b4003f4a4a23f7f049bdf3d0f Binary files /dev/null and b/shared/package-files/06/0600bdcbbe66cf203999ac90486cc347c7a99610220618b0ae573fcc821fe099/test_polynomialring.cpython-311.pyc differ diff --git a/shared/package-files/06/0601c9e6868e9c3cff3ea836c8099510ef5b1974c2e447585619c93a1326a5f0/test_groupby.cpython-311.pyc b/shared/package-files/06/0601c9e6868e9c3cff3ea836c8099510ef5b1974c2e447585619c93a1326a5f0/test_groupby.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..223f70437d869dba5de0595511658e29ea75d3cd Binary files /dev/null and b/shared/package-files/06/0601c9e6868e9c3cff3ea836c8099510ef5b1974c2e447585619c93a1326a5f0/test_groupby.cpython-311.pyc differ diff --git a/shared/package-files/06/06043dbc1200bb751f07c4b7c24045e7738d16b55709ba31b3943a53f8d9c2e9/SegmentReduce.h b/shared/package-files/06/06043dbc1200bb751f07c4b7c24045e7738d16b55709ba31b3943a53f8d9c2e9/SegmentReduce.h new file mode 100644 index 0000000000000000000000000000000000000000..03c09a7f8d3f892ecb6b6da537058e3f69060693 --- /dev/null +++ b/shared/package-files/06/06043dbc1200bb751f07c4b7c24045e7738d16b55709ba31b3943a53f8d9c2e9/SegmentReduce.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include +#include + +namespace at { +class Tensor; + +namespace native { + +using segment_reduce_lengths_fn = Tensor (*)( + ReductionType, + const Tensor&, + const Tensor&, + int64_t, + const std::optional&); +DECLARE_DISPATCH(segment_reduce_lengths_fn, _segment_reduce_lengths_stub) + +using segment_reduce_offsets_fn = Tensor (*)( + ReductionType, + const Tensor&, + const Tensor&, + int64_t, + const std::optional&); +DECLARE_DISPATCH(segment_reduce_offsets_fn, _segment_reduce_offsets_stub) + +using segment_reduce_lengths_backward_fn = Tensor (*)( + const Tensor&, + const Tensor&, + const Tensor&, + ReductionType, + const Tensor&, + int64_t, + const std::optional&); +DECLARE_DISPATCH(segment_reduce_lengths_backward_fn, _segment_reduce_lengths_backward_stub) + +using segment_reduce_offsets_backward_fn = Tensor (*)( + const Tensor&, + const Tensor&, + const Tensor&, + ReductionType, + const Tensor&, + int64_t, + const std::optional&); +DECLARE_DISPATCH(segment_reduce_offsets_backward_fn, _segment_reduce_offsets_backward_stub) + +} // namespace native +} // namespace at diff --git a/shared/package-files/06/0604deb1660cc3365ed6a84bba8139715d6afe30955559022e25e7544365e325/prune.py b/shared/package-files/06/0604deb1660cc3365ed6a84bba8139715d6afe30955559022e25e7544365e325/prune.py new file mode 100644 index 0000000000000000000000000000000000000000..583620dfa40d35066288bde03d109bfe55ebb513 --- /dev/null +++ b/shared/package-files/06/0604deb1660cc3365ed6a84bba8139715d6afe30955559022e25e7544365e325/prune.py @@ -0,0 +1,1372 @@ +# mypy: allow-untyped-defs +r"""Pruning methods.""" +import numbers +from abc import ABC, abstractmethod +from collections.abc import Iterable + +import torch + + +class BasePruningMethod(ABC): + r"""Abstract base class for creation of new pruning techniques. + + Provides a skeleton for customization requiring the overriding of methods + such as :meth:`compute_mask` and :meth:`apply`. + """ + + _tensor_name: str + + def __call__(self, module, inputs): + r"""Multiply the mask into original tensor and store the result. + + Multiplies the mask (stored in ``module[name + '_mask']``) + into the original tensor (stored in ``module[name + '_orig']``) + and stores the result into ``module[name]`` by using :meth:`apply_mask`. + + Args: + module (nn.Module): module containing the tensor to prune + inputs: not used. + """ + setattr(module, self._tensor_name, self.apply_mask(module)) + + @abstractmethod + def compute_mask(self, t, default_mask): + r"""Compute and returns a mask for the input tensor ``t``. + + Starting from a base ``default_mask`` (which should be a mask of ones + if the tensor has not been pruned yet), generate a random mask to + apply on top of the ``default_mask`` according to the specific pruning + method recipe. + + Args: + t (torch.Tensor): tensor representing the importance scores of the + parameter to prune. + default_mask (torch.Tensor): Base mask from previous pruning + iterations, that need to be respected after the new mask is + applied. Same dims as ``t``. + + Returns: + mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` + """ + + def apply_mask(self, module): + r"""Simply handles the multiplication between the parameter being pruned and the generated mask. + + Fetches the mask and the original tensor from the module + and returns the pruned version of the tensor. + + Args: + module (nn.Module): module containing the tensor to prune + + Returns: + pruned_tensor (torch.Tensor): pruned version of the input tensor + """ + # to carry out the multiplication, the mask needs to have been computed, + # so the pruning method must know what tensor it's operating on + assert ( + self._tensor_name is not None + ), f"Module {module} has to be pruned" # this gets set in apply() + mask = getattr(module, self._tensor_name + "_mask") + orig = getattr(module, self._tensor_name + "_orig") + pruned_tensor = mask.to(dtype=orig.dtype) * orig + return pruned_tensor + + @classmethod + def apply(cls, module, name, *args, importance_scores=None, **kwargs): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + args: arguments passed on to a subclass of + :class:`BasePruningMethod` + importance_scores (torch.Tensor): tensor of importance scores (of + same shape as module parameter) used to compute mask for pruning. + The values in this tensor indicate the importance of the + corresponding elements in the parameter being pruned. + If unspecified or None, the parameter will be used in its place. + kwargs: keyword arguments passed on to a subclass of a + :class:`BasePruningMethod` + """ + + def _get_composite_method(cls, module, name, *args, **kwargs): + # Check if a pruning method has already been applied to + # `module[name]`. If so, store that in `old_method`. + old_method = None + found = 0 + # there should technically be only 1 hook with hook.name == name + # assert this using `found` + hooks_to_remove = [] + for k, hook in module._forward_pre_hooks.items(): + # if it exists, take existing thing, remove hook, then + # go through normal thing + if isinstance(hook, BasePruningMethod) and hook._tensor_name == name: + old_method = hook + hooks_to_remove.append(k) + found += 1 + assert ( + found <= 1 + ), f"Avoid adding multiple pruning hooks to the\ + same tensor {name} of module {module}. Use a PruningContainer." + + for k in hooks_to_remove: + del module._forward_pre_hooks[k] + + # Apply the new pruning method, either from scratch or on top of + # the previous one. + method = cls(*args, **kwargs) # new pruning + # Have the pruning method remember what tensor it's been applied to + method._tensor_name = name + + # combine `methods` with `old_method`, if `old_method` exists + if old_method is not None: # meaning that there was a hook + # if the hook is already a pruning container, just add the + # new pruning method to the container + if isinstance(old_method, PruningContainer): + old_method.add_pruning_method(method) + method = old_method # rename old_method --> method + + # if the hook is simply a single pruning method, create a + # container, add the old pruning method and the new one + elif isinstance(old_method, BasePruningMethod): + container = PruningContainer(old_method) + # Have the pruning method remember the name of its tensor + # setattr(container, '_tensor_name', name) + container.add_pruning_method(method) + method = container # rename container --> method + return method + + method = _get_composite_method(cls, module, name, *args, **kwargs) + # at this point we have no forward_pre_hooks but we could have an + # active reparametrization of the tensor if another pruning method + # had been applied (in which case `method` would be a PruningContainer + # and not a simple pruning method). + + # Pruning is to be applied to the module's tensor named `name`, + # starting from the state it is found in prior to this iteration of + # pruning. The pruning mask is calculated based on importances scores. + + orig = getattr(module, name) + if importance_scores is not None: + assert ( + importance_scores.shape == orig.shape + ), f"importance_scores should have the same shape as parameter {name} of {module}" + else: + importance_scores = orig + + # If this is the first time pruning is applied, take care of moving + # the original tensor to a new parameter called name + '_orig' and + # and deleting the original parameter + if not isinstance(method, PruningContainer): + # copy `module[name]` to `module[name + '_orig']` + module.register_parameter(name + "_orig", orig) + # temporarily delete `module[name]` + del module._parameters[name] + default_mask = torch.ones_like(orig) # temp + # If this is not the first time pruning is applied, all of the above + # has been done before in a previous pruning iteration, so we're good + # to go + else: + default_mask = ( + getattr(module, name + "_mask") + .detach() + .clone(memory_format=torch.contiguous_format) + ) + + # Use try/except because if anything goes wrong with the mask + # computation etc., you'd want to roll back. + try: + # get the final mask, computed according to the specific method + mask = method.compute_mask(importance_scores, default_mask=default_mask) + # reparameterize by saving mask to `module[name + '_mask']`... + module.register_buffer(name + "_mask", mask) + # ... and the new pruned tensor to `module[name]` + setattr(module, name, method.apply_mask(module)) + # associate the pruning method to the module via a hook to + # compute the function before every forward() (compile by run) + module.register_forward_pre_hook(method) + + except Exception as e: + if not isinstance(method, PruningContainer): + orig = getattr(module, name + "_orig") + module.register_parameter(name, orig) + del module._parameters[name + "_orig"] + raise e + + return method + + def prune(self, t, default_mask=None, importance_scores=None): + r"""Compute and returns a pruned version of input tensor ``t``. + + According to the pruning rule specified in :meth:`compute_mask`. + + Args: + t (torch.Tensor): tensor to prune (of same dimensions as + ``default_mask``). + importance_scores (torch.Tensor): tensor of importance scores (of + same shape as ``t``) used to compute mask for pruning ``t``. + The values in this tensor indicate the importance of the + corresponding elements in the ``t`` that is being pruned. + If unspecified or None, the tensor ``t`` will be used in its place. + default_mask (torch.Tensor, optional): mask from previous pruning + iteration, if any. To be considered when determining what + portion of the tensor that pruning should act on. If None, + default to a mask of ones. + + Returns: + pruned version of tensor ``t``. + """ + if importance_scores is not None: + assert ( + importance_scores.shape == t.shape + ), "importance_scores should have the same shape as tensor t" + else: + importance_scores = t + default_mask = default_mask if default_mask is not None else torch.ones_like(t) + return t * self.compute_mask(importance_scores, default_mask=default_mask) + + def remove(self, module): + r"""Remove the pruning reparameterization from a module. + + The pruned parameter named ``name`` remains permanently pruned, + and the parameter named ``name+'_orig'`` is removed from the parameter list. + Similarly, the buffer named ``name+'_mask'`` is removed from the buffers. + + Note: + Pruning itself is NOT undone or reversed! + """ + # before removing pruning from a tensor, it has to have been applied + assert ( + self._tensor_name is not None + ), f"Module {module} has to be pruned before pruning can be removed" # this gets set in apply() + + # to update module[name] to latest trained weights + weight = self.apply_mask(module) # masked weights + + # delete and reset + if hasattr(module, self._tensor_name): + delattr(module, self._tensor_name) + orig = module._parameters[self._tensor_name + "_orig"] + orig.data = weight.data + del module._parameters[self._tensor_name + "_orig"] + del module._buffers[self._tensor_name + "_mask"] + setattr(module, self._tensor_name, orig) + + +class PruningContainer(BasePruningMethod): + """Container holding a sequence of pruning methods for iterative pruning. + + Keeps track of the order in which pruning methods are applied and handles + combining successive pruning calls. + + Accepts as argument an instance of a BasePruningMethod or an iterable of + them. + """ + + def __init__(self, *args): + self._pruning_methods: tuple[BasePruningMethod, ...] = () + if not isinstance(args, Iterable): # only 1 item + self._tensor_name = args._tensor_name + self.add_pruning_method(args) + elif len(args) == 1: # only 1 item in a tuple + self._tensor_name = args[0]._tensor_name + self.add_pruning_method(args[0]) + else: # manual construction from list or other iterable (or no args) + for method in args: + self.add_pruning_method(method) + + def add_pruning_method(self, method): + r"""Add a child pruning ``method`` to the container. + + Args: + method (subclass of BasePruningMethod): child pruning method + to be added to the container. + """ + # check that we're adding a pruning method to the container + if not isinstance(method, BasePruningMethod) and method is not None: + raise TypeError(f"{type(method)} is not a BasePruningMethod subclass") + elif method is not None and self._tensor_name != method._tensor_name: + raise ValueError( + "Can only add pruning methods acting on " + f"the parameter named '{self._tensor_name}' to PruningContainer {self}." + + f" Found '{method._tensor_name}'" + ) + # if all checks passed, add to _pruning_methods tuple + self._pruning_methods += (method,) # type: ignore[operator] + + def __len__(self): + return len(self._pruning_methods) + + def __iter__(self): + return iter(self._pruning_methods) + + def __getitem__(self, idx): + return self._pruning_methods[idx] + + def compute_mask(self, t, default_mask): + r"""Apply the latest ``method`` by computing the new partial masks and returning its combination with the ``default_mask``. + + The new partial mask should be computed on the entries or channels + that were not zeroed out by the ``default_mask``. + Which portions of the tensor ``t`` the new mask will be calculated from + depends on the ``PRUNING_TYPE`` (handled by the type handler): + + * for 'unstructured', the mask will be computed from the raveled + list of nonmasked entries; + + * for 'structured', the mask will be computed from the nonmasked + channels in the tensor; + + * for 'global', the mask will be computed across all entries. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + (of same dimensions as ``default_mask``). + default_mask (torch.Tensor): mask from previous pruning iteration. + + Returns: + mask (torch.Tensor): new mask that combines the effects + of the ``default_mask`` and the new mask from the current + pruning ``method`` (of same dimensions as ``default_mask`` and + ``t``). + """ + + def _combine_masks(method, t, mask): + r"""Combine the masks from all pruning methods and returns a new mask. + + Args: + method (a BasePruningMethod subclass): pruning method + currently being applied. + t (torch.Tensor): tensor representing the parameter to prune + (of same dimensions as mask). + mask (torch.Tensor): mask from previous pruning iteration + + Returns: + new_mask (torch.Tensor): new mask that combines the effects + of the old mask and the new mask from the current + pruning method (of same dimensions as mask and t). + """ + new_mask = mask # start off from existing mask + new_mask = new_mask.to(dtype=t.dtype) + + # compute a slice of t onto which the new pruning method will operate + if method.PRUNING_TYPE == "unstructured": + # prune entries of t where the mask is 1 + slc = mask == 1 + + # for struct pruning, exclude channels that have already been + # entirely pruned + elif method.PRUNING_TYPE == "structured": + if not hasattr(method, "dim"): + raise AttributeError( + "Pruning methods of PRUNING_TYPE " + '"structured" need to have the attribute `dim` defined.' + ) + + # find the channels to keep by removing the ones that have been + # zeroed out already (i.e. where sum(entries) == 0) + n_dims = t.dim() # "is this a 2D tensor? 3D? ..." + dim = method.dim + # convert negative indexing + if dim < 0: + dim = n_dims + dim + # if dim is still negative after subtracting it from n_dims + if dim < 0: + raise IndexError( + f"Index is out of bounds for tensor with dimensions {n_dims}" + ) + # find channels along dim = dim that aren't already tots 0ed out + keep_channel = mask.sum(dim=[d for d in range(n_dims) if d != dim]) != 0 + # create slice to identify what to prune + slc = [slice(None)] * n_dims + slc[dim] = keep_channel + + elif method.PRUNING_TYPE == "global": + n_dims = len(t.shape) # "is this a 2D tensor? 3D? ..." + slc = [slice(None)] * n_dims + + else: + raise ValueError(f"Unrecognized PRUNING_TYPE {method.PRUNING_TYPE}") + + # compute the new mask on the unpruned slice of the tensor t + partial_mask = method.compute_mask(t[slc], default_mask=mask[slc]) + new_mask[slc] = partial_mask.to(dtype=new_mask.dtype) + + return new_mask + + method = self._pruning_methods[-1] + mask = _combine_masks(method, t, default_mask) + return mask + + +class Identity(BasePruningMethod): + r"""Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones.""" + + PRUNING_TYPE = "unstructured" + + def compute_mask(self, t, default_mask): + mask = default_mask + return mask + + @classmethod + def apply(cls, module, name): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + """ + return super().apply(module, name) + + +class RandomUnstructured(BasePruningMethod): + r"""Prune (currently unpruned) units in a tensor at random. + + Args: + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + """ + + PRUNING_TYPE = "unstructured" + + def __init__(self, amount): + # Check range of validity of pruning amount + _validate_pruning_amount_init(amount) + self.amount = amount + + def compute_mask(self, t, default_mask): + # Check that the amount of units to prune is not > than the number of + # parameters in t + tensor_size = t.nelement() + # Compute number of units to prune: amount if int, + # else amount * tensor_size + nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size) + # This should raise an error if the number of units to prune is larger + # than the number of units in the tensor + _validate_pruning_amount(nparams_toprune, tensor_size) + + mask = default_mask.clone(memory_format=torch.contiguous_format) + + if nparams_toprune != 0: # k=0 not supported by torch.kthvalue + prob = torch.rand_like(t) + topk = torch.topk(prob.view(-1), k=nparams_toprune) + mask.view(-1)[topk.indices] = 0 + + return mask + + @classmethod + def apply(cls, module, name, amount): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + """ + return super().apply(module, name, amount=amount) + + +class L1Unstructured(BasePruningMethod): + r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. + + Args: + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + """ + + PRUNING_TYPE = "unstructured" + + def __init__(self, amount): + # Check range of validity of pruning amount + _validate_pruning_amount_init(amount) + self.amount = amount + + def compute_mask(self, t, default_mask): + # Check that the amount of units to prune is not > than the number of + # parameters in t + tensor_size = t.nelement() + # Compute number of units to prune: amount if int, + # else amount * tensor_size + nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size) + # This should raise an error if the number of units to prune is larger + # than the number of units in the tensor + _validate_pruning_amount(nparams_toprune, tensor_size) + + mask = default_mask.clone(memory_format=torch.contiguous_format) + + if nparams_toprune != 0: # k=0 not supported by torch.kthvalue + # largest=True --> top k; largest=False --> bottom k + # Prune the smallest k + topk = torch.topk(torch.abs(t).view(-1), k=nparams_toprune, largest=False) + # topk will have .indices and .values + mask.view(-1)[topk.indices] = 0 + + return mask + + @classmethod + def apply(cls, module, name, amount, importance_scores=None): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + importance_scores (torch.Tensor): tensor of importance scores (of same + shape as module parameter) used to compute mask for pruning. + The values in this tensor indicate the importance of the corresponding + elements in the parameter being pruned. + If unspecified or None, the module parameter will be used in its place. + """ + return super().apply( + module, name, amount=amount, importance_scores=importance_scores + ) + + +class RandomStructured(BasePruningMethod): + r"""Prune entire (currently unpruned) channels in a tensor at random. + + Args: + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + dim (int, optional): index of the dim along which we define + channels to prune. Default: -1. + """ + + PRUNING_TYPE = "structured" + + def __init__(self, amount, dim=-1): + # Check range of validity of amount + _validate_pruning_amount_init(amount) + self.amount = amount + self.dim = dim + + def compute_mask(self, t, default_mask): + r"""Compute and returns a mask for the input tensor ``t``. + + Starting from a base ``default_mask`` (which should be a mask of ones + if the tensor has not been pruned yet), generate a random mask to + apply on top of the ``default_mask`` by randomly zeroing out channels + along the specified dim of the tensor. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + default_mask (torch.Tensor): Base mask from previous pruning + iterations, that need to be respected after the new mask is + applied. Same dims as ``t``. + + Returns: + mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` + + Raises: + IndexError: if ``self.dim >= len(t.shape)`` + """ + # Check that tensor has structure (i.e. more than 1 dimension) such + # that the concept of "channels" makes sense + _validate_structured_pruning(t) + + # Check that self.dim is a valid dim to index t, else raise IndexError + _validate_pruning_dim(t, self.dim) + + # Check that the amount of channels to prune is not > than the number of + # channels in t along the dim to prune + tensor_size = t.shape[self.dim] + # Compute number of units to prune: amount if int, + # else amount * tensor_size + nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size) + # This should raise an error if the number of units to prune is larger + # than the number of units in the tensor + _validate_pruning_amount(nparams_toprune, tensor_size) + + # Compute binary mask by initializing it to all 0s and then filling in + # 1s wherever topk.indices indicates, along self.dim. + # mask has the same shape as tensor t + def make_mask(t, dim, nchannels, nchannels_toprune): + # generate a random number in [0, 1] to associate to each channel + prob = torch.rand(nchannels) + # generate mask for each channel by 0ing out the channels that + # got assigned the k = nchannels_toprune lowest values in prob + threshold = torch.kthvalue(prob, k=nchannels_toprune).values + channel_mask = prob > threshold + + mask = torch.zeros_like(t) + slc = [slice(None)] * len(t.shape) + slc[dim] = channel_mask + mask[slc] = 1 + return mask + + if nparams_toprune == 0: # k=0 not supported by torch.kthvalue + mask = default_mask + else: + # apply the new structured mask on top of prior (potentially + # unstructured) mask + mask = make_mask(t, self.dim, tensor_size, nparams_toprune) + mask *= default_mask.to(dtype=mask.dtype) + return mask + + @classmethod + def apply(cls, module, name, amount, dim=-1): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + dim (int, optional): index of the dim along which we define + channels to prune. Default: -1. + """ + return super().apply(module, name, amount=amount, dim=dim) + + +class LnStructured(BasePruningMethod): + r"""Prune entire (currently unpruned) channels in a tensor based on their L\ ``n``-norm. + + Args: + amount (int or float): quantity of channels to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid + entries for argument ``p`` in :func:`torch.norm`. + dim (int, optional): index of the dim along which we define + channels to prune. Default: -1. + """ + + PRUNING_TYPE = "structured" + + def __init__(self, amount, n, dim=-1): + # Check range of validity of amount + _validate_pruning_amount_init(amount) + self.amount = amount + self.n = n + self.dim = dim + + def compute_mask(self, t, default_mask): + r"""Compute and returns a mask for the input tensor ``t``. + + Starting from a base ``default_mask`` (which should be a mask of ones + if the tensor has not been pruned yet), generate a mask to apply on + top of the ``default_mask`` by zeroing out the channels along the + specified dim with the lowest L\ ``n``-norm. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + default_mask (torch.Tensor): Base mask from previous pruning + iterations, that need to be respected after the new mask is + applied. Same dims as ``t``. + + Returns: + mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` + + Raises: + IndexError: if ``self.dim >= len(t.shape)`` + """ + # Check that tensor has structure (i.e. more than 1 dimension) such + # that the concept of "channels" makes sense + _validate_structured_pruning(t) + # Check that self.dim is a valid dim to index t, else raise IndexError + _validate_pruning_dim(t, self.dim) + + # Check that the amount of channels to prune is not > than the number of + # channels in t along the dim to prune + tensor_size = t.shape[self.dim] + # Compute number of units to prune: amount if int, + # else amount * tensor_size + nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size) + nparams_tokeep = tensor_size - nparams_toprune + # This should raise an error if the number of units to prune is larger + # than the number of units in the tensor + _validate_pruning_amount(nparams_toprune, tensor_size) + + # Structured pruning prunes entire channels so we need to know the + # L_n norm along each channel to then find the topk based on this + # metric + norm = _compute_norm(t, self.n, self.dim) + # largest=True --> top k; largest=False --> bottom k + # Keep the largest k channels along dim=self.dim + topk = torch.topk(norm, k=nparams_tokeep, largest=True) + # topk will have .indices and .values + + # Compute binary mask by initializing it to all 0s and then filling in + # 1s wherever topk.indices indicates, along self.dim. + # mask has the same shape as tensor t + def make_mask(t, dim, indices): + # init mask to 0 + mask = torch.zeros_like(t) + # e.g.: slc = [None, None, None], if len(t.shape) = 3 + slc = [slice(None)] * len(t.shape) + # replace a None at position=dim with indices + # e.g.: slc = [None, None, [0, 2, 3]] if dim=2 & indices=[0,2,3] + slc[dim] = indices + # use slc to slice mask and replace all its entries with 1s + # e.g.: mask[:, :, [0, 2, 3]] = 1 + mask[slc] = 1 + return mask + + if nparams_toprune == 0: # k=0 not supported by torch.kthvalue + mask = default_mask + else: + mask = make_mask(t, self.dim, topk.indices) + mask *= default_mask.to(dtype=mask.dtype) + + return mask + + @classmethod + def apply(cls, module, name, amount, n, dim, importance_scores=None): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid + entries for argument ``p`` in :func:`torch.norm`. + dim (int): index of the dim along which we define channels to + prune. + importance_scores (torch.Tensor): tensor of importance scores (of same + shape as module parameter) used to compute mask for pruning. + The values in this tensor indicate the importance of the corresponding + elements in the parameter being pruned. + If unspecified or None, the module parameter will be used in its place. + """ + return super().apply( + module, + name, + amount=amount, + n=n, + dim=dim, + importance_scores=importance_scores, + ) + + +class CustomFromMask(BasePruningMethod): + PRUNING_TYPE = "global" + + def __init__(self, mask): + self.mask = mask + + def compute_mask(self, t, default_mask): + assert default_mask.shape == self.mask.shape + mask = default_mask * self.mask.to(dtype=default_mask.dtype) + return mask + + @classmethod + def apply(cls, module, name, mask): + r"""Add pruning on the fly and reparametrization of a tensor. + + Adds the forward pre-hook that enables pruning on the fly and + the reparametrization of a tensor in terms of the original tensor + and the pruning mask. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + """ + return super().apply(module, name, mask=mask) + + +def identity(module, name): + r"""Apply pruning reparametrization without pruning any units. + + Applies pruning reparametrization to the tensor corresponding to the + parameter called ``name`` in ``module`` without actually pruning any + units. Modifies module in place (and also return the modified module) + by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Note: + The mask is a tensor of ones. + + Args: + module (nn.Module): module containing the tensor to prune. + name (str): parameter name within ``module`` on which pruning + will act. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> # xdoctest: +SKIP + >>> m = prune.identity(nn.Linear(2, 3), 'bias') + >>> print(m.bias_mask) + tensor([1., 1., 1.]) + """ + Identity.apply(module, name) + return module + + +def random_unstructured(module, name, amount): + r"""Prune tensor by removing random (currently unpruned) units. + + Prunes tensor corresponding to parameter called ``name`` in ``module`` + by removing the specified ``amount`` of (currently unpruned) units + selected at random. + Modifies module in place (and also return the modified module) by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> # xdoctest: +SKIP + >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1) + >>> torch.sum(m.weight_mask == 0) + tensor(1) + + """ + RandomUnstructured.apply(module, name, amount) + return module + + +def l1_unstructured(module, name, amount, importance_scores=None): + r"""Prune tensor by removing units with the lowest L1-norm. + + Prunes tensor corresponding to parameter called ``name`` in ``module`` + by removing the specified `amount` of (currently unpruned) units with the + lowest L1-norm. + Modifies module in place (and also return the modified module) + by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + importance_scores (torch.Tensor): tensor of importance scores (of same + shape as module parameter) used to compute mask for pruning. + The values in this tensor indicate the importance of the corresponding + elements in the parameter being pruned. + If unspecified or None, the module parameter will be used in its place. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> # xdoctest: +SKIP + >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2) + >>> m.state_dict().keys() + odict_keys(['bias', 'weight_orig', 'weight_mask']) + """ + L1Unstructured.apply( + module, name, amount=amount, importance_scores=importance_scores + ) + return module + + +def random_structured(module, name, amount, dim): + r"""Prune tensor by removing random channels along the specified dimension. + + Prunes tensor corresponding to parameter called ``name`` in ``module`` + by removing the specified ``amount`` of (currently unpruned) channels + along the specified ``dim`` selected at random. + Modifies module in place (and also return the modified module) + by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + dim (int): index of the dim along which we define channels to prune. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> # xdoctest: +SKIP + >>> m = prune.random_structured( + ... nn.Linear(5, 3), 'weight', amount=3, dim=1 + ... ) + >>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0)) + >>> print(columns_pruned) + 3 + """ + RandomStructured.apply(module, name, amount, dim) + return module + + +def ln_structured(module, name, amount, n, dim, importance_scores=None): + r"""Prune tensor by removing channels with the lowest L\ ``n``-norm along the specified dimension. + + Prunes tensor corresponding to parameter called ``name`` in ``module`` + by removing the specified ``amount`` of (currently unpruned) channels + along the specified ``dim`` with the lowest L\ ``n``-norm. + Modifies module in place (and also return the modified module) + by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + amount (int or float): quantity of parameters to prune. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid + entries for argument ``p`` in :func:`torch.norm`. + dim (int): index of the dim along which we define channels to prune. + importance_scores (torch.Tensor): tensor of importance scores (of same + shape as module parameter) used to compute mask for pruning. + The values in this tensor indicate the importance of the corresponding + elements in the parameter being pruned. + If unspecified or None, the module parameter will be used in its place. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> from torch.nn.utils import prune + >>> m = prune.ln_structured( + ... nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf') + ... ) + """ + LnStructured.apply( + module, name, amount, n, dim, importance_scores=importance_scores + ) + return module + + +def global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs): + r""" + Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. + + Modifies modules in place by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + parameters (Iterable of (module, name) tuples): parameters of + the model to prune in a global fashion, i.e. by aggregating all + weights prior to deciding which ones to prune. module must be of + type :class:`nn.Module`, and name must be a string. + pruning_method (function): a valid pruning function from this module, + or a custom one implemented by the user that satisfies the + implementation guidelines and has ``PRUNING_TYPE='unstructured'``. + importance_scores (dict): a dictionary mapping (module, name) tuples to + the corresponding parameter's importance scores tensor. The tensor + should be the same shape as the parameter, and is used for computing + mask for pruning. + If unspecified or None, the parameter will be used in place of its + importance scores. + kwargs: other keyword arguments such as: + amount (int or float): quantity of parameters to prune across the + specified parameters. + If ``float``, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If ``int``, it represents the + absolute number of parameters to prune. + + Raises: + TypeError: if ``PRUNING_TYPE != 'unstructured'`` + + Note: + Since global structured pruning doesn't make much sense unless the + norm is normalized by the size of the parameter, we now limit the + scope of global pruning to unstructured methods. + + Examples: + >>> from torch.nn.utils import prune + >>> from collections import OrderedDict + >>> net = nn.Sequential(OrderedDict([ + ... ('first', nn.Linear(10, 4)), + ... ('second', nn.Linear(4, 1)), + ... ])) + >>> parameters_to_prune = ( + ... (net.first, 'weight'), + ... (net.second, 'weight'), + ... ) + >>> prune.global_unstructured( + ... parameters_to_prune, + ... pruning_method=prune.L1Unstructured, + ... amount=10, + ... ) + >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0)) + tensor(10) + + """ + # ensure parameters is a list or generator of tuples + if not isinstance(parameters, Iterable): + raise TypeError("global_unstructured(): parameters is not an Iterable") + + importance_scores = importance_scores if importance_scores is not None else {} + if not isinstance(importance_scores, dict): + raise TypeError("global_unstructured(): importance_scores must be of type dict") + + # flatten importance scores to consider them all at once in global pruning + relevant_importance_scores = torch.nn.utils.parameters_to_vector( + [ + importance_scores.get((module, name), getattr(module, name)) + for (module, name) in parameters + ] + ) + # similarly, flatten the masks (if they exist), or use a flattened vector + # of 1s of the same dimensions as t + default_mask = torch.nn.utils.parameters_to_vector( + [ + getattr(module, name + "_mask", torch.ones_like(getattr(module, name))) + for (module, name) in parameters + ] + ) + + # use the canonical pruning methods to compute the new mask, even if the + # parameter is now a flattened out version of `parameters` + container = PruningContainer() + container._tensor_name = "temp" # to make it match that of `method` + method = pruning_method(**kwargs) + method._tensor_name = "temp" # to make it match that of `container` + if method.PRUNING_TYPE != "unstructured": + raise TypeError( + 'Only "unstructured" PRUNING_TYPE supported for ' + f"the `pruning_method`. Found method {pruning_method} of type {method.PRUNING_TYPE}" + ) + + container.add_pruning_method(method) + + # use the `compute_mask` method from `PruningContainer` to combine the + # mask computed by the new method with the pre-existing mask + final_mask = container.compute_mask(relevant_importance_scores, default_mask) + + # Pointer for slicing the mask to match the shape of each parameter + pointer = 0 + for module, name in parameters: + param = getattr(module, name) + # The length of the parameter + num_param = param.numel() + # Slice the mask, reshape it + param_mask = final_mask[pointer : pointer + num_param].view_as(param) + # Assign the correct pre-computed mask to each parameter and add it + # to the forward_pre_hooks like any other pruning method + custom_from_mask(module, name, mask=param_mask) + + # Increment the pointer to continue slicing the final_mask + pointer += num_param + + +def custom_from_mask(module, name, mask): + r"""Prune tensor corresponding to parameter called ``name`` in ``module`` by applying the pre-computed mask in ``mask``. + + Modifies module in place (and also return the modified module) by: + + 1) adding a named buffer called ``name+'_mask'`` corresponding to the + binary mask applied to the parameter ``name`` by the pruning method. + 2) replacing the parameter ``name`` by its pruned version, while the + original (unpruned) parameter is stored in a new parameter named + ``name+'_orig'``. + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + mask (Tensor): binary mask to be applied to the parameter. + + Returns: + module (nn.Module): modified (i.e. pruned) version of the input module + + Examples: + >>> from torch.nn.utils import prune + >>> m = prune.custom_from_mask( + ... nn.Linear(5, 3), name='bias', mask=torch.tensor([0, 1, 0]) + ... ) + >>> print(m.bias_mask) + tensor([0., 1., 0.]) + + """ + CustomFromMask.apply(module, name, mask) + return module + + +def remove(module, name): + r"""Remove the pruning reparameterization from a module and the pruning method from the forward hook. + + The pruned parameter named ``name`` remains permanently pruned, and the parameter + named ``name+'_orig'`` is removed from the parameter list. Similarly, + the buffer named ``name+'_mask'`` is removed from the buffers. + + Note: + Pruning itself is NOT undone or reversed! + + Args: + module (nn.Module): module containing the tensor to prune + name (str): parameter name within ``module`` on which pruning + will act. + + Examples: + >>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2) + >>> m = remove(m, name='weight') + """ + for k, hook in module._forward_pre_hooks.items(): + if isinstance(hook, BasePruningMethod) and hook._tensor_name == name: + hook.remove(module) + del module._forward_pre_hooks[k] + return module + + raise ValueError( + f"Parameter '{name}' of module {module} has to be pruned before pruning can be removed" + ) + + +def is_pruned(module): + r"""Check if a module is pruned by looking for pruning pre-hooks. + + Check whether ``module`` is pruned by looking for + ``forward_pre_hooks`` in its modules that inherit from the + :class:`BasePruningMethod`. + + Args: + module (nn.Module): object that is either pruned or unpruned + + Returns: + binary answer to whether ``module`` is pruned. + + Examples: + >>> from torch.nn.utils import prune + >>> m = nn.Linear(5, 7) + >>> print(prune.is_pruned(m)) + False + >>> prune.random_unstructured(m, name='weight', amount=0.2) + >>> print(prune.is_pruned(m)) + True + """ + for _, submodule in module.named_modules(): + for hook in submodule._forward_pre_hooks.values(): + if isinstance(hook, BasePruningMethod): + return True + return False + + +def _validate_pruning_amount_init(amount): + r"""Validate helper to check the range of amount at init. + + Args: + amount (int or float): quantity of parameters to prune. + If float, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If int, it represents the + absolute number of parameters to prune. + + Raises: + ValueError: if amount is a float not in [0, 1], or if it's a negative + integer. + TypeError: if amount is neither a float nor an integer. + + Note: + This does not take into account the number of parameters in the + tensor to be pruned, which is known only at prune. + """ + if not isinstance(amount, numbers.Real): + raise TypeError(f"Invalid type for amount: {amount}. Must be int or float.") + + if (isinstance(amount, numbers.Integral) and amount < 0) or ( + not isinstance(amount, numbers.Integral) # so it's a float + and (float(amount) > 1.0 or float(amount) < 0.0) + ): + raise ValueError( + f"amount={amount} should either be a float in the range [0, 1] or a non-negative integer" + ) + + +def _validate_pruning_amount(amount, tensor_size): + r"""Validate that the pruning amount is meaningful wrt to the size of the data. + + Validation helper to check that the amount of parameters to prune + is meaningful wrt to the size of the data (`tensor_size`). + + Args: + amount (int or float): quantity of parameters to prune. + If float, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If int, it represents the + absolute number of parameters to prune. + tensor_size (int): absolute number of parameters in the tensor + to prune. + """ + # TODO: consider removing this check and allowing users to specify + # a number of units to prune that is greater than the number of units + # left to prune. In this case, the tensor will just be fully pruned. + + if isinstance(amount, numbers.Integral) and amount > tensor_size: + raise ValueError( + f"amount={amount} should be smaller than the number of parameters to prune={tensor_size}" + ) + + +def _validate_structured_pruning(t): + r"""Validate that the tensor to be pruned is at least 2-Dimensional. + + Validation helper to check that the tensor to be pruned is multi- + dimensional, such that the concept of "channels" is well-defined. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + + Raises: + ValueError: if the tensor `t` is not at least 2D. + """ + shape = t.shape + if len(shape) <= 1: + raise ValueError( + "Structured pruning can only be applied to " + "multidimensional tensors. Found tensor of shape " + f"{shape} with {len(shape)} dims" + ) + + +def _compute_nparams_toprune(amount, tensor_size): + r"""Convert the pruning amount from a percentage to absolute value. + + Since amount can be expressed either in absolute value or as a + percentage of the number of units/channels in a tensor, this utility + function converts the percentage to absolute value to standardize + the handling of pruning. + + Args: + amount (int or float): quantity of parameters to prune. + If float, should be between 0.0 and 1.0 and represent the + fraction of parameters to prune. If int, it represents the + absolute number of parameters to prune. + tensor_size (int): absolute number of parameters in the tensor + to prune. + + Returns: + int: the number of units to prune in the tensor + """ + # incorrect type already checked in _validate_pruning_amount_init + if isinstance(amount, numbers.Integral): + return amount + else: + return round(amount * tensor_size) + + +def _validate_pruning_dim(t, dim): + r"""Validate that the pruning dimension is within the bounds of the tensor dimension. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + dim (int): index of the dim along which we define channels to prune + """ + if dim >= t.dim(): + raise IndexError(f"Invalid index {dim} for tensor of size {t.shape}") + + +def _compute_norm(t, n, dim): + r"""Compute the L_n-norm of a tensor along all dimensions except for the specified dimension. + + The L_n-norm will be computed across all entries in tensor `t` along all dimension + except for the one identified by dim. + Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim), + then norm will have Size [4], and each entry will represent the + `L_n`-norm computed using the 3x2=6 entries for each of the 4 channels. + + Args: + t (torch.Tensor): tensor representing the parameter to prune + n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid + entries for argument p in torch.norm + dim (int): dim identifying the channels to prune + + Returns: + norm (torch.Tensor): L_n norm computed across all dimensions except + for `dim`. By construction, `norm.shape = t.shape[-1]`. + """ + # dims = all axes, except for the one identified by `dim` + dims = list(range(t.dim())) + # convert negative indexing + if dim < 0: + dim = dims[dim] + dims.remove(dim) + + norm = torch.norm(t, p=n, dim=dims) + return norm diff --git a/shared/package-files/06/0606ec3c5cdeaf9e772a86bc2f5675abc97a862012be42b5d5228bdb01b8e132/linear_ops.h b/shared/package-files/06/0606ec3c5cdeaf9e772a86bc2f5675abc97a862012be42b5d5228bdb01b8e132/linear_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cb5d2076e59ad154c1c0256376c1575db586f185 --- /dev/null +++ b/shared/package-files/06/0606ec3c5cdeaf9e772a86bc2f5675abc97a862012be42b5d5228bdb01b8e132/linear_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linear { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const ::std::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::linear"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor"; + static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias); +}; + +struct TORCH_API linear_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const ::std::optional &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::linear"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/061101b9748a06c3462430490ed60bd1c191237c17ff0fce2200390fe6312169/sm_20_intrinsics.hpp b/shared/package-files/06/061101b9748a06c3462430490ed60bd1c191237c17ff0fce2200390fe6312169/sm_20_intrinsics.hpp new file mode 100644 index 0000000000000000000000000000000000000000..30c1ab99e0d66ebbceb8fe88b1122443cbf5f998 --- /dev/null +++ b/shared/package-files/06/061101b9748a06c3462430490ed60bd1c191237c17ff0fce2200390fe6312169/sm_20_intrinsics.hpp @@ -0,0 +1,221 @@ +/* + * Copyright 1993-2014 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__SM_20_INTRINSICS_HPP__) +#define __SM_20_INTRINSICS_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_20_INTRINSICS_DECL__ __device__ +#else /* __CUDACC_RTC__ */ +#define __SM_20_INTRINSICS_DECL__ static __inline__ __device__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "cuda_runtime_api.h" + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +__SM_20_INTRINSICS_DECL__ unsigned int ballot(bool pred) +{ + return __ballot((int)pred); +} + +__SM_20_INTRINSICS_DECL__ int syncthreads_count(bool pred) +{ + return __syncthreads_count((int)pred); +} + +__SM_20_INTRINSICS_DECL__ bool syncthreads_and(bool pred) +{ + return (bool)__syncthreads_and((int)pred); +} + +__SM_20_INTRINSICS_DECL__ bool syncthreads_or(bool pred) +{ + return (bool)__syncthreads_or((int)pred); +} + + +extern "C" { + __device__ unsigned __nv_isGlobal_impl(const void *); + __device__ unsigned __nv_isShared_impl(const void *); + __device__ unsigned __nv_isConstant_impl(const void *); + __device__ unsigned __nv_isLocal_impl(const void *); + __device__ unsigned __nv_isGridConstant_impl(const void *); +} + +__SM_20_INTRINSICS_DECL__ unsigned int __isGlobal(const void *ptr) +{ + return __nv_isGlobal_impl(ptr); +} + +__SM_20_INTRINSICS_DECL__ unsigned int __isShared(const void *ptr) +{ + return __nv_isShared_impl(ptr); +} + +__SM_20_INTRINSICS_DECL__ unsigned int __isConstant(const void *ptr) +{ + return __nv_isConstant_impl(ptr); +} + +__SM_20_INTRINSICS_DECL__ unsigned int __isLocal(const void *ptr) +{ + return __nv_isLocal_impl(ptr); +} + +#if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) +__SM_20_INTRINSICS_DECL__ unsigned int __isGridConstant(const void *ptr) +{ + return __nv_isGridConstant_impl(ptr); +} +#endif /* !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) */ + +extern "C" { + __device__ size_t __nv_cvta_generic_to_global_impl(const void *); + __device__ size_t __nv_cvta_generic_to_shared_impl(const void *); + __device__ size_t __nv_cvta_generic_to_constant_impl(const void *); + __device__ size_t __nv_cvta_generic_to_local_impl(const void *); + __device__ void * __nv_cvta_global_to_generic_impl(size_t); + __device__ void * __nv_cvta_shared_to_generic_impl(size_t); + __device__ void * __nv_cvta_constant_to_generic_impl(size_t); + __device__ void * __nv_cvta_local_to_generic_impl(size_t); +} + +__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_global(const void *p) +{ + return __nv_cvta_generic_to_global_impl(p); +} + +__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_shared(const void *p) +{ + return __nv_cvta_generic_to_shared_impl(p); +} + +__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_constant(const void *p) +{ + return __nv_cvta_generic_to_constant_impl(p); +} + +__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_local(const void *p) +{ + return __nv_cvta_generic_to_local_impl(p); +} + +__SM_20_INTRINSICS_DECL__ void * __cvta_global_to_generic(size_t rawbits) +{ + return __nv_cvta_global_to_generic_impl(rawbits); +} + +__SM_20_INTRINSICS_DECL__ void * __cvta_shared_to_generic(size_t rawbits) +{ + return __nv_cvta_shared_to_generic_impl(rawbits); +} + +__SM_20_INTRINSICS_DECL__ void * __cvta_constant_to_generic(size_t rawbits) +{ + return __nv_cvta_constant_to_generic_impl(rawbits); +} + +__SM_20_INTRINSICS_DECL__ void * __cvta_local_to_generic(size_t rawbits) +{ + return __nv_cvta_local_to_generic_impl(rawbits); +} + +#if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __CVTA_PTR_64 1 +#endif + +__SM_20_INTRINSICS_DECL__ size_t __cvta_generic_to_grid_constant(const void *ptr) +{ +#if __CVTA_PTR_64 + unsigned long long ret; + asm("cvta.to.param.u64 %0, %1;" : "=l"(ret) : "l"(ptr)); +#else /* !__CVTA_PTR_64 */ + unsigned ret; + asm("cvta.to.param.u32 %0, %1;" : "=r"(ret) : "r"(ptr)); +#endif /* __CVTA_PTR_64 */ + return (size_t)ret; + +} + +__SM_20_INTRINSICS_DECL__ void * __cvta_grid_constant_to_generic(size_t rawbits) +{ + void *ret; +#if __CVTA_PTR_64 + unsigned long long in = rawbits; + asm("cvta.param.u64 %0, %1;" : "=l"(ret) : "l"(in)); +#else /* !__CVTA_PTR_64 */ + unsigned in = rawbits; + asm("cvta.param.u32 %0, %1;" : "=r"(ret) : "r"(in)); +#endif /* __CVTA_PTR_64 */ + return ret; +} +#undef __CVTA_PTR_64 +#endif /* !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700) */ + + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_20_INTRINSICS_DECL__ + +#endif /* !__SM_20_INTRINSICS_HPP__ */ + diff --git a/shared/package-files/06/061c05003bc9c10a5a90dcbe70b111fa21bf559558deb35f20f4b8d756b1db6d/bam_mate.c.pysam.c b/shared/package-files/06/061c05003bc9c10a5a90dcbe70b111fa21bf559558deb35f20f4b8d756b1db6d/bam_mate.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..a0ba82051e56fedc626d27e1c8af0f9e6c921fc8 --- /dev/null +++ b/shared/package-files/06/061c05003bc9c10a5a90dcbe70b111fa21bf559558deb35f20f4b8d756b1db6d/bam_mate.c.pysam.c @@ -0,0 +1,1252 @@ +#include "samtools.pysam.h" + +/* bam_mate.c -- fix mate pairing information and clean up flags. + + Copyright (C) 2009, 2011-2017, 2019, 2022, 2024 Genome Research Ltd. + Portions copyright (C) 2011 Broad Institute. + Portions copyright (C) 2012 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "samtools.h" + + +#define MD_MIN_QUALITY 15 + +/* + * This function calculates ct tag for two bams, it assumes they are from the same template and + * writes the tag to the first read in position terms. + */ +static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str) +{ + bam1_t *swap; + int i; + hts_pos_t end; + uint32_t *cigar; + str->l = 0; + 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 + if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate + kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + end = bam_endpos(b1); + kputw(b2->core.pos - end, str); + kputc('T', str); + kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + + uint8_t* data; + if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data); + if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data); + + bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s); +} + +/* + * What This Program is Supposed To Do: + * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted + * alignment. + * + * How We Handle Input + * + * Secondary and supplementary Reads: + * -write to output unchanged + * All Reads: + * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag + * single Reads: + * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0, + * tid = -1 + * -clear bad flags (MREVERSE, PROPER_PAIR) + * -set mpos = 0 (1 based), mtid = -1 and isize = 0 + * -write to output + * Paired Reads: + * -if read is unmapped and mate is not, set pos and tid to equal that of mate + * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid + * -recalculate ISIZE if possible, otherwise set it to 0 + * -optionally clear PROPER_PAIR flag from reads where mapping or orientation + * indicate this is not possible (Illumina orientation only) + * -calculate ct and apply to lowest positioned read + * -write to output + * Limitations + * -Does not handle tandem reads + * -Should mark supplementary reads the same as primary. + * Notes + * -CT definition appears to be something else in spec, this was in here before + * I started tampering with it, anyone know what is going on here? To work + * around this I have demoted the CT this tool generates to ct. + */ + +static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) { + if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) { + // Set unmapped read's RNAME and POS to those of its mapped mate + // (recommended best practice, ensures if coord sort will be together) + dest->core.tid = src->core.tid; + dest->core.pos = src->core.pos; + } +} + +static void sync_mate_inner(bam1_t* src, bam1_t* dest) +{ + // sync mate pos information + dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos; + // sync flag info + if (src->core.flag&BAM_FREVERSE) + dest->core.flag |= BAM_FMREVERSE; + else + dest->core.flag &= ~BAM_FMREVERSE; + if (src->core.flag & BAM_FUNMAP) { + dest->core.flag |= BAM_FMUNMAP; + } +} + +// Is it plausible that these reads are properly paired? +// Can't really give definitive answer without checking isize +static bool plausibly_properly_paired(bam1_t* a, bam1_t* b) +{ + if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false; + assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly + + if (a->core.tid != b->core.tid) return false; + + bam1_t* first = a; + bam1_t* second = b; + hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos; + hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos; + if (a_pos > b_pos) { + first = b; + second = a; + } else { + first = a; + second = b; + } + + if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE)) + return true; + else + return false; +} + +// Returns 0 on success, -1 on failure. +static int bam_format_cigar(const bam1_t* b, kstring_t* str) +{ + // An empty cigar is a special case return "*" rather than "" + if (b->core.n_cigar == 0) { + return (kputc('*', str) == EOF) ? -1 : 0; + } + + const uint32_t *cigar = bam_get_cigar(b); + uint32_t i; + + for (i = 0; i < b->core.n_cigar; ++i) { + if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1; + if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1; + } + + return 0; +} + +// Returns 0 on success, -1 on failure. +static int sync_mq_mc(bam1_t* src, bam1_t* dest) +{ + if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped + // Copy Mate Mapping Quality + uint32_t mq = src->core.qual; + uint8_t* data; + if ((data = bam_aux_get(dest,"MQ")) != NULL) { + bam_aux_del(dest, data); + } + + bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq); + } + // Copy mate cigar if either read is mapped + if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) { + uint8_t* data_mc; + if ((data_mc = bam_aux_get(dest,"MC")) != NULL) { + bam_aux_del(dest, data_mc); + } + + // Convert cigar to string + kstring_t mc = { 0, 0, NULL }; + if (bam_format_cigar(src, &mc) < 0) return -1; + + bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc)); + free(mc.s); + } + return 0; +} + +// Copy flags. +// Returns 0 on success, -1 on failure. +static int sync_mate(bam1_t* a, bam1_t* b) +{ + sync_unmapped_pos_inner(a,b); + sync_unmapped_pos_inner(b,a); + sync_mate_inner(a,b); + sync_mate_inner(b,a); + if (sync_mq_mc(a,b) < 0) return -1; + if (sync_mq_mc(b,a) < 0) return -1; + return 0; +} + + +static uint32_t calc_mate_score(bam1_t *b) +{ + uint32_t score = 0; + uint8_t *qual = bam_get_qual(b); + int i; + + for (i = 0; i < b->core.l_qseq; i++) { + if (qual[i] >= MD_MIN_QUALITY) score += qual[i]; + } + + return score; +} + + +static int add_mate_score(bam1_t *src, bam1_t *dest) +{ + uint8_t *data_ms; + uint32_t mate_score = calc_mate_score(src); + + if ((data_ms = bam_aux_get(dest, "ms")) != NULL) { + bam_aux_del(dest, data_ms); + } + + if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) { + return -1; + } + + return 0; +} + +// Completely delete the CIGAR field +static void clear_cigar(bam1_t *b) { + memmove(bam_get_cigar(b), bam_get_seq(b), + b->data + b->l_data - bam_get_seq(b)); + b->l_data -= 4*b->core.n_cigar; + b->core.n_cigar = 0; +} + +// Trim a CIGAR field to end on reference position "end". Remaining bases +// are turned to soft clips. +static int bam_trim(bam1_t *b, hts_pos_t end) { + hts_pos_t pos = b->core.pos; + int n_cigar = b->core.n_cigar, i; + uint32_t new_cigar_a[1024]; + uint32_t *new_cigar = new_cigar_a; + uint32_t *cigar = bam_get_cigar(b); + + // Find end of alignment or end of ref + int op = 0, oplen = 0; + for (i = 0; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (!(bam_cigar_type(op) & 2)) + continue; + pos += oplen; + if (pos > end) + break; + } + + if (i == n_cigar) + // looks fine already + return 0; + + int old_i = i, j = 0; + // At worst we grow by 1 element (eg 100M -> 70M30S) + if (n_cigar-i >= 1024-1) { + new_cigar = malloc(4*(n_cigar-i+1)); + if (!new_cigar) + return -1; + } + + // We fill out to new_cigar from here on. + if (pos-oplen < end) { + // Partial CIGAR op? Split existing tag. + cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op); + new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP); + } else if (pos > end) { + // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0 + b->core.flag |= BAM_FUNMAP; + b->core.flag &= ~BAM_FPROPER_PAIR; + } else { + // CIGAR op started on the trim junction + new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP); + } + + // Replace trailing elements. + for (i++; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (op == BAM_CHARD_CLIP) { + new_cigar[j++] = cigar[i]; + } else { + new_cigar[j-1] = + bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen, + BAM_CSOFT_CLIP); + } + } + + // We now have cigar[0..old_i-1] for existing CIGAR + // and new_cigar[0..j-1] for new CIGAR trailing component. + + if (old_i+j == n_cigar) { + // Fits and no data move needed + memcpy(&cigar[old_i], new_cigar, j*4); + } else { + uint8_t *seq_old = bam_get_seq(b); + uint8_t *aux_end = b->data + b->l_data; + int nshift; + if (old_i+j < n_cigar) { + // Smaller, and can move data down + nshift = -4*(n_cigar - (old_i+j)); + } else { + // Bigger, so grow BAM and move data up + nshift = 4*(old_i+j - n_cigar); + // FIXME: make htslib's sam_realloc_bam_data public + if (b->l_data + nshift > b->m_data) { + uint8_t *new_data = realloc(b->data, b->l_data + nshift); + if (!new_data) { + if (new_cigar != new_cigar_a) + free(new_cigar); + return -1; + } + b->m_data = b->l_data + nshift; + if (b->data != new_data) { + b->data = new_data; + seq_old = bam_get_seq(b); + aux_end = b->data + b->l_data; + cigar = bam_get_cigar(b); + } + } + } + memmove(seq_old+nshift, seq_old, aux_end - seq_old); + b->l_data += nshift; + memcpy(&cigar[old_i], new_cigar, j*4); + b->core.n_cigar = old_i+j; + } + + if (new_cigar != new_cigar_a) + free(new_cigar); + + return 0; +} + +// Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux" +// keywords for the bam sanitizer. +int bam_sanitize_options(const char *str) { + int opt = 0; + + while (str && *str) { + const char *str_start; + while(*str && *str == ',') + str++; + + for (str_start = str; *str && *str != ','; str++); + int len = str - str_start; + if (strncmp(str_start, "all", 3) == 0 || *str_start == '*') + opt = FIX_ALL; + else if (strncmp(str_start, "none", 4) == 0 || + strncmp(str_start, "off", 3) == 0) + opt = 0; + else if (strncmp(str_start, "on", 2) == 0) + // default for position sorted data + opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX; + else if (strncmp(str_start, "pos", 3) == 0) + opt |= FIX_POS; + else if (strncmp(str_start, "mqual", 5) == 0) + opt |= FIX_MQUAL; + else if (strncmp(str_start, "unmap", 5) == 0) + opt |= FIX_UNMAP; + else if (strncmp(str_start, "cigar", 5) == 0) + opt |= FIX_CIGAR; + else if (strncmp(str_start, "aux", 3) == 0) + opt |= FIX_AUX; + else { + print_error("sanitize", "Unrecognised keyword %.*s\n", + len, str_start); + return -1; + } + } + + return opt; +} + +int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) { + if ((flags & FIX_POS) && b->core.tid < 0) { + // RNAME * => pos 0. NB can break alignment chr/pos sort order + b->core.pos = -1; + if (flags & FIX_UNMAP) + b->core.flag |= BAM_FUNMAP; + } + + if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) { + // Mapped => unmapped correction + if (b->core.pos < 0 && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + } else { + hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid); + if (b->core.pos >= rlen && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + if (flags & FIX_POS) + b->core.tid = b->core.pos = -1; + } else if ((cur_end = bam_endpos(b)) > rlen) { + if (bam_trim(b, rlen) < 0) + return -1; + } + } + } + + if (b->core.flag & BAM_FUNMAP) { + // Unmapped -> cigar/qual correctoins + if ((flags & FIX_CIGAR) && b->core.n_cigar > 0) + clear_cigar(b); + + if (flags & FIX_MQUAL) + b->core.qual = 0; + + // Remove NM, MD, CG, SM tags. + if (flags & FIX_AUX) { + uint8_t *from = bam_aux_first(b); + uint8_t *end = b->data + b->l_data; + uint8_t *to = from ? from-2 : end; + +#define XTAG(a) (((a)[0]<<8) + (a)[1]) + while (from) { + uint8_t *next = bam_aux_next(b, from); + if (!next && errno != ENOENT) + return -1; + + // Keep tag unless one of a specific set. + // NB "to" always points to an aux tag start, while + // "from" is after key. + from -= 2; + int key = (int)from[0]<<8 | from[1]; + if (key != XTAG("NM") && key != XTAG("MD") && + key != XTAG("CG") && key != XTAG("SM")) { + ptrdiff_t len = (next ? next-2 : end) - from; + if (from != to) + memmove(to, from, len); + to += len; + } + from = next; + } + b->l_data = to - b->data; + } + } + + return 0; +} + +// Look for 3 tags in one pass, for efficiencies sake. +// We also convert the draft tags Mm and Ml to MM and ML here. +static inline void find_tags(bam1_t *b, + char *t1, uint8_t **t1p, + char *t2, uint8_t **t2p, + char *t3, uint8_t **t3p) { + *t1p = *t2p = *t3p = NULL; + uint8_t *aux = bam_aux_first(b); + + while (aux) { + if (aux[-2] == t1[0] && toupper(aux[-1]) == t1[1]) { + *t1p = aux; + if (islower(aux[-1])) + aux[-1] = t1[1]; + } else if (aux[-2] == t2[0] && toupper(aux[-1]) == t2[1]) { + *t2p = aux; + if (islower(aux[-1])) + aux[-1] = t2[1]; + } else if (aux[-2] == t3[0] && toupper(aux[-1]) == t3[1]) { + *t3p = aux; + if (islower(aux[-1])) + aux[-1] = t3[1]; + } + aux = bam_aux_next(b, aux); + } +} + +// Return 5' and 3' CIGAR hard-clip counts +static inline void hard_clips(bam1_t *b, int *end5, int *end3) { + uint32_t *cigar = bam_get_cigar(b); + int ncigar = b->core.n_cigar; + int endL = 0, endR = 0, nh = 0; + + if (ncigar && bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) + endL = bam_cigar_oplen(cigar[0]), nh=1; + if (ncigar > nh && bam_cigar_op(cigar[ncigar-1]) == BAM_CHARD_CLIP) + endR = bam_cigar_oplen(cigar[ncigar-1]); + + if (b->core.flag & BAM_FREVERSE) { + *end5 = endR; + *end3 = endL; + } else { + *end5 = endL; + *end3 = endR; + } +} + +// Get MM, ML and MN tags, and 5' and 3' hard-clip lengths. +// MNi is integer copy of MN, or -1 if absent/invalid +void get_mod_info(bam1_t *b, uint8_t **MM, uint8_t **ML, uint8_t **MN, + int *MNi, int *end5, int *end3) { + find_tags(b, "MM", MM, "ML", ML, "MN", MN); + if (*MN) { + int save_errno = errno; + errno = 0; + *MNi = bam_aux2i(*MN); + if (errno == EINVAL) + *MNi = -1; + errno = save_errno; + } else { + *MNi = -1; + } + + if (*MM) + hard_clips(b, end5, end3); + else + *end5 = *end3 = 0; // don't need if MM not found +} + +typedef struct MM_state { + // tags found on "pre" BAM + uint8_t *MM, *ML, *MN; +} MM_state; + +uint8_t *MN_enc(uint8_t *tag, uint32_t n) { + if (n > UINT16_MAX) { + tag[0] = 'I'; + i32_to_le(n, tag+1); + tag += 5; + } else if (n > UINT8_MAX) { + tag[0] = 'S'; + i16_to_le(n, tag+1); + tag += 3; + } else { + *tag++ = 'C'; + *tag++ = n; + } + + return tag; +} + +// Trim 5'/3' bases off MM and ML tags, using a previous sequence as a guide. +int trim_MM(bam1_t *pre, bam1_t *cur, int end5, int end3, + uint8_t *MM, uint8_t *ML, uint8_t *MN) { + // Count number of bases + int counts5[16] = {0}, counts3[16] = {0}; + + uint8_t *seq = bam_get_seq(pre); + int i; + for (i = 0; i < end5; i++) + counts5[bam_seqi(seq, i)]++; + memcpy(counts3, counts5, 16 * sizeof(*counts3)); + for (; i < pre->core.l_qseq - end3; i++) + counts3[bam_seqi(seq, i)]++; + + // "p" is position in pre. + // "q" is position in cur. + // Hence move up "p" to start and copy from there to "q". + uint8_t *MMp, *MLp, *MMq = NULL, *MLq = NULL; + if (ML && ML[0] == 'B' && ML[1] == 'C') { + MLp = ML+6; + } else { + ML = MLp = NULL; + } + MMq = MM+1; + MLq = MLp; + for (MMp = MM+1; *MMp; ) { + int fundamental = seq_nt16_table[*MMp]; + while (*MMp && *MMp != ',') + *MMq++ = *MMp++; + if (*MMp) + *MMq++ = *MMp++; + + // Now on comma separated list for MM and BC array for ML. Skip + int n = 0; + while (*MMp != ';' && n < counts5[fundamental]) { + char *endptr; + long delta = strtol((char *)MMp, &endptr, 10); + if (counts5[fundamental] - n > delta) { + // Skip entire delta in MM and ML. + // Eg counts[]=10, MM=3,10 ML=<10><20> => MM=10 ML=<20> + n += delta+1; + if(ML) MLp++; + } else if (counts3[fundamental] > counts5[fundamental]) { + // Shrink delta, writing MM and ML is unchanged. + // Eg counts[]=3, MM=10,4 ML=<10><20> => MM=7,4 ML=<10><20> + char num[50]; + int l = sprintf(num, "%ld", + delta - (counts5[fundamental]-n)); + memcpy((char *)MMq, num, l); + MMq += l; + *MMq++ = *endptr; + n += delta+1; + if (ML) + *MLq++ = *MLp++; + } else { + // next base mod is on boundary of 3' clip point + break; + } + + MMp = (uint8_t *)endptr; + if (*MMp != ',') + // error? if not ; also? + break; + MMp++; + } + + // Copy + while (*MMp != ';' && n < counts3[fundamental]) { + char *endptr; + long delta = strtol((char *)MMp, &endptr, 10); + if (counts3[fundamental] - n > delta) { + // Copy entire delta in MM and ML including [,;] + memmove(MMq, MMp, (uint8_t *)endptr - MMp + 1); + MMq += (uint8_t *)endptr - MMp + 1; + n += delta+1; + if (ML) + *MLq++ = *MLp++; + } else { + // Next mod is into 3' cutoff, so can terminate MM/ML now + n = counts3[fundamental]; + if (ML) + MLp++; + } + + MMp = (uint8_t *)endptr; + if (*MMp != ',') + break; + MMp++; + } + + // Skip + while (*MMp && *MMp != ';') { + while (*MMp && *MMp != ',' && *MMp != ';') + MMp++; + if (*MMp == ',') + MMp++; + + if (ML) + MLp++; + } + MMq[-1] = ';'; // replaces , with ; if clipping right + if (*MMp) + MMp++; + } + + MMp++; // skip nul + *MMq++ = 0; + + // Adjust ML B array length + if (ML) + u32_to_le(MLq-(ML+6), ML+2); + + // Move MM and ML down to include their MM:Z and ML:B bits + if (MM) MM-=2; + if (ML) ML-=2; + + // Now MM/ML are start of tags, MMq/MLq are ends of edited tags, + // and MMp/MLp are ends of original tags. Walk through tags taking up + // any gaps + // + // Eg XXXXXXmmmmm--YYYlllll-ZZ (m and l are edited MM and ML tags) + // => XXXXXXmmmmmYYYlllllZZ + + uint8_t *tag = bam_get_aux(cur), *tag_end = cur->data + cur->l_data; + uint8_t *to = tag; + while (tag && tag < tag_end) { + if (tag[0] == 'M' && (tag[1] == 'M' || tag[1] == 'm')) { + // Slow but easy + memmove(to, MM, MMq-MM); // length of new tag + to += MMq-MM; + tag = MMp; // size of old tag + } else if (tag[0] == 'M' && (tag[1] == 'L' || tag[1] == 'l')) { + memmove(to, ML, MLq-ML); + to += MLq-ML; + tag = MLp; + } else if (tag[0] == 'M' && tag[1] == 'N') { + tag = bam_aux_next(cur, tag+2); + // Skip it as we'll overwrite this later, although this + // does change the tag order. Instead we could do: + // + // *to++ = 'M'; + // *to++ = 'N'; + // to = MN_enc(to, cur->core.l_qseq); + } else { + // Want aux_skip, but it's private. + // So we use bam_aux_next with work-arounds. :( + uint8_t *from = tag; + tag = bam_aux_next(cur, tag+2); + tag = tag ? tag-2 : tag_end; + memmove(to, from, tag-from); + to += tag-from; + } + } + cur->l_data = to - cur->data; + + return 0; +} + +// Removes base modification tags: MM, ML and MN. +// This is more efficient than a series of bam_aux_remove and +// bam_aux_find calls, as the previous removes shuffle the tags we've +// previously found. However it's still not optimal. +void delete_mod_tags(bam1_t *b) { + uint8_t *tag = bam_aux_first(b), *next; + uint8_t *to = tag; + while (tag) { + next = bam_aux_next(b, tag); + if (tag[-2] == 'M' && + (tag[-1] == 'M' || tag[-1] == 'm' || + tag[-1] == 'L' || tag[-1] == 'l' || + tag[-1] == 'N')) { + // Skip. Equivalent to bam_aux_remove without multiple passes + } else { + // Copy. All these +/-2s are an annoyance caused by the + // tag iterator pointing to the byte after the 2-letter code + uint8_t *end = next ? next : b->data + b->l_data + 2; + if (tag != to) + memmove(to-2, tag-2, end-tag); + to += end-tag; + } + tag = next; + } + + b->l_data = (to-2) - b->data; +} + +int validate_MM(bam1_t *b, hts_base_mod_state *state) { + hts_base_mod mods[10]; + int n, pos; + while ((n = bam_next_basemod(b, state, mods, 10, &pos)) > 0) { + // bam_next_basemod will trigger MM out-of-bound checks + } + return n; +} + +// Fix base modification tags MM, ML and MN. +// For supplementary-style alignments we may have hard-clipped the sequence +// and just duplicated the MM/ML tags. Use the primary alignment to get the +// clipped sequence so we can trim MM/ML accordingly. +// +// We call this first on primary reads with pre == NULL. This caches +// MM and ML data into MM_state. +// +// We then call it again on secondary and/or supplementary data with +// pre == the primary record and pass in the associated state. This then +// validates MM/ML/MN match, and if not adjusts them if they have hard-clips +// which yields consistent data. +// +// TODO: add sanity check on counts of base types and MM tag to ensure it's +// possible. We can do this post-trimming, so we sanitize everything. +// +// Returns 0 on success, +// -1 on failure +int fix_MM(bam1_t *pre, bam1_t *cur, MM_state *state) { + int end5, end3; + int MNi = 0; // MN of -1 is used as indicator for no valid mods + + if (!pre && state) { + // First time we've see this name. + // Look for base modification tags and sanity check. + get_mod_info(cur, &state->MM, &state->ML, &state->MN, &MNi, + &end5, &end3); + if (!state->MM) { + delete_mod_tags(cur); + return 0; + } + + if (!end5 && !end3 && MNi <= 0) { + // No MN tag, but also no clipping. Assume MM is valid + if (cur->core.l_qseq) + if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0) + return -1; + } else if ((end3 || end5) && cur->core.l_qseq != MNi) { + // We have hard clips and MN tag, but the MN tag doesn't match + // observed sequence length so it appears the hard-clipping + // happened after base-mods called without updating. + // Fail as this is a primary read. + delete_mod_tags(cur); + } + // Otherwise we assume the base modifications are correct + + } else if (state) { + // A supplementary or secondary alignment with known primary + uint8_t *cur_MM = NULL, *cur_ML = NULL, *cur_MN = NULL; + MNi = -1; + get_mod_info(cur, &cur_MM, &cur_ML, &cur_MN, &MNi, &end5, &end3); + + if (!cur_MM) { + delete_mod_tags(cur); + return 0; + } + + // Does MN match seq length? If so, we believe it's already valid + if (MNi == cur->core.l_qseq) + goto validate; + + // Length mismatch and/or no known length, so check vs full seq. + if (pre->core.l_qseq != cur->core.l_qseq + end3 + end5) { + delete_mod_tags(cur); + return 0; + } else if (end5 || end3) { + if (MNi < 0 || MNi == pre->core.l_qseq) + trim_MM(pre, cur, end5, end3, cur_MM, cur_ML, cur_MN); + } // else no hard clips so MM is already valid + + // Set MN so we've validated it, provided seq isn't "*". + // inefficient, but minimal compared to everything else + if (cur->core.l_qseq) + if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0) + return -1; + } + + validate: + ; + + // Also validate MM length matches sequence length. This mirrors the + // logic in htslib/sam_mods.c. + // For now we take the inefficient approach of using bam_parse_basemod2. + // Inefficient, but robust. + hts_base_mod_state *mst = hts_base_mod_state_alloc(); + if (!mst) + return -1; + + enum htsLogLevel lvl = hts_get_log_level(); + hts_set_log_level(HTS_LOG_OFF); + if (bam_parse_basemod(cur, mst) < 0) + // Maybe we want hts_log_warning still though? + delete_mod_tags(cur); + if (validate_MM(cur, mst) < 0) + delete_mod_tags(cur); + hts_set_log_level(lvl); + hts_base_mod_state_free(mst); + + return 0; +} + +// Ensure the b[] array is at least n. +// Returns 0 on success, +// -1 on failure +static int grow_b_array(bam1_t **b, int *ba, int n) { + if (n < *ba) + return 0; + + bam1_t *bnew = realloc(*b, (n+=10) * sizeof(**b)); + if (!bnew) + return -1; + *b = bnew; + + // bam_init1 equivalent + int i; + for (i = *ba; i < n; i++) + memset(&(*b)[i], 0, sizeof(bam1_t)); + + *b = bnew; + *ba = n; + + return 0; +} + +// We have b[0]..b[bn-1] entries all from the same template (qname) +typedef struct { + bam1_t *b; + int n, ba; // number used and number allocated + int b_next; // b[b_next] for start of next set, -1 if unset + int eof; // marker for having seen eof +} bam_set; + +// Fetches a new batch of BAM records all containing the same name. +// NB: we cache the last (non-matching) name in b[n], so we can use it to +// start the next batch. +// Returns the number of records on success, +// <0 on failure or EOF (sam_read1 return vals) +static int next_template(samFile *in, sam_hdr_t *header, bam_set *bs, + int sanitize_flags) { + int result; + + if (bs->eof) + return -1; + + // First time through, prime the template name + if (bs->b_next < 0) { + if (grow_b_array(&bs->b, &bs->ba, 1) < 0) + return -2; + result = sam_read1(in, header, &bs->b[0]); + if (result < 0) + return result; + if (bam_sanitize(header, &bs->b[0], sanitize_flags) < 0) + return -2; + } else { + // Otherwise use the previous template name read + bam1_t btmp = bs->b[0]; + bs->b[0] = bs->b[bs->b_next]; + bs->b[bs->b_next] = btmp; // For ->{,l_,m_}data + } + bs->n = 1; + + // Now keep reading until we find a read that mismatches or we hit eof. + char *name = bam_get_qname(&bs->b[0]); + for (;;) { + if (grow_b_array(&bs->b, &bs->ba, bs->n+1) < 0) + return -2; + + result = sam_read1(in, header, &bs->b[bs->n]); + if (result < -1) + return result; + + if (result < 0) { + bs->eof = 1; + bs->b_next = -1; + break; + } else { + if (bam_sanitize(header, &bs->b[bs->n], sanitize_flags) < 0) + return -2; + + bs->b_next = bs->n; + if (strcmp(name, bam_get_qname(&bs->b[bs->n])) != 0) + break; + } + + bs->n++; + } + + return bs->n; +} + +// currently, this function ONLY works if each read has one hit +// +// Returns 0 on success, +// >0 on failure +static int bam_mating_core(samFile *in, samFile *out, int remove_reads, + int proper_pair_check, int add_ct, + int do_mate_scoring, char *arg_list, int no_pg, + int sanitize_flags, int base_mods) +{ + sam_hdr_t *header; + int result, n; + kstring_t str = KS_INITIALIZE; + bam_set bs = {NULL, 0, 0, -1, 0}; + + header = sam_hdr_read(in); + if (header == NULL) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: Couldn't read header\n"); + return 1; + } + + // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted. + if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n"); + goto fail; + } + ks_free(&str); + + if (!no_pg && sam_hdr_add_pg(header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto fail; + + if (sam_hdr_write(out, header) < 0) goto write_fail; + + // Iterate template by template fetching bs->n records at a time + while ((result = next_template(in, header, &bs, sanitize_flags)) >= 0) { + bam1_t *cur = NULL, *pre = NULL, *rnum[2] = {NULL, NULL}; + int prev = -1, curr = -1; + hts_pos_t pre_end = 0, cur_end = 0; + + // Find and fix up primary alignments + MM_state state[2]; + for (n = 0; n < bs.n; n++) { + int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0; + if (bs.b[n].core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) + continue; + + if (base_mods) + if (fix_MM(NULL, &bs.b[n], &state[is_r2]) < 0) + goto fail; + + if (!pre) { + pre = &bs.b[prev = n]; + rnum[(pre->core.flag & BAM_FREAD2) != 0] = pre; + + pre_end = (pre->core.flag & BAM_FUNMAP) == 0 + ? bam_endpos(pre) : 0; + continue; + } + + // Note, more than 2 primary alignments will use 'curr' as last + cur = &bs.b[curr = n]; + rnum[(cur->core.flag & BAM_FREAD2) != 0] = cur; + cur_end = (cur->core.flag & BAM_FUNMAP) == 0 + ? bam_endpos(cur) : 0; + + pre->core.flag |= BAM_FPAIRED; + cur->core.flag |= BAM_FPAIRED; + if (sync_mate(pre, cur)) + goto fail; + + // If safe set TLEN/ISIZE + if (pre->core.tid == cur->core.tid + && !(cur->core.flag & (BAM_FUNMAP | BAM_FMUNMAP)) + && !(pre->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))) { + hts_pos_t cur5, pre5; + cur5 = (cur->core.flag & BAM_FREVERSE) + ? cur_end + : cur->core.pos; + pre5 = (pre->core.flag & BAM_FREVERSE) + ? pre_end + : pre->core.pos; + cur->core.isize = pre5 - cur5; + pre->core.isize = cur5 - pre5; + } else { + cur->core.isize = pre->core.isize = 0; + } + + if (add_ct) + bam_template_cigar(pre, cur, &str); + + // TODO: Add code to properly check if read is in a proper + // pair based on ISIZE distribution + if (proper_pair_check && !plausibly_properly_paired(pre,cur)) { + pre->core.flag &= ~BAM_FPROPER_PAIR; + cur->core.flag &= ~BAM_FPROPER_PAIR; + } + + if (do_mate_scoring) { + if ((add_mate_score(pre, cur) == -1) || + (add_mate_score(cur, pre) == -1)) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: " + "unable to add mate score.\n"); + goto fail; + } + } + + // If we have to remove reads make sure we do it in a way that + // doesn't create orphans with bad flags + if (remove_reads) { + if (pre->core.flag&BAM_FUNMAP) + cur->core.flag &= + ~(BAM_FMREVERSE|BAM_FPROPER_PAIR); + if (cur->core.flag&BAM_FUNMAP) + pre->core.flag &= + ~(BAM_FMREVERSE|BAM_FPROPER_PAIR); + } + } + + // Handle unpaired primary data + if (!cur && pre) { + pre->core.mtid = -1; + pre->core.mpos = -1; + pre->core.isize = 0; + pre->core.flag &= ~(BAM_FMREVERSE|BAM_FPROPER_PAIR); + } + + // Now process secondary and supplementary alignments + for (n = 0; n < bs.n; n++) { + if (!(bs.b[n].core.flag & (BAM_FSECONDARY|BAM_FSUPPLEMENTARY))) { + // primary + continue; + } + + // Secondary or supplementary + int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0; + bam1_t *primary = rnum[is_r2]; + if (primary) { + if (base_mods) + fix_MM(primary, &bs.b[n], &state[is_r2]); + } else { + // Record with base modifications but no known primary + //fprintf(samtools_stderr, "Unpaired secondary or supplementary\n"); + if (base_mods) + fix_MM(NULL, &bs.b[n], NULL); + } + } + + // Finally having curated everything, write out all records in their + // original ordering + for (n = 0; n < bs.n; n++) { + bam1_t *cur = &bs.b[n]; + // We may remove unmapped and secondary alignments + if (remove_reads && (cur->core.flag & (BAM_FSECONDARY|BAM_FUNMAP))) + continue; + + if (sam_write1(out, header, cur) < 0) + goto write_fail; + } + } + if (result < -1) + goto read_fail; + + sam_hdr_destroy(header); + + for (n = 0; n < bs.ba; n++) + free(bs.b[n].data); + free(bs.b); + ks_free(&str); + return 0; + + read_fail: + print_error("fixmate", "Couldn't read from input file"); + goto fail; + + write_fail: + print_error_errno("fixmate", "Couldn't write to output file"); + fail: + sam_hdr_destroy(header); + for (n = 0; n < bs.ba; n++) + free(bs.b[n].data); + free(bs.b); + ks_free(&str); + return 1; +} + +void usage(FILE* where) +{ + fprintf(where, +"Usage: samtools fixmate \n" +"Options:\n" +" -r Remove unmapped reads and secondary alignments\n" +" -p Disable FR proper pair check\n" +" -c Add template cigar ct tag\n" +" -m Add mate score tag\n" +" -u Uncompressed output\n" +" -z, --sanitize FLAG[,FLAG]\n" +" Sanitize alignment fields [defaults to all types]\n" +" -M Fix base modification tags (MM/ML/MN)\n" +" --no-PG do not add a PG line\n"); + + sam_global_opt_help(where, "-.O..@-."); + + fprintf(where, +"\n" +"As elsewhere in samtools, use '-' as the filename for stdin/samtools_stdout. The input\n" +"file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n" +"input is not accepted.\n"); +} + +int bam_mating(int argc, char *argv[]) +{ + htsThreadPool p = {NULL, 0}; + samFile *in = NULL, *out = NULL; + int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1, + mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL, base_mods = 0; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + char wmode[4] = {'w', 'b', 0, 0}; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + char *arg_list = NULL; + + // parse args + if (argc == 1) { usage(samtools_stdout); return 0; } + while ((c = getopt_long(argc, argv, "rpcmMO:@:uz:", lopts, NULL)) >= 0) { + switch (c) { + case 'r': remove_reads = 1; break; + case 'p': proper_pair_check = 0; break; + case 'c': add_ct = 1; break; + case 'm': mate_score = 1; break; + case 'M': base_mods = 1; break; + case 'u': wmode[2] = '0'; break; + case 1: no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage(samtools_stderr); goto fail; + case 'z': + if ((sanitize_flags = bam_sanitize_options(optarg)) < 0) + samtools_exit(1); + break; + } + } + if (optind+1 >= argc) { usage(samtools_stderr); goto fail; } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) + goto fail; + + // init + if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) { + print_error_errno("fixmate", "cannot open input file"); + goto fail; + } + sam_open_mode(wmode+1, argv[optind+1], NULL); + if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) { + print_error_errno("fixmate", "cannot open output file"); + goto fail; + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(samtools_stderr, "Error creating thread pool\n"); + goto fail; + } + hts_set_opt(in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(out, HTS_OPT_THREAD_POOL, &p); + } + + // run + res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct, + mate_score, arg_list, no_pg, sanitize_flags, + base_mods); + + // cleanup + sam_close(in); + if (sam_close(out) < 0) { + fprintf(samtools_stderr, "[bam_mating] error while closing output file\n"); + res = 1; + } + + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return res; + + fail: + if (in) sam_close(in); + if (out) sam_close(out); + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return 1; +} + + diff --git a/shared/package-files/06/061f300ea91b48bfb2aff30342a1395d4a16cd96afe49fd5cc2f0b7efdc10650/test_ndarray_like.py b/shared/package-files/06/061f300ea91b48bfb2aff30342a1395d4a16cd96afe49fd5cc2f0b7efdc10650/test_ndarray_like.py new file mode 100644 index 0000000000000000000000000000000000000000..6c16e7dbf49d38547e320500568560c1256e6822 --- /dev/null +++ b/shared/package-files/06/061f300ea91b48bfb2aff30342a1395d4a16cd96afe49fd5cc2f0b7efdc10650/test_ndarray_like.py @@ -0,0 +1,48 @@ +import pytest + +from numcodecs.ndarray_like import DType, FlagsObj, NDArrayLike + + +@pytest.mark.parametrize("module", ["numpy", "cupy"]) +def test_is_ndarray_like(module): + m = pytest.importorskip(module) + a = m.arange(10) + assert isinstance(a, NDArrayLike) + + +def test_is_not_ndarray_like(): + assert not isinstance([1, 2, 3], NDArrayLike) + assert not isinstance(b"1,2,3", NDArrayLike) + + +@pytest.mark.parametrize("module", ["numpy", "cupy"]) +def test_is_dtype_like(module): + m = pytest.importorskip(module) + d = m.dtype("u8") + assert isinstance(d, DType) + + +def test_is_not_dtype_like(): + assert not isinstance([1, 2, 3], DType) + assert not isinstance(b"1,2,3", DType) + + +@pytest.mark.parametrize("module", ["numpy", "cupy"]) +def test_is_flags_like(module): + m = pytest.importorskip(module) + d = m.arange(10).flags + assert isinstance(d, FlagsObj) + + +def test_is_not_flags_like(): + assert not isinstance([1, 2, 3], FlagsObj) + assert not isinstance(b"1,2,3", FlagsObj) + + +@pytest.mark.parametrize("module", ["numpy", "cupy"]) +def test_cached_isinstance_check(module): + m = pytest.importorskip(module) + a = m.arange(10) + assert isinstance(a, NDArrayLike) + assert not isinstance(a, DType) + assert not isinstance(a, FlagsObj) diff --git a/shared/package-files/06/0620689f239b0ac4ba1272d4208ff5903b5c84337b4eeaf44f818cce8528d3a3/pkgdata.py b/shared/package-files/06/0620689f239b0ac4ba1272d4208ff5903b5c84337b4eeaf44f818cce8528d3a3/pkgdata.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf2065759362ee09a252d4736bd612b8d271e72 --- /dev/null +++ b/shared/package-files/06/0620689f239b0ac4ba1272d4208ff5903b5c84337b4eeaf44f818cce8528d3a3/pkgdata.py @@ -0,0 +1,33 @@ +# This module is deprecated and will be removed. + +import sys +import os +from io import StringIO + +from sympy.utilities.decorator import deprecated + + +@deprecated( + """ + The sympy.utilities.pkgdata module and its get_resource function are + deprecated. Use the stdlib importlib.resources module instead. + """, + deprecated_since_version="1.12", + active_deprecations_target="pkgdata", +) +def get_resource(identifier, pkgname=__name__): + + mod = sys.modules[pkgname] + fn = getattr(mod, '__file__', None) + if fn is None: + raise OSError("%r has no __file__!") + path = os.path.join(os.path.dirname(fn), identifier) + loader = getattr(mod, '__loader__', None) + if loader is not None: + try: + data = loader.get_data(path) + except (OSError, AttributeError): + pass + else: + return StringIO(data.decode('utf-8')) + return open(os.path.normpath(path), 'rb') diff --git a/shared/package-files/06/0624dc495f0084fa8167b834d09a44098fb0fdff8dcb5f0a4320b15602b04ac8/_embedding_bag_sparse_backward_native.h b/shared/package-files/06/0624dc495f0084fa8167b834d09a44098fb0fdff8dcb5f0a4320b15602b04ac8/_embedding_bag_sparse_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..332d231002c1403f4590925e221b1d0463c0d060 --- /dev/null +++ b/shared/package-files/06/0624dc495f0084fa8167b834d09a44098fb0fdff8dcb5f0a4320b15602b04ac8/_embedding_bag_sparse_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +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 & per_sample_weights, int64_t padding_idx=-1); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/062c95ed30861d0f06883087f299fa0d7a1fd2e64e95a7c9b38085d1fe402572/test_sort_values.cpython-311.pyc b/shared/package-files/06/062c95ed30861d0f06883087f299fa0d7a1fd2e64e95a7c9b38085d1fe402572/test_sort_values.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b3ca83d4eeda15b65c465678600a692d8fe9cdb Binary files /dev/null and b/shared/package-files/06/062c95ed30861d0f06883087f299fa0d7a1fd2e64e95a7c9b38085d1fe402572/test_sort_values.cpython-311.pyc differ diff --git a/shared/package-files/06/062f6ebf5e41e4c5d437dfa1c940f21d90e4de3f82a3032c1b550eabbf90be52/fx_symbolic_graph_extractor.py b/shared/package-files/06/062f6ebf5e41e4c5d437dfa1c940f21d90e4de3f82a3032c1b550eabbf90be52/fx_symbolic_graph_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..ff31a8875fc34618e385bd95a0cc02f55b0088c5 --- /dev/null +++ b/shared/package-files/06/062f6ebf5e41e4c5d437dfa1c940f21d90e4de3f82a3032c1b550eabbf90be52/fx_symbolic_graph_extractor.py @@ -0,0 +1,254 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import functools +from typing import Any, Callable, TYPE_CHECKING + +import torch +import torch.fx +import torch.onnx +import torch.onnx._internal.fx.passes as passes +from torch.onnx._internal import _exporter_legacy, io_adapter + + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + +# Functions directly wrapped to produce torch.fx.Proxy so that symbolic +# data can flow through those functions. Python functions (e.g., `torch.arange`) +# not defined by pybind11 in C++ do not go though Python dispatcher, so +# they are not automatically patched by FX's Python dispatcher. +# The list below means `torch.arange`, `torch.tensor`, and so on will be +# patched. +_TORCH_METHODS_TO_PATCH: tuple[str, ...] = ( + "arange", + "tensor", + "finfo", + "full", + "empty", +) + + +class ModuleExpansionTracer(torch.fx._symbolic_trace.Tracer): + """Tracer to create ONNX-exporting friendly FX graph. + + This tracer traces models into operators. That is, + the traced graph mostly contains call_function nodes and + has no call_module nodes. The call_module nodes + are problematic to the use of make_fx(...) in ONNX + exporter. + """ + + def is_leaf_module( + self, module: torch.nn.Module, module_qualified_name: str + ) -> bool: + # This returns False so that all sub-modules are considered as not leaves + # and therefore expanded into operators in + # torch.fx._symbolic_trace.Tracer.call_module. + return False + + def to_bool(self, obj: torch.fx.Proxy) -> bool: + # FIXME: This is a hack to tracing through if-else Python blocks. + # It may generate incorrect ONNX graphs if the if-else block + return False + + +def _wrap_for_symbolic_trace(target: Callable) -> tuple[Callable, Callable]: + """This function wraps ```target`` for symbolic tracing. + + This function wraps ```target``` so that its wrapper produces + torch.fx.Proxy in symbolic computation. The returned values are + the wrapper and then the original function. Per `_TORCH_METHODS_TO_PATCH`, + this function shall receive `torch.arange`, `torch.tensor`, etc. as inputs. + """ + + @functools.wraps(target) + def wrapper(*args, **kwargs): + proxy = None + + def check_has_proxy(v): + if isinstance(v, torch.fx.Proxy): + nonlocal proxy + proxy = v + + torch.fx.node.map_aggregate(args, check_has_proxy) + torch.fx.node.map_aggregate(kwargs, check_has_proxy) + + if proxy is not None: + return proxy.tracer.create_proxy("call_function", target, args, kwargs) + else: + return target(*args, **kwargs) + + return wrapper, target + + +def _module_expansion_symbolic_trace( + root: torch.nn.Module | Callable[..., Any], + concrete_args: dict[str, Any] | None = None, +) -> torch.fx.GraphModule: + """Trace a callable into FX graph. + + When "root" is torch.nn.Module, calls to its submodule (type: torch.nn.Module) will be + expanded into operators (e.g., torch.matmul, torch.add, +, and -) to simplify graph + structure. + """ + # For functions doesn't support symbolic tracing, create wrappers + # which produce symbolic results during tracing. + patched_torch_methods = { + target_name: _wrap_for_symbolic_trace(getattr(torch, target_name)) + for target_name in _TORCH_METHODS_TO_PATCH + } + + # Set the symbolic-tracing friendly functions so that `tracer.trace` below + # can work. + for name, (wrapper, _) in patched_torch_methods.items(): + setattr(torch, name, wrapper) + + try: + # Set up a tracer. + tracer = ModuleExpansionTracer() + # Trace the model. + graph = tracer.trace(root, concrete_args) + name = ( + root.__class__.__name__ + if isinstance(root, torch.nn.Module) + else root.__name__ + ) + return torch.fx.GraphModule(tracer.root, graph, name) + finally: + # Revert the patches for symbolic tracing. + for name, (_, wrapped) in patched_torch_methods.items(): + # wrapped is the original version of `torch.name`. + setattr(torch, name, wrapped) + + +# TODO: Migrate to `DynamoExporter` after fake model tracing is supported. +# Proposal at https://github.com/pytorch/pytorch/issues/95900. +class FXSymbolicTracer(_exporter_legacy.FXGraphExtractor): + """Generates a FX GraphModule using torch.fx.symbolic_trace API + Args: + concrete_args: Inputs to be partially specialized + It can be used to remove control flow or data structures. + For example:: + def f(a, b): + if b == True: + return a + else: + return a*2 + FX can typically not trace through this due to the presence of control + flow. However, we can use `concrete_args` to specialize on the value of + `b` to trace through this:: + f = fx.symbolic_trace(f, concrete_args={'b': False}) + assert f(3, False) == 6 + Note that although you can still pass in different values of `b`, they will be ignored. + It can also be used to eliminate data-structure handling from + our function. This will use pytrees to flatten your input. To avoid + overspecializing, pass in `fx.PH` for values that shouldn't be + specialized. For example:: + def f(x): + out = 0 + for v in x.values(): + out += v + return out + + + f = fx.symbolic_trace( + f, + concrete_args={"x": {"a": fx.PH, "b": fx.PH, "c": fx.PH}}, + ) + assert f({"a": 1, "b": 2, "c": 4}) == 7 + """ + + def __init__(self, concrete_args: dict[str, Any] | None = None): + super().__init__() + # TODO: plumb ``concrete_args`` to symbolic_trace call at ``generate_fx`` + self.concrete_args = concrete_args + + def _trace_into_fx_graph_via_fx_symbolic_trace( + self, model, model_args, model_kwargs + ) -> torch.fx.GraphModule: + # Bind model args and kwargs with model signature to retrieve default values + # of unprovided arguments. These are then used to construct ``concrete_args``. + bind_input_step = io_adapter.BindInputStep( + torch.onnx.utils.model_signature(model) + ) + self.input_adapter.append_step(bind_input_step) + _, named_args = bind_input_step.apply(model_args, model_kwargs, model=model) + + # Create inputs to call symbolic trace (torch.fx.symbolic_trace) + # Example content of concrete_args: + # concrete_args["x"] = torch.fx._symbolic_trace.PH + # concrete_args["b"] = 1 + # where "x" and "b" are argument names in "signature". + concrete_args = {} + for param_name, param_value in named_args.items(): + if isinstance(param_value, torch.Tensor): + # param_value can be, e.g., a real tensor or a fake tensor. + # param_value is treated as substitutable tensor symbol (aka placeholder). + concrete_args[param_name] = torch.fx._symbolic_trace.PH + else: + concrete_args[param_name] = param_value + + # Merge kwargs back into args since that is the format FX graph expects. + merge_kwargs_step = io_adapter.MergeKwargsIntoArgsInputStep() + self.input_adapter.append_step(merge_kwargs_step) + return _module_expansion_symbolic_trace(model, concrete_args=concrete_args) + + def generate_fx( + self, + options: _exporter_legacy.ResolvedExportOptions, + model: torch.nn.Module | Callable, + model_args: Sequence[Any], + model_kwargs: Mapping[str, Any], + ) -> torch.fx.GraphModule: + diagnostic_context = options.diagnostic_context + graph_module = self._trace_into_fx_graph_via_fx_symbolic_trace( + model, model_args, model_kwargs + ) + + # Make sure all placeholder nodes are executed before get_attr nodes. + # Otherwise, inputs can interleave with initializers in the final ModeoProto.graph.input. + # Basically, we want + # ModeoProto.graph.input = + # [input_0, input_1, ..., input_n, weight_0, weight_1, ..., weight_m] + # and we don't want + # ModeoProto.graph.input = + # [input_0, weight_0, input_1, weight_1, ..., input_n, weight_0, weight_1, ..., weight_m] + graph_module = passes.MovePlaceholderToFront( + diagnostic_context, graph_module + ).run() + # To save memory, move get_attr to input so that the generated model doesn't + # have weigh tensors. "replaced_attrs" are a tuple of replaced weight tensors. + replace_get_attr_with_placeholder_pass = passes.ReplaceGetAttrWithPlaceholder( + diagnostic_context, graph_module + ) + graph_module = replace_get_attr_with_placeholder_pass.run() + replaced_attrs = replace_get_attr_with_placeholder_pass.replaced_attrs + append_extra_input_step = io_adapter.LiftParametersAndBuffersIntoArgsInputStep( + replaced_attrs + ) + self.input_adapter.append_step(append_extra_input_step) + # Move all newly created placeholder nodes to the front of the graph. + graph_module = passes.MovePlaceholderToFront( + diagnostic_context, graph_module + ).run() + # Finalize the graph editing. + graph_module.recompile() + + updated_model_args = self.input_adapter.apply( + *model_args, model=model, **model_kwargs + ) + + return self.pre_export_passes(options, model, graph_module, updated_model_args) # type: ignore[return-value] + + def pre_export_passes( + self, + options: _exporter_legacy.ResolvedExportOptions, + original_model: torch.nn.Module | Callable, + fx_module: torch.fx.GraphModule, + fx_module_args: Sequence[Any], + ): + return _exporter_legacy.common_pre_export_passes( + options, original_model, fx_module, fx_module_args + ) diff --git a/shared/package-files/06/06363bb2a8bd33adf787d66028d17c99bc1a030cf368a2048a9f087a8f4e02be/test_python.cpython-311.pyc b/shared/package-files/06/06363bb2a8bd33adf787d66028d17c99bc1a030cf368a2048a9f087a8f4e02be/test_python.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77a88e12575112a147e368c5856cf910999acbe5 Binary files /dev/null and b/shared/package-files/06/06363bb2a8bd33adf787d66028d17c99bc1a030cf368a2048a9f087a8f4e02be/test_python.cpython-311.pyc differ diff --git a/shared/package-files/06/0636f045562112f6e9f30d39b1877cdfc55f812e1d364b5bf13ee6d8f89c8c23/feather_format.py b/shared/package-files/06/0636f045562112f6e9f30d39b1877cdfc55f812e1d364b5bf13ee6d8f89c8c23/feather_format.py new file mode 100644 index 0000000000000000000000000000000000000000..d0aaf83b84cb241ebdd872c1c8b7982fadc9acdb --- /dev/null +++ b/shared/package-files/06/0636f045562112f6e9f30d39b1877cdfc55f812e1d364b5bf13ee6d8f89c8c23/feather_format.py @@ -0,0 +1,143 @@ +""" feather-format compat """ +from __future__ import annotations + +from typing import ( + TYPE_CHECKING, + Any, +) + +from pandas._config import using_pyarrow_string_dtype + +from pandas._libs import lib +from pandas.compat._optional import import_optional_dependency +from pandas.util._decorators import doc +from pandas.util._validators import check_dtype_backend + +import pandas as pd +from pandas.core.api import DataFrame +from pandas.core.shared_docs import _shared_docs + +from pandas.io._util import arrow_string_types_mapper +from pandas.io.common import get_handle + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Sequence, + ) + + from pandas._typing import ( + DtypeBackend, + FilePath, + ReadBuffer, + StorageOptions, + WriteBuffer, + ) + + +@doc(storage_options=_shared_docs["storage_options"]) +def to_feather( + df: DataFrame, + path: FilePath | WriteBuffer[bytes], + storage_options: StorageOptions | None = None, + **kwargs: Any, +) -> None: + """ + Write a DataFrame to the binary Feather format. + + Parameters + ---------- + df : DataFrame + path : str, path object, or file-like object + {storage_options} + **kwargs : + Additional keywords passed to `pyarrow.feather.write_feather`. + + """ + import_optional_dependency("pyarrow") + from pyarrow import feather + + if not isinstance(df, DataFrame): + raise ValueError("feather only support IO with DataFrames") + + with get_handle( + path, "wb", storage_options=storage_options, is_text=False + ) as handles: + feather.write_feather(df, handles.handle, **kwargs) + + +@doc(storage_options=_shared_docs["storage_options"]) +def read_feather( + path: FilePath | ReadBuffer[bytes], + columns: Sequence[Hashable] | None = None, + use_threads: bool = True, + storage_options: StorageOptions | None = None, + dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, +) -> DataFrame: + """ + Load a feather-format object from the file path. + + Parameters + ---------- + path : str, path object, or file-like object + String, path object (implementing ``os.PathLike[str]``), or file-like + object implementing a binary ``read()`` function. The string could be a URL. + Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is + expected. A local file could be: ``file://localhost/path/to/table.feather``. + columns : sequence, default None + If not provided, all columns are read. + use_threads : bool, default True + Whether to parallelize reading using multiple threads. + {storage_options} + + dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable' + Back-end data type applied to the resultant :class:`DataFrame` + (still experimental). Behaviour is as follows: + + * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` + (default). + * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` + DataFrame. + + .. versionadded:: 2.0 + + Returns + ------- + type of object stored in file + + Examples + -------- + >>> df = pd.read_feather("path/to/file.feather") # doctest: +SKIP + """ + import_optional_dependency("pyarrow") + from pyarrow import feather + + # import utils to register the pyarrow extension types + import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401 + + check_dtype_backend(dtype_backend) + + with get_handle( + path, "rb", storage_options=storage_options, is_text=False + ) as handles: + if dtype_backend is lib.no_default and not using_pyarrow_string_dtype(): + return feather.read_feather( + handles.handle, columns=columns, use_threads=bool(use_threads) + ) + + pa_table = feather.read_table( + handles.handle, columns=columns, use_threads=bool(use_threads) + ) + + if dtype_backend == "numpy_nullable": + from pandas.io._util import _arrow_dtype_mapping + + return pa_table.to_pandas(types_mapper=_arrow_dtype_mapping().get) + + elif dtype_backend == "pyarrow": + return pa_table.to_pandas(types_mapper=pd.ArrowDtype) + + elif using_pyarrow_string_dtype(): + return pa_table.to_pandas(types_mapper=arrow_string_types_mapper()) + else: + raise NotImplementedError diff --git a/shared/package-files/06/0639372bac40320c313cd4ca7e293b482e58db8c202acf0ecf9563bc5772d240/class.h b/shared/package-files/06/0639372bac40320c313cd4ca7e293b482e58db8c202acf0ecf9563bc5772d240/class.h new file mode 100644 index 0000000000000000000000000000000000000000..b990507d629b4260d66d51e23a7f34a0fa465c9e --- /dev/null +++ b/shared/package-files/06/0639372bac40320c313cd4ca7e293b482e58db8c202acf0ecf9563bc5772d240/class.h @@ -0,0 +1,767 @@ +/* + pybind11/detail/class.h: Python C API implementation details for py::class_ + + Copyright (c) 2017 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include + +#include "exception_translation.h" + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) + +#if !defined(PYPY_VERSION) +# define PYBIND11_BUILTIN_QUALNAME +# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) +#else +// In PyPy, we still set __qualname__ so that we can produce reliable function type +// signatures; in CPython this macro expands to nothing: +# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \ + setattr((PyObject *) obj, "__qualname__", nameobj) +#endif + +inline std::string get_fully_qualified_tp_name(PyTypeObject *type) { +#if !defined(PYPY_VERSION) + return type->tp_name; +#else + auto module_name = handle((PyObject *) type).attr("__module__").cast(); + if (module_name == PYBIND11_BUILTINS_MODULE) + return type->tp_name; + else + return std::move(module_name) + "." + type->tp_name; +#endif +} + +inline PyTypeObject *type_incref(PyTypeObject *type) { + Py_INCREF(type); + return type; +} + +#if !defined(PYPY_VERSION) + +/// `pybind11_static_property.__get__()`: Always pass the class instead of the instance. +extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) { + return PyProperty_Type.tp_descr_get(self, cls, cls); +} + +/// `pybind11_static_property.__set__()`: Just like the above `__get__()`. +extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) { + PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj); + return PyProperty_Type.tp_descr_set(self, cls, value); +} + +// Forward declaration to use in `make_static_property_type()` +inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type); + +/** A `static_property` is the same as a `property` but the `__get__()` and `__set__()` + methods are modified to always use the object type instead of a concrete instance. + Return value: New reference. */ +inline PyTypeObject *make_static_property_type() { + constexpr auto *name = "pybind11_static_property"; + auto name_obj = reinterpret_steal(PYBIND11_FROM_STRING(name)); + + /* Danger zone: from now (and until PyType_Ready), make sure to + issue no Python C API calls which could potentially invoke the + garbage collector (the GC will call type_traverse(), which will in + turn find the newly constructed type in an invalid state) */ + auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0); + if (!heap_type) { + pybind11_fail("make_static_property_type(): error allocating type!"); + } + + heap_type->ht_name = name_obj.inc_ref().ptr(); +# ifdef PYBIND11_BUILTIN_QUALNAME + heap_type->ht_qualname = name_obj.inc_ref().ptr(); +# endif + + auto *type = &heap_type->ht_type; + type->tp_name = name; + type->tp_base = type_incref(&PyProperty_Type); + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE; + type->tp_descr_get = pybind11_static_get; + type->tp_descr_set = pybind11_static_set; + +# if PY_VERSION_HEX >= 0x030C0000 + // Since Python-3.12 property-derived types are required to + // have dynamic attributes (to set `__doc__`) + enable_dynamic_attributes(heap_type); +# endif + + if (PyType_Ready(type) < 0) { + pybind11_fail("make_static_property_type(): failure in PyType_Ready()!"); + } + + setattr((PyObject *) type, "__module__", str("pybind11_builtins")); + PYBIND11_SET_OLDPY_QUALNAME(type, name_obj); + + return type; +} + +#else // PYPY + +/** PyPy has some issues with the above C API, so we evaluate Python code instead. + This function will only be called once so performance isn't really a concern. + Return value: New reference. */ +inline PyTypeObject *make_static_property_type() { + auto d = dict(); + PyObject *result = PyRun_String(R"(\ +class pybind11_static_property(property): + def __get__(self, obj, cls): + return property.__get__(self, cls, cls) + + def __set__(self, obj, value): + cls = obj if isinstance(obj, type) else type(obj) + property.__set__(self, cls, value) +)", + Py_file_input, + d.ptr(), + d.ptr()); + if (result == nullptr) + throw error_already_set(); + Py_DECREF(result); + return (PyTypeObject *) d["pybind11_static_property"].cast().release().ptr(); +} + +#endif // PYPY + +/** Types with static properties need to handle `Type.static_prop = x` in a specific way. + By default, Python replaces the `static_property` itself, but for wrapped C++ types + we need to call `static_property.__set__()` in order to propagate the new value to + the underlying C++ data structure. */ +extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) { + // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw + // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`). + PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name); + + // The following assignment combinations are possible: + // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)` + // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop` + // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment + auto *const static_prop = (PyObject *) get_internals().static_property_type; + const auto call_descr_set = (descr != nullptr) && (value != nullptr) + && (PyObject_IsInstance(descr, static_prop) != 0) + && (PyObject_IsInstance(value, static_prop) == 0); + if (call_descr_set) { + // Call `static_property.__set__()` instead of replacing the `static_property`. +#if !defined(PYPY_VERSION) + return Py_TYPE(descr)->tp_descr_set(descr, obj, value); +#else + if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) { + Py_DECREF(result); + return 0; + } else { + return -1; + } +#endif + } else { + // Replace existing attribute. + return PyType_Type.tp_setattro(obj, name, value); + } +} + +/** + * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing + * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function, + * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here + * to do a special case bypass for PyInstanceMethod_Types. + */ +extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) { + PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name); + if (descr && PyInstanceMethod_Check(descr)) { + Py_INCREF(descr); + return descr; + } + return PyType_Type.tp_getattro(obj, name); +} + +/// metaclass `__call__` function that is used to create all pybind11 objects. +extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) { + + // use the default metaclass call to create/initialize the object + PyObject *self = PyType_Type.tp_call(type, args, kwargs); + if (self == nullptr) { + return nullptr; + } + + // Ensure that the base __init__ function(s) were called + values_and_holders vhs(self); + for (const auto &vh : vhs) { + if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) { + PyErr_Format(PyExc_TypeError, + "%.200s.__init__() must be called when overriding __init__", + get_fully_qualified_tp_name(vh.type->type).c_str()); + Py_DECREF(self); + return nullptr; + } + } + + return self; +} + +/// Cleanup the type-info for a pybind11-registered type. +extern "C" inline void pybind11_meta_dealloc(PyObject *obj) { + with_internals([obj](internals &internals) { + auto *type = (PyTypeObject *) obj; + + // A pybind11-registered type will: + // 1) be found in internals.registered_types_py + // 2) have exactly one associated `detail::type_info` + auto found_type = internals.registered_types_py.find(type); + if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1 + && found_type->second[0]->type == type) { + + auto *tinfo = found_type->second[0]; + auto tindex = std::type_index(*tinfo->cpptype); + internals.direct_conversions.erase(tindex); + + if (tinfo->module_local) { + get_local_internals().registered_types_cpp.erase(tindex); + } else { + internals.registered_types_cpp.erase(tindex); + } + internals.registered_types_py.erase(tinfo->type); + + // Actually just `std::erase_if`, but that's only available in C++20 + auto &cache = internals.inactive_override_cache; + for (auto it = cache.begin(), last = cache.end(); it != last;) { + if (it->first == (PyObject *) tinfo->type) { + it = cache.erase(it); + } else { + ++it; + } + } + + delete tinfo; + } + }); + + PyType_Type.tp_dealloc(obj); +} + +/** This metaclass is assigned by default to all pybind11 types and is required in order + for static properties to function correctly. Users may override this using `py::metaclass`. + Return value: New reference. */ +inline PyTypeObject *make_default_metaclass() { + constexpr auto *name = "pybind11_type"; + auto name_obj = reinterpret_steal(PYBIND11_FROM_STRING(name)); + + /* Danger zone: from now (and until PyType_Ready), make sure to + issue no Python C API calls which could potentially invoke the + garbage collector (the GC will call type_traverse(), which will in + turn find the newly constructed type in an invalid state) */ + auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0); + if (!heap_type) { + pybind11_fail("make_default_metaclass(): error allocating metaclass!"); + } + + heap_type->ht_name = name_obj.inc_ref().ptr(); +#ifdef PYBIND11_BUILTIN_QUALNAME + heap_type->ht_qualname = name_obj.inc_ref().ptr(); +#endif + + auto *type = &heap_type->ht_type; + type->tp_name = name; + type->tp_base = type_incref(&PyType_Type); + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE; + + type->tp_call = pybind11_meta_call; + + type->tp_setattro = pybind11_meta_setattro; + type->tp_getattro = pybind11_meta_getattro; + + type->tp_dealloc = pybind11_meta_dealloc; + + if (PyType_Ready(type) < 0) { + pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!"); + } + + setattr((PyObject *) type, "__module__", str("pybind11_builtins")); + PYBIND11_SET_OLDPY_QUALNAME(type, name_obj); + + return type; +} + +/// For multiple inheritance types we need to recursively register/deregister base pointers for any +/// base classes with pointers that are difference from the instance value pointer so that we can +/// correctly recognize an offset base class pointer. This calls a function with any offset base +/// ptrs. +inline void traverse_offset_bases(void *valueptr, + const detail::type_info *tinfo, + instance *self, + bool (*f)(void * /*parentptr*/, instance * /*self*/)) { + for (handle h : reinterpret_borrow(tinfo->type->tp_bases)) { + if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) { + for (auto &c : parent_tinfo->implicit_casts) { + if (c.first == tinfo->cpptype) { + auto *parentptr = c.second(valueptr); + if (parentptr != valueptr) { + f(parentptr, self); + } + traverse_offset_bases(parentptr, parent_tinfo, self, f); + break; + } + } + } + } +} + +inline bool register_instance_impl(void *ptr, instance *self) { + with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); }); + return true; // unused, but gives the same signature as the deregister func +} +inline bool deregister_instance_impl(void *ptr, instance *self) { + return with_instance_map(ptr, [&](instance_map &instances) { + auto range = instances.equal_range(ptr); + for (auto it = range.first; it != range.second; ++it) { + if (self == it->second) { + instances.erase(it); + return true; + } + } + return false; + }); +} + +inline void register_instance(instance *self, void *valptr, const type_info *tinfo) { + register_instance_impl(valptr, self); + if (!tinfo->simple_ancestors) { + traverse_offset_bases(valptr, tinfo, self, register_instance_impl); + } +} + +inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) { + bool ret = deregister_instance_impl(valptr, self); + if (!tinfo->simple_ancestors) { + traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl); + } + return ret; +} + +/// Instance creation function for all pybind11 types. It allocates the internal instance layout +/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is +/// cast to a reference or pointer), and initialization is done by an `__init__` function. +inline PyObject *make_new_instance(PyTypeObject *type) { +#if defined(PYPY_VERSION) + // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first + // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it. + ssize_t instance_size = static_cast(sizeof(instance)); + if (type->tp_basicsize < instance_size) { + type->tp_basicsize = instance_size; + } +#endif + PyObject *self = type->tp_alloc(type, 0); + auto *inst = reinterpret_cast(self); + // Allocate the value/holder internals: + inst->allocate_layout(); + + return self; +} + +/// Instance creation function for all pybind11 types. It only allocates space for the +/// C++ object, but doesn't call the constructor -- an `__init__` function must do that. +extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) { + return make_new_instance(type); +} + +/// An `__init__` function constructs the C++ object. Users should provide at least one +/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the +/// following default function will be used which simply throws an exception. +extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) { + PyTypeObject *type = Py_TYPE(self); + std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!"; + set_error(PyExc_TypeError, msg.c_str()); + return -1; +} + +inline void add_patient(PyObject *nurse, PyObject *patient) { + auto *instance = reinterpret_cast(nurse); + instance->has_patients = true; + Py_INCREF(patient); + + with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); }); +} + +inline void clear_patients(PyObject *self) { + auto *instance = reinterpret_cast(self); + std::vector patients; + + with_internals([&](internals &internals) { + auto pos = internals.patients.find(self); + + if (pos == internals.patients.end()) { + pybind11_fail( + "FATAL: Internal consistency check failed: Invalid clear_patients() call."); + } + + // Clearing the patients can cause more Python code to run, which + // can invalidate the iterator. Extract the vector of patients + // from the unordered_map first. + patients = std::move(pos->second); + internals.patients.erase(pos); + }); + + instance->has_patients = false; + for (PyObject *&patient : patients) { + Py_CLEAR(patient); + } +} + +/// Clears all internal data from the instance and removes it from registered instances in +/// preparation for deallocation. +inline void clear_instance(PyObject *self) { + auto *instance = reinterpret_cast(self); + + // Deallocate any values/holders, if present: + for (auto &v_h : values_and_holders(instance)) { + if (v_h) { + + // We have to deregister before we call dealloc because, for virtual MI types, we still + // need to be able to get the parent pointers. + if (v_h.instance_registered() + && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) { + pybind11_fail( + "pybind11_object_dealloc(): Tried to deallocate unregistered instance!"); + } + + if (instance->owned || v_h.holder_constructed()) { + v_h.type->dealloc(v_h); + } + } + } + // Deallocate the value/holder layout internals: + instance->deallocate_layout(); + + if (instance->weakrefs) { + PyObject_ClearWeakRefs(self); + } + + PyObject **dict_ptr = _PyObject_GetDictPtr(self); + if (dict_ptr) { + Py_CLEAR(*dict_ptr); + } + + if (instance->has_patients) { + clear_patients(self); + } +} + +/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc` +/// to destroy the C++ object itself, while the rest is Python bookkeeping. +extern "C" inline void pybind11_object_dealloc(PyObject *self) { + auto *type = Py_TYPE(self); + + // If this is a GC tracked object, untrack it first + // Note that the track call is implicitly done by the + // default tp_alloc, which we never override. + if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) { + PyObject_GC_UnTrack(self); + } + + clear_instance(self); + + type->tp_free(self); + +#if PY_VERSION_HEX < 0x03080000 + // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called + // as part of a derived type's dealloc, in which case we're not allowed to decref + // the type here. For cross-module compatibility, we shouldn't compare directly + // with `pybind11_object_dealloc`, but with the common one stashed in internals. + auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base; + if (type->tp_dealloc == pybind11_object_type->tp_dealloc) + Py_DECREF(type); +#else + // This was not needed before Python 3.8 (Python issue 35810) + // https://github.com/pybind/pybind11/issues/1946 + Py_DECREF(type); +#endif +} + +std::string error_string(); + +/** Create the type which can be used as a common base for all classes. This is + needed in order to satisfy Python's requirements for multiple inheritance. + Return value: New reference. */ +inline PyObject *make_object_base_type(PyTypeObject *metaclass) { + constexpr auto *name = "pybind11_object"; + auto name_obj = reinterpret_steal(PYBIND11_FROM_STRING(name)); + + /* Danger zone: from now (and until PyType_Ready), make sure to + issue no Python C API calls which could potentially invoke the + garbage collector (the GC will call type_traverse(), which will in + turn find the newly constructed type in an invalid state) */ + auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0); + if (!heap_type) { + pybind11_fail("make_object_base_type(): error allocating type!"); + } + + heap_type->ht_name = name_obj.inc_ref().ptr(); +#ifdef PYBIND11_BUILTIN_QUALNAME + heap_type->ht_qualname = name_obj.inc_ref().ptr(); +#endif + + auto *type = &heap_type->ht_type; + type->tp_name = name; + type->tp_base = type_incref(&PyBaseObject_Type); + type->tp_basicsize = static_cast(sizeof(instance)); + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE; + + type->tp_new = pybind11_object_new; + type->tp_init = pybind11_object_init; + type->tp_dealloc = pybind11_object_dealloc; + + /* Support weak references (needed for the keep_alive feature) */ + type->tp_weaklistoffset = offsetof(instance, weakrefs); + + if (PyType_Ready(type) < 0) { + pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string()); + } + + setattr((PyObject *) type, "__module__", str("pybind11_builtins")); + PYBIND11_SET_OLDPY_QUALNAME(type, name_obj); + + assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)); + return (PyObject *) heap_type; +} + +/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`. +extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) { +#if PY_VERSION_HEX >= 0x030D0000 + PyObject_VisitManagedDict(self, visit, arg); +#else + PyObject *&dict = *_PyObject_GetDictPtr(self); + Py_VISIT(dict); +#endif +// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse +#if PY_VERSION_HEX >= 0x03090000 + Py_VISIT(Py_TYPE(self)); +#endif + return 0; +} + +/// dynamic_attr: Allow the GC to clear the dictionary. +extern "C" inline int pybind11_clear(PyObject *self) { +#if PY_VERSION_HEX >= 0x030D0000 + PyObject_ClearManagedDict(self); +#else + PyObject *&dict = *_PyObject_GetDictPtr(self); + Py_CLEAR(dict); +#endif + return 0; +} + +/// Give instances of this type a `__dict__` and opt into garbage collection. +inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) { + auto *type = &heap_type->ht_type; + type->tp_flags |= Py_TPFLAGS_HAVE_GC; +#if PY_VERSION_HEX < 0x030B0000 + type->tp_dictoffset = type->tp_basicsize; // place dict at the end + type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it +#else + type->tp_flags |= Py_TPFLAGS_MANAGED_DICT; +#endif + type->tp_traverse = pybind11_traverse; + type->tp_clear = pybind11_clear; + + static PyGetSetDef getset[] + = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr}, + {nullptr, nullptr, nullptr, nullptr, nullptr}}; + type->tp_getset = getset; +} + +/// buffer_protocol: Fill in the view as specified by flags. +extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) { + // Look for a `get_buffer` implementation in this type's info or any bases (following MRO). + type_info *tinfo = nullptr; + for (auto type : reinterpret_borrow(Py_TYPE(obj)->tp_mro)) { + tinfo = get_type_info((PyTypeObject *) type.ptr()); + if (tinfo && tinfo->get_buffer) { + break; + } + } + if (view == nullptr || !tinfo || !tinfo->get_buffer) { + if (view) { + view->obj = nullptr; + } + set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error"); + return -1; + } + std::memset(view, 0, sizeof(Py_buffer)); + buffer_info *info = nullptr; + try { + info = tinfo->get_buffer(obj, tinfo->get_buffer_data); + } catch (...) { + try_translate_exceptions(); + raise_from(PyExc_BufferError, "Error getting buffer"); + return -1; + } + if (info == nullptr) { + pybind11_fail("FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr."); + } + + if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) { + delete info; + // view->obj = nullptr; // Was just memset to 0, so not necessary + set_error(PyExc_BufferError, "Writable buffer requested for readonly storage"); + return -1; + } + view->obj = obj; + view->ndim = 1; + view->internal = info; + view->buf = info->ptr; + view->itemsize = info->itemsize; + view->len = view->itemsize; + for (auto s : info->shape) { + view->len *= s; + } + view->readonly = static_cast(info->readonly); + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { + view->format = const_cast(info->format.c_str()); + } + if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { + view->ndim = (int) info->ndim; + view->strides = info->strides.data(); + view->shape = info->shape.data(); + } + Py_INCREF(view->obj); + return 0; +} + +/// buffer_protocol: Release the resources of the buffer. +extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) { + delete (buffer_info *) view->internal; +} + +/// Give this type a buffer interface. +inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) { + heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer; + + heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer; + heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer; +} + +/** Create a brand new Python type according to the `type_record` specification. + Return value: New reference. */ +inline PyObject *make_new_python_type(const type_record &rec) { + auto name = reinterpret_steal(PYBIND11_FROM_STRING(rec.name)); + + auto qualname = name; + if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) { + qualname = reinterpret_steal( + PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr())); + } + + object module_; + if (rec.scope) { + if (hasattr(rec.scope, "__module__")) { + module_ = rec.scope.attr("__module__"); + } else if (hasattr(rec.scope, "__name__")) { + module_ = rec.scope.attr("__name__"); + } + } + + const auto *full_name = c_str( +#if !defined(PYPY_VERSION) + module_ ? str(module_).cast() + "." + rec.name : +#endif + rec.name); + + char *tp_doc = nullptr; + if (rec.doc && options::show_user_defined_docstrings()) { + /* Allocate memory for docstring (Python will free this later on) */ + size_t size = std::strlen(rec.doc) + 1; +#if PY_VERSION_HEX >= 0x030D0000 + tp_doc = (char *) PyMem_MALLOC(size); +#else + tp_doc = (char *) PyObject_MALLOC(size); +#endif + std::memcpy((void *) tp_doc, rec.doc, size); + } + + auto &internals = get_internals(); + auto bases = tuple(rec.bases); + auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr(); + + /* Danger zone: from now (and until PyType_Ready), make sure to + issue no Python C API calls which could potentially invoke the + garbage collector (the GC will call type_traverse(), which will in + turn find the newly constructed type in an invalid state) */ + auto *metaclass + = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass; + + auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0); + if (!heap_type) { + pybind11_fail(std::string(rec.name) + ": Unable to create type object!"); + } + + heap_type->ht_name = name.release().ptr(); +#ifdef PYBIND11_BUILTIN_QUALNAME + heap_type->ht_qualname = qualname.inc_ref().ptr(); +#endif + + auto *type = &heap_type->ht_type; + type->tp_name = full_name; + type->tp_doc = tp_doc; + type->tp_base = type_incref((PyTypeObject *) base); + type->tp_basicsize = static_cast(sizeof(instance)); + if (!bases.empty()) { + type->tp_bases = bases.release().ptr(); + } + + /* Don't inherit base __init__ */ + type->tp_init = pybind11_object_init; + + /* Supported protocols */ + type->tp_as_number = &heap_type->as_number; + type->tp_as_sequence = &heap_type->as_sequence; + type->tp_as_mapping = &heap_type->as_mapping; + type->tp_as_async = &heap_type->as_async; + + /* Flags */ + type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE; + if (!rec.is_final) { + type->tp_flags |= Py_TPFLAGS_BASETYPE; + } + + if (rec.dynamic_attr) { + enable_dynamic_attributes(heap_type); + } + + if (rec.buffer_protocol) { + enable_buffer_protocol(heap_type); + } + + if (rec.custom_type_setup_callback) { + rec.custom_type_setup_callback(heap_type); + } + + if (PyType_Ready(type) < 0) { + pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string()); + } + + assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)); + + /* Register type with the parent scope */ + if (rec.scope) { + setattr(rec.scope, rec.name, (PyObject *) type); + } else { + Py_INCREF(type); // Keep it alive forever (reference leak) + } + + if (module_) { // Needed by pydoc + setattr((PyObject *) type, "__module__", module_); + } + + PYBIND11_SET_OLDPY_QUALNAME(type, qualname); + + return (PyObject *) type; +} + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/shared/package-files/06/0640d1e3e3a6c9d3f0c5df43e38de780e38904adbf87f9b1e8608366cf552414/special_psi.h b/shared/package-files/06/0640d1e3e3a6c9d3f0c5df43e38de780e38904adbf87f9b1e8608366cf552414/special_psi.h new file mode 100644 index 0000000000000000000000000000000000000000..b1429c8b5008e85d1369abd40de136e4c523e768 --- /dev/null +++ b/shared/package-files/06/0640d1e3e3a6c9d3f0c5df43e38de780e38904adbf87f9b1e8608366cf552414/special_psi.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_psi(Tensor self) -> Tensor +inline at::Tensor special_psi(const at::Tensor & self) { + return at::_ops::special_psi::call(self); +} + +// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_psi_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_psi_out::call(self, out); +} +// aten::special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_psi_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_psi_out::call(self, out); +} + +} diff --git a/shared/package-files/06/0643726a604b3902e52b2ea607805274f46300a3f5821679c5cc900e452cfbfb/_conversions.py b/shared/package-files/06/0643726a604b3902e52b2ea607805274f46300a3f5821679c5cc900e452cfbfb/_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..8092469741981efce3c53f424e3b2fb83a38e8eb --- /dev/null +++ b/shared/package-files/06/0643726a604b3902e52b2ea607805274f46300a3f5821679c5cc900e452cfbfb/_conversions.py @@ -0,0 +1,119 @@ +# mypy: allow-untyped-defs +import torch +import torch._prims_common as utils + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition +from torch._prims_common import TensorLikeType +from torch._prims_common.wrappers import out_wrapper +from torch._refs import _broadcast_shapes + + +# Data conversion references. +# +# Note: this module breaks the usual _refs to torch naming scheme where +# _refs.foo.bar is a ref for torch.foo.bar. The following definitions are not +# part of _refs/__init__.py to avoid name clashes with Python builtin types +# (like int). + +__all__ = [ + # dtypes + "bfloat16", + "bool", + "byte", + "cdouble", + "cfloat", + "chalf", + "char", + "double", + "float", + "half", + "int", + "long", + "short", + # misc + "complex", + "polar", +] + + +def _make_conversion_method(name: str, dtype: torch.dtype): + def fn( + self: TensorLikeType, memory_format: torch.memory_format = torch.preserve_format + ) -> TensorLikeType: + return self.to(dtype, memory_format=memory_format) # type: ignore[call-overload] + + fn.__name__ = name + return fn + + +bfloat16 = _make_conversion_method("bfloat16", torch.bfloat16) + +bool = _make_conversion_method("bool", torch.bool) + +byte = _make_conversion_method("byte", torch.uint8) + +cdouble = _make_conversion_method("cdouble", torch.cdouble) + +cfloat = _make_conversion_method("cfloat", torch.cfloat) + +chalf = _make_conversion_method("chalf", torch.complex32) + +char = _make_conversion_method("char", torch.int8) + +double = _make_conversion_method("double", torch.double) + +float = _make_conversion_method("float", torch.float) + +half = _make_conversion_method("half", torch.half) + +int = _make_conversion_method("int", torch.int) + +long = _make_conversion_method("long", torch.long) + +short = _make_conversion_method("short", torch.short) + + +@register_decomposition(torch._ops.ops.aten.complex) +# Note: complex has type promotion tests disabled due to different semantics. +# exact_dtype is for compat with complex_check_dtype from core. +@out_wrapper(exact_dtype=True) +def complex(real: TensorLikeType, imag: TensorLikeType) -> TensorLikeType: + allowed_dtypes = (torch.float32, torch.float64, torch.float16) + torch._check( + real.dtype in allowed_dtypes and imag.dtype in allowed_dtypes, + lambda: ( + f"Expected both inputs to be Half, Float or Double tensors but got " + f"{real.dtype} and {imag.dtype}" + ), + ) + torch._check( + real.dtype == imag.dtype, + lambda: ( + f"Expected object of scalar type {real.dtype} but got " + f"scalar type {imag.dtype} for second argument" + ), + ) + result_dtype = utils.corresponding_complex_dtype(real.dtype) # type: ignore[arg-type] + common_shape = _broadcast_shapes(real.shape, imag.shape) + result = real.new_empty( + common_shape, + dtype=result_dtype, + layout=real.layout, + device=real.device, + # pin_memory=real.is_pinned(), # NYI + ) + result.real = real + result.imag = imag + return result + + +@register_decomposition(torch._ops.ops.aten.polar) +# Note: polar has type promotion tests disabled due to different semantics. +# exact_dtype is for compat with complex_check_dtype from core. +@out_wrapper(exact_dtype=True) +def polar(abs: TensorLikeType, angle: TensorLikeType) -> TensorLikeType: + result = torch.complex(abs, angle) + result.real = abs * torch.cos(angle) + result.imag = abs * torch.sin(angle) + return result diff --git a/shared/package-files/06/064806f0fa6a1892d858494e44382d2c9cf27e2b986a7140610f9bbd331692e8/hts_prog_cc_warnings.m4 b/shared/package-files/06/064806f0fa6a1892d858494e44382d2c9cf27e2b986a7140610f9bbd331692e8/hts_prog_cc_warnings.m4 new file mode 100644 index 0000000000000000000000000000000000000000..f2aed93284c4926a2059a6599753451396c306d2 --- /dev/null +++ b/shared/package-files/06/064806f0fa6a1892d858494e44382d2c9cf27e2b986a7140610f9bbd331692e8/hts_prog_cc_warnings.m4 @@ -0,0 +1,208 @@ +dnl @synopsis HTS_PROG_CC_WARNINGS([ANSI]) +dnl +dnl Derived from +dnl http://ac-archive.sourceforge.net/ac-archive/vl_prog_cc_warnings.html +dnl +dnl Enables a reasonable set of warnings for the C compiler. +dnl Optionally, if the first argument is nonempty, turns on flags which +dnl enforce and/or enable proper ANSI C if such are known with the +dnl compiler used. +dnl +dnl Currently this macro knows about GCC, Solaris C compiler, Digital +dnl Unix C compiler, C for AIX Compiler, HP-UX C compiler, IRIX C +dnl compiler, NEC SX-5 (Super-UX 10) C compiler, and Cray J90 (Unicos +dnl 10.0.0.8) C compiler. +dnl +dnl @category C +dnl @author Ville Laurikari +dnl Updated by Rob Davies for HTSlib +dnl @license AllPermissive +dnl Copying and distribution of this file, with or without modification, +dnl are permitted in any medium without royalty provided the copyright notice +dnl and this notice are preserved. Users of this software should generally +dnl follow the principles of the MIT License including its disclaimer. +dnl Original Copyright (c) Ville Laurikari 2002 +dnl Modifications Copyright (c) Genome Research Limited 2015,2017 + +AC_DEFUN([HTS_PROG_CC_WARNINGS], [ + AC_ARG_ENABLE([warnings], + [AS_HELP_STRING([--disable-warnings], [turn off compiler warnings])], + [], + [enable_warnings=yes]) + + AS_IF([test "x$enable_warnings" != xno],[ + AC_REQUIRE([AC_PROG_GREP]) + + ansi="$1" + AS_IF([test "x$ansi" = "x"], + [msg="for C compiler warning flags"], + [msg="for C compiler warning and ANSI conformance flags"]) + + AC_MSG_CHECKING($msg) + AC_CACHE_VAL(hts_cv_prog_cc_warnings, [dnl + hts_cv_prog_cc_warnings="" + AS_IF([test "x$CC" != "x"],[ + cat > conftest.c < /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-Wall"], + [hts_cv_prog_cc_warnings="-Wall -ansi -pedantic"]) + ], + # Sun Studio or Solaris C compiler + ["$CC" -V 2>&1 | $GREP -i -E "WorkShop|Sun C" > /dev/null 2>&1 && + "$CC" -c -v -Xc conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-v"], + [hts_cv_prog_cc_warnings="-v -Xc"]) + ], + # Digital Unix C compiler + ["$CC" -V 2>&1 | $GREP -i "Digital UNIX Compiler" > /dev/null 2>&1 && + "$CC" -c -verbose -w0 -warnprotos -std1 conftest.c > /dev/null 2>&1 && + test -f conftest.o], [dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-verbose -w0 -warnprotos"], + [hts_cv_prog_cc_warnings="-verbose -w0 -warnprotos -std1"]) + ], + # C for AIX Compiler + ["$CC" 2>&1 | $GREP -i "C for AIX Compiler" > /dev/null 2>&1 && + "$CC" -c -qlanglvl=ansi -qinfo=all conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd"], + [hts_cv_prog_cc_warnings="-qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd -qlanglvl=ansi"]) + ], + # IRIX C compiler + ["$CC" -version 2>&1 | $GREP -i "MIPSpro Compilers" > /dev/null 2>&1 && + "$CC" -c -fullwarn -ansi -ansiE conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-fullwarn"], + [hts_cv_prog_cc_warnings="-fullwarn -ansi -ansiE"]) + ], + # HP-UX C compiler + [what "$CC" 2>&1 | $GREP -i "HP C Compiler" > /dev/null 2>&1 && + "$CC" -c -Aa +w1 conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="+w1"], + [hts_cv_prog_cc_warnings="+w1 -Aa"]) + ], + # The NEC SX series (Super-UX 10) C compiler + ["$CC" -V 2>&1 | $GREP "/SX" > /dev/null 2>&1 && + "$CC" -c -pvctl[,]fullmsg -Xc conftest.c > /dev/null 2>&1 && + test -f conftest.o],[ + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-pvctl[,]fullmsg"], + [hts_cv_prog_cc_warnings="-pvctl[,]fullmsg -Xc"]) + ], + # The Cray C compiler (Unicos) + ["$CC" -V 2>&1 | $GREP -i "Cray" > /dev/null 2>&1 && + "$CC" -c -h msglevel_2 conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + AS_IF([test "x$ansi" = "x"], + [hts_cv_prog_cc_warnings="-h#msglevel_2"], + [hts_cv_prog_cc_warnings="-h#msglevel_2,conform"]) + ], + # The Tiny C Compiler + ["$CC" -v 2>&1 | $GREP "tcc version" > /dev/null && + "$CC" -Wall -c conftest.c > /dev/null 2>&1 && + test -f conftest.o],[dnl + hts_cv_prog_cc_warnings="-Wall" + ]) + rm -f conftest.* + ]) + ]) + + AS_IF([test "x$hts_cv_prog_cc_warnings" != "x"],[ +dnl Print result, with underscores as spaces +ac_arg_result=`echo "$hts_cv_prog_cc_warnings" | tr '#' ' '` +AC_MSG_RESULT($ac_arg_result) + +dnl Add options to CFLAGS only if they are not already present +ac_arg_needed="" +for ac_arg in $hts_cv_prog_cc_warnings +do + ac_arg_sp=`echo "$ac_arg" | tr '#' ' '` + AS_CASE([" $CFLAGS "], +[*" $ac_arg_sp "*], [], +[ac_arg_needed="$ac_arg_all $ac_arg_sp"]) +done +CFLAGS="$ac_arg_needed $CFLAGS"],[dnl + AC_MSG_RESULT(unknown) + ]) + ]) +])dnl HTS_PROG_CC_WARNINGS + +# SYNOPSIS +# +# HTS_PROG_CC_WERROR(FLAGS_VAR) +# +# Set FLAGS_VAR to the flags needed to make the C compiler treat warnings +# as errors. + +AC_DEFUN([HTS_PROG_CC_WERROR], [ + AC_ARG_ENABLE([werror], + [AS_HELP_STRING([--enable-werror], [change warnings into errors, where supported])], + [], + [enable_werror=no]) + + AS_IF([test "x$enable_werror" != xno],[ + AC_MSG_CHECKING([for C compiler flags to error on warnings]) + AC_CACHE_VAL(hts_cv_prog_cc_werror, [dnl + hts_cv_prog_cc_werror="" + AS_IF([test "x$CC" != "x"],[ + cat > conftest.c < /dev/null 2>&1 && + test -f conftest.o],[hts_cv_prog_cc_werror="-Werror"], + # Sun Studio or Solaris C compiler + ["$CC" -V 2>&1 | $GREP -i -E "WorkShop|Sun C" > /dev/null 2>&1 && + "$CC" -c -errwarn=%all conftest.c > /dev/null 2>&1 && + test -f conftest.o],[hts_cv_prog_cc_werror="-errwarn=%all"], + # The Tiny C Compiler + ["$CC" -v 2>&1 | $GREP "tcc version" > /dev/null && + "$CC" -Wall -c conftest.c > /dev/null 2>&1 && + test -f conftest.o],[hts_cv_prog_cc_werror="-Werror"] + dnl TODO: Add more compilers + ) + rm -f conftest.* + ]) + ]) + AS_IF([test "x$hts_cv_prog_cc_werror" != x],[ + AC_MSG_RESULT($hts_cv_prog_cc_werror) + AS_IF([test "x$1" != x],[eval AS_TR_SH([$1])="$hts_cv_prog_cc_werror"]) + ],[dnl + AC_MSG_RESULT(unknown) + ]) + ]) +])dnl HTS_PROG_CC_WERROR diff --git a/shared/package-files/06/0656ef4ad12ca223866c0f39a4ff61c3cb9f657aea8b18d38c6683ea6b0826e1/test_append.py b/shared/package-files/06/0656ef4ad12ca223866c0f39a4ff61c3cb9f657aea8b18d38c6683ea6b0826e1/test_append.py new file mode 100644 index 0000000000000000000000000000000000000000..00a81a4f1f385d044a21b987cfa9c5d2c65d1f0d --- /dev/null +++ b/shared/package-files/06/0656ef4ad12ca223866c0f39a4ff61c3cb9f657aea8b18d38c6683ea6b0826e1/test_append.py @@ -0,0 +1,986 @@ +import datetime +from datetime import timedelta +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import ( + DataFrame, + Index, + Series, + _testing as tm, + concat, + date_range, + read_hdf, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_store, +) + +pytestmark = pytest.mark.single_cpu + +tables = pytest.importorskip("tables") + + +@pytest.mark.filterwarnings("ignore::tables.NaturalNameWarning") +def test_append(setup_path): + with ensure_clean_store(setup_path) as store: + # this is allowed by almost always don't want to do it + # tables.NaturalNameWarning): + df = DataFrame( + np.random.default_rng(2).standard_normal((20, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=20, freq="B"), + ) + _maybe_remove(store, "df1") + store.append("df1", df[:10]) + store.append("df1", df[10:]) + tm.assert_frame_equal(store["df1"], df) + + _maybe_remove(store, "df2") + store.put("df2", df[:10], format="table") + store.append("df2", df[10:]) + tm.assert_frame_equal(store["df2"], df) + + _maybe_remove(store, "df3") + store.append("/df3", df[:10]) + store.append("/df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) + + # this is allowed by almost always don't want to do it + # tables.NaturalNameWarning + _maybe_remove(store, "/df3 foo") + store.append("/df3 foo", df[:10]) + store.append("/df3 foo", df[10:]) + tm.assert_frame_equal(store["df3 foo"], df) + + # dtype issues - mizxed type in a single object column + df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) + df["mixed_column"] = "testing" + df.loc[2, "mixed_column"] = np.nan + _maybe_remove(store, "df") + store.append("df", df) + tm.assert_frame_equal(store["df"], df) + + # uints - test storage of uints + uint_data = DataFrame( + { + "u08": Series( + np.random.default_rng(2).integers(0, high=255, size=5), + dtype=np.uint8, + ), + "u16": Series( + np.random.default_rng(2).integers(0, high=65535, size=5), + dtype=np.uint16, + ), + "u32": Series( + np.random.default_rng(2).integers(0, high=2**30, size=5), + dtype=np.uint32, + ), + "u64": Series( + [2**58, 2**59, 2**60, 2**61, 2**62], + dtype=np.uint64, + ), + }, + index=np.arange(5), + ) + _maybe_remove(store, "uints") + store.append("uints", uint_data) + tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) + + # uints - test storage of uints in indexable columns + _maybe_remove(store, "uints") + # 64-bit indices not yet supported + store.append("uints", uint_data, data_columns=["u08", "u16", "u32"]) + tm.assert_frame_equal(store["uints"], uint_data, check_index_type=True) + + +def test_append_series(setup_path): + with ensure_clean_store(setup_path) as store: + # basic + ss = Series(range(20), dtype=np.float64, index=[f"i_{i}" for i in range(20)]) + ts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + ns = Series(np.arange(100)) + + store.append("ss", ss) + result = store["ss"] + tm.assert_series_equal(result, ss) + assert result.name is None + + store.append("ts", ts) + result = store["ts"] + tm.assert_series_equal(result, ts) + assert result.name is None + + ns.name = "foo" + store.append("ns", ns) + result = store["ns"] + tm.assert_series_equal(result, ns) + assert result.name == ns.name + + # select on the values + expected = ns[ns > 60] + result = store.select("ns", "foo>60") + tm.assert_series_equal(result, expected) + + # select on the index and values + expected = ns[(ns > 70) & (ns.index < 90)] + result = store.select("ns", "foo>70 and index<90") + tm.assert_series_equal(result, expected, check_index_type=True) + + # multi-index + mi = DataFrame(np.random.default_rng(2).standard_normal((5, 1)), columns=["A"]) + mi["B"] = np.arange(len(mi)) + mi["C"] = "foo" + mi.loc[3:5, "C"] = "bar" + mi.set_index(["C", "B"], inplace=True) + s = mi.stack(future_stack=True) + s.index = s.index.droplevel(2) + store.append("mi", s) + tm.assert_series_equal(store["mi"], s, check_index_type=True) + + +def test_append_some_nans(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame( + { + "A": Series(np.random.default_rng(2).standard_normal(20)).astype( + "int32" + ), + "A1": np.random.default_rng(2).standard_normal(20), + "A2": np.random.default_rng(2).standard_normal(20), + "B": "foo", + "C": "bar", + "D": Timestamp("2001-01-01").as_unit("ns"), + "E": Timestamp("2001-01-02").as_unit("ns"), + }, + index=np.arange(20), + ) + # some nans + _maybe_remove(store, "df1") + df.loc[0:15, ["A1", "B", "D", "E"]] = np.nan + store.append("df1", df[:10]) + store.append("df1", df[10:]) + tm.assert_frame_equal(store["df1"], df, check_index_type=True) + + # first column + df1 = df.copy() + df1["A1"] = np.nan + _maybe_remove(store, "df1") + store.append("df1", df1[:10]) + store.append("df1", df1[10:]) + tm.assert_frame_equal(store["df1"], df1, check_index_type=True) + + # 2nd column + df2 = df.copy() + df2["A2"] = np.nan + _maybe_remove(store, "df2") + store.append("df2", df2[:10]) + store.append("df2", df2[10:]) + tm.assert_frame_equal(store["df2"], df2, check_index_type=True) + + # datetimes + df3 = df.copy() + df3["E"] = np.nan + _maybe_remove(store, "df3") + store.append("df3", df3[:10]) + store.append("df3", df3[10:]) + tm.assert_frame_equal(store["df3"], df3, check_index_type=True) + + +def test_append_all_nans(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame( + { + "A1": np.random.default_rng(2).standard_normal(20), + "A2": np.random.default_rng(2).standard_normal(20), + }, + index=np.arange(20), + ) + df.loc[0:15, :] = np.nan + + # nan some entire rows (dropna=True) + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df[-4:], check_index_type=True) + + # nan some entire rows (dropna=False) + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df, check_index_type=True) + + # tests the option io.hdf.dropna_table + with pd.option_context("io.hdf.dropna_table", False): + _maybe_remove(store, "df3") + store.append("df3", df[:10]) + store.append("df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) + + with pd.option_context("io.hdf.dropna_table", True): + _maybe_remove(store, "df4") + store.append("df4", df[:10]) + store.append("df4", df[10:]) + tm.assert_frame_equal(store["df4"], df[-4:]) + + # nan some entire rows (string are still written!) + df = DataFrame( + { + "A1": np.random.default_rng(2).standard_normal(20), + "A2": np.random.default_rng(2).standard_normal(20), + "B": "foo", + "C": "bar", + }, + index=np.arange(20), + ) + + df.loc[0:15, :] = np.nan + + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df, check_index_type=True) + + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df, check_index_type=True) + + # nan some entire rows (but since we have dates they are still + # written!) + df = DataFrame( + { + "A1": np.random.default_rng(2).standard_normal(20), + "A2": np.random.default_rng(2).standard_normal(20), + "B": "foo", + "C": "bar", + "D": Timestamp("2001-01-01").as_unit("ns"), + "E": Timestamp("2001-01-02").as_unit("ns"), + }, + index=np.arange(20), + ) + + df.loc[0:15, :] = np.nan + + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df, check_index_type=True) + + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df, check_index_type=True) + + +def test_append_frame_column_oriented(setup_path): + with ensure_clean_store(setup_path) as store: + # column oriented + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df.index = df.index._with_freq(None) # freq doesn't round-trip + + _maybe_remove(store, "df1") + store.append("df1", df.iloc[:, :2], axes=["columns"]) + store.append("df1", df.iloc[:, 2:]) + tm.assert_frame_equal(store["df1"], df) + + result = store.select("df1", "columns=A") + expected = df.reindex(columns=["A"]) + tm.assert_frame_equal(expected, result) + + # selection on the non-indexable + result = store.select("df1", ("columns=A", "index=df.index[0:4]")) + expected = df.reindex(columns=["A"], index=df.index[0:4]) + tm.assert_frame_equal(expected, result) + + # this isn't supported + msg = re.escape( + "passing a filterable condition to a non-table indexer " + "[Filter: Not Initialized]" + ) + with pytest.raises(TypeError, match=msg): + store.select("df1", "columns=A and index>df.index[4]") + + +def test_append_with_different_block_ordering(setup_path): + # GH 4096; using same frames, but different block orderings + with ensure_clean_store(setup_path) as store: + for i in range(10): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB") + ) + df["index"] = range(10) + df["index"] += i * 10 + df["int64"] = Series([1] * len(df), dtype="int64") + df["int16"] = Series([1] * len(df), dtype="int16") + + if i % 2 == 0: + del df["int64"] + df["int64"] = Series([1] * len(df), dtype="int64") + if i % 3 == 0: + a = df.pop("A") + df["A"] = a + + df.set_index("index", inplace=True) + + store.append("df", df) + + # test a different ordering but with more fields (like invalid + # combinations) + with ensure_clean_store(setup_path) as store: + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), + columns=list("AB"), + dtype="float64", + ) + df["int64"] = Series([1] * len(df), dtype="int64") + df["int16"] = Series([1] * len(df), dtype="int16") + store.append("df", df) + + # store additional fields in different blocks + df["int16_2"] = Series([1] * len(df), dtype="int16") + msg = re.escape( + "cannot match existing table structure for [int16] on appending data" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # store multiple additional fields in different blocks + df["float_3"] = Series([1.0] * len(df), dtype="float64") + msg = re.escape( + "cannot match existing table structure for [A,B] on appending data" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + +def test_append_with_strings(setup_path): + with ensure_clean_store(setup_path) as store: + + def check_col(key, name, size): + assert ( + getattr(store.get_storer(key).table.description, name).itemsize == size + ) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big", df) + tm.assert_frame_equal(store.select("df_big"), df) + check_col("df_big", "values_block_1", 15) + + # appending smaller string ok + df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]]) + store.append("df_big", df2) + expected = concat([df, df2]) + tm.assert_frame_equal(store.select("df_big"), expected) + check_col("df_big", "values_block_1", 15) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big2", df, min_itemsize={"values": 50}) + tm.assert_frame_equal(store.select("df_big2"), df) + check_col("df_big2", "values_block_1", 50) + + # bigger string on next append + store.append("df_new", df) + df_new = DataFrame([[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]]) + msg = ( + r"Trying to store a string with len \[26\] in " + r"\[values_block_1\] column but\n" + r"this column has a limit of \[15\]!\n" + "Consider using min_itemsize to preset the sizes on these " + "columns" + ) + with pytest.raises(ValueError, match=msg): + store.append("df_new", df_new) + + # min_itemsize on Series index (GH 11412) + df = DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "D": date_range("20130101", periods=5), + } + ).set_index("C") + store.append("ss", df["B"], min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss"), df["B"]) + + # same as above, with data_columns=True + store.append("ss2", df["B"], data_columns=True, min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss2"), df["B"]) + + # min_itemsize in index without appending (GH 10381) + store.put("ss3", df, format="table", min_itemsize={"index": 6}) + # just make sure there is a longer string: + df2 = df.copy().reset_index().assign(C="longer").set_index("C") + store.append("ss3", df2) + tm.assert_frame_equal(store.select("ss3"), concat([df, df2])) + + # same as above, with a Series + store.put("ss4", df["B"], format="table", min_itemsize={"index": 6}) + store.append("ss4", df2["B"]) + tm.assert_series_equal(store.select("ss4"), concat([df["B"], df2["B"]])) + + # with nans + _maybe_remove(store, "df") + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df["string"] = "foo" + df.loc[df.index[1:4], "string"] = np.nan + df["string2"] = "bar" + df.loc[df.index[4:8], "string2"] = np.nan + df["string3"] = "bah" + df.loc[df.index[1:], "string3"] = np.nan + store.append("df", df) + result = store.select("df") + tm.assert_frame_equal(result, df) + + with ensure_clean_store(setup_path) as store: + df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) + + # a min_itemsize that creates a data_column + _maybe_remove(store, "df") + store.append("df", df, min_itemsize={"A": 200}) + check_col("df", "A", 200) + assert store.get_storer("df").data_columns == ["A"] + + # a min_itemsize that creates a data_column2 + _maybe_remove(store, "df") + store.append("df", df, data_columns=["B"], min_itemsize={"A": 200}) + check_col("df", "A", 200) + assert store.get_storer("df").data_columns == ["B", "A"] + + # a min_itemsize that creates a data_column2 + _maybe_remove(store, "df") + store.append("df", df, data_columns=["B"], min_itemsize={"values": 200}) + check_col("df", "B", 200) + check_col("df", "values_block_0", 200) + assert store.get_storer("df").data_columns == ["B"] + + # infer the .typ on subsequent appends + _maybe_remove(store, "df") + store.append("df", df[:5], min_itemsize=200) + store.append("df", df[5:], min_itemsize=200) + tm.assert_frame_equal(store["df"], df) + + # invalid min_itemsize keys + df = DataFrame(["foo", "foo", "foo", "barh", "barh", "barh"], columns=["A"]) + _maybe_remove(store, "df") + msg = re.escape( + "min_itemsize has the key [foo] which is not an axis or data_column" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df, min_itemsize={"foo": 20, "foobar": 20}) + + +def test_append_with_empty_string(setup_path): + with ensure_clean_store(setup_path) as store: + # with all empty strings (GH 12242) + df = DataFrame({"x": ["a", "b", "c", "d", "e", "f", ""]}) + store.append("df", df[:-1], min_itemsize={"x": 1}) + store.append("df", df[-1:], min_itemsize={"x": 1}) + tm.assert_frame_equal(store.select("df"), df) + + +def test_append_with_data_columns(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df.iloc[0, df.columns.get_loc("B")] = 1.0 + _maybe_remove(store, "df") + store.append("df", df[:2], data_columns=["B"]) + store.append("df", df[2:]) + tm.assert_frame_equal(store["df"], df) + + # check that we have indices created + assert store._handle.root.df.table.cols.index.is_indexed is True + assert store._handle.root.df.table.cols.B.is_indexed is True + + # data column searching + result = store.select("df", "B>0") + expected = df[df.B > 0] + tm.assert_frame_equal(result, expected) + + # data column searching (with an indexable and a data_columns) + result = store.select("df", "B>0 and index>df.index[3]") + df_new = df.reindex(index=df.index[4:]) + expected = df_new[df_new.B > 0] + tm.assert_frame_equal(result, expected) + + # data column selection with a string data_column + df_new = df.copy() + df_new["string"] = "foo" + df_new.loc[df_new.index[1:4], "string"] = np.nan + df_new.loc[df_new.index[5:6], "string"] = "bar" + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"]) + result = store.select("df", "string='foo'") + expected = df_new[df_new.string == "foo"] + tm.assert_frame_equal(result, expected) + + # using min_itemsize and a data column + def check_col(key, name, size): + assert ( + getattr(store.get_storer(key).table.description, name).itemsize == size + ) + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize={"string": 30}) + check_col("df", "string", 30) + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize=30) + check_col("df", "string", 30) + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize={"values": 30}) + check_col("df", "string", 30) + + with ensure_clean_store(setup_path) as store: + df_new["string2"] = "foobarbah" + df_new["string_block1"] = "foobarbah1" + df_new["string_block2"] = "foobarbah2" + _maybe_remove(store, "df") + store.append( + "df", + df_new, + data_columns=["string", "string2"], + min_itemsize={"string": 30, "string2": 40, "values": 50}, + ) + check_col("df", "string", 30) + check_col("df", "string2", 40) + check_col("df", "values_block_1", 50) + + with ensure_clean_store(setup_path) as store: + # multiple data columns + df_new = df.copy() + df_new.iloc[0, df_new.columns.get_loc("A")] = 1.0 + df_new.iloc[0, df_new.columns.get_loc("B")] = -1.0 + df_new["string"] = "foo" + + sl = df_new.columns.get_loc("string") + df_new.iloc[1:4, sl] = np.nan + df_new.iloc[5:6, sl] = "bar" + + df_new["string2"] = "foo" + sl = df_new.columns.get_loc("string2") + df_new.iloc[2:5, sl] = np.nan + df_new.iloc[7:8, sl] = "bar" + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["A", "B", "string", "string2"]) + result = store.select("df", "string='foo' and string2='foo' and A>0 and B<0") + expected = df_new[ + (df_new.string == "foo") + & (df_new.string2 == "foo") + & (df_new.A > 0) + & (df_new.B < 0) + ] + tm.assert_frame_equal(result, expected, check_freq=False) + # FIXME: 2020-05-07 freq check randomly fails in the CI + + # yield an empty frame + result = store.select("df", "string='foo' and string2='cool'") + expected = df_new[(df_new.string == "foo") & (df_new.string2 == "cool")] + tm.assert_frame_equal(result, expected) + + with ensure_clean_store(setup_path) as store: + # doc example + df_dc = df.copy() + df_dc["string"] = "foo" + df_dc.loc[df_dc.index[4:6], "string"] = np.nan + df_dc.loc[df_dc.index[7:9], "string"] = "bar" + df_dc["string2"] = "cool" + df_dc["datetime"] = Timestamp("20010102").as_unit("ns") + df_dc.loc[df_dc.index[3:5], ["A", "B", "datetime"]] = np.nan + + _maybe_remove(store, "df_dc") + store.append( + "df_dc", df_dc, data_columns=["B", "C", "string", "string2", "datetime"] + ) + result = store.select("df_dc", "B>0") + + expected = df_dc[df_dc.B > 0] + tm.assert_frame_equal(result, expected) + + result = store.select("df_dc", ["B > 0", "C > 0", "string == foo"]) + expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] + tm.assert_frame_equal(result, expected, check_freq=False) + # FIXME: 2020-12-07 intermittent build failures here with freq of + # None instead of BDay(4) + + with ensure_clean_store(setup_path) as store: + # doc example part 2 + + index = date_range("1/1/2000", periods=8) + df_dc = DataFrame( + np.random.default_rng(2).standard_normal((8, 3)), + index=index, + columns=["A", "B", "C"], + ) + df_dc["string"] = "foo" + df_dc.loc[df_dc.index[4:6], "string"] = np.nan + df_dc.loc[df_dc.index[7:9], "string"] = "bar" + df_dc[["B", "C"]] = df_dc[["B", "C"]].abs() + df_dc["string2"] = "cool" + + # on-disk operations + store.append("df_dc", df_dc, data_columns=["B", "C", "string", "string2"]) + + result = store.select("df_dc", "B>0") + expected = df_dc[df_dc.B > 0] + tm.assert_frame_equal(result, expected) + + result = store.select("df_dc", ["B > 0", "C > 0", 'string == "foo"']) + expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] + tm.assert_frame_equal(result, expected) + + +def test_append_hierarchical(tmp_path, setup_path, multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + df.columns.name = None + + with ensure_clean_store(setup_path) as store: + store.append("mi", df) + result = store.select("mi") + tm.assert_frame_equal(result, df) + + # GH 3748 + result = store.select("mi", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + path = tmp_path / "test.hdf" + df.to_hdf(path, key="df", format="table") + result = read_hdf(path, "df", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + +def test_append_misc(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + store.append("df", df, chunksize=1) + result = store.select("df") + tm.assert_frame_equal(result, df) + + store.append("df1", df, expectedrows=10) + result = store.select("df1") + tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize("chunksize", [10, 200, 1000]) +def test_append_misc_chunksize(setup_path, chunksize): + # more chunksize in append tests + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + df["string"] = "foo" + df["float322"] = 1.0 + df["float322"] = df["float322"].astype("float32") + df["bool"] = df["float322"] > 0 + df["time1"] = Timestamp("20130101").as_unit("ns") + df["time2"] = Timestamp("20130102").as_unit("ns") + with ensure_clean_store(setup_path, mode="w") as store: + store.append("obj", df, chunksize=chunksize) + result = store.select("obj") + tm.assert_frame_equal(result, df) + + +def test_append_misc_empty_frame(setup_path): + # empty frame, GH4273 + with ensure_clean_store(setup_path) as store: + # 0 len + df_empty = DataFrame(columns=list("ABC")) + store.append("df", df_empty) + with pytest.raises(KeyError, match="'No object named df in the file'"): + store.select("df") + + # repeated append of 0/non-zero frames + df = DataFrame(np.random.default_rng(2).random((10, 3)), columns=list("ABC")) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + store.append("df", df_empty) + tm.assert_frame_equal(store.select("df"), df) + + # store + df = DataFrame(columns=list("ABC")) + store.put("df2", df) + tm.assert_frame_equal(store.select("df2"), df) + + +# TODO(ArrayManager) currently we rely on falling back to BlockManager, but +# the conversion from AM->BM converts the invalid object dtype column into +# a datetime64 column no longer raising an error +@td.skip_array_manager_not_yet_implemented +def test_append_raise(setup_path): + with ensure_clean_store(setup_path) as store: + # test append with invalid input to get good error messages + + # list in column + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + df["invalid"] = [["a"]] * len(df) + assert df.dtypes["invalid"] == np.object_ + msg = re.escape( + """Cannot serialize the column [invalid] +because its data contents are not [string] but [mixed] object dtype""" + ) + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # multiple invalid columns + df["invalid2"] = [["a"]] * len(df) + df["invalid3"] = [["a"]] * len(df) + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # datetime with embedded nans as object + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + s = Series(datetime.datetime(2001, 1, 2), index=df.index) + s = s.astype(object) + s[0:5] = np.nan + df["invalid"] = s + assert df.dtypes["invalid"] == np.object_ + msg = "too many timezones in this block, create separate data columns" + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # directly ndarray + msg = "value must be None, Series, or DataFrame" + with pytest.raises(TypeError, match=msg): + store.append("df", np.arange(10)) + + # series directly + msg = re.escape( + "cannot properly create the storer for: " + "[group->df,value->]" + ) + with pytest.raises(TypeError, match=msg): + store.append("df", Series(np.arange(10))) + + # appending an incompatible table + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + store.append("df", df) + + df["foo"] = "foo" + msg = re.escape( + "invalid combination of [non_index_axes] on appending data " + "[(1, ['A', 'B', 'C', 'D', 'foo'])] vs current table " + "[(1, ['A', 'B', 'C', 'D'])]" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # incompatible type (GH 41897) + _maybe_remove(store, "df") + df["foo"] = Timestamp("20130101") + store.append("df", df) + df["foo"] = "bar" + msg = re.escape( + "invalid combination of [values_axes] on appending data " + "[name->values_block_1,cname->values_block_1," + "dtype->bytes24,kind->string,shape->(1, 30)] " + "vs current table " + "[name->values_block_1,cname->values_block_1," + "dtype->datetime64[s],kind->datetime64[s],shape->None]" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + +def test_append_with_timedelta(setup_path): + # GH 3577 + # append timedelta + + ts = Timestamp("20130101").as_unit("ns") + df = DataFrame( + { + "A": ts, + "B": [ts + timedelta(days=i, seconds=10) for i in range(10)], + } + ) + df["C"] = df["A"] - df["B"] + df.loc[3:5, "C"] = np.nan + + with ensure_clean_store(setup_path) as store: + # table + _maybe_remove(store, "df") + store.append("df", df, data_columns=True) + result = store.select("df") + tm.assert_frame_equal(result, df) + + result = store.select("df", where="C<100000") + tm.assert_frame_equal(result, df) + + result = store.select("df", where="C0", "B>0"], selector="df1" + ) + expected = df[(df.A > 0) & (df.B > 0)] + tm.assert_frame_equal(result, expected) + + +def test_append_to_multiple_dropna(setup_path): + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ).rename(columns="{}_2".format) + df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan + df = concat([df1, df2], axis=1) + + with ensure_clean_store(setup_path) as store: + # dropna=True should guarantee rows are synchronized + store.append_to_multiple( + {"df1": ["A", "B"], "df2": None}, df, selector="df1", dropna=True + ) + result = store.select_as_multiple(["df1", "df2"]) + expected = df.dropna() + tm.assert_frame_equal(result, expected, check_index_type=True) + tm.assert_index_equal(store.select("df1").index, store.select("df2").index) + + +def test_append_to_multiple_dropna_false(setup_path): + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy().rename(columns="{}_2".format) + df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan + df = concat([df1, df2], axis=1) + + with ensure_clean_store(setup_path) as store, pd.option_context( + "io.hdf.dropna_table", True + ): + # dropna=False shouldn't synchronize row indexes + store.append_to_multiple( + {"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False + ) + + msg = "all tables must have exactly the same nrows!" + with pytest.raises(ValueError, match=msg): + store.select_as_multiple(["df1a", "df2a"]) + + assert not store.select("df1a").index.equals(store.select("df2a").index) + + +def test_append_to_multiple_min_itemsize(setup_path): + # GH 11238 + df = DataFrame( + { + "IX": np.arange(1, 21), + "Num": np.arange(1, 21), + "BigNum": np.arange(1, 21) * 88, + "Str": ["a" for _ in range(20)], + "LongStr": ["abcde" for _ in range(20)], + } + ) + expected = df.iloc[[0]] + + with ensure_clean_store(setup_path) as store: + store.append_to_multiple( + { + "index": ["IX"], + "nums": ["Num", "BigNum"], + "strs": ["Str", "LongStr"], + }, + df.iloc[[0]], + "index", + min_itemsize={"Str": 10, "LongStr": 100, "Num": 2}, + ) + result = store.select_as_multiple(["index", "nums", "strs"]) + tm.assert_frame_equal(result, expected, check_index_type=True) diff --git a/shared/package-files/06/0658667d3f0dbbc4c37b070863e78497ab0a8638c0a569170c0ea05a299b24bd/_cufft_get_plan_cache_size_native.h b/shared/package-files/06/0658667d3f0dbbc4c37b070863e78497ab0a8638c0a569170c0ea05a299b24bd/_cufft_get_plan_cache_size_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ebc1be64f5de8027d5dac1531237890bb423415b --- /dev/null +++ b/shared/package-files/06/0658667d3f0dbbc4c37b070863e78497ab0a8638c0a569170c0ea05a299b24bd/_cufft_get_plan_cache_size_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API int64_t _cufft_get_plan_cache_size(at::DeviceIndex device_index); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/0658a0f240042117853b765ed9cd0f9c923a3515f6172e7e8142e55adc3cd608/sun.cpython-311.pyc b/shared/package-files/06/0658a0f240042117853b765ed9cd0f9c923a3515f6172e7e8142e55adc3cd608/sun.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49bb0da5e50206cb877fe0fa9764a126295ec685 Binary files /dev/null and b/shared/package-files/06/0658a0f240042117853b765ed9cd0f9c923a3515f6172e7e8142e55adc3cd608/sun.cpython-311.pyc differ diff --git a/shared/package-files/06/0659cc7cb2a37602ddcdf6a45e4b03fbaf4fb3b36721ee782c862ec4b0359d1d/test_storage_v3.py b/shared/package-files/06/0659cc7cb2a37602ddcdf6a45e4b03fbaf4fb3b36721ee782c862ec4b0359d1d/test_storage_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..47e19d911befc075251fd4476707afa2f465e555 --- /dev/null +++ b/shared/package-files/06/0659cc7cb2a37602ddcdf6a45e4b03fbaf4fb3b36721ee782c862ec4b0359d1d/test_storage_v3.py @@ -0,0 +1,695 @@ +import array +import atexit +import copy +import inspect +import os +import tempfile +import warnings + +import numpy as np +import pytest + +import zarr +from zarr._storage.store import ( + _get_hierarchy_metadata, + assert_zarr_v3_api_available, + v3_api_available, + StorageTransformer, +) +from zarr._storage.v3_storage_transformers import ShardingStorageTransformer, v3_sharding_available +from zarr.core import Array +from zarr.meta import _default_entry_point_metadata_v3 +from zarr.storage import ( + atexit_rmglob, + atexit_rmtree, + data_root, + default_compressor, + getsize, + init_array, + meta_root, + normalize_store_arg, +) +from zarr._storage.v3 import ( + ABSStoreV3, + ConsolidatedMetadataStoreV3, + DBMStoreV3, + DirectoryStoreV3, + FSStoreV3, + KVStore, + KVStoreV3, + LMDBStoreV3, + LRUStoreCacheV3, + MemoryStoreV3, + MongoDBStoreV3, + RedisStoreV3, + SQLiteStoreV3, + StoreV3, + ZipStoreV3, +) +from zarr.tests.util import CountingDictV3, have_fsspec, skip_test_env_var, mktemp + +# pytest will fail to run if the following fixtures aren't imported here +from .test_storage import StoreTests as _StoreTests +from .test_storage import TestABSStore as _TestABSStore +from .test_storage import TestConsolidatedMetadataStore as _TestConsolidatedMetadataStore +from .test_storage import TestDBMStore as _TestDBMStore +from .test_storage import TestDBMStoreDumb as _TestDBMStoreDumb +from .test_storage import TestDBMStoreGnu as _TestDBMStoreGnu +from .test_storage import TestDBMStoreNDBM as _TestDBMStoreNDBM +from .test_storage import TestDirectoryStore as _TestDirectoryStore +from .test_storage import TestFSStore as _TestFSStore +from .test_storage import TestLMDBStore as _TestLMDBStore +from .test_storage import TestLRUStoreCache as _TestLRUStoreCache +from .test_storage import TestMemoryStore as _TestMemoryStore +from .test_storage import TestSQLiteStore as _TestSQLiteStore +from .test_storage import TestSQLiteStoreInMemory as _TestSQLiteStoreInMemory +from .test_storage import TestZipStore as _TestZipStore +from .test_storage import dimension_separator_fixture, s3, skip_if_nested_chunks # noqa + + +pytestmark = pytest.mark.skipif(not v3_api_available, reason="v3 api is not available") + + +@pytest.fixture( + params=[ + (None, "/"), + (".", "."), + ("/", "/"), + ] +) +def dimension_separator_fixture_v3(request): + return request.param + + +class DummyStore: + # contains all methods expected of Mutable Mapping + + def keys(self): + """keys""" + + def values(self): + """values""" + + def get(self, value, default=None): + """get""" + + def __setitem__(self, key, value): + """__setitem__""" + + def __getitem__(self, key): + """__getitem__""" + + def __delitem__(self, key): + """__delitem__""" + + def __contains__(self, key): + """__contains__""" + + +class InvalidDummyStore: + # does not contain expected methods of a MutableMapping + + def keys(self): + """keys""" + + +class DummyStorageTransfomer(StorageTransformer): + TEST_CONSTANT = "test1234" + + extension_uri = "https://purl.org/zarr/spec/storage_transformers/dummy/1.0" + valid_types = ["dummy_type"] + + def __init__(self, _type, test_value) -> None: + super().__init__(_type) + assert test_value == self.TEST_CONSTANT + self.test_value = test_value + + +def test_ensure_store_v3(): + class InvalidStore: + pass + + with pytest.raises(ValueError): + StoreV3._ensure_store(InvalidStore()) + + # cannot initialize with a store from a different Zarr version + with pytest.raises(ValueError): + StoreV3._ensure_store(KVStore(dict())) + + assert StoreV3._ensure_store(None) is None + + # class with all methods of a MutableMapping will become a KVStoreV3 + assert isinstance(StoreV3._ensure_store(DummyStore), KVStoreV3) + + with pytest.raises(ValueError): + # does not have the methods expected of a MutableMapping + StoreV3._ensure_store(InvalidDummyStore) + + +def test_valid_key(): + store = KVStoreV3(dict) + + # only ascii keys are valid + assert not store._valid_key(5) + assert not store._valid_key(2.8) + + for key in store._valid_key_characters: + assert store._valid_key(key) + + # other characters not in store._valid_key_characters are not allowed + assert not store._valid_key("*") + assert not store._valid_key("~") + assert not store._valid_key("^") + + +def test_validate_key(): + store = KVStoreV3(dict) + + # zarr.json is a valid key + store._validate_key("zarr.json") + # but other keys not starting with meta/ or data/ are not + with pytest.raises(ValueError): + store._validate_key("zar.json") + + # valid ascii keys + for valid in [ + meta_root + "arr1.array.json", + data_root + "arr1.array.json", + meta_root + "subfolder/item_1-0.group.json", + ]: + store._validate_key(valid) + # but otherwise valid keys cannot end in / + with pytest.raises(ValueError): + assert store._validate_key(valid + "/") + + for invalid in [0, "*", "~", "^", "&"]: + with pytest.raises(ValueError): + store._validate_key(invalid) + + +class StoreV3Tests(_StoreTests): + version = 3 + root = meta_root + + def test_getsize(self): + # TODO: determine proper getsize() behavior for v3 + # Currently returns the combined size of entries under + # meta/root/path and data/root/path. + # Any path not under meta/root/ or data/root/ (including zarr.json) + # returns size 0. + + store = self.create_store() + if isinstance(store, dict) or hasattr(store, "getsize"): + assert 0 == getsize(store, "zarr.json") + store[meta_root + "foo/a"] = b"x" + assert 1 == getsize(store) + assert 1 == getsize(store, "foo") + store[meta_root + "foo/b"] = b"x" + assert 2 == getsize(store, "foo") + assert 1 == getsize(store, "foo/b") + store[meta_root + "bar/a"] = b"yy" + assert 2 == getsize(store, "bar") + store[data_root + "bar/a"] = b"zzz" + assert 5 == getsize(store, "bar") + store[data_root + "baz/a"] = b"zzz" + assert 3 == getsize(store, "baz") + assert 10 == getsize(store) + store[data_root + "quux"] = array.array("B", b"zzzz") + assert 14 == getsize(store) + assert 4 == getsize(store, "quux") + store[data_root + "spong"] = np.frombuffer(b"zzzzz", dtype="u1") + assert 19 == getsize(store) + assert 5 == getsize(store, "spong") + store.close() + + def test_init_array(self, dimension_separator_fixture_v3): + pass_dim_sep, want_dim_sep = dimension_separator_fixture_v3 + + store = self.create_store() + path = "arr1" + transformer = DummyStorageTransfomer( + "dummy_type", test_value=DummyStorageTransfomer.TEST_CONSTANT + ) + init_array( + store, + path=path, + shape=1000, + chunks=100, + dimension_separator=pass_dim_sep, + storage_transformers=[transformer], + ) + + # check metadata + mkey = meta_root + path + ".array.json" + assert mkey in store + meta = store._metadata_class.decode_array_metadata(store[mkey]) + assert (1000,) == meta["shape"] + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype(None) == meta["data_type"] + assert default_compressor == meta["compressor"] + assert meta["fill_value"] is None + # Missing MUST be assumed to be "/" + assert meta["chunk_grid"]["separator"] is want_dim_sep + assert len(meta["storage_transformers"]) == 1 + assert isinstance(meta["storage_transformers"][0], DummyStorageTransfomer) + assert meta["storage_transformers"][0].test_value == DummyStorageTransfomer.TEST_CONSTANT + store.close() + + def test_list_prefix(self): + store = self.create_store() + path = "arr1" + init_array(store, path=path, shape=1000, chunks=100) + + expected = [meta_root + "arr1.array.json", "zarr.json"] + assert sorted(store.list_prefix("")) == expected + + expected = [meta_root + "arr1.array.json"] + assert sorted(store.list_prefix(meta_root.rstrip("/"))) == expected + + # cannot start prefix with '/' + with pytest.raises(ValueError): + store.list_prefix(prefix="/" + meta_root.rstrip("/")) + + def test_equal(self): + store = self.create_store() + assert store == store + + def test_rename_nonexisting(self): + store = self.create_store() + if store.is_erasable(): + with pytest.raises(ValueError): + store.rename("a", "b") + else: + with pytest.raises(NotImplementedError): + store.rename("a", "b") + + def test_get_partial_values(self): + store = self.create_store() + assert store.supports_efficient_get_partial_values in [True, False] + store[data_root + "foo"] = b"abcdefg" + store[data_root + "baz"] = b"z" + assert [b"a"] == store.get_partial_values([(data_root + "foo", (0, 1))]) + assert [ + b"d", + b"b", + b"z", + b"abc", + b"defg", + b"defg", + b"g", + b"ef", + ] == store.get_partial_values( + [ + (data_root + "foo", (3, 1)), + (data_root + "foo", (1, 1)), + (data_root + "baz", (0, 1)), + (data_root + "foo", (0, 3)), + (data_root + "foo", (3, 4)), + (data_root + "foo", (3, None)), + (data_root + "foo", (-1, None)), + (data_root + "foo", (-3, 2)), + ] + ) + + def test_set_partial_values(self): + store = self.create_store() + store.supports_efficient_set_partial_values() + store[data_root + "foo"] = b"abcdefg" + store.set_partial_values([(data_root + "foo", 0, b"hey")]) + assert store[data_root + "foo"] == b"heydefg" + + store.set_partial_values([(data_root + "baz", 0, b"z")]) + assert store[data_root + "baz"] == b"z" + store.set_partial_values( + [ + (data_root + "foo", 1, b"oo"), + (data_root + "baz", 1, b"zzz"), + (data_root + "baz", 4, b"aaaa"), + (data_root + "foo", 6, b"done"), + ] + ) + assert store[data_root + "foo"] == b"hoodefdone" + assert store[data_root + "baz"] == b"zzzzaaaa" + store.set_partial_values( + [ + (data_root + "foo", -2, b"NE"), + (data_root + "baz", -5, b"q"), + ] + ) + assert store[data_root + "foo"] == b"hoodefdoNE" + assert store[data_root + "baz"] == b"zzzq" + + +class TestMappingStoreV3(StoreV3Tests): + def create_store(self, **kwargs): + return KVStoreV3(dict()) + + def test_set_invalid_content(self): + # Generic mappings support non-buffer types + pass + + +class TestMemoryStoreV3(_TestMemoryStore, StoreV3Tests): + def create_store(self, **kwargs): + skip_if_nested_chunks(**kwargs) + return MemoryStoreV3(**kwargs) + + +class TestDirectoryStoreV3(_TestDirectoryStore, StoreV3Tests): + def create_store(self, normalize_keys=False, **kwargs): + # For v3, don't have to skip if nested. + # skip_if_nested_chunks(**kwargs) + + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = DirectoryStoreV3(path, normalize_keys=normalize_keys, **kwargs) + return store + + def test_rename_nonexisting(self): + store = self.create_store() + with pytest.raises(FileNotFoundError): + store.rename(meta_root + "a", meta_root + "b") + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestFSStoreV3(_TestFSStore, StoreV3Tests): + def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs): + if path is None: + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + + store = FSStoreV3( + path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs + ) + return store + + def test_init_array(self): + store = self.create_store() + path = "arr1" + init_array(store, path=path, shape=1000, chunks=100) + + # check metadata + mkey = meta_root + path + ".array.json" + assert mkey in store + meta = store._metadata_class.decode_array_metadata(store[mkey]) + assert (1000,) == meta["shape"] + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype(None) == meta["data_type"] + assert meta["chunk_grid"]["separator"] == "/" + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestFSStoreV3WithKeySeparator(StoreV3Tests): + def create_store(self, normalize_keys=False, key_separator=".", **kwargs): + # Since the user is passing key_separator, that will take priority. + skip_if_nested_chunks(**kwargs) + + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + return FSStoreV3(path, normalize_keys=normalize_keys, key_separator=key_separator) + + +# TODO: enable once N5StoreV3 has been implemented +# @pytest.mark.skipif(True, reason="N5StoreV3 not yet fully implemented") +# class TestN5StoreV3(_TestN5Store, TestDirectoryStoreV3, StoreV3Tests): + + +class TestZipStoreV3(_TestZipStore, StoreV3Tests): + ZipStoreClass = ZipStoreV3 + + def create_store(self, **kwargs): + path = mktemp(suffix=".zip") + atexit.register(os.remove, path) + store = ZipStoreV3(path, mode="w", **kwargs) + return store + + +class TestDBMStoreV3(_TestDBMStore, StoreV3Tests): + def create_store(self, dimension_separator=None): + path = mktemp(suffix=".anydbm") + atexit.register(atexit_rmglob, path + "*") + # create store using default dbm implementation + store = DBMStoreV3(path, flag="n", dimension_separator=dimension_separator) + return store + + +class TestDBMStoreV3Dumb(_TestDBMStoreDumb, StoreV3Tests): + def create_store(self, **kwargs): + path = mktemp(suffix=".dumbdbm") + atexit.register(atexit_rmglob, path + "*") + + import dbm.dumb as dumbdbm + + store = DBMStoreV3(path, flag="n", open=dumbdbm.open, **kwargs) + return store + + +class TestDBMStoreV3Gnu(_TestDBMStoreGnu, StoreV3Tests): + def create_store(self, **kwargs): + gdbm = pytest.importorskip("dbm.gnu") + path = mktemp(suffix=".gdbm") # pragma: no cover + atexit.register(os.remove, path) # pragma: no cover + store = DBMStoreV3( + path, flag="n", open=gdbm.open, write_lock=False, **kwargs + ) # pragma: no cover + return store # pragma: no cover + + +class TestDBMStoreV3NDBM(_TestDBMStoreNDBM, StoreV3Tests): + def create_store(self, **kwargs): + ndbm = pytest.importorskip("dbm.ndbm") + path = mktemp(suffix=".ndbm") # pragma: no cover + atexit.register(atexit_rmglob, path + "*") # pragma: no cover + store = DBMStoreV3(path, flag="n", open=ndbm.open, **kwargs) # pragma: no cover + return store # pragma: no cover + + +class TestLMDBStoreV3(_TestLMDBStore, StoreV3Tests): + def create_store(self, **kwargs): + pytest.importorskip("lmdb") + path = mktemp(suffix=".lmdb") + atexit.register(atexit_rmtree, path) + buffers = True + store = LMDBStoreV3(path, buffers=buffers, **kwargs) + return store + + +class TestSQLiteStoreV3(_TestSQLiteStore, StoreV3Tests): + def create_store(self, **kwargs): + pytest.importorskip("sqlite3") + path = mktemp(suffix=".db") + atexit.register(atexit_rmtree, path) + store = SQLiteStoreV3(path, **kwargs) + return store + + +class TestSQLiteStoreV3InMemory(_TestSQLiteStoreInMemory, StoreV3Tests): + def create_store(self, **kwargs): + pytest.importorskip("sqlite3") + store = SQLiteStoreV3(":memory:", **kwargs) + return store + + +@skip_test_env_var("ZARR_TEST_MONGO") +class TestMongoDBStoreV3(StoreV3Tests): + def create_store(self, **kwargs): + pytest.importorskip("pymongo") + store = MongoDBStoreV3( + host="127.0.0.1", database="zarr_tests", collection="zarr_tests", **kwargs + ) + # start with an empty store + store.clear() + return store + + +@skip_test_env_var("ZARR_TEST_REDIS") +class TestRedisStoreV3(StoreV3Tests): + def create_store(self, **kwargs): + # TODO: this is the default host for Redis on Travis, + # we probably want to generalize this though + pytest.importorskip("redis") + store = RedisStoreV3(host="localhost", port=6379, **kwargs) + # start with an empty store + store.clear() + return store + + +@pytest.mark.skipif(not v3_sharding_available, reason="sharding is disabled") +class TestStorageTransformerV3(TestMappingStoreV3): + def create_store(self, **kwargs): + inner_store = super().create_store(**kwargs) + dummy_transformer = DummyStorageTransfomer( + "dummy_type", test_value=DummyStorageTransfomer.TEST_CONSTANT + ) + sharding_transformer = ShardingStorageTransformer( + "indexed", + chunks_per_shard=2, + ) + path = "bla" + init_array( + inner_store, + path=path, + shape=1000, + chunks=100, + dimension_separator=".", + storage_transformers=[dummy_transformer, sharding_transformer], + ) + store = Array(store=inner_store, path=path).chunk_store + store.erase_prefix("data/root/bla/") + store.clear() + return store + + def test_method_forwarding(self): + store = self.create_store() + inner_store = store.inner_store.inner_store + assert store.list() == inner_store.list() + assert store.list_dir(data_root) == inner_store.list_dir(data_root) + + assert store.is_readable() + assert store.is_writeable() + assert store.is_listable() + inner_store._readable = False + inner_store._writeable = False + inner_store._listable = False + assert not store.is_readable() + assert not store.is_writeable() + assert not store.is_listable() + + +class TestLRUStoreCacheV3(_TestLRUStoreCache, StoreV3Tests): + CountingClass = CountingDictV3 + LRUStoreClass = LRUStoreCacheV3 + + +@skip_test_env_var("ZARR_TEST_ABS") +class TestABSStoreV3(_TestABSStore, StoreV3Tests): + ABSStoreClass = ABSStoreV3 + + +def test_normalize_store_arg_v3(tmpdir): + fn = tmpdir.join("store.zip") + store = normalize_store_arg(str(fn), zarr_version=3, mode="w") + assert isinstance(store, ZipStoreV3) + assert "zarr.json" in store + + # can't pass storage_options to non-fsspec store + with pytest.raises(ValueError): + normalize_store_arg(str(fn), zarr_version=3, mode="w", storage_options={"some": "kwargs"}) + + if have_fsspec: + import fsspec + + path = tempfile.mkdtemp() + store = normalize_store_arg("file://" + path, zarr_version=3, mode="w") + assert isinstance(store, FSStoreV3) + assert "zarr.json" in store + + store = normalize_store_arg(fsspec.get_mapper("file://" + path), zarr_version=3) + assert isinstance(store, FSStoreV3) + + # regression for https://github.com/zarr-developers/zarr-python/issues/1382 + # contents of zarr.json are not important for this test + out = {"version": 1, "refs": {"zarr.json": "{...}"}} + store = normalize_store_arg( + "reference://", storage_options={"fo": out, "remote_protocol": "memory"}, zarr_version=3 + ) + assert isinstance(store, FSStoreV3) + + fn = tmpdir.join("store.n5") + with pytest.raises(NotImplementedError): + normalize_store_arg(str(fn), zarr_version=3, mode="w") + + # error on zarr_version=3 with a v2 store + with pytest.raises(ValueError): + normalize_store_arg(KVStore(dict()), zarr_version=3, mode="w") + + # error on zarr_version=2 with a v3 store + with pytest.raises(ValueError): + normalize_store_arg(KVStoreV3(dict()), zarr_version=2, mode="w") + + +class TestConsolidatedMetadataStoreV3(_TestConsolidatedMetadataStore): + version = 3 + ConsolidatedMetadataClass = ConsolidatedMetadataStoreV3 + + @property + def metadata_key(self): + return meta_root + "consolidated/.zmetadata" + + def test_bad_store_version(self): + with pytest.raises(ValueError): + self.ConsolidatedMetadataClass(KVStore(dict())) + + +def test_get_hierarchy_metadata(): + store = KVStoreV3({}) + + # error raised if 'jarr.json' is not in the store + with pytest.raises(ValueError): + _get_hierarchy_metadata(store) + + store["zarr.json"] = _default_entry_point_metadata_v3 + assert _get_hierarchy_metadata(store) == _default_entry_point_metadata_v3 + + # ValueError if only a subset of keys are present + store["zarr.json"] = {"zarr_format": "https://purl.org/zarr/spec/protocol/core/3.0"} + with pytest.raises(ValueError): + _get_hierarchy_metadata(store) + + # ValueError if any unexpected keys are present + extra_metadata = copy.copy(_default_entry_point_metadata_v3) + extra_metadata["extra_key"] = "value" + store["zarr.json"] = extra_metadata + with pytest.raises(ValueError): + _get_hierarchy_metadata(store) + + +def test_top_level_imports(): + for store_name in [ + "ABSStoreV3", + "DBMStoreV3", + "KVStoreV3", + "DirectoryStoreV3", + "LMDBStoreV3", + "LRUStoreCacheV3", + "MemoryStoreV3", + "MongoDBStoreV3", + "RedisStoreV3", + "SQLiteStoreV3", + "ZipStoreV3", + ]: + if v3_api_available: + assert hasattr(zarr, store_name) # pragma: no cover + else: + assert not hasattr(zarr, store_name) # pragma: no cover + + +def test_assert_zarr_v3_api_available_warns_once(): + import zarr._storage.store + + zarr._storage.store._has_warned_about_v3 = False + warnings.resetwarnings() + with pytest.warns() as record: + assert_zarr_v3_api_available() + assert_zarr_v3_api_available() + assert len(record) == 1 + assert "The experimental Zarr V3 implementation" in str(record[0].message) + + +def _get_public_and_dunder_methods(some_class): + return set( + name + for name, _ in inspect.getmembers(some_class, predicate=inspect.isfunction) + if not name.startswith("_") or name.startswith("__") + ) + + +def test_storage_transformer_interface(): + store_v3_methods = _get_public_and_dunder_methods(StoreV3) + store_v3_methods.discard("__init__") + # Note, getitems() isn't mandatory when get_partial_values() is available + store_v3_methods.discard("getitems") + storage_transformer_methods = _get_public_and_dunder_methods(StorageTransformer) + storage_transformer_methods.discard("__init__") + storage_transformer_methods.discard("get_config") + assert storage_transformer_methods == store_v3_methods diff --git a/shared/package-files/06/065d8910135bd7c972b1ef8e31d68379fb41709f772ad4d0789acde63d6144e3/multidigraph.cpython-311.pyc b/shared/package-files/06/065d8910135bd7c972b1ef8e31d68379fb41709f772ad4d0789acde63d6144e3/multidigraph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f81531402c225a8e1656557f47d4ef5757724c2d Binary files /dev/null and b/shared/package-files/06/065d8910135bd7c972b1ef8e31d68379fb41709f772ad4d0789acde63d6144e3/multidigraph.cpython-311.pyc differ diff --git a/shared/package-files/06/065ec0fe53e8ba84bbb8af049f26eabed317a7a59ab48ed4f3d390c0c79c5956/test_analytics.py b/shared/package-files/06/065ec0fe53e8ba84bbb8af049f26eabed317a7a59ab48ed4f3d390c0c79c5956/test_analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c53fbc4637ed60dc92914f6e2ca74d5e0bdfe9 --- /dev/null +++ b/shared/package-files/06/065ec0fe53e8ba84bbb8af049f26eabed317a7a59ab48ed4f3d390c0c79c5956/test_analytics.py @@ -0,0 +1,349 @@ +import re +import sys + +import numpy as np +import pytest + +from pandas.compat import PYPY + +from pandas import ( + Categorical, + CategoricalDtype, + DataFrame, + Index, + NaT, + Series, + date_range, +) +import pandas._testing as tm +from pandas.api.types import is_scalar + + +class TestCategoricalAnalytics: + @pytest.mark.parametrize("aggregation", ["min", "max"]) + def test_min_max_not_ordered_raises(self, aggregation): + # unordered cats have no min/max + cat = Categorical(["a", "b", "c", "d"], ordered=False) + msg = f"Categorical is not ordered for operation {aggregation}" + agg_func = getattr(cat, aggregation) + + with pytest.raises(TypeError, match=msg): + agg_func() + + ufunc = np.minimum if aggregation == "min" else np.maximum + with pytest.raises(TypeError, match=msg): + ufunc.reduce(cat) + + def test_min_max_ordered(self, index_or_series_or_array): + cat = Categorical(["a", "b", "c", "d"], ordered=True) + obj = index_or_series_or_array(cat) + _min = obj.min() + _max = obj.max() + assert _min == "a" + assert _max == "d" + + assert np.minimum.reduce(obj) == "a" + assert np.maximum.reduce(obj) == "d" + # TODO: raises if we pass axis=0 (on Index and Categorical, not Series) + + cat = Categorical( + ["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True + ) + obj = index_or_series_or_array(cat) + _min = obj.min() + _max = obj.max() + assert _min == "d" + assert _max == "a" + assert np.minimum.reduce(obj) == "d" + assert np.maximum.reduce(obj) == "a" + + def test_min_max_reduce(self): + # GH52788 + cat = Categorical(["a", "b", "c", "d"], ordered=True) + df = DataFrame(cat) + + result_max = df.agg("max") + expected_max = Series(Categorical(["d"], dtype=cat.dtype)) + tm.assert_series_equal(result_max, expected_max) + + result_min = df.agg("min") + expected_min = Series(Categorical(["a"], dtype=cat.dtype)) + tm.assert_series_equal(result_min, expected_min) + + @pytest.mark.parametrize( + "categories,expected", + [ + (list("ABC"), np.nan), + ([1, 2, 3], np.nan), + pytest.param( + Series(date_range("2020-01-01", periods=3), dtype="category"), + NaT, + marks=pytest.mark.xfail( + reason="https://github.com/pandas-dev/pandas/issues/29962" + ), + ), + ], + ) + @pytest.mark.parametrize("aggregation", ["min", "max"]) + def test_min_max_ordered_empty(self, categories, expected, aggregation): + # GH 30227 + cat = Categorical([], categories=categories, ordered=True) + + agg_func = getattr(cat, aggregation) + result = agg_func() + assert result is expected + + @pytest.mark.parametrize( + "values, categories", + [(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])], + ) + @pytest.mark.parametrize("skipna", [True, False]) + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_with_nan(self, values, categories, function, skipna): + # GH 25303 + cat = Categorical(values, categories=categories, ordered=True) + result = getattr(cat, function)(skipna=skipna) + + if skipna is False: + assert result is np.nan + else: + expected = categories[0] if function == "min" else categories[2] + assert result == expected + + @pytest.mark.parametrize("function", ["min", "max"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_only_nan(self, function, skipna): + # https://github.com/pandas-dev/pandas/issues/33450 + cat = Categorical([np.nan], categories=[1, 2], ordered=True) + result = getattr(cat, function)(skipna=skipna) + assert result is np.nan + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_numeric_only_min_max_raises(self, method): + # GH 25303 + cat = Categorical( + [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True + ) + with pytest.raises(TypeError, match=".* got an unexpected keyword"): + getattr(cat, method)(numeric_only=True) + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_numpy_min_max_raises(self, method): + cat = Categorical(["a", "b", "c", "b"], ordered=False) + msg = ( + f"Categorical is not ordered for operation {method}\n" + "you can use .as_ordered() to change the Categorical to an ordered one" + ) + method = getattr(np, method) + with pytest.raises(TypeError, match=re.escape(msg)): + method(cat) + + @pytest.mark.parametrize("kwarg", ["axis", "out", "keepdims"]) + @pytest.mark.parametrize("method", ["min", "max"]) + def test_numpy_min_max_unsupported_kwargs_raises(self, method, kwarg): + cat = Categorical(["a", "b", "c", "b"], ordered=True) + msg = ( + f"the '{kwarg}' parameter is not supported in the pandas implementation " + f"of {method}" + ) + if kwarg == "axis": + msg = r"`axis` must be fewer than the number of dimensions \(1\)" + kwargs = {kwarg: 42} + method = getattr(np, method) + with pytest.raises(ValueError, match=msg): + method(cat, **kwargs) + + @pytest.mark.parametrize("method, expected", [("min", "a"), ("max", "c")]) + def test_numpy_min_max_axis_equals_none(self, method, expected): + cat = Categorical(["a", "b", "c", "b"], ordered=True) + method = getattr(np, method) + result = method(cat, axis=None) + assert result == expected + + @pytest.mark.parametrize( + "values,categories,exp_mode", + [ + ([1, 1, 2, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5]), + ([1, 1, 1, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5, 1]), + ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1]), + ([np.nan, np.nan, np.nan, 4, 5], [5, 4, 3, 2, 1], [5, 4]), + ([np.nan, np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]), + ([np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]), + ], + ) + def test_mode(self, values, categories, exp_mode): + cat = Categorical(values, categories=categories, ordered=True) + res = Series(cat).mode()._values + exp = Categorical(exp_mode, categories=categories, ordered=True) + tm.assert_categorical_equal(res, exp) + + def test_searchsorted(self, ordered): + # https://github.com/pandas-dev/pandas/issues/8420 + # https://github.com/pandas-dev/pandas/issues/14522 + + cat = Categorical( + ["cheese", "milk", "apple", "bread", "bread"], + categories=["cheese", "milk", "apple", "bread"], + ordered=ordered, + ) + ser = Series(cat) + + # Searching for single item argument, side='left' (default) + res_cat = cat.searchsorted("apple") + assert res_cat == 2 + assert is_scalar(res_cat) + + res_ser = ser.searchsorted("apple") + assert res_ser == 2 + assert is_scalar(res_ser) + + # Searching for single item array, side='left' (default) + res_cat = cat.searchsorted(["bread"]) + res_ser = ser.searchsorted(["bread"]) + exp = np.array([3], dtype=np.intp) + tm.assert_numpy_array_equal(res_cat, exp) + tm.assert_numpy_array_equal(res_ser, exp) + + # Searching for several items array, side='right' + res_cat = cat.searchsorted(["apple", "bread"], side="right") + res_ser = ser.searchsorted(["apple", "bread"], side="right") + exp = np.array([3, 5], dtype=np.intp) + tm.assert_numpy_array_equal(res_cat, exp) + tm.assert_numpy_array_equal(res_ser, exp) + + # Searching for a single value that is not from the Categorical + with pytest.raises(TypeError, match="cucumber"): + cat.searchsorted("cucumber") + with pytest.raises(TypeError, match="cucumber"): + ser.searchsorted("cucumber") + + # Searching for multiple values one of each is not from the Categorical + msg = ( + "Cannot setitem on a Categorical with a new category, " + "set the categories first" + ) + with pytest.raises(TypeError, match=msg): + cat.searchsorted(["bread", "cucumber"]) + with pytest.raises(TypeError, match=msg): + ser.searchsorted(["bread", "cucumber"]) + + def test_unique(self, ordered): + # GH38140 + dtype = CategoricalDtype(["a", "b", "c"], ordered=ordered) + + # categories are reordered based on value when ordered=False + cat = Categorical(["a", "b", "c"], dtype=dtype) + res = cat.unique() + tm.assert_categorical_equal(res, cat) + + cat = Categorical(["a", "b", "a", "a"], dtype=dtype) + res = cat.unique() + tm.assert_categorical_equal(res, Categorical(["a", "b"], dtype=dtype)) + + cat = Categorical(["c", "a", "b", "a", "a"], dtype=dtype) + res = cat.unique() + exp_cat = Categorical(["c", "a", "b"], dtype=dtype) + tm.assert_categorical_equal(res, exp_cat) + + # nan must be removed + cat = Categorical(["b", np.nan, "b", np.nan, "a"], dtype=dtype) + res = cat.unique() + exp_cat = Categorical(["b", np.nan, "a"], dtype=dtype) + tm.assert_categorical_equal(res, exp_cat) + + def test_unique_index_series(self, ordered): + # GH38140 + dtype = CategoricalDtype([3, 2, 1], ordered=ordered) + + c = Categorical([3, 1, 2, 2, 1], dtype=dtype) + # Categorical.unique sorts categories by appearance order + # if ordered=False + exp = Categorical([3, 1, 2], dtype=dtype) + tm.assert_categorical_equal(c.unique(), exp) + + tm.assert_index_equal(Index(c).unique(), Index(exp)) + tm.assert_categorical_equal(Series(c).unique(), exp) + + c = Categorical([1, 1, 2, 2], dtype=dtype) + exp = Categorical([1, 2], dtype=dtype) + tm.assert_categorical_equal(c.unique(), exp) + tm.assert_index_equal(Index(c).unique(), Index(exp)) + tm.assert_categorical_equal(Series(c).unique(), exp) + + def test_shift(self): + # GH 9416 + cat = Categorical(["a", "b", "c", "d", "a"]) + + # shift forward + sp1 = cat.shift(1) + xp1 = Categorical([np.nan, "a", "b", "c", "d"]) + tm.assert_categorical_equal(sp1, xp1) + tm.assert_categorical_equal(cat[:-1], sp1[1:]) + + # shift back + sn2 = cat.shift(-2) + xp2 = Categorical( + ["c", "d", "a", np.nan, np.nan], categories=["a", "b", "c", "d"] + ) + tm.assert_categorical_equal(sn2, xp2) + tm.assert_categorical_equal(cat[2:], sn2[:-2]) + + # shift by zero + tm.assert_categorical_equal(cat, cat.shift(0)) + + def test_nbytes(self): + cat = Categorical([1, 2, 3]) + exp = 3 + 3 * 8 # 3 int8s for values + 3 int64s for categories + assert cat.nbytes == exp + + def test_memory_usage(self): + cat = Categorical([1, 2, 3]) + + # .categories is an index, so we include the hashtable + assert 0 < cat.nbytes <= cat.memory_usage() + assert 0 < cat.nbytes <= cat.memory_usage(deep=True) + + cat = Categorical(["foo", "foo", "bar"]) + assert cat.memory_usage(deep=True) > cat.nbytes + + if not PYPY: + # sys.getsizeof will call the .memory_usage with + # deep=True, and add on some GC overhead + diff = cat.memory_usage(deep=True) - sys.getsizeof(cat) + assert abs(diff) < 100 + + def test_map(self): + c = Categorical(list("ABABC"), categories=list("CBA"), ordered=True) + result = c.map(lambda x: x.lower(), na_action=None) + exp = Categorical(list("ababc"), categories=list("cba"), ordered=True) + tm.assert_categorical_equal(result, exp) + + c = Categorical(list("ABABC"), categories=list("ABC"), ordered=False) + result = c.map(lambda x: x.lower(), na_action=None) + exp = Categorical(list("ababc"), categories=list("abc"), ordered=False) + tm.assert_categorical_equal(result, exp) + + result = c.map(lambda x: 1, na_action=None) + # GH 12766: Return an index not an array + tm.assert_index_equal(result, Index(np.array([1] * 5, dtype=np.int64))) + + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_inplace_raises(self, value): + cat = Categorical(["A", "B", "B", "C", "A"]) + msg = ( + 'For argument "inplace" expected type bool, ' + f"received type {type(value).__name__}" + ) + + with pytest.raises(ValueError, match=msg): + cat.sort_values(inplace=value) + + def test_quantile_empty(self): + # make sure we have correct itemsize on resulting codes + cat = Categorical(["A", "B"]) + idx = Index([0.0, 0.5]) + result = cat[:0]._quantile(idx, interpolation="linear") + assert result._codes.dtype == np.int8 + + expected = cat.take([-1, -1], allow_fill=True) + tm.assert_extension_array_equal(result, expected) diff --git a/shared/package-files/06/066c81b911f49e5598b2e87dfb479255d510566dd924aa93fd5a6add20976c9d/to_sparse_csr_ops.h b/shared/package-files/06/066c81b911f49e5598b2e87dfb479255d510566dd924aa93fd5a6add20976c9d/to_sparse_csr_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f981515afc597aebbe3fd5de092c20dfd4dc0672 --- /dev/null +++ b/shared/package-files/06/066c81b911f49e5598b2e87dfb479255d510566dd924aa93fd5a6add20976c9d/to_sparse_csr_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API to_sparse_csr { + using schema = at::Tensor (const at::Tensor &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::to_sparse_csr"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, ::std::optional dense_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dense_dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/066ed109d0c499f2a2a7921b77a783b12df960571d6d4a0ffdbd1ed18626ff59/chunk_native.h b/shared/package-files/06/066ed109d0c499f2a2a7921b77a783b12df960571d6d4a0ffdbd1ed18626ff59/chunk_native.h new file mode 100644 index 0000000000000000000000000000000000000000..faf844bb8e1d4bb8ea43e2814e14f6f027a19da3 --- /dev/null +++ b/shared/package-files/06/066ed109d0c499f2a2a7921b77a783b12df960571d6d4a0ffdbd1ed18626ff59/chunk_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector chunk(const at::Tensor & self, int64_t chunks, int64_t dim=0); +TORCH_API ::std::vector chunk_nested_tensor(const at::Tensor & self, int64_t chunks, int64_t dim=0); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/0673e3297b7562438e66345a6236554a77c4996cc05222c00a07f1db6e1f4d85/__init__.cpython-311.pyc b/shared/package-files/06/0673e3297b7562438e66345a6236554a77c4996cc05222c00a07f1db6e1f4d85/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12c559c0d8ede730c6c094d6845a499b7fd15df4 Binary files /dev/null and b/shared/package-files/06/0673e3297b7562438e66345a6236554a77c4996cc05222c00a07f1db6e1f4d85/__init__.cpython-311.pyc differ diff --git a/shared/package-files/06/0675df29e6744f7d3cf74a1d1914541bbc58ad9a356ae968becbda190443427f/miopen-wrapper.h b/shared/package-files/06/0675df29e6744f7d3cf74a1d1914541bbc58ad9a356ae968becbda190443427f/miopen-wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..d1976da873ed7263e7bb4efe638fb18862d0379f --- /dev/null +++ b/shared/package-files/06/0675df29e6744f7d3cf74a1d1914541bbc58ad9a356ae968becbda190443427f/miopen-wrapper.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +#if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4) +// miopen 3.4 moved find mode from private header to public header +#else +// from miopen_internal.h +extern "C" { + +typedef enum +{ + miopenConvolutionFindModeNormal = 1, /*!< Normal mode */ +} miopenConvolutionFindMode_t; + +miopenStatus_t miopenSetConvolutionFindMode( + miopenConvolutionDescriptor_t convDesc, + miopenConvolutionFindMode_t findMode); +} +#endif diff --git a/shared/package-files/06/067c5d6843ebd6f78ce0acad16f76d837dc8ead8360f8cb2f7595f673df3ea76/partitions_.cpython-311.pyc b/shared/package-files/06/067c5d6843ebd6f78ce0acad16f76d837dc8ead8360f8cb2f7595f673df3ea76/partitions_.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64c7252c1cdd7e3c2fe92c3e1418b309aa677426 Binary files /dev/null and b/shared/package-files/06/067c5d6843ebd6f78ce0acad16f76d837dc8ead8360f8cb2f7595f673df3ea76/partitions_.cpython-311.pyc differ diff --git a/shared/package-files/06/067cdb6f68dc14e79c7b002446e9c7ebdd8b1cf2203e76676f4bde3fd4084305/kai_ukernel_interface.h b/shared/package-files/06/067cdb6f68dc14e79c7b002446e9c7ebdd8b1cf2203e76676f4bde3fd4084305/kai_ukernel_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..c0835729f88b58859336924b6a0f3608516ef0d6 --- /dev/null +++ b/shared/package-files/06/067cdb6f68dc14e79c7b002446e9c7ebdd8b1cf2203e76676f4bde3fd4084305/kai_ukernel_interface.h @@ -0,0 +1,144 @@ +#pragma once +#include +#include +#if AT_KLEIDIAI_ENABLED() + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native::kleidiai { + +enum class kai_kernel_id { + matmul_clamp_f32_qai8dxp1x8_qsi4c32p8x8_1x8x32_neon_dotprod = + 0, // Groupwise 4 bit GEMV + matmul_clamp_f32_qai8dxp4x8_qsi4c32p4x8_4x8x32_neon_i8mm = + 1, // Groupwise 4 bit GEMM + matmul_clamp_f32_qai8dxp1x8_qsi4cxp8x8_1x8x32_neon_dotprod = + 2, // Channelwise 4 bit GEMV + matmul_clamp_f32_qai8dxp4x8_qsi4cxp8x8_8x8x32_neon_i8mm = + 3 // Channelwise 4 bit GEMM +}; + +// Channelwise Kernel mapping +struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp { + struct kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel ukernel; + struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params rhs_pack_params; + size_t (*kai_get_lhs_packed_size)( + size_t m, + size_t k, + size_t mr, + size_t kr, + size_t sr); + size_t (*kai_get_rhs_packed_size)( + size_t n, + size_t k, + size_t nr, + size_t kr, + size_t sr); + void (*kai_run_lhs_quant_pack)( + size_t m, + size_t k, + size_t mr, + size_t kr, + size_t sr, + size_t m_idx_start, + const float* lhs, + size_t lhs_stride, + void* lhs_packed); + void (*kai_run_rhs_pack)( + size_t num_groups, + size_t n, + size_t k, + size_t nr, + size_t kr, + size_t sr, + const uint8_t* rhs, + const float* bias, + const float* scale, + void* rhs_packed, + size_t extra_bytes, + const struct kai_rhs_pack_nxk_qsi4cxp_qs4cxs1s0_params* params); + + kai_matmul_ukernel_f32_qa8dxp_qs4cxp( + const kai_matmul_clamp_f32_qai8dxp_qsi4cxp_ukernel& kernel) + : ukernel(kernel), + kai_get_lhs_packed_size( + &kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32), + kai_get_rhs_packed_size( + &kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qs4cxs1s0), + kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32), + kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4cxp_qs4cxs1s0) {} +}; + +struct kai_matmul_ukernel_f32_qa8dxp_qs4cxp +kai_select_channelwise_matmul_ukernel(const kai_kernel_id id); + +// Groupwise Kernel mapping +struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p { + struct kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel ukernel; + struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params rhs_pack_params; + size_t (*kai_get_lhs_packed_size)( + size_t m, + size_t k, + size_t mr, + size_t kr, + size_t sr); + size_t (*kai_get_rhs_packed_size)( + size_t n, + size_t k, + size_t nr, + size_t kr, + size_t sr, + size_t bl, + enum kai_datatype scale_dt); + void (*kai_run_lhs_quant_pack)( + size_t m, + size_t k, + size_t mr, + size_t kr, + size_t sr, + size_t m_idx_start, + const float* lhs, + size_t lhs_stride, + void* lhs_packed); + void (*kai_run_rhs_pack)( + size_t num_groups, + size_t n, + size_t k, + size_t nr, + size_t kr, + size_t sr, + size_t bl, + const uint8_t* rhs, + size_t rhs_stride, + const float* bias, + const void* scale, + size_t scale_stride, + void* rhs_packed, + size_t extra_bytes, + const struct kai_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0_params* params); + + kai_matmul_ukernel_f32_qa8dxp_qs4c32p( + const kai_matmul_clamp_f32_qai8dxp_qsi4c32p_ukernel& kernel) + : ukernel(kernel), + kai_get_lhs_packed_size( + &kai_get_lhs_packed_size_lhs_quant_pack_qai8dxp_f32), + kai_get_rhs_packed_size( + &kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0), + kai_run_lhs_quant_pack(&kai_run_lhs_quant_pack_qai8dxp_f32), + kai_run_rhs_pack(&kai_run_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0) {} +}; + +struct kai_matmul_ukernel_f32_qa8dxp_qs4c32p kai_select_groupwise_matmul_ukernel( + const kai_kernel_id id); + +} // namespace at::native::kleidiai +#endif diff --git a/shared/package-files/06/067ebb0bc1123126935f9a875c987589046a7f9ba72077bb4ca1521d7cfebfab/test_subscheck.cpython-311.pyc b/shared/package-files/06/067ebb0bc1123126935f9a875c987589046a7f9ba72077bb4ca1521d7cfebfab/test_subscheck.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1774841e5c2303efecf8dd330cd1f51d7216185 Binary files /dev/null and b/shared/package-files/06/067ebb0bc1123126935f9a875c987589046a7f9ba72077bb4ca1521d7cfebfab/test_subscheck.cpython-311.pyc differ diff --git a/shared/package-files/06/0687d2136038b7793c2af2430cf4b4e4e3bcad231462398e66fba772959436d1/_utils.py b/shared/package-files/06/0687d2136038b7793c2af2430cf4b4e4e3bcad231462398e66fba772959436d1/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8925bc662b5f97555d273d4c641ae5930f50d789 --- /dev/null +++ b/shared/package-files/06/0687d2136038b7793c2af2430cf4b4e4e3bcad231462398e66fba772959436d1/_utils.py @@ -0,0 +1,47 @@ +# mypy: allow-untyped-defs +import logging +from contextlib import contextmanager +from typing import cast + +from . import api, TensorPipeAgent + + +logger = logging.getLogger(__name__) + + +@contextmanager +def _group_membership_management(store, name, is_join): + token_key = "RpcGroupManagementToken" + join_or_leave = "join" if is_join else "leave" + my_token = f"Token_for_{name}_{join_or_leave}" + while True: + # Retrieve token from store to signal start of rank join/leave critical section + returned = store.compare_set(token_key, "", my_token).decode() + if returned == my_token: + # Yield to the function this context manager wraps + yield + # Finished, now exit and release token + # Update from store to signal end of rank join/leave critical section + store.set(token_key, "") + # Other will wait for this token to be set before they execute + store.set(my_token, "Done") + break + else: + # Store will wait for the token to be released + try: + store.wait([returned]) + except RuntimeError: + logger.error( + "Group membership token %s timed out waiting for %s to be released.", + my_token, + returned, + ) + raise + + +def _update_group_membership(worker_info, my_devices, reverse_device_map, is_join): + agent = cast(TensorPipeAgent, api._get_current_rpc_agent()) + ret = agent._update_group_membership( + worker_info, my_devices, reverse_device_map, is_join + ) + return ret diff --git a/shared/package-files/06/068a1600b0d6013bd9ba925a2fbf8615045060ea2d35efc5cb5d48e4d1a1d850/mma.h b/shared/package-files/06/068a1600b0d6013bd9ba925a2fbf8615045060ea2d35efc5cb5d48e4d1a1d850/mma.h new file mode 100644 index 0000000000000000000000000000000000000000..7d0b79141f65461e0384f34f9e30c482969041ca --- /dev/null +++ b/shared/package-files/06/068a1600b0d6013bd9ba925a2fbf8615045060ea2d35efc5cb5d48e4d1a1d850/mma.h @@ -0,0 +1,761 @@ +/* + * Copyright 2017-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead.") +#else +#warning "crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__ +#endif + +#if !defined(__CUDA_MMA_H__) +#define __CUDA_MMA_H__ + +#include +#include + +#define __CUDA_MMA_DEVICE_DECL__ static __device__ __inline__ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 +#define __CUDA_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 +#define __CUDA_SUBBYTE_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define __CUDA_AMPERE_MMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 */ + +namespace nvcuda { +namespace wmma { + + // utility functions +#ifdef __CUDA_AMPERE_MMA__ + inline __device__ float __float_to_tf32(float in) + { + float ret; + asm("{\n .reg .b32 __$1;" + "\n cvt.rna.tf32.f32 __$1, %1;" + "\n mov.b32 %0, __$1;\n}\n" : "=f"(ret) : "f"(in) ); + return ret; + } +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // tags + // + struct row_major; + struct col_major; + struct matrix_a; + struct matrix_b; + struct accumulator; + +#ifdef __CUDA_AMPERE_MMA__ + namespace precision { + struct tf32; + } +#endif /* __CUDA_AMPERE_MMA__ */ +#ifdef __CUDA_SUBBYTE_IMMA__ + namespace experimental { + namespace precision { + struct u4; // 4-bit unsigned + struct s4; // 4-bit signed + struct b1; // 1-bit + } + enum bmmaBitOp { bmmaBitOpXOR = 1 +#ifdef __CUDA_AMPERE_MMA__ + , bmmaBitOpAND = 2 +#endif /* __CUDA_AMPERE_MMA__ */ + }; + enum bmmaAccumulateOp { bmmaAccumulateOpPOPC = 1 }; + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + // + // layout + // + enum layout_t { + mem_row_major, mem_col_major + }; + + template + struct helper_traits { + typedef T element_type; + typedef T storage_element_type; + typedef T fill_argument_type; + }; + +#ifdef __CUDA_SUBBYTE_IMMA__ + template<> struct helper_traits { + typedef experimental::precision::u4 element_type; + typedef unsigned int storage_element_type; + typedef unsigned int fill_argument_type; + }; + + template<> struct helper_traits { + typedef experimental::precision::s4 element_type; + typedef int storage_element_type; + typedef int fill_argument_type; + }; + + template<> struct helper_traits { + typedef experimental::precision::b1 element_type; + typedef unsigned int storage_element_type; + typedef unsigned int fill_argument_type; + }; +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> struct helper_traits { + typedef precision::tf32 element_type; + typedef float storage_element_type; + typedef float fill_argument_type; + }; +#endif /* __CUDA_AMPERE_MMA__ */ + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4324) +#endif + // + // The base fragment type + // + /* note: alignment required for compiler implementation */ + template + struct __align__(8) __frag_base { + + /* Number of elements in the fragment */ + enum {num_elements = size}; + + /* Number of storage elements in the fragment. + + The elements of the fragment are packed together when the + fragment element type is experimental::precision::u4, + experimental::precision::s4 or experimental::precision::b1. + When elements are packed, num_storage_elements + will be smaller than num_elements. + */ + enum {num_storage_elements = packed_size}; + + /* element type of the fragment */ + typedef T element_type; + + /* element type of the storage representation. + + The mapping from element_type to storage_element_type is as follows: + experimental::precision::u4 -> unsigned (8 elements in 1 storage element) + experimental::precision::s4 -> int (8 elements in 1 storage element) + experimental::precision::b1 -> unsigned (32 elements in 1 storage element) + precision::tf32 -> float (1 element in 1 storage element) + all other types T -> T + */ + typedef typename helper_traits::storage_element_type storage_element_type; + + /* Storage for the (possibly packed) fragment elements. */ + storage_element_type x[num_storage_elements]; + }; +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + + template + static inline __device__ StorageType __get_storage_value(ArgType in) { return in; } + +#ifdef __CUDA_SUBBYTE_IMMA__ + template<> + __device__ inline unsigned + __get_storage_value(unsigned in) + { + /* For experimental::precision::u4 fragment element type, pack 8 elements into a single + 32-bit unsigned int storage element */ + unsigned val = in & 0xf; + return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) | + (val << 20) | (val << 24) | (val << 28)); + }; + + template<> + __device__ inline int + __get_storage_value(int in) + { + /* For experimental::precision::s4 fragment element type, pack 8 elements into a single + 32-bit signed int storage element */ + int val = in & 0xf; + return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) | + (val << 20) | (val << 24) | (val << 28)); + }; + + template<> + __device__ inline unsigned + __get_storage_value(unsigned in) + { + /* For experimental::precision::b1 fragment element type, pack 32 elements into a + single 32-bit unsigned int storage element */ + return (in & 0x1) ? 0xFFFFFFFFU : 0; + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + template + __CUDA_MMA_DEVICE_DECL__ void fill_fragment(__frag_base& f, + /* The mapping from fragment element type (FragEleType) to fill_argument_type is: + experimental::precision::u4 -> unsigned (only lower 4 bits taken) + experimental::precision::s4 -> int (only lower 4 bits taken) + experimental::precision::b1 -> unsigned (only lowest 1 bit taken) + precision::tf32 -> float + all other types T -> T + */ + const typename helper_traits::fill_argument_type & in) { + + /* get the (possibly packed) storage element value. See the specializations above for fragment + element types where the storage representation is packed */ + typedef typename helper_traits::storage_element_type storage_type; + storage_type v = __get_storage_value(in); +#pragma unroll + for (int i=0; i< f.num_storage_elements; i++) + f.x[i] = v; + } + + // + // Fragment template + // + template class fragment; + + // + // Fragments for 16x16x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Fragments for 32x8x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Fragments for 8x32x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Fragments for 8x8x32 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + + // + // Fragments for 8x8x128 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // Fragments for 16x16x8 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + + // + // Fragments for 8x8x4 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + + // + // Load functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Load functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Load functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Load functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Load functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + +#ifdef __CUDA_AMPERE_MMA__ + // + // Load functions for frags of shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Load functions for frags of shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Store functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Store functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Store functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // Store functions for frags of shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Store functions for frags of shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(double *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // MMA functions for shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + + + // + // MMA functions for shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void bmma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, + experimental::bmmaBitOp = experimental::bmmaBitOpXOR, + experimental::bmmaAccumulateOp = experimental::bmmaAccumulateOpPOPC) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // MMA functions for shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + + // + // MMA functions for shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ +}; +}; + +#undef __DEF_IF_HOST +#undef __CUDA_IMMA__ +#undef __CUDA_SUBBYTE_IMMA__ +#undef __CUDA_AMPERE_MMA__ +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __CUDA_MMA_DEVICE_DECL__ + +#if defined(__CUDA_ARCH__) +#include "mma.hpp" +#endif /* defined(__CUDA_ARCH__) */ + + +#endif /* !__CUDA_MMA_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__ +#endif diff --git a/shared/package-files/06/068a9409b5608306a8a86095cbfaf8d8c2151ee015f8fde038d155648956a235/fractionfield.py b/shared/package-files/06/068a9409b5608306a8a86095cbfaf8d8c2151ee015f8fde038d155648956a235/fractionfield.py new file mode 100644 index 0000000000000000000000000000000000000000..78f5054ddd5480fe6f77442f7a25f22603a4d90d --- /dev/null +++ b/shared/package-files/06/068a9409b5608306a8a86095cbfaf8d8c2151ee015f8fde038d155648956a235/fractionfield.py @@ -0,0 +1,181 @@ +"""Implementation of :class:`FractionField` class. """ + + +from sympy.polys.domains.compositedomain import CompositeDomain +from sympy.polys.domains.field import Field +from sympy.polys.polyerrors import CoercionFailed, GeneratorsError +from sympy.utilities import public + +@public +class FractionField(Field, CompositeDomain): + """A class for representing multivariate rational function fields. """ + + is_FractionField = is_Frac = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self, domain_or_field, symbols=None, order=None): + from sympy.polys.fields import FracField + + if isinstance(domain_or_field, FracField) and symbols is None and order is None: + field = domain_or_field + else: + field = FracField(symbols, domain_or_field, order) + + self.field = field + self.dtype = field.dtype + + self.gens = field.gens + self.ngens = field.ngens + self.symbols = field.symbols + self.domain = field.domain + + # TODO: remove this + self.dom = self.domain + + def new(self, element): + return self.field.field_new(element) + + def of_type(self, element): + """Check if ``a`` is of type ``dtype``. """ + return self.field.is_element(element) + + @property + def zero(self): + return self.field.zero + + @property + def one(self): + return self.field.one + + @property + def order(self): + return self.field.order + + def __str__(self): + return str(self.domain) + '(' + ','.join(map(str, self.symbols)) + ')' + + def __hash__(self): + return hash((self.__class__.__name__, self.field, self.domain, self.symbols)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if not isinstance(other, FractionField): + return NotImplemented + return self.field == other.field + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return a.as_expr() + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + return self.field.from_expr(a) + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + dom = K1.domain + conv = dom.convert_from + if dom.is_ZZ: + return K1(conv(K0.numer(a), K0)) / K1(conv(K0.denom(a), K0)) + else: + return K1(conv(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianRational`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a ``GaussianInteger`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ComplexField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_AlgebraicField(K1, a, K0): + """Convert an algebraic number to ``dtype``. """ + if K1.domain != K0: + a = K1.domain.convert_from(a, K0) + if a is not None: + return K1.new(a) + + def from_PolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + if a.is_ground: + return K1.convert_from(a.coeff(1), K0.domain) + try: + return K1.new(a.set_ring(K1.field.ring)) + except (CoercionFailed, GeneratorsError): + # XXX: We get here if K1=ZZ(x,y) and K0=QQ[x,y] + # and the poly a in K0 has non-integer coefficients. + # It seems that K1.new can handle this but K1.new doesn't work + # when K0.domain is an algebraic field... + try: + return K1.new(a) + except (CoercionFailed, GeneratorsError): + return None + + def from_FractionField(K1, a, K0): + """Convert a rational function to ``dtype``. """ + try: + return a.set_field(K1.field) + except (CoercionFailed, GeneratorsError): + return None + + def get_ring(self): + """Returns a field associated with ``self``. """ + return self.field.to_ring().to_domain() + + def is_positive(self, a): + """Returns True if ``LC(a)`` is positive. """ + return self.domain.is_positive(a.numer.LC) + + def is_negative(self, a): + """Returns True if ``LC(a)`` is negative. """ + return self.domain.is_negative(a.numer.LC) + + def is_nonpositive(self, a): + """Returns True if ``LC(a)`` is non-positive. """ + return self.domain.is_nonpositive(a.numer.LC) + + def is_nonnegative(self, a): + """Returns True if ``LC(a)`` is non-negative. """ + return self.domain.is_nonnegative(a.numer.LC) + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numer + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denom + + def factorial(self, a): + """Returns factorial of ``a``. """ + return self.dtype(self.domain.factorial(a)) diff --git a/shared/package-files/06/068c759e5e0cda01113978e09532a50dcd979e1b560fdc541ba20ebeae87300c/closure.py b/shared/package-files/06/068c759e5e0cda01113978e09532a50dcd979e1b560fdc541ba20ebeae87300c/closure.py new file mode 100644 index 0000000000000000000000000000000000000000..dce2a58a5d881d78e753d450b3d140a6be36e82d --- /dev/null +++ b/shared/package-files/06/068c759e5e0cda01113978e09532a50dcd979e1b560fdc541ba20ebeae87300c/closure.py @@ -0,0 +1,135 @@ +# mypy: allow-untyped-defs +import os +import threading +from queue import Empty as EmptyQueue, Queue + +from torch._lazy.device_context import get_device_context + + +class ClosureHandler: + def __init__(self) -> None: + pass + + def run(self, closure): + """Run closure function + + Args: + closure: callable function to run + """ + closure() + + def __call__(self, closures): + for closure in closures: + self.run(closure) + + +class AsyncClosureHandler(ClosureHandler): + """Handler for Asynchronous Step Closures + Args: + max_queue_size: The maximum length of the closure queue after which + the training loop will block until closures are evaluated. + By default, a reasonable limit of a maximum of 100 on the queue. + This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment + variable. + """ + + def __init__(self, max_queue_size=100): + super().__init__() + self._closure_queue: Queue = Queue( + int(os.environ.get("LTC_MAX_ASYNC_QUEUE", max_queue_size)) + ) + self._closure_exception: Queue = Queue() + self._closure_lock = threading.Lock() + self._closure_event_loop_finished = threading.Event() + self._closure_event_loop = None + + def start_event_loop(self): + """Start closure event loop if not started""" + if self._closure_event_loop is None: + + def event_loop(): + # Run loop until closure event is set and closure queue is empty + while True: + try: + closure = self._closure_queue.get(block=True, timeout=3) + closure() + self._closure_queue.task_done() + except EmptyQueue: + with self._closure_lock: + if self._closure_queue.empty(): + self._closure_event_loop_finished.set() + return + except Exception as e: + self._closure_exception.put(e) + return + + self._closure_event_loop = threading.Thread(target=event_loop) + self._closure_event_loop.start() + + def run(self, closure): + with self._closure_lock: + self._closure_queue.put(closure, block=True) + if ( + self._closure_event_loop is None + or not self._closure_event_loop.is_alive() + ): + try: + e = self._closure_exception.get(block=False) + raise RuntimeError( + "Cannot run asynchronous closure due to previously raised exception" + ) from e + except EmptyQueue: + self._closure_event_loop = None + self.start_event_loop() + + +def add_step_closure(closure, args=(), run_async=False): + """Adds a closure to the list of the ones to be run at the end of the step. + Many times during model training there is the need to print/report (print to + console, post to tensorboard, etc...) information which require the content of + intermediary tensors to be inspected. + Inspecting different tensors content in different points of the model code + requires many executions and typically causes performance issues. + Adding a step closure will ensure that it will be run after the barrier, when + all the live tensors will be already materialized to device data. + Live tensors which will include the ones captured by the closure arguments. + So using `add_step_closure()` will ensure a single execution will be + performed, even when multiple closures are queued, requiring multiple tensors + to be inspected. + Step closures will be run sequentially in the order they have been queued. + Note that even though using this API the execution will be optimized, it is + advised to throttle the printing/reporting events once every N steps. + Args: + closure (callable): The function to be called. + args (tuple): The arguments to be passed to the closure. + run_async: If True, run the closure asynchronously. + """ + devctx = get_device_context() + closures_type = "async_step_closures" if run_async else "step_closures" + step_closures = getattr(devctx, closures_type, None) + if step_closures is None: + step_closures = [] + setattr(devctx, closures_type, step_closures) + step_closures.append(lambda a=args: closure(*a)) + + +def run_step_closures(): + devctx = get_device_context() + async_step_closures = getattr(devctx, "async_step_closures", None) + if async_step_closures is not None: + devctx.async_step_closures = [] # type: ignore[attr-defined] + async_closure_handler = getattr(devctx, "async_closure_handler", None) + if async_closure_handler is None: + async_closure_handler = AsyncClosureHandler() + devctx.async_closure_handler = async_closure_handler # type: ignore[attr-defined] + async_closure_handler(async_step_closures) + + step_closures = getattr(devctx, "step_closures", None) + if step_closures is not None: + devctx.step_closures = [] # type: ignore[attr-defined] + closure_handler = getattr(devctx, "closure_handler", None) + if closure_handler is None: + closure_handler = ClosureHandler() + devctx.closure_handler = closure_handler # type: ignore[attr-defined] + closure_handler(step_closures) + return devctx diff --git a/shared/package-files/06/06907f46e852cea98bf4240fa02a6b453927085feb0758203af2d23d645dfc4a/log2_ops.h b/shared/package-files/06/06907f46e852cea98bf4240fa02a6b453927085feb0758203af2d23d645dfc4a/log2_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eda566632516fa7a6cbd2dc50bdcfea7c40ffe70 --- /dev/null +++ b/shared/package-files/06/06907f46e852cea98bf4240fa02a6b453927085feb0758203af2d23d645dfc4a/log2_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API log2 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log2"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log2(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API log2_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log2_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log2_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API log2_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log2"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5/test_pipe.py b/shared/package-files/06/069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5/test_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5c1625b8ab466677280de30562eb13c53376d7 --- /dev/null +++ b/shared/package-files/06/069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5/test_pipe.py @@ -0,0 +1,80 @@ +import numpy as np + +import pandas as pd +from pandas import ( + DataFrame, + Index, +) +import pandas._testing as tm + + +def test_pipe(): + # Test the pipe method of DataFrameGroupBy. + # Issue #17871 + + random_state = np.random.default_rng(2) + + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": random_state.standard_normal(8), + "C": random_state.standard_normal(8), + } + ) + + def f(dfgb): + return dfgb.B.max() - dfgb.C.min().min() + + def square(srs): + return srs**2 + + # Note that the transformations are + # GroupBy -> Series + # Series -> Series + # This then chains the GroupBy.pipe and the + # NDFrame.pipe methods + result = df.groupby("A").pipe(f).pipe(square) + + index = Index(["bar", "foo"], dtype="object", name="A") + expected = pd.Series([3.749306591013693, 6.717707873081384], name="B", index=index) + + tm.assert_series_equal(expected, result) + + +def test_pipe_args(): + # Test passing args to the pipe method of DataFrameGroupBy. + # Issue #17871 + + df = DataFrame( + { + "group": ["A", "A", "B", "B", "C"], + "x": [1.0, 2.0, 3.0, 2.0, 5.0], + "y": [10.0, 100.0, 1000.0, -100.0, -1000.0], + } + ) + + def f(dfgb, arg1): + filtered = dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False) + return filtered.groupby("group") + + def g(dfgb, arg2): + return dfgb.sum() / dfgb.sum().sum() + arg2 + + def h(df, arg3): + return df.x + df.y - arg3 + + result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100) + + # Assert the results here + index = Index(["A", "B"], name="group") + expected = pd.Series([-79.5160891089, -78.4839108911], index=index) + + tm.assert_series_equal(result, expected) + + # test SeriesGroupby.pipe + ser = pd.Series([1, 1, 2, 2, 3, 3]) + result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count()) + + expected = pd.Series([4, 8, 12], index=Index([1, 2, 3], dtype=np.int64)) + + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/06/0694aa8e6abdae0abf13d62b3765a2cb5042fcb516c5e344fad4281664a3a5c9/_utils.py b/shared/package-files/06/0694aa8e6abdae0abf13d62b3765a2cb5042fcb516c5e344fad4281664a3a5c9/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..449075adb23f72bf35e61f25e534f72355574bbe --- /dev/null +++ b/shared/package-files/06/0694aa8e6abdae0abf13d62b3765a2cb5042fcb516c5e344fad4281664a3a5c9/_utils.py @@ -0,0 +1,1092 @@ +# mypy: allow-untyped-defs +import copyreg +import functools +import importlib +import logging +import sys +import traceback +import warnings +from collections import defaultdict +from types import ModuleType +from typing import Any, Callable, Generic, Optional, TYPE_CHECKING +from typing_extensions import deprecated, ParamSpec + +import torch + + +def _type(self, dtype=None, non_blocking=False, **kwargs): + """Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (type or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + non_blocking = _get_async_or_non_blocking("type", non_blocking, kwargs) + if dtype is None: + return self.__module__ + "." + self.__class__.__name__ + + if isinstance(dtype, str): + dtype = _import_dotted_name(dtype) + if dtype == type(self): + return self + if self.is_sparse: + if not dtype.is_sparse: + raise RuntimeError("Cannot cast sparse tensor to dense tensor") + new_module_name = dtype.__module__.replace(".sparse", "") + new_values_type_name = new_module_name + "." + dtype.__name__ + new_values = torch.Tensor._values(self).type(new_values_type_name, non_blocking) + new_indices_type_name = new_module_name + ".LongTensor" + new_indices = torch.Tensor._indices(self).type( + new_indices_type_name, non_blocking + ) + return dtype(new_indices, new_values, self.size()) + if dtype.is_sparse: + raise RuntimeError("Cannot cast dense tensor to sparse tensor") + return dtype(self.size()).copy_(self, non_blocking) + + +def _to(self, device, non_blocking=False): + """Returns a copy of this object in device memory. + + If this object is already on the correct device, then no copy is performed + and the original object is returned. + + Args: + device (int): The destination device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + if self.device == device: + return self + + if device.type == "cpu": + pin_memory = non_blocking and self.device.type in ( + "cuda", + torch._C._get_privateuse1_backend_name(), + ) + untyped_storage = torch.empty( + self.nbytes(), dtype=torch.uint8, device=device, pin_memory=pin_memory + ).untyped_storage() + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + device_module = getattr(torch, device.type, None) + assert device_module is not None, ( + f"{device.type.upper()} device module is not loaded" + ) + with device_module.device(device): + if self.is_sparse and hasattr(device_module, "sparse"): + new_type = getattr(device_module.sparse, self.__class__.__name__) + indices = getattr(torch.Tensor._indices(self), device.type)( + device, non_blocking + ) + values = getattr(torch.Tensor._values(self), device.type)( + device, non_blocking + ) + return new_type(indices, values, self.size()) + else: + assert not self.is_sparse, ( + f"sparse storage is not supported for {device.type.upper()} tensors" + ) + untyped_storage = torch.UntypedStorage(self.size(), device=device) + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + +def _get_async_or_non_blocking(function_name, non_blocking, kwargs): + """Return the non-blocking flag given the function name and kwargs. + + Args: + function_name (str): the name of the function being used. + non_blocking (bool): the default value. + **kwargs (dict): the kwargs passed to the function. + """ + if not kwargs: + return non_blocking + if len(kwargs) != 1 or "async" not in kwargs: + message = "{}() got an unexpected keyword argument '{}'" + argument = list(kwargs.keys()).pop() + raise TypeError(message.format(function_name, argument)) + warnings.warn("'async' is deprecated; use 'non_blocking'") + return kwargs["async"] + + +def _get_restore_location(device): + """Return the map_location location. + + Used for rebuild functions where the tensor device is distinct from the storage + """ + + map_location = torch.serialization._serialization_tls.map_location + if map_location is None: + return device + else: + if isinstance(map_location, dict): + return map_location.get(device, device) + elif isinstance(map_location, (str, torch.device)): + return map_location + else: + assert callable(map_location) + raise RuntimeError( + "Callable map_location not supported with _rebuild_wrapper_subclass " + "or _rebuild_device_tensor_from_numpy" + ) + + +# Note [Don't serialize hooks] +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Since time immemorial, we have serialized the backward hooks associated with +# variables. This kind of half-worked--Python can pickle global functions +# (but not closures!)--but there were problems. +# +# - It's fragile. If you serialize a backward hook into a saved +# model, and then you rename the function associated with the hook, +# now your saved model is broken and you can't load it anymore. +# +# - It's not actually used. The standard recommendation is to +# serialize the *state_dict* of a model, not the model itself +# (since this is more stable to code changes affecting the model +# serialization), and the state dict saves "data" only, thus +# stripping the backward hooks. In some cases, hooks are +# essential to the well-functioning of a model (e.g., DDP), +# but DDP already manages readding the hooks! +# +# - We didn't serialize them in many cases. Prior to #10220, we +# were dropping backward hooks in ForkingPickler. We "fixed" this +# to be convenient with other serialization sites, but lack of +# serializing backward hooks wasn't actually the root cause of +# the bug. +# +# With these cases in mind, we have decided that a better strategy +# is to just NOT serialize hooks at all. +# +# Since this is a BC-breaking change, we should warn when we previously +# serialized a hook, but no longer do so. This will be done by adding a special +# sentinel property to hooks will be used to suppress this warning. If a hook +# has the property _torch_serialize_ignore, we will not emit a warning if we +# attempt to serialize a Tensor with this hook attached to it. +# +# By the way, when _backward_hooks is skipped, we must give an EMPTY +# OrderedDict(), if you pass a None you'll run afoul #12219. + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_tensor(storage, storage_offset, size, stride): + # first construct a tensor with the correct dtype/device + t = torch.empty((0,), dtype=storage.dtype, device=storage._untyped_storage.device) + return t.set_(storage._untyped_storage, storage_offset, size, stride) + + +def get_tensor_metadata(tensor): + # Tensor's Metadata for serializing. + # Currently, this only returns a dict[string, bool] specifing whether + # `conj` or `neg` bit is set. + assert isinstance(tensor, torch.Tensor) + return torch._C._get_tensor_metadata(tensor) # type: ignore[attr-defined] + + +def set_tensor_metadata(tensor, metadata): + # See `get_tensor_metadata` above + assert isinstance(metadata, dict) + assert isinstance(tensor, torch.Tensor) + torch._C._set_tensor_metadata(tensor, metadata) # type: ignore[attr-defined] + + +def _restore_device_fake_mode(tensor): + if torch._guards.detect_fake_mode(None) is not None: + if tensor.untyped_storage()._fake_device is not None: + device = _get_restore_location(tensor.untyped_storage()._fake_device) + if not isinstance(device, torch.device): + device = torch.device(device) + tensor.fake_device = torch.device(device) + return tensor + + +def _rebuild_tensor_v2( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata=None, +): + tensor = _rebuild_tensor(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + if metadata: + set_tensor_metadata(tensor, metadata) + + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + + tensor = _restore_device_fake_mode(tensor) + return tensor + + +def _rebuild_tensor_v3( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + dtype, + metadata=None, +): + t = torch.empty( + (0,), + dtype=dtype, + device=storage._untyped_storage.device, + requires_grad=requires_grad, + ) + t.set_(storage._untyped_storage, storage_offset, size, stride) + if metadata: + set_tensor_metadata(t, metadata) + t._backward_hooks = backward_hooks + t = _restore_device_fake_mode(t) + return t + + +_sparse_tensors_to_validate: list["torch.Tensor"] = [] + + +# In _legacy_load() in serialization.py we unpickle storages after the sparse +# tensors have been already unpickled. Those storages contain data necessary for +# validating sparse tensors: indices and values. That's why sparse tensors are +# first unpickled without any validation, and then this function is called just +# before _legacy_load() returns, so that all the sparse tensors can be validated +# in bulk. +# +# The same procedure must be followed by _load() in serialization.py because due +# to Pickler semantics, we have to use the same (non-validating) function for +# unpickling sparse tensors, regardless of the caller. +def _validate_loaded_sparse_tensors(): + try: + for t in _sparse_tensors_to_validate: + if t.layout is torch.sparse_coo: + torch._validate_sparse_coo_tensor_args( + t._indices(), t._values(), t.size(), t.is_coalesced() + ) + elif t.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + # TODO: Validation currently involves an expensive traversal + # on CPU, which may include a device transfer. + if t.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices, plain_indices = ( + t.crow_indices(), + t.col_indices(), + ) + else: + compressed_indices, plain_indices = ( + t.ccol_indices(), + t.row_indices(), + ) + torch._validate_sparse_compressed_tensor_args( + compressed_indices, plain_indices, t.values(), t.size(), t.layout + ) + else: + raise NotImplementedError( + f"_validate_loaded_sparse_tensors for layout `{t.layout}`" + ) + + finally: + _sparse_tensors_to_validate.clear() + + +def _rebuild_sparse_tensor(layout, data): + """ + Rebuilds a sparse tensor from its sparse storage representation. + + Args: + layout (str): The sparse storage layout of the tensor. + data (tuple): The tensor's sparse storage representation. + """ + if layout == torch.sparse_coo: + if len(data) == 3: + # For BC: + indices, values, size = data + is_coalesced = None + else: + indices, values, size, is_coalesced = data + result = torch.sparse_coo_tensor( + indices, values, size, check_invariants=False, is_coalesced=is_coalesced + ) + _sparse_tensors_to_validate.append(result) + return result + + elif layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + compressed_indices, plain_indices, values, size = data + result = torch.sparse_compressed_tensor( + compressed_indices, + plain_indices, + values, + size, + layout=layout, + check_invariants=False, + ) + _sparse_tensors_to_validate.append(result) + return result + + raise NotImplementedError(f"rebuilding sparse tensor for layout {layout}") + + +def _rebuild_nested_tensor(buffer, sizes, strides, storage_offsets): + return torch._nested_view_from_buffer(buffer, sizes, strides, storage_offsets) + + +def _rebuild_device_tensor_from_cpu_tensor(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = data.to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +def _rebuild_device_tensor_from_numpy(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = torch.from_numpy(data).to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +# Should not be used, only here to be able to load Tensors serialized with older versions of pytorch +_rebuild_xla_tensor = _rebuild_device_tensor_from_numpy + + +def _rebuild_meta_tensor_no_storage(dtype, size, stride, requires_grad): + return torch.empty_strided( + size, stride, dtype=dtype, device="meta", requires_grad=requires_grad + ) + + +def _rebuild_wrapper_subclass( + cls, + dtype, + size, + stride, + storage_offset, + layout, + device, + requires_grad, +): + device = _get_restore_location(device) + return torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined] + cls, + size, + strides=stride, + dtype=dtype, + storage_offset=storage_offset, + layout=layout, + device=device, + requires_grad=requires_grad, + ) + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_qtensor( + storage, + storage_offset, + size, + stride, + quantizer_params, + requires_grad, + backward_hooks, +): + qscheme = quantizer_params[0] + if qscheme == torch.per_tensor_affine: + _, scale, zero_point = quantizer_params + tensor = torch._empty_affine_quantized( + size, + scale=scale, + zero_point=zero_point, + dtype=storage.dtype, + device=storage.device, + ) + elif qscheme in (torch.per_channel_affine, torch.per_channel_affine_float_qparams): + _, scales, zero_points, axis = quantizer_params + if type(scales) is list and type(zero_points) is list: + if qscheme == torch.per_channel_affine: + scales = torch.tensor(scales, dtype=torch.double, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.long, device=storage.device + ) + else: + scales = torch.tensor(scales, dtype=torch.float, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.float, device=storage.device + ) + tensor = torch._empty_per_channel_affine_quantized( + size, + scales=scales, + zero_points=zero_points, + axis=axis, + dtype=storage.dtype, + device=storage.device, + ) + else: + raise RuntimeError(f"Can't deserialize quantized tensor with qscheme {qscheme}") + tensor.set_(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + return tensor + + +def _rebuild_parameter(data, requires_grad, backward_hooks): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + return param + + +def _rebuild_parameter_with_state(data, requires_grad, backward_hooks, state): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + # Restore state on Parameter like python attr. + param = _set_obj_state(param, state) + return param + + +def _get_obj_state(obj): + # Get the state of the python subclass + # This loosely mimicks the function on the object class but since Tensor do not inherit + # from it, we cannot call that function directly + # https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891 + # Note that starting with Python 3.11, this `__getstate__` is always defined and thus + # the else branch will never be taken. + getstate_fn = getattr(obj, "__getstate__", None) + if getstate_fn: + state = getstate_fn() + else: + slots_to_save = copyreg._slotnames(obj.__class__) # type: ignore[attr-defined] + if slots_to_save: + state = ( + obj.__dict__, + { + name: getattr(obj, name) + for name in slots_to_save + if hasattr(obj, name) + }, + ) + else: + state = obj.__dict__ + + return state + + +def _set_obj_state(obj, state): + if isinstance(state, tuple): + if not len(state) == 2: + raise RuntimeError(f"Invalid serialized state: {state}") + dict_state = state[0] + slots_state = state[1] + else: + dict_state = state + slots_state = None + + # Starting with Python 3.11, the __dict__ attribute is lazily created + # and is serialized as None when not needed. + if dict_state: + for k, v in dict_state.items(): + setattr(obj, k, v) + + if slots_state: + for k, v in slots_state.items(): + setattr(obj, k, v) + return obj + + +def _import_dotted_name(name): + components = name.split(".") + obj = __import__(components[0]) + for component in components[1:]: + obj = getattr(obj, component) + return obj + + +def _flatten_dense_tensors(tensors): + """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of + same dense type. + + Since inputs are dense, the resulting tensor will be a concatenated 1D + buffer. Element-wise operation on this buffer will be equivalent to + operating individually. + + Args: + tensors (Iterable[Tensor]): dense tensors to flatten. + + Returns: + A contiguous 1D buffer containing input tensors. + """ + return torch._C._nn.flatten_dense_tensors(tensors) + + +def _flatten_sparse_tensors(tensors): + """Flatten sparse tensors into two contiguous 1D buffers, one of indices and + one of values. Assume tensors are of same sparse type. + + Args: + tensors (Iterable[Tensor]): sparse tensors to flatten. + + Returns: + A tuple of two contiguous 1D buffers, one containing input tensors' + indices and the other containing the values. + """ + flat_indices = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._indices(t) for t in tensors] + ) + flat_values = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._values(t) for t in tensors] + ) + return flat_indices, flat_values + + +def _unflatten_dense_tensors(flat, tensors): + """View a flat buffer using the sizes of tensors. Assume that tensors are of + same dense type, and that flat is given by _flatten_dense_tensors. + + Args: + flat (Tensor): flattened dense tensors to unflatten. + tensors (Iterable[Tensor]): dense tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened dense tensors with sizes same as tensors and values from + flat. + """ + return torch._C._nn.unflatten_dense_tensors(flat, tensors) + + +def _unflatten_sparse_tensors(flat, tensors): + """View flat buffer (containing indices and values) using the sizes of + tensors. Assume that tensors are of same sparse type, and that flat is given + by _flatten_sparse_tensors. + + Args: + flat (tuple(Tensor, Tensor)): flattened indices and values of sparse + tensors to unflatten. + tensors (Iterable[Tensor]): sparse tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened sparse tensors with sizes same as tensors and values from + flat. + """ + flat_indices, flat_values = flat + indices = torch._C._nn.unflatten_dense_tensors( + flat_indices, [torch.Tensor._indices(t) for t in tensors] + ) + values = torch._C._nn.unflatten_dense_tensors( + flat_values, [torch.Tensor._values(t) for t in tensors] + ) + outputs = [] + for t, i, v in zip(tensors, indices, values): + outputs.append(t.new(i, v, t.size())) + return tuple(outputs) + + +def _reorder_tensors_as(tensors, ordered_tensors): + """Assume that tensors are of same order as ordered_tensors within their + types, e.g., from _take_tensors. Reorder them to be of same order as + ordered_tensors. + + Args: + tensors (Iterable[Tensor]): tensors to be reordered. They should be of + the same order as ordered_tensors within their own types. + ordered_tensors (Iterable[Tensor]): tensors whose order will be the + reference. + + Returns: + Ordered tuple of tensors with contents from tensors and order of + ordered_tensors. + """ + type_dict = defaultdict(list) + for tensor in tensors: + type_dict[tensor.type()].append(tensor) + type_dict_ = {t: iter(coll) for t, coll in type_dict.items()} + return tuple(next(type_dict_[tensor.type()]) for tensor in ordered_tensors) + + +def _take_tensors(tensors, size_limit): + """Group tensors into chunks. This generator yields a chunk at each time, + each containing tensors of same type up to certain byte limit in total size. + + Args: + tensors (Sequence): A sequence of tensors to be separated into chunks. + size_limit (int): The limit of each chunk in bytes. + + Yields: + Blocks of tensors of same type and within size_limit. The yielded + tensors are only ordered as the original sequence within its types. + """ + buf_dict: defaultdict[str, list] = defaultdict(lambda: [[], 0]) + for tensor in tensors: + t = tensor.type() + if tensor.is_sparse: + indices = torch.Tensor._indices(tensor) + values = torch.Tensor._values(tensor) + size = ( + indices.numel() * indices.element_size() + + values.numel() * values.element_size() + ) + else: + size = tensor.numel() * tensor.element_size() + buf_and_size = buf_dict[t] + if buf_and_size[1] + size > size_limit and buf_and_size[1] > 0: + yield buf_and_size[0] + buf_and_size = buf_dict[t] = [[], 0] + buf_and_size[0].append(tensor) + buf_and_size[1] += size + for buf, _ in buf_dict.values(): + if len(buf) > 0: + yield buf + + +# annotation decorator to get annotations in a way that is compatible +# with both Python 2 and 3 +def annotate(ret, **kwargs): + def dec(fun): + fun.__annotations__ = dict(kwargs) + fun.__annotations__["return"] = ret + return fun + + return dec + + +def render_call(fn, args, kwargs): + str_fn = torch.overrides.resolve_name(fn) + if str_fn is None: + str_fn = str(fn) + + str_args: list[str] = [] + with torch._tensor_str.printoptions(threshold=0, edgeitems=0): + str_args.extend(repr(a) for a in args) + str_args.extend(f"{k}={repr(v)}" for k, v in kwargs.items()) + r = f"{str_fn}({', '.join(str_args)})" + return r + + +# NOTE [ Python Traceback Reference Cycle Problem ] +# +# When using sys.exc_info(), it is important to **not** store the exc_info[2], +# which is the traceback, because otherwise you will run into the traceback +# reference cycle problem, i.e., the traceback holding reference to the frame, +# and the frame (which holds reference to all the object in its temporary scope) +# holding reference the traceback. + + +class KeyErrorMessage(str): + r"""str subclass that returns itself in repr""" + + __slots__ = () + + def __repr__(self): + return self + + +class ExceptionWrapper: + r"""Wraps an exception plus traceback to communicate across threads""" + + def __init__(self, exc_info=None, where="in background"): + # It is important that we don't store exc_info, see + # NOTE [ Python Traceback Reference Cycle Problem ] + if exc_info is None: + exc_info = sys.exc_info() + self.exc_type = exc_info[0] + self.exc_msg = "".join(traceback.format_exception(*exc_info)) + self.where = where + + def reraise(self): + r"""Reraises the wrapped exception in the current thread""" + # Format a message such as: "Caught ValueError in DataLoader worker + # process 2. Original Traceback:", followed by the traceback. + msg = f"Caught {self.exc_type.__name__} {self.where}.\nOriginal {self.exc_msg}" + if self.exc_type == KeyError: + # KeyError calls repr() on its argument (usually a dict key). This + # makes stack traces unreadable. It will not be changed in Python + # (https://bugs.python.org/issue2651), so we work around it. + msg = KeyErrorMessage(msg) + elif getattr(self.exc_type, "message", None): + # Some exceptions have first argument as non-str but explicitly + # have message field + raise self.exc_type(message=msg) + try: + exception = self.exc_type(msg) + except Exception: + # If the exception takes multiple arguments or otherwise can't + # be constructed, don't try to instantiate since we don't know how to + raise RuntimeError(msg) from None + raise exception + + +def _get_available_device_type(): + if torch.cuda.is_available(): + return "cuda" + if torch.backends.mps.is_available(): + return "mps" + if hasattr(torch, "xpu") and torch.xpu.is_available(): # type: ignore[attr-defined] + return "xpu" + if hasattr(torch, "mtia") and torch.mtia.is_available(): + return "mtia" + custom_backend_name = torch._C._get_privateuse1_backend_name() + custom_device_mod = getattr(torch, custom_backend_name, None) + if custom_device_mod and custom_device_mod.is_available(): + return custom_backend_name + # add more available device types here + return None + + +def _get_device_attr(get_member): + device_type = _get_available_device_type() + if device_type and device_type.lower() == "cuda": + return get_member(torch.cuda) + if device_type and device_type.lower() == "mps": + return get_member(torch.mps) + if device_type and device_type.lower() == "xpu": + return get_member(torch.xpu) # type: ignore[attr-defined] + if device_type and device_type.lower() == "mtia": + return get_member(torch.mtia) + if device_type == torch._C._get_privateuse1_backend_name(): + return get_member(getattr(torch, device_type)) + # add more available device types here + return None + + +def _get_current_device_index(): + # current device index + return _get_device_attr(lambda m: m.current_device()) + + +def _get_all_device_indices(): + # all device index + return _get_device_attr(lambda m: list(range(m.device_count()))) + + +def _get_devices_properties(device_ids): + # all device properties + return [_get_device_attr(lambda m: m.get_device_properties(i)) for i in device_ids] + + +def get_current_device_index() -> int: + r"""Checks if there are CUDA devices available and + returns the device index of the current default CUDA device. + Returns -1 in case there are no CUDA devices available. + Arguments: ``None`` + """ + if torch.cuda.device_count() > 0: + return torch.cuda.current_device() + return -1 + + +def _get_device_index( + device: Any, + optional: bool = False, + allow_cpu: bool = False, +) -> int: + r"""Gets the device index from :attr:`device`, which can be a torch.device + object, a Python integer, or ``None``. + + If :attr:`device` is a torch.device object, returns the device index if it + has index. Note that for a device without a specified index, + i.e., ``torch.device('xxx')``, this will return the current default + device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, + CPU devices will be accepted and ``-1`` will be returned in this case. + + If :attr:`device` is a Python integer, it is returned as is. + + If :attr:`device` is ``None``, this will return the current default + device of the supported runtime platform if :attr:`optional` is ``True``. + i.e., the current default CUDA device will be returned if CUDA runtime is supported. + """ + if isinstance(device, str): + device = torch.device(device) + device_idx: Optional[int] = None + if isinstance(device, torch.device): + if not allow_cpu and device.type == "cpu": + raise ValueError(f"Expected a non cpu device, but got: {device}") + device_idx = -1 if device.type == "cpu" else device.index + if isinstance(device, int): + device_idx = device + if device_idx is None: + if optional: + # The eager API _get_current_device_index uses `lambda` functions which are + # not supported in JIT and hence not scriptable. The JIT equivalent API to get + # the current device index is `get_current_device_index()` which can + # be scripted. We use is_scripting to check the mode we are in and call the + # appropriate API. + if torch.jit.is_scripting(): + device_idx = get_current_device_index() + else: + device_idx = _get_current_device_index() + else: + raise ValueError( + f"Expected a torch.device with a specified index or an integer, but got:{device}" + ) + return device_idx + + +def _handle_complex(tensor): + """ + Returns a real view of a tensor if complex dtype else just the tensor + need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule + """ + return ( + torch.view_as_real(tensor) + if not isinstance(tensor, torch.nn.UninitializedParameter) + and tensor.is_complex() + else tensor + ) + + +def _element_size(dtype): + """ + Returns the element size for a dtype, in bytes + """ + if not isinstance(dtype, torch.dtype): + raise RuntimeError(f"expected torch.dtype, but got {type(dtype)}") + + if dtype.is_complex: + return torch.finfo(dtype).bits >> 2 + elif dtype.is_floating_point: + return torch.finfo(dtype).bits >> 3 + elif dtype == torch.bool: + # NOTE: torch.bool is not supported in torch.iinfo() + return 1 + else: + return torch.iinfo(dtype).bits >> 3 + + +class _ClassPropertyDescriptor: + def __init__(self, fget, fset=None): + self.fget = fget + + def __get__(self, instance, owner=None): + if owner is None: + owner = type(instance) + return self.fget.__get__(instance, owner)() + + +def classproperty(func): + if not isinstance(func, (classmethod, staticmethod)): + func = classmethod(func) + return _ClassPropertyDescriptor(func) + + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + warnings.warn( # use `warnings.warn` instead of `@deprecated` + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + # FutureWarning, # TorchScript does not support Warning type + stacklevel=2, + ) + return torch.compiler.is_compiling() + + +def _functionalize_sync(t): + # This code lives in python instead of C++ since conditioning on a certain python subclass + # is much more of a pain in C++. + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(t, FunctionalTensor): + # If a FunctionalTensorMode is active while syncing, we don't want it to intercept any ops that get called + # when we sync our inner tensor. + # Why? + # (1) If there are input mutations in the graph, then they will be re-applied during + # AOTAutograd when we call _sync() from inside of our functionalization kernels. + # (2) _sync() causes us to regenerate our updated the tensor from the updated base, + # which dispatches to a bunch of view ops + # (3) The input to these view ops is our inner FunctionalTensorWrapper + # (since the sync was called from C++), not the python FunctionalTensor + # (4) if a python FunctionalTensorMode is active, it will complain when it intercepts + # the view op, since it will see an input that is a C++ FunctionalTensorWrapper + # (aka a normal torch.Tensor) instead of a python `FunctionalTensor). + maybe_functional_mode = torch._C._unset_dispatch_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + try: + torch._functionalize_sync(t.elem) # type: ignore[attr-defined] + finally: + if maybe_functional_mode is not None: + torch._C._set_dispatch_mode(maybe_functional_mode) + else: + torch._functionalize_sync(t) # type: ignore[attr-defined] + + +@functools.lru_cache(2) +def _get_device_module(device_type: str): + device_module = getattr(torch, device_type, None) + if device_module is None: + raise RuntimeError( + f"Device '{device_type}' does not have a corresponding module registered as 'torch.{device_type}'." + ) + return device_module + + +def _dummy_type(name: str) -> type: + def get_err_fn(is_init: bool): + def err_fn(obj, *args, **kwargs): + if is_init: + class_name = obj.__class__.__name__ + else: + class_name = obj.__name__ + raise RuntimeError(f"Tried to instantiate dummy base class {class_name}") + + return err_fn + + return type( + name, (object,), {"__init__": get_err_fn(True), "__new__": get_err_fn(False)} + ) + + +class _LazySeedTracker: + # Since seeding is memory-less, only track the latest seed. + # Note: `manual_seed_all` followed by `manual_seed` overwrites + # the seed on current device. We track the order of **latest** + # calls between these two API. + def __init__(self): + self.manual_seed_all_cb = None + self.manual_seed_cb = None + self.call_order = [] + + def queue_seed_all(self, cb, traceback): + self.manual_seed_all_cb = (cb, traceback) + # update seed_all to be latest + self.call_order = [self.manual_seed_cb, self.manual_seed_all_cb] + + def queue_seed(self, cb, traceback): + self.manual_seed_cb = (cb, traceback) + # update seed to be latest + self.call_order = [self.manual_seed_all_cb, self.manual_seed_cb] + + def get_calls(self) -> list: + return self.call_order + + +logger = logging.getLogger(__name__) +P = ParamSpec("P") + + +class CallbackRegistry(Generic[P]): + def __init__(self, name: str): + self.name = name + self.callback_list: list[Callable[P, None]] = [] + + def add_callback(self, cb: Callable[P, None]) -> None: + self.callback_list.append(cb) + + def fire_callbacks(self, *args: P.args, **kwargs: P.kwargs) -> None: + for cb in self.callback_list: + try: + cb(*args, **kwargs) + except Exception: + logger.exception( + "Exception in callback for %s registered with gpu trace", self.name + ) + + +def try_import(module_name: str) -> Optional[ModuleType]: + # Implementation based on + # https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported + if (module := sys.modules.get(module_name, None)) is not None: + return module + + if (spec := importlib.util.find_spec(module_name)) is not None: + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + + # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.loader + # "The finder should always set this attribute" + assert spec.loader is not None, "The loader attribute should always be set" + spec.loader.exec_module(module) + return module + + return None + + +# IMPORT_MAPPING and NAME_MAPPING are adapted from https://github.com/python/cpython/blob/main/Lib/_compat_pickle.py +# for use in the weights_only Unpickler. + +IMPORT_MAPPING = { + "__builtin__": "builtins", + "copy_reg": "copyreg", + "Queue": "queue", + "repr": "reprlib", + "_abcoll": "collections.abc", + # Non-mutual mappings. + "UserDict": "collections", + "UserList": "collections", + "UserString": "collections", + "whichdb": "dbm", + "StringIO": "io", + "cStringIO": "io", +} + + +# This contains rename rules that are easy to handle. We ignore the more +# complex stuff (e.g. mapping the names in the urllib and types modules). +# These rules should be run before import names are fixed. +NAME_MAPPING = { + ("__builtin__", "xrange"): ("builtins", "range"), + ("__builtin__", "reduce"): ("functools", "reduce"), + ("__builtin__", "intern"): ("sys", "intern"), + ("__builtin__", "unichr"): ("builtins", "chr"), + ("__builtin__", "unicode"): ("builtins", "str"), + ("__builtin__", "long"): ("builtins", "int"), + ("itertools", "izip"): ("builtins", "zip"), + ("itertools", "imap"): ("builtins", "map"), + ("itertools", "ifilter"): ("builtins", "filter"), + ("itertools", "ifilterfalse"): ("itertools", "filterfalse"), + ("itertools", "izip_longest"): ("itertools", "zip_longest"), + ("UserDict", "IterableUserDict"): ("collections", "UserDict"), + ("UserList", "UserList"): ("collections", "UserList"), + ("UserString", "UserString"): ("collections", "UserString"), + # Non-mutual mappings. + ("__builtin__", "basestring"): ("builtins", "str"), + ("exceptions", "StandardError"): ("builtins", "Exception"), + ("UserDict", "UserDict"): ("collections", "UserDict"), +} diff --git a/shared/package-files/06/06956f6920f4f87fb0cf200576d1ae59a12459056ba015ded2b4c98ee68fec51/optimizer.cpython-311.pyc b/shared/package-files/06/06956f6920f4f87fb0cf200576d1ae59a12459056ba015ded2b4c98ee68fec51/optimizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa97759ce141fb427153a4d34a19175756ec10dd Binary files /dev/null and b/shared/package-files/06/06956f6920f4f87fb0cf200576d1ae59a12459056ba015ded2b4c98ee68fec51/optimizer.cpython-311.pyc differ diff --git a/shared/package-files/06/0699d0c4bb1c2f84de1d9c11e606461fa20d9980d6c575045724fc6ced2007a5/test_memmap.cpython-311.pyc b/shared/package-files/06/0699d0c4bb1c2f84de1d9c11e606461fa20d9980d6c575045724fc6ced2007a5/test_memmap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ce9cf0cec857d3cb690dbcc64022078d0189da9 Binary files /dev/null and b/shared/package-files/06/0699d0c4bb1c2f84de1d9c11e606461fa20d9980d6c575045724fc6ced2007a5/test_memmap.cpython-311.pyc differ diff --git a/shared/package-files/06/069d05fc41c1970734e24011ffbbc6467d1b2065221582d6c8b194482bbaae74/is_coalesced_ops.h b/shared/package-files/06/069d05fc41c1970734e24011ffbbc6467d1b2065221582d6c8b194482bbaae74/is_coalesced_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0d57762bc5e9b29ac132aea3bf9baaf1d494e3f2 --- /dev/null +++ b/shared/package-files/06/069d05fc41c1970734e24011ffbbc6467d1b2065221582d6c8b194482bbaae74/is_coalesced_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API is_coalesced { + using schema = bool (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::is_coalesced"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "is_coalesced(Tensor self) -> bool"; + static bool call(const at::Tensor & self); + static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/069e7437f7ba5cb0a7cc296008d1952d2a6182610f6bb9609d75c7660acf36aa/native_batch_norm_native.h b/shared/package-files/06/069e7437f7ba5cb0a7cc296008d1952d2a6182610f6bb9609d75c7660acf36aa/native_batch_norm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9acc93e36a7bb4e031f6ebbc72eff0d4ce8df706 --- /dev/null +++ b/shared/package-files/06/069e7437f7ba5cb0a7cc296008d1952d2a6182610f6bb9609d75c7660acf36aa/native_batch_norm_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple batch_norm_cpu(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +TORCH_API ::std::tuple batch_norm_cpu_out(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); +TORCH_API ::std::tuple batch_norm_cuda(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +TORCH_API ::std::tuple batch_norm_cuda_out(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); +TORCH_API ::std::tuple mkldnn_batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06a35a654cc16c876b3f585bfbc36ce2a2126f0bc917e5ab1395ed5c215794ca/test_empty.cpython-311.pyc b/shared/package-files/06/06a35a654cc16c876b3f585bfbc36ce2a2126f0bc917e5ab1395ed5c215794ca/test_empty.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e4421145cb46e0880745c30d04a76506036af56 Binary files /dev/null and b/shared/package-files/06/06a35a654cc16c876b3f585bfbc36ce2a2126f0bc917e5ab1395ed5c215794ca/test_empty.cpython-311.pyc differ diff --git a/shared/package-files/06/06a63aae3e1ba541e9ee22604fe402bcc9176f722f5f5ae6b0cf707eeb4ea6d0/basic.cpython-311.pyc b/shared/package-files/06/06a63aae3e1ba541e9ee22604fe402bcc9176f722f5f5ae6b0cf707eeb4ea6d0/basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b673acf564cf913ee8a5813df371a6ff0cfe2b32 Binary files /dev/null and b/shared/package-files/06/06a63aae3e1ba541e9ee22604fe402bcc9176f722f5f5ae6b0cf707eeb4ea6d0/basic.cpython-311.pyc differ diff --git a/shared/package-files/06/06a68ea13cc90a1897aaccfe81d32887f3679645b26b8337a5dba0ce00f144d2/sqfreetools.cpython-311.pyc b/shared/package-files/06/06a68ea13cc90a1897aaccfe81d32887f3679645b26b8337a5dba0ce00f144d2/sqfreetools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e24c89c115852513d28944b9a51de625e837ced8 Binary files /dev/null and b/shared/package-files/06/06a68ea13cc90a1897aaccfe81d32887f3679645b26b8337a5dba0ce00f144d2/sqfreetools.cpython-311.pyc differ diff --git a/shared/package-files/06/06a7eebedae33b73c47034350de70dcadd9387d629b3ac6e79dd6d118e32b2f9/utils.py b/shared/package-files/06/06a7eebedae33b73c47034350de70dcadd9387d629b3ac6e79dd6d118e32b2f9/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..72c3b78bd4b09eb069757fb3f8d3632f09ec4b80 --- /dev/null +++ b/shared/package-files/06/06a7eebedae33b73c47034350de70dcadd9387d629b3ac6e79dd6d118e32b2f9/utils.py @@ -0,0 +1,698 @@ +""" +**Contains** + +* refraction_angle +* fresnel_coefficients +* deviation +* brewster_angle +* critical_angle +* lens_makers_formula +* mirror_formula +* lens_formula +* hyperfocal_distance +* transverse_magnification +""" + +__all__ = ['refraction_angle', + 'deviation', + 'fresnel_coefficients', + 'brewster_angle', + 'critical_angle', + 'lens_makers_formula', + 'mirror_formula', + 'lens_formula', + 'hyperfocal_distance', + 'transverse_magnification' + ] + +from sympy.core.numbers import (Float, I, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan) +from sympy.matrices.dense import Matrix +from sympy.polys.polytools import cancel +from sympy.series.limits import Limit +from sympy.geometry.line import Ray3D +from sympy.geometry.util import intersection +from sympy.geometry.plane import Plane +from sympy.utilities.iterables import is_sequence +from .medium import Medium + + +def refractive_index_of_medium(medium): + """ + Helper function that returns refractive index, given a medium + """ + if isinstance(medium, Medium): + n = medium.refractive_index + else: + n = sympify(medium) + return n + + +def refraction_angle(incident, medium1, medium2, normal=None, plane=None): + """ + This function calculates transmitted vector after refraction at planar + surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object. + If ``incident`` is a number then treated as angle of incidence (in radians) + in which case refraction angle is returned. + + If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance + of `Ray3D` in order to get the output as a `Ray3D`. Please note that if + plane of separation is not provided and normal is an instance of `Ray3D`, + ``normal`` will be assumed to be intersecting incident ray at the plane of + separation. This will not be the case when `normal` is a `Matrix` or + any other sequence. + If ``incident`` is an instance of `Ray3D` and `plane` has not been provided + and ``normal`` is not `Ray3D`, output will be a `Matrix`. + + Parameters + ========== + + incident : Matrix, Ray3D, sequence or a number + Incident vector or angle of incidence + medium1 : sympy.physics.optics.medium.Medium or sympifiable + Medium 1 or its refractive index + medium2 : sympy.physics.optics.medium.Medium or sympifiable + Medium 2 or its refractive index + normal : Matrix, Ray3D, or sequence + Normal vector + plane : Plane + Plane of separation of the two media. + + Returns + ======= + + Returns an angle of refraction or a refracted ray depending on inputs. + + Examples + ======== + + >>> from sympy.physics.optics import refraction_angle + >>> from sympy.geometry import Point3D, Ray3D, Plane + >>> from sympy.matrices import Matrix + >>> from sympy import symbols, pi + >>> n = Matrix([0, 0, 1]) + >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1]) + >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0)) + >>> refraction_angle(r1, 1, 1, n) + Matrix([ + [ 1], + [ 1], + [-1]]) + >>> refraction_angle(r1, 1, 1, plane=P) + Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1)) + + With different index of refraction of the two media + + >>> n1, n2 = symbols('n1, n2') + >>> refraction_angle(r1, n1, n2, n) + Matrix([ + [ n1/n2], + [ n1/n2], + [-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]]) + >>> refraction_angle(r1, n1, n2, plane=P) + Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1))) + >>> round(refraction_angle(pi/6, 1.2, 1.5), 5) + 0.41152 + """ + + n1 = refractive_index_of_medium(medium1) + n2 = refractive_index_of_medium(medium2) + + # check if an incidence angle was supplied instead of a ray + try: + angle_of_incidence = float(incident) + except TypeError: + angle_of_incidence = None + + try: + critical_angle_ = critical_angle(medium1, medium2) + except (ValueError, TypeError): + critical_angle_ = None + + if angle_of_incidence is not None: + if normal is not None or plane is not None: + raise ValueError('Normal/plane not allowed if incident is an angle') + + if not 0.0 <= angle_of_incidence < pi*0.5: + raise ValueError('Angle of incidence not in range [0:pi/2)') + + if critical_angle_ and angle_of_incidence > critical_angle_: + raise ValueError('Ray undergoes total internal reflection') + return asin(n1*sin(angle_of_incidence)/n2) + + # Treat the incident as ray below + # A flag to check whether to return Ray3D or not + return_ray = False + + if plane is not None and normal is not None: + raise ValueError("Either plane or normal is acceptable.") + + if not isinstance(incident, Matrix): + if is_sequence(incident): + _incident = Matrix(incident) + elif isinstance(incident, Ray3D): + _incident = Matrix(incident.direction_ratio) + else: + raise TypeError( + "incident should be a Matrix, Ray3D, or sequence") + else: + _incident = incident + + # If plane is provided, get direction ratios of the normal + # to the plane from the plane else go with `normal` param. + if plane is not None: + if not isinstance(plane, Plane): + raise TypeError("plane should be an instance of geometry.plane.Plane") + # If we have the plane, we can get the intersection + # point of incident ray and the plane and thus return + # an instance of Ray3D. + if isinstance(incident, Ray3D): + return_ray = True + intersection_pt = plane.intersection(incident)[0] + _normal = Matrix(plane.normal_vector) + else: + if not isinstance(normal, Matrix): + if is_sequence(normal): + _normal = Matrix(normal) + elif isinstance(normal, Ray3D): + _normal = Matrix(normal.direction_ratio) + if isinstance(incident, Ray3D): + intersection_pt = intersection(incident, normal) + if len(intersection_pt) == 0: + raise ValueError( + "Normal isn't concurrent with the incident ray.") + else: + return_ray = True + intersection_pt = intersection_pt[0] + else: + raise TypeError( + "Normal should be a Matrix, Ray3D, or sequence") + else: + _normal = normal + + eta = n1/n2 # Relative index of refraction + # Calculating magnitude of the vectors + mag_incident = sqrt(sum(i**2 for i in _incident)) + mag_normal = sqrt(sum(i**2 for i in _normal)) + # Converting vectors to unit vectors by dividing + # them with their magnitudes + _incident /= mag_incident + _normal /= mag_normal + c1 = -_incident.dot(_normal) # cos(angle_of_incidence) + cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2 + if cs2.is_negative: # This is the case of total internal reflection(TIR). + return S.Zero + drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal + # Multiplying unit vector by its magnitude + drs = drs*mag_incident + if not return_ray: + return drs + else: + return Ray3D(intersection_pt, direction_ratio=drs) + + +def fresnel_coefficients(angle_of_incidence, medium1, medium2): + """ + This function uses Fresnel equations to calculate reflection and + transmission coefficients. Those are obtained for both polarisations + when the electric field vector is in the plane of incidence (labelled 'p') + and when the electric field vector is perpendicular to the plane of + incidence (labelled 's'). There are four real coefficients unless the + incident ray reflects in total internal in which case there are two complex + ones. Angle of incidence is the angle between the incident ray and the + surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any + sympifiable object. + + Parameters + ========== + + angle_of_incidence : sympifiable + + medium1 : Medium or sympifiable + Medium 1 or its refractive index + + medium2 : Medium or sympifiable + Medium 2 or its refractive index + + Returns + ======= + + Returns a list with four real Fresnel coefficients: + [reflection p (TM), reflection s (TE), + transmission p (TM), transmission s (TE)] + If the ray is undergoes total internal reflection then returns a + list of two complex Fresnel coefficients: + [reflection p (TM), reflection s (TE)] + + Examples + ======== + + >>> from sympy.physics.optics import fresnel_coefficients + >>> fresnel_coefficients(0.3, 1, 2) + [0.317843553417859, -0.348645229818821, + 0.658921776708929, 0.651354770181179] + >>> fresnel_coefficients(0.6, 2, 1) + [-0.235625382192159 - 0.971843958291041*I, + 0.816477005968898 - 0.577377951366403*I] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Fresnel_equations + """ + if not 0 <= 2*angle_of_incidence < pi: + raise ValueError('Angle of incidence not in range [0:pi/2)') + + n1 = refractive_index_of_medium(medium1) + n2 = refractive_index_of_medium(medium2) + + angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2) + try: + angle_of_total_internal_reflection_onset = critical_angle(n1, n2) + except ValueError: + angle_of_total_internal_reflection_onset = None + + if angle_of_total_internal_reflection_onset is None or\ + angle_of_total_internal_reflection_onset > angle_of_incidence: + R_s = -sin(angle_of_incidence - angle_of_refraction)\ + /sin(angle_of_incidence + angle_of_refraction) + R_p = tan(angle_of_incidence - angle_of_refraction)\ + /tan(angle_of_incidence + angle_of_refraction) + T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\ + /sin(angle_of_incidence + angle_of_refraction) + T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\ + /(sin(angle_of_incidence + angle_of_refraction)\ + *cos(angle_of_incidence - angle_of_refraction)) + return [R_p, R_s, T_p, T_s] + else: + n = n2/n1 + R_s = cancel((cos(angle_of_incidence)-\ + I*sqrt(sin(angle_of_incidence)**2 - n**2))\ + /(cos(angle_of_incidence)+\ + I*sqrt(sin(angle_of_incidence)**2 - n**2))) + R_p = cancel((n**2*cos(angle_of_incidence)-\ + I*sqrt(sin(angle_of_incidence)**2 - n**2))\ + /(n**2*cos(angle_of_incidence)+\ + I*sqrt(sin(angle_of_incidence)**2 - n**2))) + return [R_p, R_s] + + +def deviation(incident, medium1, medium2, normal=None, plane=None): + """ + This function calculates the angle of deviation of a ray + due to refraction at planar surface. + + Parameters + ========== + + incident : Matrix, Ray3D, sequence or float + Incident vector or angle of incidence + medium1 : sympy.physics.optics.medium.Medium or sympifiable + Medium 1 or its refractive index + medium2 : sympy.physics.optics.medium.Medium or sympifiable + Medium 2 or its refractive index + normal : Matrix, Ray3D, or sequence + Normal vector + plane : Plane + Plane of separation of the two media. + + Returns angular deviation between incident and refracted rays + + Examples + ======== + + >>> from sympy.physics.optics import deviation + >>> from sympy.geometry import Point3D, Ray3D, Plane + >>> from sympy.matrices import Matrix + >>> from sympy import symbols + >>> n1, n2 = symbols('n1, n2') + >>> n = Matrix([0, 0, 1]) + >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1]) + >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0)) + >>> deviation(r1, 1, 1, n) + 0 + >>> deviation(r1, n1, n2, plane=P) + -acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3) + >>> round(deviation(0.1, 1.2, 1.5), 5) + -0.02005 + """ + refracted = refraction_angle(incident, + medium1, + medium2, + normal=normal, + plane=plane) + try: + angle_of_incidence = Float(incident) + except TypeError: + angle_of_incidence = None + + if angle_of_incidence is not None: + return float(refracted) - angle_of_incidence + + if refracted != 0: + if isinstance(refracted, Ray3D): + refracted = Matrix(refracted.direction_ratio) + + if not isinstance(incident, Matrix): + if is_sequence(incident): + _incident = Matrix(incident) + elif isinstance(incident, Ray3D): + _incident = Matrix(incident.direction_ratio) + else: + raise TypeError( + "incident should be a Matrix, Ray3D, or sequence") + else: + _incident = incident + + if plane is None: + if not isinstance(normal, Matrix): + if is_sequence(normal): + _normal = Matrix(normal) + elif isinstance(normal, Ray3D): + _normal = Matrix(normal.direction_ratio) + else: + raise TypeError( + "normal should be a Matrix, Ray3D, or sequence") + else: + _normal = normal + else: + _normal = Matrix(plane.normal_vector) + + mag_incident = sqrt(sum(i**2 for i in _incident)) + mag_normal = sqrt(sum(i**2 for i in _normal)) + mag_refracted = sqrt(sum(i**2 for i in refracted)) + _incident /= mag_incident + _normal /= mag_normal + refracted /= mag_refracted + i = acos(_incident.dot(_normal)) + r = acos(refracted.dot(_normal)) + return i - r + + +def brewster_angle(medium1, medium2): + """ + This function calculates the Brewster's angle of incidence to Medium 2 from + Medium 1 in radians. + + Parameters + ========== + + medium 1 : Medium or sympifiable + Refractive index of Medium 1 + medium 2 : Medium or sympifiable + Refractive index of Medium 1 + + Examples + ======== + + >>> from sympy.physics.optics import brewster_angle + >>> brewster_angle(1, 1.33) + 0.926093295503462 + + """ + + n1 = refractive_index_of_medium(medium1) + n2 = refractive_index_of_medium(medium2) + + return atan2(n2, n1) + +def critical_angle(medium1, medium2): + """ + This function calculates the critical angle of incidence (marking the onset + of total internal) to Medium 2 from Medium 1 in radians. + + Parameters + ========== + + medium 1 : Medium or sympifiable + Refractive index of Medium 1. + medium 2 : Medium or sympifiable + Refractive index of Medium 1. + + Examples + ======== + + >>> from sympy.physics.optics import critical_angle + >>> critical_angle(1.33, 1) + 0.850908514477849 + + """ + + n1 = refractive_index_of_medium(medium1) + n2 = refractive_index_of_medium(medium2) + + if n2 > n1: + raise ValueError('Total internal reflection impossible for n1 < n2') + else: + return asin(n2/n1) + + + +def lens_makers_formula(n_lens, n_surr, r1, r2, d=0): + """ + This function calculates focal length of a lens. + It follows cartesian sign convention. + + Parameters + ========== + + n_lens : Medium or sympifiable + Index of refraction of lens. + n_surr : Medium or sympifiable + Index of reflection of surrounding. + r1 : sympifiable + Radius of curvature of first surface. + r2 : sympifiable + Radius of curvature of second surface. + d : sympifiable, optional + Thickness of lens, default value is 0. + + Examples + ======== + + >>> from sympy.physics.optics import lens_makers_formula + >>> from sympy import S + >>> lens_makers_formula(1.33, 1, 10, -10) + 15.1515151515151 + >>> lens_makers_formula(1.2, 1, 10, S.Infinity) + 50.0000000000000 + >>> lens_makers_formula(1.33, 1, 10, -10, d=1) + 15.3418463277618 + + """ + + if isinstance(n_lens, Medium): + n_lens = n_lens.refractive_index + else: + n_lens = sympify(n_lens) + if isinstance(n_surr, Medium): + n_surr = n_surr.refractive_index + else: + n_surr = sympify(n_surr) + d = sympify(d) + + focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2)))) + + if focal_length == zoo: + return S.Infinity + return focal_length + + +def mirror_formula(focal_length=None, u=None, v=None): + """ + This function provides one of the three parameters + when two of them are supplied. + This is valid only for paraxial rays. + + Parameters + ========== + + focal_length : sympifiable + Focal length of the mirror. + u : sympifiable + Distance of object from the pole on + the principal axis. + v : sympifiable + Distance of the image from the pole + on the principal axis. + + Examples + ======== + + >>> from sympy.physics.optics import mirror_formula + >>> from sympy.abc import f, u, v + >>> mirror_formula(focal_length=f, u=u) + f*u/(-f + u) + >>> mirror_formula(focal_length=f, v=v) + f*v/(-f + v) + >>> mirror_formula(u=u, v=v) + u*v/(u + v) + + """ + if focal_length and u and v: + raise ValueError("Please provide only two parameters") + + focal_length = sympify(focal_length) + u = sympify(u) + v = sympify(v) + if u is oo: + _u = Symbol('u') + if v is oo: + _v = Symbol('v') + if focal_length is oo: + _f = Symbol('f') + if focal_length is None: + if u is oo and v is oo: + return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit() + if u is oo: + return Limit(v*_u/(v + _u), _u, oo).doit() + if v is oo: + return Limit(_v*u/(_v + u), _v, oo).doit() + return v*u/(v + u) + if u is None: + if v is oo and focal_length is oo: + return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit() + if v is oo: + return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit() + if focal_length is oo: + return Limit(v*_f/(v - _f), _f, oo).doit() + return v*focal_length/(v - focal_length) + if v is None: + if u is oo and focal_length is oo: + return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit() + if u is oo: + return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit() + if focal_length is oo: + return Limit(u*_f/(u - _f), _f, oo).doit() + return u*focal_length/(u - focal_length) + + +def lens_formula(focal_length=None, u=None, v=None): + """ + This function provides one of the three parameters + when two of them are supplied. + This is valid only for paraxial rays. + + Parameters + ========== + + focal_length : sympifiable + Focal length of the mirror. + u : sympifiable + Distance of object from the optical center on + the principal axis. + v : sympifiable + Distance of the image from the optical center + on the principal axis. + + Examples + ======== + + >>> from sympy.physics.optics import lens_formula + >>> from sympy.abc import f, u, v + >>> lens_formula(focal_length=f, u=u) + f*u/(f + u) + >>> lens_formula(focal_length=f, v=v) + f*v/(f - v) + >>> lens_formula(u=u, v=v) + u*v/(u - v) + + """ + if focal_length and u and v: + raise ValueError("Please provide only two parameters") + + focal_length = sympify(focal_length) + u = sympify(u) + v = sympify(v) + if u is oo: + _u = Symbol('u') + if v is oo: + _v = Symbol('v') + if focal_length is oo: + _f = Symbol('f') + if focal_length is None: + if u is oo and v is oo: + return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit() + if u is oo: + return Limit(v*_u/(_u - v), _u, oo).doit() + if v is oo: + return Limit(_v*u/(u - _v), _v, oo).doit() + return v*u/(u - v) + if u is None: + if v is oo and focal_length is oo: + return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit() + if v is oo: + return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit() + if focal_length is oo: + return Limit(v*_f/(_f - v), _f, oo).doit() + return v*focal_length/(focal_length - v) + if v is None: + if u is oo and focal_length is oo: + return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit() + if u is oo: + return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit() + if focal_length is oo: + return Limit(u*_f/(u + _f), _f, oo).doit() + return u*focal_length/(u + focal_length) + +def hyperfocal_distance(f, N, c): + """ + + Parameters + ========== + + f: sympifiable + Focal length of a given lens. + + N: sympifiable + F-number of a given lens. + + c: sympifiable + Circle of Confusion (CoC) of a given image format. + + Example + ======= + + >>> from sympy.physics.optics import hyperfocal_distance + >>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2) + 9.47 + """ + + f = sympify(f) + N = sympify(N) + c = sympify(c) + + return (1/(N * c))*(f**2) + +def transverse_magnification(si, so): + """ + + Calculates the transverse magnification upon reflection in a mirror, + which is the ratio of the image size to the object size. + + Parameters + ========== + + so: sympifiable + Lens-object distance. + + si: sympifiable + Lens-image distance. + + Example + ======= + + >>> from sympy.physics.optics import transverse_magnification + >>> transverse_magnification(30, 15) + -2 + + """ + + si = sympify(si) + so = sympify(so) + + return (-(si/so)) diff --git a/shared/package-files/06/06a8c47343d01f8756cb337580819f8636dfde737860de8993d70be10284e511/maximum.h b/shared/package-files/06/06a8c47343d01f8756cb337580819f8636dfde737860de8993d70be10284e511/maximum.h new file mode 100644 index 0000000000000000000000000000000000000000..f0c7beaf2c85e92ae1137c080ca39a5aad92eca2 --- /dev/null +++ b/shared/package-files/06/06a8c47343d01f8756cb337580819f8636dfde737860de8993d70be10284e511/maximum.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::maximum(Tensor self, Tensor other) -> Tensor +inline at::Tensor maximum(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::maximum::call(self, other); +} + +// aten::maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & maximum_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::maximum_out::call(self, other, out); +} +// aten::maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & maximum_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::maximum_out::call(self, other, out); +} + +} diff --git a/shared/package-files/06/06abfbd260d36cf6d6fdec37634c706d3c69cd9cae81902b6713ff414fe048f5/triu_indices_cuda_dispatch.h b/shared/package-files/06/06abfbd260d36cf6d6fdec37634c706d3c69cd9cae81902b6713ff414fe048f5/triu_indices_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6841e751ead8d06f66cd8d282bd1185d08524126 --- /dev/null +++ b/shared/package-files/06/06abfbd260d36cf6d6fdec37634c706d3c69cd9cae81902b6713ff414fe048f5/triu_indices_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset=0, at::TensorOptions options=at::kLong); +TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/06/06b2e711f499620071a8632d05fde1269b89b218877ea24b1b3f8016609ae6b4/real_ops.h b/shared/package-files/06/06b2e711f499620071a8632d05fde1269b89b218877ea24b1b3f8016609ae6b4/real_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b7fa1a14f753aa32a6f3ccd60e1597ba8c4fe12b --- /dev/null +++ b/shared/package-files/06/06b2e711f499620071a8632d05fde1269b89b218877ea24b1b3f8016609ae6b4/real_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API real { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::real"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "real(Tensor(a) self) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06b7dc386ecb3b5c9aa8a0902b70a55e52261bd87a3846f4068a637d4dc1583c/categorical.cpython-311.pyc b/shared/package-files/06/06b7dc386ecb3b5c9aa8a0902b70a55e52261bd87a3846f4068a637d4dc1583c/categorical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bb76edbf0899463f53947e482d5c7c319de017a Binary files /dev/null and b/shared/package-files/06/06b7dc386ecb3b5c9aa8a0902b70a55e52261bd87a3846f4068a637d4dc1583c/categorical.cpython-311.pyc differ diff --git a/shared/package-files/06/06bec2ad81b7cd48c181be427b5ed9aa4748de13d00f199024ffce546bb0bed8/test_nanops.cpython-311.pyc b/shared/package-files/06/06bec2ad81b7cd48c181be427b5ed9aa4748de13d00f199024ffce546bb0bed8/test_nanops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e09e4abe5c562efa21ccce38f94619a13589724 Binary files /dev/null and b/shared/package-files/06/06bec2ad81b7cd48c181be427b5ed9aa4748de13d00f199024ffce546bb0bed8/test_nanops.cpython-311.pyc differ diff --git a/shared/package-files/06/06c1e30104aad7c36c218789d09a7b1bb32249a717df243663dc6b0ccdafea3b/index_reduce_meta.h b/shared/package-files/06/06c1e30104aad7c36c218789d09a7b1bb32249a717df243663dc6b0ccdafea3b/index_reduce_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..0ad507cf3e99a0ce5177c920efcf098095ffd826 --- /dev/null +++ b/shared/package-files/06/06c1e30104aad7c36c218789d09a7b1bb32249a717df243663dc6b0ccdafea3b/index_reduce_meta.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_index_reduce : public at::impl::MetaBase { + + template + struct TORCH_API precompute_out { + + precompute_out set_dim(int64_t value) { + static_assert(DIM == false, "dim already set"); + precompute_out ret; +ret.dim = value; +return ret; + } + + int64_t dim; + }; + using meta_return_ty = precompute_out ; + meta_return_ty meta(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06c2502212a8a083065a40413f159c9ed91a2a5e34f35524b681f1148db059df/runtime_wrappers.py b/shared/package-files/06/06c2502212a8a083065a40413f159c9ed91a2a5e34f35524b681f1148db059df/runtime_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..539c1a91052dbcd269ac43465ac4a93dd19b2420 --- /dev/null +++ b/shared/package-files/06/06c2502212a8a083065a40413f159c9ed91a2a5e34f35524b681f1148db059df/runtime_wrappers.py @@ -0,0 +1,2326 @@ +# mypy: allow-untyped-defs +""" +This module defines runtime wrappers, which, based on previous analysis attempts to: +1. process the inputs and outputs +2. apply mutations +3. handle functionalized randomness +4. deduplicate inputs and consolidate views into their bases (see input_output_analysis) +""" +import builtins +import collections +import itertools +import pprint +from contextlib import nullcontext +from dataclasses import dataclass, field +from functools import wraps +from typing import Any, Callable, Optional, TYPE_CHECKING, Union + +import torch +import torch.utils.dlpack +from torch import Tensor +from torch._dynamo.utils import CompileEventLogger, dynamo_timed, get_metrics_context +from torch._guards import ( + compile_context, + CompileContext, + detect_fake_mode, + DuplicateInputs, + tracing, + TracingContext, +) +from torch._prims_common import CUDARngStateHelper +from torch._subclasses import FakeTensor +from torch.fx.experimental._backward_state import BackwardState +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata +from .functional_utils import gen_alias_from_base +from .input_output_analysis import ( + compute_overlapping_inputs, + create_synthetic_base_metadata, + remove_dupe_metadata, +) +from .logging_utils import describe_input, format_guard_bug_msg, track_graph_compiling +from .schemas import ( + AOTConfig, + InputAliasInfo, + MutationType, + OutputType, + PlainTensorMeta, + SubclassCreationMeta, + SubclassMeta, + TensorAlias, + ViewAndMutationMeta, +) +from .subclass_utils import ( + requires_subclass_dispatch, + runtime_unwrap_tensor_subclasses, + wrap_tensor_subclasses, +) +from .traced_function_transforms import aot_dispatch_subclass +from .utils import ( + call_func_at_runtime_with_args, + make_boxed_func, + partial_flatten_asdict, + strict_zip, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +zip = strict_zip + + +class CompilerWrapper: + """ + A wrapper around the inputs and outputs to the compiler_fn. We separate these into two parts: + + 1. The prologue, which edits the input to the compiler_fn(flat_fn, flat_args, etc) + 2. The epilogue, which edits the outputs of the compiler_fn (compiled_fn, real arguments) + + Each wrapper below should be implemented as a CompilerWrapper, so that we can facilitate + caching on the compiled output, and re-wrapping the output via epilogues. + Extra metadata that is needed to compute pre or post compile can be passed in via attributes. + """ + + def pre_compile( + self, + flat_fn, + flat_args: list[Tensor], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + """ + Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs. + Args: + flat_fn: The function to compile + flat_args: Metadata from example inputs of the function to compile + aot_config: AOTConfig passed in at compile time + fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args + """ + return flat_fn, flat_args, fw_metadata + + def post_compile(self, compiled_fn, aot_config, *, runtime_metadata) -> Callable: + """ + Given an output of the compiler, wrap it with information received from prologue. + Args: + compiled_fn: Callable after calling compiler_fn + aot_config: AOTConfig after calling prologue + runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps. + Example: + + def wrapped_compiled_fn(args): + # do something with args, aot_config, fw_metadata + return compiled_fn(args) + + return wrapped_compiled_fn + """ + return compiled_fn + + +# The wrapper created by this function handles all of the runtime aliasing and mutation "epilogue" logic +# that needs to run after the compiled function. +# +# This function accepts a trace_joint flag, indicating whether or not we're generating the runtime +# epilogue for a forward-only inference graph, or for an autograd.Function.apply function. +# This is because there are some minor differences in how we treat these cases at runtime: +# - resize_() is currently handled in the inference case, but not fully handled in the autograd case. +# - the autograd cases inserts TensorAlias wrapper objects for outputs that alias inputs +@dataclass +class RuntimeWrapper(CompilerWrapper): + indices_of_inps_to_detach: list[int] + trace_joint: bool + disable_amp: bool + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + return _create_runtime_wrapper( + compiled_fn, + runtime_metadata=runtime_metadata, + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + trace_joint=self.trace_joint, + keep_input_mutations=aot_config.keep_inference_input_mutations, + disable_amp=self.disable_amp, + ) + + +class NoopAliasHandler: + def __init__(self, info, runtime_metadata, trace_joint): + pass + + def __call__(self, orig_inputs, fw_outs, out): + return out + + +def _unwrap_tensoralias(x): + assert isinstance(x, TensorAlias) + return x.alias + + +def _identity(x): + return x + + +class AliasOfInputHandler: + def __init__(self, info, runtime_metadata, trace_joint): + self.base_idx = info.base_idx + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.functional_tensor = info.functional_tensor + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__(self, orig_inputs, fw_outs, out): + aliased_base_tensor = orig_inputs[self.base_idx] + return gen_alias_from_base( + aliased_base_tensor, + self.unwrap_out(out), + self.requires_grad, + self.functional_tensor, + replay_views=self.replay_views, + ) + + +class IsInputHandler: + def __init__(self, info, runtime_metadata, trace_joint): + self.base_idx = info.base_idx + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + + def __call__(self, orig_inputs, fw_outs, out): + aliased_base_tensor = orig_inputs[self.base_idx] + return aliased_base_tensor + + +class AliasOfIntermediateHandler: + def __init__(self, info, runtime_metadata, trace_joint): + self._unwrap_aliased_base_tensor = _identity + if info.output_type in ( + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + ): + num_user_outputs = len(runtime_metadata.output_info) + self.base_idx = info.base_idx + num_user_outputs + else: + self.base_idx = info.base_idx + if self.base_idx in runtime_metadata.aliased_out_indices: + self._unwrap_aliased_base_tensor = _unwrap_tensoralias + + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.functional_tensor = info.functional_tensor + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__(self, orig_inputs, fw_outs, out): + aliased_base_tensor = fw_outs[self.base_idx] + return gen_alias_from_base( + self._unwrap_aliased_base_tensor(aliased_base_tensor), + self.unwrap_out(out), + self.requires_grad, + self.functional_tensor, + replay_views=self.replay_views, + ) + + +_HANDLER_MAP = { + OutputType.non_alias: NoopAliasHandler, + OutputType.unsafe_view_alias: NoopAliasHandler, + OutputType.custom_function_view: NoopAliasHandler, + OutputType.alias_of_input: AliasOfInputHandler, + OutputType.is_input: IsInputHandler, + OutputType.alias_of_intermediate: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_save_as_output: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_base_is_user_output: AliasOfIntermediateHandler, +} + + +def make_output_handler(info, runtime_metadata, trace_joint): + handler_type = _HANDLER_MAP[info.output_type] + return handler_type(info, runtime_metadata, trace_joint) + + +def _create_runtime_wrapper( + compiled_fn, + *, + runtime_metadata: ViewAndMutationMeta, + indices_of_inps_to_detach: list[int], + trace_joint: bool, + keep_input_mutations: bool, + disable_amp: bool, +): + if not hasattr(compiled_fn, "_boxed_call"): + compiled_fn = make_boxed_func(compiled_fn) + + # Note [Inputs needed in runtime epilogue after list clearing] + # In Python functions, you can't free the input arguments of a function within the scope of that function. A workaround is to + # wrap the input arguments in a list, and clear the list from within the function. + # Here, this is implemented as `call_func_at_runtime_with_args(..., steal_args=True)`. + # + # This is needed for Compiled Autograd since some of the inputs (activations) should be freed early. + # However, we cannot blindly clear the entire list, because AOTAutograd may need access to some of the graph inputs + # **after** the compiled function has finished running. There are two main cases: + # (1) Input mutations: If there are an input mutations that we must run outside of the graph, we need access to the input. + # (2) Output aliasing: Outputs that aliases graph inputs generally must be regenerated outside of the `autograd.Function`, + # and doing so requires us accessing the corresponding input after the compiled artifact has run. + epilogue_args_idx = [] + epilogue_args_idx.extend(runtime_metadata.mutated_inp_runtime_indices) + for info in runtime_metadata.output_info: + if ( + info.output_type == OutputType.alias_of_input + or info.output_type == OutputType.is_input + ): + assert isinstance(info.base_idx, int) + epilogue_args_idx.append(info.base_idx) + + if config.unlift_effect_tokens: + assert len(runtime_metadata.tokens) == 0 + + if runtime_metadata.num_outputs_aliased > 0: + output_handlers = tuple( + make_output_handler(info, runtime_metadata, trace_joint) + for info in runtime_metadata.output_info + ) + + def runtime_wrapper(args: list[Any]): + # stash a ref to each input tensor we plan to use after the compiled function + orig_inputs = {i: args[i] for i in epilogue_args_idx} + + if keep_input_mutations: + mutated_args = ( + args[i] + for i in runtime_metadata.mutated_graph_handled_indices_seen_by_autograd + ) + torch.autograd.graph.increment_version(mutated_args) + + if trace_joint: + args_ = list(args) + # See Note [Detaching inputs that never need gradients] + for idx in indices_of_inps_to_detach: + if isinstance(args_[idx], torch.Tensor): + args_[idx] = args_[idx].detach() + + # It's possible to have trace_joint inside user specified with no_grad() region, + # if there is a nested with enable_grad(), that forces some outputs to require gradients. + # Therefore, we unconditionally turn on enable_grad() for compiled_fn execution. + with torch.autograd._force_original_view_tracking( + True + ), torch.enable_grad(): + all_outs = call_func_at_runtime_with_args( + compiled_fn, args_, disable_amp=disable_amp, steal_args=True + ) + else: + # When we have an inference graph, we run with grad disabled. + # It's possible to get an inference graph with inputs that require grad, + # in which case we want to make sure autograd is disabled + # (since e.g., inductor will generate aten.addmm.out calls which autograd will complain on) + # NOTE: We use _set_grad_enabled directly to reduce runtime overhead + grad_enabled = torch.is_grad_enabled() + try: + if grad_enabled: + torch._C._set_grad_enabled(False) + all_outs = call_func_at_runtime_with_args( + compiled_fn, args, disable_amp=disable_amp, steal_args=True + ) + finally: + if grad_enabled: + torch._C._set_grad_enabled(True) + del args + + num_mutated_runtime_inps = runtime_metadata.num_mutated_inp_runtime_indices + num_intermediate_bases = runtime_metadata.num_intermediate_bases + + assert ( + len(all_outs) + == num_mutated_runtime_inps + + runtime_metadata.num_outputs + + num_intermediate_bases + ) + + # Step 3: After running the compiled fw, apply updates to mutated inputs + num_mutations_to_apply = runtime_metadata.num_mutated_inp_runtime_indices + if num_mutations_to_apply > 0: + updated_inputs = all_outs[:num_mutations_to_apply] + fw_outs = all_outs[num_mutations_to_apply:] + + for i, inpt_idx in enumerate(runtime_metadata.mutated_inp_runtime_indices): + meta = runtime_metadata.input_info[inpt_idx] + if not meta.mutates_data and not meta.mutates_metadata: + continue + original_inpt = orig_inputs[inpt_idx] + updated_inpt = updated_inputs[i] + if meta.mutates_storage_metadata: + # See Note [set_() Input Mutations in AOTAutograd] + # mutates_storage_metadata means our input saw a x.set_(y) call. + # What if x **also** saw a data and/or a metadata mutation? + # (1) If the [meta]data mutation occurred after the set_(), + # then there is no need to copy_() the data. + # When we perform x.set_(x_updated), we are guaranteed that + # x_updated already has the final version of the data/metadata + # (2) If a data mutation occurred before the set_(). + # This case seems very difficult to support. + # TODO: discuss on the PR and decide if we want to tr to + # either support it, or detect and ban it. + if trace_joint: + assert isinstance(updated_inpt, TensorAlias) + updated_inpt = updated_inpt.alias + with torch.no_grad(): + original_inpt.set_(updated_inpt) + continue + if meta.mutates_metadata and not meta.mutates_data: + if trace_joint: + assert isinstance(updated_inpt, TensorAlias) + updated_inpt = updated_inpt.alias + # We need to grab the size/stride/storage_offset from the compiled forward, + # and use that to mutate the metadata of the input + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + if meta.mutates_data and meta.mutates_metadata: + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + assert meta.mutates_data + if meta.is_leaf and original_inpt.requires_grad: + # We can hit this situation in this case: + # def f(x): + # x.detach().mul_(2) + # return x + 1 + # AOTAutograd will see a mutation in the above case, and try to + # apply a copy_() here, in the epilogue. + # But if x required gradients, and is a leaf, then autograd + # will yell at us for trying to mutate it. + # However, it's only possible to end up in this scenario (like the above) + # if all of the mutations to the leaf input were non-autograd-tracking mutations + # (aka mutations under no_grad(), or on detached views). + # In that case, we fully want to hide the mutation from autograd, so detaching is ok. + original_inpt.detach().copy_(updated_inpt) + else: + original_inpt.copy_(updated_inpt) + else: + fw_outs = all_outs + + # Step 4: Manually regenerate any outputs that are aliased to inputs, instead of + # compiling them. + if runtime_metadata.num_outputs_aliased > 0: + # The compiled forward also returned intermediate bases. We don't want to return them to the user. + expect_num_outputs = ( + len(output_handlers) + runtime_metadata.num_intermediate_bases + ) + assert len(fw_outs) == expect_num_outputs + ret_outs = [ + handler(orig_inputs, fw_outs, out) + for out, handler in builtins.zip(fw_outs, output_handlers) + ] + else: + ret_outs = fw_outs + + if runtime_metadata.dynamic_outputs: + for t, o in zip(ret_outs, runtime_metadata.output_info): + if o.dynamic_dims is None: + continue + if hasattr(t, "_dynamo_weak_dynamic_indices"): + t._dynamo_weak_dynamic_indices |= o.dynamic_dims + else: + t._dynamo_weak_dynamic_indices = o.dynamic_dims.copy() + if runtime_metadata.grad_enabled_mutation is not None: + torch._C._set_grad_enabled(runtime_metadata.grad_enabled_mutation) + return ret_outs + + return runtime_wrapper + + +@dataclass +class FunctionalizedRngRuntimeWrapper(CompilerWrapper): + # TODO: I would love to get rid of this argument, but it's + # Wrapped pretty tightly around our aot_dispatch_autograd logic. + # Specifically, tensors_saved_for_backwards_slice's value is both used for calculating indices + # for setting placeholder strides(which is done before runtime, before this wrapper runs) + # and for saving tensors for backward (which is done during runtime, after this wrapper runs) + # So in aot_dispatch_autograd, this wrapper can't edit the set of outs without making one + # of those two indices incorrect. + return_new_outs: bool = True + + def pre_compile( + self, + flat_fn, + flat_args, + aot_config, + *, + fw_metadata, + ) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + if config.functionalize_rng_ops: + # Update example inputs for the fw_compiler + fake_mode = detect_fake_mode() + seed, offset = CUDARngStateHelper.get_torch_state_as_tuple(fake_mode) + flat_args.extend([seed, offset]) + # We are not clearing flat_args here because + # 1) There is a check in the debug compiler at the end + # 2) It does not matter as these are fake tensors + return flat_fn, flat_args, fw_metadata + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + @wraps(compiled_fn) + def wrapper(runtime_args: list[Any]): + if runtime_metadata.is_rng_op_functionalized: + # Add the seed and offset to args + seed, offset = CUDARngStateHelper.get_torch_state_as_tuple() + runtime_args.extend([seed, offset]) + out = compiled_fn(runtime_args) + out = self._functionalized_rng_runtime_epilogue( + runtime_metadata, + out, + # TODO: this won't be right for the backward when we convert the call_compiled_backward to use the wrapper + runtime_metadata.num_forward_returns, + ) + return out + return compiled_fn(runtime_args) + + return wrapper + + # Calling convention: If we are running functionalized RNG, then outs consists + # of (user_outs, rng_offset) + def _functionalized_rng_runtime_epilogue( + self, + metadata: ViewAndMutationMeta, + outs, + offset_index, + ): + if metadata.is_rng_op_functionalized: + assert metadata.num_outputs_rng_offset == 1 + new_rng_offset = outs[offset_index] + CUDARngStateHelper.set_new_offset(new_rng_offset) + if self.return_new_outs: + user_outs = outs[:offset_index] + outs[offset_index + 1 :] + return user_outs + else: + return outs + + return outs + + +@dataclass +class FakifiedOutWrapper(CompilerWrapper): + out_metas: list[torch.Tensor] = field(default_factory=list) + # TracingContext.fwd_output_strides + # Generated from actually doing compile + # NB: an entry is None if it's not a Tensor + fwd_output_strides: Optional[list[Optional[list[int]]]] = None + needs_post_compile: bool = True + + def pre_compile( + self, + fw_module, # Must be fw_module from aot_dispatch_*_graph + flat_args, + aot_config, + *, + fw_metadata, + ) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context and tracing_context.fakify_first_call: + self.out_metas = [ + n.meta["val"] for n in (list(fw_module.graph.nodes)[-1].args[0]) + ] + else: + self.needs_post_compile = False + return fw_module, flat_args, fw_metadata + + def _compute_output_meta_with_inductor_strides(self): + out = self.out_metas + fwd_output_strides = self.fwd_output_strides + if not fwd_output_strides: + return out + + from torch.fx.experimental.symbolic_shapes import statically_known_true + + for i in range(len(out)): + if not isinstance(out[i], Tensor): + continue + strides = fwd_output_strides[i] + # fwd_output_strides is best effort by Inductor. When an output + # Tensor has unbacked SymInts, Inductor may sometimes be unable + # to compute what the output stride would be. If Inductor doesn't + # have any clear direction on the layout, we don't have to run + # as_strided. To repro without this, run: + # + # python test/distributed/test_dynamo_distributed.py + # TestFakeDistributedSingleProc.test_unbacked_symbol_splitting_no_binding + if strides is None: + continue + if all( + statically_known_true(s1 == s2) + for s1, s2 in zip(out[i].stride(), strides) + ): + continue + out[i] = out[i].as_strided(out[i].shape, strides) + return out + + # To be called post compile + def set_fwd_output_strides(self, fwd_output_strides): + self.fwd_output_strides = fwd_output_strides + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + if self.needs_post_compile: + assert self.fwd_output_strides is not None + fakified_out = self._compute_output_meta_with_inductor_strides() + + @wraps(compiled_fn) + def wrapper(runtime_args): + nonlocal fakified_out + if fakified_out is not None: + out = fakified_out + fakified_out = None + return out + return compiled_fn(runtime_args) + + return wrapper + # If we don't need to fakify, we can just return the original compiled function + return compiled_fn + + +# This wrapper handles the AOTDispatch runtime logic for tensor subclasses. +# At runtime, we have a compiled function that knows how to operate on the domain of DenseTensor -> DenseTensor, +# But the user might have passed us some tensor subclass inputs (or expect some subclass tensor outputs). +# This function handles the wrapping and unwrapping of tensor subclasses at runtime. +@dataclass +class AOTDispatchSubclassWrapper(CompilerWrapper): + trace_joint: bool + fw_only: Optional[Callable] # Not cached, only used in pre_compile + maybe_subclass_meta: Optional[SubclassMeta] + num_fw_outs_saved_for_bw: Optional[int] + + def pre_compile( + self, + flat_fn, + flat_args: list[Tensor], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ): + (new_flat_fn, new_flat_args, subclass_meta) = aot_dispatch_subclass( + flat_fn, + flat_args, + is_joint_structure=self.trace_joint, + meta=fw_metadata, + fw_only=self.fw_only, # type: ignore[arg-type] + ) + self.maybe_subclass_meta = subclass_meta + return new_flat_fn, new_flat_args, fw_metadata + + def post_compile( + self, + compiled_fn, + _aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + if self.maybe_subclass_meta is None: + return compiled_fn + + subclass_metas = runtime_metadata.subclass_fw_graph_out_meta + + @wraps(compiled_fn) + def inner_fn(args: list[Any]): + unwrapped_args = runtime_unwrap_tensor_subclasses( + args, + subclass_metas=runtime_metadata.subclass_inp_meta, + append_symints=True, + ) + args.clear() + # expectation: runtime_fn is a boxed fn + unwrapped_outs = compiled_fn(unwrapped_args) + wrapped_outs = wrap_tensor_subclasses( + unwrapped_outs, + subclass_metas=subclass_metas, + num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw, + is_runtime=True, + included_subclass_symints=True, + ) + return wrapped_outs + + # box it + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +@dataclass +class EffectTokensWrapper(CompilerWrapper): + def post_compile( + self, + compiled_fn, + _aot_config, + *, + runtime_metadata: ViewAndMutationMeta, + ): + num_tokens = len(runtime_metadata.tokens) + + @wraps(compiled_fn) + def inner_fn(args: list[Any]): + if num_tokens > 0: + # Pass in forward effect tokens (See Note [Side-Effectful Tokens in AOTAutograd]) + old_args = args + args = [*([None] * num_tokens), *args] + old_args.clear() + + outs = compiled_fn(args) + + # Inductor cache DummyModule can return None + if outs is None: + return None + # Toss out the effect tokens (See Note [Side-Effectful Tokens in AOTAutograd]) + return outs[num_tokens:] if num_tokens != 0 else outs + + # box it + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +# MOTIVATION: +# +# When tracing functions for future execution, one must be careful not to pass +# in the same input tensor multiple times (e.g., f(x, x), as this can result +# in graphs that are ONLY valid if you later pass a new tensor in exactly the +# same way (e.g., f(y, y)). (NB: we really mean duplicate; two distinct +# tensors that alias each other is a different situation that is covered by +# aot_dispatch_deduplicated_autograd). Here are two examples: +# +# (1) Suppose you have a function: +# +# def f(x, y): +# return x + y +# +# If you make_fx(f)(x, x), you will trace out: +# +# def f(x, y): +# return y + y +# +# Oops! +# +# (2) For most tensors x and y, you can compute f's gradient with respect to +# these to inputs by saying torch.autograd.grad(f(x, y), (x, y)). However, +# if x is y, you will trace out a program that gets incorrect gradients: +# +# >>> x = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + x, (x, x)) +# (tensor([2.]), tensor([2.])) +# +# In other words, the gradient is double-counted. Deduplicating the arguments +# gives you an appropriate gradient: +# +# >>> y = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + y, (x, y)) +# (tensor([1.]), tensor([1.])) +# +# HOW TO DEDUPLICATE: +# +# There are a few strategies, in order of preference: +# +# 1. For every duplicate argument to the function, detach it into +# a separate leaf tensor, so that it is no longer duplicated. +# +# PRO: The resulting compiled graph works for any configuration +# of duplicated arguments. +# +# CON: It does not (naively) work if you mutate the metadata of inputs: +# +# def f(x, y): +# x.transpose_(0, 1) +# y.transpose_(0, 2) +# +# x = torch.randn(2, 3, 4) +# f(x, x) +# +# The ordering of the transposes inside f dictates whether or not +# you get [4, 2, 3] or [3, 4, 2]. This means that you cannot precompute +# what metadata mutations should get applied to each input; you need to +# assume they aren't duplicates (what we do today) or preserve +# the original metadata mutations exactly in order, so that they work +# for any duplicate configuration. +# +# CON: It does not (naively) work if you mutate the data of inputs. +# In particular, leaf tensors that require grad cannot be mutated, +# this makes it impossible to differentiate with respect to the original +# base. +# +# 2. For every duplicate argument to the function, remove it, so it is +# no longer part of the "true" signature: +# +# PRO: Implemented naively, it still works for metadata/data mutation. +# +# CON: The resulting compiled graph is duplicate-specialized: it only +# works if future calls duplicate arguments in exactly the same way. +# Horribly, Dynamo doesn't guard on this at the moment. But even if +# it did, you could still end up recompiling a bunch of each duplicate. +# +# Our strategy is to do (1) if we can, and do (2) otherwise, erroring if +# Dynamo's guards are not enough. In practice, this seems to cover +# everything. +# +@dataclass +class AOTDedupeWrapper(CompilerWrapper): + keep_arg_mask: list[bool] = field(default_factory=list) + add_dupe_map: list[int] = field(default_factory=list) + old_input_metadata: list[InputAliasInfo] = field(default_factory=list) + needs_post_compile: bool = True + + # NB: Hot path, avoid set lookups here + # TODO: Can avoid the zip here too, probably + def remove_dupe_args(self, args): + return [t for t, keep in zip(args, self.keep_arg_mask) if keep] + + def add_dupe_args(self, args): + return [args[i] for i in self.add_dupe_map] + + def pre_compile( + self, + flat_fn, + flat_args: list[Tensor], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + # Use information about whether or not flat_fn mutates its arguments + # or not to handle dupe args + + # Strategy 1: For any input that is not mutated, we can leafify it if we + # need to remove a duplicate. + leaf_flat_args = [] + args_set = set() + ok = True + + for i, a in enumerate(flat_args): + if not isinstance(a, torch.Tensor): + leaf_flat_args.append(a) + elif a not in args_set: + args_set.add(a) + leaf_flat_args.append(a) + elif ( + not fw_metadata.input_info[i].mutates_data + and not fw_metadata.input_info[i].mutates_metadata + ): + leaf_flat_args.append(a.detach().requires_grad_(a.requires_grad)) + else: + ok = False + break + + if ok: + self.needs_post_compile = False + return flat_fn, leaf_flat_args, fw_metadata + + if requires_subclass_dispatch(leaf_flat_args, fw_metadata): + raise RuntimeError( + """\ + Encountered duplicate inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + # export path: ban duplicate inputs for now, add later if requested. + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered duplicated inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + fw_metadata={str(fw_metadata)} + """ + ) + + # Strategy 2: Duplicate specialize. + # + # In Haskell types, suppose you have: + # + # add_dupe_args :: DedupedArgs -> Args + # remove_dupe_args :: Args -> DedupedArgs + # + # compiler_fn + # :: (DedupedArgs -> R) -> DedupedArgs -> AOTConfig -> (DedupedArgs -> R) + # deped_compiler_fn + # :: (Args -> R) -> Args -> AOTConfig -> (Args -> R) + # + # Then the code below can be written in point-free style as: + # + # deduped_compiler_fn f a c = + # compiler_fn (f . add_dupe_args) (remove_dupe_args a) c . remove_dupe_args + # + # Suppose you have: + # + # [a, b, a, c] + # + # We want: + # + # remove_dupe_args([a, b, a, c]) == [a, b, c] + # add_dupe_args([a, b, c]) == [a, b, a, c] + # + # This is done via (respectively): + # + # seen_args = {a: 0, b: 1, c: 2} + # enumerate(add_dupe_map) = [ # how to get args from the deduped list + # (0, 0), + # (1, 1), + # (2, 0), + # (3, 2), + # ] + # keep_arg_mask = [True, True, False, True] + + seen_args: dict[Tensor, int] = {} + # Implicitly map duped arg position (list index) to de-duped arg position + keep_arg_mask: list[bool] = [] + add_dupe_map: list[int] = [] + duped_arg_len = len(flat_args) + + j = 0 # index into deduped_flat_args + for t in flat_args: + if isinstance(t, torch.Tensor): + if t in seen_args: + keep_arg_mask.append(False) + add_dupe_map.append(seen_args[t]) + continue + seen_args[t] = j + + keep_arg_mask.append(True) + add_dupe_map.append(j) + j += 1 + assert ( + len(add_dupe_map) == duped_arg_len + ), f"Expects add_dupe_map to have length {duped_arg_len} but got {len(add_dupe_map)}" + + self.keep_arg_mask = keep_arg_mask + self.add_dupe_map = add_dupe_map + + deduped_flat_args = self.remove_dupe_args(flat_args) + + # Update our input metadata to remove duped input metadata. + updated_fw_metadata = remove_dupe_metadata( + fw_metadata, keep_arg_mask, add_dupe_map + ) + + if ( + tracing_context := TracingContext.try_get() + and aot_config.aot_autograd_arg_pos_to_source + ): + # TODO(voz): This structure is 1:1, we could consider an alternate structure like + # kept_pos:[dupe_arg_pos], however, add_dupe_map is 1:1 so we would need a new structure there, + # which feels like needless complexity for a tiny bit of efficiency at this point. + for dupe_arg_pos, (kept_pos, keep_arg) in enumerate( + zip(add_dupe_map, keep_arg_mask) + ): + if not keep_arg: + dupe_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + dupe_arg_pos + ] + kept_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + kept_pos + ] + tracing_context.guards_context.aotautograd_guards.append( # type: ignore[attr-defined] + DuplicateInputs(kept_arg_source, dupe_arg_source) + ) + + @wraps(flat_fn) + def wrapped_flat_fn(*args): + return flat_fn(*self.add_dupe_args(args)) + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + wrapped_flat_fn, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + is_train=fw_metadata.is_train, + )(*deduped_flat_args) + assert ( + ref_fw_metadata == updated_fw_metadata + ), f"ref_metadata={str(ref_fw_metadata)}, actual_metadata={str(updated_fw_metadata)}" + + return wrapped_flat_fn, deduped_flat_args, updated_fw_metadata + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + if not self.needs_post_compile: + return compiled_fn + + @wraps(compiled_fn) + def wrapped_compiled_fn(args: list[Any]): + deduped_args = self.remove_dupe_args(args) + args.clear() + return compiled_fn(deduped_args) + + wrapped_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + # This can be uncommented when we properly guard for duplicates, + # but right now we must not do it. + # if not config.debug_assert: + # return wrapped_compiled_fn + + @wraps(wrapped_compiled_fn) + def debugged_compiled_fn(args): + # Test that the computed remove/add arg functions are an inverse + new_args = self.add_dupe_args(self.remove_dupe_args(args)) + seen: dict[Any, None] = {} + for i, (x, y) in enumerate(zip(new_args, args)): + seen[y] = None + assert x is y, format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would be a duplicate of " + f"{describe_input(self.add_dupe_map[i], aot_config)}", + ) + # This is only an error if there is metadata mutation on both of + # the duped arguments; in this case, we need to know what order + # the metadata mutation applies in. You'll get the correct result + # otherwise, because a graph that assumes distinct inputs works if + # you dupe the inputs (the gradient contributions from each input + # will get summed up appropriately.) + # + # TODO: work out how to setup this assert correctly + """ + assert len(seen) == unique_args, format_guard_bug_msg(aot_config, + f"there would be {unique_args} distinct arguments" + ) + """ + return wrapped_compiled_fn(args) + + debugged_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + return debugged_compiled_fn + + +# This layer handles the situation where you have two inputs that alias each other, +# and one of the inputs is mutated. +# We need to take special care to ensure that the mutation is applied to the other aliases in the graph. +# +# pre-condition: AOTDedupWrapper has already run. +# (This function will in theory work if there are duplicate args. +# However, the synthetic base code path is a bit sub-optimal, and running with dupe'd inputs +# would cause us to hit that path more frequently). +@dataclass +class AOTSyntheticBaseWrapper(CompilerWrapper): + # Currently, the only reason we need to plumb this bool is because + # the synthetic base code prohibits more cases in the autograd case than the inference case. + trace_joint: bool # TODO: refactor trace_joint + needs_post_compile: bool = True + aliased_arg_idx_with_metadata_mutations: list[int] = field(default_factory=list) + + def pre_compile( + self, + flat_fn, + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + is_inference = not self.trace_joint + flat_args_with_synthetic_bases, synthetic_base_info = merge_view_inputs( + aot_config, + flat_args, + fw_metadata.input_info, + is_inference=is_inference, + ) + + # Happy path: we don't need synthetic bases + if synthetic_base_info is None: + self.needs_post_compile = False + return flat_fn, flat_args, fw_metadata + + # export path: ban synthetic bases for now, add later if requested. + if requires_subclass_dispatch(flat_args, fw_metadata): + raise RuntimeError( + """\ + Encountered aliased inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered aliased inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + synthetic_base_info={str(synthetic_base_info)} + + fw_metadata={str(fw_metadata)} + """ + ) + + assert len(fw_metadata.input_info) == len(synthetic_base_info) + + # Update our forward metadata to take synthetic bases into account + ( + fw_metadata_updated, + aliased_arg_idx_with_metadata_mutations, + ) = create_synthetic_base_metadata( + fw_metadata, synthetic_base_info, flat_args, flat_args_with_synthetic_bases + ) + # Save old input args for post-compile + self.old_input_info = fw_metadata.input_info + + self.aliased_arg_idx_with_metadata_mutations = ( + aliased_arg_idx_with_metadata_mutations + ) + replay_views = config.view_replay_for_aliased_outputs + + def _unpack_synthetic_bases(primals: tuple[Any, ...]) -> list[Any]: + f_args_inner = [] + for inner_idx_or_tuple in synthetic_base_info: + if isinstance(inner_idx_or_tuple, int): + f_args_inner.append(primals[inner_idx_or_tuple]) + else: + inner_base_idx, view_tensor = inner_idx_or_tuple + base = primals[inner_base_idx] + view_arg = gen_alias_from_base( + base, + view_tensor, + view_tensor.requires_grad, + replay_views=replay_views, + ) + f_args_inner.append(view_arg) + return f_args_inner + + @wraps(flat_fn) + def wrapped_flat_fn(*args): + unpacked_args = _unpack_synthetic_bases(args) + # This is a bit subtle. The goal of this entire function (aot_dispatch_synthetic_bases) + # is to relieve the downstream logic from having to reason about mutations on inputs that alias + # each other, by replacing aliased inputs with a synthetic base. + # One area where this breaks down a bit however is if one of those aliased inputs + # experienced a metadata mutation. + # We are now obligated to reapply the metadata mutation directly to the user's input; + # it isn't enough to apply mutations back to the synthetic base in the downstream logic. + # + # The way we handle this is by pretending that those aliased inputs that experience metadata mutations + # are additional outputs in the user's forward function. + # The downstream logic will just treat these as "user outputs that alias inputs". + # However, we will manually grab them at runtime here, use them to reapply the metadata mutation + # to the user inputs, and not return them to the user. + aliased_args_with_metadata_mutations = [ + x + for i, x in enumerate(unpacked_args) + if i in self.aliased_arg_idx_with_metadata_mutations + ] + if len(aliased_args_with_metadata_mutations) > 0: + return *(flat_fn(*unpacked_args)), *aliased_args_with_metadata_mutations + else: + return flat_fn(*unpacked_args) + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + wrapped_flat_fn, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + is_train=fw_metadata.is_train, + )(*flat_args_with_synthetic_bases) + assert ref_fw_metadata == fw_metadata_updated, ( + f"ref_metadata={pprint.pformat(partial_flatten_asdict(ref_fw_metadata))}, " + f"\nactual_metadata={pprint.pformat(partial_flatten_asdict(fw_metadata_updated))}" + ) + return ( + wrapped_flat_fn, + flat_args_with_synthetic_bases, + fw_metadata_updated, + ) + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + if not self.needs_post_compile: + return compiled_fn + + is_inference = not self.trace_joint + + @wraps(compiled_fn) + def wrapped_compiled_fn(args): + args_with_synthetic_bases, synthetic_base_info = merge_view_inputs( + aot_config, args, self.old_input_info, is_inference=is_inference + ) + assert synthetic_base_info is not None + aliased_args_w_metadata_mutations = [ + args[i] for i in self.aliased_arg_idx_with_metadata_mutations + ] + num_aliased_args_with_metadata_mutations = len( + aliased_args_w_metadata_mutations + ) + args.clear() + outs = compiled_fn(args_with_synthetic_bases) + if num_aliased_args_with_metadata_mutations > 0: + # This code does not handle **all** input metadata mutations. + # Instead, it only handles metadata mutations on inputs that were converted into synthetic bases + # (which only happens if at least one aliased input experienced a data mutation). + # e.g: + # def f(a, b): + # a.mul_(2) + # b.t_(1, 0) + # f(x.view(2, 2), x.view(2, 2)) + mutated_metadata_inps = outs[-num_aliased_args_with_metadata_mutations:] + user_outs = outs[:-num_aliased_args_with_metadata_mutations] + for inp, mutated_inp in zip( + aliased_args_w_metadata_mutations, mutated_metadata_inps + ): + inp.as_strided_( + mutated_inp.size(), + mutated_inp.stride(), + mutated_inp.storage_offset(), + ) + return user_outs + return outs + + return wrapped_compiled_fn + + +# Note [Handling mutations on an input that aliases other inputs] +# The easiest example to show-case this edge case is here: +# +# def f(a, b): +# a.mul_(2) +# out = a + b +# return out +# b = torch.ones(...) +# a = b.view(-1) +# f(a, b) +# +# In this situation, if a and b happened to be aliased, we need to trace something different! +# Suppose we had b = a.view(-1) +# (In this case, that means that `a._base is b`) +# +# We need to ensure that the aliasing relationship between a and b is preserved. +# We do that detecting the specific situation above (mutate an input that aliases another input), +# and when we do that, we create a synthetic base argument. Then inside of the traced forward, +# we regenerate a and b off of that base. +# The complete example of the transformed function looks like this: +# +# // The traced forward takes in a synthetic base, and regenerates the aliased inputs as views +# // We could consider getting view-replay support here to minimize as_strided_scatter ops in the graph +# def traced_forward(base): +# a = base.as_strided(...) +# b = base.as_strided(...) +# a_updated = a.mul(2) +# base_updated = torch.as_strided_scatter(base, a_updated, ...) +# b_updated = base_updated.as_strided(...) +# out = a_updated + b_updated +# return a_updated, out +# +# def compiled_fn(a, b): +# // we detect that a is the "differentiable base" here +# base = a +# // In other situations, we might do either: +# // (1) a and b are both views off of some larger differentiable base +# // assert a._base is b._base and a._base is not None +# // base = a._base +# // (2) a and b both don't require gradients. Create a base from the storage +# // assert a._base is None and b._base is None +# // base = torch.Tensor(a.storage()) +# a_updated, out = traced_forward(base) +# a.copy_(a_updated) +# return out +# +# This function: +# (1) Merges input views into a synthetic base argument, when any of those input views are mutated +# (2) Returns metadata telling the autograd.Function how to modify their arguments properly, +# to respect the new calling convention. +# +# The calling convention is as follows. +# Any inputs that were originally views of one another get yanked, and replaced with a synthetic base. +# The argument list ordering goes [base1, ..., baseN], [arg1, ..., argN], +# Where the ordering of the bases is determined from the ordering of the original view args. +# baseA will come before baseB if the earliest original argument coming from baseA +# showed up earlier in the argument list than the earliest original argument coming from baseB. +# +# Example, given some tensors a, b, c, d +# call site: +# f(a, c.view(-1), b.view(-1), b, c, d) +# Modified argument list: +# c_base comes first because the first c view came earlier in arg list than the first b view +# a and d still show up in the modified arg list, but b and c don't- they're regenerated from their bases +# b_base = torch.Tensor(b.storage()) +# c_base = torch.Tensor(c.storage()) +# f(c_base, b_base, a, d) +def merge_view_inputs( + aot_config: AOTConfig, + fwd_inputs: list[Any], + mutated_input_info: list[InputAliasInfo], + *, + # The autograd case currently has more restrictions than the inference case. + is_inference: bool, +) -> tuple[list[Any], Optional[list[Union[int, tuple[int, torch.Tensor]]]]]: + def _are_differentiable_views(view1, view2): + if view1 is view2: + return True + if view1._base is None and view2._base is None: + return False + if view1._base is view2._base or view1._base is view2 or view1 is view2._base: + return True + return False + + def _same_dtype_views(view1, view2): + if view1.dtype != view2.dtype: + return False + if view1._base is not None and view1.dtype != view1._base.dtype: + return False + if view2._base is not None and view2.dtype != view2._base.dtype: + return False + return True + + assert len(fwd_inputs) == len(mutated_input_info) + if not [info for info in mutated_input_info if info.mutates_data]: + # Return early when there are no mutations. + return fwd_inputs, None + + storage_ref_to_idx: dict[StorageWeakRef, list[int]] = collections.defaultdict(list) + base_args = [] + other_args = [] + for i, inpt in enumerate(fwd_inputs): + if isinstance(inpt, Tensor): + storage_ref = StorageWeakRef(inpt.untyped_storage()) + storage_ref_to_idx[storage_ref].append(i) + else: + other_args.append(inpt) + # Note [Synthetic Base Info Metadata] + # This list contains metadata that tells you what the i'th argument in the inner calling convention should be. + # It's either: + # - another int (corresponding to the index in the argument list of the element from the outer calling convention) + # - idx, view_tensor, where we can generate the new output with view_tensor._view_func(old_args[idx]) + # idx corresponds to which synthetic base from the outer calling context to view + inner_calling_convention_meta: dict[int, Union[int, tuple[int, torch.Tensor]]] = {} + for aliased_input_indices in storage_ref_to_idx.values(): + if len(aliased_input_indices) <= 1 or not any( + # We only care about mutations that affect all aliases, + # so metadata mutations on an input doesn't require us to do synthetic base handling. + mutated_input_info[inpt_idx].mutates_data + for inpt_idx in aliased_input_indices + ): + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # Here, we attempt to do a more complicated check to detect false aliasing + # (e.g. if all the tensors have the same storage, but don't actually overlap) + # In theory, we could have a large group of tensors that all share storages, where only *some* of them + # have overlapping memory. + # I don't bother with that case for now: here, we only bail out earlier if we detect that **every** pair + # of tensors in the current group that shares a storage is non-overlapping. + aliased_input_indices_no_false_sharing = compute_overlapping_inputs( + aot_config, fwd_inputs, aliased_input_indices + ) + if len(aliased_input_indices_no_false_sharing) <= 1: + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # We detected an input that was mutated, AND aliases with another input. + # we need to replace this set of aliased inputs with a single synthetic base. + # For now, I'm banning a bunch of cases. We expect dynamo to properly detect these cases + # and error out. We can fix them later. + # These checks are transitive, so we don't need to check every pair. + for idx1, idx2 in zip( + aliased_input_indices, aliased_input_indices[1:], strict=False + ): + view1 = fwd_inputs[idx1] + view2 = fwd_inputs[idx2] + # The "inputs that are aliased but have different differentiable bases" case + # is more complicated and hopefully pretty rare. Not currently handled. + if not is_inference: + assert _are_differentiable_views( + view1, view2 + ), "aot_autograd() does not yet handle non-differentiable view input mutations." + # Regenerating views when reinterpreting complex / real tensors seems non-trivial, + # not handling for now + assert _same_dtype_views( + view1, view2 + ), "aot_autograd() does not yet handle input mutations on views with different dtypes." + non_none_bases = [ + fwd_inputs[i]._base + for i in aliased_input_indices + if fwd_inputs[i]._base is not None + ] + aliases_with_none_bases = [ + fwd_inputs[i] for i in aliased_input_indices if fwd_inputs[i]._base is None + ] + if len(non_none_bases) == 0: + # Case where none of the aliases have a ._base + # we generate a synthetic base without gradients, and generate views off of it + # We hit this case when we have input tensors to the graph that share a storage, + # but do not have a ._base field. + # Wondering when we hit this case? + # The _base field simply says that autograd knows about the aliasing relationship, + # but sometimes we create tensors which are aliased out of the same storage but guaranteed + # to be disjoint. In these cases, we will skip setting up the _base relationship + # for performance reasons (because the fact that the tensors share the same storage + # is unobservable unless you (1) do naughty things with resize_/as_strided + # or (2) look at the storage--as we are doing here.) + # One particular example of this is optimizer steps on the LSTM module: + # LSTM parameters are packed into a contiguous storage for efficiency reasons when + # calling cuDNN kernels, so when these parameters get passed to the optimizer we will + # find they share the same storage, but do not have _base set since they are all disjoint. + # + # NOTE: There is one case where this is unsafe: + # torch.Tensor(storage) will ALWAYS create a 1D tensor, which is not necessarily + # the same shape as the "actual" base that the tensor came from. + # For the most part this is fine, because we always use as_strided() + # to generate the original aliased inputs again. + # If we were to use view-replay though, this could cause the aliased views + # to have incorrect sizes. + example_idx = aliased_input_indices[0] + example_alias = fwd_inputs[example_idx] + # Note that this function is re-used at both trace time and runtime. + # At trace time, we're under a FakeMode so synthetic_base becomes a FakeTensor. + synthetic_base = torch.empty( + (0,), dtype=example_alias.dtype, device=example_alias.device + ) + # We don't actually have a convenient way of going from storage -> tensor, + # So using set_() here (we suffer some minor overhead, but this case is rare). + synthetic_base.set_(example_alias.untyped_storage()) + else: + # Case where all of the aliases require gradients, and have the same _base. + synthetic_base = non_none_bases[0] + for other_base in non_none_bases[1:]: + assert ( + other_base is synthetic_base + ), "aot_autograd() does not yet handle non-differentiable view input mutations." + for alias in aliases_with_none_bases: + assert ( + alias is synthetic_base + ), "aot_autograd() does not yet handle non-differentiable view input mutations." + base_args.append(synthetic_base) + for curr_view_idx in aliased_input_indices: + curr_view = fwd_inputs[curr_view_idx] + base_idx = len(base_args) - 1 + # We store just enough info here so that we can regenerate the view later. + # Regeneration: curr_view._view_func(args[base_idx]) + inner_calling_convention_meta[curr_view_idx] = (base_idx, curr_view) + if len(base_args) == 0: + assert len(other_args) == len(fwd_inputs) + # If no synthetic bases are necessary, just return the original inputs. + return fwd_inputs, None + else: + from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr + + def make_hashable(arg): + if isinstance(arg, torch.SymInt): + # Since only nested SymInt objects can be hashed, we wrap them with + # SymIntEqByExpr, which is a hashable wrapper of SymInts. + return SymIntEqByExpr(arg) + return arg + + # Otherwise, return: + # (1) The new args according to the updated calling convention: (synthetic_bases, other_args) + # (2) Metadata telling functionalization how to generate the inner argument list given the outer calling convention. + # We post-process it into a list, where meta[i] tells you info about the i'th argument in the inner calling convention. + args_to_functionalization = base_args + other_args + arg_to_old_idx_map = { + make_hashable(arg): i for (i, arg) in enumerate(fwd_inputs) + } + for i, other_arg in enumerate(other_args): + new_idx = len(base_args) + i + old_idx = arg_to_old_idx_map[make_hashable(other_arg)] + inner_calling_convention_meta[old_idx] = new_idx + # post process into a list + post_processed_calling_convention_meta: list[ + Union[int, tuple[int, torch.Tensor]] + ] = [-1 for _ in range(len(inner_calling_convention_meta))] + for k, v in inner_calling_convention_meta.items(): + post_processed_calling_convention_meta[k] = v + # Quick assert: every argument in the inner calling convention should be accounted for. + for x in post_processed_calling_convention_meta: + assert x != -1 + return args_to_functionalization, post_processed_calling_convention_meta + + +@dataclass +class AutogradLazyBackwardCompileInfo: + bw_module: Callable + placeholder_list: list[Any] + saved_context: Optional[TracingContext] + saved_compile_context: Optional[CompileContext] + + +def _raise_if_functorch_active(): + # not ideal but prevent the user from seeing a nasty traceback - See #138422 + stack = torch._C._functorch.peek_interpreter_stack() + torch._check( + stack is None, + lambda: ( + "It looks like you're trying to call a compiled backward function within vmap/grad/vjp, " + "which isn't supported. Try wrapping vmap inside torch.compile, or skip compiling the " + "backward function." + ), + ) + + +# NOTE: this function must be torch._dynamo.allow_in_graph-able. Non tensor/symnode inputs must be constants. +def _backward_prologue_functional( + ctx_saved_tensors, ctx_symints, metadata, maybe_subclass_metadata, *flat_args +): + # Calling convention: we expect a grad_out passed to the backward: + # - for every output of the fw that does *not* alias an input or graph intermediate + # - for every updated_input generated by the fw that does *not* alias an input (aka only data-mutations) + # - for every graph intermediate that we need to use to generate an output later. + # The other outputs in the autograd.Function.forward that do *not* show up in the backward include: + # - outputs that alias inputs or graph intermediates + # - updated inputs due to metadata-only mutations. + # We need to return them in the forward, but ensure that they all do not get gradients in the backward, + # and we filter them out here before passing the remaining grad_outputs into the compiled backward. + _raise_if_functorch_active() + + num_intermediate_bases = metadata.num_intermediate_bases + num_mutated_runtime_inps = metadata.num_mutated_inp_runtime_indices + expected_grad_outs = ( + metadata.num_outputs + num_mutated_runtime_inps + num_intermediate_bases + ) + deterministic = metadata.deterministic + global_deterministic = torch.are_deterministic_algorithms_enabled() + if deterministic is not None: + torch._check( + not (not deterministic and global_deterministic), + lambda: ( + "This compiled backward function is being run with " + "torch.use_deterministic_algorithms(True), " + "but it was previously generated during the forward function while " + "torch.use_deterministic_algorithms(False) was set." + ), + ) + + assert len(flat_args) == expected_grad_outs + out_info = metadata.output_info + + inp_tangents, out_tangents, intermediate_base_tangents = ( + flat_args[:num_mutated_runtime_inps], + flat_args[ + num_mutated_runtime_inps : num_mutated_runtime_inps + metadata.num_outputs + ], + flat_args[num_mutated_runtime_inps + metadata.num_outputs :], + ) + # input_info contains info on *every* input, + # But in the backward(), we are only given grad outputs for every mutated input + # We then need to filter out the grad outputs that correspond to metadata-only mutations or don't require grad + input_info = metadata.input_info + inp_tangents_filtered = [ + x + for x, info_idx in zip( + inp_tangents, + metadata.mutated_inp_runtime_indices, + ) + if input_info[info_idx].mutates_data and input_info[info_idx].requires_grad + ] + # We also need to filter out grad outputs that correspond to outputs aliasing inputs/intermediates + out_tangents_filtered = [ + x + for x, info in zip(out_tangents, out_info) + if info.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + and issubclass(info.raw_type, torch.Tensor) + and info.requires_grad + ] + # intermediate bases always require gradients, and always participate in the backward graph. + flat_bw_args_with_grads = [ + *inp_tangents_filtered, + *out_tangents_filtered, + *intermediate_base_tangents, + ] + num_flat_bw_args_with_grads = len(flat_bw_args_with_grads) + + # sanity asserts + # metadata_only_inps = [ + # x for x, info_idx in zip(inp_tangents, mutated_inp_indices) + # if not input_info[info_idx].mutates_data + # ] + # aliased_outputs = [ + # x for x, info in zip(out_tangents, out_info) if info.output_type != OutputType.non_alias] + # assert all(x is None for x in metadata_only_inps) + # assert all(x is None for x in aliased_outputs) + # TODO: replace this with FunctionalizedRngRuntimeWrapper + rng_args = [] + if metadata.is_rng_op_functionalized: + # Add the seed and offset to args + rng_args = CUDARngStateHelper.get_torch_state_as_tuple() + + bw_tokens = [None] * metadata.num_backward_tokens + + # - note: donated buffer logic requires (*ctx.symints, *ctx.saved_tensors) showing up first + # in the bw output order. + + # Every dereference of ctx.saved_tensors incurs saved_tensors_hooks calls + # There are tests that count these calls, saving to var. + num_ctx_saved_tensors = len(ctx_saved_tensors) + all_args = [ + *ctx_symints, + *ctx_saved_tensors, + *flat_bw_args_with_grads, + *bw_tokens, + *rng_args, + ] + del ctx_saved_tensors + + # Note: [AOTAutograd Backward Guards] + # During AOTDispatch, we eagerly create and trace out a joint fw-bw graph. + # Doing so requires us to "guess" about some of the metadata of our grad_outputs. + # + # In particular: if an output to the forward is a plain tensor or a subclass, + # its corresponding grad_output in the backward **may or may not** be + # a plain tensor or a subclass. The main cases are: + # (1) If an output is a plain tensor, its grad_out will also be a plain tensor, + # *unless* the output is used in some subclass compute later in the forward graph, + # which will cause its grad_output to become a subclass + # (2) If an output is a subclass, its grad_out will also be a subclass, + # *unless* the output of the forward did not actually participate in the gradient computation, + # in which case autograd will insert a plain tensor of zeros for the grad_output. + # We could avoid this case with `torch.autograd.Function.set_materialize_grads`, + # although this is not turned on today in AOTAutgrad and would require more work. + # + # Today, we make a guess on subclass-ness based on the above examples, + # and hard-error in the backward if we guessed wrong. + # + # In the future, we should add backward guards that would allow us to + # properly handle this case instead of erroring: we would need to retrace the backward graph, + # since we might produce an entirely different trace if our grad_outputs are subclass or not. + del flat_bw_args_with_grads + + tangents_start_idx = ( + len(all_args) - num_flat_bw_args_with_grads - len(rng_args) - len(bw_tokens) + ) + assert tangents_start_idx == len(ctx_symints) + num_ctx_saved_tensors + tangents_end_idx = len(all_args) - len(rng_args) - len(bw_tokens) + + # TODO: figure out how to refactor the backward properly + # so I can use aot_dispatch_subclass_wrapper() here. + if maybe_subclass_metadata is not None: + tangents = all_args[tangents_start_idx:tangents_end_idx] + + if len(tangents) != len(metadata.subclass_tangent_meta): + raise RuntimeError( + "The grad inputs should be same number as forward output tangents" + ) + + flat_processed_tangents = list( + itertools.chain.from_iterable( + ( + AOTDispatchAutograd.process_runtime_tangent( + t, + m, + )[1] + ) + for t, m in zip( + tangents, + metadata.subclass_tangent_meta, + ) + ) + ) + + all_args = ( + runtime_unwrap_tensor_subclasses( + all_args[:tangents_start_idx], + # SymInts that are inputs to the backward graph are + # already included in the "all_args" list. + # Any symints coming from tensor subclasses should always + # come from primals, and so they will show up as extra + # arguments to the forward graph, and they will be saved + # as activation in the backward graph. + append_symints=False, + ) + + flat_processed_tangents + + runtime_unwrap_tensor_subclasses( + all_args[tangents_end_idx:], + append_symints=False, + ) + ) + else: + all_args = [ + ( + AOTDispatchAutograd.process_runtime_tangent( + t, + metadata.subclass_tangent_meta[i - tangents_start_idx], + )[0] + if (tangents_start_idx <= i < tangents_end_idx) + else t + ) + for i, t in enumerate(all_args) + ] + + # Backward with forward inputs mutations is not supported in double backward. + if ( + torch.is_grad_enabled() + and metadata.indices_of_inputs_that_requires_grad_with_mutations_in_bw + ): + raise RuntimeError( + "aot_autograd does not support input mutations with requires_grad in backward for create_graph=True" + ) + + return all_args + + +def initialize_rng_states( + num_rng: int, + graphsafe_idx: int, + fwd_rng_states: list[torch.Generator], + bwd_rng_states: list[torch.Generator], +): + """ + Initialize the cudagraph safe rng states. + + Initialization of rng states should have a few properties: + - the initialization for each rng state should be independent + - the initialization should be deterministic + - the initialization should be based off current rng state, so that independent graphs do not + have equal rng behavior + + We defer initialization of rng states until runtime because compilation is wrapped + with preserve_rng_states. Seed initialization should advance the rng states so consecutive compilations + do not give equal randomness. + """ + with torch.utils._python_dispatch._disable_current_modes(): + seeds = torch.randint(0, torch.iinfo(torch.int64).max, (num_rng,), device="cpu") + fwd_rng_states.extend( + [ + torch.cuda.default_generators[graphsafe_idx] + .clone_state() + .manual_seed(int(seeds[i])) + for i in range(num_rng) + ] + ) + bwd_rng_states.extend( + [ + torch.cuda.default_generators[graphsafe_idx] + .clone_state() + .manual_seed(int(seeds[i])) + for i in range(num_rng) + ] + ) + + +# NOTE: this function must be torch._dynamo.allow_in_graph-able. Non tensor/symnode inputs must be constants. +def _backward_epilogue_functional( + metadata, maybe_subclass_metadata, out, *, make_subclass_override=None +): + # Toss out the backward output tokens + num_bw_tokens = metadata.num_backward_tokens + if num_bw_tokens > 0: + out = out[:-num_bw_tokens] + + # TODO: replace this with FunctionalizedRngRuntimeWrapper.post_compile + out = FunctionalizedRngRuntimeWrapper()._functionalized_rng_runtime_epilogue( + metadata, out, offset_index=len(out) - 1 + ) + out = tuple(out) + + # TODO: figure out how to refactor the backward properly so I can use aot_dispatch_subclass_wrapper() here. + if maybe_subclass_metadata is not None: + assert maybe_subclass_metadata.grad_input_metas is not None + outs_wrapped = wrap_tensor_subclasses( + out, + subclass_metas=maybe_subclass_metadata.grad_input_metas, + included_subclass_symints=True, + is_runtime=True, + make_subclass_override=make_subclass_override, + ) + return outs_wrapped + return out + + +# This is wrapped in a class just for namespacing purposes +# No need to make it into an actual CompilerWrapper because it doesn't fit the abstract as cleanly +class AOTDispatchAutograd: + @staticmethod + def process_runtime_tangent(x, meta: Union[PlainTensorMeta, SubclassCreationMeta]): + if not isinstance(x, torch.Tensor): + return x, [x] + + if isinstance(x, FakeTensor): + if not x.is_contiguous(memory_format=meta.memory_format): + x = x.contiguous(memory_format=meta.memory_format) + return x, [x] + + expected_type: Optional[type] = torch.Tensor + expected_meta = None + if isinstance(meta, SubclassCreationMeta): + expected_type = meta.original_subclass_type + expected_meta = meta.meta + + runtime_type = type(x) + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + # When we're inside compiled autograd's AOTDispatcher step, + # regular Tensors look like FunctionalTensors. + # Tensor subclasses still look like Tensor subclasses though. + if isinstance(x, torch._subclasses.functional_tensor.FunctionalTensor): + runtime_type = torch.Tensor + + runtime_meta = None + runtime_subclass_keys: Sequence[str] = [] + + if is_traceable_wrapper_subclass(x): + runtime_subclass_keys, runtime_meta = x.__tensor_flatten__() + + def maybe_coerce(x): + same_type: bool = expected_type == runtime_type + same_meta: bool = expected_meta == runtime_meta + + if same_type and same_meta: + return x + + if not hasattr(x, "__coerce_same_metadata_as_tangent__"): + return None + + if same_type: + # Backward Compatibility, as some Subclass impls can have original 1-arg function. + return x.__coerce_same_metadata_as_tangent__(expected_meta) + + return x.__coerce_same_metadata_as_tangent__(expected_meta, expected_type) + + # Coerce to expected type and metadata + orig_x = x + x = maybe_coerce(x) + if x is None: + raise RuntimeError( + f""" +During the backward, we encountered a tensor subclass where we guessed its +metadata incorrectly. + +Expected metadata: {str(expected_meta)}, expected type: {str(expected_type)} + +Runtime metadata: {str(runtime_meta)}, runtime type: {str(runtime_type)} + +shape: {str(orig_x.shape)} +To fix this, your tensor subclass must implement the dunder method __force_to_same_metadata__. +""" + ) + + # Coerce to expected memory format + if not x.is_contiguous(memory_format=meta.memory_format): + x = x.contiguous(memory_format=meta.memory_format) + + if not is_traceable_wrapper_subclass(x): + return x, [x] + + assert isinstance(meta, SubclassCreationMeta) + if orig_x is not x: + runtime_subclass_keys = x.__tensor_flatten__()[0] + + assert len(meta.attrs) == len(runtime_subclass_keys) + leaves = [] + for i, (attr, attr_meta) in enumerate(meta.attrs.items()): + elem = getattr(x, attr) + new_elem, elem_leaves = AOTDispatchAutograd.process_runtime_tangent( + elem, attr_meta + ) + if new_elem is not elem: + setattr(x, attr, new_elem) + leaves.extend(elem_leaves) + + return x, leaves + + @staticmethod + def post_compile( + compiled_fw_func, # fw_module after compilation + wrappers + compiled_bw_func, # bw_module after compilation + wrappers + maybe_subclass_meta: Optional[SubclassMeta], + num_symints_saved_for_bw_: int, + backward_state_indices: list[int], + disable_amp: bool, + indices_of_inps_to_detach: list[int], + lazy_backward_info: Optional[AutogradLazyBackwardCompileInfo], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, # runtime metadata + try_save_cache_entry: Optional[Callable], # Save cache entry after compilation + ): + # For additional context see Note [CUDA Graph Safe RNG Functionalization] + # Each pair forward, backward rng states must be equal prior to its invocation on any + # iteration of forward, backward. Because they are initialized equal, and are computing the same rng op, + # running forward then backward advances them the same amount and keeps them equal. + # However, a user may invoke multiple forwards, then backwards, such that they are not in sync. + # Initially we have: + # fwd_state0 == bwd_state0. + # Lets say we run: + # fwd0: fwd_state0 -> fwd_state1 + # fwd1: fwd_state1 -> fwd_state2 + # fwd2: fwd_state2 -> fwd_state3 + # If we now invoke bwd2, + # we need to update bwd_state equal to the rng that was observed in fwd2. + # we save the rng_state fwd_state2 in forward because we detect that it is not the + # current backward state and therefore would not be accessible if we do not save it. + # Similarly, if we are going to update the backward state to a new value, and there is a pending + # forwards which needs its current state, we will save it. + # Within the autograd context, we keep track of the curr iteration so that on backward + # we know what the generator state must be before the backward is run. + num_rng = fw_metadata.num_graphsafe_rng_states + graphsafe_idx = fw_metadata.graphsafe_rng_state_index + fwd_rng_states: list[torch.Generator] = [] + bwd_rng_states: list[torch.Generator] = [] + curr_fwd_iter = itertools.count(0) + backward_state_position = 0 + pending_forwards: set[int] = set() + saved_backward_tensor_states: dict[int, list[torch.Tensor]] = {} + + class CompiledFunction(torch.autograd.Function): + compiled_fw = compiled_fw_func + compiled_bw = compiled_bw_func + metadata: ViewAndMutationMeta = fw_metadata # type: ignore[assignment] + maybe_subclass_metadata: Optional[SubclassMeta] = maybe_subclass_meta + num_symints_saved_for_bw = num_symints_saved_for_bw_ + _aot_id = aot_config.aot_id + _lazy_backward_info = lazy_backward_info + + @staticmethod + def _compiled_autograd_key(ctx): + return (ctx._autograd_function_id, *ctx.symints) + + @staticmethod + def forward(ctx, *deduped_flat_tensor_args): + args = deduped_flat_tensor_args + if backward_state_indices: + bw_state = args[backward_state_indices[0]] + assert isinstance(bw_state, BackwardState) + ctx._compiled_autograd_backward_state = bw_state + + if num_rng: + if len(fwd_rng_states) == 0: + assert graphsafe_idx is not None + initialize_rng_states( + num_rng, graphsafe_idx, fwd_rng_states, bwd_rng_states + ) + + _curr_iter = next(curr_fwd_iter) + ctx._curr_iter = _curr_iter + + # if this state is not contained in the backward, + # we need to save it for when its backward pass happens + if _curr_iter != backward_state_position: + saved_backward_tensor_states[_curr_iter] = [ + rng_state.get_state() for rng_state in fwd_rng_states + ] + + pending_forwards.add(_curr_iter) + args = (*args, *fwd_rng_states) + + # There is a pretty complicated calling convention around what the compiled fw returns. + # The full list of outputs and their relative order is: + # (*tokens, *mutated_inputs, *fw_outs, *fw_intermediate_bases, *saved_tensors, *saved_symints) + # - Note that in the synthetic bases case, mutated_inputs will correspond to an updated version + # of the original view, and not the synthetic base + # - Note that donated buffer logic requires (*saved_tensors, *saved_symints) showing up last + # in the fw output order. + fw_outs = call_func_at_runtime_with_args( + CompiledFunction.compiled_fw, + args, + disable_amp=disable_amp, + ) + + num_outputs = CompiledFunction.metadata.num_outputs + num_outputs_aliased = CompiledFunction.metadata.num_outputs_aliased + num_mutated_runtime_inps = ( + CompiledFunction.metadata.num_mutated_inp_runtime_indices + ) + num_forward_returns = CompiledFunction.metadata.num_forward_returns + + # Partitioners must put symint arguments at the end separate from tensor arguments + tensors_saved_for_backwards = fw_outs[ + CompiledFunction.metadata.tensors_saved_for_backwards_slice + ] + assert all( + isinstance(x, torch.Tensor) for x in tensors_saved_for_backwards + ) + # See Note [Detaching saved tensors in AOTAutograd] + ctx.save_for_backward( + *( + x.detach() if x._is_view() else x + for x in tensors_saved_for_backwards + ) + ) + symint_outs = fw_outs[ + CompiledFunction.metadata.symints_saved_for_backwards_slice + ] + assert all( + isinstance(x, (int, float, torch.SymInt, torch.SymFloat)) + for x in symint_outs + ), str([type(x) for x in symint_outs]) + ctx.symints = symint_outs + + raw_returns = fw_outs[0:num_forward_returns] + + # Wrap all autograd.Function.forward() outputs that are aliases + # so that autograd.Function doesn't treat them as tensors + if num_mutated_runtime_inps > 0: + for i, idx in enumerate( + CompiledFunction.metadata.mutated_inp_runtime_indices + ): + # We could make this faster by only looping over inputs with metadata-only mutations + # (instead of looping over inputs with either data or metadata mutations), but there shouldn't be many. + info = CompiledFunction.metadata.input_info[idx] + if info.mutates_metadata and not info.mutates_data: + raw_return_idx = i + raw_returns[raw_return_idx] = TensorAlias( + raw_returns[raw_return_idx] + ) + + if config.debug_assert: + user_mutated_inputs_raw = raw_returns[ + 0:num_mutated_runtime_inps + ] + mut_inp_infos = [ + x + for x in CompiledFunction.metadata.input_info + if x.mutates_data or x.mutates_metadata + ] + assert len(user_mutated_inputs_raw) == len(mut_inp_infos) + + if CompiledFunction.metadata.num_unsafe_view_outputs > 0: + for idx in CompiledFunction.metadata.unsafe_view_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + o = raw_returns[raw_return_idx] + raw_returns[raw_return_idx] = torch.ops.aten._unsafe_view( + o, o.shape + ) + + if num_outputs_aliased > 0: + for idx in CompiledFunction.metadata.aliased_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + raw_returns[raw_return_idx] = TensorAlias( + raw_returns[raw_return_idx] + ) + + if config.debug_assert: + intermediates_raw = raw_returns[ + num_mutated_runtime_inps + num_outputs : + ] + assert not any( + isinstance(x, TensorAlias) for x in intermediates_raw + ) + + # invariant: intermediate bases always require gradients, so we don't have to + # consider marking them as non-differentiable. + raw_returns_not_including_intermediate_bases = raw_returns[ + : num_mutated_runtime_inps + num_outputs + ] + raw_returns_meta = [ + x + for x in CompiledFunction.metadata.input_info + if x.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + CompiledFunction.metadata.output_info + + fw_outs_not_requiring_grad = [ + x + for (i, x) in enumerate( + raw_returns_not_including_intermediate_bases + ) + if isinstance(x, torch.Tensor) + and not raw_returns_meta[i].requires_grad + ] + ctx.mark_non_differentiable(*fw_outs_not_requiring_grad) + ctx._materialize_non_diff_grads = False + return tuple(raw_returns) + + @staticmethod + def backward(ctx, *flat_args): + all_args = _backward_prologue_functional( + ctx.saved_tensors, + ctx.symints, + CompiledFunction.metadata, + CompiledFunction.maybe_subclass_metadata, + *flat_args, + ) + + if num_rng: + nonlocal backward_state_position, bwd_rng_states + curr_backward_iter = ctx._curr_iter + retain_graph = ( + torch._C._autograd._get_current_graph_task_keep_graph() + ) + + # Save current state if we have a pending forward that needs this state + # or this state may be needed again because of retain graph + if ( + backward_state_position in pending_forwards + and backward_state_position not in saved_backward_tensor_states + and ( + backward_state_position != curr_backward_iter + or retain_graph + ) + ): + saved_backward_tensor_states[backward_state_position] = [ + rng_state.get_state() for rng_state in bwd_rng_states + ] + + # Restore saved states if needed + if curr_backward_iter in saved_backward_tensor_states: + if backward_state_position != curr_backward_iter: + for bwd_state, saved_state in zip( + bwd_rng_states, + saved_backward_tensor_states[curr_backward_iter], + ): + bwd_state.set_state(saved_state) + if not retain_graph: + del saved_backward_tensor_states[curr_backward_iter] + else: + assert backward_state_position == curr_backward_iter + + backward_state_position = curr_backward_iter + 1 + if not retain_graph: + pending_forwards.remove(curr_backward_iter) + all_args.extend(bwd_rng_states) + + def impl_fn(double_ctx=None): + out = CompiledFunction._backward_impl(ctx, all_args) + return _backward_epilogue_functional( + CompiledFunction.metadata, + CompiledFunction.maybe_subclass_metadata, + out, + ) + + needs_grad = torch.is_grad_enabled() and any( + t.requires_grad for t in all_args if isinstance(t, torch.Tensor) + ) + if needs_grad: + # double backward + return CompiledFunction._double_backward(ctx, impl_fn, all_args) + else: + return impl_fn() + + @staticmethod + def _double_backward(ctx, impl_fn, all_args): + # Ensure that the graph is connected, and error if double backward is performed. + # See comment for why once_differentiable is not sufficient: + # https://github.com/pytorch/pytorch/pull/92348/files#r1072962107 + class CompiledFunctionBackward(torch.autograd.Function): + # CompiledFunctionBackward is not yet supported in dynamo skipfiles + _aot_id = aot_config.aot_id + + @staticmethod + def forward(double_ctx, *unused_args): + return impl_fn(double_ctx) + + @staticmethod + def backward(double_ctx, *args): + raise RuntimeError( + "torch.compile with aot_autograd does not currently support double backward" + ) + + CompiledFunctionBackward._compiled_autograd_key = ( # type: ignore[method-assign] + CompiledFunction._compiled_autograd_key + ) + + return CompiledFunctionBackward.apply(*all_args) + + @staticmethod + def _backward_impl(ctx, all_args): + # compiled autograd reimplements this function at proxy_call_aot_backward + assert ( + not backward_state_indices + ), "BackwardState requires CompiledAutograd" + ctx.maybe_clear_saved_tensors() + + saved_tensors_use_once = ( + not torch._C._autograd._get_current_graph_task_keep_graph() + ) + + if CompiledFunction.compiled_bw is None: + assert lazy_backward_info is not None + + if not saved_tensors_use_once: + fw_metadata.bw_donated_idxs = [] + # Update bw_donated_idxs if using lazy_backward_info from `aot_dispatch_autograd` + if ( + hasattr(lazy_backward_info, "saved_context") + and hasattr(lazy_backward_info.saved_context, "fw_metadata") + and hasattr( + lazy_backward_info.saved_context.fw_metadata, # type: ignore[union-attr] + "bw_donated_idxs", + ) + ): + lazy_backward_info.saved_context.fw_metadata.bw_donated_idxs = ( # type: ignore[union-attr] + [] + ) + + bw_module = lazy_backward_info.bw_module + placeholder_list = lazy_backward_info.placeholder_list + saved_context = lazy_backward_info.saved_context + saved_compile_context = lazy_backward_info.saved_compile_context + + context = torch._C._DisableAutocast if disable_amp else nullcontext + metrics_context = get_metrics_context() + with tracing(saved_context), compile_context( + saved_compile_context + ), context(), track_graph_compiling( + aot_config, "backward" + ), metrics_context, dynamo_timed( + "backward._backward_impl", + phase_name="entire_backward_compile", + log_pt2_compile_event=True, + dynamo_compile_column_us="backward_cumulative_compile_time_us", + ): + CompileEventLogger.compilation_metric(is_forward=False) + CompiledFunction.compiled_bw = aot_config.bw_compiler( + bw_module, placeholder_list + ) + # Maybe save cache entry + if try_save_cache_entry is not None: + # CompiledFunction.metadata + # CompiledFunction.maybe_subclass_metadata + # bw_module + try_save_cache_entry( + CompiledFunction.compiled_bw, + fw_metadata, + aot_config, + ) + + if ( + torch._functorch.config.donated_buffer + and not saved_tensors_use_once + and fw_metadata.bw_donated_idxs != [] + ): + torch._check( + False, + lambda: ( + "This backward function was compiled with non-empty donated " + "buffers which requires create_graph=False and retain_graph=False. " + "Please keep backward(create_graph=False, retain_graph=False) " + "across all backward() function calls, or set " + "torch._functorch.config.donated_buffer=False to disable " + "donated buffer." + ), + ) + + out = call_func_at_runtime_with_args( + CompiledFunction.compiled_bw, + all_args, + steal_args=True, + disable_amp=disable_amp, + ) + return out + + compiled_function = RuntimeWrapper( + indices_of_inps_to_detach=indices_of_inps_to_detach, + trace_joint=True, + disable_amp=disable_amp, + ).post_compile( + CompiledFunction.apply, + aot_config, + runtime_metadata=fw_metadata, + ) + + return compiled_function + + +@dataclass +class DebugAssertWrapper(CompilerWrapper): + flat_requires_grad: list[Optional[bool]] = field(default_factory=list) + + def post_compile( + self, + compiled_fn, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ): + @wraps(compiled_fn) + def debug_compiled_function(args: list[Any]): + # TODO: Check aliasing relationships + # TODO: Check strides for metadata mutation + # (NB: ideally, this logic is factored out of this function and + # you move these debug checks there) + + # Check requires grad. Bad case is when we compiled with + # requires_grad = False, but input requires_grad = True + # (vice versa is OK; we compute a gradient and then throw + # it away when it hits the input.) + for i, a in enumerate(args): + can_require_grad = self.flat_requires_grad[i] + if can_require_grad is None: + assert not isinstance(a, Tensor) + elif not can_require_grad: + assert not a.requires_grad, format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would not require grad", + ) + + return compiled_fn(args) + + return debug_compiled_function + + +def pre_compile( + wrappers: list[CompilerWrapper], + flat_fn: Callable, + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[Callable, list[Tensor], ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function and arguments. + Mutates wrappers in place. + """ + for wrapper in wrappers: + flat_fn, flat_args, fw_metadata = wrapper.pre_compile( + flat_fn, flat_args, aot_config, fw_metadata=fw_metadata + ) + return flat_fn, flat_args, fw_metadata + + +def post_compile( + wrappers: list[CompilerWrapper], + compiled_fn: Callable, + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, +) -> tuple[Callable, ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function. Should be called after pre_compile() + """ + for wrapper in reversed(wrappers): + compiled_fn = wrapper.post_compile( + compiled_fn, aot_config, runtime_metadata=runtime_metadata + ) + return compiled_fn, runtime_metadata + + +def make_runtime_safe( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: Optional[SubclassMeta], +): + """ + Calls make_runtime_safe on all ViewAndMutationMetas. + Modifies both arguments. Allows ViewAndMutationMetas to + be safely cached in AOTAutogradCache. + """ + fw_metadata.make_runtime_safe() + if maybe_subclass_meta is not None: + maybe_subclass_meta.fw_metadata.make_runtime_safe() + if maybe_subclass_meta.grad_input_metas: + for meta in maybe_subclass_meta.grad_input_metas: + if isinstance(meta, SubclassCreationMeta): + meta.make_runtime_safe() diff --git a/shared/package-files/06/06c4a5745f03c817f863a63c798609a6197c83dcf65d4a3b141ade8368a653bf/hub.cpython-311.pyc b/shared/package-files/06/06c4a5745f03c817f863a63c798609a6197c83dcf65d4a3b141ade8368a653bf/hub.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6128088396ae4d2f2a7b47585835446ecf93a1 Binary files /dev/null and b/shared/package-files/06/06c4a5745f03c817f863a63c798609a6197c83dcf65d4a3b141ade8368a653bf/hub.cpython-311.pyc differ diff --git a/shared/package-files/06/06c707fc66b30196dba2d75d5732f946669f6d0f908d1c7c7fe2353b4d48056f/host_config.h b/shared/package-files/06/06c707fc66b30196dba2d75d5732f946669f6d0f908d1c7c7fe2353b4d48056f/host_config.h new file mode 100644 index 0000000000000000000000000000000000000000..785bec4e5c0652f9605ccf9341b7f761a85471ab --- /dev/null +++ b/shared/package-files/06/06c707fc66b30196dba2d75d5732f946669f6d0f908d1c7c7fe2353b4d48056f/host_config.h @@ -0,0 +1,65 @@ +/* + * Copyright 1993-2018 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("host_config.h is an internal header file and must not be used directly. This file will be removed in a future CUDA release. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "host_config.h is an internal header file and must not be used directly. This file will be removed in a future CUDA release. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H_WRAPPER__ +#endif + +#include "crt/host_config.h" + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H_WRAPPER__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H_WRAPPER__ +#endif diff --git a/shared/package-files/06/06cca037270b27893c0b99ceb882d470f3e1b6f054bc92d5af70a5318ff35746/_adafactor.py b/shared/package-files/06/06cca037270b27893c0b99ceb882d470f3e1b6f054bc92d5af70a5318ff35746/_adafactor.py new file mode 100644 index 0000000000000000000000000000000000000000..f499045dbbbc2f8abed3ba6b744c2f71278bf71b --- /dev/null +++ b/shared/package-files/06/06cca037270b27893c0b99ceb882d470f3e1b6f054bc92d5af70a5318ff35746/_adafactor.py @@ -0,0 +1,649 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +from typing import cast, Optional, TYPE_CHECKING, Union + +import torch +from torch import Tensor + +from .optimizer import ( + _disable_dynamo_if_unsupported, + _get_scalar_dtype, + _maximize_doc, + _params_doc, + Optimizer, + ParamsT, + TensorListList, +) + + +__all__ = ["Adafactor", "adafactor"] + + +class Adafactor(Optimizer): + def __init__( + self, + params: ParamsT, + lr: Union[float, Tensor] = 1e-2, + beta2_decay: float = -0.8, + eps: tuple[Optional[float], float] = (None, 1e-3), + d: float = 1.0, + weight_decay: float = 0.0, + *, + foreach: Optional[bool] = None, + maximize: bool = False, + ): + if isinstance(lr, Tensor) and lr.numel() != 1: + raise ValueError("Tensor lr must be 1-element") + if not 0.0 <= lr: + raise ValueError(f"Learning rate should be >= 0 but is: {lr}") + if not 0.0 >= beta2_decay: + raise ValueError(f"beta2_decay should be <= 0 but is: {beta2_decay}") + if eps[0] is not None and not 0.0 <= eps[0]: + raise ValueError(f"epsilon1 should be >= 0 but is: {eps[0]}") + if not 0.0 <= eps[1]: + raise ValueError(f"epsilon2 should be >= 0 but is: {eps[1]}") + if not 1.0 <= d: + raise ValueError(f"Clipping threshold d should be >= 1 but is: {d}") + if not 0.0 <= weight_decay: + raise ValueError(f"weight_decay should be >= 0 but is: {weight_decay}") + defaults = dict( + lr=lr, + beta2_decay=beta2_decay, + eps=eps, + d=d, + weight_decay=weight_decay, + foreach=foreach, + maximize=maximize, + ) + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault("foreach", None) + for p in group["params"]: + p_state = self.state.get(p, []) + if len(p_state) != 0 and not torch.is_tensor(p_state["step"]): + step_val = float(p_state["step"]) + p_state["step"] = torch.tensor(step_val, dtype=_get_scalar_dtype()) + + def _init_group( + self, + group, + params_with_grad, + grads, + row_vars, + col_vars, + variances, + state_steps, + ): + for p in group["params"]: + if p.grad is None: + continue + if torch.is_complex(p): + raise RuntimeError("Adafactor does not support complex parameters") + if p.grad.is_sparse: + raise RuntimeError("Adafactor does not support sparse gradients") + + params_with_grad.append(p) + grads.append(p.grad) + + state = self.state[p] + + # State initialization + if len(state) == 0: + # note(crcrpar): Deliberately host `step` on CPU if both capturable and fused are off. + # This is because kernel launches are costly on CUDA and XLA. + state["step"] = torch.tensor(0.0, dtype=_get_scalar_dtype()) + + if p.grad.dim() > 1: + row_shape = list(p.grad.shape) + row_shape[-1] = 1 + # Row factor of variance, NOT the same shape as grads (will be reduced along last dim) + state["row_var"] = p.grad.new_zeros(row_shape) + + col_shape = list(p.grad.shape) + col_shape[-2] = 1 + # Col factor of variance, NOT the same shape as grads (will be reduced along penultimate dim) + state["col_var"] = p.grad.new_zeros(col_shape) + else: + state["variance"] = torch.zeros_like( + p.grad, memory_format=torch.preserve_format + ) + + row_vars.append(state.get("row_var", None)) + col_vars.append(state.get("col_var", None)) + variances.append(state.get("variance", None)) + state_steps.append(state["step"]) + return False # has_complex + + @torch.no_grad() + def step(self, closure=None): + r"""Perform a single optimization step. + + Args: + closure (Callable, optional): A closure that reevaluates the model + and returns the loss. + """ + self._cuda_graph_capture_health_check() + + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params_with_grad: list[Tensor] = [] + grads: list[Tensor] = [] + row_vars: list[Optional[Tensor]] = [] + col_vars: list[Optional[Tensor]] = [] + variances: list[Optional[Tensor]] = [] + state_steps: list[Tensor] = [] + eps1, eps2 = group["eps"] + + has_complex = self._init_group( + group, + params_with_grad, + grads, + row_vars, + col_vars, + variances, + state_steps, + ) + + adafactor( + params_with_grad, + grads, + row_vars, + col_vars, + variances, + state_steps, + d=group["d"], + lr=group["lr"], + beta2_decay=group["beta2_decay"], + weight_decay=group["weight_decay"], + eps1=eps1, + eps2=eps2, + foreach=group["foreach"], + maximize=group["maximize"], + grad_scale=getattr(self, "grad_scale", None), + found_inf=getattr(self, "found_inf", None), + has_complex=has_complex, + ) + + return loss + + +Adafactor.__doc__ = ( + r"""Implements Adafactor algorithm. + + .. math:: + \begin{aligned} + &\rule{110mm}{0.4pt} \\ + &\textbf{input} : \gamma \text{(lr)}, \: \tau + \text{(}\beta_2\text{ decay)}, \: \theta_0 \text{(params)}, \: f(\theta) \text{(objective)}, \\ + &\hspace{15mm} \: \epsilon_1, \epsilon_2 \text{ (epsilons)}, \: d \text{(clipping threshold)}, \\ + &\hspace{15mm} \: \lambda \text{(weight decay)}, + \: \textit{maximize} \\ + &\textbf{initialize} : \: R_0 \leftarrow 0 \text{ (second moment row factor)}, \\ + &\hspace{23mm} \: C_0 \leftarrow 0 \text{ (second moment col factor)}, \\ + &\hspace{23mm} \: \widehat{V}_0 \leftarrow 0 \text{ (second moment for vectors)} \\[-1.ex] + &\rule{110mm}{0.4pt} \\ + &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\ + + &\hspace{5mm}\textbf{if} \: \textit{maximize}: \\ + &\hspace{10mm}G_t \leftarrow -\nabla_{\theta} f_t (\theta_{t-1}) \\ + &\hspace{5mm}\textbf{else} \\ + &\hspace{10mm}G_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\ + &\hspace{5mm}\widehat{\beta}_{2_t} \leftarrow 1 - t^{\tau} \\ + &\hspace{5mm}\rho_t \leftarrow min(lr, \frac{1}{\sqrt{t}}) \\ + &\hspace{5mm}\alpha_t \leftarrow max(\epsilon_2, + \text{RMS}(\theta_{t-1}))\rho_t \\ + &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \gamma \lambda \theta_{t-1} \\ + &\hspace{5mm}\textbf{if} \: \text{dim}(G_t) > 1: \\ + &\hspace{10mm}R_t \leftarrow \widehat{\beta}_{2_t}R_{t-1}+ + (1-\widehat{\beta}_{2_t})(G_t \odot G_t) \cdot 1_m \\ + &\hspace{10mm}C_t \leftarrow \widehat{\beta}_{2_t}C_{t-1}+ + (1-\widehat{\beta}_{2_t}) 1^\top_n \cdot (G_t \odot G_t) \\ + &\hspace{10mm}\widehat{V}_t \leftarrow + \frac{R_t \cdot C_t}{max(1^\top_n \cdot R_t, \epsilon_1)} \\ + &\hspace{5mm}\textbf{else} \\ + &\hspace{10mm}\widehat{V}_t \leftarrow \widehat{\beta}_{2_t}\widehat{V}_{t-1}+ + (1-\widehat{\beta}_{2_t}) \cdot (G_t \odot G_t) \\ + &\hspace{5mm}U_t \leftarrow + \frac{G_t}{max(\sqrt{\widehat{V}_t}, \epsilon_1)} \\ + &\hspace{5mm}\widehat{U}_t \leftarrow \frac{U_t}{max(1, \frac{\text{RMS}(U_t)}{d})} \\ + &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \alpha_t \widehat{U}_t \\ + + &\rule{110mm}{0.4pt} \\[-1.ex] + &\bf{return} \: \theta_t \\[-1.ex] + &\rule{110mm}{0.4pt} \\[-1.ex] + \end{aligned} + + For further details regarding the algorithm we refer to `Adafactor: Adaptive Learning Rates with Sublinear Memory Cost`_. + """ + + rf""" + Args: + {_params_doc} + lr (float, Tensor, optional): unlike other optimizers, Adafactor does not require a + learning rate, and Shazeer, Noam, and Mitchell Stern do not use lr at all. + Deviating from the paper, this implementation uses lr for applying weight + decay and as the maximum value for relative step size rho_t. Note that in + the paper, a constant of 0.01 is used as the maximum value for relative + step size, and so we set 0.01 as the default value. (default: 1e-2) + beta2_decay (float, optional): the decay rate of beta2. beta2 standardly refers + to the coefficient used for computing the running average of the gradient + squared. (default: -0.8) + eps (Tuple[float, float], optional): epsilon1 is the term added to the denominator + of the update calculation to improve numerical stability. This use of epsilon1 + deviates from the algorithm written in the paper! See note below for more details. + epsilon2 is the term used to avoid having too small a weight update when applying + parameter scaling. (default: (None, 1e-3)) + d (float, optional): the clipping threshold, used to avoid larger-than-desired + updates. + weight_decay (float, optional): weight decay coefficient (default: 1e-2) + foreach (bool, optional): whether foreach implementation of optimizer is used. Note + that the foreach implementation uses ~ sizeof(params) more peak memory than the + for-loop version due to the intermediates being a tensorlist vs just one tensor. + As Adafactor is commonly used when memory is prohibitive, Adafactor will default + to the slower single tensor for-loop implementation unless this flag is explicitly + True. This behavior is contrary to other optimizers, which will attempt defaulting + to foreach on CUDA for faster runtime. (default: None) + {_maximize_doc}""" + + r""" + .. Note:: + The implementation of Adafactor subtly differs from Shazeer, Noam, and Mitchell Stern + and implementations in some other frameworks with its use of learning rate and + :math:`\epsilon_1`. + + Regarding the learning rate hyperparameter: Shazeer, Noam, and Mitchell Stern do not + use lr at all, as the stated algorithm uses :math:`\rho_t` and update clipping to + affect the step size. + + This implementation allows `lr` to influence the maximum value for :math:`\rho_t`: + + .. math:: + \begin{aligned} + &\hspace{5mm}\rho_t \leftarrow min(lr, \frac{1}{\sqrt{t}}) + \end{aligned} + + This differs from Shazeer, Noam, and Mitchell Stern, who use a constant of 0.01 as + the maximum value of :math:`\rho_t` + + .. math:: + \begin{aligned} + &\hspace{5mm}\rho_t \leftarrow min(0.01, \frac{1}{\sqrt{t}}) + \end{aligned} + + Shazeer, Noam, and Mitchell Stern do not enforce an opinion on how weight decay should + be computed, and so we use the learning rate as a coefficient for decoupled weight + decay, similar to what is suggested in `Decoupled Weight Decay Regularization`_. + + Regarding the use of :math:`\epsilon_1`: The implementation attempts to replicate the + presumed intention of Shazeer, Noam, and Mitchell Stern to use :math:`\epsilon_1` as + a stabilizing term when the squared gradient becomes small. + + This stabilization can be written as + + .. math:: + \begin{aligned} + &\hspace{5mm}R_t \leftarrow \widehat{\beta}_{2_t}R_{t-1}+ + (1-\widehat{\beta}_{2_t})(G_t \odot G_t + 1_n \cdot 1^\top_m) \cdot 1_m \\ + &\hspace{5mm}C_t \leftarrow \widehat{\beta}_{2_t}C_{t-1}+ + (1-\widehat{\beta}_{2_t}) 1^\top_n \cdot (G_t \odot G_t + 1_n \cdot 1^\top_m) \\ + &\hspace{5mm}\widehat{V}_t \leftarrow + \frac{R_t \cdot C_t}{max(1^\top_n \cdot R_t, \epsilon_1)} \\ + &\hspace{5mm}U_t \leftarrow \frac{G_t}{max(\sqrt{\widehat{V}_t}, \epsilon_1)} \\ + \end{aligned} + + where the row and column factors of gradient squared :math:`R_t` and :math:`C_t` + are left alone, and we apply :math:`\epsilon_1` at the final calculation of + the variance estimate :math:`\widehat{V}_t` and for the update :math:`U_t`. + + This is in contrast to Shazeer, Noam, and Mitchell Stern and other frameworks which + apply :math:`\epsilon_1` to both row and column factors of the squared gradient, but + not in the calculations after: + + .. math:: + \begin{aligned} + &\hspace{5mm}R_t \leftarrow \widehat{\beta}_{2_t}R_{t-1}+ + (1-\widehat{\beta}_{2_t})(G_t \odot G_t + \epsilon_1 1_n \cdot 1^\top_m) \cdot 1_m \\ + &\hspace{5mm}C_t \leftarrow \widehat{\beta}_{2_t}C_{t-1}+ + (1-\widehat{\beta}_{2_t}) 1^\top_n \cdot (G_t \odot G_t + \epsilon_1 1_n \cdot 1^\top_m) \\ + &\hspace{5mm}\widehat{V}_t \leftarrow \frac{R_t \cdot C_t}{1^\top_n \cdot R_t} \\ + &\hspace{5mm}U_t \leftarrow \frac{G_t}{\sqrt{\widehat{V}_t}} \\ + \end{aligned} + + + .. _Adafactor\: Adaptive Learning Rates with Sublinear Memory Cost: + https://arxiv.org/pdf/1804.04235 + .. _Decoupled Weight Decay Regularization: + https://arxiv.org/abs/1711.05101 + """ +) + + +def _single_tensor_adafactor( + params: list[Tensor], + grads: list[Tensor], + # If grad is 1-dimensional (aka a vector), there is no factorization necessary + # so row_var and col_var will be None while variance will be filled. + # Contrarily, for a grad with multiple dimensions, we will factor along the last + # 2 dimensions, and so row_var and col_var will be filled and variance will be None. + row_vars: list[Optional[Tensor]], + col_vars: list[Optional[Tensor]], + variances: list[Optional[Tensor]], + state_steps: list[Tensor], + grad_scale: Optional[Tensor], + found_inf: Optional[Tensor], + *, + d: float, + lr: Union[Tensor, float], + beta2_decay: float, + weight_decay: float, + eps1: Optional[float], + eps2: float, + maximize: bool, + has_complex: bool, +): + assert ( + grad_scale is None and found_inf is None + ), "Grad scaling should occur outside of optimizer.step()" + + if torch.jit.is_scripting(): + # this assert is due to JIT being dumb and not realizing that the ops below + # have overloads to handle both float and Tensor lrs, so we just assert it's + # a float since most people using JIT are using floats + assert isinstance(lr, float) + + for i, param in enumerate(params): + grad = grads[i] if not maximize else -grads[i] + step_t = state_steps[i] + row_var = row_vars[i] + col_var = col_vars[i] + variance = variances[i] + if eps1 is None: + eps1 = torch.finfo(param.dtype).eps + + # update step + step_t += 1 + step_float = step_t.item() + + one_minus_beta2_t = step_float**beta2_decay + rho_t = min(lr, 1 / (step_float**0.5)) + alpha = max(eps2, param.norm(2).item() / (param.numel() ** 0.5)) * rho_t + + # Perform stepweight decay + if weight_decay != 0: + param.mul_(1 - lr * weight_decay) + + if grad.dim() > 1: + assert ( + row_var is not None and col_var is not None + ), "row_var and col_var should be defined when grad is multidimensional" + # same as (g * g).mean(dim=-1) w/o materializing an intermediate size g + row_mean = ( + torch.norm(grad, dim=-1, keepdim=True).square_().div_(grad.size(-1)) + ) + row_var.lerp_(row_mean, one_minus_beta2_t) + # same as (g * g).mean(dim=-2) w/o materializing an intermediate size g + col_mean = ( + torch.norm(grad, dim=-2, keepdim=True).square_().div_(grad.size(-2)) + ) + col_var.lerp_(col_mean, one_minus_beta2_t) + var_estimate = row_var @ col_var + var_estimate.div_(row_var.mean(dim=-2, keepdim=True).clamp_(min=eps1)) + else: + assert ( + variance is not None + ), "variance should be defined when grad is a vector" + grad_squared = grad * grad + variance.lerp_(grad_squared, one_minus_beta2_t) + # avoid writing into variance during update + var_estimate = variance.clone() + + # square the eps1 as we sqrt after to keep eps1's magnitude + update = var_estimate.clamp_(min=eps1 * eps1).rsqrt_() + update.mul_(grad) + denom = max(1.0, update.norm(2).item() / ((update.numel() ** 0.5) * d)) + param.add_(update, alpha=-alpha / denom) + + +def _group_tensors_by_device_dtype_and_is_multidim( + tensorlists: TensorListList, +) -> dict[ + tuple[Optional[torch.device], Optional[torch.dtype], bool], + list[list[Optional[Tensor]]], +]: + """Groups tensors by device, dtype, AND multidimensionality -- whether the tensor + has multiple dims or just one dim (is a vector). This allows the foreach impl of + Adafactor to assume that every group of params will either be factored or not.""" + grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(tensorlists) + ultra_grouped_tensors: dict[ + tuple[Optional[torch.device], Optional[torch.dtype], bool], + list[list[Optional[Tensor]]], + ] = {} + for (device, dtype), (tensorlists, _) in grouped_tensors.items(): + matrix_key = (device, dtype, True) + vector_key = (device, dtype, False) + + # assumes grad is the second tensorlist + for j, tensor in enumerate(tensorlists[1]): + assert tensor is not None, "grad should not be None" + if tensor.dim() > 1: + if matrix_key not in ultra_grouped_tensors: + ultra_grouped_tensors[matrix_key] = [[] for _ in tensorlists] + for i in range(len(tensorlists)): + ultra_grouped_tensors[matrix_key][i].append(tensorlists[i][j]) + else: + if vector_key not in ultra_grouped_tensors: + ultra_grouped_tensors[vector_key] = [[] for _ in tensorlists] + for i in range(len(tensorlists)): + ultra_grouped_tensors[vector_key][i].append(tensorlists[i][j]) + return ultra_grouped_tensors + + +def _multi_tensor_adafactor( + params: list[Tensor], + grads: list[Tensor], + # If grad is 1-dimensional (aka a vector), there is no factorization necessary + # so row_var and col_var will be None while variance will be filled. + # Contrarily, for a grad with multiple dimensions, we will factor along the last + # 2 dimensions, and so row_var and col_var will be filled and variance will be None. + row_vars: list[Optional[Tensor]], + col_vars: list[Optional[Tensor]], + variances: list[Optional[Tensor]], + state_steps: list[Tensor], + grad_scale: Optional[Tensor], + found_inf: Optional[Tensor], + *, + d: float, + lr: Union[Tensor, float], + beta2_decay: float, + weight_decay: float, + eps1: Optional[float], + eps2: float, + maximize: bool, + has_complex: bool, +): + if len(params) == 0: + return + + assert ( + grad_scale is None and found_inf is None + ), "Grad scaling should occur outside of optimizer.step()" + + grouped_tensors = _group_tensors_by_device_dtype_and_is_multidim( + [params, grads, row_vars, col_vars, variances, state_steps] # type: ignore[list-item] + ) + for (_, dtype, is_multidim), ( + ( + device_params_, + device_grads_, + device_row_vars_, + device_col_vars_, + device_variances_, + device_state_steps_, + ) + ) in grouped_tensors.items(): + device_params = cast(list[Tensor], device_params_) + device_grads = cast(list[Tensor], device_grads_) + device_state_steps = cast(list[Tensor], device_state_steps_) + if eps1 is None: + assert ( + dtype is not None + ), "dtype is needed to compute eps1 when eps1 is unset" + eps1 = torch.finfo(dtype).eps + + if TYPE_CHECKING: + assert device_state_steps[0] is not None + + if maximize: + device_grads = torch._foreach_neg(device_grads) # type: ignore[assignment] + + # Update steps + # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over + # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just + # wrapped it once now. The alpha is required to assure we go to the right overload. + if not torch.compiler.is_compiling() and device_state_steps[0].is_cpu: + torch._foreach_add_( + device_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0 + ) + else: + torch._foreach_add_(device_state_steps, 1.0) + + one_minus_beta2_ts = [] + beta2_ts = [] + rho_ts = [] + for s in device_state_steps: + one_minus_beta2_ts.append(s.item() ** beta2_decay) + beta2_ts.append(1 - s.item() ** beta2_decay) + rho_ts.append(min(lr, 1 / (s.item() ** 0.5))) + + alphas = [ + max(eps2, p.norm(2).item() / (p.numel() ** 0.5)) * r + for p, r in zip(device_params, rho_ts) + ] + + # Perform stepweight decay + if weight_decay != 0: + torch._foreach_mul_(device_params, 1 - lr * weight_decay) + + if is_multidim: + device_row_vars = cast(list[Tensor], device_row_vars_) + device_col_vars = cast(list[Tensor], device_col_vars_) + assert ( + device_row_vars[0] is not None and device_col_vars[0] is not None + ), "row_var and col_var should be defined when grad is multidimensional" + # same as (g * g).mean(dim=-1) w/o materializing an intermediate size g + row_means = [ + torch.norm(grad, dim=-1, keepdim=True) for grad in device_grads + ] + torch._foreach_mul_(row_means, row_means) + torch._foreach_div_(row_means, [grad.size(-1) for grad in device_grads]) + torch._foreach_lerp_(device_row_vars, row_means, one_minus_beta2_ts) + del row_means + + # same as (g * g).mean(dim=-2) w/o materializing an intermediate size g + col_means = [ + torch.norm(grad, dim=-2, keepdim=True) for grad in device_grads + ] + torch._foreach_mul_(col_means, col_means) + torch._foreach_div_(col_means, [grad.size(-2) for grad in device_grads]) + torch._foreach_lerp_(device_col_vars, col_means, one_minus_beta2_ts) + del col_means + + var_estimates = [ + row_var @ col_var + for row_var, col_var in zip(device_row_vars, device_col_vars) + ] + row_var_means = [ + row_var.mean(dim=-2, keepdim=True) for row_var in device_row_vars + ] + torch._foreach_clamp_min_(row_var_means, eps1) + torch._foreach_div_(var_estimates, row_var_means) + del row_var_means + else: + device_variances = cast(list[Tensor], device_variances_) + assert ( + device_variances[0] is not None + ), "variance should be defined when grad is a vector" + + grads_squared = torch._foreach_mul(device_grads, device_grads) + torch._foreach_lerp_(device_variances, grads_squared, one_minus_beta2_ts) + del grads_squared + + # avoid writing into variance during update + var_estimates = [v.clone() for v in device_variances] + + # square the eps1 as we sqrt after to keep eps1's magnitude + torch._foreach_clamp_min_(var_estimates, eps1 * eps1) + torch._foreach_rsqrt_(var_estimates) + torch._foreach_mul_(var_estimates, device_grads) + updates = var_estimates + + alphas = [ + -a / (max(1.0, update.norm(2).item() / ((update.numel() ** 0.5) * d))) + for a, update in zip(alphas, updates) + ] + torch._foreach_mul_(updates, alphas) + torch._foreach_add_(device_params, updates) + + +@_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_adafactor) +def adafactor( + params: list[Tensor], + grads: list[Tensor], + row_vars: list[Optional[Tensor]], + col_vars: list[Optional[Tensor]], + variances: list[Optional[Tensor]], + state_steps: list[Tensor], + # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627 + # setting this as kwarg for now as functional API is compiled by torch/distributed/optim + foreach: Optional[bool] = None, + grad_scale: Optional[Tensor] = None, + found_inf: Optional[Tensor] = None, + has_complex: bool = False, + *, + d: float, + lr: Union[float, Tensor], + beta2_decay: float, + weight_decay: float, + eps1: float, + eps2: float, + maximize: bool, +): + r"""Functional API that performs Adafactor algorithm computation. + + See :class:`~torch.optim.Adafactor` for details. + """ + if not torch.compiler.is_compiling() and not all( + isinstance(t, torch.Tensor) for t in state_steps + ): + raise RuntimeError( + "`state_steps` argument must contain a list of singleton tensors" + ) + + if foreach: + func = _multi_tensor_adafactor + else: + func = _single_tensor_adafactor + + func( + params, + grads, + row_vars, + col_vars, + variances, + state_steps, + d=d, + lr=lr, + beta2_decay=beta2_decay, + weight_decay=weight_decay, + eps1=eps1, + eps2=eps2, + maximize=maximize, + grad_scale=grad_scale, + found_inf=found_inf, + has_complex=has_complex, + ) diff --git a/shared/package-files/06/06d16c2a64e9b4de13387a1c12271f35b065d8909d6562a6fdb77999ce4ecd86/hip_fp16_gcc.h b/shared/package-files/06/06d16c2a64e9b4de13387a1c12271f35b065d8909d6562a6fdb77999ce4ecd86/hip_fp16_gcc.h new file mode 100644 index 0000000000000000000000000000000000000000..e76a7fff3a7bdc0061cc81b3aa77f6f9fa1fec88 --- /dev/null +++ b/shared/package-files/06/06d16c2a64e9b4de13387a1c12271f35b065d8909d6562a6fdb77999ce4ecd86/hip_fp16_gcc.h @@ -0,0 +1,254 @@ +#pragma once + +#if defined(__cplusplus) + #include +#endif + +struct __half_raw { + unsigned short x; +}; + +struct __half2_raw { + unsigned short x; + unsigned short y; +}; + +#if defined(__cplusplus) + struct __half; + + __half __float2half(float); + float __half2float(__half); + + // BEGIN STRUCT __HALF + struct __half { + protected: + unsigned short __x; + public: + // CREATORS + __half() = default; + __half(const __half_raw& x) : __x{x.x} {} + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + __half(float x) : __x{__float2half(x).__x} {} + __half(double x) : __x{__float2half(x).__x} {} + #endif + __half(const __half&) = default; + __half(__half&&) = default; + ~__half() = default; + + // MANIPULATORS + __half& operator=(const __half&) = default; + __half& operator=(__half&&) = default; + __half& operator=(const __half_raw& x) { __x = x.x; return *this; } + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + __half& operator=(float x) + { + __x = __float2half(x).__x; + return *this; + } + __half& operator=(double x) + { + return *this = static_cast(x); + } + #endif + + // ACCESSORS + operator float() const { return __half2float(*this); } + operator __half_raw() const { return __half_raw{__x}; } + }; + // END STRUCT __HALF + + // BEGIN STRUCT __HALF2 + struct __half2 { + public: + __half x; + __half y; + + // CREATORS + __half2() = default; + __half2(const __half2_raw& ix) + : + x{reinterpret_cast(ix.x)}, + y{reinterpret_cast(ix.y)} + {} + __half2(const __half& ix, const __half& iy) : x{ix}, y{iy} {} + __half2(const __half2&) = default; + __half2(__half2&&) = default; + ~__half2() = default; + + // MANIPULATORS + __half2& operator=(const __half2&) = default; + __half2& operator=(__half2&&) = default; + __half2& operator=(const __half2_raw& ix) + { + x = reinterpret_cast(ix.x); + y = reinterpret_cast(ix.y); + return *this; + } + + // ACCESSORS + operator __half2_raw() const + { + return __half2_raw{ + reinterpret_cast(x), + reinterpret_cast(y)}; + } + }; + // END STRUCT __HALF2 + + inline + unsigned short __internal_float2half( + float flt, unsigned int& sgn, unsigned int& rem) + { + unsigned int x{}; + std::memcpy(&x, &flt, sizeof(flt)); + + unsigned int u = (x & 0x7fffffffU); + sgn = ((x >> 16) & 0x8000U); + + // NaN/+Inf/-Inf + if (u >= 0x7f800000U) { + rem = 0; + return static_cast( + (u == 0x7f800000U) ? (sgn | 0x7c00U) : 0x7fffU); + } + // Overflows + if (u > 0x477fefffU) { + rem = 0x80000000U; + return static_cast(sgn | 0x7bffU); + } + // Normal numbers + if (u >= 0x38800000U) { + rem = u << 19; + u -= 0x38000000U; + return static_cast(sgn | (u >> 13)); + } + // +0/-0 + if (u < 0x33000001U) { + rem = u; + return static_cast(sgn); + } + // Denormal numbers + unsigned int exponent = u >> 23; + unsigned int mantissa = (u & 0x7fffffU); + unsigned int shift = 0x7eU - exponent; + mantissa |= 0x800000U; + rem = mantissa << (32 - shift); + return static_cast(sgn | (mantissa >> shift)); + } + + inline + __half __float2half(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem > 0x80000000U || (rem == 0x80000000U && (r.x & 0x1))) ++r.x; + + return r; + } + + inline + __half __float2half_rn(float x) { return __float2half(x); } + + inline + __half __float2half_rz(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + + return r; + } + + inline + __half __float2half_rd(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem && sgn) ++r.x; + + return r; + } + + inline + __half __float2half_ru(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem && !sgn) ++r.x; + + return r; + } + + inline + __half2 __float2half2_rn(float x) + { + return __half2{__float2half_rn(x), __float2half_rn(x)}; + } + + inline + __half2 __floats2half2_rn(float x, float y) + { + return __half2{__float2half_rn(x), __float2half_rn(y)}; + } + + inline + float __internal_half2float(unsigned short x) + { + unsigned int sign = ((x >> 15) & 1); + unsigned int exponent = ((x >> 10) & 0x1f); + unsigned int mantissa = ((x & 0x3ff) << 13); + + if (exponent == 0x1fU) { /* NaN or Inf */ + mantissa = (mantissa ? (sign = 0, 0x7fffffU) : 0); + exponent = 0xffU; + } else if (!exponent) { /* Denorm or Zero */ + if (mantissa) { + unsigned int msb; + exponent = 0x71U; + do { + msb = (mantissa & 0x400000U); + mantissa <<= 1; /* normalize */ + --exponent; + } while (!msb); + mantissa &= 0x7fffffU; /* 1.mantissa is implicit */ + } + } else { + exponent += 0x70U; + } + unsigned int u = ((sign << 31) | (exponent << 23) | mantissa); + float f; + memcpy(&f, &u, sizeof(u)); + + return f; + } + + inline + float __half2float(__half x) + { + return __internal_half2float(static_cast<__half_raw>(x).x); + } + + inline + float __low2float(__half2 x) + { + return __internal_half2float(static_cast<__half2_raw>(x).x); + } + + inline + float __high2float(__half2 x) + { + return __internal_half2float(static_cast<__half2_raw>(x).y); + } + + #if !defined(HIP_NO_HALF) + using half = __half; + using half2 = __half2; + #endif +#endif // defined(__cplusplus) diff --git a/shared/package-files/06/06d34a1e31fc8df3c9d1e28535e1945b19aab2ad1fb7f642e37d9d0291dafb1d/logaddexp.h b/shared/package-files/06/06d34a1e31fc8df3c9d1e28535e1945b19aab2ad1fb7f642e37d9d0291dafb1d/logaddexp.h new file mode 100644 index 0000000000000000000000000000000000000000..7beef01b3bcdda0b4507d907032e34c64b423943 --- /dev/null +++ b/shared/package-files/06/06d34a1e31fc8df3c9d1e28535e1945b19aab2ad1fb7f642e37d9d0291dafb1d/logaddexp.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logaddexp_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logaddexp_out::call(self, other, out); +} +// aten::logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logaddexp_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::logaddexp_out::call(self, other, out); +} + +// aten::logaddexp(Tensor self, Tensor other) -> Tensor +inline at::Tensor logaddexp(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logaddexp::call(self, other); +} + +} diff --git a/shared/package-files/06/06dd6b71aef9bdcaa132767b6a5945b7efd783e2e7377206201fa871dedaa582/clamp_min_meta.h b/shared/package-files/06/06dd6b71aef9bdcaa132767b6a5945b7efd783e2e7377206201fa871dedaa582/clamp_min_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..0cebbf947357cb4077a54aa71f5a5afde6db3a54 --- /dev/null +++ b/shared/package-files/06/06dd6b71aef9bdcaa132767b6a5945b7efd783e2e7377206201fa871dedaa582/clamp_min_meta.h @@ -0,0 +1,32 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_clamp_min : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Scalar & min); +}; +struct TORCH_API structured_clamp_min_Tensor : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & min); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/06/06e9080cac094ca64ca1ab1fbf328b4e23fe906388a1cee9b4088bb6b3377a09/ufunc.py b/shared/package-files/06/06e9080cac094ca64ca1ab1fbf328b4e23fe906388a1cee9b4088bb6b3377a09/ufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..17adcccecab563b6a4003215c778a00d5e1399c4 --- /dev/null +++ b/shared/package-files/06/06e9080cac094ca64ca1ab1fbf328b4e23fe906388a1cee9b4088bb6b3377a09/ufunc.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import torchgen.api.types as api_types +from torchgen.api import cpp, structured +from torchgen.api.types import ( + ArgName, + BaseCppType, + BaseCType, + Binding, + ConstRefCType, + CType, + NamedCType, + scalarT, +) +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + DispatchKey, + FunctionSchema, + NativeFunctionsGroup, + Type, +) + + +def schema_kernel_name(func: FunctionSchema, dispatch_key: DispatchKey) -> str: + assert func.is_out_fn(), "ufunc.kernel_name should only be invoked on out schemas" + return f"ufunc_{func.name.name}_{dispatch_key}" + + +def kernel_name(g: NativeFunctionsGroup, dispatch_key: DispatchKey) -> str: + return schema_kernel_name(g.out.func, dispatch_key) + + +# Tensors are omitted (as they are stored in TensorIterator), everything else is +# passed along (technically, we can pass tensors along too, it just wastes +# argument registers) +# +# NB: used for CPU only +def dispatchstub_type(t: Type, *, binds: ArgName) -> NamedCType | None: + # Dispatch stubs are always plain ints + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + elif t == BaseType(BaseTy.Tensor): + return None + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +def opmath_type(scalar_t: BaseCppType) -> BaseCppType: + if scalar_t == api_types.scalar_t: + return api_types.opmath_t + raise NotImplementedError + + +# NB: Tensors in constructor are stored in opmath_t, not scalar_t +# because Tensor in constructor = its a scalar tensor partially applied = +# it can be higher precision and we want to compute in that higher precision +# +# NB: CUDA only +def ufunctor_ctor_type(t: Type, *, binds: ArgName, scalar_t: BaseCppType) -> NamedCType: + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, BaseCType(opmath_type(scalar_t))) + elif t == BaseType(BaseTy.Tensor): + return NamedCType(binds, BaseCType(opmath_type(scalar_t))) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Only Tensors ever get passed directly to operator() +# +# NB: CUDA only +# (Actually, this works for CPU too) +def ufunctor_apply_type( + t: Type, *, binds: ArgName, scalar_t: BaseCppType +) -> NamedCType: + if t == BaseType(BaseTy.Tensor): + return NamedCType(binds, BaseCType(scalar_t)) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# The actual ufunc template function the user writes. Everything here +# is done in the computation type. compute_t is opmath_t in CUDA and scalar_t +# in CPU +def ufunc_type(t: Type, *, binds: ArgName, compute_t: CType) -> NamedCType: + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, compute_t) + elif t == BaseType(BaseTy.Tensor): + return NamedCType(binds, compute_t) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +def ufunctor_ctor_argument(a: Argument, scalar_t: BaseCppType) -> Binding: + return Binding( + nctype=ufunctor_ctor_type(a.type, binds=a.name, scalar_t=scalar_t), + name=a.name, + default=None, + argument=a, + ) + + +def ufunctor_apply_argument(a: Argument, scalar_t: BaseCppType) -> Binding: + return Binding( + nctype=ufunctor_apply_type(a.type, binds=a.name, scalar_t=scalar_t), + name=a.name, + default=None, + argument=a, + ) + + +def ufunc_argument(a: Argument, compute_t: CType) -> Binding: + return Binding( + nctype=ufunc_type(a.type, binds=a.name, compute_t=compute_t), + name=a.name, + default=None, + argument=a, + ) + + +@dataclass(frozen=True) +class UfunctorBindings: + ctor: list[Binding] + apply: list[Binding] + + +# ufunctors are a CUDA-only concept representing functors that take some of +# their arguments on a host-side constructor, and the rest in the device-side +# apply. E.g., +# +# template +# struct CUDAFunctorOnSelf_add { +# using opmath_t = at::opmath_type; +# opmath_t other_; +# opmath_t alpha_; +# CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha) : other_(other), alpha_(alpha) {} +# __device__ scalar_t operator()(scalar_t self) { +# return ufunc::add(static_cast(self), other_, alpha_); +# } +# }; +# +# The ctor refers to the constructor CUDAFunctorOnSelf_add, while apply refers +# to the operator() definition +def ufunctor_arguments( + g: NativeFunctionsGroup, *, scalar_tensor_idx: int | None, scalar_t: BaseCppType +) -> UfunctorBindings: + ctor = [] + apply = [] + for a in g.functional.func.arguments.flat_non_out: + if a.type.is_tensor_like(): + if scalar_tensor_idx == 0: + # put it in the ctor anyway + ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t)) + scalar_tensor_idx = None + else: + if scalar_tensor_idx is not None: + scalar_tensor_idx -= 1 + apply.append(ufunctor_apply_argument(a, scalar_t=scalar_t)) + else: + ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t)) + assert scalar_tensor_idx is None + return UfunctorBindings(ctor=ctor, apply=apply) + + +# ufuncs are the inner loop template functions that you wrote in ufunc/add.h +# which do the actual computation in question. E.g., +# +# template +# C10_HOST_DEVICE T add(T self, T other, T alpha) __ubsan_ignore_undefined__ { +# return self + alpha * other; +# } +# +# In this file, we refer to T as compute_t which is bound by caller +def ufunc_arguments(g: NativeFunctionsGroup, *, compute_t: CType) -> list[Binding]: + return [ + ufunc_argument(a, compute_t=compute_t) + for a in g.functional.func.arguments.flat_non_out + ] + + +# Stubs are the DispatchStub trampolines that CPU kernels use to get to their +# vectorized versions. E.g., +# +# using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha); +# DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub); +def stub_arguments(g: NativeFunctionsGroup) -> list[Binding]: + # stubs drop all tensor arguments (they are implicit in the TensorIterator + # argument and keep everything else) + return [ + r + for a in g.out.func.arguments.flat_non_out + if not a.type.is_tensor_like() + for r in structured.argument(a) + ] diff --git a/shared/package-files/06/06eb813117ddf7ff6eacaa7d13af69b6591ae5740563784a73b26ba41caddf72/_sparse_softmax_ops.h b/shared/package-files/06/06eb813117ddf7ff6eacaa7d13af69b6591ae5740563784a73b26ba41caddf72/_sparse_softmax_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cd31db7e8d241968449dfb327ef97ebf1cea656a --- /dev/null +++ b/shared/package-files/06/06eb813117ddf7ff6eacaa7d13af69b6591ae5740563784a73b26ba41caddf72/_sparse_softmax_ops.h @@ -0,0 +1,62 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_softmax_int { + using schema = at::Tensor (const at::Tensor &, int64_t, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_softmax"; + static constexpr const char* overload_name = "int"; + static constexpr const char* schema_str = "_sparse_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t dim, ::std::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, ::std::optional dtype); +}; + +struct TORCH_API _sparse_softmax_Dimname { + using schema = at::Tensor (const at::Tensor &, at::Dimname, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_softmax"; + static constexpr const char* overload_name = "Dimname"; + static constexpr const char* schema_str = "_sparse_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::Dimname dim, ::std::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, ::std::optional dtype); +}; + +struct TORCH_API _sparse_softmax { + using schema = at::Tensor (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_softmax"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t dim, bool half_to_float); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool half_to_float); +}; + +struct TORCH_API _sparse_softmax_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_softmax"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_sparse_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/06/06ebaa8caf56dab98b7c7e5a973274e3a38bbfc61cd70dab317f7d5f5a88977f/test_expressions.cpython-311.pyc b/shared/package-files/06/06ebaa8caf56dab98b7c7e5a973274e3a38bbfc61cd70dab317f7d5f5a88977f/test_expressions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..901dcac223d7772c65e2dfed157d540775d63879 Binary files /dev/null and b/shared/package-files/06/06ebaa8caf56dab98b7c7e5a973274e3a38bbfc61cd70dab317f7d5f5a88977f/test_expressions.cpython-311.pyc differ diff --git a/shared/package-files/06/06ee7fb0eeb05e92cee0fae9c4ee348a9dc0f7e762c0de0f1937b73bd815e6da/_export.pyi b/shared/package-files/06/06ee7fb0eeb05e92cee0fae9c4ee348a9dc0f7e762c0de0f1937b73bd815e6da/_export.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5351945b9d51637313d4feec88656ff796863a89 --- /dev/null +++ b/shared/package-files/06/06ee7fb0eeb05e92cee0fae9c4ee348a9dc0f7e762c0de0f1937b73bd815e6da/_export.pyi @@ -0,0 +1,10 @@ +# Defined in torch/csrc/export/pybind.cpp + +class CppExportedProgram: ... + +def deserialize_exported_program( + serialized_program: str, +) -> CppExportedProgram: ... +def serialize_exported_program( + cpp_exported_program: CppExportedProgram, +) -> str: ... diff --git a/shared/package-files/06/06ef98dd62b6846391f8a200fcd179b86b82112c50ab43b53b19c681c0175f54/_euclidean_dist.h b/shared/package-files/06/06ef98dd62b6846391f8a200fcd179b86b82112c50ab43b53b19c681c0175f54/_euclidean_dist.h new file mode 100644 index 0000000000000000000000000000000000000000..f8ac30777dc04fe9b8abbc5be89ff6961a415a1f --- /dev/null +++ b/shared/package-files/06/06ef98dd62b6846391f8a200fcd179b86b82112c50ab43b53b19c681c0175f54/_euclidean_dist.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_euclidean_dist(Tensor x1, Tensor x2) -> Tensor +inline at::Tensor _euclidean_dist(const at::Tensor & x1, const at::Tensor & x2) { + return at::_ops::_euclidean_dist::call(x1, x2); +} + +// aten::_euclidean_dist.out(Tensor x1, Tensor x2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _euclidean_dist_out(at::Tensor & out, const at::Tensor & x1, const at::Tensor & x2) { + return at::_ops::_euclidean_dist_out::call(x1, x2, out); +} +// aten::_euclidean_dist.out(Tensor x1, Tensor x2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _euclidean_dist_outf(const at::Tensor & x1, const at::Tensor & x2, at::Tensor & out) { + return at::_ops::_euclidean_dist_out::call(x1, x2, out); +} + +} diff --git a/shared/package-files/06/06f9c786e5bf585783eef6d75ca4d7facf1eee10400ceea998cc266bf44ca4dd/_serialization.cpython-311.pyc b/shared/package-files/06/06f9c786e5bf585783eef6d75ca4d7facf1eee10400ceea998cc266bf44ca4dd/_serialization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a68c327fda1d051de3a5fd5b90a224fc042e2a8 Binary files /dev/null and b/shared/package-files/06/06f9c786e5bf585783eef6d75ca4d7facf1eee10400ceea998cc266bf44ca4dd/_serialization.cpython-311.pyc differ diff --git a/shared/package-files/06/06fa3f6979f69f3b7beb81456ac46b72050238e441ce184d177ce72d26e9404d/test_storage.py b/shared/package-files/06/06fa3f6979f69f3b7beb81456ac46b72050238e441ce184d177ce72d26e9404d/test_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..d72718d77a6fdcd660866dd81c98984f5d3c3737 --- /dev/null +++ b/shared/package-files/06/06fa3f6979f69f3b7beb81456ac46b72050238e441ce184d177ce72d26e9404d/test_storage.py @@ -0,0 +1,2623 @@ +import array +import atexit +import json +import os +import pathlib +import sys +import pickle +import shutil +import tempfile +from contextlib import contextmanager +from pickle import PicklingError +from zipfile import ZipFile + +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal, assert_array_equal + +from numcodecs.compat import ensure_bytes + +import zarr +from zarr._storage.store import _get_hierarchy_metadata +from zarr.codecs import BZ2, AsType, Blosc, Zlib +from zarr.context import Context +from zarr.convenience import consolidate_metadata +from zarr.errors import ContainsArrayError, ContainsGroupError, MetadataError +from zarr.hierarchy import group +from zarr.meta import ZARR_FORMAT, decode_array_metadata +from zarr.n5 import N5Store, N5FSStore, N5_FORMAT, n5_attrs_key +from zarr.storage import ( + ABSStore, + ConsolidatedMetadataStore, + DBMStore, + DictStore, + DirectoryStore, + KVStore, + LMDBStore, + LRUStoreCache, + MemoryStore, + MongoDBStore, + NestedDirectoryStore, + RedisStore, + SQLiteStore, + Store, + TempStore, + ZipStore, + array_meta_key, + atexit_rmglob, + atexit_rmtree, + attrs_key, + data_root, + default_compressor, + getsize, + group_meta_key, + init_array, + init_group, + migrate_1to2, + meta_root, + normalize_store_arg, +) +from zarr.storage import FSStore, rename, listdir +from zarr._storage.v3 import KVStoreV3 +from zarr.tests.util import CountingDict, have_fsspec, skip_test_env_var, abs_container, mktemp +from zarr.util import ConstantMap, json_dumps + + +@contextmanager +def does_not_raise(): + yield + + +@pytest.fixture( + params=[ + (None, "."), + (".", "."), + ("/", "/"), + ] +) +def dimension_separator_fixture(request): + return request.param + + +def skip_if_nested_chunks(**kwargs): + if kwargs.get("dimension_separator") == "/": + pytest.skip("nested chunks are unsupported") + + +def test_kvstore_repr(): + repr(KVStore(dict())) + + +def test_ensure_store(): + class InvalidStore: + pass + + with pytest.raises(ValueError): + Store._ensure_store(InvalidStore()) + + # cannot initialize with a store from a different Zarr version + with pytest.raises(ValueError): + Store._ensure_store(KVStoreV3(dict())) + + # cannot initialize without a store + with pytest.raises(ValueError): + Store._ensure_store(None) + + +def test_capabilities(): + s = KVStore(dict()) + assert s.is_readable() + assert s.is_listable() + assert s.is_erasable() + assert s.is_writeable() + + +def test_getsize_non_implemented(): + assert getsize(object()) == -1 + + +def test_kvstore_eq(): + assert KVStore(dict()) != dict() + + +def test_coverage_rename(): + store = dict() + store["a"] = 1 + rename(store, "a", "b") + + +def test_deprecated_listdir_nosotre(): + store = dict() + with pytest.warns(UserWarning, match="has no `listdir`"): + listdir(store) + + +class StoreTests: + """Abstract store tests.""" + + version = 2 + root = "" + + def create_store(self, **kwargs): # pragma: no cover + # implement in sub-class + raise NotImplementedError + + def test_context_manager(self): + with self.create_store(): + pass + + def test_get_set_del_contains(self): + store = self.create_store() + + # test __contains__, __getitem__, __setitem__ + key = self.root + "foo" + assert key not in store + with pytest.raises(KeyError): + # noinspection PyStatementEffect + store[key] + store[key] = b"bar" + assert key in store + assert b"bar" == ensure_bytes(store[key]) + + # test __delitem__ (optional) + try: + del store[key] + except NotImplementedError: + pass + else: + assert key not in store + with pytest.raises(KeyError): + # noinspection PyStatementEffect + store[key] + with pytest.raises(KeyError): + # noinspection PyStatementEffect + del store[key] + + store.close() + + def test_set_invalid_content(self): + store = self.create_store() + + with pytest.raises(TypeError): + store[self.root + "baz"] = list(range(5)) + + store.close() + + def test_clear(self): + store = self.create_store() + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"qux" + assert len(store) == 2 + store.clear() + assert len(store) == 0 + assert self.root + "foo" not in store + assert self.root + "baz" not in store + + store.close() + + def test_pop(self): + store = self.create_store() + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"qux" + assert len(store) == 2 + v = store.pop(self.root + "foo") + assert ensure_bytes(v) == b"bar" + assert len(store) == 1 + v = store.pop(self.root + "baz") + assert ensure_bytes(v) == b"qux" + assert len(store) == 0 + with pytest.raises(KeyError): + store.pop(self.root + "xxx") + v = store.pop(self.root + "xxx", b"default") + assert v == b"default" + v = store.pop(self.root + "xxx", b"") + assert v == b"" + v = store.pop(self.root + "xxx", None) + assert v is None + + store.close() + + def test_popitem(self): + store = self.create_store() + store[self.root + "foo"] = b"bar" + k, v = store.popitem() + assert k == self.root + "foo" + assert ensure_bytes(v) == b"bar" + assert len(store) == 0 + with pytest.raises(KeyError): + store.popitem() + + store.close() + + def test_writeable_values(self): + store = self.create_store() + + # __setitem__ should accept any value that implements buffer interface + store[self.root + "foo1"] = b"bar" + store[self.root + "foo2"] = bytearray(b"bar") + store[self.root + "foo3"] = array.array("B", b"bar") + store[self.root + "foo4"] = np.frombuffer(b"bar", dtype="u1") + + store.close() + + def test_update(self): + store = self.create_store() + assert self.root + "foo" not in store + assert self.root + "baz" not in store + + if self.version == 2: + store.update(foo=b"bar", baz=b"quux") + else: + kv = {self.root + "foo": b"bar", self.root + "baz": b"quux"} + store.update(kv) + + assert b"bar" == ensure_bytes(store[self.root + "foo"]) + assert b"quux" == ensure_bytes(store[self.root + "baz"]) + + store.close() + + def test_iterators(self): + store = self.create_store() + + # test iterator methods on empty store + assert 0 == len(store) + assert set() == set(store) + assert set() == set(store.keys()) + assert set() == set(store.values()) + assert set() == set(store.items()) + + # setup some values + store[self.root + "a"] = b"aaa" + store[self.root + "b"] = b"bbb" + store[self.root + "c/d"] = b"ddd" + store[self.root + "c/e/f"] = b"fff" + + # test iterators on store with data + assert 4 == len(store) + expected = set(self.root + k for k in ["a", "b", "c/d", "c/e/f"]) + assert expected == set(store) + assert expected == set(store.keys()) + assert {b"aaa", b"bbb", b"ddd", b"fff"} == set(map(ensure_bytes, store.values())) + assert { + (self.root + "a", b"aaa"), + (self.root + "b", b"bbb"), + (self.root + "c/d", b"ddd"), + (self.root + "c/e/f", b"fff"), + } == set(map(lambda kv: (kv[0], ensure_bytes(kv[1])), store.items())) + + store.close() + + def test_pickle(self): + # setup store + store = self.create_store() + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"quux" + n = len(store) + keys = sorted(store.keys()) + + # round-trip through pickle + dump = pickle.dumps(store) + # some stores cannot be opened twice at the same time, need to close + # store before can round-trip through pickle + store.close() + # check can still pickle after close + assert dump == pickle.dumps(store) + store2 = pickle.loads(dump) + + # verify + assert n == len(store2) + assert keys == sorted(store2.keys()) + assert b"bar" == ensure_bytes(store2[self.root + "foo"]) + assert b"quux" == ensure_bytes(store2[self.root + "baz"]) + + store2.close() + + def test_getsize(self): + store = self.create_store() + if isinstance(store, dict) or hasattr(store, "getsize"): + assert 0 == getsize(store) + store["foo"] = b"x" + assert 1 == getsize(store) + assert 1 == getsize(store, "foo") + store["bar"] = b"yy" + assert 3 == getsize(store) + assert 2 == getsize(store, "bar") + store["baz"] = bytearray(b"zzz") + assert 6 == getsize(store) + assert 3 == getsize(store, "baz") + store["quux"] = array.array("B", b"zzzz") + assert 10 == getsize(store) + assert 4 == getsize(store, "quux") + store["spong"] = np.frombuffer(b"zzzzz", dtype="u1") + assert 15 == getsize(store) + assert 5 == getsize(store, "spong") + + store.close() + + # noinspection PyStatementEffect + def test_hierarchy(self): + # setup + store = self.create_store() + store[self.root + "a"] = b"aaa" + store[self.root + "b"] = b"bbb" + store[self.root + "c/d"] = b"ddd" + store[self.root + "c/e/f"] = b"fff" + store[self.root + "c/e/g"] = b"ggg" + + # check keys + assert self.root + "a" in store + assert self.root + "b" in store + assert self.root + "c/d" in store + assert self.root + "c/e/f" in store + assert self.root + "c/e/g" in store + assert self.root + "c" not in store + assert self.root + "c/" not in store + assert self.root + "c/e" not in store + assert self.root + "c/e/" not in store + assert self.root + "c/d/x" not in store + + # check __getitem__ + with pytest.raises(KeyError): + store[self.root + "c"] + with pytest.raises(KeyError): + store[self.root + "c/e"] + with pytest.raises(KeyError): + store[self.root + "c/d/x"] + + # test getsize (optional) + if hasattr(store, "getsize"): + # TODO: proper behavior of getsize? + # v3 returns size of all nested arrays, not just the + # size of the arrays in the current folder. + if self.version == 2: + assert 6 == store.getsize() + else: + assert 15 == store.getsize() + assert 3 == store.getsize("a") + assert 3 == store.getsize("b") + if self.version == 2: + assert 3 == store.getsize("c") + else: + assert 9 == store.getsize("c") + assert 3 == store.getsize("c/d") + assert 6 == store.getsize("c/e") + assert 3 == store.getsize("c/e/f") + assert 3 == store.getsize("c/e/g") + # non-existent paths + assert 0 == store.getsize("x") + assert 0 == store.getsize("a/x") + assert 0 == store.getsize("c/x") + assert 0 == store.getsize("c/x/y") + assert 0 == store.getsize("c/d/y") + assert 0 == store.getsize("c/d/y/z") + + # access item via full path + assert 3 == store.getsize(self.root + "a") + + # test listdir (optional) + if hasattr(store, "listdir"): + assert {"a", "b", "c"} == set(store.listdir(self.root)) + assert {"d", "e"} == set(store.listdir(self.root + "c")) + assert {"f", "g"} == set(store.listdir(self.root + "c/e")) + # no exception raised if path does not exist or is leaf + assert [] == store.listdir(self.root + "x") + assert [] == store.listdir(self.root + "a/x") + assert [] == store.listdir(self.root + "c/x") + assert [] == store.listdir(self.root + "c/x/y") + assert [] == store.listdir(self.root + "c/d/y") + assert [] == store.listdir(self.root + "c/d/y/z") + assert [] == store.listdir(self.root + "c/e/f") + + # test rename (optional) + if store.is_erasable(): + store.rename("c/e", "c/e2") + assert self.root + "c/d" in store + assert self.root + "c/e" not in store + assert self.root + "c/e/f" not in store + assert self.root + "c/e/g" not in store + assert self.root + "c/e2" not in store + assert self.root + "c/e2/f" in store + assert self.root + "c/e2/g" in store + store.rename("c/e2", "c/e") + assert self.root + "c/d" in store + assert self.root + "c/e2" not in store + assert self.root + "c/e2/f" not in store + assert self.root + "c/e2/g" not in store + assert self.root + "c/e" not in store + assert self.root + "c/e/f" in store + assert self.root + "c/e/g" in store + store.rename("c", "c1/c2/c3") + assert self.root + "a" in store + assert self.root + "c" not in store + assert self.root + "c/d" not in store + assert self.root + "c/e" not in store + assert self.root + "c/e/f" not in store + assert self.root + "c/e/g" not in store + assert self.root + "c1" not in store + assert self.root + "c1/c2" not in store + assert self.root + "c1/c2/c3" not in store + assert self.root + "c1/c2/c3/d" in store + assert self.root + "c1/c2/c3/e" not in store + assert self.root + "c1/c2/c3/e/f" in store + assert self.root + "c1/c2/c3/e/g" in store + store.rename("c1/c2/c3", "c") + assert self.root + "c" not in store + assert self.root + "c/d" in store + assert self.root + "c/e" not in store + assert self.root + "c/e/f" in store + assert self.root + "c/e/g" in store + assert self.root + "c1" not in store + assert self.root + "c1/c2" not in store + assert self.root + "c1/c2/c3" not in store + assert self.root + "c1/c2/c3/d" not in store + assert self.root + "c1/c2/c3/e" not in store + assert self.root + "c1/c2/c3/e/f" not in store + assert self.root + "c1/c2/c3/e/g" not in store + + # test rmdir (optional) + store.rmdir("c/e") + assert self.root + "c/d" in store + assert self.root + "c/e/f" not in store + assert self.root + "c/e/g" not in store + store.rmdir("c") + assert self.root + "c/d" not in store + store.rmdir() + assert self.root + "a" not in store + assert self.root + "b" not in store + store[self.root + "a"] = b"aaa" + store[self.root + "c/d"] = b"ddd" + store[self.root + "c/e/f"] = b"fff" + # no exceptions raised if path does not exist or is leaf + store.rmdir("x") + store.rmdir("a/x") + store.rmdir("c/x") + store.rmdir("c/x/y") + store.rmdir("c/d/y") + store.rmdir("c/d/y/z") + store.rmdir("c/e/f") + assert self.root + "a" in store + assert self.root + "c/d" in store + assert self.root + "c/e/f" in store + + store.close() + + def test_init_array(self, dimension_separator_fixture): + pass_dim_sep, want_dim_sep = dimension_separator_fixture + + store = self.create_store(dimension_separator=pass_dim_sep) + init_array(store, shape=1000, chunks=100) + + # check metadata + assert array_meta_key in store + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + assert default_compressor.get_config() == meta["compressor"] + assert meta["fill_value"] is None + # Missing MUST be assumed to be "." + assert meta.get("dimension_separator", ".") is want_dim_sep + + store.close() + + def test_init_array_overwrite(self): + self._test_init_array_overwrite("F") + + def test_init_array_overwrite_path(self): + self._test_init_array_overwrite_path("F") + + def test_init_array_overwrite_chunk_store(self): + self._test_init_array_overwrite_chunk_store("F") + + def test_init_group_overwrite(self): + self._test_init_group_overwrite("F") + + def test_init_group_overwrite_path(self): + self._test_init_group_overwrite_path("F") + + def test_init_group_overwrite_chunk_store(self): + self._test_init_group_overwrite_chunk_store("F") + + def _test_init_array_overwrite(self, order): + # setup + store = self.create_store() + if self.version == 2: + path = None + mkey = array_meta_key + meta = dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=Zlib(1).get_config(), + fill_value=0, + order=order, + filters=None, + ) + else: + path = "arr1" # no default, have to specify for v3 + mkey = meta_root + path + ".array.json" + meta = dict( + shape=(2000,), + chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")), + data_type=np.dtype("u1"), + compressor=Zlib(1), + fill_value=0, + chunk_memory_layout=order, + filters=None, + ) + store[mkey] = store._metadata_class.encode_array_metadata(meta) + + # don't overwrite (default) + with pytest.raises(ContainsArrayError): + init_array(store, shape=1000, chunks=100, path=path) + + # do overwrite + try: + init_array(store, shape=1000, chunks=100, dtype="i4", overwrite=True, path=path) + except NotImplementedError: + pass + else: + assert mkey in store + meta = store._metadata_class.decode_array_metadata(store[mkey]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + assert (100,) == meta["chunks"] + assert np.dtype("i4") == meta["dtype"] + else: + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype("i4") == meta["data_type"] + assert (1000,) == meta["shape"] + + store.close() + + def test_init_array_path(self): + path = "foo/bar" + store = self.create_store() + init_array(store, shape=1000, chunks=100, path=path) + + # check metadata + if self.version == 2: + mkey = path + "/" + array_meta_key + else: + mkey = meta_root + path + ".array.json" + assert mkey in store + meta = store._metadata_class.decode_array_metadata(store[mkey]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + assert default_compressor.get_config() == meta["compressor"] + else: + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype(None) == meta["data_type"] + assert default_compressor == meta["compressor"] + assert (1000,) == meta["shape"] + assert meta["fill_value"] is None + + store.close() + + def _test_init_array_overwrite_path(self, order): + # setup + path = "foo/bar" + store = self.create_store() + if self.version == 2: + mkey = path + "/" + array_meta_key + meta = dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=Zlib(1).get_config(), + fill_value=0, + order=order, + filters=None, + ) + else: + mkey = meta_root + path + ".array.json" + meta = dict( + shape=(2000,), + chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")), + data_type=np.dtype("u1"), + compressor=Zlib(1), + fill_value=0, + chunk_memory_layout=order, + filters=None, + ) + store[mkey] = store._metadata_class.encode_array_metadata(meta) + + # don't overwrite + with pytest.raises(ContainsArrayError): + init_array(store, shape=1000, chunks=100, path=path) + + # do overwrite + try: + init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True) + except NotImplementedError: + pass + else: + if self.version == 2: + assert group_meta_key in store + assert array_meta_key not in store + assert mkey in store + # should have been overwritten + meta = store._metadata_class.decode_array_metadata(store[mkey]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + assert (100,) == meta["chunks"] + assert np.dtype("i4") == meta["dtype"] + else: + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype("i4") == meta["data_type"] + assert (1000,) == meta["shape"] + + store.close() + + def test_init_array_overwrite_group(self): + # setup + path = "foo/bar" + store = self.create_store() + if self.version == 2: + array_key = path + "/" + array_meta_key + group_key = path + "/" + group_meta_key + else: + array_key = meta_root + path + ".array.json" + group_key = meta_root + path + ".group.json" + store[group_key] = store._metadata_class.encode_group_metadata() + + # don't overwrite + with pytest.raises(ContainsGroupError): + init_array(store, shape=1000, chunks=100, path=path) + + # do overwrite + try: + init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True) + except NotImplementedError: + pass + else: + assert group_key not in store + assert array_key in store + meta = store._metadata_class.decode_array_metadata(store[array_key]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + assert (100,) == meta["chunks"] + assert np.dtype("i4") == meta["dtype"] + else: + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype("i4") == meta["data_type"] + assert (1000,) == meta["shape"] + + store.close() + + def _test_init_array_overwrite_chunk_store(self, order): + # setup + store = self.create_store() + chunk_store = self.create_store() + + if self.version == 2: + path = None + data_path = "" + mkey = array_meta_key + meta = dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=None, + fill_value=0, + filters=None, + order=order, + ) + else: + path = "arr1" + data_path = data_root + "arr1/" + mkey = meta_root + path + ".array.json" + meta = dict( + shape=(2000,), + chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")), + data_type=np.dtype("u1"), + compressor=None, + fill_value=0, + filters=None, + chunk_memory_layout=order, + ) + + store[mkey] = store._metadata_class.encode_array_metadata(meta) + + chunk_store[data_path + "0"] = b"aaa" + chunk_store[data_path + "1"] = b"bbb" + + # don't overwrite (default) + with pytest.raises(ContainsArrayError): + init_array(store, path=path, shape=1000, chunks=100, chunk_store=chunk_store) + + # do overwrite + try: + init_array( + store, + path=path, + shape=1000, + chunks=100, + dtype="i4", + overwrite=True, + chunk_store=chunk_store, + ) + except NotImplementedError: + pass + else: + assert mkey in store + meta = store._metadata_class.decode_array_metadata(store[mkey]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + assert (100,) == meta["chunks"] + assert np.dtype("i4") == meta["dtype"] + else: + assert (100,) == meta["chunk_grid"]["chunk_shape"] + assert np.dtype("i4") == meta["data_type"] + assert (1000,) == meta["shape"] + assert data_path + "0" not in chunk_store + assert data_path + "1" not in chunk_store + + store.close() + chunk_store.close() + + def test_init_array_compat(self): + store = self.create_store() + if self.version == 2: + path = None + mkey = array_meta_key + else: + path = "arr1" + mkey = meta_root + path + ".array.json" + init_array(store, path=path, shape=1000, chunks=100, compressor="none") + meta = store._metadata_class.decode_array_metadata(store[mkey]) + if self.version == 2: + assert meta["compressor"] is None + else: + assert "compressor" not in meta + store.close() + + def test_init_group(self): + store = self.create_store() + if self.version == 2: + path = None + mkey = group_meta_key + else: + path = "foo" + mkey = meta_root + path + ".group.json" + init_group(store, path=path) + + # check metadata + assert mkey in store + meta = store._metadata_class.decode_group_metadata(store[mkey]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + else: + assert meta == {"attributes": {}} + + store.close() + + def _test_init_group_overwrite(self, order): + if self.version == 3: + pytest.skip("In v3 array and group names cannot overlap") + # setup + store = self.create_store() + store[array_meta_key] = store._metadata_class.encode_array_metadata( + dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=None, + fill_value=0, + order=order, + filters=None, + ) + ) + + # don't overwrite array (default) + with pytest.raises(ContainsArrayError): + init_group(store) + + # do overwrite + try: + init_group(store, overwrite=True) + except NotImplementedError: + pass + else: + assert array_meta_key not in store + assert group_meta_key in store + meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + + # don't overwrite group + with pytest.raises(ValueError): + init_group(store) + + store.close() + + def _test_init_group_overwrite_path(self, order): + # setup + path = "foo/bar" + store = self.create_store() + if self.version == 2: + meta = dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=None, + fill_value=0, + order=order, + filters=None, + ) + array_key = path + "/" + array_meta_key + group_key = path + "/" + group_meta_key + else: + meta = dict( + shape=(2000,), + chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")), + data_type=np.dtype("u1"), + compressor=None, + fill_value=0, + filters=None, + chunk_memory_layout=order, + ) + array_key = meta_root + path + ".array.json" + group_key = meta_root + path + ".group.json" + store[array_key] = store._metadata_class.encode_array_metadata(meta) + + # don't overwrite + with pytest.raises(ValueError): + init_group(store, path=path) + + # do overwrite + try: + init_group(store, overwrite=True, path=path) + except NotImplementedError: + pass + else: + if self.version == 2: + assert array_meta_key not in store + assert group_meta_key in store + assert array_key not in store + assert group_key in store + # should have been overwritten + meta = store._metadata_class.decode_group_metadata(store[group_key]) + if self.version == 2: + assert ZARR_FORMAT == meta["zarr_format"] + else: + assert meta == {"attributes": {}} + + store.close() + + def _test_init_group_overwrite_chunk_store(self, order): + if self.version == 3: + pytest.skip("In v3 array and group names cannot overlap") + # setup + store = self.create_store() + chunk_store = self.create_store() + store[array_meta_key] = store._metadata_class.encode_array_metadata( + dict( + shape=(2000,), + chunks=(200,), + dtype=np.dtype("u1"), + compressor=None, + fill_value=0, + filters=None, + order=order, + ) + ) + chunk_store["foo"] = b"bar" + chunk_store["baz"] = b"quux" + + # don't overwrite array (default) + with pytest.raises(ValueError): + init_group(store, chunk_store=chunk_store) + + # do overwrite + try: + init_group(store, overwrite=True, chunk_store=chunk_store) + except NotImplementedError: + pass + else: + assert array_meta_key not in store + assert group_meta_key in store + meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert "foo" not in chunk_store + assert "baz" not in chunk_store + + # don't overwrite group + with pytest.raises(ValueError): + init_group(store) + + store.close() + chunk_store.close() + + +class TestMappingStore(StoreTests): + def create_store(self, **kwargs): + skip_if_nested_chunks(**kwargs) + return KVStore(dict()) + + def test_set_invalid_content(self): + # Generic mappings support non-buffer types + pass + + +def setdel_hierarchy_checks(store, root=""): + # these tests are for stores that are aware of hierarchy levels; this + # behaviour is not strictly required by Zarr but these tests are included + # to define behaviour of MemoryStore and DirectoryStore classes + + # check __setitem__ and __delitem__ blocked by leaf + + store[root + "a/b"] = b"aaa" + with pytest.raises(KeyError): + store[root + "a/b/c"] = b"xxx" + with pytest.raises(KeyError): + del store[root + "a/b/c"] + + store[root + "d"] = b"ddd" + with pytest.raises(KeyError): + store[root + "d/e/f"] = b"xxx" + with pytest.raises(KeyError): + del store[root + "d/e/f"] + + # test __setitem__ overwrite level + store[root + "x/y/z"] = b"xxx" + store[root + "x/y"] = b"yyy" + assert b"yyy" == ensure_bytes(store[root + "x/y"]) + assert root + "x/y/z" not in store + store[root + "x"] = b"zzz" + assert b"zzz" == ensure_bytes(store[root + "x"]) + assert root + "x/y" not in store + + # test __delitem__ overwrite level + store[root + "r/s/t"] = b"xxx" + del store[root + "r/s"] + assert root + "r/s/t" not in store + store[root + "r/s"] = b"xxx" + del store[root + "r"] + assert root + "r/s" not in store + + +class TestMemoryStore(StoreTests): + def create_store(self, **kwargs): + skip_if_nested_chunks(**kwargs) + return MemoryStore(**kwargs) + + def test_store_contains_bytes(self): + store = self.create_store() + store[self.root + "foo"] = np.array([97, 98, 99, 100, 101], dtype=np.uint8) + assert store[self.root + "foo"] == b"abcde" + + def test_setdel(self): + store = self.create_store() + setdel_hierarchy_checks(store, self.root) + + +class TestDictStore(StoreTests): + def create_store(self, **kwargs): + skip_if_nested_chunks(**kwargs) + + with pytest.warns(DeprecationWarning): + return DictStore(**kwargs) + + def test_deprecated(self): + store = self.create_store() + assert isinstance(store, MemoryStore) + + def test_pickle(self): + with pytest.warns(DeprecationWarning): + # pickle.load() will also trigger deprecation warning + super().test_pickle() + + +class TestDirectoryStore(StoreTests): + def create_store(self, normalize_keys=False, dimension_separator=".", **kwargs): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = DirectoryStore( + path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs + ) + return store + + def test_filesystem_path(self): + # test behaviour with path that does not exist + path = "data/store" + if os.path.exists(path): + shutil.rmtree(path) + store = DirectoryStore(path) + # should only be created on demand + assert not os.path.exists(path) + store["foo"] = b"bar" + assert os.path.isdir(path) + + # check correct permissions + # regression test for https://github.com/zarr-developers/zarr-python/issues/325 + stat = os.stat(path) + mode = stat.st_mode & 0o666 + umask = os.umask(0) + os.umask(umask) + assert mode == (0o666 & ~umask) + + # test behaviour with file path + with tempfile.NamedTemporaryFile() as f: + with pytest.raises(ValueError): + DirectoryStore(f.name) + + def test_init_pathlib(self): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + DirectoryStore(pathlib.Path(path)) + + def test_pickle_ext(self): + store = self.create_store() + store2 = pickle.loads(pickle.dumps(store)) + + # check path is preserved + assert store.path == store2.path + + # check point to same underlying directory + assert self.root + "xxx" not in store + store2[self.root + "xxx"] = b"yyy" + assert b"yyy" == ensure_bytes(store[self.root + "xxx"]) + + def test_setdel(self): + store = self.create_store() + setdel_hierarchy_checks(store, self.root) + + def test_normalize_keys(self): + store = self.create_store(normalize_keys=True) + store[self.root + "FOO"] = b"bar" + assert self.root + "FOO" in store + assert self.root + "foo" in store + + def test_listing_keys_slash(self): + def mock_walker_slash(_path): + yield from [ + # trailing slash in first key + ("root_with_slash/", ["d1", "g1"], [".zgroup"]), + ("root_with_slash/d1", [], [".zarray"]), + ("root_with_slash/g1", [], [".zgroup"]), + ] + + res = set(DirectoryStore._keys_fast("root_with_slash/", walker=mock_walker_slash)) + assert res == {".zgroup", "g1/.zgroup", "d1/.zarray"} + + def test_listing_keys_no_slash(self): + def mock_walker_no_slash(_path): + yield from [ + # no trailing slash in first key + ("root_with_no_slash", ["d1", "g1"], [".zgroup"]), + ("root_with_no_slash/d1", [], [".zarray"]), + ("root_with_no_slash/g1", [], [".zgroup"]), + ] + + res = set(DirectoryStore._keys_fast("root_with_no_slash", mock_walker_no_slash)) + assert res == {".zgroup", "g1/.zgroup", "d1/.zarray"} + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestFSStore(StoreTests): + @pytest.fixture + def memory_store(self): + store = FSStore("memory://") + yield store + store.fs.store.clear() + + def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs): + if path is None: + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + + store = FSStore( + path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs + ) + return store + + def test_init_array(self): + store = self.create_store() + init_array(store, shape=1000, chunks=100) + + # check metadata + assert array_meta_key in store + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + assert meta["dimension_separator"] == "." + + def test_dimension_separator(self): + for x in (".", "/"): + store = self.create_store(dimension_separator=x) + norm = store._normalize_key + assert ".zarray" == norm(".zarray") + assert ".zarray" == norm("/.zarray") + assert ".zgroup" == norm("/.zgroup") + assert "group/.zarray" == norm("group/.zarray") + assert "group/.zgroup" == norm("group/.zgroup") + assert "group/.zarray" == norm("/group/.zarray") + assert "group/.zgroup" == norm("/group/.zgroup") + + def test_complex(self): + path1 = tempfile.mkdtemp() + path2 = tempfile.mkdtemp() + store = self.create_store( + path="simplecache::file://" + path1, + simplecache={"same_names": True, "cache_storage": path2}, + ) + assert not store + assert not os.listdir(path1) + assert not os.listdir(path2) + store[self.root + "foo"] = b"hello" + assert "foo" in os.listdir(str(path1) + "/" + self.root) + assert self.root + "foo" in store + assert not os.listdir(str(path2)) + assert store[self.root + "foo"] == b"hello" + assert "foo" in os.listdir(str(path2)) + + def test_deep_ndim(self): + import zarr + + store = self.create_store() + path = None if self.version == 2 else "group1" + foo = zarr.open_group(store=store, path=path) + bar = foo.create_group("bar") + baz = bar.create_dataset("baz", shape=(4, 4, 4), chunks=(2, 2, 2), dtype="i8") + baz[:] = 1 + if self.version == 2: + assert set(store.listdir()) == {".zgroup", "bar"} + else: + assert set(store.listdir()) == {"data", "meta", "zarr.json"} + assert set(store.listdir("meta/root/" + path)) == {"bar", "bar.group.json"} + assert set(store.listdir("data/root/" + path)) == {"bar"} + assert foo["bar"]["baz"][(0, 0, 0)] == 1 + + def test_not_fsspec(self): + import zarr + + path = tempfile.mkdtemp() + with pytest.raises(ValueError, match="storage_options"): + zarr.open_array(path, mode="w", storage_options={"some": "kwargs"}) + with pytest.raises(ValueError, match="storage_options"): + zarr.open_group(path, mode="w", storage_options={"some": "kwargs"}) + zarr.open_array("file://" + path, mode="w", shape=(1,), dtype="f8") + + def test_create(self): + import zarr + + path1 = tempfile.mkdtemp() + path2 = tempfile.mkdtemp() + g = zarr.open_group("file://" + path1, mode="w", storage_options={"auto_mkdir": True}) + a = g.create_dataset("data", shape=(8,)) + a[:4] = [0, 1, 2, 3] + assert "data" in os.listdir(path1) + assert ".zgroup" in os.listdir(path1) + + # consolidated metadata (GH#915) + consolidate_metadata("file://" + path1) + assert ".zmetadata" in os.listdir(path1) + + g = zarr.open_group( + "simplecache::file://" + path1, + mode="r", + storage_options={"cache_storage": path2, "same_names": True}, + ) + assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] + with pytest.raises(PermissionError): + g.data[:] = 1 + + @pytest.mark.parametrize("mode,allowed", [("r", False), ("r+", True)]) + def test_modify_consolidated(self, mode, allowed): + import zarr + + url = "file://" + tempfile.mkdtemp() + + # create + root = zarr.open_group(url, mode="w") + root.zeros("baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="i4") + zarr.consolidate_metadata(url) + + # reopen and modify + root = zarr.open_consolidated(url, mode=mode) + if allowed: + root["baz"][0, 0] = 7 + + root = zarr.open_consolidated(url, mode="r") + assert root["baz"][0, 0] == 7 + else: + with pytest.raises(zarr.errors.ReadOnlyError): + root["baz"][0, 0] = 7 + + @pytest.mark.parametrize("mode", ["r", "r+"]) + def test_modify_consolidated_metadata_raises(self, mode): + import zarr + + url = "file://" + tempfile.mkdtemp() + + # create + root = zarr.open_group(url, mode="w") + root.zeros("baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="i4") + zarr.consolidate_metadata(url) + + # reopen and modify + root = zarr.open_consolidated(url, mode=mode) + with pytest.raises(zarr.errors.ReadOnlyError): + root["baz"].resize(100, 100) + + def test_read_only(self): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = self.create_store(path=path) + store[self.root + "foo"] = b"bar" + + store = self.create_store(path=path, mode="r") + + with pytest.raises(PermissionError): + store[self.root + "foo"] = b"hex" + + with pytest.raises(PermissionError): + del store[self.root + "foo"] + + with pytest.raises(PermissionError): + store.delitems([self.root + "foo"]) + + with pytest.raises(PermissionError): + store.setitems({self.root + "foo": b"baz"}) + + with pytest.raises(PermissionError): + store.clear() + + with pytest.raises(PermissionError): + store.rmdir(self.root + "anydir") + + assert store[self.root + "foo"] == b"bar" + + def test_eq(self): + store1 = self.create_store(path="anypath") + store2 = self.create_store(path="anypath") + assert store1 == store2 + + @pytest.mark.usefixtures("s3") + def test_s3(self): + import zarr + + g = zarr.open_group("s3://test/out.zarr", mode="w", storage_options=self.s3so) + a = g.create_dataset("data", shape=(8,)) + a[:4] = [0, 1, 2, 3] + + g = zarr.open_group("s3://test/out.zarr", mode="r", storage_options=self.s3so) + + assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] + + # test via convenience + g = zarr.open("s3://test/out.zarr", mode="r", storage_options=self.s3so) + assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] + + @pytest.mark.usefixtures("s3") + def test_s3_complex(self): + import zarr + + g = zarr.open_group("s3://test/out.zarr", mode="w", storage_options=self.s3so) + expected = np.empty((8, 8, 8), dtype="int64") + expected[:] = -1 + a = g.create_dataset( + "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True + ) + expected[0] = 0 + expected[3] = 3 + expected[6, 6, 6] = 6 + a[6, 6, 6] = 6 + a[:4] = expected[:4] + + b = g.create_dataset( + "data_f", + shape=(8,), + chunks=(1,), + dtype=[("foo", "S3"), ("bar", "i4")], + fill_value=(b"b", 1), + ) + b[:4] = (b"aaa", 2) + g2 = zarr.open_group("s3://test/out.zarr", mode="r", storage_options=self.s3so) + + assert (g2.data[:] == expected).all() + a.chunk_store.fs.invalidate_cache("test/out.zarr/data") + a[:] = 5 + assert (a[:] == 5).all() + + assert g2.data_f["foo"].tolist() == [b"aaa"] * 4 + [b"b"] * 4 + with pytest.raises(PermissionError): + g2.data[:] = 5 + + with pytest.raises(PermissionError): + g2.store.setitems({}) + + with pytest.raises(PermissionError): + # even though overwrite=True, store is read-only, so fails + g2.create_dataset( + "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True + ) + + a = g.create_dataset( + "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True + ) + assert (a[:] == -np.ones((8, 8, 8))).all() + + def test_exceptions(self, memory_store): + fs = memory_store.fs + group = zarr.open(memory_store, mode="w") + x = group.create_dataset("x", data=[1, 2, 3]) + y = group.create_dataset("y", data=1) + fs.store["/x/0"] = None + fs.store["/y/0"] = None + # no exception from FSStore.getitems getting KeyError + assert group.store.getitems(["foo"], contexts={}) == {} + # exception from FSStore.getitems getting AttributeError + with pytest.raises(Exception): # noqa: B017 + group.store.getitems(["x/0"], contexts={}) + # exception from FSStore.getitems getting AttributeError + with pytest.raises(Exception): # noqa: B017 + x[...] + # exception from FSStore.__getitem__ getting AttributeError + with pytest.raises(Exception): # noqa: B017 + y[...] + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestFSStoreWithKeySeparator(StoreTests): + def create_store(self, normalize_keys=False, key_separator=".", **kwargs): + # Since the user is passing key_separator, that will take priority. + skip_if_nested_chunks(**kwargs) + + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + return FSStore(path, normalize_keys=normalize_keys, key_separator=key_separator) + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestFSStoreFromFilesystem(StoreTests): + def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs): + import fsspec + + fs = fsspec.filesystem("file") + + if path is None: + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + + with pytest.raises(ValueError): + # can't specify storage_options when passing an + # existing fs object + _ = FSStore(path, fs=fs, auto_mkdir=True) + + store = FSStore( + path, + normalize_keys=normalize_keys, + dimension_separator=dimension_separator, + fs=fs, + **kwargs, + ) + + return store + + +@pytest.fixture() +def s3(request): + # writable local S3 system + import shlex + import subprocess + import time + + if "BOTO_CONFIG" not in os.environ: # pragma: no cover + os.environ["BOTO_CONFIG"] = "/dev/null" + if "AWS_ACCESS_KEY_ID" not in os.environ: # pragma: no cover + os.environ["AWS_ACCESS_KEY_ID"] = "foo" + if "AWS_SECRET_ACCESS_KEY" not in os.environ: # pragma: no cover + os.environ["AWS_SECRET_ACCESS_KEY"] = "bar" + requests = pytest.importorskip("requests") + s3fs = pytest.importorskip("s3fs") + pytest.importorskip("moto") + + port = 5555 + endpoint_uri = f"http://127.0.0.1:{port}/" + proc = subprocess.Popen( + shlex.split(f"moto_server -p {port}"), + stderr=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + ) + + timeout = 5 + while timeout > 0: + try: + r = requests.get(endpoint_uri) + if r.ok: + break + except Exception: # pragma: no cover + pass + timeout -= 0.1 # pragma: no cover + time.sleep(0.1) # pragma: no cover + s3so = dict(client_kwargs={"endpoint_url": endpoint_uri}, use_listings_cache=False) + s3 = s3fs.S3FileSystem(anon=False, **s3so) + s3.mkdir("test") + request.cls.s3so = s3so + yield + proc.terminate() + proc.wait() + + +class TestNestedDirectoryStore(TestDirectoryStore): + def create_store(self, normalize_keys=False, **kwargs): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = NestedDirectoryStore(path, normalize_keys=normalize_keys, **kwargs) + return store + + def test_init_array(self): + store = self.create_store() + assert store._dimension_separator == "/" + init_array(store, shape=1000, chunks=100) + + # check metadata + assert array_meta_key in store + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + assert meta["dimension_separator"] == "/" + + def test_chunk_nesting(self): + store = self.create_store() + # any path where last segment looks like a chunk key gets special handling + store[self.root + "0.0"] = b"xxx" + assert b"xxx" == store[self.root + "0.0"] + # assert b'xxx' == store['0/0'] + store[self.root + "foo/10.20.30"] = b"yyy" + assert b"yyy" == store[self.root + "foo/10.20.30"] + # assert b'yyy' == store['foo/10/20/30'] + store[self.root + "42"] = b"zzz" + assert b"zzz" == store[self.root + "42"] + + def test_listdir(self): + store = self.create_store() + z = zarr.zeros((10, 10), chunks=(5, 5), store=store) + z[:] = 1 # write to all chunks + for k in store.listdir(): + assert store.get(k) is not None + + +class TestNestedDirectoryStoreNone: + def test_value_error(self): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = NestedDirectoryStore(path, normalize_keys=True, dimension_separator=None) + assert store._dimension_separator == "/" + + +class TestNestedDirectoryStoreWithWrongValue: + def test_value_error(self): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + with pytest.raises(ValueError): + NestedDirectoryStore(path, normalize_keys=True, dimension_separator=".") + + +class TestN5Store(TestNestedDirectoryStore): + def create_store(self, normalize_keys=False): + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = N5Store(path, normalize_keys=normalize_keys) + return store + + def test_equal(self): + store_a = self.create_store() + store_b = N5Store(store_a.path) + assert store_a == store_b + + @pytest.mark.parametrize("zarr_meta_key", [".zarray", ".zattrs", ".zgroup"]) + def test_del_zarr_meta_key(self, zarr_meta_key): + store = self.create_store() + store[n5_attrs_key] = json_dumps({"foo": "bar"}) + del store[zarr_meta_key] + assert n5_attrs_key not in store + + def test_chunk_nesting(self): + store = self.create_store() + store["0.0"] = b"xxx" + assert "0.0" in store + assert b"xxx" == store["0.0"] + # assert b'xxx' == store['0/0'] + store["foo/10.20.30"] = b"yyy" + assert "foo/10.20.30" in store + assert b"yyy" == store["foo/10.20.30"] + # N5 reverses axis order + assert b"yyy" == store["foo/30/20/10"] + del store["foo/10.20.30"] + assert "foo/30/20/10" not in store + store["42"] = b"zzz" + assert "42" in store + assert b"zzz" == store["42"] + + def test_init_array(self): + store = self.create_store() + init_array(store, shape=1000, chunks=100) + + # check metadata + assert array_meta_key in store + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert default_compressor.get_config() == compressor_config + # N5Store always has a fill value of 0 + assert meta["fill_value"] == 0 + assert meta["dimension_separator"] == "." + # Top-level groups AND arrays should have + # the n5 keyword in metadata + raw_n5_meta = json.loads(store[n5_attrs_key]) + assert raw_n5_meta.get("n5", None) == N5_FORMAT + + def test_init_array_path(self): + path = "foo/bar" + store = self.create_store() + init_array(store, shape=1000, chunks=100, path=path) + + # check metadata + key = path + "/" + array_meta_key + assert key in store + meta = store._metadata_class.decode_array_metadata(store[key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert default_compressor.get_config() == compressor_config + # N5Store always has a fill value of 0 + assert meta["fill_value"] == 0 + + def test_init_array_compat(self): + store = self.create_store() + init_array(store, shape=1000, chunks=100, compressor="none") + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert compressor_config is None + + def test_init_array_overwrite(self): + self._test_init_array_overwrite("C") + + def test_init_array_overwrite_path(self): + self._test_init_array_overwrite_path("C") + + def test_init_array_overwrite_chunk_store(self): + self._test_init_array_overwrite_chunk_store("C") + + def test_init_group_overwrite(self): + self._test_init_group_overwrite("C") + + def test_init_group_overwrite_path(self): + self._test_init_group_overwrite_path("C") + + def test_init_group_overwrite_chunk_store(self): + self._test_init_group_overwrite_chunk_store("C") + + def test_init_group(self): + store = self.create_store() + init_group(store) + store[".zattrs"] = json_dumps({"foo": "bar"}) + # check metadata + assert group_meta_key in store + assert group_meta_key in store.listdir() + assert group_meta_key in store.listdir("") + meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + + def test_filters(self): + all_filters, all_errors = zip( + *[ + (None, does_not_raise()), + ([], does_not_raise()), + ([AsType("f4", "f8")], pytest.raises(ValueError)), + ] + ) + for filters, error in zip(all_filters, all_errors): + store = self.create_store() + with error: + init_array(store, shape=1000, chunks=100, filters=filters) + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestN5FSStore(TestFSStore): + def create_store(self, normalize_keys=False, path=None, **kwargs): + if path is None: + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + + store = N5FSStore(path, normalize_keys=normalize_keys, **kwargs) + return store + + def test_equal(self): + store_a = self.create_store() + store_b = N5FSStore(store_a.path) + assert store_a == store_b + + # This is copied wholesale from the N5Store tests. The same test could + # be run by making TestN5FSStore inherit from both TestFSStore and + # TestN5Store, but a direct copy is arguably more explicit. + + @pytest.mark.parametrize("zarr_meta_key", [".zarray", ".zattrs", ".zgroup"]) + def test_del_zarr_meta_key(self, zarr_meta_key): + store = self.create_store() + store[n5_attrs_key] = json_dumps({"foo": "bar"}) + del store[zarr_meta_key] + assert n5_attrs_key not in store + + def test_chunk_nesting(self): + store = self.create_store() + store["0.0"] = b"xxx" + assert "0.0" in store + assert b"xxx" == store["0.0"] + # assert b'xxx' == store['0/0'] + store["foo/10.20.30"] = b"yyy" + assert "foo/10.20.30" in store + assert b"yyy" == store["foo/10.20.30"] + # N5 reverses axis order + assert b"yyy" == store["foo/30/20/10"] + del store["foo/10.20.30"] + assert "foo/30/20/10" not in store + store["42"] = b"zzz" + assert "42" in store + assert b"zzz" == store["42"] + + def test_init_array(self): + store = self.create_store() + init_array(store, shape=1000, chunks=100) + + # check metadata + assert array_meta_key in store + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert default_compressor.get_config() == compressor_config + # N5Store always has a fill value of 0 + assert meta["fill_value"] == 0 + assert meta["dimension_separator"] == "." + # Top-level groups AND arrays should have + # the n5 keyword in metadata + raw_n5_meta = json.loads(store[n5_attrs_key]) + assert raw_n5_meta.get("n5", None) == N5_FORMAT + + def test_init_array_path(self): + path = "foo/bar" + store = self.create_store() + init_array(store, shape=1000, chunks=100, path=path) + + # check metadata + key = path + "/" + array_meta_key + assert key in store + meta = store._metadata_class.decode_array_metadata(store[key]) + assert ZARR_FORMAT == meta["zarr_format"] + assert (1000,) == meta["shape"] + assert (100,) == meta["chunks"] + assert np.dtype(None) == meta["dtype"] + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert default_compressor.get_config() == compressor_config + # N5Store always has a fill value of 0 + assert meta["fill_value"] == 0 + + def test_init_array_compat(self): + store = self.create_store() + init_array(store, shape=1000, chunks=100, compressor="none") + meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) + # N5Store wraps the actual compressor + compressor_config = meta["compressor"]["compressor_config"] + assert compressor_config is None + + def test_init_array_overwrite(self): + self._test_init_array_overwrite("C") + + def test_init_array_overwrite_path(self): + self._test_init_array_overwrite_path("C") + + def test_init_array_overwrite_chunk_store(self): + self._test_init_array_overwrite_chunk_store("C") + + def test_init_group_overwrite(self): + self._test_init_group_overwrite("C") + + def test_init_group_overwrite_path(self): + self._test_init_group_overwrite_path("C") + + def test_init_group_overwrite_chunk_store(self): + self._test_init_group_overwrite_chunk_store("C") + + def test_dimension_separator(self): + with pytest.warns(UserWarning, match="dimension_separator"): + self.create_store(dimension_separator="/") + + def test_init_group(self): + store = self.create_store() + init_group(store) + store[".zattrs"] = json_dumps({"foo": "bar"}) + # check metadata + assert group_meta_key in store + assert group_meta_key in store.listdir() + assert group_meta_key in store.listdir("") + meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) + assert ZARR_FORMAT == meta["zarr_format"] + + def test_filters(self): + all_filters, all_errors = zip( + *[ + (None, does_not_raise()), + ([], does_not_raise()), + ([AsType("f4", "f8")], pytest.raises(ValueError)), + ] + ) + for filters, error in zip(all_filters, all_errors): + store = self.create_store() + with error: + init_array(store, shape=1000, chunks=100, filters=filters) + + +@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") +class TestNestedFSStore(TestNestedDirectoryStore): + def create_store(self, normalize_keys=False, path=None, **kwargs): + if path is None: + path = tempfile.mkdtemp() + atexit.register(atexit_rmtree, path) + store = FSStore( + path, normalize_keys=normalize_keys, dimension_separator="/", auto_mkdir=True, **kwargs + ) + return store + + def test_numbered_groups(self): + import zarr + + # Create an array + store = self.create_store() + group = zarr.group(store=store) + arr = group.create_dataset("0", shape=(10, 10)) + arr[1] = 1 + + # Read it back + store = self.create_store(path=store.path) + zarr.open_group(store.path)["0"] + + +class TestTempStore(StoreTests): + def create_store(self, **kwargs): + skip_if_nested_chunks(**kwargs) + return TempStore(**kwargs) + + def test_setdel(self): + store = self.create_store() + setdel_hierarchy_checks(store, self.root) + + +class TestZipStore(StoreTests): + ZipStoreClass = ZipStore + + def create_store(self, **kwargs): + path = mktemp(suffix=".zip") + atexit.register(os.remove, path) + store = ZipStore(path, mode="w", **kwargs) + return store + + def test_mode(self): + with self.ZipStoreClass("data/store.zip", mode="w") as store: + store[self.root + "foo"] = b"bar" + store = self.ZipStoreClass("data/store.zip", mode="r") + with pytest.raises(PermissionError): + store[self.root + "foo"] = b"bar" + with pytest.raises(PermissionError): + store.clear() + + def test_flush(self): + store = self.ZipStoreClass("data/store.zip", mode="w") + store[self.root + "foo"] = b"bar" + store.flush() + assert store[self.root + "foo"] == b"bar" + store.close() + + store = self.ZipStoreClass("data/store.zip", mode="r") + store.flush() # no-op + + def test_context_manager(self): + with self.create_store() as store: + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"qux" + assert 2 == len(store) + + def test_pop(self): + # override because not implemented + store = self.create_store() + store[self.root + "foo"] = b"bar" + with pytest.raises(NotImplementedError): + store.pop(self.root + "foo") + + def test_popitem(self): + # override because not implemented + store = self.create_store() + store[self.root + "foo"] = b"bar" + with pytest.raises(NotImplementedError): + store.popitem() + + def test_permissions(self): + store = self.ZipStoreClass("data/store.zip", mode="w") + foo_key = "foo" if self.version == 2 else self.root + "foo" + # TODO: cannot provide key ending in / for v3 + # how to create an empty folder in that case? + baz_key = "baz/" if self.version == 2 else self.root + "baz" + store[foo_key] = b"bar" + store[baz_key] = b"" + + store.flush() + store.close() + z = ZipFile("data/store.zip", "r") + info = z.getinfo(foo_key) + perm = oct(info.external_attr >> 16) + assert perm == "0o644" + info = z.getinfo(baz_key) + perm = oct(info.external_attr >> 16) + # only for posix platforms + if os.name == "posix": + if self.version == 2: + assert perm == "0o40775" + else: + # baz/ on v2, but baz on v3, so not a directory + assert perm == "0o644" + z.close() + + def test_store_and_retrieve_ndarray(self): + store = ZipStore("data/store.zip") + x = np.array([[1, 2], [3, 4]]) + store["foo"] = x + y = np.frombuffer(store["foo"], dtype=x.dtype).reshape(x.shape) + assert np.array_equiv(y, x) + + +class TestDBMStore(StoreTests): + def create_store(self, dimension_separator=None): + path = mktemp(suffix=".anydbm") + atexit.register(atexit_rmglob, path + "*") + # create store using default dbm implementation + store = DBMStore(path, flag="n", dimension_separator=dimension_separator) + return store + + def test_context_manager(self): + with self.create_store() as store: + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"qux" + assert 2 == len(store) + + +class TestDBMStoreDumb(TestDBMStore): + def create_store(self, **kwargs): + path = mktemp(suffix=".dumbdbm") + atexit.register(atexit_rmglob, path + "*") + + import dbm.dumb as dumbdbm + + store = DBMStore(path, flag="n", open=dumbdbm.open, **kwargs) + return store + + +class TestDBMStoreGnu(TestDBMStore): + def create_store(self, **kwargs): + gdbm = pytest.importorskip("dbm.gnu") + path = mktemp(suffix=".gdbm") # pragma: no cover + atexit.register(os.remove, path) # pragma: no cover + store = DBMStore( + path, flag="n", open=gdbm.open, write_lock=False, **kwargs + ) # pragma: no cover + return store # pragma: no cover + + +class TestDBMStoreNDBM(TestDBMStore): + def create_store(self, **kwargs): + ndbm = pytest.importorskip("dbm.ndbm") + path = mktemp(suffix=".ndbm") # pragma: no cover + atexit.register(atexit_rmglob, path + "*") # pragma: no cover + store = DBMStore(path, flag="n", open=ndbm.open, **kwargs) # pragma: no cover + return store # pragma: no cover + + +class TestLMDBStore(StoreTests): + def create_store(self, **kwargs): + pytest.importorskip("lmdb") + path = mktemp(suffix=".lmdb") + atexit.register(atexit_rmtree, path) + buffers = True + store = LMDBStore(path, buffers=buffers, **kwargs) + return store + + def test_context_manager(self): + with self.create_store() as store: + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"qux" + assert 2 == len(store) + + +class TestSQLiteStore(StoreTests): + def create_store(self, **kwargs): + pytest.importorskip("sqlite3") + path = mktemp(suffix=".db") + atexit.register(atexit_rmtree, path) + store = SQLiteStore(path, **kwargs) + return store + + def test_underscore_in_name(self): + path = mktemp(suffix=".db") + atexit.register(atexit_rmtree, path) + store = SQLiteStore(path) + store["a"] = b"aaa" + store["a_b"] = b"aa_bb" + store.rmdir("a") + assert "a_b" in store + + +class TestSQLiteStoreInMemory(TestSQLiteStore): + def create_store(self, **kwargs): + pytest.importorskip("sqlite3") + store = SQLiteStore(":memory:", **kwargs) + return store + + def test_pickle(self): + # setup store + store = self.create_store() + store[self.root + "foo"] = b"bar" + store[self.root + "baz"] = b"quux" + + # round-trip through pickle + with pytest.raises(PicklingError): + pickle.dumps(store) + + +@skip_test_env_var("ZARR_TEST_MONGO") +class TestMongoDBStore(StoreTests): + def create_store(self, **kwargs): + pytest.importorskip("pymongo") + store = MongoDBStore( + host="127.0.0.1", database="zarr_tests", collection="zarr_tests", **kwargs + ) + # start with an empty store + store.clear() + return store + + +@skip_test_env_var("ZARR_TEST_REDIS") +class TestRedisStore(StoreTests): + def create_store(self, **kwargs): + # TODO: this is the default host for Redis on Travis, + # we probably want to generalize this though + pytest.importorskip("redis") + store = RedisStore(host="localhost", port=6379, **kwargs) + # start with an empty store + store.clear() + return store + + +class TestLRUStoreCache(StoreTests): + CountingClass = CountingDict + LRUStoreClass = LRUStoreCache + + def create_store(self, **kwargs): + # wrapper therefore no dimension_separator argument + skip_if_nested_chunks(**kwargs) + return self.LRUStoreClass(dict(), max_size=2**27) + + def test_cache_values_no_max_size(self): + # setup store + store = self.CountingClass() + foo_key = self.root + "foo" + bar_key = self.root + "bar" + store[foo_key] = b"xxx" + store[bar_key] = b"yyy" + assert 0 == store.counter["__getitem__", foo_key] + assert 1 == store.counter["__setitem__", foo_key] + assert 0 == store.counter["__getitem__", bar_key] + assert 1 == store.counter["__setitem__", bar_key] + + # setup cache + cache = self.LRUStoreClass(store, max_size=None) + assert 0 == cache.hits + assert 0 == cache.misses + + # test first __getitem__, cache miss + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 1 == store.counter["__setitem__", foo_key] + assert 0 == cache.hits + assert 1 == cache.misses + + # test second __getitem__, cache hit + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 1 == store.counter["__setitem__", foo_key] + assert 1 == cache.hits + assert 1 == cache.misses + + # test __setitem__, __getitem__ + cache[foo_key] = b"zzz" + assert 1 == store.counter["__getitem__", foo_key] + assert 2 == store.counter["__setitem__", foo_key] + # should be a cache hit + assert b"zzz" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 2 == store.counter["__setitem__", foo_key] + assert 2 == cache.hits + assert 1 == cache.misses + + # manually invalidate all cached values + cache.invalidate_values() + assert b"zzz" == cache[foo_key] + assert 2 == store.counter["__getitem__", foo_key] + assert 2 == store.counter["__setitem__", foo_key] + cache.invalidate() + assert b"zzz" == cache[foo_key] + assert 3 == store.counter["__getitem__", foo_key] + assert 2 == store.counter["__setitem__", foo_key] + + # test __delitem__ + del cache[foo_key] + with pytest.raises(KeyError): + # noinspection PyStatementEffect + cache[foo_key] + with pytest.raises(KeyError): + # noinspection PyStatementEffect + store[foo_key] + + # verify other keys untouched + assert 0 == store.counter["__getitem__", bar_key] + assert 1 == store.counter["__setitem__", bar_key] + + def test_cache_values_with_max_size(self): + # setup store + store = self.CountingClass() + foo_key = self.root + "foo" + bar_key = self.root + "bar" + store[foo_key] = b"xxx" + store[bar_key] = b"yyy" + assert 0 == store.counter["__getitem__", foo_key] + assert 0 == store.counter["__getitem__", bar_key] + # setup cache - can only hold one item + cache = self.LRUStoreClass(store, max_size=5) + assert 0 == cache.hits + assert 0 == cache.misses + + # test first 'foo' __getitem__, cache miss + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 0 == cache.hits + assert 1 == cache.misses + + # test second 'foo' __getitem__, cache hit + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 1 == cache.hits + assert 1 == cache.misses + + # test first 'bar' __getitem__, cache miss + assert b"yyy" == cache[bar_key] + assert 1 == store.counter["__getitem__", bar_key] + assert 1 == cache.hits + assert 2 == cache.misses + + # test second 'bar' __getitem__, cache hit + assert b"yyy" == cache[bar_key] + assert 1 == store.counter["__getitem__", bar_key] + assert 2 == cache.hits + assert 2 == cache.misses + + # test 'foo' __getitem__, should have been evicted, cache miss + assert b"xxx" == cache[foo_key] + assert 2 == store.counter["__getitem__", foo_key] + assert 2 == cache.hits + assert 3 == cache.misses + + # test 'bar' __getitem__, should have been evicted, cache miss + assert b"yyy" == cache[bar_key] + assert 2 == store.counter["__getitem__", bar_key] + assert 2 == cache.hits + assert 4 == cache.misses + + # setup store + store = self.CountingClass() + store[foo_key] = b"xxx" + store[bar_key] = b"yyy" + assert 0 == store.counter["__getitem__", foo_key] + assert 0 == store.counter["__getitem__", bar_key] + # setup cache - can hold two items + cache = self.LRUStoreClass(store, max_size=6) + assert 0 == cache.hits + assert 0 == cache.misses + + # test first 'foo' __getitem__, cache miss + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 0 == cache.hits + assert 1 == cache.misses + + # test second 'foo' __getitem__, cache hit + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 1 == cache.hits + assert 1 == cache.misses + + # test first 'bar' __getitem__, cache miss + assert b"yyy" == cache[bar_key] + assert 1 == store.counter["__getitem__", bar_key] + assert 1 == cache.hits + assert 2 == cache.misses + + # test second 'bar' __getitem__, cache hit + assert b"yyy" == cache[bar_key] + assert 1 == store.counter["__getitem__", bar_key] + assert 2 == cache.hits + assert 2 == cache.misses + + # test 'foo' __getitem__, should still be cached + assert b"xxx" == cache[foo_key] + assert 1 == store.counter["__getitem__", foo_key] + assert 3 == cache.hits + assert 2 == cache.misses + + # test 'bar' __getitem__, should still be cached + assert b"yyy" == cache[bar_key] + assert 1 == store.counter["__getitem__", bar_key] + assert 4 == cache.hits + assert 2 == cache.misses + + def test_cache_keys(self): + # setup + store = self.CountingClass() + foo_key = self.root + "foo" + bar_key = self.root + "bar" + baz_key = self.root + "baz" + store[foo_key] = b"xxx" + store[bar_key] = b"yyy" + assert 0 == store.counter["__contains__", foo_key] + assert 0 == store.counter["__iter__"] + assert 0 == store.counter["keys"] + cache = self.LRUStoreClass(store, max_size=None) + + # keys should be cached on first call + keys = sorted(cache.keys()) + assert keys == [bar_key, foo_key] + assert 1 == store.counter["keys"] + # keys should now be cached + assert keys == sorted(cache.keys()) + assert 1 == store.counter["keys"] + assert foo_key in cache + assert 1 == store.counter["__contains__", foo_key] + # the next check for `foo_key` is cached + assert foo_key in cache + assert 1 == store.counter["__contains__", foo_key] + assert keys == sorted(cache) + assert 0 == store.counter["__iter__"] + assert 1 == store.counter["keys"] + + # cache should be cleared if store is modified - crude but simple for now + cache[baz_key] = b"zzz" + keys = sorted(cache.keys()) + assert keys == [bar_key, baz_key, foo_key] + assert 2 == store.counter["keys"] + # keys should now be cached + assert keys == sorted(cache.keys()) + assert 2 == store.counter["keys"] + + # manually invalidate keys + cache.invalidate_keys() + keys = sorted(cache.keys()) + assert keys == [bar_key, baz_key, foo_key] + assert 3 == store.counter["keys"] + assert 1 == store.counter["__contains__", foo_key] + assert 0 == store.counter["__iter__"] + cache.invalidate_keys() + keys = sorted(cache) + assert keys == [bar_key, baz_key, foo_key] + assert 4 == store.counter["keys"] + assert 1 == store.counter["__contains__", foo_key] + assert 0 == store.counter["__iter__"] + cache.invalidate_keys() + assert foo_key in cache + assert 4 == store.counter["keys"] + assert 2 == store.counter["__contains__", foo_key] + assert 0 == store.counter["__iter__"] + + # check these would get counted if called directly + assert foo_key in store + assert 3 == store.counter["__contains__", foo_key] + assert keys == sorted(store) + assert 1 == store.counter["__iter__"] + + +def test_getsize(): + store = KVStore(dict()) + store["foo"] = b"aaa" + store["bar"] = b"bbbb" + store["baz/quux"] = b"ccccc" + assert 7 == getsize(store) + assert 5 == getsize(store, "baz") + + store = KVStore(dict()) + store["boo"] = None + assert -1 == getsize(store) + + +@pytest.mark.parametrize("dict_store", [False, True]) +def test_migrate_1to2(dict_store): + from zarr import meta_v1 + + # N.B., version 1 did not support hierarchies, so we only have to be + # concerned about migrating a single array at the root of the store + + # setup + store = dict() if dict_store else KVStore(dict()) + meta = dict( + shape=(100,), + chunks=(10,), + dtype=np.dtype("f4"), + compression="zlib", + compression_opts=1, + fill_value=None, + order="C", + ) + meta_json = meta_v1.encode_metadata(meta) + store["meta"] = meta_json + store["attrs"] = json.dumps(dict()).encode("ascii") + + # run migration + migrate_1to2(store) + + # check results + assert "meta" not in store + assert array_meta_key in store + assert "attrs" not in store + assert attrs_key in store + meta_migrated = decode_array_metadata(store[array_meta_key]) + assert 2 == meta_migrated["zarr_format"] + + # preserved fields + for f in "shape", "chunks", "dtype", "fill_value", "order": + assert meta[f] == meta_migrated[f] + + # migrate should have added empty filters field + assert meta_migrated["filters"] is None + + # check compression and compression_opts migrated to compressor + assert "compression" not in meta_migrated + assert "compression_opts" not in meta_migrated + assert meta_migrated["compressor"] == Zlib(1).get_config() + + # check dict compression_opts + store = dict() if dict_store else KVStore(dict()) + meta["compression"] = "blosc" + meta["compression_opts"] = dict(cname="lz4", clevel=5, shuffle=1) + meta_json = meta_v1.encode_metadata(meta) + store["meta"] = meta_json + store["attrs"] = json.dumps(dict()).encode("ascii") + migrate_1to2(store) + meta_migrated = decode_array_metadata(store[array_meta_key]) + assert "compression" not in meta_migrated + assert "compression_opts" not in meta_migrated + assert meta_migrated["compressor"] == Blosc(cname="lz4", clevel=5, shuffle=1).get_config() + + # check 'none' compression is migrated to None (null in JSON) + store = dict() if dict_store else KVStore(dict()) + meta["compression"] = "none" + meta_json = meta_v1.encode_metadata(meta) + store["meta"] = meta_json + store["attrs"] = json.dumps(dict()).encode("ascii") + migrate_1to2(store) + meta_migrated = decode_array_metadata(store[array_meta_key]) + assert "compression" not in meta_migrated + assert "compression_opts" not in meta_migrated + assert meta_migrated["compressor"] is None + + +def test_format_compatibility(): + # This test is intended to catch any unintended changes that break the ability to + # read data stored with a previous minor version (which should be format-compatible). + + # fixture data + fixture = group(store=DirectoryStore("fixture")) + + # set seed to get consistent random data + np.random.seed(42) + + arrays_chunks = [ + (np.arange(1111, dtype=" 2 else "" + # setup some values + store[prefix + "a"] = b"aaa" + store[prefix + "b"] = b"bbb" + store[prefix + "c/d"] = b"ddd" + store[prefix + "c/e/f"] = b"fff" + + # test iterators on store with data + assert 4 == len(store) + keys = [prefix + "a", prefix + "b", prefix + "c/d", prefix + "c/e/f"] + values = [b"aaa", b"bbb", b"ddd", b"fff"] + items = list(zip(keys, values)) + assert set(keys) == set(store) + assert set(keys) == set(store.keys()) + assert set(values) == set(store.values()) + assert set(items) == set(store.items()) + + def test_getsize(self): + return super().test_getsize() + + def test_hierarchy(self): + return super().test_hierarchy() + + @pytest.mark.skipif(sys.version_info < (3, 7), reason="attr not serializable in py36") + def test_pickle(self): + # internal attribute on ContainerClient isn't serializable for py36 and earlier + super().test_pickle() + + +class TestConsolidatedMetadataStore: + version = 2 + ConsolidatedMetadataClass = ConsolidatedMetadataStore + + @property + def metadata_key(self): + return ".zmetadata" + + def test_bad_format(self): + # setup store with consolidated metadata + store = dict() + consolidated = { + # bad format version + "zarr_consolidated_format": 0, + } + store[self.metadata_key] = json.dumps(consolidated).encode() + + # check appropriate error is raised + with pytest.raises(MetadataError): + self.ConsolidatedMetadataClass(store) + + def test_bad_store_version(self): + with pytest.raises(ValueError): + self.ConsolidatedMetadataClass(KVStoreV3(dict())) + + def test_read_write(self): + # setup store with consolidated metadata + store = dict() + consolidated = { + "zarr_consolidated_format": 1, + "metadata": { + "foo": "bar", + "baz": 42, + }, + } + store[self.metadata_key] = json.dumps(consolidated).encode() + + # create consolidated store + cs = self.ConsolidatedMetadataClass(store) + + # test __contains__, __getitem__ + for key, value in consolidated["metadata"].items(): + assert key in cs + assert value == cs[key] + + # test __delitem__, __setitem__ + with pytest.raises(PermissionError): + del cs["foo"] + with pytest.raises(PermissionError): + cs["bar"] = 0 + with pytest.raises(PermissionError): + cs["spam"] = "eggs" + + +# standalone test we do not want to run on each store. + + +def test_fill_value_change(): + a = zarr.create((10, 10), dtype=int) + + assert a[0, 0] == 0 + + a.fill_value = 1 + + assert a[0, 0] == 1 + + assert json.loads(a.store[".zarray"])["fill_value"] == 1 + + +def test_get_hierarchy_metadata_v2(): + # v2 stores do not have hierarchy metadata (i.e. zarr.json) + with pytest.raises(ValueError): + _get_hierarchy_metadata(KVStore(dict)) + + +def test_normalize_store_arg(tmpdir): + with pytest.raises(ValueError): + normalize_store_arg(dict(), zarr_version=4) + + for ext, Class in [(".zip", ZipStore), (".n5", N5Store)]: + fn = tmpdir.join("store" + ext) + store = normalize_store_arg(str(fn), zarr_version=2, mode="w") + assert isinstance(store, Class) + + if have_fsspec: + import fsspec + + path = tempfile.mkdtemp() + store = normalize_store_arg("file://" + path, zarr_version=2, mode="w") + assert isinstance(store, FSStore) + + store = normalize_store_arg(fsspec.get_mapper("file://" + path)) + assert isinstance(store, FSStore) + + +def test_meta_prefix_6853(): + fixture = pathlib.Path(zarr.__file__).resolve().parent.parent / "fixture" + meta = fixture / "meta" + if not meta.exists(): # pragma: no cover + s = DirectoryStore(str(meta), dimension_separator=".") + a = zarr.open(store=s, mode="w", shape=(2, 2), dtype=" str: + return self.error_message or "" + + +class OutOfResources(TritonError): + + def __init__(self, required, limit, name): + self.required = required + self.limit = limit + self.name = name + + def __str__(self) -> str: + return f"out of resource: {self.name}, Required: {self.required}, Hardware limit: {self.limit}. Reducing block sizes or `num_stages` may help." + + def __reduce__(self): + # this is necessary to make CompilationError picklable + return (type(self), (self.required, self.limit, self.name)) + + +class PTXASError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + error_message = self.error_message or "" + return f"PTXAS error: {error_message}" diff --git a/shared/package-files/0b/0b10d0b4b66900c83776c10351d6a20b299e6d9a55c0cf20a7b049c9b151acbc/normalization.py b/shared/package-files/0b/0b10d0b4b66900c83776c10351d6a20b299e6d9a55c0cf20a7b049c9b151acbc/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..e025184bd4a20c75a51993aa999e71f2c11f8e63 --- /dev/null +++ b/shared/package-files/0b/0b10d0b4b66900c83776c10351d6a20b299e6d9a55c0cf20a7b049c9b151acbc/normalization.py @@ -0,0 +1,346 @@ +# mypy: allow-untyped-defs +import torch + + +__all__ = [ + "LayerNorm", + "GroupNorm", + "InstanceNorm1d", + "InstanceNorm2d", + "InstanceNorm3d", +] + + +class LayerNorm(torch.nn.LayerNorm): + r"""This is the quantized version of :class:`~torch.nn.LayerNorm`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + + def __init__( + self, + normalized_shape, + weight, + bias, + scale, + zero_point, + eps=1e-5, + elementwise_affine=True, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + normalized_shape, + eps=eps, + elementwise_affine=elementwise_affine, + **factory_kwargs, + ) + self.weight = weight + self.bias = bias + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.layer_norm( + input, + self.normalized_shape, + weight=self.weight, + bias=self.bias, + eps=self.eps, + output_scale=self.scale, + output_zero_point=self.zero_point, + ) + + def _get_name(self): + return "QuantizedLayerNorm" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.normalized_shape, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.elementwise_affine, + ) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.normalized_shape, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.elementwise_affine, + ) + + +class GroupNorm(torch.nn.GroupNorm): + r"""This is the quantized version of :class:`~torch.nn.GroupNorm`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + __constants__ = ["num_groups", "num_channels", "eps", "affine"] + + def __init__( + self, + num_groups, + num_channels, + weight, + bias, + scale, + zero_point, + eps=1e-5, + affine=True, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__(num_groups, num_channels, eps, affine, **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.group_norm( + input, + self.num_groups, + self.weight, + self.bias, + self.eps, + self.scale, + self.zero_point, + ) + + def _get_name(self): + return "QuantizedGroupNorm" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_groups, + mod.num_channels, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + return new_mod + + +class InstanceNorm1d(torch.nn.InstanceNorm1d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm1d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + + def __init__( + self, + num_features, + weight, + bias, + scale, + zero_point, + eps=1e-5, + momentum=0.1, + affine=False, + track_running_stats=False, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + num_features, eps, momentum, affine, track_running_stats, **factory_kwargs + ) + self.weight = weight + self.bias = bias + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedInstanceNorm1d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + + +class InstanceNorm2d(torch.nn.InstanceNorm2d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm2d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + + def __init__( + self, + num_features, + weight, + bias, + scale, + zero_point, + eps=1e-5, + momentum=0.1, + affine=False, + track_running_stats=False, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + num_features, eps, momentum, affine, track_running_stats, **factory_kwargs + ) + self.weight = weight + self.bias = bias + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedInstanceNorm2d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + + +class InstanceNorm3d(torch.nn.InstanceNorm3d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm3d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + + def __init__( + self, + num_features, + weight, + bias, + scale, + zero_point, + eps=1e-5, + momentum=0.1, + affine=False, + track_running_stats=False, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + num_features, eps, momentum, affine, track_running_stats, **factory_kwargs + ) + self.weight = weight + self.bias = bias + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedInstanceNorm3d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, + mod.weight, + mod.bias, + float(scale), + int(zero_point), + mod.eps, + mod.affine, + ) diff --git a/shared/package-files/0b/0b1508de60736b3430b0a06186c88cede449fbce16d4ef9b580e327f36c69a3a/test_pynodes.cpython-311.pyc b/shared/package-files/0b/0b1508de60736b3430b0a06186c88cede449fbce16d4ef9b580e327f36c69a3a/test_pynodes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1be5a2bf8118acd02bbb149ff51ab666852733d Binary files /dev/null and b/shared/package-files/0b/0b1508de60736b3430b0a06186c88cede449fbce16d4ef9b580e327f36c69a3a/test_pynodes.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b153a3908429ae92056178405f8d44ad204282cbc188ac7ab5ea4bf3c4f65e0/pty.py b/shared/package-files/0b/0b153a3908429ae92056178405f8d44ad204282cbc188ac7ab5ea4bf3c4f65e0/pty.py new file mode 100644 index 0000000000000000000000000000000000000000..fefb63abfb04e4fd08dabad5a7627e555fc33220 --- /dev/null +++ b/shared/package-files/0b/0b153a3908429ae92056178405f8d44ad204282cbc188ac7ab5ea4bf3c4f65e0/pty.py @@ -0,0 +1,217 @@ +"""Pseudo terminal utilities.""" + +# Bugs: No signal handling. Doesn't set slave termios and window size. +# Only tested on Linux, FreeBSD, and macOS. +# See: W. Richard Stevens. 1992. Advanced Programming in the +# UNIX Environment. Chapter 19. +# Author: Steen Lumholt -- with additions by Guido. + +from select import select +import os +import sys +import tty + +# names imported directly for test mocking purposes +from os import close, waitpid +from tty import setraw, tcgetattr, tcsetattr + +__all__ = ["openpty", "fork", "spawn"] + +STDIN_FILENO = 0 +STDOUT_FILENO = 1 +STDERR_FILENO = 2 + +CHILD = 0 + +def openpty(): + """openpty() -> (master_fd, slave_fd) + Open a pty master/slave pair, using os.openpty() if possible.""" + + try: + return os.openpty() + except (AttributeError, OSError): + pass + master_fd, slave_name = _open_terminal() + slave_fd = slave_open(slave_name) + return master_fd, slave_fd + +def master_open(): + """master_open() -> (master_fd, slave_name) + Open a pty master and return the fd, and the filename of the slave end. + Deprecated, use openpty() instead.""" + + try: + master_fd, slave_fd = os.openpty() + except (AttributeError, OSError): + pass + else: + slave_name = os.ttyname(slave_fd) + os.close(slave_fd) + return master_fd, slave_name + + return _open_terminal() + +def _open_terminal(): + """Open pty master and return (master_fd, tty_name).""" + for x in 'pqrstuvwxyzPQRST': + for y in '0123456789abcdef': + pty_name = '/dev/pty' + x + y + try: + fd = os.open(pty_name, os.O_RDWR) + except OSError: + continue + return (fd, '/dev/tty' + x + y) + raise OSError('out of pty devices') + +def slave_open(tty_name): + """slave_open(tty_name) -> slave_fd + Open the pty slave and acquire the controlling terminal, returning + opened filedescriptor. + Deprecated, use openpty() instead.""" + + result = os.open(tty_name, os.O_RDWR) + try: + from fcntl import ioctl, I_PUSH + except ImportError: + return result + try: + ioctl(result, I_PUSH, "ptem") + ioctl(result, I_PUSH, "ldterm") + except OSError: + pass + return result + +def fork(): + """fork() -> (pid, master_fd) + Fork and make the child a session leader with a controlling terminal.""" + + try: + pid, fd = os.forkpty() + except (AttributeError, OSError): + pass + else: + if pid == CHILD: + try: + os.setsid() + except OSError: + # os.forkpty() already set us session leader + pass + return pid, fd + + master_fd, slave_fd = openpty() + pid = os.fork() + if pid == CHILD: + # Establish a new session. + os.setsid() + os.close(master_fd) + + # Slave becomes stdin/stdout/stderr of child. + os.dup2(slave_fd, STDIN_FILENO) + os.dup2(slave_fd, STDOUT_FILENO) + os.dup2(slave_fd, STDERR_FILENO) + if slave_fd > STDERR_FILENO: + os.close(slave_fd) + + # Explicitly open the tty to make it become a controlling tty. + tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) + os.close(tmp_fd) + else: + os.close(slave_fd) + + # Parent and child process. + return pid, master_fd + +def _read(fd): + """Default read function.""" + return os.read(fd, 1024) + +def _copy(master_fd, master_read=_read, stdin_read=_read): + """Parent copy loop. + Copies + pty master -> standard output (master_read) + standard input -> pty master (stdin_read)""" + if os.get_blocking(master_fd): + # If we write more than tty/ndisc is willing to buffer, we may block + # indefinitely. So we set master_fd to non-blocking temporarily during + # the copy operation. + os.set_blocking(master_fd, False) + try: + _copy(master_fd, master_read=master_read, stdin_read=stdin_read) + finally: + # restore blocking mode for backwards compatibility + os.set_blocking(master_fd, True) + return + high_waterlevel = 4096 + stdin_avail = master_fd != STDIN_FILENO + stdout_avail = master_fd != STDOUT_FILENO + i_buf = b'' + o_buf = b'' + while 1: + rfds = [] + wfds = [] + if stdin_avail and len(i_buf) < high_waterlevel: + rfds.append(STDIN_FILENO) + if stdout_avail and len(o_buf) < high_waterlevel: + rfds.append(master_fd) + if stdout_avail and len(o_buf) > 0: + wfds.append(STDOUT_FILENO) + if len(i_buf) > 0: + wfds.append(master_fd) + + rfds, wfds, _xfds = select(rfds, wfds, []) + + if STDOUT_FILENO in wfds: + try: + n = os.write(STDOUT_FILENO, o_buf) + o_buf = o_buf[n:] + except OSError: + stdout_avail = False + + if master_fd in rfds: + # Some OSes signal EOF by returning an empty byte string, + # some throw OSErrors. + try: + data = master_read(master_fd) + except OSError: + data = b"" + if not data: # Reached EOF. + return # Assume the child process has exited and is + # unreachable, so we clean up. + o_buf += data + + if master_fd in wfds: + n = os.write(master_fd, i_buf) + i_buf = i_buf[n:] + + if stdin_avail and STDIN_FILENO in rfds: + data = stdin_read(STDIN_FILENO) + if not data: + stdin_avail = False + else: + i_buf += data + +def spawn(argv, master_read=_read, stdin_read=_read): + """Create a spawned process.""" + if type(argv) == type(''): + argv = (argv,) + sys.audit('pty.spawn', argv) + + pid, master_fd = fork() + if pid == CHILD: + os.execlp(argv[0], *argv) + + try: + mode = tcgetattr(STDIN_FILENO) + setraw(STDIN_FILENO) + restore = True + except tty.error: # This is the same as termios.error + restore = False + + try: + _copy(master_fd, master_read, stdin_read) + finally: + if restore: + tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode) + + close(master_fd) + return waitpid(pid, 0)[1] diff --git a/shared/package-files/0b/0b17e5e91f60a69c54ded394e68d8e7ad611c1d2a5055face60b6ede7b0ee38a/unix_compat.cpython-311.pyc b/shared/package-files/0b/0b17e5e91f60a69c54ded394e68d8e7ad611c1d2a5055face60b6ede7b0ee38a/unix_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb59b1adcde3897bf7aa0a8d9c8ed80d5c087297 Binary files /dev/null and b/shared/package-files/0b/0b17e5e91f60a69c54ded394e68d8e7ad611c1d2a5055face60b6ede7b0ee38a/unix_compat.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b1b9ce1388ee5185f180d7331b1658d07038b0437b522db4ced15cf0d1c020a/triads.cpython-311.pyc b/shared/package-files/0b/0b1b9ce1388ee5185f180d7331b1658d07038b0437b522db4ced15cf0d1c020a/triads.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e087c0e31c8bae0aa43e118f1f93e4cdaa80182 Binary files /dev/null and b/shared/package-files/0b/0b1b9ce1388ee5185f180d7331b1658d07038b0437b522db4ced15cf0d1c020a/triads.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b1f94d1799e05ecae76933c05295644b577daf163482e017bac4aaa8405e906/__init__.cpython-311.pyc b/shared/package-files/0b/0b1f94d1799e05ecae76933c05295644b577daf163482e017bac4aaa8405e906/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d3136b0428200d8f9a1601042a70a7d67f804c1 Binary files /dev/null and b/shared/package-files/0b/0b1f94d1799e05ecae76933c05295644b577daf163482e017bac4aaa8405e906/__init__.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b2813b12b61c82287b3465366c0a05a7c9a4fc6a79d06cba54b5a8667d8f52c/summarization.py b/shared/package-files/0b/0b2813b12b61c82287b3465366c0a05a7c9a4fc6a79d06cba54b5a8667d8f52c/summarization.py new file mode 100644 index 0000000000000000000000000000000000000000..23db8da4efffa7dcbabfb75e031187d1b2b190dc --- /dev/null +++ b/shared/package-files/0b/0b2813b12b61c82287b3465366c0a05a7c9a4fc6a79d06cba54b5a8667d8f52c/summarization.py @@ -0,0 +1,564 @@ +""" +Graph summarization finds smaller representations of graphs resulting in faster +runtime of algorithms, reduced storage needs, and noise reduction. +Summarization has applications in areas such as visualization, pattern mining, +clustering and community detection, and more. Core graph summarization +techniques are grouping/aggregation, bit-compression, +simplification/sparsification, and influence based. Graph summarization +algorithms often produce either summary graphs in the form of supergraphs or +sparsified graphs, or a list of independent structures. Supergraphs are the +most common product, which consist of supernodes and original nodes and are +connected by edges and superedges, which represent aggregate edges between +nodes and supernodes. + +Grouping/aggregation based techniques compress graphs by representing +close/connected nodes and edges in a graph by a single node/edge in a +supergraph. Nodes can be grouped together into supernodes based on their +structural similarities or proximity within a graph to reduce the total number +of nodes in a graph. Edge-grouping techniques group edges into lossy/lossless +nodes called compressor or virtual nodes to reduce the total number of edges in +a graph. Edge-grouping techniques can be lossless, meaning that they can be +used to re-create the original graph, or techniques can be lossy, requiring +less space to store the summary graph, but at the expense of lower +reconstruction accuracy of the original graph. + +Bit-compression techniques minimize the amount of information needed to +describe the original graph, while revealing structural patterns in the +original graph. The two-part minimum description length (MDL) is often used to +represent the model and the original graph in terms of the model. A key +difference between graph compression and graph summarization is that graph +summarization focuses on finding structural patterns within the original graph, +whereas graph compression focuses on compressions the original graph to be as +small as possible. **NOTE**: Some bit-compression methods exist solely to +compress a graph without creating a summary graph or finding comprehensible +structural patterns. + +Simplification/Sparsification techniques attempt to create a sparse +representation of a graph by removing unimportant nodes and edges from the +graph. Sparsified graphs differ from supergraphs created by +grouping/aggregation by only containing a subset of the original nodes and +edges of the original graph. + +Influence based techniques aim to find a high-level description of influence +propagation in a large graph. These methods are scarce and have been mostly +applied to social graphs. + +*dedensification* is a grouping/aggregation based technique to compress the +neighborhoods around high-degree nodes in unweighted graphs by adding +compressor nodes that summarize multiple edges of the same type to +high-degree nodes (nodes with a degree greater than a given threshold). +Dedensification was developed for the purpose of increasing performance of +query processing around high-degree nodes in graph databases and enables direct +operations on the compressed graph. The structural patterns surrounding +high-degree nodes in the original is preserved while using fewer edges and +adding a small number of compressor nodes. The degree of nodes present in the +original graph is also preserved. The current implementation of dedensification +supports graphs with one edge type. + +For more information on graph summarization, see `Graph Summarization Methods +and Applications: A Survey `_ +""" + +from collections import Counter, defaultdict + +import networkx as nx + +__all__ = ["dedensify", "snap_aggregation"] + + +@nx._dispatchable(mutates_input={"not copy": 3}, returns_graph=True) +def dedensify(G, threshold, prefix=None, copy=True): + """Compresses neighborhoods around high-degree nodes + + Reduces the number of edges to high-degree nodes by adding compressor nodes + that summarize multiple edges of the same type to high-degree nodes (nodes + with a degree greater than a given threshold). Dedensification also has + the added benefit of reducing the number of edges around high-degree nodes. + The implementation currently supports graphs with a single edge type. + + Parameters + ---------- + G: graph + A networkx graph + threshold: int + Minimum degree threshold of a node to be considered a high degree node. + The threshold must be greater than or equal to 2. + prefix: str or None, optional (default: None) + An optional prefix for denoting compressor nodes + copy: bool, optional (default: True) + Indicates if dedensification should be done inplace + + Returns + ------- + dedensified networkx graph : (graph, set) + 2-tuple of the dedensified graph and set of compressor nodes + + Notes + ----- + According to the algorithm in [1]_, removes edges in a graph by + compressing/decompressing the neighborhoods around high degree nodes by + adding compressor nodes that summarize multiple edges of the same type + to high-degree nodes. Dedensification will only add a compressor node when + doing so will reduce the total number of edges in the given graph. This + implementation currently supports graphs with a single edge type. + + Examples + -------- + Dedensification will only add compressor nodes when doing so would result + in fewer edges:: + + >>> original_graph = nx.DiGraph() + >>> original_graph.add_nodes_from( + ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"] + ... ) + >>> original_graph.add_edges_from( + ... [ + ... ("1", "C"), ("1", "B"), + ... ("2", "C"), ("2", "B"), ("2", "A"), + ... ("3", "B"), ("3", "A"), ("3", "6"), + ... ("4", "C"), ("4", "B"), ("4", "A"), + ... ("5", "B"), ("5", "A"), + ... ("6", "5"), + ... ("A", "6") + ... ] + ... ) + >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2) + >>> original_graph.number_of_edges() + 15 + >>> c_graph.number_of_edges() + 14 + + A dedensified, directed graph can be "densified" to reconstruct the + original graph:: + + >>> original_graph = nx.DiGraph() + >>> original_graph.add_nodes_from( + ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"] + ... ) + >>> original_graph.add_edges_from( + ... [ + ... ("1", "C"), ("1", "B"), + ... ("2", "C"), ("2", "B"), ("2", "A"), + ... ("3", "B"), ("3", "A"), ("3", "6"), + ... ("4", "C"), ("4", "B"), ("4", "A"), + ... ("5", "B"), ("5", "A"), + ... ("6", "5"), + ... ("A", "6") + ... ] + ... ) + >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2) + >>> # re-densifies the compressed graph into the original graph + >>> for c_node in c_nodes: + ... all_neighbors = set(nx.all_neighbors(c_graph, c_node)) + ... out_neighbors = set(c_graph.neighbors(c_node)) + ... for out_neighbor in out_neighbors: + ... c_graph.remove_edge(c_node, out_neighbor) + ... in_neighbors = all_neighbors - out_neighbors + ... for in_neighbor in in_neighbors: + ... c_graph.remove_edge(in_neighbor, c_node) + ... for out_neighbor in out_neighbors: + ... c_graph.add_edge(in_neighbor, out_neighbor) + ... c_graph.remove_node(c_node) + ... + >>> nx.is_isomorphic(original_graph, c_graph) + True + + References + ---------- + .. [1] Maccioni, A., & Abadi, D. J. (2016, August). + Scalable pattern matching over compressed graphs via dedensification. + In Proceedings of the 22nd ACM SIGKDD International Conference on + Knowledge Discovery and Data Mining (pp. 1755-1764). + http://www.cs.umd.edu/~abadi/papers/graph-dedense.pdf + """ + if threshold < 2: + raise nx.NetworkXError("The degree threshold must be >= 2") + + degrees = G.in_degree if G.is_directed() else G.degree + # Group nodes based on degree threshold + high_degree_nodes = {n for n, d in degrees if d > threshold} + low_degree_nodes = G.nodes() - high_degree_nodes + + auxiliary = {} + for node in G: + high_degree_nbrs = frozenset(high_degree_nodes & set(G[node])) + if high_degree_nbrs: + if high_degree_nbrs in auxiliary: + auxiliary[high_degree_nbrs].add(node) + else: + auxiliary[high_degree_nbrs] = {node} + + if copy: + G = G.copy() + + compressor_nodes = set() + for index, (high_degree_nodes, low_degree_nodes) in enumerate(auxiliary.items()): + low_degree_node_count = len(low_degree_nodes) + high_degree_node_count = len(high_degree_nodes) + old_edges = high_degree_node_count * low_degree_node_count + new_edges = high_degree_node_count + low_degree_node_count + if old_edges <= new_edges: + continue + compression_node = "".join(str(node) for node in high_degree_nodes) + if prefix: + compression_node = str(prefix) + compression_node + for node in low_degree_nodes: + for high_node in high_degree_nodes: + if G.has_edge(node, high_node): + G.remove_edge(node, high_node) + + G.add_edge(node, compression_node) + for node in high_degree_nodes: + G.add_edge(compression_node, node) + compressor_nodes.add(compression_node) + return G, compressor_nodes + + +def _snap_build_graph( + G, + groups, + node_attributes, + edge_attributes, + neighbor_info, + edge_types, + prefix, + supernode_attribute, + superedge_attribute, +): + """ + Build the summary graph from the data structures produced in the SNAP aggregation algorithm + + Used in the SNAP aggregation algorithm to build the output summary graph and supernode + lookup dictionary. This process uses the original graph and the data structures to + create the supernodes with the correct node attributes, and the superedges with the correct + edge attributes + + Parameters + ---------- + G: networkx.Graph + the original graph to be summarized + groups: dict + A dictionary of unique group IDs and their corresponding node groups + node_attributes: iterable + An iterable of the node attributes considered in the summarization process + edge_attributes: iterable + An iterable of the edge attributes considered in the summarization process + neighbor_info: dict + A data structure indicating the number of edges a node has with the + groups in the current summarization of each edge type + edge_types: dict + dictionary of edges in the graph and their corresponding attributes recognized + in the summarization + prefix: string + The prefix to be added to all supernodes + supernode_attribute: str + The node attribute for recording the supernode groupings of nodes + superedge_attribute: str + The edge attribute for recording the edge types represented by superedges + + Returns + ------- + summary graph: Networkx graph + """ + output = G.__class__() + node_label_lookup = {} + for index, group_id in enumerate(groups): + group_set = groups[group_id] + supernode = f"{prefix}{index}" + node_label_lookup[group_id] = supernode + supernode_attributes = { + attr: G.nodes[next(iter(group_set))][attr] for attr in node_attributes + } + supernode_attributes[supernode_attribute] = group_set + output.add_node(supernode, **supernode_attributes) + + for group_id in groups: + group_set = groups[group_id] + source_supernode = node_label_lookup[group_id] + for other_group, group_edge_types in neighbor_info[ + next(iter(group_set)) + ].items(): + if group_edge_types: + target_supernode = node_label_lookup[other_group] + summary_graph_edge = (source_supernode, target_supernode) + + edge_types = [ + dict(zip(edge_attributes, edge_type)) + for edge_type in group_edge_types + ] + + has_edge = output.has_edge(*summary_graph_edge) + if output.is_multigraph(): + if not has_edge: + for edge_type in edge_types: + output.add_edge(*summary_graph_edge, **edge_type) + elif not output.is_directed(): + existing_edge_data = output.get_edge_data(*summary_graph_edge) + for edge_type in edge_types: + if edge_type not in existing_edge_data.values(): + output.add_edge(*summary_graph_edge, **edge_type) + else: + superedge_attributes = {superedge_attribute: edge_types} + output.add_edge(*summary_graph_edge, **superedge_attributes) + + return output + + +def _snap_eligible_group(G, groups, group_lookup, edge_types): + """ + Determines if a group is eligible to be split. + + A group is eligible to be split if all nodes in the group have edges of the same type(s) + with the same other groups. + + Parameters + ---------- + G: graph + graph to be summarized + groups: dict + A dictionary of unique group IDs and their corresponding node groups + group_lookup: dict + dictionary of nodes and their current corresponding group ID + edge_types: dict + dictionary of edges in the graph and their corresponding attributes recognized + in the summarization + + Returns + ------- + tuple: group ID to split, and neighbor-groups participation_counts data structure + """ + nbr_info = {node: {gid: Counter() for gid in groups} for node in group_lookup} + for group_id in groups: + current_group = groups[group_id] + + # build nbr_info for nodes in group + for node in current_group: + nbr_info[node] = {group_id: Counter() for group_id in groups} + edges = G.edges(node, keys=True) if G.is_multigraph() else G.edges(node) + for edge in edges: + neighbor = edge[1] + edge_type = edge_types[edge] + neighbor_group_id = group_lookup[neighbor] + nbr_info[node][neighbor_group_id][edge_type] += 1 + + # check if group_id is eligible to be split + group_size = len(current_group) + for other_group_id in groups: + edge_counts = Counter() + for node in current_group: + edge_counts.update(nbr_info[node][other_group_id].keys()) + + if not all(count == group_size for count in edge_counts.values()): + # only the nbr_info of the returned group_id is required for handling group splits + return group_id, nbr_info + + # if no eligible groups, complete nbr_info is calculated + return None, nbr_info + + +def _snap_split(groups, neighbor_info, group_lookup, group_id): + """ + Splits a group based on edge types and updates the groups accordingly + + Splits the group with the given group_id based on the edge types + of the nodes so that each new grouping will all have the same + edges with other nodes. + + Parameters + ---------- + groups: dict + A dictionary of unique group IDs and their corresponding node groups + neighbor_info: dict + A data structure indicating the number of edges a node has with the + groups in the current summarization of each edge type + edge_types: dict + dictionary of edges in the graph and their corresponding attributes recognized + in the summarization + group_lookup: dict + dictionary of nodes and their current corresponding group ID + group_id: object + ID of group to be split + + Returns + ------- + dict + The updated groups based on the split + """ + new_group_mappings = defaultdict(set) + for node in groups[group_id]: + signature = tuple( + frozenset(edge_types) for edge_types in neighbor_info[node].values() + ) + new_group_mappings[signature].add(node) + + # leave the biggest new_group as the original group + new_groups = sorted(new_group_mappings.values(), key=len) + for new_group in new_groups[:-1]: + # Assign unused integer as the new_group_id + # ids are tuples, so will not interact with the original group_ids + new_group_id = len(groups) + groups[new_group_id] = new_group + groups[group_id] -= new_group + for node in new_group: + group_lookup[node] = new_group_id + + return groups + + +@nx._dispatchable( + node_attrs="[node_attributes]", edge_attrs="[edge_attributes]", returns_graph=True +) +def snap_aggregation( + G, + node_attributes, + edge_attributes=(), + prefix="Supernode-", + supernode_attribute="group", + superedge_attribute="types", +): + """Creates a summary graph based on attributes and connectivity. + + This function uses the Summarization by Grouping Nodes on Attributes + and Pairwise edges (SNAP) algorithm for summarizing a given + graph by grouping nodes by node attributes and their edge attributes + into supernodes in a summary graph. This name SNAP should not be + confused with the Stanford Network Analysis Project (SNAP). + + Here is a high-level view of how this algorithm works: + + 1) Group nodes by node attribute values. + + 2) Iteratively split groups until all nodes in each group have edges + to nodes in the same groups. That is, until all the groups are homogeneous + in their member nodes' edges to other groups. For example, + if all the nodes in group A only have edge to nodes in group B, then the + group is homogeneous and does not need to be split. If all nodes in group B + have edges with nodes in groups {A, C}, but some also have edges with other + nodes in B, then group B is not homogeneous and needs to be split into + groups have edges with {A, C} and a group of nodes having + edges with {A, B, C}. This way, viewers of the summary graph can + assume that all nodes in the group have the exact same node attributes and + the exact same edges. + + 3) Build the output summary graph, where the groups are represented by + super-nodes. Edges represent the edges shared between all the nodes in each + respective groups. + + A SNAP summary graph can be used to visualize graphs that are too large to display + or visually analyze, or to efficiently identify sets of similar nodes with similar connectivity + patterns to other sets of similar nodes based on specified node and/or edge attributes in a graph. + + Parameters + ---------- + G: graph + Networkx Graph to be summarized + node_attributes: iterable, required + An iterable of the node attributes used to group nodes in the summarization process. Nodes + with the same values for these attributes will be grouped together in the summary graph. + edge_attributes: iterable, optional + An iterable of the edge attributes considered in the summarization process. If provided, unique + combinations of the attribute values found in the graph are used to + determine the edge types in the graph. If not provided, all edges + are considered to be of the same type. + prefix: str + The prefix used to denote supernodes in the summary graph. Defaults to 'Supernode-'. + supernode_attribute: str + The node attribute for recording the supernode groupings of nodes. Defaults to 'group'. + superedge_attribute: str + The edge attribute for recording the edge types of multiple edges. Defaults to 'types'. + + Returns + ------- + networkx.Graph: summary graph + + Examples + -------- + SNAP aggregation takes a graph and summarizes it in the context of user-provided + node and edge attributes such that a viewer can more easily extract and + analyze the information represented by the graph + + >>> nodes = { + ... "A": dict(color="Red"), + ... "B": dict(color="Red"), + ... "C": dict(color="Red"), + ... "D": dict(color="Red"), + ... "E": dict(color="Blue"), + ... "F": dict(color="Blue"), + ... } + >>> edges = [ + ... ("A", "E", "Strong"), + ... ("B", "F", "Strong"), + ... ("C", "E", "Weak"), + ... ("D", "F", "Weak"), + ... ] + >>> G = nx.Graph() + >>> for node in nodes: + ... attributes = nodes[node] + ... G.add_node(node, **attributes) + >>> for source, target, type in edges: + ... G.add_edge(source, target, type=type) + >>> node_attributes = ("color",) + >>> edge_attributes = ("type",) + >>> summary_graph = nx.snap_aggregation( + ... G, node_attributes=node_attributes, edge_attributes=edge_attributes + ... ) + + Notes + ----- + The summary graph produced is called a maximum Attribute-edge + compatible (AR-compatible) grouping. According to [1]_, an + AR-compatible grouping means that all nodes in each group have the same + exact node attribute values and the same exact edges and + edge types to one or more nodes in the same groups. The maximal + AR-compatible grouping is the grouping with the minimal cardinality. + + The AR-compatible grouping is the most detailed grouping provided by + any of the SNAP algorithms. + + References + ---------- + .. [1] Y. Tian, R. A. Hankins, and J. M. Patel. Efficient aggregation + for graph summarization. In Proc. 2008 ACM-SIGMOD Int. Conf. + Management of Data (SIGMOD’08), pages 567–580, Vancouver, Canada, + June 2008. + """ + edge_types = { + edge: tuple(attrs.get(attr) for attr in edge_attributes) + for edge, attrs in G.edges.items() + } + if not G.is_directed(): + if G.is_multigraph(): + # list is needed to avoid mutating while iterating + edges = [((v, u, k), etype) for (u, v, k), etype in edge_types.items()] + else: + # list is needed to avoid mutating while iterating + edges = [((v, u), etype) for (u, v), etype in edge_types.items()] + edge_types.update(edges) + + group_lookup = { + node: tuple(attrs[attr] for attr in node_attributes) + for node, attrs in G.nodes.items() + } + groups = defaultdict(set) + for node, node_type in group_lookup.items(): + groups[node_type].add(node) + + eligible_group_id, nbr_info = _snap_eligible_group( + G, groups, group_lookup, edge_types + ) + while eligible_group_id: + groups = _snap_split(groups, nbr_info, group_lookup, eligible_group_id) + eligible_group_id, nbr_info = _snap_eligible_group( + G, groups, group_lookup, edge_types + ) + return _snap_build_graph( + G, + groups, + node_attributes, + edge_attributes, + nbr_info, + edge_types, + prefix, + supernode_attribute, + superedge_attribute, + ) diff --git a/shared/package-files/0b/0b2ee741e438cae6d9f757b2e62b501788cfc9922166513da81d1c1508fdc68b/test_regular.py b/shared/package-files/0b/0b2ee741e438cae6d9f757b2e62b501788cfc9922166513da81d1c1508fdc68b/test_regular.py new file mode 100644 index 0000000000000000000000000000000000000000..021ad32a93cd44fdb8ca7db15911eaa64c775aa2 --- /dev/null +++ b/shared/package-files/0b/0b2ee741e438cae6d9f757b2e62b501788cfc9922166513da81d1c1508fdc68b/test_regular.py @@ -0,0 +1,91 @@ +import pytest + +import networkx as nx +import networkx.algorithms.regular as reg +import networkx.generators as gen + + +class TestKFactor: + def test_k_factor_trivial(self): + g = gen.cycle_graph(4) + f = reg.k_factor(g, 2) + assert g.edges == f.edges + + def test_k_factor1(self): + g = gen.grid_2d_graph(4, 4) + g_kf = reg.k_factor(g, 2) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 2 + + def test_k_factor2(self): + g = gen.complete_graph(6) + g_kf = reg.k_factor(g, 3) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 3 + + def test_k_factor3(self): + g = gen.grid_2d_graph(4, 4) + with pytest.raises(nx.NetworkXUnfeasible): + reg.k_factor(g, 3) + + def test_k_factor4(self): + g = gen.lattice.hexagonal_lattice_graph(4, 4) + # Perfect matching doesn't exist for 4,4 hexagonal lattice graph + with pytest.raises(nx.NetworkXUnfeasible): + reg.k_factor(g, 2) + + def test_k_factor5(self): + g = gen.complete_graph(6) + # small k to exercise SmallKGadget + g_kf = reg.k_factor(g, 2) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 2 + + +class TestIsRegular: + def test_is_regular1(self): + g = gen.cycle_graph(4) + assert reg.is_regular(g) + + def test_is_regular2(self): + g = gen.complete_graph(5) + assert reg.is_regular(g) + + def test_is_regular3(self): + g = gen.lollipop_graph(5, 5) + assert not reg.is_regular(g) + + def test_is_regular4(self): + g = nx.DiGraph() + g.add_edges_from([(0, 1), (1, 2), (2, 0)]) + assert reg.is_regular(g) + + +def test_is_regular_empty_graph_raises(): + G = nx.Graph() + with pytest.raises(nx.NetworkXPointlessConcept, match="Graph has no nodes"): + nx.is_regular(G) + + +class TestIsKRegular: + def test_is_k_regular1(self): + g = gen.cycle_graph(4) + assert reg.is_k_regular(g, 2) + assert not reg.is_k_regular(g, 3) + + def test_is_k_regular2(self): + g = gen.complete_graph(5) + assert reg.is_k_regular(g, 4) + assert not reg.is_k_regular(g, 3) + assert not reg.is_k_regular(g, 6) + + def test_is_k_regular3(self): + g = gen.lollipop_graph(5, 5) + assert not reg.is_k_regular(g, 5) + assert not reg.is_k_regular(g, 6) diff --git a/shared/package-files/0b/0b3396efc8340b9118b791749b864d653f7bf5e9c658acab12b6e13f1e0cbb40/cudnn_convolution_relu_cuda_dispatch.h b/shared/package-files/0b/0b3396efc8340b9118b791749b864d653f7bf5e9c658acab12b6e13f1e0cbb40/cudnn_convolution_relu_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..72be7fddc50886b4eabb68b352ffe2401485f7dd --- /dev/null +++ b/shared/package-files/0b/0b3396efc8340b9118b791749b864d653f7bf5e9c658acab12b6e13f1e0cbb40/cudnn_convolution_relu_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor cudnn_convolution_relu(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups); +TORCH_API at::Tensor cudnn_convolution_relu_symint(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/0b/0b35ba3271241d5558d48a719e096296ec3703baac2b767e21e026be485fbc44/special_modified_bessel_i1_meta.h b/shared/package-files/0b/0b35ba3271241d5558d48a719e096296ec3703baac2b767e21e026be485fbc44/special_modified_bessel_i1_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..27d72fb2608941f1fb059c368d4f8c043ea835cf --- /dev/null +++ b/shared/package-files/0b/0b35ba3271241d5558d48a719e096296ec3703baac2b767e21e026be485fbc44/special_modified_bessel_i1_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_modified_bessel_i1 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b383e598ca6b4133e50369f0657158c17574ab81d6a944a5854e5fb3fd5f519/__init__.cpython-311.pyc b/shared/package-files/0b/0b383e598ca6b4133e50369f0657158c17574ab81d6a944a5854e5fb3fd5f519/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6041e0a183cd0d22703b06833ec173e7a2f5fbb1 Binary files /dev/null and b/shared/package-files/0b/0b383e598ca6b4133e50369f0657158c17574ab81d6a944a5854e5fb3fd5f519/__init__.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b3a66320d868b2ef2114f597efce6e22cbb4652f6e493959dd379dd8a746c4a/test_tz_localize.cpython-311.pyc b/shared/package-files/0b/0b3a66320d868b2ef2114f597efce6e22cbb4652f6e493959dd379dd8a746c4a/test_tz_localize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec6ae13bbd8792c6a71d70038776c21ad38d386f Binary files /dev/null and b/shared/package-files/0b/0b3a66320d868b2ef2114f597efce6e22cbb4652f6e493959dd379dd8a746c4a/test_tz_localize.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b3ffb557073c3ee8299a70c655a43bebd6a81dfbeb94fde89a7322f218e7904/commutator.cpython-311.pyc b/shared/package-files/0b/0b3ffb557073c3ee8299a70c655a43bebd6a81dfbeb94fde89a7322f218e7904/commutator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75c2e4c250fa4e55dd29552eebabac15e1e1d13 Binary files /dev/null and b/shared/package-files/0b/0b3ffb557073c3ee8299a70c655a43bebd6a81dfbeb94fde89a7322f218e7904/commutator.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b409c9b4007f67a945ee11cad90737fc968a1ed29763c89788ba4de1f40576e/frontend.cpython-311.pyc b/shared/package-files/0b/0b409c9b4007f67a945ee11cad90737fc968a1ed29763c89788ba4de1f40576e/frontend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02711aeced432939b9964cdc94888785fe08d7b9 Binary files /dev/null and b/shared/package-files/0b/0b409c9b4007f67a945ee11cad90737fc968a1ed29763c89788ba4de1f40576e/frontend.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b445fe3e984382df744a2ca00b2f778a04e90f0ec8b6eb8a2b94f8f0d7ff31a/tbx.c b/shared/package-files/0b/0b445fe3e984382df744a2ca00b2f778a04e90f0ec8b6eb8a2b94f8f0d7ff31a/tbx.c new file mode 100644 index 0000000000000000000000000000000000000000..6625005496c1513d2fdc1c4129db5e2decfb9065 --- /dev/null +++ b/shared/package-files/0b/0b445fe3e984382df744a2ca00b2f778a04e90f0ec8b6eb8a2b94f8f0d7ff31a/tbx.c @@ -0,0 +1,529 @@ +/* tbx.c -- tabix API functions. + + Copyright (C) 2009, 2010, 2012-2015, 2017-2020, 2022-2023 Genome Research Ltd. + Copyright (C) 2010-2012 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h +#include + +#include +#include +#include +#include +#include +#include "htslib/tbx.h" +#include "htslib/bgzf.h" +#include "htslib/hts_endian.h" +#include "hts_internal.h" + +#include "htslib/khash.h" +KHASH_DECLARE(s2i, kh_cstr_t, int64_t) + +HTSLIB_EXPORT +const tbx_conf_t tbx_conf_gff = { 0, 1, 4, 5, '#', 0 }; + +HTSLIB_EXPORT +const tbx_conf_t tbx_conf_bed = { TBX_UCSC, 1, 2, 3, '#', 0 }; + +HTSLIB_EXPORT +const tbx_conf_t tbx_conf_psltbl = { TBX_UCSC, 15, 17, 18, '#', 0 }; + +HTSLIB_EXPORT +const tbx_conf_t tbx_conf_sam = { TBX_SAM, 3, 4, 0, '@', 0 }; + +HTSLIB_EXPORT +const tbx_conf_t tbx_conf_vcf = { TBX_VCF, 1, 2, 0, '#', 0 }; +const tbx_conf_t tbx_conf_gaf = { TBX_GAF, 1, 6, 0, '#', 0 }; + +typedef struct { + int64_t beg, end; + char *ss, *se; + int tid; +} tbx_intv_t; + +static inline int get_tid(tbx_t *tbx, const char *ss, int is_add) +{ + khint_t k; + khash_t(s2i) *d; + if ((tbx->conf.preset&0xffff) == TBX_GAF) return(0); + if (tbx->dict == 0) tbx->dict = kh_init(s2i); + if (!tbx->dict) return -1; // Out of memory + d = (khash_t(s2i)*)tbx->dict; + if (is_add) { + int absent; + k = kh_put(s2i, d, ss, &absent); + if (absent < 0) { + return -1; // Out of memory + } else if (absent) { + char *ss_dup = strdup(ss); + if (ss_dup) { + kh_key(d, k) = ss_dup; + kh_val(d, k) = kh_size(d) - 1; + } else { + kh_del(s2i, d, k); + return -1; // Out of memory + } + } + } else k = kh_get(s2i, d, ss); + return k == kh_end(d)? -1 : kh_val(d, k); +} + +int tbx_name2id(tbx_t *tbx, const char *ss) +{ + return get_tid(tbx, ss, 0); +} + +int tbx_parse1(const tbx_conf_t *conf, size_t len, char *line, tbx_intv_t *intv) +{ + size_t i, b = 0; + int id = 1; + char *s; + intv->ss = intv->se = 0; intv->beg = intv->end = -1; + for (i = 0; i <= len; ++i) { + if (line[i] == '\t' || line[i] == 0) { + if (id == conf->sc) { + intv->ss = line + b; intv->se = line + i; + } else if (id == conf->bc) { + // here ->beg is 0-based. + if ((conf->preset&0xffff) == TBX_GAF){ + // if gaf find the smallest and largest node id + char *t; + int64_t nodeid = -1; + for (s = line + b + 1; s < line + i;) { + nodeid = strtoll(s, &t, 0); + if(intv->beg == -1){ + intv->beg = intv->end = nodeid; + } else { + if(nodeid < intv->beg){ + intv->beg = nodeid; + } + + if(nodeid > intv->end){ + intv->end = nodeid; + } + } + s = t + 1; + } + } else { + intv->beg = strtoll(line + b, &s, 0); + + if (conf->bc <= conf->ec) // don't overwrite an already set end point + intv->end = intv->beg; + + if ( s==line+b ) return -1; // expected int + + if (!(conf->preset&TBX_UCSC)) + --intv->beg; + else if (conf->bc <= conf->ec) + ++intv->end; + + if (intv->beg < 0) { + hts_log_warning("Coordinate <= 0 detected. " + "Did you forget to use the -0 option?"); + intv->beg = 0; + } + if (intv->end < 1) intv->end = 1; + } + } else { + if ((conf->preset&0xffff) == TBX_GENERIC) { + if (id == conf->ec) + { + intv->end = strtoll(line + b, &s, 0); + if ( s==line+b ) return -1; // expected int + } + } else if ((conf->preset&0xffff) == TBX_SAM) { + if (id == 6) { // CIGAR + int l = 0; + char *t; + for (s = line + b; s < line + i;) { + long x = strtol(s, &t, 10); + char op = toupper_c(*t); + if (op == 'M' || op == 'D' || op == 'N') l += x; + s = t + 1; + } + if (l == 0) l = 1; + intv->end = intv->beg + l; + } + } else if ((conf->preset&0xffff) == TBX_VCF) { + if (id == 4) { + if (b < i) intv->end = intv->beg + (i - b); + } else if (id == 8) { // look for "END=" + int c = line[i]; + line[i] = 0; + s = strstr(line + b, "END="); + if (s == line + b) s += 4; + else if (s) { + s = strstr(line + b, ";END="); + if (s) s += 5; + } + if (s && *s != '.') { + long long end = strtoll(s, &s, 0); + if (end <= intv->beg) { + static int reported = 0; + if (!reported) { + int l = intv->ss ? (int) (intv->se - intv->ss) : 0; + hts_log_warning("VCF INFO/END=%lld is smaller than POS at %.*s:%"PRIhts_pos"\n" + "This tag will be ignored. " + "Note: only one invalid END tag will be reported.", + end, l >= 0 ? l : 0, + intv->ss ? intv->ss : "", + intv->beg); + reported = 1; + } + } else { + intv->end = end; + } + } + line[i] = c; + } + } + } + b = i + 1; + ++id; + } + } + if (intv->ss == 0 || intv->se == 0 || intv->beg < 0 || intv->end < 0) return -1; + return 0; +} + +static inline int get_intv(tbx_t *tbx, kstring_t *str, tbx_intv_t *intv, int is_add) +{ + if (tbx_parse1(&tbx->conf, str->l, str->s, intv) == 0) { + int c = *intv->se; + *intv->se = '\0'; + if ((tbx->conf.preset&0xffff) == TBX_GAF){ + intv->tid = 0; + } else { + intv->tid = get_tid(tbx, intv->ss, is_add); + } + *intv->se = c; + if (intv->tid < 0) return -2; // get_tid out of memory + return (intv->beg >= 0 && intv->end >= 0)? 0 : -1; + } else { + char *type = NULL; + switch (tbx->conf.preset&0xffff) + { + case TBX_SAM: type = "TBX_SAM"; break; + case TBX_VCF: type = "TBX_VCF"; break; + case TBX_GAF: type = "TBX_GAF"; break; + case TBX_UCSC: type = "TBX_UCSC"; break; + default: type = "TBX_GENERIC"; break; + } + if (hts_is_utf16_text(str)) + hts_log_error("Failed to parse %s: offending line appears to be encoded as UTF-16", type); + else + hts_log_error("Failed to parse %s: was wrong -p [type] used?\nThe offending line was: \"%s\"", + type, str->s); + return -1; + } +} + +/* + * Called by tabix iterator to read the next record. + * Returns >= 0 on success + * -1 on EOF + * <= -2 on error + */ +int tbx_readrec(BGZF *fp, void *tbxv, void *sv, int *tid, hts_pos_t *beg, hts_pos_t *end) +{ + tbx_t *tbx = (tbx_t *) tbxv; + kstring_t *s = (kstring_t *) sv; + int ret; + if ((ret = bgzf_getline(fp, '\n', s)) >= 0) { + tbx_intv_t intv; + if (get_intv(tbx, s, &intv, 0) < 0) + return -2; + *tid = intv.tid; *beg = intv.beg; *end = intv.end; + } + return ret; +} + +static int tbx_set_meta(tbx_t *tbx) +{ + int i, l = 0, l_nm; + uint32_t x[7]; + char **name; + uint8_t *meta; + khint_t k; + khash_t(s2i) *d = (khash_t(s2i)*)tbx->dict; + + memcpy(x, &tbx->conf, 24); + name = (char**)malloc(sizeof(char*) * kh_size(d)); + if (!name) return -1; + for (k = kh_begin(d), l = 0; k != kh_end(d); ++k) { + if (!kh_exist(d, k)) continue; + name[kh_val(d, k)] = (char*)kh_key(d, k); + l += strlen(kh_key(d, k)) + 1; // +1 to include '\0' + } + l_nm = x[6] = l; + meta = (uint8_t*)malloc(l_nm + 28); + if (!meta) { free(name); return -1; } + if (ed_is_big()) + for (i = 0; i < 7; ++i) + x[i] = ed_swap_4(x[i]); + memcpy(meta, x, 28); + for (l = 28, i = 0; i < (int)kh_size(d); ++i) { + int x = strlen(name[i]) + 1; + memcpy(meta + l, name[i], x); + l += x; + } + free(name); + hts_idx_set_meta(tbx->idx, l, meta, 0); + return 0; +} + +// Minimal effort parser to extract reference length out of VCF header line +// This is used only used to adjust the number of levels if necessary, +// so not a major problem if it doesn't always work. +static void adjust_max_ref_len_vcf(const char *str, int64_t *max_ref_len) +{ + const char *ptr; + int64_t len; + if (strncmp(str, "##contig", 8) != 0) return; + ptr = strstr(str + 8, "length"); + if (!ptr) return; + for (ptr += 6; *ptr == ' ' || *ptr == '='; ptr++) {} + len = strtoll(ptr, NULL, 10); + if (*max_ref_len < len) *max_ref_len = len; +} + +// Same for sam files +static void adjust_max_ref_len_sam(const char *str, int64_t *max_ref_len) +{ + const char *ptr; + int64_t len; + if (strncmp(str, "@SQ", 3) != 0) return; + ptr = strstr(str + 3, "\tLN:"); + if (!ptr) return; + ptr += 4; + len = strtoll(ptr, NULL, 10); + if (*max_ref_len < len) *max_ref_len = len; +} + +// Adjusts number of levels if not big enough. This can happen for +// files with very large contigs. +static int adjust_n_lvls(int min_shift, int n_lvls, int64_t max_len) +{ + int64_t s = hts_bin_maxpos(min_shift, n_lvls); + max_len += 256; + for (; max_len > s; ++n_lvls, s <<= 3) {} + return n_lvls; +} + +tbx_t *tbx_index(BGZF *fp, int min_shift, const tbx_conf_t *conf) +{ + tbx_t *tbx; + kstring_t str; + int ret, first = 0, n_lvls, fmt; + int64_t lineno = 0; + uint64_t last_off = 0; + tbx_intv_t intv; + int64_t max_ref_len = 0; + + str.s = 0; str.l = str.m = 0; + tbx = (tbx_t*)calloc(1, sizeof(tbx_t)); + if (!tbx) return NULL; + tbx->conf = *conf; + if (min_shift > 0) n_lvls = (TBX_MAX_SHIFT - min_shift + 2) / 3, fmt = HTS_FMT_CSI; + else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_TBI; + while ((ret = bgzf_getline(fp, '\n', &str)) >= 0) { + ++lineno; + if (str.s[0] == tbx->conf.meta_char && fmt == HTS_FMT_CSI) { + switch (tbx->conf.preset) { + case TBX_SAM: + adjust_max_ref_len_sam(str.s, &max_ref_len); break; + case TBX_VCF: + adjust_max_ref_len_vcf(str.s, &max_ref_len); break; + default: + break; + } + } + if (lineno <= tbx->conf.line_skip || str.s[0] == tbx->conf.meta_char) { + last_off = bgzf_tell(fp); + continue; + } + if (first == 0) { + if (fmt == HTS_FMT_CSI) { + if (!max_ref_len) + max_ref_len = (int64_t)100*1024*1024*1024; // 100G default + n_lvls = adjust_n_lvls(min_shift, n_lvls, max_ref_len); + } + tbx->idx = hts_idx_init(0, fmt, last_off, min_shift, n_lvls); + if (!tbx->idx) goto fail; + first = 1; + } + ret = get_intv(tbx, &str, &intv, 1); + if (ret < -1) goto fail; // Out of memory + if (ret < 0) continue; // Skip unparsable lines + if (hts_idx_push(tbx->idx, intv.tid, intv.beg, intv.end, + bgzf_tell(fp), 1) < 0) { + goto fail; + } + } + if (ret < -1) goto fail; + if ( !tbx->idx ) tbx->idx = hts_idx_init(0, fmt, last_off, min_shift, n_lvls); // empty file + if (!tbx->idx) goto fail; + if ( !tbx->dict ) tbx->dict = kh_init(s2i); + if (!tbx->dict) goto fail; + if (hts_idx_finish(tbx->idx, bgzf_tell(fp)) != 0) goto fail; + if (tbx_set_meta(tbx) != 0) goto fail; + free(str.s); + return tbx; + + fail: + free(str.s); + tbx_destroy(tbx); + return NULL; +} + +void tbx_destroy(tbx_t *tbx) +{ + khash_t(s2i) *d = (khash_t(s2i)*)tbx->dict; + if (d != NULL) + { + khint_t k; + for (k = kh_begin(d); k != kh_end(d); ++k) + if (kh_exist(d, k)) free((char*)kh_key(d, k)); + } + hts_idx_destroy(tbx->idx); + kh_destroy(s2i, d); + free(tbx); +} + +int tbx_index_build3(const char *fn, const char *fnidx, int min_shift, int n_threads, const tbx_conf_t *conf) +{ + tbx_t *tbx; + BGZF *fp; + int ret; + if ((fp = bgzf_open(fn, "r")) == 0) return -1; + if ( n_threads ) bgzf_mt(fp, n_threads, 256); + if ( bgzf_compression(fp) != bgzf ) { bgzf_close(fp); return -2; } + tbx = tbx_index(fp, min_shift, conf); + bgzf_close(fp); + if ( !tbx ) return -1; + ret = hts_idx_save_as(tbx->idx, fn, fnidx, min_shift > 0? HTS_FMT_CSI : HTS_FMT_TBI); + tbx_destroy(tbx); + return ret; +} + +int tbx_index_build2(const char *fn, const char *fnidx, int min_shift, const tbx_conf_t *conf) +{ + return tbx_index_build3(fn, fnidx, min_shift, 0, conf); +} + +int tbx_index_build(const char *fn, int min_shift, const tbx_conf_t *conf) +{ + return tbx_index_build3(fn, NULL, min_shift, 0, conf); +} + +static tbx_t *index_load(const char *fn, const char *fnidx, int flags) +{ + tbx_t *tbx; + uint8_t *meta; + char *nm, *p; + uint32_t l_meta, l_nm; + tbx = (tbx_t*)calloc(1, sizeof(tbx_t)); + if (!tbx) + return NULL; + tbx->idx = hts_idx_load3(fn, fnidx, HTS_FMT_TBI, flags); + if ( !tbx->idx ) + { + free(tbx); + return NULL; + } + meta = hts_idx_get_meta(tbx->idx, &l_meta); + if ( !meta || l_meta < 28) goto invalid; + + tbx->conf.preset = le_to_i32(&meta[0]); + tbx->conf.sc = le_to_i32(&meta[4]); + tbx->conf.bc = le_to_i32(&meta[8]); + tbx->conf.ec = le_to_i32(&meta[12]); + tbx->conf.meta_char = le_to_i32(&meta[16]); + tbx->conf.line_skip = le_to_i32(&meta[20]); + l_nm = le_to_u32(&meta[24]); + if (l_nm > l_meta - 28) goto invalid; + + p = nm = (char*)meta + 28; + // This assumes meta is NUL-terminated, so we can merrily strlen away. + // hts_idx_load_local() assures this for us by adding a NUL on the end + // of whatever it reads. + for (; p - nm < l_nm; p += strlen(p) + 1) { + if (get_tid(tbx, p, 1) < 0) { + hts_log_error("%s", strerror(errno)); + goto fail; + } + } + return tbx; + + invalid: + hts_log_error("Invalid index header for %s", fnidx ? fnidx : fn); + + fail: + tbx_destroy(tbx); + return NULL; +} + +tbx_t *tbx_index_load3(const char *fn, const char *fnidx, int flags) +{ + return index_load(fn, fnidx, flags); +} + +tbx_t *tbx_index_load2(const char *fn, const char *fnidx) +{ + return index_load(fn, fnidx, 1); +} + +tbx_t *tbx_index_load(const char *fn) +{ + return index_load(fn, NULL, 1); +} + +const char **tbx_seqnames(tbx_t *tbx, int *n) +{ + khash_t(s2i) *d = (khash_t(s2i)*)tbx->dict; + if (d == NULL) + { + *n = 0; + return calloc(1, sizeof(char *)); + } + int tid, m = kh_size(d); + const char **names = (const char**) calloc(m,sizeof(const char*)); + khint_t k; + if (!names) { + *n = 0; + return NULL; + } + for (k=kh_begin(d); k +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +${meta_function_declarations} + +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b48f404d28939d9c7783369d76894ad9e786503a83449cc81aebd59088558d2/test_simple_paths.cpython-311.pyc b/shared/package-files/0b/0b48f404d28939d9c7783369d76894ad9e786503a83449cc81aebd59088558d2/test_simple_paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1590367fd51e57ce361c8b308622b82f8ce9f9a Binary files /dev/null and b/shared/package-files/0b/0b48f404d28939d9c7783369d76894ad9e786503a83449cc81aebd59088558d2/test_simple_paths.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b51151dd19d9cd45bcee21c0cafb05373c095b0b74832047bfaeb63f815aff6/isneginf_ops.h b/shared/package-files/0b/0b51151dd19d9cd45bcee21c0cafb05373c095b0b74832047bfaeb63f815aff6/isneginf_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..bfc0274c586d729868007c5c9526c7a15fc71573 --- /dev/null +++ b/shared/package-files/0b/0b51151dd19d9cd45bcee21c0cafb05373c095b0b74832047bfaeb63f815aff6/isneginf_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API isneginf { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::isneginf"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "isneginf(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API isneginf_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::isneginf"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "isneginf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0b5279e704d9a9a46af5cbc27b94fad04572b19689d72925073e1cb5db6141cb/nll_loss_forward_native.h b/shared/package-files/0b/0b5279e704d9a9a46af5cbc27b94fad04572b19689d72925073e1cb5db6141cb/nll_loss_forward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ccb1a656042c840fe0c216b1ab49dcd44ab650 --- /dev/null +++ b/shared/package-files/0b/0b5279e704d9a9a46af5cbc27b94fad04572b19689d72925073e1cb5db6141cb/nll_loss_forward_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_nll_loss_forward_out_cpu : public at::meta::structured_nll_loss_forward { +void impl(const at::Tensor & self, const at::Tensor & target, at::OptionalTensorRef weight, int64_t reduction, int64_t ignore_index, const at::Tensor & output, const at::Tensor & total_weight); +}; +struct TORCH_API structured_nll_loss_forward_out_cuda : public at::meta::structured_nll_loss_forward { +void impl(const at::Tensor & self, const at::Tensor & target, at::OptionalTensorRef weight, int64_t reduction, int64_t ignore_index, const at::Tensor & output, const at::Tensor & total_weight); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b5f03de8d3907dd6822b7a2aa21198dcf4fb5443172bc5fbc34ba8b34e4ea73/expressionrawdomain.cpython-311.pyc b/shared/package-files/0b/0b5f03de8d3907dd6822b7a2aa21198dcf4fb5443172bc5fbc34ba8b34e4ea73/expressionrawdomain.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccbecce24ed4c141f3425a082fcce3d31c61fd24 Binary files /dev/null and b/shared/package-files/0b/0b5f03de8d3907dd6822b7a2aa21198dcf4fb5443172bc5fbc34ba8b34e4ea73/expressionrawdomain.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b5f27343ba6be32dd7e66182ef80dba0e3527e03303d10a156b89b4dbbcee11/cpp_bmm_template.py b/shared/package-files/0b/0b5f27343ba6be32dd7e66182ef80dba0e3527e03303d10a156b89b4dbbcee11/cpp_bmm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb0ee97d6c6229a88353589a1a8e06817f3a2a0 --- /dev/null +++ b/shared/package-files/0b/0b5f27343ba6be32dd7e66182ef80dba0e3527e03303d10a156b89b4dbbcee11/cpp_bmm_template.py @@ -0,0 +1,262 @@ +# mypy: allow-untyped-defs +import contextlib +import itertools +from typing import Any, Callable, Optional +from unittest.mock import patch + +import sympy + +from .. import ir +from ..select_algorithm import PartialRender +from ..virtualized import V +from .common import ArgName +from .cpp_gemm_template import CppGemmTemplate, GEMM_TEMPLATE +from .cpp_micro_gemm import LayoutType +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import DTYPE_TO_CPP, GemmBlocking + + +# We pass all sizevars present in BY to the GEMM templates so variables are not renamed in the BMM definition +GEMM_SINGLE_THREAD_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_single_thread_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +GEMM_THREADED_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_threaded_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +BMM_TEMPLATE = r""" +{{ template.codegen_microkernel_def() }} +{{ template.codegen_single_thread_gemm() }} +{{ template.codegen_multi_thread_gemm() }} + +extern "C" +{{kernel.def_kernel(inputs={"X": BX, "W": BW}, outputs={"Y": BY}, aliases=aliases)}} +{ + const int64_t B = {{kernel.size(BY_2d, 0)}}; + {%- if num_threads > 1 %} + constexpr int64_t num_threads = {{num_threads}}; + int64_t B_single_thread_block = (B / num_threads) * num_threads; + + #pragma omp parallel for num_threads({{num_threads}}) + {%- else %} + int64_t B_single_thread_block = B; + {%- endif %} + for (int64_t b_start = 0; b_start < B_single_thread_block; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_single_thread_mm", + "", + b_index="b_start", + )}} + } + for (int64_t b_start = B_single_thread_block; b_start < B; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_threaded_mm", + "", + b_index="b_start", + )}} + } +} +""" + + +class CppBmmTemplate(CppGemmTemplate): + def __init__( + self, + input_nodes, + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta=1, + alpha=1, + has_bias=False, + epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None, + should_block_weights: bool = False, + name="bmm", + ): + """ + In order to simplify the implementation and increase code reuse, the BMM template implements + two versions of the GEMM kernel: a single-threaded version and a multi-threaded version. + GEMM kernels are called in a loop over the batch dimension, with single-threaded GEMM calls + for all but the last (B % num_threads), which are handled by the multi-threaded GEMM kernel. + + We use an extra sizevar `b_index` to index the batch dimension, which we pass into the GEMM + template as a sympy.Symbol. This allows us to slice the 3D batch tensors in the GEMM template + without any changes to the GEMM template itself. + """ + super().__init__( + input_nodes, + layout, + num_threads, + register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + should_block_weights=should_block_weights, + name=name, + ) + self.b_index = sympy.Symbol("s_b_index", integer=True, nonnegative=True) + + @staticmethod + def get_padded_size(n, block_n, k, should_block_weight): + if should_block_weight: + # Tensor is constant or not contiguous, so we will pad and block + new_size, padded_n = CppGemmTemplate.get_padded_size( + n, block_n, k, should_block_weight + ) + # Add the new batch dimension + new_size.insert(0, -1) + return new_size, padded_n + else: + new_size = [-1, k, n] + return new_size, n + + @staticmethod + def check_if_block_weight(W, micro_gemm): + assert isinstance(W, ir.IRNode) + _, n = W.get_size()[-2:] + result = ( + not W.get_layout().is_contiguous() + or W.get_name() in V.graph.constants + or ( + n % micro_gemm.register_blocking.block_n != 0 + and micro_gemm.get_b_layout != LayoutType.NORMAL + ) + ) + return result + + def get_gemm_function_call( + self, + kernel: CppTemplateKernel, + function_name: str, + placeholder: str, + b_index: str, + ) -> str: + """ + Similar to 'def_kernel' in cpp_template_kernel, but instead of generating a function definition, + generate a function call for the GEMM kernel. + Args: + placeholder: The string to replace the function call with + b_index: The index for slicing the 3D batch tensors + """ + + def hook(): + arg_defs, call_args, _, _ = kernel.args.python_argdefs() + for i, buf in enumerate(call_args): + if buf == self.b_index: + arg_defs[i] = ArgName(b_index) + call = f"{function_name}({', '.join(x.full_name() for x in arg_defs)});" + return call + + assert placeholder not in kernel.render_hooks + kernel.render_hooks[placeholder] = hook + return placeholder + + def get_default_reindexers(self, epilogue_nodes): + def reindexer(args): + # if epilogue nodes exist, they have 3D ranges but args are 2D, so add 0 index + return [self.b_index] + args + + return [reindexer] * len(epilogue_nodes) + + def get_options( + self, + kernel: CppTemplateKernel, + template_buffer_node: Optional[ir.CppTemplateBuffer] = None, + flag_template_buffer_has_other_users: Optional[bool] = None, + epilogue_nodes: Optional[list[ir.IRNode]] = None, + **kwargs, + ) -> dict[str, Any]: + options = super().get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + + BX, BW, BY = options["X"], options["W"], options["Y"] + options["BX"], options["BW"], options["BY"] = BX, BW, BY + options["BY_2d"] = options["Y_2d"] + for kword in ["X", "W", "GemmOut", "Y_2d"]: + options[kword] = kernel.select(options[kword], 0, self.b_index) + for kword in ["X", "W", "Y_2d"]: + options[kword + "_dtype"] = DTYPE_TO_CPP[options[kword].dtype] + options["b_index"] = self.b_index + options["BY_sizevars"] = [ + s + for sym in itertools.chain(BY.get_size(), BY.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ] + options["kernel_name"] = kernel.kernel_name + + return options + + def render( # type: ignore[override, return] + self, + kernel: CppTemplateKernel, + template_buffer_node: Optional[ir.CppTemplateBuffer] = None, + flag_template_buffer_has_other_users: Optional[bool] = None, + epilogue_nodes: Optional[list[ir.IRNode]] = None, + **kwargs, + ) -> str: + options = self.get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + self.render_options = options + + with contextlib.ExitStack() as stack: + for buf in options["fake_buffers"]: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + result = self._template_from_string(BMM_TEMPLATE).render(**options) + + # Finalize the function definitions for the gemm routines + sub_mm_hooks = { + name: hook + for name, hook in kernel.render_hooks.items() + if "FOR_BMM" in name + } + result = PartialRender(result, sub_mm_hooks).finalize_all() + for name in sub_mm_hooks: + del kernel.render_hooks[name] + del kernel.args.sizevars[options["b_index"]] + return result + + def codegen_single_thread_gemm(self): + stub = self._template_from_string(GEMM_SINGLE_THREAD_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + {**self.render_options, "num_threads": 1} + ) + + def codegen_multi_thread_gemm(self): + stub = self._template_from_string(GEMM_THREADED_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + self.render_options + ) + + def codegen_gemm_stub_def(self): + return "" diff --git a/shared/package-files/0b/0b61e8395b436c84f6af2c784f312f414e3a62a73c2eead3041b63bf99b6f814/lie_group.py b/shared/package-files/0b/0b61e8395b436c84f6af2c784f312f414e3a62a73c2eead3041b63bf99b6f814/lie_group.py new file mode 100644 index 0000000000000000000000000000000000000000..260fe33f3771b76e28266062e6a993a2786aaf3b --- /dev/null +++ b/shared/package-files/0b/0b61e8395b436c84f6af2c784f312f414e3a62a73c2eead3041b63bf99b6f814/lie_group.py @@ -0,0 +1,1096 @@ +r""" +This module contains the implementation of the internal helper functions for the lie_group hint for +dsolve. These helper functions apply different heuristics on the given equation +and return the solution. These functions are used by :py:meth:`sympy.solvers.ode.single.LieGroup` + +References +========= + +- `abaco1_simple`, `function_sum` and `chi` are referenced from E.S Cheb-Terrab, L.G.S Duarte +and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using +Symmetry Methods, pp. 7 - pp. 8 + +- `abaco1_product`, `abaco2_similar`, `abaco2_unique_unknown`, `linear` and `abaco2_unique_general` +are referenced from E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order +ODE Patterns, pp. 7 - pp. 12 + +- `bivariate` from Lie Groups and Differential Equations pp. 327 - pp. 329 + +""" +from itertools import islice + +from sympy.core import Add, S, Mul, Pow +from sympy.core.exprtools import factor_terms +from sympy.core.function import Function, AppliedUndef, expand +from sympy.core.relational import Equality, Eq +from sympy.core.symbol import Symbol, Wild, Dummy, symbols +from sympy.functions import exp, log +from sympy.integrals.integrals import integrate +from sympy.polys import Poly +from sympy.polys.polytools import cancel, div +from sympy.simplify import (collect, powsimp, # type: ignore + separatevars, simplify) +from sympy.solvers import solve +from sympy.solvers.pde import pdsolve + +from sympy.utilities import numbered_symbols +from sympy.solvers.deutils import _preprocess, ode_order +from .ode import checkinfsol + + +lie_heuristics = ( + "abaco1_simple", + "abaco1_product", + "abaco2_similar", + "abaco2_unique_unknown", + "abaco2_unique_general", + "linear", + "function_sum", + "bivariate", + "chi" + ) + + +def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf): + + xi = Function("xi") + eta = Function("eta") + f = func.func + x = func.args[0] + y = match['y'] + h = match['h'] + tempsol = [] + if not inf: + try: + inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match) + except ValueError: + return None + for infsim in inf: + xiinf = (infsim[xi(x, func)]).subs(func, y) + etainf = (infsim[eta(x, func)]).subs(func, y) + # This condition creates recursion while using pdsolve. + # Since the first step while solving a PDE of form + # a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0 + # is to solve the ODE dy/dx = b/a + if simplify(etainf/xiinf) == h: + continue + rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf + r = pdsolve(rpde, func=f(x, y)).rhs + s = pdsolve(rpde - 1, func=f(x, y)).rhs + newcoord = [_lie_group_remove(coord) for coord in [r, s]] + r = Dummy("r") + s = Dummy("s") + C1 = Symbol("C1") + rcoord = newcoord[0] + scoord = newcoord[-1] + try: + sol = solve([r - rcoord, s - scoord], x, y, dict=True) + if sol == []: + continue + except NotImplementedError: + continue + else: + sol = sol[0] + xsub = sol[x] + ysub = sol[y] + num = simplify(scoord.diff(x) + scoord.diff(y)*h) + denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h) + if num and denom: + diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)])) + sep = separatevars(diffeq, symbols=[r, s], dict=True) + if sep: + # Trying to separate, r and s coordinates + deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r) + # Substituting and reverting back to original coordinates + deq = deq.subs([(r, rcoord), (s, scoord)]) + try: + sdeq = solve(deq, y) + except NotImplementedError: + tempsol.append(deq) + else: + return [Eq(f(x), sol) for sol in sdeq] + + + elif denom: # (ds/dr) is zero which means s is constant + return [Eq(f(x), solve(scoord - C1, y)[0])] + + elif num: # (dr/ds) is zero which means r is constant + return [Eq(f(x), solve(rcoord - C1, y)[0])] + + # If nothing works, return solution as it is, without solving for y + if tempsol: + return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol] + return None + + +def _ode_lie_group( s, func, order, match): + + heuristics = lie_heuristics + inf = {} + f = func.func + x = func.args[0] + df = func.diff(x) + xi = Function("xi") + eta = Function("eta") + xis = match['xi'] + etas = match['eta'] + y = match.pop('y', None) + if y: + h = -simplify(match[match['d']]/match[match['e']]) + else: + y = Dummy("y") + h = s.subs(func, y) + + if xis is not None and etas is not None: + inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}] + + if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]: + heuristics = ["user_defined"] + list(heuristics) + + match = {'h': h, 'y': y} + + # This is done so that if any heuristic raises a ValueError + # another heuristic can be used. + sol = None + for heuristic in heuristics: + sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf) + if sol: + return sol + return sol + + +def infinitesimals(eq, func=None, order=None, hint='default', match=None): + r""" + The infinitesimal functions of an ordinary differential equation, `\xi(x,y)` + and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations + for which the differential equation is invariant. So, the ODE `y'=f(x,y)` + would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`, + `y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`. + A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group + becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`. + They are tangents to the coordinate curves of the new system. + + Consider the transformation `(x, y) \to (X, Y)` such that the + differential equation remains invariant. `\xi` and `\eta` are the tangents to + the transformed coordinates `X` and `Y`, at `\varepsilon=0`. + + .. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon + }\right)|_{\varepsilon=0} = \xi, + \left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon + }\right)|_{\varepsilon=0} = \eta, + + The infinitesimals can be found by solving the following PDE: + + >>> from sympy import Function, Eq, pprint + >>> from sympy.abc import x, y + >>> xi, eta, h = map(Function, ['xi', 'eta', 'h']) + >>> h = h(x, y) # dy/dx = h + >>> eta = eta(x, y) + >>> xi = xi(x, y) + >>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h + ... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0) + >>> pprint(genform) + /d d \ d 2 d d d + |--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(xi(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0 + \dy dx / dy dy dx dx + + Solving the above mentioned PDE is not trivial, and can be solved only by + making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an + infinitesimal is found, the attempt to find more heuristics stops. This is done to + optimise the speed of solving the differential equation. If a list of all the + infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives + the complete list of infinitesimals. If the infinitesimals for a particular + heuristic needs to be found, it can be passed as a flag to ``hint``. + + Examples + ======== + + >>> from sympy import Function + >>> from sympy.solvers.ode.lie_group import infinitesimals + >>> from sympy.abc import x + >>> f = Function('f') + >>> eq = f(x).diff(x) - x**2*f(x) + >>> infinitesimals(eq) + [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}] + + References + ========== + + - Solving differential equations by Symmetry Groups, + John Starrett, pp. 1 - pp. 14 + + """ + + if isinstance(eq, Equality): + eq = eq.lhs - eq.rhs + if not func: + eq, func = _preprocess(eq) + variables = func.args + if len(variables) != 1: + raise ValueError("ODE's have only one independent variable") + else: + x = variables[0] + if not order: + order = ode_order(eq, func) + if order != 1: + raise NotImplementedError("Infinitesimals for only " + "first order ODE's have been implemented") + else: + df = func.diff(x) + # Matching differential equation of the form a*df + b + a = Wild('a', exclude = [df]) + b = Wild('b', exclude = [df]) + if match: # Used by lie_group hint + h = match['h'] + y = match['y'] + else: + match = collect(expand(eq), df).match(a*df + b) + if match: + h = -simplify(match[b]/match[a]) + else: + try: + sol = solve(eq, df) + except NotImplementedError: + raise NotImplementedError("Infinitesimals for the " + "first order ODE could not be found") + else: + h = sol[0] # Find infinitesimals for one solution + y = Dummy("y") + h = h.subs(func, y) + + u = Dummy("u") + hx = h.diff(x) + hy = h.diff(y) + hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE + match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv} + if hint == 'all': + xieta = [] + for heuristic in lie_heuristics: + function = globals()['lie_heuristic_' + heuristic] + inflist = function(match, comp=True) + if inflist: + xieta.extend([inf for inf in inflist if inf not in xieta]) + if xieta: + return xieta + else: + raise NotImplementedError("Infinitesimals could not be found for " + "the given ODE") + + elif hint == 'default': + for heuristic in lie_heuristics: + function = globals()['lie_heuristic_' + heuristic] + xieta = function(match, comp=False) + if xieta: + return xieta + + raise NotImplementedError("Infinitesimals could not be found for" + " the given ODE") + + elif hint not in lie_heuristics: + raise ValueError("Heuristic not recognized: " + hint) + + else: + function = globals()['lie_heuristic_' + hint] + xieta = function(match, comp=True) + if xieta: + return xieta + else: + raise ValueError("Infinitesimals could not be found using the" + " given heuristic") + + +def lie_heuristic_abaco1_simple(match, comp=False): + r""" + The first heuristic uses the following four sets of + assumptions on `\xi` and `\eta` + + .. math:: \xi = 0, \eta = f(x) + + .. math:: \xi = 0, \eta = f(y) + + .. math:: \xi = f(x), \eta = 0 + + .. math:: \xi = f(y), \eta = 0 + + The success of this heuristic is determined by algebraic factorisation. + For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE + + .. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y} + - \frac{\partial \xi}{\partial x})*h + - \frac{\partial \xi}{\partial y}*h^{2} + - \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0 + + reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0` + If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually + be integrated easily. A similar idea is applied to the other 3 assumptions as well. + + + References + ========== + + - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra + Solving of First Order ODEs Using Symmetry Methods, pp. 8 + + + """ + + xieta = [] + y = match['y'] + h = match['h'] + func = match['func'] + x = func.args[0] + hx = match['hx'] + hy = match['hy'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + hysym = hy.free_symbols + if y not in hysym: + try: + fx = exp(integrate(hy, x)) + except NotImplementedError: + pass + else: + inf = {xi: S.Zero, eta: fx} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + factor = hy/h + facsym = factor.free_symbols + if x not in facsym: + try: + fy = exp(integrate(factor, y)) + except NotImplementedError: + pass + else: + inf = {xi: S.Zero, eta: fy.subs(y, func)} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + factor = -hx/h + facsym = factor.free_symbols + if y not in facsym: + try: + fx = exp(integrate(factor, x)) + except NotImplementedError: + pass + else: + inf = {xi: fx, eta: S.Zero} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + factor = -hx/(h**2) + facsym = factor.free_symbols + if x not in facsym: + try: + fy = exp(integrate(factor, y)) + except NotImplementedError: + pass + else: + inf = {xi: fy.subs(y, func), eta: S.Zero} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + if xieta: + return xieta + +def lie_heuristic_abaco1_product(match, comp=False): + r""" + The second heuristic uses the following two assumptions on `\xi` and `\eta` + + .. math:: \eta = 0, \xi = f(x)*g(y) + + .. math:: \eta = f(x)*g(y), \xi = 0 + + The first assumption of this heuristic holds good if + `\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is + separable in `x` and `y`, then the separated factors containing `x` + is `f(x)`, and `g(y)` is obtained by + + .. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy} + + provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function + of `y` only. + + The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as + `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption + satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again + interchanged, to get `\eta` as `f(x)*g(y)` + + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 7 - pp. 8 + + """ + + xieta = [] + y = match['y'] + h = match['h'] + hinv = match['hinv'] + func = match['func'] + x = func.args[0] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + + inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y]) + if inf and inf['coeff']: + fx = inf[x] + gy = simplify(fx*((1/(fx*h)).diff(x))) + gysyms = gy.free_symbols + if x not in gysyms: + gy = exp(integrate(gy, y)) + inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + u1 = Dummy("u1") + inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y]) + if inf and inf['coeff']: + fx = inf[x] + gy = simplify(fx*((1/(fx*hinv)).diff(x))) + gysyms = gy.free_symbols + if x not in gysyms: + gy = exp(integrate(gy, y)) + etaval = fx*gy + etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y) + inf = {eta: etaval.subs(y, func), xi: S.Zero} + if not comp: + return [inf] + if comp and inf not in xieta: + xieta.append(inf) + + if xieta: + return xieta + +def lie_heuristic_bivariate(match, comp=False): + r""" + The third heuristic assumes the infinitesimals `\xi` and `\eta` + to be bi-variate polynomials in `x` and `y`. The assumption made here + for the logic below is that `h` is a rational function in `x` and `y` + though that may not be necessary for the infinitesimals to be + bivariate polynomials. The coefficients of the infinitesimals + are found out by substituting them in the PDE and grouping similar terms + that are polynomials and since they form a linear system, solve and check + for non trivial solutions. The degree of the assumed bivariates + are increased till a certain maximum value. + + References + ========== + - Lie Groups and Differential Equations + pp. 327 - pp. 329 + + """ + + h = match['h'] + hx = match['hx'] + hy = match['hy'] + func = match['func'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + if h.is_rational_function(): + # The maximum degree that the infinitesimals can take is + # calculated by this technique. + etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid") + ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy + num, denom = cancel(ipde).as_numer_denom() + deg = Poly(num, x, y).total_degree() + deta = Function('deta')(x, y) + dxi = Function('dxi')(x, y) + ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2 + - dxi*hx - deta*hy) + xieq = Symbol("xi0") + etaeq = Symbol("eta0") + + for i in range(deg + 1): + if i: + xieq += Add(*[ + Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) + for power in range(i + 1)]) + etaeq += Add(*[ + Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) + for power in range(i + 1)]) + pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom() + pden = expand(pden) + + # If the individual terms are monomials, the coefficients + # are grouped + if pden.is_polynomial(x, y) and pden.is_Add: + polyy = Poly(pden, x, y).as_dict() + if polyy: + symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y} + soldict = solve(polyy.values(), *symset) + if isinstance(soldict, list): + soldict = soldict[0] + if any(soldict.values()): + xired = xieq.subs(soldict) + etared = etaeq.subs(soldict) + # Scaling is done by substituting one for the parameters + # This can be any number except zero. + dict_ = dict.fromkeys(symset, 1) + inf = {eta: etared.subs(dict_).subs(y, func), + xi: xired.subs(dict_).subs(y, func)} + return [inf] + +def lie_heuristic_chi(match, comp=False): + r""" + The aim of the fourth heuristic is to find the function `\chi(x, y)` + that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx} + - \frac{\partial h}{\partial y}\chi = 0`. + + This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition, + `h` should be a rational function in `x` and `y`. The method used here is + to substitute a general binomial for `\chi` up to a certain maximum degree + is reached. The coefficients of the polynomials, are calculated by by collecting + terms of the same order in `x` and `y`. + + After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to + determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h` + which would give `-\xi` as the quotient and `\eta` as the remainder. + + + References + ========== + - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra + Solving of First Order ODEs Using Symmetry Methods, pp. 8 + + """ + + h = match['h'] + hy = match['hy'] + func = match['func'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + if h.is_rational_function(): + schi, schix, schiy = symbols("schi, schix, schiy") + cpde = schix + h*schiy - hy*schi + num, denom = cancel(cpde).as_numer_denom() + deg = Poly(num, x, y).total_degree() + + chi = Function('chi')(x, y) + chix = chi.diff(x) + chiy = chi.diff(y) + cpde = chix + h*chiy - hy*chi + chieq = Symbol("chi") + for i in range(1, deg + 1): + chieq += Add(*[ + Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) + for power in range(i + 1)]) + cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom() + cnum = expand(cnum) + if cnum.is_polynomial(x, y) and cnum.is_Add: + cpoly = Poly(cnum, x, y).as_dict() + if cpoly: + solsyms = chieq.free_symbols - {x, y} + soldict = solve(cpoly.values(), *solsyms) + if isinstance(soldict, list): + soldict = soldict[0] + if any(soldict.values()): + chieq = chieq.subs(soldict) + dict_ = dict.fromkeys(solsyms, 1) + chieq = chieq.subs(dict_) + # After finding chi, the main aim is to find out + # eta, xi by the equation eta = xi*h + chi + # One method to set xi, would be rearranging it to + # (eta/h) - xi = (chi/h). This would mean dividing + # chi by h would give -xi as the quotient and eta + # as the remainder. Thanks to Sean Vig for suggesting + # this method. + xic, etac = div(chieq, h) + inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)} + return [inf] + +def lie_heuristic_function_sum(match, comp=False): + r""" + This heuristic uses the following two assumptions on `\xi` and `\eta` + + .. math:: \eta = 0, \xi = f(x) + g(y) + + .. math:: \eta = f(x) + g(y), \xi = 0 + + The first assumption of this heuristic holds good if + + .. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{ + \partial x^{2}}(h^{-1}))^{-1}] + + is separable in `x` and `y`, + + 1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`. + From this `g(y)` can be determined. + 2. The separated factors containing `x` is `f''(x)`. + 3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals + `\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined. + + The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as + `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first + assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates + are again interchanged, to get `\eta` as `f(x) + g(y)`. + + For both assumptions, the constant factors are separated among `g(y)` + and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that + obtained from 2]. If not possible, then this heuristic fails. + + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 7 - pp. 8 + + """ + + xieta = [] + h = match['h'] + func = match['func'] + hinv = match['hinv'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + for odefac in [h, hinv]: + factor = odefac*((1/odefac).diff(x, 2)) + sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y]) + if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y): + k = Dummy("k") + try: + gy = k*integrate(sep[y], y) + except NotImplementedError: + pass + else: + fdd = 1/(k*sep[x]*sep['coeff']) + fx = simplify(fdd/factor - gy) + check = simplify(fx.diff(x, 2) - fdd) + if fx: + if not check: + fx = fx.subs(k, 1) + gy = (gy/k) + else: + sol = solve(check, k) + if sol: + sol = sol[0] + fx = fx.subs(k, sol) + gy = (gy/k)*sol + else: + continue + if odefac == hinv: # Inverse ODE + fx = fx.subs(x, y) + gy = gy.subs(y, x) + etaval = factor_terms(fx + gy) + if etaval.is_Mul: + etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)]) + if odefac == hinv: # Inverse ODE + inf = {eta: etaval.subs(y, func), xi : S.Zero} + else: + inf = {xi: etaval.subs(y, func), eta : S.Zero} + if not comp: + return [inf] + else: + xieta.append(inf) + + if xieta: + return xieta + +def lie_heuristic_abaco2_similar(match, comp=False): + r""" + This heuristic uses the following two assumptions on `\xi` and `\eta` + + .. math:: \eta = g(x), \xi = f(x) + + .. math:: \eta = f(y), \xi = g(y) + + For the first assumption, + + 1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{ + \partial yy}}` is calculated. Let us say this value is A + + 2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{ + \frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)` + and `A(x)*f(x)` gives `g(x)` + + 3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{ + \partial Y}} = \gamma` is calculated. If + + a] `\gamma` is a function of `x` alone + + b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{ + \partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone. + then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)` + + The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as + `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption + satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again + interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)` + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 10 - pp. 12 + + """ + + h = match['h'] + hx = match['hx'] + hy = match['hy'] + func = match['func'] + hinv = match['hinv'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + factor = cancel(h.diff(y)/h.diff(y, 2)) + factorx = factor.diff(x) + factory = factor.diff(y) + if not factor.has(x) and not factor.has(y): + A = Wild('A', exclude=[y]) + B = Wild('B', exclude=[y]) + C = Wild('C', exclude=[x, y]) + match = h.match(A + B*exp(y/C)) + try: + tau = exp(-integrate(match[A]/match[C]), x)/match[B] + except NotImplementedError: + pass + else: + gx = match[A]*tau + return [{xi: tau, eta: gx}] + + else: + gamma = cancel(factorx/factory) + if not gamma.has(y): + tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma)) + if not tauint.has(y): + try: + tau = exp(integrate(tauint, x)) + except NotImplementedError: + pass + else: + gx = -tau*gamma + return [{xi: tau, eta: gx}] + + factor = cancel(hinv.diff(y)/hinv.diff(y, 2)) + factorx = factor.diff(x) + factory = factor.diff(y) + if not factor.has(x) and not factor.has(y): + A = Wild('A', exclude=[y]) + B = Wild('B', exclude=[y]) + C = Wild('C', exclude=[x, y]) + match = h.match(A + B*exp(y/C)) + try: + tau = exp(-integrate(match[A]/match[C]), x)/match[B] + except NotImplementedError: + pass + else: + gx = match[A]*tau + return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] + + else: + gamma = cancel(factorx/factory) + if not gamma.has(y): + tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/( + hinv + gamma)) + if not tauint.has(y): + try: + tau = exp(integrate(tauint, x)) + except NotImplementedError: + pass + else: + gx = -tau*gamma + return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] + + +def lie_heuristic_abaco2_unique_unknown(match, comp=False): + r""" + This heuristic assumes the presence of unknown functions or known functions + with non-integer powers. + + 1. A list of all functions and non-integer powers containing x and y + 2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{ + \frac{\partial f}{\partial x}} = R` + + If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then + + a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return + `\xi` and `\eta` + b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE. + If yes, then return `\xi` and `\eta` + + If not, then check if + + a] :math:`\xi = -R,\eta = 1` + + b] :math:`\xi = 1, \eta = -\frac{1}{R}` + + are solutions. + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 10 - pp. 12 + + """ + + h = match['h'] + hx = match['hx'] + hy = match['hy'] + func = match['func'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + funclist = [] + for atom in h.atoms(Pow): + base, exp = atom.as_base_exp() + if base.has(x) and base.has(y): + if not exp.is_Integer: + funclist.append(atom) + + for function in h.atoms(AppliedUndef): + syms = function.free_symbols + if x in syms and y in syms: + funclist.append(function) + + for f in funclist: + frac = cancel(f.diff(y)/f.diff(x)) + sep = separatevars(frac, dict=True, symbols=[x, y]) + if sep and sep['coeff']: + xitry1 = sep[x] + etatry1 = -1/(sep[y]*sep['coeff']) + pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy + if not simplify(pde1): + return [{xi: xitry1, eta: etatry1.subs(y, func)}] + xitry2 = 1/etatry1 + etatry2 = 1/xitry1 + pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy + if not simplify(expand(pde2)): + return [{xi: xitry2.subs(y, func), eta: etatry2}] + + else: + etatry = -1/frac + pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy + if not simplify(pde): + return [{xi: S.One, eta: etatry.subs(y, func)}] + xitry = -frac + pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy + if not simplify(expand(pde)): + return [{xi: xitry.subs(y, func), eta: S.One}] + + +def lie_heuristic_abaco2_unique_general(match, comp=False): + r""" + This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)` + without making any assumptions on `h`. + + The complete sequence of steps is given in the paper mentioned below. + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 10 - pp. 12 + + """ + hx = match['hx'] + hy = match['hy'] + func = match['func'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + A = hx.diff(y) + B = hy.diff(y) + hy**2 + C = hx.diff(x) - hx**2 + + if not (A and B and C): + return + + Ax = A.diff(x) + Ay = A.diff(y) + Axy = Ax.diff(y) + Axx = Ax.diff(x) + Ayy = Ay.diff(y) + D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay + if not D: + E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A) + if E1: + E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) + if not E2: + E3 = simplify( + E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4) + if not E3: + etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1)) + if x not in etaval: + try: + etaval = exp(integrate(etaval, y)) + except NotImplementedError: + pass + else: + xival = -4*A**3*etaval/E1 + if y not in xival: + return [{xi: xival, eta: etaval.subs(y, func)}] + + else: + E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) + if E1: + E2 = simplify( + 4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2)) + if not E2: + E3 = simplify( + -(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D + + (A*hx - 3*Ax)*E1)*E1) + if not E3: + etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D)) + if x not in etaval: + try: + etaval = exp(integrate(etaval, y)) + except NotImplementedError: + pass + else: + xival = -E1*etaval/D + if y not in xival: + return [{xi: xival, eta: etaval.subs(y, func)}] + + +def lie_heuristic_linear(match, comp=False): + r""" + This heuristic assumes + + 1. `\xi = ax + by + c` and + 2. `\eta = fx + gy + h` + + After substituting the following assumptions in the determining PDE, it + reduces to + + .. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x} + - (fx + gy + c)\frac{\partial h}{\partial y} + + Solving the reduced PDE obtained, using the method of characteristics, becomes + impractical. The method followed is grouping similar terms and solving the system + of linear equations obtained. The difference between the bivariate heuristic is that + `h` need not be a rational function in this case. + + References + ========== + - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order + ODE Patterns, pp. 10 - pp. 12 + + """ + h = match['h'] + hx = match['hx'] + hy = match['hy'] + func = match['func'] + x = func.args[0] + y = match['y'] + xi = Function('xi')(x, func) + eta = Function('eta')(x, func) + + coeffdict = {} + symbols = numbered_symbols("c", cls=Dummy) + symlist = [next(symbols) for _ in islice(symbols, 6)] + C0, C1, C2, C3, C4, C5 = symlist + pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2 + pde, denom = pde.as_numer_denom() + pde = powsimp(expand(pde)) + if pde.is_Add: + terms = pde.args + for term in terms: + if term.is_Mul: + rem = Mul(*[m for m in term.args if not m.has(x, y)]) + xypart = term/rem + if xypart not in coeffdict: + coeffdict[xypart] = rem + else: + coeffdict[xypart] += rem + else: + if term not in coeffdict: + coeffdict[term] = S.One + else: + coeffdict[term] += S.One + + sollist = coeffdict.values() + soldict = solve(sollist, symlist) + if soldict: + if isinstance(soldict, list): + soldict = soldict[0] + subval = soldict.values() + if any(t for t in subval): + onedict = dict(zip(symlist, [1]*6)) + xival = C0*x + C1*func + C2 + etaval = C3*x + C4*func + C5 + xival = xival.subs(soldict) + etaval = etaval.subs(soldict) + xival = xival.subs(onedict) + etaval = etaval.subs(onedict) + return [{xi: xival, eta: etaval}] + + +def _lie_group_remove(coords): + r""" + This function is strictly meant for internal use by the Lie group ODE solving + method. It replaces arbitrary functions returned by pdsolve as follows: + + 1] If coords is an arbitrary function, then its argument is returned. + 2] An arbitrary function in an Add object is replaced by zero. + 3] An arbitrary function in a Mul object is replaced by one. + 4] If there is no arbitrary function coords is returned unchanged. + + Examples + ======== + + >>> from sympy.solvers.ode.lie_group import _lie_group_remove + >>> from sympy import Function + >>> from sympy.abc import x, y + >>> F = Function("F") + >>> eq = x**2*y + >>> _lie_group_remove(eq) + x**2*y + >>> eq = F(x**2*y) + >>> _lie_group_remove(eq) + x**2*y + >>> eq = x*y**2 + F(x**3) + >>> _lie_group_remove(eq) + x*y**2 + >>> eq = (F(x**3) + y)*x**4 + >>> _lie_group_remove(eq) + x**4*y + + """ + if isinstance(coords, AppliedUndef): + return coords.args[0] + elif coords.is_Add: + subfunc = coords.atoms(AppliedUndef) + if subfunc: + for func in subfunc: + coords = coords.subs(func, 0) + return coords + elif coords.is_Pow: + base, expr = coords.as_base_exp() + base = _lie_group_remove(base) + expr = _lie_group_remove(expr) + return base**expr + elif coords.is_Mul: + mulargs = [] + coordargs = coords.args + for arg in coordargs: + if not isinstance(coords, AppliedUndef): + mulargs.append(_lie_group_remove(arg)) + return Mul(*mulargs) + return coords diff --git a/shared/package-files/0b/0b63a84e43546a614c661fbf0ccf973a7c2a75aa79e90a3eea1770a9cb4e5563/cpp_codegen.h b/shared/package-files/0b/0b63a84e43546a614c661fbf0ccf973a7c2a75aa79e90a3eea1770a9cb4e5563/cpp_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..d8a46fa7893aaf9c2da29b65e7c64241b6470b75 --- /dev/null +++ b/shared/package-files/0b/0b63a84e43546a614c661fbf0ccf973a7c2a75aa79e90a3eea1770a9cb4e5563/cpp_codegen.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +class CppVarNameRewriter; + +// Generates C++ code from the IR. +// +// Vector operations are unrolled. +// For example: +// C[Ramp(0, 1, 3)] = A[Ramp(0, 2, 3)] + B[Ramp(0, 3, 3)]; +// is unrolled into: +// C[0] = A[0] + B[0]; +// C[1] = A[2] + B[3]; +// C[2] = A[4] + B[6]; +class TORCH_API CppPrinter : public IRPrinter { + public: + explicit CppPrinter(std::ostream* os); + ~CppPrinter() override; + + void printPrologue(); + + using IRPrinter::visit; + + // Binary expressions. + void visit(const ModPtr&) override; + void visit(const MaxPtr&) override; + void visit(const MinPtr&) override; + + // Conditional expressions. + void visit(const CompareSelectPtr&) override; + void visit(const IfThenElsePtr&) override; + + // Tensor operations. + void visit(const AllocatePtr&) override; + void visit(const FreePtr&) override; + void visit(const LoadPtr&) override; + void visit(const StorePtr&) override; + + // Casts. + void visit(const CastPtr&) override; + void visit(const BitCastPtr&) override; + + // Calls. + void visit(const IntrinsicsPtr&) override; + void visit(const ExternalCallPtr&) override; + + // Vars. + void visit(const LetPtr&) override; + void visit(const VarPtr&) override; + + // Vector data types. + void visit(const RampPtr&) override; + void visit(const BroadcastPtr&) override; + + private: + int lane_; + std::unordered_map vector_vars_; +}; + +class TORCH_API CppCodeGen : public CodeGen { + public: + CppCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + + ~CppCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + template + void operator()(const Ts&... ts) { + call(std::vector({CallArg(ts)...})); + } + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + void init(); + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr var_name_rewriter_; +}; + +} // namespace torch::jit::tensorexpr diff --git a/shared/package-files/0b/0b66f71d905a127ea7bb03bb5dc5cfeed09fce684fc711fa1c4a9f475a4c70b1/_utils.py b/shared/package-files/0b/0b66f71d905a127ea7bb03bb5dc5cfeed09fce684fc711fa1c4a9f475a4c70b1/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..25f1c51171734704c6c2ccea3a739de629ff5262 --- /dev/null +++ b/shared/package-files/0b/0b66f71d905a127ea7bb03bb5dc5cfeed09fce684fc711fa1c4a9f475a4c70b1/_utils.py @@ -0,0 +1,67 @@ +# mypy: allow-untyped-defs +import sys +from typing import Optional + +import torch +from torch._logging import LazyString + + +def lazy_format_graph_code(name, gm, maybe_id=None, **kwargs): + """ + Returns a LazyString that formats the graph code. + """ + + def format_name(): + if maybe_id is not None: + return f"{name} {maybe_id}" + else: + return name + + if "print_output" not in kwargs: + kwargs["print_output"] = False + + if "colored" in kwargs: + try: + if not sys.stdout.isatty(): + kwargs["colored"] = False + except AttributeError: + kwargs["colored"] = False + + return LazyString( + lambda: _format_graph_code( + f"===== {format_name()} =====\n", + gm.forward.__code__.co_filename, + gm.print_readable(**kwargs), + ) + ) + + +def _format_graph_code(name, filename, graph_str): + """ + Returns a string that formats the graph code. + """ + return f"TRACED GRAPH\n {name} {filename} {graph_str}\n" + + +def first_call_function_nn_module_stack(graph: torch.fx.Graph) -> Optional[dict]: + """ + Returns the nn_module_stack of the first call_function node. + """ + for node in graph.nodes: + if node.op == "call_function" and "nn_module_stack" in node.meta: + return node.meta["nn_module_stack"] + return None + + +def get_node_context(node, num_nodes=2) -> str: + """ + Returns a string of the last num_nodes nodes in the graph. + """ + node_contexts = [] + cur = node + for _ in range(num_nodes): + node_contexts.append(cur.format_node()) + if cur.op == "root": + break + cur = cur.prev + return "\n".join(node_contexts[::-1]) diff --git a/shared/package-files/0b/0b6ee589582e6e0d20d5390bc40b515f5237186ae03f260a729b2b87f3680c8d/shape_analysis.h b/shared/package-files/0b/0b6ee589582e6e0d20d5390bc40b515f5237186ae03f260a729b2b87f3680c8d/shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d784f7fc23237064a8387ba993b312a36e83375c --- /dev/null +++ b/shared/package-files/0b/0b6ee589582e6e0d20d5390bc40b515f5237186ae03f260a729b2b87f3680c8d/shape_analysis.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Graph; + +struct propagation_error : std::exception {}; + +class PropertyPropBase { + // Used for both Shape Propagation and Dtype/Device Propagation + public: + explicit PropertyPropBase(std::shared_ptr graph) + : graph_(std::move(graph)) {} + virtual ~PropertyPropBase() = default; + + void propagateBlock(Block* block, bool insert_expands = true); + // insert_expands is used for shape inference + + void processIf(Node* node); + void processLoop(Node* node); + + protected: + virtual void propagateNode(Node* node, bool insert_expands = true) = 0; + void setUnshapedType(Value* o); + void setUnshapedType(Node* node); + std::shared_ptr graph_; +}; + +TORCH_API void EraseShapeInformation(const std::shared_ptr& graph); +TORCH_API void PropagateInputShapes(const std::shared_ptr& graph); + +TORCH_API bool mergeTypes( + ArrayRef lhs, + ArrayRef rhs, + ArrayRef outputs); + +} // namespace torch::jit diff --git a/shared/package-files/0b/0b70bad7ef3ed293b296d49223d9204a7214df1d3f5e14838112343247a3d748/resharding.cpython-311.pyc b/shared/package-files/0b/0b70bad7ef3ed293b296d49223d9204a7214df1d3f5e14838112343247a3d748/resharding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceeb5d3936e2622cd1c228801fd9690bfe0b575b Binary files /dev/null and b/shared/package-files/0b/0b70bad7ef3ed293b296d49223d9204a7214df1d3f5e14838112343247a3d748/resharding.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b75c4175fb9139d71c3895c6426123761499027e85ca81047693cddbac38d7b/fix_itertools.cpython-311.pyc b/shared/package-files/0b/0b75c4175fb9139d71c3895c6426123761499027e85ca81047693cddbac38d7b/fix_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc62fa3626e4f99f99ffc5f57ec3bb2c41d626f8 Binary files /dev/null and b/shared/package-files/0b/0b75c4175fb9139d71c3895c6426123761499027e85ca81047693cddbac38d7b/fix_itertools.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b7a1c94d6dcc187a374487c0c2a08a8dccf0b54e5c04e7917ad928b723118e3/test_round.cpython-311.pyc b/shared/package-files/0b/0b7a1c94d6dcc187a374487c0c2a08a8dccf0b54e5c04e7917ad928b723118e3/test_round.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a1c27330f864d1ba9b39050a8b62544a5631f58 Binary files /dev/null and b/shared/package-files/0b/0b7a1c94d6dcc187a374487c0c2a08a8dccf0b54e5c04e7917ad928b723118e3/test_round.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b7a2be5f8069cfd54cd37c495a57ab040dd306f165306ab962943cf5f3f22ed/graph_signature.cpython-311.pyc b/shared/package-files/0b/0b7a2be5f8069cfd54cd37c495a57ab040dd306f165306ab962943cf5f3f22ed/graph_signature.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85890fcc1bfa57da132db66d4969bd3b4201f439 Binary files /dev/null and b/shared/package-files/0b/0b7a2be5f8069cfd54cd37c495a57ab040dd306f165306ab962943cf5f3f22ed/graph_signature.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b7b92d8d33efd8dd7578fb513df324aea8c934be4929fbddf4aca20cc5b465c/__init__.cpython-311.pyc b/shared/package-files/0b/0b7b92d8d33efd8dd7578fb513df324aea8c934be4929fbddf4aca20cc5b465c/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7eebe0c110a1cff226fbf2a848ddbbd5fc5f286 Binary files /dev/null and b/shared/package-files/0b/0b7b92d8d33efd8dd7578fb513df324aea8c934be4929fbddf4aca20cc5b465c/__init__.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b7b997c504986aa97f54a15b1fb9e665e41c6916ff805c48320ce94e63db12e/_weight_int8pack_mm.h b/shared/package-files/0b/0b7b997c504986aa97f54a15b1fb9e665e41c6916ff805c48320ce94e63db12e/_weight_int8pack_mm.h new file mode 100644 index 0000000000000000000000000000000000000000..3997eaf2e6e367c3580d1c8911a101a759f978ce --- /dev/null +++ b/shared/package-files/0b/0b7b997c504986aa97f54a15b1fb9e665e41c6916ff805c48320ce94e63db12e/_weight_int8pack_mm.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_weight_int8pack_mm(Tensor self, Tensor mat2, Tensor scales) -> Tensor +inline at::Tensor _weight_int8pack_mm(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & scales) { + return at::_ops::_weight_int8pack_mm::call(self, mat2, scales); +} + +} diff --git a/shared/package-files/0b/0b80f55fc236b2db5e00f80c9e8dd9075f33cdd1f0489a8f7449c3ff75667a35/run_const_graph.cpython-311.pyc b/shared/package-files/0b/0b80f55fc236b2db5e00f80c9e8dd9075f33cdd1f0489a8f7449c3ff75667a35/run_const_graph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd617514a0a27c60961e723253493449bdb2bcf2 Binary files /dev/null and b/shared/package-files/0b/0b80f55fc236b2db5e00f80c9e8dd9075f33cdd1f0489a8f7449c3ff75667a35/run_const_graph.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b86e8f923b1f01b31bd3e0cff438f522c121174a168caa9611a1e74c99b4758/test_runtests_pytest.py b/shared/package-files/0b/0b86e8f923b1f01b31bd3e0cff438f522c121174a168caa9611a1e74c99b4758/test_runtests_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..cd56d831f3618c9dbb8a1dffe63d95a0befc6adf --- /dev/null +++ b/shared/package-files/0b/0b86e8f923b1f01b31bd3e0cff438f522c121174a168caa9611a1e74c99b4758/test_runtests_pytest.py @@ -0,0 +1,171 @@ +import pathlib +from typing import List + +import pytest + +from sympy.testing.runtests_pytest import ( + make_absolute_path, + sympy_dir, + update_args_with_paths, +) + + +class TestMakeAbsolutePath: + + @staticmethod + @pytest.mark.parametrize( + 'partial_path', ['sympy', 'sympy/core', 'sympy/nonexistant_directory'], + ) + def test_valid_partial_path(partial_path: str): + """Paths that start with `sympy` are valid.""" + _ = make_absolute_path(partial_path) + + @staticmethod + @pytest.mark.parametrize( + 'partial_path', ['not_sympy', 'also/not/sympy'], + ) + def test_invalid_partial_path_raises_value_error(partial_path: str): + """A `ValueError` is raises on paths that don't start with `sympy`.""" + with pytest.raises(ValueError): + _ = make_absolute_path(partial_path) + + +class TestUpdateArgsWithPaths: + + @staticmethod + def test_no_paths(): + """If no paths are passed, only `sympy` and `doc/src` are appended. + + `sympy` and `doc/src` are the `testpaths` stated in `pytest.ini`. They + need to be manually added as if any path-related arguments are passed + to `pytest.main` then the settings in `pytest.ini` may be ignored. + + """ + paths = [] + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy')), + str(pathlib.Path(sympy_dir(), 'doc/src')), + ] + assert args == expected + + @staticmethod + @pytest.mark.parametrize( + 'path', + ['sympy/core/tests/test_basic.py', '_basic'] + ) + def test_one_file(path: str): + """Single files/paths, full or partial, are matched correctly.""" + args = update_args_with_paths(paths=[path], keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')), + ] + assert args == expected + + @staticmethod + def test_partial_path_from_root(): + """Partial paths from the root directly are matched correctly.""" + args = update_args_with_paths(paths=['sympy/functions'], keywords=None, args=[]) + expected = [str(pathlib.Path(sympy_dir(), 'sympy/functions'))] + assert args == expected + + @staticmethod + def test_multiple_paths_from_root(): + """Multiple paths, partial or full, are matched correctly.""" + paths = ['sympy/core/tests/test_basic.py', 'sympy/functions'] + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')), + str(pathlib.Path(sympy_dir(), 'sympy/functions')), + ] + assert args == expected + + @staticmethod + @pytest.mark.parametrize( + 'paths, expected_paths', + [ + ( + ['/core', '/util'], + [ + 'doc/src/modules/utilities', + 'doc/src/reference/public/utilities', + 'sympy/core', + 'sympy/logic/utilities', + 'sympy/utilities', + ] + ), + ] + ) + def test_multiple_paths_from_non_root(paths: List[str], expected_paths: List[str]): + """Multiple partial paths are matched correctly.""" + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + assert len(args) == len(expected_paths) + for arg, expected in zip(sorted(args), expected_paths): + assert expected in arg + + @staticmethod + @pytest.mark.parametrize( + 'paths', + [ + + [], + ['sympy/physics'], + ['sympy/physics/mechanics'], + ['sympy/physics/mechanics/tests'], + ['sympy/physics/mechanics/tests/test_kane3.py'], + ] + ) + def test_string_as_keyword(paths: List[str]): + """String keywords are matched correctly.""" + keywords = ('bicycle', ) + args = update_args_with_paths(paths=paths, keywords=keywords, args=[]) + expected_args = ['sympy/physics/mechanics/tests/test_kane3.py::test_bicycle'] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + @pytest.mark.parametrize( + 'paths', + [ + + [], + ['sympy/core'], + ['sympy/core/tests'], + ['sympy/core/tests/test_sympify.py'], + ] + ) + def test_integer_as_keyword(paths: List[str]): + """Integer keywords are matched correctly.""" + keywords = ('3538', ) + args = update_args_with_paths(paths=paths, keywords=keywords, args=[]) + expected_args = ['sympy/core/tests/test_sympify.py::test_issue_3538'] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + def test_multiple_keywords(): + """Multiple keywords are matched correctly.""" + keywords = ('bicycle', '3538') + args = update_args_with_paths(paths=[], keywords=keywords, args=[]) + expected_args = [ + 'sympy/core/tests/test_sympify.py::test_issue_3538', + 'sympy/physics/mechanics/tests/test_kane3.py::test_bicycle', + ] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + def test_keyword_match_in_multiple_files(): + """Keywords are matched across multiple files.""" + keywords = ('1130', ) + args = update_args_with_paths(paths=[], keywords=keywords, args=[]) + expected_args = [ + 'sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs_1130', + 'sympy/utilities/tests/test_lambdify.py::test_python_div_zero_issue_11306', + ] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg diff --git a/shared/package-files/0b/0b89c21490a500d91c2f28beaebb8b84fd3c9519fcd3d04d039d5f4d3ac28b40/meta_tracer.cpython-311.pyc b/shared/package-files/0b/0b89c21490a500d91c2f28beaebb8b84fd3c9519fcd3d04d039d5f4d3ac28b40/meta_tracer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ddc4ab13c66a3c6f02ef0b31b95830b26b45e48 Binary files /dev/null and b/shared/package-files/0b/0b89c21490a500d91c2f28beaebb8b84fd3c9519fcd3d04d039d5f4d3ac28b40/meta_tracer.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b8aa7d229bb521be9db6e9598bfd06c5d9be391e1b2cd9ea247526ea5a405cb/hip_fp8.h b/shared/package-files/0b/0b8aa7d229bb521be9db6e9598bfd06c5d9be391e1b2cd9ea247526ea5a405cb/hip_fp8.h new file mode 100644 index 0000000000000000000000000000000000000000..82f47afcba08f02ff35d129a075d57225afb6b94 --- /dev/null +++ b/shared/package-files/0b/0b8aa7d229bb521be9db6e9598bfd06c5d9be391e1b2cd9ea247526ea5a405cb/hip_fp8.h @@ -0,0 +1,33 @@ +/* +Copyright (c) 2024 Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +#ifndef HIP_INCLUDE_HIP_HIP_FP8_H +#define HIP_INCLUDE_HIP_HIP_FP8_H + +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +// We only have fnuz defs for now, which are not supported by other platforms +#include +#endif + +#endif // HIP_INCLUDE_HIP_HIP_FP8_H diff --git a/shared/package-files/0b/0b8ad69d227293b2fab999c8fa4018bed6df157c5b6b4a355e3a4e4e45abf7bb/test_fp_groups.py b/shared/package-files/0b/0b8ad69d227293b2fab999c8fa4018bed6df157c5b6b4a355e3a4e4e45abf7bb/test_fp_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..3f57bdf8eff92a3022d8e01cd74ce98575987929 --- /dev/null +++ b/shared/package-files/0b/0b8ad69d227293b2fab999c8fa4018bed6df157c5b6b4a355e3a4e4e45abf7bb/test_fp_groups.py @@ -0,0 +1,257 @@ +from sympy.core.singleton import S +from sympy.combinatorics.fp_groups import (FpGroup, low_index_subgroups, + reidemeister_presentation, FpSubgroup, + simplify_presentation) +from sympy.combinatorics.free_groups import (free_group, FreeGroup) + +from sympy.testing.pytest import slow + +""" +References +========== + +[1] Holt, D., Eick, B., O'Brien, E. +"Handbook of Computational Group Theory" + +[2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson +Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. +"Implementation and Analysis of the Todd-Coxeter Algorithm" + +[3] PROC. SECOND INTERNAT. CONF. THEORY OF GROUPS, CANBERRA 1973, +pp. 347-356. "A Reidemeister-Schreier program" by George Havas. +http://staff.itee.uq.edu.au/havas/1973cdhw.pdf + +""" + +def test_low_index_subgroups(): + F, x, y = free_group("x, y") + + # Example 5.10 from [1] Pg. 194 + f = FpGroup(F, [x**2, y**3, (x*y)**4]) + L = low_index_subgroups(f, 4) + t1 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]], + [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]], + [[1, 1, 0, 0], [0, 0, 1, 1]]] + for i in range(len(t1)): + assert L[i].table == t1[i] + + f = FpGroup(F, [x**2, y**3, (x*y)**7]) + L = low_index_subgroups(f, 15) + t2 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [4, 4, 5, 3], [6, 6, 3, 4], [5, 5, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [5, 5, 3, 4], [4, 4, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [9, 9, 6, 8], [12, 12, 11, 7], [8, 8, 7, 10], + [10, 10, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [12, 12, 6, 8], [10, 10, 11, 7], [8, 8, 7, 10], + [9, 9, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [12, 12, 6, 8], [13, 13, 11, 7], [8, 8, 7, 10], + [9, 9, 12, 12], [10, 10, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] + , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [11, 11, 12, 10], [13, 13, 10, 11], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] + , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], + [11, 11, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 4, 4] + , [7, 7, 6, 3], [8, 8, 3, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], + [11, 11, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [5, 5, 6, 3], [9, 9, 3, 5], [10, 10, 8, 4], [8, 8, 4, 7], + [6, 6, 10, 11], [7, 7, 11, 9], [12, 12, 9, 10], [11, 11, 13, 14], + [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], + [5, 5, 10, 12], [7, 7, 12, 9], [8, 8, 11, 11], [13, 13, 9, 10], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], + [5, 5, 12, 11], [7, 7, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], + [5, 5, 9, 9], [6, 6, 11, 12], [8, 8, 12, 10], [13, 13, 10, 11], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], + [5, 5, 12, 11], [6, 6, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [11, 11, 8, 4], [12, 12, 4, 7], + [5, 5, 9, 9], [6, 6, 12, 13], [7, 7, 11, 11], [8, 8, 13, 10], + [13, 13, 10, 12]], + [[1, 1, 0, 0], [0, 0, 2, 3], [4, 4, 3, 1], [5, 5, 1, 2], [2, 2, 4, 4] + , [3, 3, 6, 7], [7, 7, 7, 5], [6, 6, 5, 6]]] + for i in range(len(t2)): + assert L[i].table == t2[i] + + f = FpGroup(F, [x**2, y**3, (x*y)**7]) + L = low_index_subgroups(f, 10, [x]) + t3 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [4, 4, 5, 3], + [6, 6, 3, 4], [5, 5, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], + [5, 5, 3, 4], [4, 4, 6, 6]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8], + [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]]] + for i in range(len(t3)): + assert L[i].table == t3[i] + + +def test_subgroup_presentations(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x**3, y**5, (x*y)**2]) + H = [x*y, x**-1*y**-1*x*y*x] + p1 = reidemeister_presentation(f, H) + assert str(p1) == "((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))" + + H = f.subgroup(H) + assert (H.generators, H.relators) == p1 + + f = FpGroup(F, [x**3, y**3, (x*y)**3]) + H = [x*y, x*y**-1] + p2 = reidemeister_presentation(f, H) + assert str(p2) == "((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))" + + f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) + H = [x] + p3 = reidemeister_presentation(f, H) + assert str(p3) == "((x_0,), (x_0**4,))" + + f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) + H = [x] + p4 = reidemeister_presentation(f, H) + assert str(p4) == "((x_0,), (x_0**6,))" + + # this presentation can be improved, the most simplified form + # of presentation is + # See [2] Pg 474 group PSL_2(11) + # This is the group PSL_2(11) + F, a, b, c = free_group("a, b, c") + f = FpGroup(F, [a**11, b**5, c**4, (b*c**2)**2, (a*b*c)**3, (a**4*c**2)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b]) + H = [a, b, c**2] + gens, rels = reidemeister_presentation(f, H) + assert str(gens) == "(b_1, c_3)" + assert len(rels) == 18 + + +@slow +def test_order(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert f.order() == 8 + + f = FpGroup(F, [x*y*x**-1*y**-1, y**2]) + assert f.order() is S.Infinity + + F, a, b, c = free_group("a, b, c") + f = FpGroup(F, [a**250, b**2, c*b*c**-1*b, c**4, c**-1*a**-1*c*a, a**-1*b**-1*a*b]) + assert f.order() == 2000 + + F, x = free_group("x") + f = FpGroup(F, []) + assert f.order() is S.Infinity + + f = FpGroup(free_group('')[0], []) + assert f.order() == 1 + +def test_fp_subgroup(): + def _test_subgroup(K, T, S): + _gens = T(K.generators) + assert all(elem in S for elem in _gens) + assert T.is_injective() + assert T.image().order() == S.order() + F, x, y = free_group("x, y") + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + S = FpSubgroup(f, [x*y]) + assert (x*y)**-3 in S + K, T = f.subgroup([x*y], homomorphism=True) + assert T(K.generators) == [y*x**-1] + _test_subgroup(K, T, S) + + S = FpSubgroup(f, [x**-1*y*x]) + assert x**-1*y**4*x in S + assert x**-1*y**4*x**2 not in S + K, T = f.subgroup([x**-1*y*x], homomorphism=True) + assert T(K.generators[0]**3) == y**3 + _test_subgroup(K, T, S) + + f = FpGroup(F, [x**3, y**5, (x*y)**2]) + H = [x*y, x**-1*y**-1*x*y*x] + K, T = f.subgroup(H, homomorphism=True) + S = FpSubgroup(f, H) + _test_subgroup(K, T, S) + +def test_permutation_methods(): + F, x, y = free_group("x, y") + # DihedralGroup(8) + G = FpGroup(F, [x**2, y**8, x*y*x**-1*y]) + T = G._to_perm_group()[1] + assert T.is_isomorphism() + assert G.center() == [y**4] + + # DiheadralGroup(4) + G = FpGroup(F, [x**2, y**4, x*y*x**-1*y]) + S = FpSubgroup(G, G.normal_closure([x])) + assert x in S + assert y**-1*x*y in S + + # Z_5xZ_4 + G = FpGroup(F, [x*y*x**-1*y**-1, y**5, x**4]) + assert G.is_abelian + assert G.is_solvable + + # AlternatingGroup(5) + G = FpGroup(F, [x**3, y**2, (x*y)**5]) + assert not G.is_solvable + + # AlternatingGroup(4) + G = FpGroup(F, [x**3, y**2, (x*y)**3]) + assert len(G.derived_series()) == 3 + S = FpSubgroup(G, G.derived_subgroup()) + assert S.order() == 4 + + +def test_simplify_presentation(): + # ref #16083 + G = simplify_presentation(FpGroup(FreeGroup([]), [])) + assert not G.generators + assert not G.relators + + # CyclicGroup(3) + # The second generator in is trivial due to relators {x^2, x^5} + F, x, y = free_group("x, y") + G = simplify_presentation(FpGroup(F, [x**2, x**5, y**3])) + assert x in G.relators + +def test_cyclic(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) + assert f.is_cyclic + f = FpGroup(F, [x*y, x*y**-1]) + assert f.is_cyclic + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert not f.is_cyclic + + +def test_abelian_invariants(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) + assert f.abelian_invariants() == [] + f = FpGroup(F, [x*y, x*y**-1]) + assert f.abelian_invariants() == [2] + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert f.abelian_invariants() == [2, 4] diff --git a/shared/package-files/0b/0b8e28a8f36c9dd513ab3ed31d577b7656ad53c82012f8fcd5c7e3b1e756406a/test_linalg.cpython-311.pyc b/shared/package-files/0b/0b8e28a8f36c9dd513ab3ed31d577b7656ad53c82012f8fcd5c7e3b1e756406a/test_linalg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b28c313df7f09b4ef8d34c35e2902df86c7dc6 Binary files /dev/null and b/shared/package-files/0b/0b8e28a8f36c9dd513ab3ed31d577b7656ad53c82012f8fcd5c7e3b1e756406a/test_linalg.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b8e8c31ddd09da1307a6071336332ca3a0d7fb485ba30f0048b58b52677cb01/converter.cpython-311.pyc b/shared/package-files/0b/0b8e8c31ddd09da1307a6071336332ca3a0d7fb485ba30f0048b58b52677cb01/converter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..378badb404214fa069f607f53c56f9bc83b9498d Binary files /dev/null and b/shared/package-files/0b/0b8e8c31ddd09da1307a6071336332ca3a0d7fb485ba30f0048b58b52677cb01/converter.cpython-311.pyc differ diff --git a/shared/package-files/0b/0b937188231dd5fc12c0708cfd216b8cd56c6621a3e9768dd766ca59d80155c5/logical_xor_native.h b/shared/package-files/0b/0b937188231dd5fc12c0708cfd216b8cd56c6621a3e9768dd766ca59d80155c5/logical_xor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..784c8a544d31b65c2c38c2f9c2a1565536416688 --- /dev/null +++ b/shared/package-files/0b/0b937188231dd5fc12c0708cfd216b8cd56c6621a3e9768dd766ca59d80155c5/logical_xor_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor logical_xor(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_xor_(at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_xor_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0b9713cf64967cdb453f246345a3ad23ce461dee97ba83885c40ebe464ad4630/PhiloxCudaStateRaw.cuh b/shared/package-files/0b/0b9713cf64967cdb453f246345a3ad23ce461dee97ba83885c40ebe464ad4630/PhiloxCudaStateRaw.cuh new file mode 100644 index 0000000000000000000000000000000000000000..231cd167cacb4f9b4f2f48e159431b30f3d6dc28 --- /dev/null +++ b/shared/package-files/0b/0b9713cf64967cdb453f246345a3ad23ce461dee97ba83885c40ebe464ad4630/PhiloxCudaStateRaw.cuh @@ -0,0 +1,43 @@ +// No "#pragma once" because this is a raw definition that can be copied by jit codegen. +// Eager mode clients should not include this file directly, instead, +// they should #include , which has a #pragma once. + +// Stores RNG state values. Passed as a kernel argument. +// See Note [CUDA Graph-safe RNG states]. +// +// The raw definition lives in its own file so jit codegen can easily copy it. +namespace at { + +struct PhiloxCudaState { + PhiloxCudaState() = default; + // Called if graph capture is not underway + PhiloxCudaState(uint64_t seed, + uint64_t offset) { + seed_.val = seed; + offset_.val = offset; + } + // Called if graph capture is underway + PhiloxCudaState(int64_t* seed, + int64_t* offset_extragraph, + uint32_t offset_intragraph) { + seed_.ptr = seed; + offset_.ptr = offset_extragraph; + offset_intragraph_ = offset_intragraph; + captured_ = true; + } + + // Public members, directly accessible by at::cuda::philox::unpack. + // If we made them private with getters/setters, the getters/setters + // would have to be __device__, and we can't declare __device__ in ATen. + union Payload { + uint64_t val; + int64_t* ptr; + }; + + Payload seed_{}; + Payload offset_{}; + uint32_t offset_intragraph_ = 0; + bool captured_ = false; +}; + +} // namespace at diff --git a/shared/package-files/0b/0b9a78b2bb9dd97549ce563ec13fe61086c74848ff5d5e72e767fe0e1e7d4960/TensorpipeTargets.cmake b/shared/package-files/0b/0b9a78b2bb9dd97549ce563ec13fe61086c74848ff5d5e72e767fe0e1e7d4960/TensorpipeTargets.cmake new file mode 100644 index 0000000000000000000000000000000000000000..aae4e9095ecf2c2fdf659e6547c867cd631fbabc --- /dev/null +++ b/shared/package-files/0b/0b9a78b2bb9dd97549ce563ec13fe61086c74848ff5d5e72e767fe0e1e7d4960/TensorpipeTargets.cmake @@ -0,0 +1,122 @@ +# Generated by CMake + +if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8) + message(FATAL_ERROR "CMake >= 2.8.12 required") +endif() +if(CMAKE_VERSION VERSION_LESS "2.8.12") + message(FATAL_ERROR "CMake >= 2.8.12 required") +endif() +cmake_policy(PUSH) +cmake_policy(VERSION 2.8.12...3.30) +#---------------------------------------------------------------- +# Generated CMake target import file. +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Protect against multiple inclusion, which would fail when already imported targets are added once more. +set(_cmake_targets_defined "") +set(_cmake_targets_not_defined "") +set(_cmake_expected_targets "") +foreach(_cmake_expected_target IN ITEMS tensorpipe_uv tensorpipe tensorpipe_cuda) + list(APPEND _cmake_expected_targets "${_cmake_expected_target}") + if(TARGET "${_cmake_expected_target}") + list(APPEND _cmake_targets_defined "${_cmake_expected_target}") + else() + list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}") + endif() +endforeach() +unset(_cmake_expected_target) +if(_cmake_targets_defined STREQUAL _cmake_expected_targets) + unset(_cmake_targets_defined) + unset(_cmake_targets_not_defined) + unset(_cmake_expected_targets) + unset(CMAKE_IMPORT_FILE_VERSION) + cmake_policy(POP) + return() +endif() +if(NOT _cmake_targets_defined STREQUAL "") + string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}") + string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}") + message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n") +endif() +unset(_cmake_targets_defined) +unset(_cmake_targets_not_defined) +unset(_cmake_expected_targets) + + +# Compute the installation prefix relative to this file. +get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +if(_IMPORT_PREFIX STREQUAL "/") + set(_IMPORT_PREFIX "") +endif() + +# Create imported target tensorpipe_uv +add_library(tensorpipe_uv STATIC IMPORTED) + +set_target_properties(tensorpipe_uv PROPERTIES + INTERFACE_LINK_LIBRARIES "\$;\$;\$" +) + +# Create imported target tensorpipe +add_library(tensorpipe STATIC IMPORTED) + +set_target_properties(tensorpipe PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include" + INTERFACE_LINK_LIBRARIES "\$" +) + +# Create imported target tensorpipe_cuda +add_library(tensorpipe_cuda STATIC IMPORTED) + +set_target_properties(tensorpipe_cuda PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "/usr/local/cuda/include" + INTERFACE_LINK_LIBRARIES "tensorpipe;/usr/local/cuda/lib64/libcudart.so" +) + +# Load information for each installed configuration. +file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/TensorpipeTargets-*.cmake") +foreach(_cmake_config_file IN LISTS _cmake_config_files) + include("${_cmake_config_file}") +endforeach() +unset(_cmake_config_file) +unset(_cmake_config_files) + +# Cleanup temporary variables. +set(_IMPORT_PREFIX) + +# Loop over all imported files and verify that they actually exist +foreach(_cmake_target IN LISTS _cmake_import_check_targets) + if(CMAKE_VERSION VERSION_LESS "3.28" + OR NOT DEFINED _cmake_import_check_xcframework_for_${_cmake_target} + OR NOT IS_DIRECTORY "${_cmake_import_check_xcframework_for_${_cmake_target}}") + foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}") + if(NOT EXISTS "${_cmake_file}") + message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file + \"${_cmake_file}\" +but this file does not exist. Possible reasons include: +* The file was deleted, renamed, or moved to another location. +* An install or uninstall procedure did not complete successfully. +* The installation package was faulty and contained + \"${CMAKE_CURRENT_LIST_FILE}\" +but not all the files it references. +") + endif() + endforeach() + endif() + unset(_cmake_file) + unset("_cmake_import_check_files_for_${_cmake_target}") +endforeach() +unset(_cmake_target) +unset(_cmake_import_check_targets) + +# This file does not depend on other imported targets which have +# been exported from the same project but in a separate export set. + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) +cmake_policy(POP) diff --git a/shared/package-files/0b/0b9c5740f23d8c8f1918c346790fdb9627b00252ee9def25c39dccef7d88f252/pass_manager.py b/shared/package-files/0b/0b9c5740f23d8c8f1918c346790fdb9627b00252ee9def25c39dccef7d88f252/pass_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..68753d9351f103003c9a8fcac402900ad63d1658 --- /dev/null +++ b/shared/package-files/0b/0b9c5740f23d8c8f1918c346790fdb9627b00252ee9def25c39dccef7d88f252/pass_manager.py @@ -0,0 +1,309 @@ +# mypy: allow-untyped-defs +import inspect +import logging +from functools import wraps +from queue import Queue +from typing import Callable + +import torch.nn as nn +from torch.fx._compatibility import compatibility +from torch.fx.graph_module import GraphModule +from torch.fx.passes.infra.pass_base import PassResult + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.WARNING) + +__all__ = ["pass_result_wrapper", "this_before_that_pass_constraint", "PassManager"] + + +@compatibility(is_backward_compatible=False) +def pass_result_wrapper(fn: Callable) -> Callable: + """ + Wrapper for passes which currently do not return a PassResult. + This wrapper makes them return a PassResult containing the modified object + and True for the "modified" flag. + + Args: + fn (Callable[Module, Any]) + + Returns: + wrapped_fn (Callable[Module, PassResult]) + """ + if fn is None: + return None + + @wraps(fn) + def wrapped_fn(gm): + res = fn(gm) + if res is None: + return PassResult(gm, True) + if isinstance(res, PassResult): + return res + elif isinstance(res, nn.Module): + return PassResult(res, True) + + if not inspect.isfunction(fn): + wrapped_fn.__name__ = type(fn).__name__ + + return wrapped_fn + + +def _validate_pass_schedule_constraint( + constraint: Callable[[Callable, Callable], bool], passes: list[Callable] +) -> None: + for i, a in enumerate(passes): + for j, b in enumerate(passes[i + 1 :]): + if constraint(a, b): + continue + raise RuntimeError( + f"pass schedule constraint violated. Expected {a} before {b}" + f" but found {a} at index {i} and {b} at index{j} in pass" + f" list." + ) + + +def _topological_sort_passes( + passes: list[Callable], constraints: list[Callable] +) -> list[Callable]: + """ + Args + passes: Passes that we are ordering + constraints: Constraints applied on these passes + + Returns + A sorted list of callables and a boolean of if a circular dependency + existed + """ + if len(constraints) == 0: + return passes + + # Contruct a graph mapping nodes to a list of their users + graph: dict[Callable, list[Callable]] = {p: [] for p in passes} + indegree_map: dict[Callable, int] = dict.fromkeys(passes, 0) + candidates: Queue = Queue() + for a in passes: + for b in passes: + if a == b: + continue + + for constraint in constraints: + if not constraint(a, b): + graph[b].append(a) + indegree_map[a] += 1 + + if indegree_map[a] == 0: + candidates.put(a) + + visited: dict[Callable, bool] = dict.fromkeys(passes, False) + sorted_passes: list[Callable] = [] + + while not candidates.empty(): + p = candidates.get() + sorted_passes.append(p) + visited[p] = True + + for n in graph[p]: + if not visited[n]: + indegree_map[n] -= 1 + if indegree_map[n] == 0: + candidates.put(n) + + # Check if there are unvisited nodes (aka cycles in the graph) + cycle_passes = list(filter(lambda p: indegree_map[p] != 0, indegree_map.keys())) + if len(cycle_passes) != 0: + error = ( + f"Circular dependency detected within the following passes: {cycle_passes}" + ) + raise RuntimeError(error) + + return sorted_passes + + +@compatibility(is_backward_compatible=False) +def this_before_that_pass_constraint(this: Callable, that: Callable) -> Callable: + """ + Defines a partial order ('depends on' function) where `this` must occur + before `that`. + + For example, the following pass list and constraint list would be invalid. + ``` + passes = [pass_b, pass_a] + + constraints = [this_before_that_pass_constraint(pass_a, pass_b)] + ``` + + Args: + this (Callable): pass which should occur first + that (Callable): pass which should occur later + + Returns: + depends_on (Callable[[Object, Object], bool] + """ + + def depends_on(a: Callable, b: Callable): + return a != that or b != this + + return depends_on + + +@compatibility(is_backward_compatible=False) +class PassManager: + """ + Construct a PassManager. + + Collects passes and constraints. This defines the pass schedule, manages + pass constraints and pass execution. + + Args: + passes (Optional[List[Callable]]): List of passes. A pass is a + callable which modifies an object and returns a PassResult + constraint (Optional[List[Callable]]): List of constraints. A + constraint is a callable which takes two passes (A, B) and returns + True if A depends on B and False otherwise. See implementation of + `this_before_that_pass_constraint` for example. + steps (int): Max number of times we run the passes (default = 1). + run_checks_after_each_pass (bool): Whether to run checks and linting + after each pass + suppress_check_failures (bool): Whether to raise errors when running + checks + """ + + passes: list[Callable[[nn.Module], PassResult]] + constraints: list[Callable[[Callable, Callable], bool]] + _validated: bool = False + steps: int = 1 + + def __init__( + self, + passes=None, + constraints=None, + steps=None, + run_checks_after_each_pass: bool = False, + suppress_check_failures: bool = False, + ): + self.passes = passes or [] + self.constraints = constraints or [] + if steps: + self.steps = steps + + self.run_checks_after_each_pass = run_checks_after_each_pass + self.suppress_check_failures = suppress_check_failures + + def add_pass(self, _pass: Callable): + """ + Adds a pass into the current list of passes. + """ + self.passes.append(_pass) + self._validated = False + + def add_constraint(self, constraint: Callable): + """ + Adds a constraint into the current list of constraints. + """ + self.constraints.append(constraint) + self._validated = False + + def validate_constraints(self): + """ + Validates that current pass schedule defined by `self.passes` is valid + according to all constraints in `self.constraints` + """ + if self._validated: + return + for constraint in self.constraints: + _validate_pass_schedule_constraint(constraint, self.passes) + self._validated = True + + def solve_constraints(self): + """ + Finds a valid traversal order based on the given constraints and orders + the passes based on this order. + + If a circular dependency exists between the constraints and steps = 1, + then we will raise an error because if steps != 1 this means that we + will re-run the passes, allowing for circular dependencies. + """ + self.passes = _topological_sort_passes(self.passes, self.constraints) + self._validated = True + + def add_checks(self, check: Callable) -> None: + """ + Adds a function which takes runs various checks on a given graph module. + This function is run before and after each pass if the + `run_checks_after_each_pass` flag is enabled. + """ + sig = inspect.signature(check) + + if len(list(sig.parameters.values())) != 1: + raise TypeError( + "PassManager check function should only take in one variable, a module" + ) + + setattr(self, "check", check) # noqa: B010 + + def check(self, module: nn.Module) -> None: + pass + + def __call__(self, module: nn.Module) -> PassResult: + """ + Runs a list of passes in the order based on `self.passes` on the given + graph module. Each time a pass is run, checks and linting will be run on + the graph module if `run_checks_after_each_pass` is set. + + If the module is a graph module, we will run the list of passes until + the graph stops changing, or until `steps` number of times. + """ + # Order the passes based on the constraints + if not self._validated: + self.solve_constraints() + + # Check graph invariants + self.check(module) + + # Run the set of passes `steps` number of times or until the graph stops + # changing + overall_modified = False + for _ in range(self.steps): + modified = False + + # Run the set of passes on the graph module + for i, fn in enumerate(self.passes): + fn_name = fn.__name__ if inspect.isfunction(fn) else type(fn).__name__ + logger.debug("Running pass '%s'", fn_name) + + try: + res = fn(module) + + if not isinstance(res, PassResult) and not hasattr( + res, "graph_module" + ): + raise TypeError( + f"The result of the pass {fn_name} should be type PassResult." + + "Please wrap it with pass_result_wrapper()" + ) + module = res.graph_module + modified = modified or res.modified + + if isinstance(module, GraphModule): + logger.debug("Graph after pass '%s': %s", fn_name, module.graph) + module.recompile() + + # Check graph invariants + if self.run_checks_after_each_pass: + self.check(module) + + except Exception as e: + prev_pass_names = [ + p.__name__ if inspect.isfunction(p) else type(p).__name__ + for p in self.passes[:i] + ] + msg = f"An error occurred when running the '{fn_name}' pass after the following passes: {prev_pass_names}" + raise Exception(msg) from e # noqa: TRY002 + + # If the graph no longer changes, then we can stop running these passes + overall_modified = overall_modified or modified + if not modified: + break + + return PassResult(module, overall_modified) diff --git a/shared/package-files/0b/0b9e45f1ae3cd10b16d7afa2c0df53213ddc2a71a1e86a1ea04684bf76958788/amd_hsa_kernel_code.h b/shared/package-files/0b/0b9e45f1ae3cd10b16d7afa2c0df53213ddc2a71a1e86a1ea04684bf76958788/amd_hsa_kernel_code.h new file mode 100644 index 0000000000000000000000000000000000000000..901e49c8dd1d9d5624fb95ada6d695cf9b64e17d --- /dev/null +++ b/shared/package-files/0b/0b9e45f1ae3cd10b16d7afa2c0df53213ddc2a71a1e86a1ea04684bf76958788/amd_hsa_kernel_code.h @@ -0,0 +1,269 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef AMD_HSA_KERNEL_CODE_H +#define AMD_HSA_KERNEL_CODE_H + +#include "amd_hsa_common.h" +#include "hsa.h" + +// AMD Kernel Code Version Enumeration Values. +typedef uint32_t amd_kernel_code_version32_t; +enum amd_kernel_code_version_t { + AMD_KERNEL_CODE_VERSION_MAJOR = 1, + AMD_KERNEL_CODE_VERSION_MINOR = 1 +}; + +// AMD Machine Kind Enumeration Values. +typedef uint16_t amd_machine_kind16_t; +enum amd_machine_kind_t { + AMD_MACHINE_KIND_UNDEFINED = 0, + AMD_MACHINE_KIND_AMDGPU = 1 +}; + +// AMD Machine Version. +typedef uint16_t amd_machine_version16_t; + +// AMD Float Round Mode Enumeration Values. +enum amd_float_round_mode_t { + AMD_FLOAT_ROUND_MODE_NEAREST_EVEN = 0, + AMD_FLOAT_ROUND_MODE_PLUS_INFINITY = 1, + AMD_FLOAT_ROUND_MODE_MINUS_INFINITY = 2, + AMD_FLOAT_ROUND_MODE_ZERO = 3 +}; + +// AMD Float Denorm Mode Enumeration Values. +enum amd_float_denorm_mode_t { + AMD_FLOAT_DENORM_MODE_FLUSH_SOURCE_OUTPUT = 0, + AMD_FLOAT_DENORM_MODE_FLUSH_OUTPUT = 1, + AMD_FLOAT_DENORM_MODE_FLUSH_SOURCE = 2, + AMD_FLOAT_DENORM_MODE_NO_FLUSH = 3 +}; + +// AMD Compute Program Resource Register One. +typedef uint32_t amd_compute_pgm_rsrc_one32_t; +enum amd_compute_pgm_rsrc_one_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WORKITEM_VGPR_COUNT, 0, 6), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WAVEFRONT_SGPR_COUNT, 6, 4), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_PRIORITY, 10, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_ROUND_MODE_32, 12, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_ROUND_MODE_16_64, 14, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_DENORM_MODE_32, 16, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_DENORM_MODE_16_64, 18, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_PRIV, 20, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_ENABLE_DX10_CLAMP, 21, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_DEBUG_MODE, 22, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_ENABLE_IEEE_MODE, 23, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_BULKY, 24, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_CDBG_USER, 25, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_RESERVED1, 26, 6) +}; + +// AMD System VGPR Workitem ID Enumeration Values. +enum amd_system_vgpr_workitem_id_t { + AMD_SYSTEM_VGPR_WORKITEM_ID_X = 0, + AMD_SYSTEM_VGPR_WORKITEM_ID_X_Y = 1, + AMD_SYSTEM_VGPR_WORKITEM_ID_X_Y_Z = 2, + AMD_SYSTEM_VGPR_WORKITEM_ID_UNDEFINED = 3 +}; + +// AMD Compute Program Resource Register Two. +typedef uint32_t amd_compute_pgm_rsrc_two32_t; +enum amd_compute_pgm_rsrc_two_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_PRIVATE_SEGMENT_WAVE_BYTE_OFFSET, 0, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_USER_SGPR_COUNT, 1, 5), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_TRAP_HANDLER, 6, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_X, 7, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_Y, 8, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_Z, 9, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_INFO, 10, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_VGPR_WORKITEM_ID, 11, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_ADDRESS_WATCH, 13, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_MEMORY_VIOLATION, 14, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_GRANULATED_LDS_SIZE, 15, 9), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION, 24, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE, 25, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO, 26, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW, 27, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW, 28, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT, 29, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_INT_DIVISION_BY_ZERO, 30, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_RESERVED1, 31, 1) +}; + +// AMD Element Byte Size Enumeration Values. +enum amd_element_byte_size_t { + AMD_ELEMENT_BYTE_SIZE_2 = 0, + AMD_ELEMENT_BYTE_SIZE_4 = 1, + AMD_ELEMENT_BYTE_SIZE_8 = 2, + AMD_ELEMENT_BYTE_SIZE_16 = 3 +}; + +// AMD Kernel Code Properties. +typedef uint32_t amd_kernel_code_properties32_t; +enum amd_kernel_code_properties_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER, 0, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_DISPATCH_PTR, 1, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_QUEUE_PTR, 2, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_KERNARG_SEGMENT_PTR, 3, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_DISPATCH_ID, 4, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_FLAT_SCRATCH_INIT, 5, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE, 6, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X, 7, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y, 8, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z, 9, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_RESERVED1, 10, 6), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_ORDERED_APPEND_GDS, 16, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_PRIVATE_ELEMENT_SIZE, 17, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_PTR64, 19, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_DYNAMIC_CALLSTACK, 20, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_DEBUG_ENABLED, 21, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_XNACK_ENABLED, 22, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_RESERVED2, 23, 9) +}; + +// AMD Power Of Two Enumeration Values. +typedef uint8_t amd_powertwo8_t; +enum amd_powertwo_t { + AMD_POWERTWO_1 = 0, + AMD_POWERTWO_2 = 1, + AMD_POWERTWO_4 = 2, + AMD_POWERTWO_8 = 3, + AMD_POWERTWO_16 = 4, + AMD_POWERTWO_32 = 5, + AMD_POWERTWO_64 = 6, + AMD_POWERTWO_128 = 7, + AMD_POWERTWO_256 = 8 +}; + +// AMD Enabled Control Directive Enumeration Values. +typedef uint64_t amd_enabled_control_directive64_t; +enum amd_enabled_control_directive_t { + AMD_ENABLED_CONTROL_DIRECTIVE_ENABLE_BREAK_EXCEPTIONS = 1, + AMD_ENABLED_CONTROL_DIRECTIVE_ENABLE_DETECT_EXCEPTIONS = 2, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_DYNAMIC_GROUP_SIZE = 4, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_FLAT_GRID_SIZE = 8, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_FLAT_WORKGROUP_SIZE = 16, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_DIM = 32, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_GRID_SIZE = 64, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_WORKGROUP_SIZE = 128, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRE_NO_PARTIAL_WORKGROUPS = 256 +}; + +// AMD Exception Kind Enumeration Values. +typedef uint16_t amd_exception_kind16_t; +enum amd_exception_kind_t { + AMD_EXCEPTION_KIND_INVALID_OPERATION = 1, + AMD_EXCEPTION_KIND_DIVISION_BY_ZERO = 2, + AMD_EXCEPTION_KIND_OVERFLOW = 4, + AMD_EXCEPTION_KIND_UNDERFLOW = 8, + AMD_EXCEPTION_KIND_INEXACT = 16 +}; + +// AMD Control Directives. +#define AMD_CONTROL_DIRECTIVES_ALIGN_BYTES 64 +#define AMD_CONTROL_DIRECTIVES_ALIGN __ALIGNED__(AMD_CONTROL_DIRECTIVES_ALIGN_BYTES) +typedef AMD_CONTROL_DIRECTIVES_ALIGN struct amd_control_directives_s { + amd_enabled_control_directive64_t enabled_control_directives; + uint16_t enable_break_exceptions; + uint16_t enable_detect_exceptions; + uint32_t max_dynamic_group_size; + uint64_t max_flat_grid_size; + uint32_t max_flat_workgroup_size; + uint8_t required_dim; + uint8_t reserved1[3]; + uint64_t required_grid_size[3]; + uint32_t required_workgroup_size[3]; + uint8_t reserved2[60]; +} amd_control_directives_t; + +// AMD Kernel Code. +#define AMD_ISA_ALIGN_BYTES 256 +#define AMD_KERNEL_CODE_ALIGN_BYTES 64 +#define AMD_KERNEL_CODE_ALIGN __ALIGNED__(AMD_KERNEL_CODE_ALIGN_BYTES) +typedef AMD_KERNEL_CODE_ALIGN struct amd_kernel_code_s { + amd_kernel_code_version32_t amd_kernel_code_version_major; + amd_kernel_code_version32_t amd_kernel_code_version_minor; + amd_machine_kind16_t amd_machine_kind; + amd_machine_version16_t amd_machine_version_major; + amd_machine_version16_t amd_machine_version_minor; + amd_machine_version16_t amd_machine_version_stepping; + int64_t kernel_code_entry_byte_offset; + int64_t kernel_code_prefetch_byte_offset; + uint64_t kernel_code_prefetch_byte_size; + uint64_t max_scratch_backing_memory_byte_size; + amd_compute_pgm_rsrc_one32_t compute_pgm_rsrc1; + amd_compute_pgm_rsrc_two32_t compute_pgm_rsrc2; + amd_kernel_code_properties32_t kernel_code_properties; + uint32_t workitem_private_segment_byte_size; + uint32_t workgroup_group_segment_byte_size; + uint32_t gds_segment_byte_size; + uint64_t kernarg_segment_byte_size; + uint32_t workgroup_fbarrier_count; + uint16_t wavefront_sgpr_count; + uint16_t workitem_vgpr_count; + uint16_t reserved_vgpr_first; + uint16_t reserved_vgpr_count; + uint16_t reserved_sgpr_first; + uint16_t reserved_sgpr_count; + uint16_t debug_wavefront_private_segment_offset_sgpr; + uint16_t debug_private_segment_buffer_sgpr; + amd_powertwo8_t kernarg_segment_alignment; + amd_powertwo8_t group_segment_alignment; + amd_powertwo8_t private_segment_alignment; + amd_powertwo8_t wavefront_size; + int32_t call_convention; + uint8_t reserved1[12]; + uint64_t runtime_loader_kernel_symbol; + amd_control_directives_t control_directives; +} amd_kernel_code_t; + +// TODO: this struct should be completely gone once debugger designs/implements +// Debugger APIs. +typedef struct amd_runtime_loader_debug_info_s { + const void* elf_raw; + size_t elf_size; + const char *kernel_name; + const void *owning_segment; +} amd_runtime_loader_debug_info_t; + +#endif // AMD_HSA_KERNEL_CODE_H diff --git a/shared/package-files/0b/0ba01d720acd61d9622ae0a68104213d443abca2acc29f968825694bf33f750b/__init__.cpython-311.pyc b/shared/package-files/0b/0ba01d720acd61d9622ae0a68104213d443abca2acc29f968825694bf33f750b/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4867be478044b9659602d1101c06c060fcb025 Binary files /dev/null and b/shared/package-files/0b/0ba01d720acd61d9622ae0a68104213d443abca2acc29f968825694bf33f750b/__init__.cpython-311.pyc differ diff --git a/shared/package-files/0b/0ba0b7126f58523aa0e2052155dbbdecad16b7f811c6e84d1d2d135ba325af14/misc.py b/shared/package-files/0b/0ba0b7126f58523aa0e2052155dbbdecad16b7f811c6e84d1d2d135ba325af14/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..741b983f03272890b22f2545f67b141767507634 --- /dev/null +++ b/shared/package-files/0b/0ba0b7126f58523aa0e2052155dbbdecad16b7f811c6e84d1d2d135ba325af14/misc.py @@ -0,0 +1,564 @@ +"""Miscellaneous stuff that does not really fit anywhere else.""" + +from __future__ import annotations + +import operator +import sys +import os +import re as _re +import struct +from textwrap import fill, dedent + + +class Undecidable(ValueError): + # an error to be raised when a decision cannot be made definitively + # where a definitive answer is needed + pass + + +def filldedent(s, w=70, **kwargs): + """ + Strips leading and trailing empty lines from a copy of ``s``, then dedents, + fills and returns it. + + Empty line stripping serves to deal with docstrings like this one that + start with a newline after the initial triple quote, inserting an empty + line at the beginning of the string. + + Additional keyword arguments will be passed to ``textwrap.fill()``. + + See Also + ======== + strlines, rawlines + + """ + return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs) + + +def strlines(s, c=64, short=False): + """Return a cut-and-pastable string that, when printed, is + equivalent to the input. The lines will be surrounded by + parentheses and no line will be longer than c (default 64) + characters. If the line contains newlines characters, the + `rawlines` result will be returned. If ``short`` is True + (default is False) then if there is one line it will be + returned without bounding parentheses. + + Examples + ======== + + >>> from sympy.utilities.misc import strlines + >>> q = 'this is a long string that should be broken into shorter lines' + >>> print(strlines(q, 40)) + ( + 'this is a long string that should be b' + 'roken into shorter lines' + ) + >>> q == ( + ... 'this is a long string that should be b' + ... 'roken into shorter lines' + ... ) + True + + See Also + ======== + filldedent, rawlines + """ + if not isinstance(s, str): + raise ValueError('expecting string input') + if '\n' in s: + return rawlines(s) + q = '"' if repr(s).startswith('"') else "'" + q = (q,)*2 + if '\\' in s: # use r-string + m = '(\nr%s%%s%s\n)' % q + j = '%s\nr%s' % q + c -= 3 + else: + m = '(\n%s%%s%s\n)' % q + j = '%s\n%s' % q + c -= 2 + out = [] + while s: + out.append(s[:c]) + s=s[c:] + if short and len(out) == 1: + return (m % out[0]).splitlines()[1] # strip bounding (\n...\n) + return m % j.join(out) + + +def rawlines(s): + """Return a cut-and-pastable string that, when printed, is equivalent + to the input. Use this when there is more than one line in the + string. The string returned is formatted so it can be indented + nicely within tests; in some cases it is wrapped in the dedent + function which has to be imported from textwrap. + + Examples + ======== + + Note: because there are characters in the examples below that need + to be escaped because they are themselves within a triple quoted + docstring, expressions below look more complicated than they would + be if they were printed in an interpreter window. + + >>> from sympy.utilities.misc import rawlines + >>> from sympy import TableForm + >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee']))) + >>> print(rawlines(s)) + ( + 'a bee\\n' + '-----\\n' + '1 10 ' + ) + >>> print(rawlines('''this + ... that''')) + dedent('''\\ + this + that''') + + >>> print(rawlines('''this + ... that + ... ''')) + dedent('''\\ + this + that + ''') + + >>> s = \"\"\"this + ... is a triple ''' + ... \"\"\" + >>> print(rawlines(s)) + dedent(\"\"\"\\ + this + is a triple ''' + \"\"\") + + >>> print(rawlines('''this + ... that + ... ''')) + ( + 'this\\n' + 'that\\n' + ' ' + ) + + See Also + ======== + filldedent, strlines + """ + lines = s.split('\n') + if len(lines) == 1: + return repr(lines[0]) + triple = ["'''" in s, '"""' in s] + if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple): + rv = [] + # add on the newlines + trailing = s.endswith('\n') + last = len(lines) - 1 + for i, li in enumerate(lines): + if i != last or trailing: + rv.append(repr(li + '\n')) + else: + rv.append(repr(li)) + return '(\n %s\n)' % '\n '.join(rv) + else: + rv = '\n '.join(lines) + if triple[0]: + return 'dedent("""\\\n %s""")' % rv + else: + return "dedent('''\\\n %s''')" % rv + +ARCH = str(struct.calcsize('P') * 8) + "-bit" + + +# XXX: PyPy does not support hash randomization +HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False) + +_debug_tmp: list[str] = [] +_debug_iter = 0 + +def debug_decorator(func): + """If SYMPY_DEBUG is True, it will print a nice execution tree with + arguments and results of all decorated functions, else do nothing. + """ + from sympy import SYMPY_DEBUG + + if not SYMPY_DEBUG: + return func + + def maketree(f, *args, **kw): + global _debug_tmp, _debug_iter + oldtmp = _debug_tmp + _debug_tmp = [] + _debug_iter += 1 + + def tree(subtrees): + def indent(s, variant=1): + x = s.split("\n") + r = "+-%s\n" % x[0] + for a in x[1:]: + if a == "": + continue + if variant == 1: + r += "| %s\n" % a + else: + r += " %s\n" % a + return r + if len(subtrees) == 0: + return "" + f = [] + for a in subtrees[:-1]: + f.append(indent(a)) + f.append(indent(subtrees[-1], 2)) + return ''.join(f) + + # If there is a bug and the algorithm enters an infinite loop, enable the + # following lines. It will print the names and parameters of all major functions + # that are called, *before* they are called + #from functools import reduce + #print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \ + # map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args)) + + r = f(*args, **kw) + + _debug_iter -= 1 + s = "%s%s = %s\n" % (f.__name__, args, r) + if _debug_tmp != []: + s += tree(_debug_tmp) + _debug_tmp = oldtmp + _debug_tmp.append(s) + if _debug_iter == 0: + print(_debug_tmp[0]) + _debug_tmp = [] + return r + + def decorated(*args, **kwargs): + return maketree(func, *args, **kwargs) + + return decorated + + +def debug(*args): + """ + Print ``*args`` if SYMPY_DEBUG is True, else do nothing. + """ + from sympy import SYMPY_DEBUG + if SYMPY_DEBUG: + print(*args, file=sys.stderr) + + +def debugf(string, args): + """ + Print ``string%args`` if SYMPY_DEBUG is True, else do nothing. This is + intended for debug messages using formatted strings. + """ + from sympy import SYMPY_DEBUG + if SYMPY_DEBUG: + print(string%args, file=sys.stderr) + + +def find_executable(executable, path=None): + """Try to find 'executable' in the directories listed in 'path' (a + string listing directories separated by 'os.pathsep'; defaults to + os.environ['PATH']). Returns the complete filename or None if not + found + """ + from .exceptions import sympy_deprecation_warning + sympy_deprecation_warning( + """ + sympy.utilities.misc.find_executable() is deprecated. Use the standard + library shutil.which() function instead. + """, + deprecated_since_version="1.7", + active_deprecations_target="deprecated-find-executable", + ) + if path is None: + path = os.environ['PATH'] + paths = path.split(os.pathsep) + extlist = [''] + if os.name == 'os2': + (base, ext) = os.path.splitext(executable) + # executable files on OS/2 can have an arbitrary extension, but + # .exe is automatically appended if no dot is present in the name + if not ext: + executable = executable + ".exe" + elif sys.platform == 'win32': + pathext = os.environ['PATHEXT'].lower().split(os.pathsep) + (base, ext) = os.path.splitext(executable) + if ext.lower() not in pathext: + extlist = pathext + for ext in extlist: + execname = executable + ext + if os.path.isfile(execname): + return execname + else: + for p in paths: + f = os.path.join(p, execname) + if os.path.isfile(f): + return f + + return None + + +def func_name(x, short=False): + """Return function name of `x` (if defined) else the `type(x)`. + If short is True and there is a shorter alias for the result, + return the alias. + + Examples + ======== + + >>> from sympy.utilities.misc import func_name + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> func_name(Matrix.eye(3)) + 'MutableDenseMatrix' + >>> func_name(x < 1) + 'StrictLessThan' + >>> func_name(x < 1, short=True) + 'Lt' + """ + alias = { + 'GreaterThan': 'Ge', + 'StrictGreaterThan': 'Gt', + 'LessThan': 'Le', + 'StrictLessThan': 'Lt', + 'Equality': 'Eq', + 'Unequality': 'Ne', + } + typ = type(x) + if str(typ).startswith(">> from sympy.utilities.misc import _replace + >>> f = _replace(dict(foo='bar', d='t')) + >>> f('food') + 'bart' + >>> f = _replace({}) + >>> f('food') + 'food' + """ + if not reps: + return lambda x: x + D = lambda match: reps[match.group(0)] + pattern = _re.compile("|".join( + [_re.escape(k) for k, v in reps.items()]), _re.MULTILINE) + return lambda string: pattern.sub(D, string) + + +def replace(string, *reps): + """Return ``string`` with all keys in ``reps`` replaced with + their corresponding values, longer strings first, irrespective + of the order they are given. ``reps`` may be passed as tuples + or a single mapping. + + Examples + ======== + + >>> from sympy.utilities.misc import replace + >>> replace('foo', {'oo': 'ar', 'f': 'b'}) + 'bar' + >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5")) + 'eggsham md5' + + There is no guarantee that a unique answer will be + obtained if keys in a mapping overlap (i.e. are the same + length and have some identical sequence at the + beginning/end): + + >>> reps = [ + ... ('ab', 'x'), + ... ('bc', 'y')] + >>> replace('abc', *reps) in ('xc', 'ay') + True + + References + ========== + + .. [1] https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string + """ + if len(reps) == 1: + kv = reps[0] + if isinstance(kv, dict): + reps = kv + else: + return string.replace(*kv) + else: + reps = dict(reps) + return _replace(reps)(string) + + +def translate(s, a, b=None, c=None): + """Return ``s`` where characters have been replaced or deleted. + + SYNTAX + ====== + + translate(s, None, deletechars): + all characters in ``deletechars`` are deleted + translate(s, map [,deletechars]): + all characters in ``deletechars`` (if provided) are deleted + then the replacements defined by map are made; if the keys + of map are strings then the longer ones are handled first. + Multicharacter deletions should have a value of ''. + translate(s, oldchars, newchars, deletechars) + all characters in ``deletechars`` are deleted + then each character in ``oldchars`` is replaced with the + corresponding character in ``newchars`` + + Examples + ======== + + >>> from sympy.utilities.misc import translate + >>> abc = 'abc' + >>> translate(abc, None, 'a') + 'bc' + >>> translate(abc, {'a': 'x'}, 'c') + 'xb' + >>> translate(abc, {'abc': 'x', 'a': 'y'}) + 'x' + + >>> translate('abcd', 'ac', 'AC', 'd') + 'AbC' + + There is no guarantee that a unique answer will be + obtained if keys in a mapping overlap are the same + length and have some identical sequences at the + beginning/end: + + >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay') + True + """ + + mr = {} + if a is None: + if c is not None: + raise ValueError('c should be None when a=None is passed, instead got %s' % c) + if b is None: + return s + c = b + a = b = '' + else: + if isinstance(a, dict): + short = {} + for k in list(a.keys()): + if len(k) == 1 and len(a[k]) == 1: + short[k] = a.pop(k) + mr = a + c = b + if short: + a, b = [''.join(i) for i in list(zip(*short.items()))] + else: + a = b = '' + elif len(a) != len(b): + raise ValueError('oldchars and newchars have different lengths') + + if c: + val = str.maketrans('', '', c) + s = s.translate(val) + s = replace(s, mr) + n = str.maketrans(a, b) + return s.translate(n) + + +def ordinal(num): + """Return ordinal number string of num, e.g. 1 becomes 1st. + """ + # modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers + n = as_int(num) + k = abs(n) % 100 + if 11 <= k <= 13: + suffix = 'th' + elif k % 10 == 1: + suffix = 'st' + elif k % 10 == 2: + suffix = 'nd' + elif k % 10 == 3: + suffix = 'rd' + else: + suffix = 'th' + return str(n) + suffix + + +def as_int(n, strict=True): + """ + Convert the argument to a builtin integer. + + The return value is guaranteed to be equal to the input. ValueError is + raised if the input has a non-integral value. When ``strict`` is True, this + uses `__index__ `_ + and when it is False it uses ``int``. + + + Examples + ======== + + >>> from sympy.utilities.misc import as_int + >>> from sympy import sqrt, S + + The function is primarily concerned with sanitizing input for + functions that need to work with builtin integers, so anything that + is unambiguously an integer should be returned as an int: + + >>> as_int(S(3)) + 3 + + Floats, being of limited precision, are not assumed to be exact and + will raise an error unless the ``strict`` flag is False. This + precision issue becomes apparent for large floating point numbers: + + >>> big = 1e23 + >>> type(big) is float + True + >>> big == int(big) + True + >>> as_int(big) + Traceback (most recent call last): + ... + ValueError: ... is not an integer + >>> as_int(big, strict=False) + 99999999999999991611392 + + Input that might be a complex representation of an integer value is + also rejected by default: + + >>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2) + >>> int(one) == 1 + True + >>> as_int(one) + Traceback (most recent call last): + ... + ValueError: ... is not an integer + """ + if strict: + try: + if isinstance(n, bool): + raise TypeError + return operator.index(n) + except TypeError: + raise ValueError('%s is not an integer' % (n,)) + else: + try: + result = int(n) + except TypeError: + raise ValueError('%s is not an integer' % (n,)) + if n - result: + raise ValueError('%s is not an integer' % (n,)) + return result diff --git a/shared/package-files/0b/0ba5405fc2a49ac5bed13e3274832ac3b2e8aee15ae58cb5e2172bbe64d1f0d0/series.py b/shared/package-files/0b/0ba5405fc2a49ac5bed13e3274832ac3b2e8aee15ae58cb5e2172bbe64d1f0d0/series.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd019656d207b12e01c9f5bc7260c8ff84bbdf5 --- /dev/null +++ b/shared/package-files/0b/0ba5405fc2a49ac5bed13e3274832ac3b2e8aee15ae58cb5e2172bbe64d1f0d0/series.py @@ -0,0 +1,6631 @@ +""" +Data structure for 1-dimensional cross-sectional and time series data +""" +from __future__ import annotations + +from collections.abc import ( + Hashable, + Iterable, + Mapping, + Sequence, +) +import operator +import sys +from textwrap import dedent +from typing import ( + IO, + TYPE_CHECKING, + Any, + Callable, + Literal, + cast, + overload, +) +import warnings +import weakref + +import numpy as np + +from pandas._config import ( + using_copy_on_write, + warn_copy_on_write, +) +from pandas._config.config import _get_option + +from pandas._libs import ( + lib, + properties, + reshape, +) +from pandas._libs.lib import is_range_indexer +from pandas.compat import PYPY +from pandas.compat._constants import REF_COUNT +from pandas.compat._optional import import_optional_dependency +from pandas.compat.numpy import function as nv +from pandas.errors import ( + ChainedAssignmentError, + InvalidIndexError, + _chained_assignment_method_msg, + _chained_assignment_msg, + _chained_assignment_warning_method_msg, + _chained_assignment_warning_msg, + _check_cacher, +) +from pandas.util._decorators import ( + Appender, + Substitution, + deprecate_nonkeyword_arguments, + doc, +) +from pandas.util._exceptions import find_stack_level +from pandas.util._validators import ( + validate_ascending, + validate_bool_kwarg, + validate_percentile, +) + +from pandas.core.dtypes.astype import astype_is_view +from pandas.core.dtypes.cast import ( + LossySetitemError, + construct_1d_arraylike_from_scalar, + find_common_type, + infer_dtype_from, + maybe_box_native, + maybe_cast_pointwise_result, +) +from pandas.core.dtypes.common import ( + is_dict_like, + is_integer, + is_iterator, + is_list_like, + is_object_dtype, + is_scalar, + pandas_dtype, + validate_all_hashable, +) +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + ExtensionDtype, + SparseDtype, +) +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCSeries, +) +from pandas.core.dtypes.inference import is_hashable +from pandas.core.dtypes.missing import ( + isna, + na_value_for_dtype, + notna, + remove_na_arraylike, +) + +from pandas.core import ( + algorithms, + base, + common as com, + missing, + nanops, + ops, + roperator, +) +from pandas.core.accessor import CachedAccessor +from pandas.core.apply import SeriesApply +from pandas.core.arrays import ExtensionArray +from pandas.core.arrays.arrow import ( + ListAccessor, + StructAccessor, +) +from pandas.core.arrays.categorical import CategoricalAccessor +from pandas.core.arrays.sparse import SparseAccessor +from pandas.core.arrays.string_ import StringDtype +from pandas.core.construction import ( + array as pd_array, + extract_array, + sanitize_array, +) +from pandas.core.generic import ( + NDFrame, + make_doc, +) +from pandas.core.indexers import ( + disallow_ndim_indexing, + unpack_1tuple, +) +from pandas.core.indexes.accessors import CombinedDatetimelikeProperties +from pandas.core.indexes.api import ( + DatetimeIndex, + Index, + MultiIndex, + PeriodIndex, + default_index, + ensure_index, +) +import pandas.core.indexes.base as ibase +from pandas.core.indexes.multi import maybe_droplevels +from pandas.core.indexing import ( + check_bool_indexer, + check_dict_or_set_indexers, +) +from pandas.core.internals import ( + SingleArrayManager, + SingleBlockManager, +) +from pandas.core.methods import selectn +from pandas.core.shared_docs import _shared_docs +from pandas.core.sorting import ( + ensure_key_mapped, + nargsort, +) +from pandas.core.strings.accessor import StringMethods +from pandas.core.tools.datetimes import to_datetime + +import pandas.io.formats.format as fmt +from pandas.io.formats.info import ( + INFO_DOCSTRING, + SeriesInfo, + series_sub_kwargs, +) +import pandas.plotting + +if TYPE_CHECKING: + from pandas._libs.internals import BlockValuesRefs + from pandas._typing import ( + AggFuncType, + AnyAll, + AnyArrayLike, + ArrayLike, + Axis, + AxisInt, + CorrelationMethod, + DropKeep, + Dtype, + DtypeObj, + FilePath, + Frequency, + IgnoreRaise, + IndexKeyFunc, + IndexLabel, + Level, + MutableMappingT, + NaPosition, + NumpySorter, + NumpyValueArrayLike, + QuantileInterpolation, + ReindexMethod, + Renamer, + Scalar, + Self, + SingleManager, + SortKind, + StorageOptions, + Suffixes, + ValueKeyFunc, + WriteBuffer, + npt, + ) + + from pandas.core.frame import DataFrame + from pandas.core.groupby.generic import SeriesGroupBy + +__all__ = ["Series"] + +_shared_doc_kwargs = { + "axes": "index", + "klass": "Series", + "axes_single_arg": "{0 or 'index'}", + "axis": """axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame.""", + "inplace": """inplace : bool, default False + If True, performs operation inplace and returns None.""", + "unique": "np.ndarray", + "duplicated": "Series", + "optional_by": "", + "optional_reindex": """ +index : array-like, optional + New labels for the index. Preferably an Index object to avoid + duplicating data. +axis : int or str, optional + Unused.""", +} + + +def _coerce_method(converter): + """ + Install the scalar coercion methods. + """ + + def wrapper(self): + if len(self) == 1: + warnings.warn( + f"Calling {converter.__name__} on a single element Series is " + "deprecated and will raise a TypeError in the future. " + f"Use {converter.__name__}(ser.iloc[0]) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + return converter(self.iloc[0]) + raise TypeError(f"cannot convert the series to {converter}") + + wrapper.__name__ = f"__{converter.__name__}__" + return wrapper + + +# ---------------------------------------------------------------------- +# Series class + + +# error: Cannot override final attribute "ndim" (previously declared in base +# class "NDFrame") +# error: Cannot override final attribute "size" (previously declared in base +# class "NDFrame") +# definition in base class "NDFrame" +class Series(base.IndexOpsMixin, NDFrame): # type: ignore[misc] + """ + One-dimensional ndarray with axis labels (including time series). + + Labels need not be unique but must be a hashable type. The object + supports both integer- and label-based indexing and provides a host of + methods for performing operations involving the index. Statistical + methods from ndarray have been overridden to automatically exclude + missing data (currently represented as NaN). + + Operations between Series (+, -, /, \\*, \\*\\*) align values based on their + associated index values-- they need not be the same length. The result + index will be the sorted union of the two indexes. + + Parameters + ---------- + data : array-like, Iterable, dict, or scalar value + Contains data stored in Series. If data is a dict, argument order is + maintained. + index : array-like or Index (1d) + Values must be hashable and have the same length as `data`. + Non-unique index values are allowed. Will default to + RangeIndex (0, 1, 2, ..., n) if not provided. If data is dict-like + and index is None, then the keys in the data are used as the index. If the + index is not None, the resulting Series is reindexed with the index values. + dtype : str, numpy.dtype, or ExtensionDtype, optional + Data type for the output Series. If not specified, this will be + inferred from `data`. + See the :ref:`user guide ` for more usages. + name : Hashable, default None + The name to give to the Series. + copy : bool, default False + Copy input data. Only affects Series or 1d ndarray input. See examples. + + Notes + ----- + Please reference the :ref:`User Guide ` for more information. + + Examples + -------- + Constructing Series from a dictionary with an Index specified + + >>> d = {'a': 1, 'b': 2, 'c': 3} + >>> ser = pd.Series(data=d, index=['a', 'b', 'c']) + >>> ser + a 1 + b 2 + c 3 + dtype: int64 + + The keys of the dictionary match with the Index values, hence the Index + values have no effect. + + >>> d = {'a': 1, 'b': 2, 'c': 3} + >>> ser = pd.Series(data=d, index=['x', 'y', 'z']) + >>> ser + x NaN + y NaN + z NaN + dtype: float64 + + Note that the Index is first build with the keys from the dictionary. + After this the Series is reindexed with the given Index values, hence we + get all NaN as a result. + + Constructing Series from a list with `copy=False`. + + >>> r = [1, 2] + >>> ser = pd.Series(r, copy=False) + >>> ser.iloc[0] = 999 + >>> r + [1, 2] + >>> ser + 0 999 + 1 2 + dtype: int64 + + Due to input data type the Series has a `copy` of + the original data even though `copy=False`, so + the data is unchanged. + + Constructing Series from a 1d ndarray with `copy=False`. + + >>> r = np.array([1, 2]) + >>> ser = pd.Series(r, copy=False) + >>> ser.iloc[0] = 999 + >>> r + array([999, 2]) + >>> ser + 0 999 + 1 2 + dtype: int64 + + Due to input data type the Series has a `view` on + the original data, so + the data is changed as well. + """ + + _typ = "series" + _HANDLED_TYPES = (Index, ExtensionArray, np.ndarray) + + _name: Hashable + _metadata: list[str] = ["_name"] + _internal_names_set = {"index", "name"} | NDFrame._internal_names_set + _accessors = {"dt", "cat", "str", "sparse"} + _hidden_attrs = ( + base.IndexOpsMixin._hidden_attrs | NDFrame._hidden_attrs | frozenset([]) + ) + + # similar to __array_priority__, positions Series after DataFrame + # but before Index and ExtensionArray. Should NOT be overridden by subclasses. + __pandas_priority__ = 3000 + + # Override cache_readonly bc Series is mutable + # error: Incompatible types in assignment (expression has type "property", + # base class "IndexOpsMixin" defined the type as "Callable[[IndexOpsMixin], bool]") + hasnans = property( # type: ignore[assignment] + # error: "Callable[[IndexOpsMixin], bool]" has no attribute "fget" + base.IndexOpsMixin.hasnans.fget, # type: ignore[attr-defined] + doc=base.IndexOpsMixin.hasnans.__doc__, + ) + _mgr: SingleManager + + # ---------------------------------------------------------------------- + # Constructors + + def __init__( + self, + data=None, + index=None, + dtype: Dtype | None = None, + name=None, + copy: bool | None = None, + fastpath: bool | lib.NoDefault = lib.no_default, + ) -> None: + if fastpath is not lib.no_default: + warnings.warn( + "The 'fastpath' keyword in pd.Series is deprecated and will " + "be removed in a future version.", + DeprecationWarning, + stacklevel=find_stack_level(), + ) + else: + fastpath = False + + allow_mgr = False + if ( + isinstance(data, (SingleBlockManager, SingleArrayManager)) + and index is None + and dtype is None + and (copy is False or copy is None) + ): + if not allow_mgr: + # GH#52419 + warnings.warn( + f"Passing a {type(data).__name__} to {type(self).__name__} " + "is deprecated and will raise in a future version. " + "Use public APIs instead.", + DeprecationWarning, + stacklevel=2, + ) + if using_copy_on_write(): + data = data.copy(deep=False) + # GH#33357 called with just the SingleBlockManager + NDFrame.__init__(self, data) + if fastpath: + # e.g. from _box_col_values, skip validation of name + object.__setattr__(self, "_name", name) + else: + self.name = name + return + + is_pandas_object = isinstance(data, (Series, Index, ExtensionArray)) + data_dtype = getattr(data, "dtype", None) + original_dtype = dtype + + if isinstance(data, (ExtensionArray, np.ndarray)): + if copy is not False and using_copy_on_write(): + if dtype is None or astype_is_view(data.dtype, pandas_dtype(dtype)): + data = data.copy() + if copy is None: + copy = False + + # we are called internally, so short-circuit + if fastpath: + # data is a ndarray, index is defined + if not isinstance(data, (SingleBlockManager, SingleArrayManager)): + manager = _get_option("mode.data_manager", silent=True) + if manager == "block": + data = SingleBlockManager.from_array(data, index) + elif manager == "array": + data = SingleArrayManager.from_array(data, index) + allow_mgr = True + elif using_copy_on_write() and not copy: + data = data.copy(deep=False) + + if not allow_mgr: + warnings.warn( + f"Passing a {type(data).__name__} to {type(self).__name__} " + "is deprecated and will raise in a future version. " + "Use public APIs instead.", + DeprecationWarning, + stacklevel=2, + ) + + if copy: + data = data.copy() + # skips validation of the name + object.__setattr__(self, "_name", name) + NDFrame.__init__(self, data) + return + + if isinstance(data, SingleBlockManager) and using_copy_on_write() and not copy: + data = data.copy(deep=False) + + if not allow_mgr: + warnings.warn( + f"Passing a {type(data).__name__} to {type(self).__name__} " + "is deprecated and will raise in a future version. " + "Use public APIs instead.", + DeprecationWarning, + stacklevel=2, + ) + + name = ibase.maybe_extract_name(name, data, type(self)) + + if index is not None: + index = ensure_index(index) + + if dtype is not None: + dtype = self._validate_dtype(dtype) + + if data is None: + index = index if index is not None else default_index(0) + if len(index) or dtype is not None: + data = na_value_for_dtype(pandas_dtype(dtype), compat=False) + else: + data = [] + + if isinstance(data, MultiIndex): + raise NotImplementedError( + "initializing a Series from a MultiIndex is not supported" + ) + + refs = None + if isinstance(data, Index): + if dtype is not None: + data = data.astype(dtype, copy=False) + + if using_copy_on_write(): + refs = data._references + data = data._values + else: + # GH#24096 we need to ensure the index remains immutable + data = data._values.copy() + copy = False + + elif isinstance(data, np.ndarray): + if len(data.dtype): + # GH#13296 we are dealing with a compound dtype, which + # should be treated as 2D + raise ValueError( + "Cannot construct a Series from an ndarray with " + "compound dtype. Use DataFrame instead." + ) + elif isinstance(data, Series): + if index is None: + index = data.index + data = data._mgr.copy(deep=False) + else: + data = data.reindex(index, copy=copy) + copy = False + data = data._mgr + elif isinstance(data, Mapping): + data, index = self._init_dict(data, index, dtype) + dtype = None + copy = False + elif isinstance(data, (SingleBlockManager, SingleArrayManager)): + if index is None: + index = data.index + elif not data.index.equals(index) or copy: + # GH#19275 SingleBlockManager input should only be called + # internally + raise AssertionError( + "Cannot pass both SingleBlockManager " + "`data` argument and a different " + "`index` argument. `copy` must be False." + ) + + if not allow_mgr: + warnings.warn( + f"Passing a {type(data).__name__} to {type(self).__name__} " + "is deprecated and will raise in a future version. " + "Use public APIs instead.", + DeprecationWarning, + stacklevel=2, + ) + allow_mgr = True + + elif isinstance(data, ExtensionArray): + pass + else: + data = com.maybe_iterable_to_list(data) + if is_list_like(data) and not len(data) and dtype is None: + # GH 29405: Pre-2.0, this defaulted to float. + dtype = np.dtype(object) + + if index is None: + if not is_list_like(data): + data = [data] + index = default_index(len(data)) + elif is_list_like(data): + com.require_length_match(data, index) + + # create/copy the manager + if isinstance(data, (SingleBlockManager, SingleArrayManager)): + if dtype is not None: + data = data.astype(dtype=dtype, errors="ignore", copy=copy) + elif copy: + data = data.copy() + else: + data = sanitize_array(data, index, dtype, copy) + + manager = _get_option("mode.data_manager", silent=True) + if manager == "block": + data = SingleBlockManager.from_array(data, index, refs=refs) + elif manager == "array": + data = SingleArrayManager.from_array(data, index) + + NDFrame.__init__(self, data) + self.name = name + self._set_axis(0, index) + + if original_dtype is None and is_pandas_object and data_dtype == np.object_: + if self.dtype != data_dtype: + warnings.warn( + "Dtype inference on a pandas object " + "(Series, Index, ExtensionArray) is deprecated. The Series " + "constructor will keep the original dtype in the future. " + "Call `infer_objects` on the result to get the old behavior.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + def _init_dict( + self, data: Mapping, index: Index | None = None, dtype: DtypeObj | None = None + ): + """ + Derive the "_mgr" and "index" attributes of a new Series from a + dictionary input. + + Parameters + ---------- + data : dict or dict-like + Data used to populate the new Series. + index : Index or None, default None + Index for the new Series: if None, use dict keys. + dtype : np.dtype, ExtensionDtype, or None, default None + The dtype for the new Series: if None, infer from data. + + Returns + ------- + _data : BlockManager for the new Series + index : index for the new Series + """ + keys: Index | tuple + + # Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')] + # raises KeyError), so we iterate the entire dict, and align + if data: + # GH:34717, issue was using zip to extract key and values from data. + # using generators in effects the performance. + # Below is the new way of extracting the keys and values + + keys = tuple(data.keys()) + values = list(data.values()) # Generating list of values- faster way + elif index is not None: + # fastpath for Series(data=None). Just use broadcasting a scalar + # instead of reindexing. + if len(index) or dtype is not None: + values = na_value_for_dtype(pandas_dtype(dtype), compat=False) + else: + values = [] + keys = index + else: + keys, values = default_index(0), [] + + # Input is now list-like, so rely on "standard" construction: + s = Series(values, index=keys, dtype=dtype) + + # Now we just make sure the order is respected, if any + if data and index is not None: + s = s.reindex(index, copy=False) + return s._mgr, s.index + + # ---------------------------------------------------------------------- + + @property + def _constructor(self) -> Callable[..., Series]: + return Series + + def _constructor_from_mgr(self, mgr, axes): + ser = Series._from_mgr(mgr, axes=axes) + ser._name = None # caller is responsible for setting real name + + if type(self) is Series: + # This would also work `if self._constructor is Series`, but + # this check is slightly faster, benefiting the most-common case. + return ser + + # We assume that the subclass __init__ knows how to handle a + # pd.Series object. + return self._constructor(ser) + + @property + def _constructor_expanddim(self) -> Callable[..., DataFrame]: + """ + Used when a manipulation result has one higher dimension as the + original, such as Series.to_frame() + """ + from pandas.core.frame import DataFrame + + return DataFrame + + def _constructor_expanddim_from_mgr(self, mgr, axes): + from pandas.core.frame import DataFrame + + df = DataFrame._from_mgr(mgr, axes=mgr.axes) + + if type(self) is Series: + # This would also work `if self._constructor_expanddim is DataFrame`, + # but this check is slightly faster, benefiting the most-common case. + return df + + # We assume that the subclass __init__ knows how to handle a + # pd.DataFrame object. + return self._constructor_expanddim(df) + + # types + @property + def _can_hold_na(self) -> bool: + return self._mgr._can_hold_na + + # ndarray compatibility + @property + def dtype(self) -> DtypeObj: + """ + Return the dtype object of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.dtype + dtype('int64') + """ + return self._mgr.dtype + + @property + def dtypes(self) -> DtypeObj: + """ + Return the dtype object of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.dtypes + dtype('int64') + """ + # DataFrame compatibility + return self.dtype + + @property + def name(self) -> Hashable: + """ + Return the name of the Series. + + The name of a Series becomes its index or column name if it is used + to form a DataFrame. It is also used whenever displaying the Series + using the interpreter. + + Returns + ------- + label (hashable object) + The name of the Series, also the column name if part of a DataFrame. + + See Also + -------- + Series.rename : Sets the Series name when given a scalar input. + Index.name : Corresponding Index property. + + Examples + -------- + The Series name can be set initially when calling the constructor. + + >>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers') + >>> s + 0 1 + 1 2 + 2 3 + Name: Numbers, dtype: int64 + >>> s.name = "Integers" + >>> s + 0 1 + 1 2 + 2 3 + Name: Integers, dtype: int64 + + The name of a Series within a DataFrame is its column name. + + >>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], + ... columns=["Odd Numbers", "Even Numbers"]) + >>> df + Odd Numbers Even Numbers + 0 1 2 + 1 3 4 + 2 5 6 + >>> df["Even Numbers"].name + 'Even Numbers' + """ + return self._name + + @name.setter + def name(self, value: Hashable) -> None: + validate_all_hashable(value, error_name=f"{type(self).__name__}.name") + object.__setattr__(self, "_name", value) + + @property + def values(self): + """ + Return Series as ndarray or ndarray-like depending on the dtype. + + .. warning:: + + We recommend using :attr:`Series.array` or + :meth:`Series.to_numpy`, depending on whether you need + a reference to the underlying data or a NumPy array. + + Returns + ------- + numpy.ndarray or ndarray-like + + See Also + -------- + Series.array : Reference to the underlying data. + Series.to_numpy : A NumPy array representing the underlying data. + + Examples + -------- + >>> pd.Series([1, 2, 3]).values + array([1, 2, 3]) + + >>> pd.Series(list('aabc')).values + array(['a', 'a', 'b', 'c'], dtype=object) + + >>> pd.Series(list('aabc')).astype('category').values + ['a', 'a', 'b', 'c'] + Categories (3, object): ['a', 'b', 'c'] + + Timezone aware datetime data is converted to UTC: + + >>> pd.Series(pd.date_range('20130101', periods=3, + ... tz='US/Eastern')).values + array(['2013-01-01T05:00:00.000000000', + '2013-01-02T05:00:00.000000000', + '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]') + """ + return self._mgr.external_values() + + @property + def _values(self): + """ + Return the internal repr of this data (defined by Block.interval_values). + This are the values as stored in the Block (ndarray or ExtensionArray + depending on the Block class), with datetime64[ns] and timedelta64[ns] + wrapped in ExtensionArrays to match Index._values behavior. + + Differs from the public ``.values`` for certain data types, because of + historical backwards compatibility of the public attribute (e.g. period + returns object ndarray and datetimetz a datetime64[ns] ndarray for + ``.values`` while it returns an ExtensionArray for ``._values`` in those + cases). + + Differs from ``.array`` in that this still returns the numpy array if + the Block is backed by a numpy array (except for datetime64 and + timedelta64 dtypes), while ``.array`` ensures to always return an + ExtensionArray. + + Overview: + + dtype | values | _values | array | + ----------- | ------------- | ------------- | --------------------- | + Numeric | ndarray | ndarray | NumpyExtensionArray | + Category | Categorical | Categorical | Categorical | + dt64[ns] | ndarray[M8ns] | DatetimeArray | DatetimeArray | + dt64[ns tz] | ndarray[M8ns] | DatetimeArray | DatetimeArray | + td64[ns] | ndarray[m8ns] | TimedeltaArray| TimedeltaArray | + Period | ndarray[obj] | PeriodArray | PeriodArray | + Nullable | EA | EA | EA | + + """ + return self._mgr.internal_values() + + @property + def _references(self) -> BlockValuesRefs | None: + if isinstance(self._mgr, SingleArrayManager): + return None + return self._mgr._block.refs + + # error: Decorated property not supported + @Appender(base.IndexOpsMixin.array.__doc__) # type: ignore[misc] + @property + def array(self) -> ExtensionArray: + return self._mgr.array_values() + + # ops + def ravel(self, order: str = "C") -> ArrayLike: + """ + Return the flattened underlying data as an ndarray or ExtensionArray. + + .. deprecated:: 2.2.0 + Series.ravel is deprecated. The underlying array is already 1D, so + ravel is not necessary. Use :meth:`to_numpy` for conversion to a numpy + array instead. + + Returns + ------- + numpy.ndarray or ExtensionArray + Flattened data of the Series. + + See Also + -------- + numpy.ndarray.ravel : Return a flattened array. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.ravel() # doctest: +SKIP + array([1, 2, 3]) + """ + warnings.warn( + "Series.ravel is deprecated. The underlying array is already 1D, so " + "ravel is not necessary. Use `to_numpy()` for conversion to a numpy " + "array instead.", + FutureWarning, + stacklevel=2, + ) + arr = self._values.ravel(order=order) + if isinstance(arr, np.ndarray) and using_copy_on_write(): + arr.flags.writeable = False + return arr + + def __len__(self) -> int: + """ + Return the length of the Series. + """ + return len(self._mgr) + + def view(self, dtype: Dtype | None = None) -> Series: + """ + Create a new view of the Series. + + .. deprecated:: 2.2.0 + ``Series.view`` is deprecated and will be removed in a future version. + Use :meth:`Series.astype` as an alternative to change the dtype. + + This function will return a new Series with a view of the same + underlying values in memory, optionally reinterpreted with a new data + type. The new data type must preserve the same size in bytes as to not + cause index misalignment. + + Parameters + ---------- + dtype : data type + Data type object or one of their string representations. + + Returns + ------- + Series + A new Series object as a view of the same data in memory. + + See Also + -------- + numpy.ndarray.view : Equivalent numpy function to create a new view of + the same data in memory. + + Notes + ----- + Series are instantiated with ``dtype=float64`` by default. While + ``numpy.ndarray.view()`` will return a view with the same data type as + the original array, ``Series.view()`` (without specified dtype) + will try using ``float64`` and may fail if the original data type size + in bytes is not the same. + + Examples + -------- + Use ``astype`` to change the dtype instead. + """ + warnings.warn( + "Series.view is deprecated and will be removed in a future version. " + "Use ``astype`` as an alternative to change the dtype.", + FutureWarning, + stacklevel=2, + ) + # self.array instead of self._values so we piggyback on NumpyExtensionArray + # implementation + res_values = self.array.view(dtype) + res_ser = self._constructor(res_values, index=self.index, copy=False) + if isinstance(res_ser._mgr, SingleBlockManager): + blk = res_ser._mgr._block + blk.refs = cast("BlockValuesRefs", self._references) + blk.refs.add_reference(blk) + return res_ser.__finalize__(self, method="view") + + # ---------------------------------------------------------------------- + # NDArray Compat + def __array__( + self, dtype: npt.DTypeLike | None = None, copy: bool | None = None + ) -> np.ndarray: + """ + Return the values as a NumPy array. + + Users should not call this directly. Rather, it is invoked by + :func:`numpy.array` and :func:`numpy.asarray`. + + Parameters + ---------- + dtype : str or numpy.dtype, optional + The dtype to use for the resulting NumPy array. By default, + the dtype is inferred from the data. + + copy : bool or None, optional + Unused. + + Returns + ------- + numpy.ndarray + The values in the series converted to a :class:`numpy.ndarray` + with the specified `dtype`. + + See Also + -------- + array : Create a new array from data. + Series.array : Zero-copy view to the array backing the Series. + Series.to_numpy : Series method for similar behavior. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + >>> np.asarray(ser) + array([1, 2, 3]) + + For timezone-aware data, the timezones may be retained with + ``dtype='object'`` + + >>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) + >>> np.asarray(tzser, dtype="object") + array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'), + Timestamp('2000-01-02 00:00:00+0100', tz='CET')], + dtype=object) + + Or the values may be localized to UTC and the tzinfo discarded with + ``dtype='datetime64[ns]'`` + + >>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS + array(['1999-12-31T23:00:00.000000000', ...], + dtype='datetime64[ns]') + """ + values = self._values + arr = np.asarray(values, dtype=dtype) + if using_copy_on_write() and astype_is_view(values.dtype, arr.dtype): + arr = arr.view() + arr.flags.writeable = False + return arr + + # ---------------------------------------------------------------------- + + def __column_consortium_standard__(self, *, api_version: str | None = None) -> Any: + """ + Provide entry point to the Consortium DataFrame Standard API. + + This is developed and maintained outside of pandas. + Please report any issues to https://github.com/data-apis/dataframe-api-compat. + """ + dataframe_api_compat = import_optional_dependency("dataframe_api_compat") + return ( + dataframe_api_compat.pandas_standard.convert_to_standard_compliant_column( + self, api_version=api_version + ) + ) + + # ---------------------------------------------------------------------- + # Unary Methods + + # coercion + __float__ = _coerce_method(float) + __int__ = _coerce_method(int) + + # ---------------------------------------------------------------------- + + # indexers + @property + def axes(self) -> list[Index]: + """ + Return a list of the row axis labels. + """ + return [self.index] + + # ---------------------------------------------------------------------- + # Indexing Methods + + def _ixs(self, i: int, axis: AxisInt = 0) -> Any: + """ + Return the i-th value or values in the Series by location. + + Parameters + ---------- + i : int + + Returns + ------- + scalar + """ + return self._values[i] + + def _slice(self, slobj: slice, axis: AxisInt = 0) -> Series: + # axis kwarg is retained for compat with NDFrame method + # _slice is *always* positional + mgr = self._mgr.get_slice(slobj, axis=axis) + out = self._constructor_from_mgr(mgr, axes=mgr.axes) + out._name = self._name + return out.__finalize__(self) + + def __getitem__(self, key): + check_dict_or_set_indexers(key) + key = com.apply_if_callable(key, self) + + if key is Ellipsis: + if using_copy_on_write() or warn_copy_on_write(): + return self.copy(deep=False) + return self + + key_is_scalar = is_scalar(key) + if isinstance(key, (list, tuple)): + key = unpack_1tuple(key) + + if is_integer(key) and self.index._should_fallback_to_positional: + warnings.warn( + # GH#50617 + "Series.__getitem__ treating keys as positions is deprecated. " + "In a future version, integer keys will always be treated " + "as labels (consistent with DataFrame behavior). To access " + "a value by position, use `ser.iloc[pos]`", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self._values[key] + + elif key_is_scalar: + return self._get_value(key) + + # Convert generator to list before going through hashable part + # (We will iterate through the generator there to check for slices) + if is_iterator(key): + key = list(key) + + if is_hashable(key) and not isinstance(key, slice): + # Otherwise index.get_value will raise InvalidIndexError + try: + # For labels that don't resolve as scalars like tuples and frozensets + result = self._get_value(key) + + return result + + except (KeyError, TypeError, InvalidIndexError): + # InvalidIndexError for e.g. generator + # see test_series_getitem_corner_generator + if isinstance(key, tuple) and isinstance(self.index, MultiIndex): + # We still have the corner case where a tuple is a key + # in the first level of our MultiIndex + return self._get_values_tuple(key) + + if isinstance(key, slice): + # Do slice check before somewhat-costly is_bool_indexer + return self._getitem_slice(key) + + if com.is_bool_indexer(key): + key = check_bool_indexer(self.index, key) + key = np.asarray(key, dtype=bool) + return self._get_rows_with_mask(key) + + return self._get_with(key) + + def _get_with(self, key): + # other: fancy integer or otherwise + if isinstance(key, ABCDataFrame): + raise TypeError( + "Indexing a Series with DataFrame is not " + "supported, use the appropriate DataFrame column" + ) + elif isinstance(key, tuple): + return self._get_values_tuple(key) + + elif not is_list_like(key): + # e.g. scalars that aren't recognized by lib.is_scalar, GH#32684 + return self.loc[key] + + if not isinstance(key, (list, np.ndarray, ExtensionArray, Series, Index)): + key = list(key) + + key_type = lib.infer_dtype(key, skipna=False) + + # Note: The key_type == "boolean" case should be caught by the + # com.is_bool_indexer check in __getitem__ + if key_type == "integer": + # We need to decide whether to treat this as a positional indexer + # (i.e. self.iloc) or label-based (i.e. self.loc) + if not self.index._should_fallback_to_positional: + return self.loc[key] + else: + warnings.warn( + # GH#50617 + "Series.__getitem__ treating keys as positions is deprecated. " + "In a future version, integer keys will always be treated " + "as labels (consistent with DataFrame behavior). To access " + "a value by position, use `ser.iloc[pos]`", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.iloc[key] + + # handle the dup indexing case GH#4246 + return self.loc[key] + + def _get_values_tuple(self, key: tuple): + # mpl hackaround + if com.any_none(*key): + # mpl compat if we look up e.g. ser[:, np.newaxis]; + # see tests.series.timeseries.test_mpl_compat_hack + # the asarray is needed to avoid returning a 2D DatetimeArray + result = np.asarray(self._values[key]) + disallow_ndim_indexing(result) + return result + + if not isinstance(self.index, MultiIndex): + raise KeyError("key of type tuple not found and not a MultiIndex") + + # If key is contained, would have returned by now + indexer, new_index = self.index.get_loc_level(key) + new_ser = self._constructor(self._values[indexer], index=new_index, copy=False) + if isinstance(indexer, slice): + new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] + return new_ser.__finalize__(self) + + def _get_rows_with_mask(self, indexer: npt.NDArray[np.bool_]) -> Series: + new_mgr = self._mgr.get_rows_with_mask(indexer) + return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self) + + def _get_value(self, label, takeable: bool = False): + """ + Quickly retrieve single value at passed index label. + + Parameters + ---------- + label : object + takeable : interpret the index as indexers, default False + + Returns + ------- + scalar value + """ + if takeable: + return self._values[label] + + # Similar to Index.get_value, but we do not fall back to positional + loc = self.index.get_loc(label) + + if is_integer(loc): + return self._values[loc] + + if isinstance(self.index, MultiIndex): + mi = self.index + new_values = self._values[loc] + if len(new_values) == 1 and mi.nlevels == 1: + # If more than one level left, we can not return a scalar + return new_values[0] + + new_index = mi[loc] + new_index = maybe_droplevels(new_index, label) + new_ser = self._constructor( + new_values, index=new_index, name=self.name, copy=False + ) + if isinstance(loc, slice): + new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] + return new_ser.__finalize__(self) + + else: + return self.iloc[loc] + + def __setitem__(self, key, value) -> None: + warn = True + if not PYPY and using_copy_on_write(): + if sys.getrefcount(self) <= 3: + warnings.warn( + _chained_assignment_msg, ChainedAssignmentError, stacklevel=2 + ) + elif not PYPY and not using_copy_on_write(): + ctr = sys.getrefcount(self) + ref_count = 3 + if not warn_copy_on_write() and _check_cacher(self): + # see https://github.com/pandas-dev/pandas/pull/56060#discussion_r1399245221 + ref_count += 1 + if ctr <= ref_count and ( + warn_copy_on_write() + or ( + not warn_copy_on_write() + and self._mgr.blocks[0].refs.has_reference() # type: ignore[union-attr] + ) + ): + warn = False + warnings.warn( + _chained_assignment_warning_msg, FutureWarning, stacklevel=2 + ) + + check_dict_or_set_indexers(key) + key = com.apply_if_callable(key, self) + cacher_needs_updating = self._check_is_chained_assignment_possible() + + if key is Ellipsis: + key = slice(None) + + if isinstance(key, slice): + indexer = self.index._convert_slice_indexer(key, kind="getitem") + return self._set_values(indexer, value, warn=warn) + + try: + self._set_with_engine(key, value, warn=warn) + except KeyError: + # We have a scalar (or for MultiIndex or object-dtype, scalar-like) + # key that is not present in self.index. + if is_integer(key): + if not self.index._should_fallback_to_positional: + # GH#33469 + self.loc[key] = value + else: + # positional setter + # can't use _mgr.setitem_inplace yet bc could have *both* + # KeyError and then ValueError, xref GH#45070 + warnings.warn( + # GH#50617 + "Series.__setitem__ treating keys as positions is deprecated. " + "In a future version, integer keys will always be treated " + "as labels (consistent with DataFrame behavior). To set " + "a value by position, use `ser.iloc[pos] = value`", + FutureWarning, + stacklevel=find_stack_level(), + ) + self._set_values(key, value) + else: + # GH#12862 adding a new key to the Series + self.loc[key] = value + + except (TypeError, ValueError, LossySetitemError): + # The key was OK, but we cannot set the value losslessly + indexer = self.index.get_loc(key) + self._set_values(indexer, value) + + except InvalidIndexError as err: + if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): + # cases with MultiIndex don't get here bc they raise KeyError + # e.g. test_basic_getitem_setitem_corner + raise KeyError( + "key of type tuple not found and not a MultiIndex" + ) from err + + if com.is_bool_indexer(key): + key = check_bool_indexer(self.index, key) + key = np.asarray(key, dtype=bool) + + if ( + is_list_like(value) + and len(value) != len(self) + and not isinstance(value, Series) + and not is_object_dtype(self.dtype) + ): + # Series will be reindexed to have matching length inside + # _where call below + # GH#44265 + indexer = key.nonzero()[0] + self._set_values(indexer, value) + return + + # otherwise with listlike other we interpret series[mask] = other + # as series[mask] = other[mask] + try: + self._where(~key, value, inplace=True, warn=warn) + except InvalidIndexError: + # test_where_dups + self.iloc[key] = value + return + + else: + self._set_with(key, value, warn=warn) + + if cacher_needs_updating: + self._maybe_update_cacher(inplace=True) + + def _set_with_engine(self, key, value, warn: bool = True) -> None: + loc = self.index.get_loc(key) + + # this is equivalent to self._values[key] = value + self._mgr.setitem_inplace(loc, value, warn=warn) + + def _set_with(self, key, value, warn: bool = True) -> None: + # We got here via exception-handling off of InvalidIndexError, so + # key should always be listlike at this point. + assert not isinstance(key, tuple) + + if is_iterator(key): + # Without this, the call to infer_dtype will consume the generator + key = list(key) + + if not self.index._should_fallback_to_positional: + # Regardless of the key type, we're treating it as labels + self._set_labels(key, value, warn=warn) + + else: + # Note: key_type == "boolean" should not occur because that + # should be caught by the is_bool_indexer check in __setitem__ + key_type = lib.infer_dtype(key, skipna=False) + + if key_type == "integer": + warnings.warn( + # GH#50617 + "Series.__setitem__ treating keys as positions is deprecated. " + "In a future version, integer keys will always be treated " + "as labels (consistent with DataFrame behavior). To set " + "a value by position, use `ser.iloc[pos] = value`", + FutureWarning, + stacklevel=find_stack_level(), + ) + self._set_values(key, value, warn=warn) + else: + self._set_labels(key, value, warn=warn) + + def _set_labels(self, key, value, warn: bool = True) -> None: + key = com.asarray_tuplesafe(key) + indexer: np.ndarray = self.index.get_indexer(key) + mask = indexer == -1 + if mask.any(): + raise KeyError(f"{key[mask]} not in index") + self._set_values(indexer, value, warn=warn) + + def _set_values(self, key, value, warn: bool = True) -> None: + if isinstance(key, (Index, Series)): + key = key._values + + self._mgr = self._mgr.setitem(indexer=key, value=value, warn=warn) + self._maybe_update_cacher() + + def _set_value(self, label, value, takeable: bool = False) -> None: + """ + Quickly set single value at passed label. + + If label is not contained, a new object is created with the label + placed at the end of the result index. + + Parameters + ---------- + label : object + Partial indexing with MultiIndex not allowed. + value : object + Scalar value. + takeable : interpret the index as indexers, default False + """ + if not takeable: + try: + loc = self.index.get_loc(label) + except KeyError: + # set using a non-recursive method + self.loc[label] = value + return + else: + loc = label + + self._set_values(loc, value) + + # ---------------------------------------------------------------------- + # Lookup Caching + + @property + def _is_cached(self) -> bool: + """Return boolean indicating if self is cached or not.""" + return getattr(self, "_cacher", None) is not None + + def _get_cacher(self): + """return my cacher or None""" + cacher = getattr(self, "_cacher", None) + if cacher is not None: + cacher = cacher[1]() + return cacher + + def _reset_cacher(self) -> None: + """ + Reset the cacher. + """ + if hasattr(self, "_cacher"): + del self._cacher + + def _set_as_cached(self, item, cacher) -> None: + """ + Set the _cacher attribute on the calling object with a weakref to + cacher. + """ + if using_copy_on_write(): + return + self._cacher = (item, weakref.ref(cacher)) + + def _clear_item_cache(self) -> None: + # no-op for Series + pass + + def _check_is_chained_assignment_possible(self) -> bool: + """ + See NDFrame._check_is_chained_assignment_possible.__doc__ + """ + if self._is_view and self._is_cached: + ref = self._get_cacher() + if ref is not None and ref._is_mixed_type: + self._check_setitem_copy(t="referent", force=True) + return True + return super()._check_is_chained_assignment_possible() + + def _maybe_update_cacher( + self, clear: bool = False, verify_is_copy: bool = True, inplace: bool = False + ) -> None: + """ + See NDFrame._maybe_update_cacher.__doc__ + """ + # for CoW, we never want to update the parent DataFrame cache + # if the Series changed, but don't keep track of any cacher + if using_copy_on_write(): + return + cacher = getattr(self, "_cacher", None) + if cacher is not None: + ref: DataFrame = cacher[1]() + + # we are trying to reference a dead referent, hence + # a copy + if ref is None: + del self._cacher + elif len(self) == len(ref) and self.name in ref.columns: + # GH#42530 self.name must be in ref.columns + # to ensure column still in dataframe + # otherwise, either self or ref has swapped in new arrays + ref._maybe_cache_changed(cacher[0], self, inplace=inplace) + else: + # GH#33675 we have swapped in a new array, so parent + # reference to self is now invalid + ref._item_cache.pop(cacher[0], None) + + super()._maybe_update_cacher( + clear=clear, verify_is_copy=verify_is_copy, inplace=inplace + ) + + # ---------------------------------------------------------------------- + # Unsorted + + def repeat(self, repeats: int | Sequence[int], axis: None = None) -> Series: + """ + Repeat elements of a Series. + + Returns a new Series where each element of the current Series + is repeated consecutively a given number of times. + + Parameters + ---------- + repeats : int or array of ints + The number of repetitions for each element. This should be a + non-negative integer. Repeating 0 times will return an empty + Series. + axis : None + Unused. Parameter needed for compatibility with DataFrame. + + Returns + ------- + Series + Newly created Series with repeated elements. + + See Also + -------- + Index.repeat : Equivalent function for Index. + numpy.repeat : Similar method for :class:`numpy.ndarray`. + + Examples + -------- + >>> s = pd.Series(['a', 'b', 'c']) + >>> s + 0 a + 1 b + 2 c + dtype: object + >>> s.repeat(2) + 0 a + 0 a + 1 b + 1 b + 2 c + 2 c + dtype: object + >>> s.repeat([1, 2, 3]) + 0 a + 1 b + 1 b + 2 c + 2 c + 2 c + dtype: object + """ + nv.validate_repeat((), {"axis": axis}) + new_index = self.index.repeat(repeats) + new_values = self._values.repeat(repeats) + return self._constructor(new_values, index=new_index, copy=False).__finalize__( + self, method="repeat" + ) + + @overload + def reset_index( + self, + level: IndexLabel = ..., + *, + drop: Literal[False] = ..., + name: Level = ..., + inplace: Literal[False] = ..., + allow_duplicates: bool = ..., + ) -> DataFrame: + ... + + @overload + def reset_index( + self, + level: IndexLabel = ..., + *, + drop: Literal[True], + name: Level = ..., + inplace: Literal[False] = ..., + allow_duplicates: bool = ..., + ) -> Series: + ... + + @overload + def reset_index( + self, + level: IndexLabel = ..., + *, + drop: bool = ..., + name: Level = ..., + inplace: Literal[True], + allow_duplicates: bool = ..., + ) -> None: + ... + + def reset_index( + self, + level: IndexLabel | None = None, + *, + drop: bool = False, + name: Level = lib.no_default, + inplace: bool = False, + allow_duplicates: bool = False, + ) -> DataFrame | Series | None: + """ + Generate a new DataFrame or Series with the index reset. + + This is useful when the index needs to be treated as a column, or + when the index is meaningless and needs to be reset to the default + before another operation. + + Parameters + ---------- + level : int, str, tuple, or list, default optional + For a Series with a MultiIndex, only remove the specified levels + from the index. Removes all levels by default. + drop : bool, default False + Just reset the index, without inserting it as a column in + the new DataFrame. + name : object, optional + The name to use for the column containing the original Series + values. Uses ``self.name`` by default. This argument is ignored + when `drop` is True. + inplace : bool, default False + Modify the Series in place (do not create a new object). + allow_duplicates : bool, default False + Allow duplicate column labels to be created. + + .. versionadded:: 1.5.0 + + Returns + ------- + Series or DataFrame or None + When `drop` is False (the default), a DataFrame is returned. + The newly created columns will come first in the DataFrame, + followed by the original Series values. + When `drop` is True, a `Series` is returned. + In either case, if ``inplace=True``, no value is returned. + + See Also + -------- + DataFrame.reset_index: Analogous function for DataFrame. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4], name='foo', + ... index=pd.Index(['a', 'b', 'c', 'd'], name='idx')) + + Generate a DataFrame with default index. + + >>> s.reset_index() + idx foo + 0 a 1 + 1 b 2 + 2 c 3 + 3 d 4 + + To specify the name of the new column use `name`. + + >>> s.reset_index(name='values') + idx values + 0 a 1 + 1 b 2 + 2 c 3 + 3 d 4 + + To generate a new Series with the default set `drop` to True. + + >>> s.reset_index(drop=True) + 0 1 + 1 2 + 2 3 + 3 4 + Name: foo, dtype: int64 + + The `level` parameter is interesting for Series with a multi-level + index. + + >>> arrays = [np.array(['bar', 'bar', 'baz', 'baz']), + ... np.array(['one', 'two', 'one', 'two'])] + >>> s2 = pd.Series( + ... range(4), name='foo', + ... index=pd.MultiIndex.from_arrays(arrays, + ... names=['a', 'b'])) + + To remove a specific level from the Index, use `level`. + + >>> s2.reset_index(level='a') + a foo + b + one bar 0 + two bar 1 + one baz 2 + two baz 3 + + If `level` is not set, all levels are removed from the Index. + + >>> s2.reset_index() + a b foo + 0 bar one 0 + 1 bar two 1 + 2 baz one 2 + 3 baz two 3 + """ + inplace = validate_bool_kwarg(inplace, "inplace") + if drop: + new_index = default_index(len(self)) + if level is not None: + level_list: Sequence[Hashable] + if not isinstance(level, (tuple, list)): + level_list = [level] + else: + level_list = level + level_list = [self.index._get_level_number(lev) for lev in level_list] + if len(level_list) < self.index.nlevels: + new_index = self.index.droplevel(level_list) + + if inplace: + self.index = new_index + elif using_copy_on_write(): + new_ser = self.copy(deep=False) + new_ser.index = new_index + return new_ser.__finalize__(self, method="reset_index") + else: + return self._constructor( + self._values.copy(), index=new_index, copy=False, dtype=self.dtype + ).__finalize__(self, method="reset_index") + elif inplace: + raise TypeError( + "Cannot reset_index inplace on a Series to create a DataFrame" + ) + else: + if name is lib.no_default: + # For backwards compatibility, keep columns as [0] instead of + # [None] when self.name is None + if self.name is None: + name = 0 + else: + name = self.name + + df = self.to_frame(name) + return df.reset_index( + level=level, drop=drop, allow_duplicates=allow_duplicates + ) + return None + + # ---------------------------------------------------------------------- + # Rendering Methods + + def __repr__(self) -> str: + """ + Return a string representation for a particular Series. + """ + # pylint: disable=invalid-repr-returned + repr_params = fmt.get_series_repr_params() + return self.to_string(**repr_params) + + @overload + def to_string( + self, + buf: None = ..., + na_rep: str = ..., + float_format: str | None = ..., + header: bool = ..., + index: bool = ..., + length: bool = ..., + dtype=..., + name=..., + max_rows: int | None = ..., + min_rows: int | None = ..., + ) -> str: + ... + + @overload + def to_string( + self, + buf: FilePath | WriteBuffer[str], + na_rep: str = ..., + float_format: str | None = ..., + header: bool = ..., + index: bool = ..., + length: bool = ..., + dtype=..., + name=..., + max_rows: int | None = ..., + min_rows: int | None = ..., + ) -> None: + ... + + def to_string( + self, + buf: FilePath | WriteBuffer[str] | None = None, + na_rep: str = "NaN", + float_format: str | None = None, + header: bool = True, + index: bool = True, + length: bool = False, + dtype: bool = False, + name: bool = False, + max_rows: int | None = None, + min_rows: int | None = None, + ) -> str | None: + """ + Render a string representation of the Series. + + Parameters + ---------- + buf : StringIO-like, optional + Buffer to write to. + na_rep : str, optional + String representation of NaN to use, default 'NaN'. + float_format : one-parameter function, optional + Formatter function to apply to columns' elements if they are + floats, default None. + header : bool, default True + Add the Series header (index name). + index : bool, optional + Add index (row) labels, default True. + length : bool, default False + Add the Series length. + dtype : bool, default False + Add the Series dtype. + name : bool, default False + Add the Series name if not None. + max_rows : int, optional + Maximum number of rows to show before truncating. If None, show + all. + min_rows : int, optional + The number of rows to display in a truncated repr (when number + of rows is above `max_rows`). + + Returns + ------- + str or None + String representation of Series if ``buf=None``, otherwise None. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]).to_string() + >>> ser + '0 1\\n1 2\\n2 3' + """ + formatter = fmt.SeriesFormatter( + self, + name=name, + length=length, + header=header, + index=index, + dtype=dtype, + na_rep=na_rep, + float_format=float_format, + min_rows=min_rows, + max_rows=max_rows, + ) + result = formatter.to_string() + + # catch contract violations + if not isinstance(result, str): + raise AssertionError( + "result must be of type str, type " + f"of result is {repr(type(result).__name__)}" + ) + + if buf is None: + return result + else: + if hasattr(buf, "write"): + buf.write(result) + else: + with open(buf, "w", encoding="utf-8") as f: + f.write(result) + return None + + @doc( + klass=_shared_doc_kwargs["klass"], + storage_options=_shared_docs["storage_options"], + examples=dedent( + """Examples + -------- + >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal") + >>> print(s.to_markdown()) + | | animal | + |---:|:---------| + | 0 | elk | + | 1 | pig | + | 2 | dog | + | 3 | quetzal | + + Output markdown with a tabulate option. + + >>> print(s.to_markdown(tablefmt="grid")) + +----+----------+ + | | animal | + +====+==========+ + | 0 | elk | + +----+----------+ + | 1 | pig | + +----+----------+ + | 2 | dog | + +----+----------+ + | 3 | quetzal | + +----+----------+""" + ), + ) + def to_markdown( + self, + buf: IO[str] | None = None, + mode: str = "wt", + index: bool = True, + storage_options: StorageOptions | None = None, + **kwargs, + ) -> str | None: + """ + Print {klass} in Markdown-friendly format. + + Parameters + ---------- + buf : str, Path or StringIO-like, optional, default None + Buffer to write to. If None, the output is returned as a string. + mode : str, optional + Mode in which file is opened, "wt" by default. + index : bool, optional, default True + Add index (row) labels. + + {storage_options} + + **kwargs + These parameters will be passed to `tabulate \ + `_. + + Returns + ------- + str + {klass} in Markdown-friendly format. + + Notes + ----- + Requires the `tabulate `_ package. + + {examples} + """ + return self.to_frame().to_markdown( + buf, mode=mode, index=index, storage_options=storage_options, **kwargs + ) + + # ---------------------------------------------------------------------- + + def items(self) -> Iterable[tuple[Hashable, Any]]: + """ + Lazily iterate over (index, value) tuples. + + This method returns an iterable tuple (index, value). This is + convenient if you want to create a lazy iterator. + + Returns + ------- + iterable + Iterable of tuples containing the (index, value) pairs from a + Series. + + See Also + -------- + DataFrame.items : Iterate over (column name, Series) pairs. + DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs. + + Examples + -------- + >>> s = pd.Series(['A', 'B', 'C']) + >>> for index, value in s.items(): + ... print(f"Index : {index}, Value : {value}") + Index : 0, Value : A + Index : 1, Value : B + Index : 2, Value : C + """ + return zip(iter(self.index), iter(self)) + + # ---------------------------------------------------------------------- + # Misc public methods + + def keys(self) -> Index: + """ + Return alias for index. + + Returns + ------- + Index + Index of the Series. + + Examples + -------- + >>> s = pd.Series([1, 2, 3], index=[0, 1, 2]) + >>> s.keys() + Index([0, 1, 2], dtype='int64') + """ + return self.index + + @overload + def to_dict( + self, *, into: type[MutableMappingT] | MutableMappingT + ) -> MutableMappingT: + ... + + @overload + def to_dict(self, *, into: type[dict] = ...) -> dict: + ... + + # error: Incompatible default for argument "into" (default has type "type[ + # dict[Any, Any]]", argument has type "type[MutableMappingT] | MutableMappingT") + @deprecate_nonkeyword_arguments( + version="3.0", allowed_args=["self"], name="to_dict" + ) + def to_dict( + self, + into: type[MutableMappingT] + | MutableMappingT = dict, # type: ignore[assignment] + ) -> MutableMappingT: + """ + Convert Series to {label -> value} dict or dict-like object. + + Parameters + ---------- + into : class, default dict + The collections.abc.MutableMapping subclass to use as the return + object. Can be the actual class or an empty instance of the mapping + type you want. If you want a collections.defaultdict, you must + pass it initialized. + + Returns + ------- + collections.abc.MutableMapping + Key-value representation of Series. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + >>> s.to_dict() + {0: 1, 1: 2, 2: 3, 3: 4} + >>> from collections import OrderedDict, defaultdict + >>> s.to_dict(into=OrderedDict) + OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) + >>> dd = defaultdict(list) + >>> s.to_dict(into=dd) + defaultdict(, {0: 1, 1: 2, 2: 3, 3: 4}) + """ + # GH16122 + into_c = com.standardize_mapping(into) + + if is_object_dtype(self.dtype) or isinstance(self.dtype, ExtensionDtype): + return into_c((k, maybe_box_native(v)) for k, v in self.items()) + else: + # Not an object dtype => all types will be the same so let the default + # indexer return native python type + return into_c(self.items()) + + def to_frame(self, name: Hashable = lib.no_default) -> DataFrame: + """ + Convert Series to DataFrame. + + Parameters + ---------- + name : object, optional + The passed name should substitute for the series name (if it has + one). + + Returns + ------- + DataFrame + DataFrame representation of Series. + + Examples + -------- + >>> s = pd.Series(["a", "b", "c"], + ... name="vals") + >>> s.to_frame() + vals + 0 a + 1 b + 2 c + """ + columns: Index + if name is lib.no_default: + name = self.name + if name is None: + # default to [0], same as we would get with DataFrame(self) + columns = default_index(1) + else: + columns = Index([name]) + else: + columns = Index([name]) + + mgr = self._mgr.to_2d_mgr(columns) + df = self._constructor_expanddim_from_mgr(mgr, axes=mgr.axes) + return df.__finalize__(self, method="to_frame") + + def _set_name( + self, name, inplace: bool = False, deep: bool | None = None + ) -> Series: + """ + Set the Series name. + + Parameters + ---------- + name : str + inplace : bool + Whether to modify `self` directly or return a copy. + deep : bool|None, default None + Whether to do a deep copy, a shallow copy, or Copy on Write(None) + """ + inplace = validate_bool_kwarg(inplace, "inplace") + ser = self if inplace else self.copy(deep and not using_copy_on_write()) + ser.name = name + return ser + + @Appender( + dedent( + """ + Examples + -------- + >>> ser = pd.Series([390., 350., 30., 20.], + ... index=['Falcon', 'Falcon', 'Parrot', 'Parrot'], + ... name="Max Speed") + >>> ser + Falcon 390.0 + Falcon 350.0 + Parrot 30.0 + Parrot 20.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(["a", "b", "a", "b"]).mean() + a 210.0 + b 185.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(level=0).mean() + Falcon 370.0 + Parrot 25.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(ser > 100).mean() + Max Speed + False 25.0 + True 370.0 + Name: Max Speed, dtype: float64 + + **Grouping by Indexes** + + We can groupby different levels of a hierarchical index + using the `level` parameter: + + >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'], + ... ['Captive', 'Wild', 'Captive', 'Wild']] + >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type')) + >>> ser = pd.Series([390., 350., 30., 20.], index=index, name="Max Speed") + >>> ser + Animal Type + Falcon Captive 390.0 + Wild 350.0 + Parrot Captive 30.0 + Wild 20.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(level=0).mean() + Animal + Falcon 370.0 + Parrot 25.0 + Name: Max Speed, dtype: float64 + >>> ser.groupby(level="Type").mean() + Type + Captive 210.0 + Wild 185.0 + Name: Max Speed, dtype: float64 + + We can also choose to include `NA` in group keys or not by defining + `dropna` parameter, the default setting is `True`. + + >>> ser = pd.Series([1, 2, 3, 3], index=["a", 'a', 'b', np.nan]) + >>> ser.groupby(level=0).sum() + a 3 + b 3 + dtype: int64 + + >>> ser.groupby(level=0, dropna=False).sum() + a 3 + b 3 + NaN 3 + dtype: int64 + + >>> arrays = ['Falcon', 'Falcon', 'Parrot', 'Parrot'] + >>> ser = pd.Series([390., 350., 30., 20.], index=arrays, name="Max Speed") + >>> ser.groupby(["a", "b", "a", np.nan]).mean() + a 210.0 + b 350.0 + Name: Max Speed, dtype: float64 + + >>> ser.groupby(["a", "b", "a", np.nan], dropna=False).mean() + a 210.0 + b 350.0 + NaN 20.0 + Name: Max Speed, dtype: float64 + """ + ) + ) + @Appender(_shared_docs["groupby"] % _shared_doc_kwargs) + def groupby( + self, + by=None, + axis: Axis = 0, + level: IndexLabel | None = None, + as_index: bool = True, + sort: bool = True, + group_keys: bool = True, + observed: bool | lib.NoDefault = lib.no_default, + dropna: bool = True, + ) -> SeriesGroupBy: + from pandas.core.groupby.generic import SeriesGroupBy + + if level is None and by is None: + raise TypeError("You have to supply one of 'by' and 'level'") + if not as_index: + raise TypeError("as_index=False only valid with DataFrame") + axis = self._get_axis_number(axis) + + return SeriesGroupBy( + obj=self, + keys=by, + axis=axis, + level=level, + as_index=as_index, + sort=sort, + group_keys=group_keys, + observed=observed, + dropna=dropna, + ) + + # ---------------------------------------------------------------------- + # Statistics, overridden ndarray methods + + # TODO: integrate bottleneck + def count(self) -> int: + """ + Return number of non-NA/null observations in the Series. + + Returns + ------- + int + Number of non-null values in the Series. + + See Also + -------- + DataFrame.count : Count non-NA cells for each column or row. + + Examples + -------- + >>> s = pd.Series([0.0, 1.0, np.nan]) + >>> s.count() + 2 + """ + return notna(self._values).sum().astype("int64") + + def mode(self, dropna: bool = True) -> Series: + """ + Return the mode(s) of the Series. + + The mode is the value that appears most often. There can be multiple modes. + + Always returns Series even if only one value is returned. + + Parameters + ---------- + dropna : bool, default True + Don't consider counts of NaN/NaT. + + Returns + ------- + Series + Modes of the Series in sorted order. + + Examples + -------- + >>> s = pd.Series([2, 4, 2, 2, 4, None]) + >>> s.mode() + 0 2.0 + dtype: float64 + + More than one mode: + + >>> s = pd.Series([2, 4, 8, 2, 4, None]) + >>> s.mode() + 0 2.0 + 1 4.0 + dtype: float64 + + With and without considering null value: + + >>> s = pd.Series([2, 4, None, None, 4, None]) + >>> s.mode(dropna=False) + 0 NaN + dtype: float64 + >>> s = pd.Series([2, 4, None, None, 4, None]) + >>> s.mode() + 0 4.0 + dtype: float64 + """ + # TODO: Add option for bins like value_counts() + values = self._values + if isinstance(values, np.ndarray): + res_values = algorithms.mode(values, dropna=dropna) + else: + res_values = values._mode(dropna=dropna) + + # Ensure index is type stable (should always use int index) + return self._constructor( + res_values, + index=range(len(res_values)), + name=self.name, + copy=False, + dtype=self.dtype, + ).__finalize__(self, method="mode") + + def unique(self) -> ArrayLike: # pylint: disable=useless-parent-delegation + """ + Return unique values of Series object. + + Uniques are returned in order of appearance. Hash table-based unique, + therefore does NOT sort. + + Returns + ------- + ndarray or ExtensionArray + The unique values returned as a NumPy array. See Notes. + + See Also + -------- + Series.drop_duplicates : Return Series with duplicate values removed. + unique : Top-level unique method for any 1-d array-like object. + Index.unique : Return Index with unique values from an Index object. + + Notes + ----- + Returns the unique values as a NumPy array. In case of an + extension-array backed Series, a new + :class:`~api.extensions.ExtensionArray` of that type with just + the unique values is returned. This includes + + * Categorical + * Period + * Datetime with Timezone + * Datetime without Timezone + * Timedelta + * Interval + * Sparse + * IntegerNA + + See Examples section. + + Examples + -------- + >>> pd.Series([2, 1, 3, 3], name='A').unique() + array([2, 1, 3]) + + >>> pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique() + + ['2016-01-01 00:00:00'] + Length: 1, dtype: datetime64[ns] + + >>> pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern') + ... for _ in range(3)]).unique() + + ['2016-01-01 00:00:00-05:00'] + Length: 1, dtype: datetime64[ns, US/Eastern] + + An Categorical will return categories in the order of + appearance and with the same dtype. + + >>> pd.Series(pd.Categorical(list('baabc'))).unique() + ['b', 'a', 'c'] + Categories (3, object): ['a', 'b', 'c'] + >>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'), + ... ordered=True)).unique() + ['b', 'a', 'c'] + Categories (3, object): ['a' < 'b' < 'c'] + """ + return super().unique() + + @overload + def drop_duplicates( + self, + *, + keep: DropKeep = ..., + inplace: Literal[False] = ..., + ignore_index: bool = ..., + ) -> Series: + ... + + @overload + def drop_duplicates( + self, *, keep: DropKeep = ..., inplace: Literal[True], ignore_index: bool = ... + ) -> None: + ... + + @overload + def drop_duplicates( + self, *, keep: DropKeep = ..., inplace: bool = ..., ignore_index: bool = ... + ) -> Series | None: + ... + + def drop_duplicates( + self, + *, + keep: DropKeep = "first", + inplace: bool = False, + ignore_index: bool = False, + ) -> Series | None: + """ + Return Series with duplicate values removed. + + Parameters + ---------- + keep : {'first', 'last', ``False``}, default 'first' + Method to handle dropping duplicates: + + - 'first' : Drop duplicates except for the first occurrence. + - 'last' : Drop duplicates except for the last occurrence. + - ``False`` : Drop all duplicates. + + inplace : bool, default ``False`` + If ``True``, performs operation inplace and returns None. + + ignore_index : bool, default ``False`` + If ``True``, the resulting axis will be labeled 0, 1, …, n - 1. + + .. versionadded:: 2.0.0 + + Returns + ------- + Series or None + Series with duplicates dropped or None if ``inplace=True``. + + See Also + -------- + Index.drop_duplicates : Equivalent method on Index. + DataFrame.drop_duplicates : Equivalent method on DataFrame. + Series.duplicated : Related method on Series, indicating duplicate + Series values. + Series.unique : Return unique values as an array. + + Examples + -------- + Generate a Series with duplicated entries. + + >>> s = pd.Series(['llama', 'cow', 'llama', 'beetle', 'llama', 'hippo'], + ... name='animal') + >>> s + 0 llama + 1 cow + 2 llama + 3 beetle + 4 llama + 5 hippo + Name: animal, dtype: object + + With the 'keep' parameter, the selection behaviour of duplicated values + can be changed. The value 'first' keeps the first occurrence for each + set of duplicated entries. The default value of keep is 'first'. + + >>> s.drop_duplicates() + 0 llama + 1 cow + 3 beetle + 5 hippo + Name: animal, dtype: object + + The value 'last' for parameter 'keep' keeps the last occurrence for + each set of duplicated entries. + + >>> s.drop_duplicates(keep='last') + 1 cow + 3 beetle + 4 llama + 5 hippo + Name: animal, dtype: object + + The value ``False`` for parameter 'keep' discards all sets of + duplicated entries. + + >>> s.drop_duplicates(keep=False) + 1 cow + 3 beetle + 5 hippo + Name: animal, dtype: object + """ + inplace = validate_bool_kwarg(inplace, "inplace") + result = super().drop_duplicates(keep=keep) + + if ignore_index: + result.index = default_index(len(result)) + + if inplace: + self._update_inplace(result) + return None + else: + return result + + def duplicated(self, keep: DropKeep = "first") -> Series: + """ + Indicate duplicate Series values. + + Duplicated values are indicated as ``True`` values in the resulting + Series. Either all duplicates, all except the first or all except the + last occurrence of duplicates can be indicated. + + Parameters + ---------- + keep : {'first', 'last', False}, default 'first' + Method to handle dropping duplicates: + + - 'first' : Mark duplicates as ``True`` except for the first + occurrence. + - 'last' : Mark duplicates as ``True`` except for the last + occurrence. + - ``False`` : Mark all duplicates as ``True``. + + Returns + ------- + Series[bool] + Series indicating whether each value has occurred in the + preceding values. + + See Also + -------- + Index.duplicated : Equivalent method on pandas.Index. + DataFrame.duplicated : Equivalent method on pandas.DataFrame. + Series.drop_duplicates : Remove duplicate values from Series. + + Examples + -------- + By default, for each set of duplicated values, the first occurrence is + set on False and all others on True: + + >>> animals = pd.Series(['llama', 'cow', 'llama', 'beetle', 'llama']) + >>> animals.duplicated() + 0 False + 1 False + 2 True + 3 False + 4 True + dtype: bool + + which is equivalent to + + >>> animals.duplicated(keep='first') + 0 False + 1 False + 2 True + 3 False + 4 True + dtype: bool + + By using 'last', the last occurrence of each set of duplicated values + is set on False and all others on True: + + >>> animals.duplicated(keep='last') + 0 True + 1 False + 2 True + 3 False + 4 False + dtype: bool + + By setting keep on ``False``, all duplicates are True: + + >>> animals.duplicated(keep=False) + 0 True + 1 False + 2 True + 3 False + 4 True + dtype: bool + """ + res = self._duplicated(keep=keep) + result = self._constructor(res, index=self.index, copy=False) + return result.__finalize__(self, method="duplicated") + + def idxmin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Hashable: + """ + Return the row label of the minimum value. + + If multiple values equal the minimum, the first row label with that + value is returned. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + skipna : bool, default True + Exclude NA/null values. If the entire Series is NA, the result + will be NA. + *args, **kwargs + Additional arguments and keywords have no effect but might be + accepted for compatibility with NumPy. + + Returns + ------- + Index + Label of the minimum value. + + Raises + ------ + ValueError + If the Series is empty. + + See Also + -------- + numpy.argmin : Return indices of the minimum values + along the given axis. + DataFrame.idxmin : Return index of first occurrence of minimum + over requested axis. + Series.idxmax : Return index *label* of the first occurrence + of maximum of values. + + Notes + ----- + This method is the Series version of ``ndarray.argmin``. This method + returns the label of the minimum, while ``ndarray.argmin`` returns + the position. To get the position, use ``series.values.argmin()``. + + Examples + -------- + >>> s = pd.Series(data=[1, None, 4, 1], + ... index=['A', 'B', 'C', 'D']) + >>> s + A 1.0 + B NaN + C 4.0 + D 1.0 + dtype: float64 + + >>> s.idxmin() + 'A' + + If `skipna` is False and there is an NA value in the data, + the function returns ``nan``. + + >>> s.idxmin(skipna=False) + nan + """ + axis = self._get_axis_number(axis) + with warnings.catch_warnings(): + # TODO(3.0): this catching/filtering can be removed + # ignore warning produced by argmin since we will issue a different + # warning for idxmin + warnings.simplefilter("ignore") + i = self.argmin(axis, skipna, *args, **kwargs) + + if i == -1: + # GH#43587 give correct NA value for Index. + warnings.warn( + f"The behavior of {type(self).__name__}.idxmin with all-NA " + "values, or any-NA and skipna=False, is deprecated. In a future " + "version this will raise ValueError", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.index._na_value + return self.index[i] + + def idxmax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Hashable: + """ + Return the row label of the maximum value. + + If multiple values equal the maximum, the first row label with that + value is returned. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + skipna : bool, default True + Exclude NA/null values. If the entire Series is NA, the result + will be NA. + *args, **kwargs + Additional arguments and keywords have no effect but might be + accepted for compatibility with NumPy. + + Returns + ------- + Index + Label of the maximum value. + + Raises + ------ + ValueError + If the Series is empty. + + See Also + -------- + numpy.argmax : Return indices of the maximum values + along the given axis. + DataFrame.idxmax : Return index of first occurrence of maximum + over requested axis. + Series.idxmin : Return index *label* of the first occurrence + of minimum of values. + + Notes + ----- + This method is the Series version of ``ndarray.argmax``. This method + returns the label of the maximum, while ``ndarray.argmax`` returns + the position. To get the position, use ``series.values.argmax()``. + + Examples + -------- + >>> s = pd.Series(data=[1, None, 4, 3, 4], + ... index=['A', 'B', 'C', 'D', 'E']) + >>> s + A 1.0 + B NaN + C 4.0 + D 3.0 + E 4.0 + dtype: float64 + + >>> s.idxmax() + 'C' + + If `skipna` is False and there is an NA value in the data, + the function returns ``nan``. + + >>> s.idxmax(skipna=False) + nan + """ + axis = self._get_axis_number(axis) + with warnings.catch_warnings(): + # TODO(3.0): this catching/filtering can be removed + # ignore warning produced by argmax since we will issue a different + # warning for argmax + warnings.simplefilter("ignore") + i = self.argmax(axis, skipna, *args, **kwargs) + + if i == -1: + # GH#43587 give correct NA value for Index. + warnings.warn( + f"The behavior of {type(self).__name__}.idxmax with all-NA " + "values, or any-NA and skipna=False, is deprecated. In a future " + "version this will raise ValueError", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.index._na_value + return self.index[i] + + def round(self, decimals: int = 0, *args, **kwargs) -> Series: + """ + Round each value in a Series to the given number of decimals. + + Parameters + ---------- + decimals : int, default 0 + Number of decimal places to round to. If decimals is negative, + it specifies the number of positions to the left of the decimal point. + *args, **kwargs + Additional arguments and keywords have no effect but might be + accepted for compatibility with NumPy. + + Returns + ------- + Series + Rounded values of the Series. + + See Also + -------- + numpy.around : Round values of an np.array. + DataFrame.round : Round values of a DataFrame. + + Examples + -------- + >>> s = pd.Series([0.1, 1.3, 2.7]) + >>> s.round() + 0 0.0 + 1 1.0 + 2 3.0 + dtype: float64 + """ + nv.validate_round(args, kwargs) + new_mgr = self._mgr.round(decimals=decimals, using_cow=using_copy_on_write()) + return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__( + self, method="round" + ) + + @overload + def quantile( + self, q: float = ..., interpolation: QuantileInterpolation = ... + ) -> float: + ... + + @overload + def quantile( + self, + q: Sequence[float] | AnyArrayLike, + interpolation: QuantileInterpolation = ..., + ) -> Series: + ... + + @overload + def quantile( + self, + q: float | Sequence[float] | AnyArrayLike = ..., + interpolation: QuantileInterpolation = ..., + ) -> float | Series: + ... + + def quantile( + self, + q: float | Sequence[float] | AnyArrayLike = 0.5, + interpolation: QuantileInterpolation = "linear", + ) -> float | Series: + """ + Return value at the given quantile. + + Parameters + ---------- + q : float or array-like, default 0.5 (50% quantile) + The quantile(s) to compute, which can lie in range: 0 <= q <= 1. + interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} + This optional parameter specifies the interpolation method to use, + when the desired quantile lies between two data points `i` and `j`: + + * linear: `i + (j - i) * (x-i)/(j-i)`, where `(x-i)/(j-i)` is + the fractional part of the index surrounded by `i > j`. + * lower: `i`. + * higher: `j`. + * nearest: `i` or `j` whichever is nearest. + * midpoint: (`i` + `j`) / 2. + + Returns + ------- + float or Series + If ``q`` is an array, a Series will be returned where the + index is ``q`` and the values are the quantiles, otherwise + a float will be returned. + + See Also + -------- + core.window.Rolling.quantile : Calculate the rolling quantile. + numpy.percentile : Returns the q-th percentile(s) of the array elements. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + >>> s.quantile(.5) + 2.5 + >>> s.quantile([.25, .5, .75]) + 0.25 1.75 + 0.50 2.50 + 0.75 3.25 + dtype: float64 + """ + validate_percentile(q) + + # We dispatch to DataFrame so that core.internals only has to worry + # about 2D cases. + df = self.to_frame() + + result = df.quantile(q=q, interpolation=interpolation, numeric_only=False) + if result.ndim == 2: + result = result.iloc[:, 0] + + if is_list_like(q): + result.name = self.name + idx = Index(q, dtype=np.float64) + return self._constructor(result, index=idx, name=self.name) + else: + # scalar + return result.iloc[0] + + def corr( + self, + other: Series, + method: CorrelationMethod = "pearson", + min_periods: int | None = None, + ) -> float: + """ + Compute correlation with `other` Series, excluding missing values. + + The two `Series` objects are not required to be the same length and will be + aligned internally before the correlation function is applied. + + Parameters + ---------- + other : Series + Series with which to compute the correlation. + method : {'pearson', 'kendall', 'spearman'} or callable + Method used to compute correlation: + + - pearson : Standard correlation coefficient + - kendall : Kendall Tau correlation coefficient + - spearman : Spearman rank correlation + - callable: Callable with input two 1d ndarrays and returning a float. + + .. warning:: + Note that the returned matrix from corr will have 1 along the + diagonals and will be symmetric regardless of the callable's + behavior. + min_periods : int, optional + Minimum number of observations needed to have a valid result. + + Returns + ------- + float + Correlation with other. + + See Also + -------- + DataFrame.corr : Compute pairwise correlation between columns. + DataFrame.corrwith : Compute pairwise correlation with another + DataFrame or Series. + + Notes + ----- + Pearson, Kendall and Spearman correlation are currently computed using pairwise complete observations. + + * `Pearson correlation coefficient `_ + * `Kendall rank correlation coefficient `_ + * `Spearman's rank correlation coefficient `_ + + Automatic data alignment: as with all pandas operations, automatic data alignment is performed for this method. + ``corr()`` automatically considers values with matching indices. + + Examples + -------- + >>> def histogram_intersection(a, b): + ... v = np.minimum(a, b).sum().round(decimals=1) + ... return v + >>> s1 = pd.Series([.2, .0, .6, .2]) + >>> s2 = pd.Series([.3, .6, .0, .1]) + >>> s1.corr(s2, method=histogram_intersection) + 0.3 + + Pandas auto-aligns the values with matching indices + + >>> s1 = pd.Series([1, 2, 3], index=[0, 1, 2]) + >>> s2 = pd.Series([1, 2, 3], index=[2, 1, 0]) + >>> s1.corr(s2) + -1.0 + """ # noqa: E501 + this, other = self.align(other, join="inner", copy=False) + if len(this) == 0: + return np.nan + + this_values = this.to_numpy(dtype=float, na_value=np.nan, copy=False) + other_values = other.to_numpy(dtype=float, na_value=np.nan, copy=False) + + if method in ["pearson", "spearman", "kendall"] or callable(method): + return nanops.nancorr( + this_values, other_values, method=method, min_periods=min_periods + ) + + raise ValueError( + "method must be either 'pearson', " + "'spearman', 'kendall', or a callable, " + f"'{method}' was supplied" + ) + + def cov( + self, + other: Series, + min_periods: int | None = None, + ddof: int | None = 1, + ) -> float: + """ + Compute covariance with Series, excluding missing values. + + The two `Series` objects are not required to be the same length and + will be aligned internally before the covariance is calculated. + + Parameters + ---------- + other : Series + Series with which to compute the covariance. + min_periods : int, optional + Minimum number of observations needed to have a valid result. + ddof : int, default 1 + Delta degrees of freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of elements. + + Returns + ------- + float + Covariance between Series and other normalized by N-1 + (unbiased estimator). + + See Also + -------- + DataFrame.cov : Compute pairwise covariance of columns. + + Examples + -------- + >>> s1 = pd.Series([0.90010907, 0.13484424, 0.62036035]) + >>> s2 = pd.Series([0.12528585, 0.26962463, 0.51111198]) + >>> s1.cov(s2) + -0.01685762652715874 + """ + this, other = self.align(other, join="inner", copy=False) + if len(this) == 0: + return np.nan + this_values = this.to_numpy(dtype=float, na_value=np.nan, copy=False) + other_values = other.to_numpy(dtype=float, na_value=np.nan, copy=False) + return nanops.nancov( + this_values, other_values, min_periods=min_periods, ddof=ddof + ) + + @doc( + klass="Series", + extra_params="", + other_klass="DataFrame", + examples=dedent( + """ + Difference with previous row + + >>> s = pd.Series([1, 1, 2, 3, 5, 8]) + >>> s.diff() + 0 NaN + 1 0.0 + 2 1.0 + 3 1.0 + 4 2.0 + 5 3.0 + dtype: float64 + + Difference with 3rd previous row + + >>> s.diff(periods=3) + 0 NaN + 1 NaN + 2 NaN + 3 2.0 + 4 4.0 + 5 6.0 + dtype: float64 + + Difference with following row + + >>> s.diff(periods=-1) + 0 0.0 + 1 -1.0 + 2 -1.0 + 3 -2.0 + 4 -3.0 + 5 NaN + dtype: float64 + + Overflow in input dtype + + >>> s = pd.Series([1, 0], dtype=np.uint8) + >>> s.diff() + 0 NaN + 1 255.0 + dtype: float64""" + ), + ) + def diff(self, periods: int = 1) -> Series: + """ + First discrete difference of element. + + Calculates the difference of a {klass} element compared with another + element in the {klass} (default is element in previous row). + + Parameters + ---------- + periods : int, default 1 + Periods to shift for calculating difference, accepts negative + values. + {extra_params} + Returns + ------- + {klass} + First differences of the Series. + + See Also + -------- + {klass}.pct_change: Percent change over given number of periods. + {klass}.shift: Shift index by desired number of periods with an + optional time freq. + {other_klass}.diff: First discrete difference of object. + + Notes + ----- + For boolean dtypes, this uses :meth:`operator.xor` rather than + :meth:`operator.sub`. + The result is calculated according to current dtype in {klass}, + however dtype of the result is always float64. + + Examples + -------- + {examples} + """ + result = algorithms.diff(self._values, periods) + return self._constructor(result, index=self.index, copy=False).__finalize__( + self, method="diff" + ) + + def autocorr(self, lag: int = 1) -> float: + """ + Compute the lag-N autocorrelation. + + This method computes the Pearson correlation between + the Series and its shifted self. + + Parameters + ---------- + lag : int, default 1 + Number of lags to apply before performing autocorrelation. + + Returns + ------- + float + The Pearson correlation between self and self.shift(lag). + + See Also + -------- + Series.corr : Compute the correlation between two Series. + Series.shift : Shift index by desired number of periods. + DataFrame.corr : Compute pairwise correlation of columns. + DataFrame.corrwith : Compute pairwise correlation between rows or + columns of two DataFrame objects. + + Notes + ----- + If the Pearson correlation is not well defined return 'NaN'. + + Examples + -------- + >>> s = pd.Series([0.25, 0.5, 0.2, -0.05]) + >>> s.autocorr() # doctest: +ELLIPSIS + 0.10355... + >>> s.autocorr(lag=2) # doctest: +ELLIPSIS + -0.99999... + + If the Pearson correlation is not well defined, then 'NaN' is returned. + + >>> s = pd.Series([1, 0, 0, 0]) + >>> s.autocorr() + nan + """ + return self.corr(cast(Series, self.shift(lag))) + + def dot(self, other: AnyArrayLike) -> Series | np.ndarray: + """ + Compute the dot product between the Series and the columns of other. + + This method computes the dot product between the Series and another + one, or the Series and each columns of a DataFrame, or the Series and + each columns of an array. + + It can also be called using `self @ other`. + + Parameters + ---------- + other : Series, DataFrame or array-like + The other object to compute the dot product with its columns. + + Returns + ------- + scalar, Series or numpy.ndarray + Return the dot product of the Series and other if other is a + Series, the Series of the dot product of Series and each rows of + other if other is a DataFrame or a numpy.ndarray between the Series + and each columns of the numpy array. + + See Also + -------- + DataFrame.dot: Compute the matrix product with the DataFrame. + Series.mul: Multiplication of series and other, element-wise. + + Notes + ----- + The Series and other has to share the same index if other is a Series + or a DataFrame. + + Examples + -------- + >>> s = pd.Series([0, 1, 2, 3]) + >>> other = pd.Series([-1, 2, -3, 4]) + >>> s.dot(other) + 8 + >>> s @ other + 8 + >>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]]) + >>> s.dot(df) + 0 24 + 1 14 + dtype: int64 + >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]]) + >>> s.dot(arr) + array([24, 14]) + """ + if isinstance(other, (Series, ABCDataFrame)): + common = self.index.union(other.index) + if len(common) > len(self.index) or len(common) > len(other.index): + raise ValueError("matrices are not aligned") + + left = self.reindex(index=common, copy=False) + right = other.reindex(index=common, copy=False) + lvals = left.values + rvals = right.values + else: + lvals = self.values + rvals = np.asarray(other) + if lvals.shape[0] != rvals.shape[0]: + raise Exception( + f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}" + ) + + if isinstance(other, ABCDataFrame): + return self._constructor( + np.dot(lvals, rvals), index=other.columns, copy=False + ).__finalize__(self, method="dot") + elif isinstance(other, Series): + return np.dot(lvals, rvals) + elif isinstance(rvals, np.ndarray): + return np.dot(lvals, rvals) + else: # pragma: no cover + raise TypeError(f"unsupported type: {type(other)}") + + def __matmul__(self, other): + """ + Matrix multiplication using binary `@` operator. + """ + return self.dot(other) + + def __rmatmul__(self, other): + """ + Matrix multiplication using binary `@` operator. + """ + return self.dot(np.transpose(other)) + + @doc(base.IndexOpsMixin.searchsorted, klass="Series") + # Signature of "searchsorted" incompatible with supertype "IndexOpsMixin" + def searchsorted( # type: ignore[override] + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + return base.IndexOpsMixin.searchsorted(self, value, side=side, sorter=sorter) + + # ------------------------------------------------------------------- + # Combination + + def _append( + self, to_append, ignore_index: bool = False, verify_integrity: bool = False + ): + from pandas.core.reshape.concat import concat + + if isinstance(to_append, (list, tuple)): + to_concat = [self] + to_concat.extend(to_append) + else: + to_concat = [self, to_append] + if any(isinstance(x, (ABCDataFrame,)) for x in to_concat[1:]): + msg = "to_append should be a Series or list/tuple of Series, got DataFrame" + raise TypeError(msg) + return concat( + to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity + ) + + @doc( + _shared_docs["compare"], + dedent( + """ + Returns + ------- + Series or DataFrame + If axis is 0 or 'index' the result will be a Series. + The resulting index will be a MultiIndex with 'self' and 'other' + stacked alternately at the inner level. + + If axis is 1 or 'columns' the result will be a DataFrame. + It will have two columns namely 'self' and 'other'. + + See Also + -------- + DataFrame.compare : Compare with another DataFrame and show differences. + + Notes + ----- + Matching NaNs will not appear as a difference. + + Examples + -------- + >>> s1 = pd.Series(["a", "b", "c", "d", "e"]) + >>> s2 = pd.Series(["a", "a", "c", "b", "e"]) + + Align the differences on columns + + >>> s1.compare(s2) + self other + 1 b a + 3 d b + + Stack the differences on indices + + >>> s1.compare(s2, align_axis=0) + 1 self b + other a + 3 self d + other b + dtype: object + + Keep all original rows + + >>> s1.compare(s2, keep_shape=True) + self other + 0 NaN NaN + 1 b a + 2 NaN NaN + 3 d b + 4 NaN NaN + + Keep all original rows and also all original values + + >>> s1.compare(s2, keep_shape=True, keep_equal=True) + self other + 0 a a + 1 b a + 2 c c + 3 d b + 4 e e + """ + ), + klass=_shared_doc_kwargs["klass"], + ) + def compare( + self, + other: Series, + align_axis: Axis = 1, + keep_shape: bool = False, + keep_equal: bool = False, + result_names: Suffixes = ("self", "other"), + ) -> DataFrame | Series: + return super().compare( + other=other, + align_axis=align_axis, + keep_shape=keep_shape, + keep_equal=keep_equal, + result_names=result_names, + ) + + def combine( + self, + other: Series | Hashable, + func: Callable[[Hashable, Hashable], Hashable], + fill_value: Hashable | None = None, + ) -> Series: + """ + Combine the Series with a Series or scalar according to `func`. + + Combine the Series and `other` using `func` to perform elementwise + selection for combined Series. + `fill_value` is assumed when value is missing at some index + from one of the two objects being combined. + + Parameters + ---------- + other : Series or scalar + The value(s) to be combined with the `Series`. + func : function + Function that takes two scalars as inputs and returns an element. + fill_value : scalar, optional + The value to assume when an index is missing from + one Series or the other. The default specifies to use the + appropriate NaN value for the underlying dtype of the Series. + + Returns + ------- + Series + The result of combining the Series with the other object. + + See Also + -------- + Series.combine_first : Combine Series values, choosing the calling + Series' values first. + + Examples + -------- + Consider 2 Datasets ``s1`` and ``s2`` containing + highest clocked speeds of different birds. + + >>> s1 = pd.Series({'falcon': 330.0, 'eagle': 160.0}) + >>> s1 + falcon 330.0 + eagle 160.0 + dtype: float64 + >>> s2 = pd.Series({'falcon': 345.0, 'eagle': 200.0, 'duck': 30.0}) + >>> s2 + falcon 345.0 + eagle 200.0 + duck 30.0 + dtype: float64 + + Now, to combine the two datasets and view the highest speeds + of the birds across the two datasets + + >>> s1.combine(s2, max) + duck NaN + eagle 200.0 + falcon 345.0 + dtype: float64 + + In the previous example, the resulting value for duck is missing, + because the maximum of a NaN and a float is a NaN. + So, in the example, we set ``fill_value=0``, + so the maximum value returned will be the value from some dataset. + + >>> s1.combine(s2, max, fill_value=0) + duck 30.0 + eagle 200.0 + falcon 345.0 + dtype: float64 + """ + if fill_value is None: + fill_value = na_value_for_dtype(self.dtype, compat=False) + + if isinstance(other, Series): + # If other is a Series, result is based on union of Series, + # so do this element by element + new_index = self.index.union(other.index) + new_name = ops.get_op_result_name(self, other) + new_values = np.empty(len(new_index), dtype=object) + with np.errstate(all="ignore"): + for i, idx in enumerate(new_index): + lv = self.get(idx, fill_value) + rv = other.get(idx, fill_value) + new_values[i] = func(lv, rv) + else: + # Assume that other is a scalar, so apply the function for + # each element in the Series + new_index = self.index + new_values = np.empty(len(new_index), dtype=object) + with np.errstate(all="ignore"): + new_values[:] = [func(lv, other) for lv in self._values] + new_name = self.name + + # try_float=False is to match agg_series + npvalues = lib.maybe_convert_objects(new_values, try_float=False) + # same_dtype here is a kludge to avoid casting e.g. [True, False] to + # ["True", "False"] + same_dtype = isinstance(self.dtype, (StringDtype, CategoricalDtype)) + res_values = maybe_cast_pointwise_result( + npvalues, self.dtype, same_dtype=same_dtype + ) + return self._constructor(res_values, index=new_index, name=new_name, copy=False) + + def combine_first(self, other) -> Series: + """ + Update null elements with value in the same location in 'other'. + + Combine two Series objects by filling null values in one Series with + non-null values from the other Series. Result index will be the union + of the two indexes. + + Parameters + ---------- + other : Series + The value(s) to be used for filling null values. + + Returns + ------- + Series + The result of combining the provided Series with the other object. + + See Also + -------- + Series.combine : Perform element-wise operation on two Series + using a given function. + + Examples + -------- + >>> s1 = pd.Series([1, np.nan]) + >>> s2 = pd.Series([3, 4, 5]) + >>> s1.combine_first(s2) + 0 1.0 + 1 4.0 + 2 5.0 + dtype: float64 + + Null values still persist if the location of that null value + does not exist in `other` + + >>> s1 = pd.Series({'falcon': np.nan, 'eagle': 160.0}) + >>> s2 = pd.Series({'eagle': 200.0, 'duck': 30.0}) + >>> s1.combine_first(s2) + duck 30.0 + eagle 160.0 + falcon NaN + dtype: float64 + """ + from pandas.core.reshape.concat import concat + + if self.dtype == other.dtype: + if self.index.equals(other.index): + return self.mask(self.isna(), other) + elif self._can_hold_na and not isinstance(self.dtype, SparseDtype): + this, other = self.align(other, join="outer") + return this.mask(this.isna(), other) + + new_index = self.index.union(other.index) + + this = self + # identify the index subset to keep for each series + keep_other = other.index.difference(this.index[notna(this)]) + keep_this = this.index.difference(keep_other) + + this = this.reindex(keep_this, copy=False) + other = other.reindex(keep_other, copy=False) + + if this.dtype.kind == "M" and other.dtype.kind != "M": + other = to_datetime(other) + combined = concat([this, other]) + combined = combined.reindex(new_index, copy=False) + return combined.__finalize__(self, method="combine_first") + + def update(self, other: Series | Sequence | Mapping) -> None: + """ + Modify Series in place using values from passed Series. + + Uses non-NA values from passed Series to make updates. Aligns + on index. + + Parameters + ---------- + other : Series, or object coercible into Series + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.update(pd.Series([4, 5, 6])) + >>> s + 0 4 + 1 5 + 2 6 + dtype: int64 + + >>> s = pd.Series(['a', 'b', 'c']) + >>> s.update(pd.Series(['d', 'e'], index=[0, 2])) + >>> s + 0 d + 1 b + 2 e + dtype: object + + >>> s = pd.Series([1, 2, 3]) + >>> s.update(pd.Series([4, 5, 6, 7, 8])) + >>> s + 0 4 + 1 5 + 2 6 + dtype: int64 + + If ``other`` contains NaNs the corresponding values are not updated + in the original Series. + + >>> s = pd.Series([1, 2, 3]) + >>> s.update(pd.Series([4, np.nan, 6])) + >>> s + 0 4 + 1 2 + 2 6 + dtype: int64 + + ``other`` can also be a non-Series object type + that is coercible into a Series + + >>> s = pd.Series([1, 2, 3]) + >>> s.update([4, np.nan, 6]) + >>> s + 0 4 + 1 2 + 2 6 + dtype: int64 + + >>> s = pd.Series([1, 2, 3]) + >>> s.update({1: 9}) + >>> s + 0 1 + 1 9 + 2 3 + dtype: int64 + """ + if not PYPY and using_copy_on_write(): + if sys.getrefcount(self) <= REF_COUNT: + warnings.warn( + _chained_assignment_method_msg, + ChainedAssignmentError, + stacklevel=2, + ) + elif not PYPY and not using_copy_on_write() and self._is_view_after_cow_rules(): + ctr = sys.getrefcount(self) + ref_count = REF_COUNT + if _check_cacher(self): + # see https://github.com/pandas-dev/pandas/pull/56060#discussion_r1399245221 + ref_count += 1 + if ctr <= ref_count: + warnings.warn( + _chained_assignment_warning_method_msg, + FutureWarning, + stacklevel=2, + ) + + if not isinstance(other, Series): + other = Series(other) + + other = other.reindex_like(self) + mask = notna(other) + + self._mgr = self._mgr.putmask(mask=mask, new=other) + self._maybe_update_cacher() + + # ---------------------------------------------------------------------- + # Reindexing, sorting + + @overload + def sort_values( + self, + *, + axis: Axis = ..., + ascending: bool | Sequence[bool] = ..., + inplace: Literal[False] = ..., + kind: SortKind = ..., + na_position: NaPosition = ..., + ignore_index: bool = ..., + key: ValueKeyFunc = ..., + ) -> Series: + ... + + @overload + def sort_values( + self, + *, + axis: Axis = ..., + ascending: bool | Sequence[bool] = ..., + inplace: Literal[True], + kind: SortKind = ..., + na_position: NaPosition = ..., + ignore_index: bool = ..., + key: ValueKeyFunc = ..., + ) -> None: + ... + + @overload + def sort_values( + self, + *, + axis: Axis = ..., + ascending: bool | Sequence[bool] = ..., + inplace: bool = ..., + kind: SortKind = ..., + na_position: NaPosition = ..., + ignore_index: bool = ..., + key: ValueKeyFunc = ..., + ) -> Series | None: + ... + + def sort_values( + self, + *, + axis: Axis = 0, + ascending: bool | Sequence[bool] = True, + inplace: bool = False, + kind: SortKind = "quicksort", + na_position: NaPosition = "last", + ignore_index: bool = False, + key: ValueKeyFunc | None = None, + ) -> Series | None: + """ + Sort by the values. + + Sort a Series in ascending or descending order by some + criterion. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + ascending : bool or list of bools, default True + If True, sort values in ascending order, otherwise descending. + inplace : bool, default False + If True, perform operation in-place. + kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort' + Choice of sorting algorithm. See also :func:`numpy.sort` for more + information. 'mergesort' and 'stable' are the only stable algorithms. + na_position : {'first' or 'last'}, default 'last' + Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at + the end. + ignore_index : bool, default False + If True, the resulting axis will be labeled 0, 1, …, n - 1. + key : callable, optional + If not None, apply the key function to the series values + before sorting. This is similar to the `key` argument in the + builtin :meth:`sorted` function, with the notable difference that + this `key` function should be *vectorized*. It should expect a + ``Series`` and return an array-like. + + Returns + ------- + Series or None + Series ordered by values or None if ``inplace=True``. + + See Also + -------- + Series.sort_index : Sort by the Series indices. + DataFrame.sort_values : Sort DataFrame by the values along either axis. + DataFrame.sort_index : Sort DataFrame by indices. + + Examples + -------- + >>> s = pd.Series([np.nan, 1, 3, 10, 5]) + >>> s + 0 NaN + 1 1.0 + 2 3.0 + 3 10.0 + 4 5.0 + dtype: float64 + + Sort values ascending order (default behaviour) + + >>> s.sort_values(ascending=True) + 1 1.0 + 2 3.0 + 4 5.0 + 3 10.0 + 0 NaN + dtype: float64 + + Sort values descending order + + >>> s.sort_values(ascending=False) + 3 10.0 + 4 5.0 + 2 3.0 + 1 1.0 + 0 NaN + dtype: float64 + + Sort values putting NAs first + + >>> s.sort_values(na_position='first') + 0 NaN + 1 1.0 + 2 3.0 + 4 5.0 + 3 10.0 + dtype: float64 + + Sort a series of strings + + >>> s = pd.Series(['z', 'b', 'd', 'a', 'c']) + >>> s + 0 z + 1 b + 2 d + 3 a + 4 c + dtype: object + + >>> s.sort_values() + 3 a + 1 b + 4 c + 2 d + 0 z + dtype: object + + Sort using a key function. Your `key` function will be + given the ``Series`` of values and should return an array-like. + + >>> s = pd.Series(['a', 'B', 'c', 'D', 'e']) + >>> s.sort_values() + 1 B + 3 D + 0 a + 2 c + 4 e + dtype: object + >>> s.sort_values(key=lambda x: x.str.lower()) + 0 a + 1 B + 2 c + 3 D + 4 e + dtype: object + + NumPy ufuncs work well here. For example, we can + sort by the ``sin`` of the value + + >>> s = pd.Series([-4, -2, 0, 2, 4]) + >>> s.sort_values(key=np.sin) + 1 -2 + 4 4 + 2 0 + 0 -4 + 3 2 + dtype: int64 + + More complicated user-defined functions can be used, + as long as they expect a Series and return an array-like + + >>> s.sort_values(key=lambda x: (np.tan(x.cumsum()))) + 0 -4 + 3 2 + 4 4 + 1 -2 + 2 0 + dtype: int64 + """ + inplace = validate_bool_kwarg(inplace, "inplace") + # Validate the axis parameter + self._get_axis_number(axis) + + # GH 5856/5853 + if inplace and self._is_cached: + raise ValueError( + "This Series is a view of some other array, to " + "sort in-place you must create a copy" + ) + + if is_list_like(ascending): + ascending = cast(Sequence[bool], ascending) + if len(ascending) != 1: + raise ValueError( + f"Length of ascending ({len(ascending)}) must be 1 for Series" + ) + ascending = ascending[0] + + ascending = validate_ascending(ascending) + + if na_position not in ["first", "last"]: + raise ValueError(f"invalid na_position: {na_position}") + + # GH 35922. Make sorting stable by leveraging nargsort + if key: + values_to_sort = cast(Series, ensure_key_mapped(self, key))._values + else: + values_to_sort = self._values + sorted_index = nargsort(values_to_sort, kind, bool(ascending), na_position) + + if is_range_indexer(sorted_index, len(sorted_index)): + if inplace: + return self._update_inplace(self) + return self.copy(deep=None) + + result = self._constructor( + self._values[sorted_index], index=self.index[sorted_index], copy=False + ) + + if ignore_index: + result.index = default_index(len(sorted_index)) + + if not inplace: + return result.__finalize__(self, method="sort_values") + self._update_inplace(result) + return None + + @overload + def sort_index( + self, + *, + axis: Axis = ..., + level: IndexLabel = ..., + ascending: bool | Sequence[bool] = ..., + inplace: Literal[True], + kind: SortKind = ..., + na_position: NaPosition = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., + key: IndexKeyFunc = ..., + ) -> None: + ... + + @overload + def sort_index( + self, + *, + axis: Axis = ..., + level: IndexLabel = ..., + ascending: bool | Sequence[bool] = ..., + inplace: Literal[False] = ..., + kind: SortKind = ..., + na_position: NaPosition = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., + key: IndexKeyFunc = ..., + ) -> Series: + ... + + @overload + def sort_index( + self, + *, + axis: Axis = ..., + level: IndexLabel = ..., + ascending: bool | Sequence[bool] = ..., + inplace: bool = ..., + kind: SortKind = ..., + na_position: NaPosition = ..., + sort_remaining: bool = ..., + ignore_index: bool = ..., + key: IndexKeyFunc = ..., + ) -> Series | None: + ... + + def sort_index( + self, + *, + axis: Axis = 0, + level: IndexLabel | None = None, + ascending: bool | Sequence[bool] = True, + inplace: bool = False, + kind: SortKind = "quicksort", + na_position: NaPosition = "last", + sort_remaining: bool = True, + ignore_index: bool = False, + key: IndexKeyFunc | None = None, + ) -> Series | None: + """ + Sort Series by index labels. + + Returns a new Series sorted by label if `inplace` argument is + ``False``, otherwise updates the original series and returns None. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + level : int, optional + If not None, sort on values in specified index level(s). + ascending : bool or list-like of bools, default True + Sort ascending vs. descending. When the index is a MultiIndex the + sort direction can be controlled for each level individually. + inplace : bool, default False + If True, perform operation in-place. + kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort' + Choice of sorting algorithm. See also :func:`numpy.sort` for more + information. 'mergesort' and 'stable' are the only stable algorithms. For + DataFrames, this option is only applied when sorting on a single + column or label. + na_position : {'first', 'last'}, default 'last' + If 'first' puts NaNs at the beginning, 'last' puts NaNs at the end. + Not implemented for MultiIndex. + sort_remaining : bool, default True + If True and sorting by level and index is multilevel, sort by other + levels too (in order) after sorting by specified level. + ignore_index : bool, default False + If True, the resulting axis will be labeled 0, 1, …, n - 1. + key : callable, optional + If not None, apply the key function to the index values + before sorting. This is similar to the `key` argument in the + builtin :meth:`sorted` function, with the notable difference that + this `key` function should be *vectorized*. It should expect an + ``Index`` and return an ``Index`` of the same shape. + + Returns + ------- + Series or None + The original Series sorted by the labels or None if ``inplace=True``. + + See Also + -------- + DataFrame.sort_index: Sort DataFrame by the index. + DataFrame.sort_values: Sort DataFrame by the value. + Series.sort_values : Sort Series by the value. + + Examples + -------- + >>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4]) + >>> s.sort_index() + 1 c + 2 b + 3 a + 4 d + dtype: object + + Sort Descending + + >>> s.sort_index(ascending=False) + 4 d + 3 a + 2 b + 1 c + dtype: object + + By default NaNs are put at the end, but use `na_position` to place + them at the beginning + + >>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, np.nan]) + >>> s.sort_index(na_position='first') + NaN d + 1.0 c + 2.0 b + 3.0 a + dtype: object + + Specify index level to sort + + >>> arrays = [np.array(['qux', 'qux', 'foo', 'foo', + ... 'baz', 'baz', 'bar', 'bar']), + ... np.array(['two', 'one', 'two', 'one', + ... 'two', 'one', 'two', 'one'])] + >>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays) + >>> s.sort_index(level=1) + bar one 8 + baz one 6 + foo one 4 + qux one 2 + bar two 7 + baz two 5 + foo two 3 + qux two 1 + dtype: int64 + + Does not sort by remaining levels when sorting by levels + + >>> s.sort_index(level=1, sort_remaining=False) + qux one 2 + foo one 4 + baz one 6 + bar one 8 + qux two 1 + foo two 3 + baz two 5 + bar two 7 + dtype: int64 + + Apply a key function before sorting + + >>> s = pd.Series([1, 2, 3, 4], index=['A', 'b', 'C', 'd']) + >>> s.sort_index(key=lambda x : x.str.lower()) + A 1 + b 2 + C 3 + d 4 + dtype: int64 + """ + + return super().sort_index( + axis=axis, + level=level, + ascending=ascending, + inplace=inplace, + kind=kind, + na_position=na_position, + sort_remaining=sort_remaining, + ignore_index=ignore_index, + key=key, + ) + + def argsort( + self, + axis: Axis = 0, + kind: SortKind = "quicksort", + order: None = None, + stable: None = None, + ) -> Series: + """ + Return the integer indices that would sort the Series values. + + Override ndarray.argsort. Argsorts the value, omitting NA/null values, + and places the result in the same locations as the non-NA values. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + kind : {'mergesort', 'quicksort', 'heapsort', 'stable'}, default 'quicksort' + Choice of sorting algorithm. See :func:`numpy.sort` for more + information. 'mergesort' and 'stable' are the only stable algorithms. + order : None + Has no effect but is accepted for compatibility with numpy. + stable : None + Has no effect but is accepted for compatibility with numpy. + + Returns + ------- + Series[np.intp] + Positions of values within the sort order with -1 indicating + nan values. + + See Also + -------- + numpy.ndarray.argsort : Returns the indices that would sort this array. + + Examples + -------- + >>> s = pd.Series([3, 2, 1]) + >>> s.argsort() + 0 2 + 1 1 + 2 0 + dtype: int64 + """ + if axis != -1: + # GH#54257 We allow -1 here so that np.argsort(series) works + self._get_axis_number(axis) + + values = self._values + mask = isna(values) + + if mask.any(): + # TODO(3.0): once this deprecation is enforced we can call + # self.array.argsort directly, which will close GH#43840 and + # GH#12694 + warnings.warn( + "The behavior of Series.argsort in the presence of NA values is " + "deprecated. In a future version, NA values will be ordered " + "last instead of set to -1.", + FutureWarning, + stacklevel=find_stack_level(), + ) + result = np.full(len(self), -1, dtype=np.intp) + notmask = ~mask + result[notmask] = np.argsort(values[notmask], kind=kind) + else: + result = np.argsort(values, kind=kind) + + res = self._constructor( + result, index=self.index, name=self.name, dtype=np.intp, copy=False + ) + return res.__finalize__(self, method="argsort") + + def nlargest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: + """ + Return the largest `n` elements. + + Parameters + ---------- + n : int, default 5 + Return this many descending sorted values. + keep : {'first', 'last', 'all'}, default 'first' + When there are duplicate values that cannot all fit in a + Series of `n` elements: + + - ``first`` : return the first `n` occurrences in order + of appearance. + - ``last`` : return the last `n` occurrences in reverse + order of appearance. + - ``all`` : keep all occurrences. This can result in a Series of + size larger than `n`. + + Returns + ------- + Series + The `n` largest values in the Series, sorted in decreasing order. + + See Also + -------- + Series.nsmallest: Get the `n` smallest elements. + Series.sort_values: Sort Series by values. + Series.head: Return the first `n` rows. + + Notes + ----- + Faster than ``.sort_values(ascending=False).head(n)`` for small `n` + relative to the size of the ``Series`` object. + + Examples + -------- + >>> countries_population = {"Italy": 59000000, "France": 65000000, + ... "Malta": 434000, "Maldives": 434000, + ... "Brunei": 434000, "Iceland": 337000, + ... "Nauru": 11300, "Tuvalu": 11300, + ... "Anguilla": 11300, "Montserrat": 5200} + >>> s = pd.Series(countries_population) + >>> s + Italy 59000000 + France 65000000 + Malta 434000 + Maldives 434000 + Brunei 434000 + Iceland 337000 + Nauru 11300 + Tuvalu 11300 + Anguilla 11300 + Montserrat 5200 + dtype: int64 + + The `n` largest elements where ``n=5`` by default. + + >>> s.nlargest() + France 65000000 + Italy 59000000 + Malta 434000 + Maldives 434000 + Brunei 434000 + dtype: int64 + + The `n` largest elements where ``n=3``. Default `keep` value is 'first' + so Malta will be kept. + + >>> s.nlargest(3) + France 65000000 + Italy 59000000 + Malta 434000 + dtype: int64 + + The `n` largest elements where ``n=3`` and keeping the last duplicates. + Brunei will be kept since it is the last with value 434000 based on + the index order. + + >>> s.nlargest(3, keep='last') + France 65000000 + Italy 59000000 + Brunei 434000 + dtype: int64 + + The `n` largest elements where ``n=3`` with all duplicates kept. Note + that the returned Series has five elements due to the three duplicates. + + >>> s.nlargest(3, keep='all') + France 65000000 + Italy 59000000 + Malta 434000 + Maldives 434000 + Brunei 434000 + dtype: int64 + """ + return selectn.SelectNSeries(self, n=n, keep=keep).nlargest() + + def nsmallest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: + """ + Return the smallest `n` elements. + + Parameters + ---------- + n : int, default 5 + Return this many ascending sorted values. + keep : {'first', 'last', 'all'}, default 'first' + When there are duplicate values that cannot all fit in a + Series of `n` elements: + + - ``first`` : return the first `n` occurrences in order + of appearance. + - ``last`` : return the last `n` occurrences in reverse + order of appearance. + - ``all`` : keep all occurrences. This can result in a Series of + size larger than `n`. + + Returns + ------- + Series + The `n` smallest values in the Series, sorted in increasing order. + + See Also + -------- + Series.nlargest: Get the `n` largest elements. + Series.sort_values: Sort Series by values. + Series.head: Return the first `n` rows. + + Notes + ----- + Faster than ``.sort_values().head(n)`` for small `n` relative to + the size of the ``Series`` object. + + Examples + -------- + >>> countries_population = {"Italy": 59000000, "France": 65000000, + ... "Brunei": 434000, "Malta": 434000, + ... "Maldives": 434000, "Iceland": 337000, + ... "Nauru": 11300, "Tuvalu": 11300, + ... "Anguilla": 11300, "Montserrat": 5200} + >>> s = pd.Series(countries_population) + >>> s + Italy 59000000 + France 65000000 + Brunei 434000 + Malta 434000 + Maldives 434000 + Iceland 337000 + Nauru 11300 + Tuvalu 11300 + Anguilla 11300 + Montserrat 5200 + dtype: int64 + + The `n` smallest elements where ``n=5`` by default. + + >>> s.nsmallest() + Montserrat 5200 + Nauru 11300 + Tuvalu 11300 + Anguilla 11300 + Iceland 337000 + dtype: int64 + + The `n` smallest elements where ``n=3``. Default `keep` value is + 'first' so Nauru and Tuvalu will be kept. + + >>> s.nsmallest(3) + Montserrat 5200 + Nauru 11300 + Tuvalu 11300 + dtype: int64 + + The `n` smallest elements where ``n=3`` and keeping the last + duplicates. Anguilla and Tuvalu will be kept since they are the last + with value 11300 based on the index order. + + >>> s.nsmallest(3, keep='last') + Montserrat 5200 + Anguilla 11300 + Tuvalu 11300 + dtype: int64 + + The `n` smallest elements where ``n=3`` with all duplicates kept. Note + that the returned Series has four elements due to the three duplicates. + + >>> s.nsmallest(3, keep='all') + Montserrat 5200 + Nauru 11300 + Tuvalu 11300 + Anguilla 11300 + dtype: int64 + """ + return selectn.SelectNSeries(self, n=n, keep=keep).nsmallest() + + @doc( + klass=_shared_doc_kwargs["klass"], + extra_params=dedent( + """copy : bool, default True + Whether to copy underlying data. + + .. note:: + The `copy` keyword will change behavior in pandas 3.0. + `Copy-on-Write + `__ + will be enabled by default, which means that all methods with a + `copy` keyword will use a lazy copy mechanism to defer the copy and + ignore the `copy` keyword. The `copy` keyword will be removed in a + future version of pandas. + + You can already get the future behavior and improvements through + enabling copy on write ``pd.options.mode.copy_on_write = True``""" + ), + examples=dedent( + """\ + Examples + -------- + >>> s = pd.Series( + ... ["A", "B", "A", "C"], + ... index=[ + ... ["Final exam", "Final exam", "Coursework", "Coursework"], + ... ["History", "Geography", "History", "Geography"], + ... ["January", "February", "March", "April"], + ... ], + ... ) + >>> s + Final exam History January A + Geography February B + Coursework History March A + Geography April C + dtype: object + + In the following example, we will swap the levels of the indices. + Here, we will swap the levels column-wise, but levels can be swapped row-wise + in a similar manner. Note that column-wise is the default behaviour. + By not supplying any arguments for i and j, we swap the last and second to + last indices. + + >>> s.swaplevel() + Final exam January History A + February Geography B + Coursework March History A + April Geography C + dtype: object + + By supplying one argument, we can choose which index to swap the last + index with. We can for example swap the first index with the last one as + follows. + + >>> s.swaplevel(0) + January History Final exam A + February Geography Final exam B + March History Coursework A + April Geography Coursework C + dtype: object + + We can also define explicitly which indices we want to swap by supplying values + for both i and j. Here, we for example swap the first and second indices. + + >>> s.swaplevel(0, 1) + History Final exam January A + Geography Final exam February B + History Coursework March A + Geography Coursework April C + dtype: object""" + ), + ) + def swaplevel( + self, i: Level = -2, j: Level = -1, copy: bool | None = None + ) -> Series: + """ + Swap levels i and j in a :class:`MultiIndex`. + + Default is to swap the two innermost levels of the index. + + Parameters + ---------- + i, j : int or str + Levels of the indices to be swapped. Can pass level name as string. + {extra_params} + + Returns + ------- + {klass} + {klass} with levels swapped in MultiIndex. + + {examples} + """ + assert isinstance(self.index, MultiIndex) + result = self.copy(deep=copy and not using_copy_on_write()) + result.index = self.index.swaplevel(i, j) + return result + + def reorder_levels(self, order: Sequence[Level]) -> Series: + """ + Rearrange index levels using input order. + + May not drop or duplicate levels. + + Parameters + ---------- + order : list of int representing new level order + Reference level by number or key. + + Returns + ------- + type of caller (new object) + + Examples + -------- + >>> arrays = [np.array(["dog", "dog", "cat", "cat", "bird", "bird"]), + ... np.array(["white", "black", "white", "black", "white", "black"])] + >>> s = pd.Series([1, 2, 3, 3, 5, 2], index=arrays) + >>> s + dog white 1 + black 2 + cat white 3 + black 3 + bird white 5 + black 2 + dtype: int64 + >>> s.reorder_levels([1, 0]) + white dog 1 + black dog 2 + white cat 3 + black cat 3 + white bird 5 + black bird 2 + dtype: int64 + """ + if not isinstance(self.index, MultiIndex): # pragma: no cover + raise Exception("Can only reorder levels on a hierarchical axis.") + + result = self.copy(deep=None) + assert isinstance(result.index, MultiIndex) + result.index = result.index.reorder_levels(order) + return result + + def explode(self, ignore_index: bool = False) -> Series: + """ + Transform each element of a list-like to a row. + + Parameters + ---------- + ignore_index : bool, default False + If True, the resulting index will be labeled 0, 1, …, n - 1. + + Returns + ------- + Series + Exploded lists to rows; index will be duplicated for these rows. + + See Also + -------- + Series.str.split : Split string values on specified separator. + Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex + to produce DataFrame. + DataFrame.melt : Unpivot a DataFrame from wide format to long format. + DataFrame.explode : Explode a DataFrame from list-like + columns to long format. + + Notes + ----- + This routine will explode list-likes including lists, tuples, sets, + Series, and np.ndarray. The result dtype of the subset rows will + be object. Scalars will be returned unchanged, and empty list-likes will + result in a np.nan for that row. In addition, the ordering of elements in + the output will be non-deterministic when exploding sets. + + Reference :ref:`the user guide ` for more examples. + + Examples + -------- + >>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]]) + >>> s + 0 [1, 2, 3] + 1 foo + 2 [] + 3 [3, 4] + dtype: object + + >>> s.explode() + 0 1 + 0 2 + 0 3 + 1 foo + 2 NaN + 3 3 + 3 4 + dtype: object + """ + if isinstance(self.dtype, ExtensionDtype): + values, counts = self._values._explode() + elif len(self) and is_object_dtype(self.dtype): + values, counts = reshape.explode(np.asarray(self._values)) + else: + result = self.copy() + return result.reset_index(drop=True) if ignore_index else result + + if ignore_index: + index: Index = default_index(len(values)) + else: + index = self.index.repeat(counts) + + return self._constructor(values, index=index, name=self.name, copy=False) + + def unstack( + self, + level: IndexLabel = -1, + fill_value: Hashable | None = None, + sort: bool = True, + ) -> DataFrame: + """ + Unstack, also known as pivot, Series with MultiIndex to produce DataFrame. + + Parameters + ---------- + level : int, str, or list of these, default last level + Level(s) to unstack, can pass level name. + fill_value : scalar value, default None + Value to use when replacing NaN values. + sort : bool, default True + Sort the level(s) in the resulting MultiIndex columns. + + Returns + ------- + DataFrame + Unstacked Series. + + Notes + ----- + Reference :ref:`the user guide ` for more examples. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4], + ... index=pd.MultiIndex.from_product([['one', 'two'], + ... ['a', 'b']])) + >>> s + one a 1 + b 2 + two a 3 + b 4 + dtype: int64 + + >>> s.unstack(level=-1) + a b + one 1 2 + two 3 4 + + >>> s.unstack(level=0) + one two + a 1 3 + b 2 4 + """ + from pandas.core.reshape.reshape import unstack + + return unstack(self, level, fill_value, sort) + + # ---------------------------------------------------------------------- + # function application + + def map( + self, + arg: Callable | Mapping | Series, + na_action: Literal["ignore"] | None = None, + ) -> Series: + """ + Map values of Series according to an input mapping or function. + + Used for substituting each value in a Series with another value, + that may be derived from a function, a ``dict`` or + a :class:`Series`. + + Parameters + ---------- + arg : function, collections.abc.Mapping subclass or Series + Mapping correspondence. + na_action : {None, 'ignore'}, default None + If 'ignore', propagate NaN values, without passing them to the + mapping correspondence. + + Returns + ------- + Series + Same index as caller. + + See Also + -------- + Series.apply : For applying more complex functions on a Series. + Series.replace: Replace values given in `to_replace` with `value`. + DataFrame.apply : Apply a function row-/column-wise. + DataFrame.map : Apply a function elementwise on a whole DataFrame. + + Notes + ----- + When ``arg`` is a dictionary, values in Series that are not in the + dictionary (as keys) are converted to ``NaN``. However, if the + dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. + provides a method for default values), then this default is used + rather than ``NaN``. + + Examples + -------- + >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit']) + >>> s + 0 cat + 1 dog + 2 NaN + 3 rabbit + dtype: object + + ``map`` accepts a ``dict`` or a ``Series``. Values that are not found + in the ``dict`` are converted to ``NaN``, unless the dict has a default + value (e.g. ``defaultdict``): + + >>> s.map({'cat': 'kitten', 'dog': 'puppy'}) + 0 kitten + 1 puppy + 2 NaN + 3 NaN + dtype: object + + It also accepts a function: + + >>> s.map('I am a {}'.format) + 0 I am a cat + 1 I am a dog + 2 I am a nan + 3 I am a rabbit + dtype: object + + To avoid applying the function to missing values (and keep them as + ``NaN``) ``na_action='ignore'`` can be used: + + >>> s.map('I am a {}'.format, na_action='ignore') + 0 I am a cat + 1 I am a dog + 2 NaN + 3 I am a rabbit + dtype: object + """ + new_values = self._map_values(arg, na_action=na_action) + return self._constructor(new_values, index=self.index, copy=False).__finalize__( + self, method="map" + ) + + def _gotitem(self, key, ndim, subset=None) -> Self: + """ + Sub-classes to define. Return a sliced object. + + Parameters + ---------- + key : string / list of selections + ndim : {1, 2} + Requested ndim of result. + subset : object, default None + Subset to act on. + """ + return self + + _agg_see_also_doc = dedent( + """ + See Also + -------- + Series.apply : Invoke function on a Series. + Series.transform : Transform function producing a Series with like indexes. + """ + ) + + _agg_examples_doc = dedent( + """ + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + dtype: int64 + + >>> s.agg('min') + 1 + + >>> s.agg(['min', 'max']) + min 1 + max 4 + dtype: int64 + """ + ) + + @doc( + _shared_docs["aggregate"], + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], + see_also=_agg_see_also_doc, + examples=_agg_examples_doc, + ) + def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): + # Validate the axis parameter + self._get_axis_number(axis) + + # if func is None, will switch to user-provided "named aggregation" kwargs + if func is None: + func = dict(kwargs.items()) + + op = SeriesApply(self, func, args=args, kwargs=kwargs) + result = op.agg() + return result + + agg = aggregate + + @doc( + _shared_docs["transform"], + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], + ) + def transform( + self, func: AggFuncType, axis: Axis = 0, *args, **kwargs + ) -> DataFrame | Series: + # Validate axis argument + self._get_axis_number(axis) + ser = ( + self.copy(deep=False) + if using_copy_on_write() or warn_copy_on_write() + else self + ) + result = SeriesApply(ser, func=func, args=args, kwargs=kwargs).transform() + return result + + def apply( + self, + func: AggFuncType, + convert_dtype: bool | lib.NoDefault = lib.no_default, + args: tuple[Any, ...] = (), + *, + by_row: Literal[False, "compat"] = "compat", + **kwargs, + ) -> DataFrame | Series: + """ + Invoke function on values of Series. + + Can be ufunc (a NumPy function that applies to the entire Series) + or a Python function that only works on single values. + + Parameters + ---------- + func : function + Python function or NumPy ufunc to apply. + convert_dtype : bool, default True + Try to find better dtype for elementwise function results. If + False, leave as dtype=object. Note that the dtype is always + preserved for some extension array dtypes, such as Categorical. + + .. deprecated:: 2.1.0 + ``convert_dtype`` has been deprecated. Do ``ser.astype(object).apply()`` + instead if you want ``convert_dtype=False``. + args : tuple + Positional arguments passed to func after the series value. + by_row : False or "compat", default "compat" + If ``"compat"`` and func is a callable, func will be passed each element of + the Series, like ``Series.map``. If func is a list or dict of + callables, will first try to translate each func into pandas methods. If + that doesn't work, will try call to apply again with ``by_row="compat"`` + and if that fails, will call apply again with ``by_row=False`` + (backward compatible). + If False, the func will be passed the whole Series at once. + + ``by_row`` has no effect when ``func`` is a string. + + .. versionadded:: 2.1.0 + **kwargs + Additional keyword arguments passed to func. + + Returns + ------- + Series or DataFrame + If func returns a Series object the result will be a DataFrame. + + See Also + -------- + Series.map: For element-wise operations. + Series.agg: Only perform aggregating type operations. + Series.transform: Only perform transforming type operations. + + Notes + ----- + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` + for more details. + + Examples + -------- + Create a series with typical summer temperatures for each city. + + >>> s = pd.Series([20, 21, 12], + ... index=['London', 'New York', 'Helsinki']) + >>> s + London 20 + New York 21 + Helsinki 12 + dtype: int64 + + Square the values by defining a function and passing it as an + argument to ``apply()``. + + >>> def square(x): + ... return x ** 2 + >>> s.apply(square) + London 400 + New York 441 + Helsinki 144 + dtype: int64 + + Square the values by passing an anonymous function as an + argument to ``apply()``. + + >>> s.apply(lambda x: x ** 2) + London 400 + New York 441 + Helsinki 144 + dtype: int64 + + Define a custom function that needs additional positional + arguments and pass these additional arguments using the + ``args`` keyword. + + >>> def subtract_custom_value(x, custom_value): + ... return x - custom_value + + >>> s.apply(subtract_custom_value, args=(5,)) + London 15 + New York 16 + Helsinki 7 + dtype: int64 + + Define a custom function that takes keyword arguments + and pass these arguments to ``apply``. + + >>> def add_custom_values(x, **kwargs): + ... for month in kwargs: + ... x += kwargs[month] + ... return x + + >>> s.apply(add_custom_values, june=30, july=20, august=25) + London 95 + New York 96 + Helsinki 87 + dtype: int64 + + Use a function from the Numpy library. + + >>> s.apply(np.log) + London 2.995732 + New York 3.044522 + Helsinki 2.484907 + dtype: float64 + """ + return SeriesApply( + self, + func, + convert_dtype=convert_dtype, + by_row=by_row, + args=args, + kwargs=kwargs, + ).apply() + + def _reindex_indexer( + self, + new_index: Index | None, + indexer: npt.NDArray[np.intp] | None, + copy: bool | None, + ) -> Series: + # Note: new_index is None iff indexer is None + # if not None, indexer is np.intp + if indexer is None and ( + new_index is None or new_index.names == self.index.names + ): + if using_copy_on_write(): + return self.copy(deep=copy) + if copy or copy is None: + return self.copy(deep=copy) + return self + + new_values = algorithms.take_nd( + self._values, indexer, allow_fill=True, fill_value=None + ) + return self._constructor(new_values, index=new_index, copy=False) + + def _needs_reindex_multi(self, axes, method, level) -> bool: + """ + Check if we do need a multi reindex; this is for compat with + higher dims. + """ + return False + + @overload + def rename( + self, + index: Renamer | Hashable | None = ..., + *, + axis: Axis | None = ..., + copy: bool = ..., + inplace: Literal[True], + level: Level | None = ..., + errors: IgnoreRaise = ..., + ) -> None: + ... + + @overload + def rename( + self, + index: Renamer | Hashable | None = ..., + *, + axis: Axis | None = ..., + copy: bool = ..., + inplace: Literal[False] = ..., + level: Level | None = ..., + errors: IgnoreRaise = ..., + ) -> Series: + ... + + @overload + def rename( + self, + index: Renamer | Hashable | None = ..., + *, + axis: Axis | None = ..., + copy: bool = ..., + inplace: bool = ..., + level: Level | None = ..., + errors: IgnoreRaise = ..., + ) -> Series | None: + ... + + def rename( + self, + index: Renamer | Hashable | None = None, + *, + axis: Axis | None = None, + copy: bool | None = None, + inplace: bool = False, + level: Level | None = None, + errors: IgnoreRaise = "ignore", + ) -> Series | None: + """ + Alter Series index labels or name. + + Function / dict values must be unique (1-to-1). Labels not contained in + a dict / Series will be left as-is. Extra labels listed don't throw an + error. + + Alternatively, change ``Series.name`` with a scalar value. + + See the :ref:`user guide ` for more. + + Parameters + ---------- + index : scalar, hashable sequence, dict-like or function optional + Functions or dict-like are transformations to apply to + the index. + Scalar or hashable sequence-like will alter the ``Series.name`` + attribute. + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + copy : bool, default True + Also copy underlying data. + + .. note:: + The `copy` keyword will change behavior in pandas 3.0. + `Copy-on-Write + `__ + will be enabled by default, which means that all methods with a + `copy` keyword will use a lazy copy mechanism to defer the copy and + ignore the `copy` keyword. The `copy` keyword will be removed in a + future version of pandas. + + You can already get the future behavior and improvements through + enabling copy on write ``pd.options.mode.copy_on_write = True`` + inplace : bool, default False + Whether to return a new Series. If True the value of copy is ignored. + level : int or level name, default None + In case of MultiIndex, only rename labels in the specified level. + errors : {'ignore', 'raise'}, default 'ignore' + If 'raise', raise `KeyError` when a `dict-like mapper` or + `index` contains labels that are not present in the index being transformed. + If 'ignore', existing keys will be renamed and extra keys will be ignored. + + Returns + ------- + Series or None + Series with index labels or name altered or None if ``inplace=True``. + + See Also + -------- + DataFrame.rename : Corresponding DataFrame method. + Series.rename_axis : Set the name of the axis. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s + 0 1 + 1 2 + 2 3 + dtype: int64 + >>> s.rename("my_name") # scalar, changes Series.name + 0 1 + 1 2 + 2 3 + Name: my_name, dtype: int64 + >>> s.rename(lambda x: x ** 2) # function, changes labels + 0 1 + 1 2 + 4 3 + dtype: int64 + >>> s.rename({1: 3, 2: 5}) # mapping, changes labels + 0 1 + 3 2 + 5 3 + dtype: int64 + """ + if axis is not None: + # Make sure we raise if an invalid 'axis' is passed. + axis = self._get_axis_number(axis) + + if callable(index) or is_dict_like(index): + # error: Argument 1 to "_rename" of "NDFrame" has incompatible + # type "Union[Union[Mapping[Any, Hashable], Callable[[Any], + # Hashable]], Hashable, None]"; expected "Union[Mapping[Any, + # Hashable], Callable[[Any], Hashable], None]" + return super()._rename( + index, # type: ignore[arg-type] + copy=copy, + inplace=inplace, + level=level, + errors=errors, + ) + else: + return self._set_name(index, inplace=inplace, deep=copy) + + @Appender( + """ + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s + 0 1 + 1 2 + 2 3 + dtype: int64 + + >>> s.set_axis(['a', 'b', 'c'], axis=0) + a 1 + b 2 + c 3 + dtype: int64 + """ + ) + @Substitution( + klass=_shared_doc_kwargs["klass"], + axes_single_arg=_shared_doc_kwargs["axes_single_arg"], + extended_summary_sub="", + axis_description_sub="", + see_also_sub="", + ) + @Appender(NDFrame.set_axis.__doc__) + def set_axis( + self, + labels, + *, + axis: Axis = 0, + copy: bool | None = None, + ) -> Series: + return super().set_axis(labels, axis=axis, copy=copy) + + # error: Cannot determine type of 'reindex' + @doc( + NDFrame.reindex, # type: ignore[has-type] + klass=_shared_doc_kwargs["klass"], + optional_reindex=_shared_doc_kwargs["optional_reindex"], + ) + def reindex( # type: ignore[override] + self, + index=None, + *, + axis: Axis | None = None, + method: ReindexMethod | None = None, + copy: bool | None = None, + level: Level | None = None, + fill_value: Scalar | None = None, + limit: int | None = None, + tolerance=None, + ) -> Series: + return super().reindex( + index=index, + method=method, + copy=copy, + level=level, + fill_value=fill_value, + limit=limit, + tolerance=tolerance, + ) + + @overload # type: ignore[override] + def rename_axis( + self, + mapper: IndexLabel | lib.NoDefault = ..., + *, + index=..., + axis: Axis = ..., + copy: bool = ..., + inplace: Literal[True], + ) -> None: + ... + + @overload + def rename_axis( + self, + mapper: IndexLabel | lib.NoDefault = ..., + *, + index=..., + axis: Axis = ..., + copy: bool = ..., + inplace: Literal[False] = ..., + ) -> Self: + ... + + @overload + def rename_axis( + self, + mapper: IndexLabel | lib.NoDefault = ..., + *, + index=..., + axis: Axis = ..., + copy: bool = ..., + inplace: bool = ..., + ) -> Self | None: + ... + + @doc(NDFrame.rename_axis) + def rename_axis( + self, + mapper: IndexLabel | lib.NoDefault = lib.no_default, + *, + index=lib.no_default, + axis: Axis = 0, + copy: bool = True, + inplace: bool = False, + ) -> Self | None: + return super().rename_axis( + mapper=mapper, + index=index, + axis=axis, + copy=copy, + inplace=inplace, + ) + + @overload + def drop( + self, + labels: IndexLabel = ..., + *, + axis: Axis = ..., + index: IndexLabel = ..., + columns: IndexLabel = ..., + level: Level | None = ..., + inplace: Literal[True], + errors: IgnoreRaise = ..., + ) -> None: + ... + + @overload + def drop( + self, + labels: IndexLabel = ..., + *, + axis: Axis = ..., + index: IndexLabel = ..., + columns: IndexLabel = ..., + level: Level | None = ..., + inplace: Literal[False] = ..., + errors: IgnoreRaise = ..., + ) -> Series: + ... + + @overload + def drop( + self, + labels: IndexLabel = ..., + *, + axis: Axis = ..., + index: IndexLabel = ..., + columns: IndexLabel = ..., + level: Level | None = ..., + inplace: bool = ..., + errors: IgnoreRaise = ..., + ) -> Series | None: + ... + + def drop( + self, + labels: IndexLabel | None = None, + *, + axis: Axis = 0, + index: IndexLabel | None = None, + columns: IndexLabel | None = None, + level: Level | None = None, + inplace: bool = False, + errors: IgnoreRaise = "raise", + ) -> Series | None: + """ + Return Series with specified index labels removed. + + Remove elements of a Series based on specifying the index labels. + When using a multi-index, labels on different levels can be removed + by specifying the level. + + Parameters + ---------- + labels : single label or list-like + Index labels to drop. + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + index : single label or list-like + Redundant for application on Series, but 'index' can be used instead + of 'labels'. + columns : single label or list-like + No change is made to the Series; use 'index' or 'labels' instead. + level : int or level name, optional + For MultiIndex, level for which the labels will be removed. + inplace : bool, default False + If True, do operation inplace and return None. + errors : {'ignore', 'raise'}, default 'raise' + If 'ignore', suppress error and only existing labels are dropped. + + Returns + ------- + Series or None + Series with specified index labels removed or None if ``inplace=True``. + + Raises + ------ + KeyError + If none of the labels are found in the index. + + See Also + -------- + Series.reindex : Return only specified index labels of Series. + Series.dropna : Return series without null values. + Series.drop_duplicates : Return Series with duplicate values removed. + DataFrame.drop : Drop specified labels from rows or columns. + + Examples + -------- + >>> s = pd.Series(data=np.arange(3), index=['A', 'B', 'C']) + >>> s + A 0 + B 1 + C 2 + dtype: int64 + + Drop labels B en C + + >>> s.drop(labels=['B', 'C']) + A 0 + dtype: int64 + + Drop 2nd level label in MultiIndex Series + + >>> midx = pd.MultiIndex(levels=[['llama', 'cow', 'falcon'], + ... ['speed', 'weight', 'length']], + ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], + ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) + >>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], + ... index=midx) + >>> s + llama speed 45.0 + weight 200.0 + length 1.2 + cow speed 30.0 + weight 250.0 + length 1.5 + falcon speed 320.0 + weight 1.0 + length 0.3 + dtype: float64 + + >>> s.drop(labels='weight', level=1) + llama speed 45.0 + length 1.2 + cow speed 30.0 + length 1.5 + falcon speed 320.0 + length 0.3 + dtype: float64 + """ + return super().drop( + labels=labels, + axis=axis, + index=index, + columns=columns, + level=level, + inplace=inplace, + errors=errors, + ) + + def pop(self, item: Hashable) -> Any: + """ + Return item and drops from series. Raise KeyError if not found. + + Parameters + ---------- + item : label + Index of the element that needs to be removed. + + Returns + ------- + Value that is popped from series. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + + >>> ser.pop(0) + 1 + + >>> ser + 1 2 + 2 3 + dtype: int64 + """ + return super().pop(item=item) + + @doc(INFO_DOCSTRING, **series_sub_kwargs) + def info( + self, + verbose: bool | None = None, + buf: IO[str] | None = None, + max_cols: int | None = None, + memory_usage: bool | str | None = None, + show_counts: bool = True, + ) -> None: + return SeriesInfo(self, memory_usage).render( + buf=buf, + max_cols=max_cols, + verbose=verbose, + show_counts=show_counts, + ) + + # TODO(3.0): this can be removed once GH#33302 deprecation is enforced + def _replace_single(self, to_replace, method: str, inplace: bool, limit): + """ + Replaces values in a Series using the fill method specified when no + replacement value is given in the replace method + """ + + result = self if inplace else self.copy() + + values = result._values + mask = missing.mask_missing(values, to_replace) + + if isinstance(values, ExtensionArray): + # dispatch to the EA's _pad_mask_inplace method + values._fill_mask_inplace(method, limit, mask) + else: + fill_f = missing.get_fill_func(method) + fill_f(values, limit=limit, mask=mask) + + if inplace: + return + return result + + def memory_usage(self, index: bool = True, deep: bool = False) -> int: + """ + Return the memory usage of the Series. + + The memory usage can optionally include the contribution of + the index and of elements of `object` dtype. + + Parameters + ---------- + index : bool, default True + Specifies whether to include the memory usage of the Series index. + deep : bool, default False + If True, introspect the data deeply by interrogating + `object` dtypes for system-level memory consumption, and include + it in the returned value. + + Returns + ------- + int + Bytes of memory consumed. + + See Also + -------- + numpy.ndarray.nbytes : Total bytes consumed by the elements of the + array. + DataFrame.memory_usage : Bytes consumed by a DataFrame. + + Examples + -------- + >>> s = pd.Series(range(3)) + >>> s.memory_usage() + 152 + + Not including the index gives the size of the rest of the data, which + is necessarily smaller: + + >>> s.memory_usage(index=False) + 24 + + The memory footprint of `object` values is ignored by default: + + >>> s = pd.Series(["a", "b"]) + >>> s.values + array(['a', 'b'], dtype=object) + >>> s.memory_usage() + 144 + >>> s.memory_usage(deep=True) + 244 + """ + v = self._memory_usage(deep=deep) + if index: + v += self.index.memory_usage(deep=deep) + return v + + def isin(self, values) -> Series: + """ + Whether elements in Series are contained in `values`. + + Return a boolean Series showing whether each element in the Series + matches an element in the passed sequence of `values` exactly. + + Parameters + ---------- + values : set or list-like + The sequence of values to test. Passing in a single string will + raise a ``TypeError``. Instead, turn a single string into a + list of one element. + + Returns + ------- + Series + Series of booleans indicating if each element is in values. + + Raises + ------ + TypeError + * If `values` is a string + + See Also + -------- + DataFrame.isin : Equivalent method on DataFrame. + + Examples + -------- + >>> s = pd.Series(['llama', 'cow', 'llama', 'beetle', 'llama', + ... 'hippo'], name='animal') + >>> s.isin(['cow', 'llama']) + 0 True + 1 True + 2 True + 3 False + 4 True + 5 False + Name: animal, dtype: bool + + To invert the boolean values, use the ``~`` operator: + + >>> ~s.isin(['cow', 'llama']) + 0 False + 1 False + 2 False + 3 True + 4 False + 5 True + Name: animal, dtype: bool + + Passing a single string as ``s.isin('llama')`` will raise an error. Use + a list of one element instead: + + >>> s.isin(['llama']) + 0 True + 1 False + 2 True + 3 False + 4 True + 5 False + Name: animal, dtype: bool + + Strings and integers are distinct and are therefore not comparable: + + >>> pd.Series([1]).isin(['1']) + 0 False + dtype: bool + >>> pd.Series([1.1]).isin(['1.1']) + 0 False + dtype: bool + """ + result = algorithms.isin(self._values, values) + return self._constructor(result, index=self.index, copy=False).__finalize__( + self, method="isin" + ) + + def between( + self, + left, + right, + inclusive: Literal["both", "neither", "left", "right"] = "both", + ) -> Series: + """ + Return boolean Series equivalent to left <= series <= right. + + This function returns a boolean vector containing `True` wherever the + corresponding Series element is between the boundary values `left` and + `right`. NA values are treated as `False`. + + Parameters + ---------- + left : scalar or list-like + Left boundary. + right : scalar or list-like + Right boundary. + inclusive : {"both", "neither", "left", "right"} + Include boundaries. Whether to set each bound as closed or open. + + .. versionchanged:: 1.3.0 + + Returns + ------- + Series + Series representing whether each element is between left and + right (inclusive). + + See Also + -------- + Series.gt : Greater than of series and other. + Series.lt : Less than of series and other. + + Notes + ----- + This function is equivalent to ``(left <= ser) & (ser <= right)`` + + Examples + -------- + >>> s = pd.Series([2, 0, 4, 8, np.nan]) + + Boundary values are included by default: + + >>> s.between(1, 4) + 0 True + 1 False + 2 True + 3 False + 4 False + dtype: bool + + With `inclusive` set to ``"neither"`` boundary values are excluded: + + >>> s.between(1, 4, inclusive="neither") + 0 True + 1 False + 2 False + 3 False + 4 False + dtype: bool + + `left` and `right` can be any scalar value: + + >>> s = pd.Series(['Alice', 'Bob', 'Carol', 'Eve']) + >>> s.between('Anna', 'Daniel') + 0 False + 1 True + 2 True + 3 False + dtype: bool + """ + if inclusive == "both": + lmask = self >= left + rmask = self <= right + elif inclusive == "left": + lmask = self >= left + rmask = self < right + elif inclusive == "right": + lmask = self > left + rmask = self <= right + elif inclusive == "neither": + lmask = self > left + rmask = self < right + else: + raise ValueError( + "Inclusive has to be either string of 'both'," + "'left', 'right', or 'neither'." + ) + + return lmask & rmask + + def case_when( + self, + caselist: list[ + tuple[ + ArrayLike | Callable[[Series], Series | np.ndarray | Sequence[bool]], + ArrayLike | Scalar | Callable[[Series], Series | np.ndarray], + ], + ], + ) -> Series: + """ + Replace values where the conditions are True. + + Parameters + ---------- + caselist : A list of tuples of conditions and expected replacements + Takes the form: ``(condition0, replacement0)``, + ``(condition1, replacement1)``, ... . + ``condition`` should be a 1-D boolean array-like object + or a callable. If ``condition`` is a callable, + it is computed on the Series + and should return a boolean Series or array. + The callable must not change the input Series + (though pandas doesn`t check it). ``replacement`` should be a + 1-D array-like object, a scalar or a callable. + If ``replacement`` is a callable, it is computed on the Series + and should return a scalar or Series. The callable + must not change the input Series + (though pandas doesn`t check it). + + .. versionadded:: 2.2.0 + + Returns + ------- + Series + + See Also + -------- + Series.mask : Replace values where the condition is True. + + Examples + -------- + >>> c = pd.Series([6, 7, 8, 9], name='c') + >>> a = pd.Series([0, 0, 1, 2]) + >>> b = pd.Series([0, 3, 4, 5]) + + >>> c.case_when(caselist=[(a.gt(0), a), # condition, replacement + ... (b.gt(0), b)]) + 0 6 + 1 3 + 2 1 + 3 2 + Name: c, dtype: int64 + """ + if not isinstance(caselist, list): + raise TypeError( + f"The caselist argument should be a list; instead got {type(caselist)}" + ) + + if not caselist: + raise ValueError( + "provide at least one boolean condition, " + "with a corresponding replacement." + ) + + for num, entry in enumerate(caselist): + if not isinstance(entry, tuple): + raise TypeError( + f"Argument {num} must be a tuple; instead got {type(entry)}." + ) + if len(entry) != 2: + raise ValueError( + f"Argument {num} must have length 2; " + "a condition and replacement; " + f"instead got length {len(entry)}." + ) + caselist = [ + ( + com.apply_if_callable(condition, self), + com.apply_if_callable(replacement, self), + ) + for condition, replacement in caselist + ] + default = self.copy() + conditions, replacements = zip(*caselist) + common_dtypes = [infer_dtype_from(arg)[0] for arg in [*replacements, default]] + if len(set(common_dtypes)) > 1: + common_dtype = find_common_type(common_dtypes) + updated_replacements = [] + for condition, replacement in zip(conditions, replacements): + if is_scalar(replacement): + replacement = construct_1d_arraylike_from_scalar( + value=replacement, length=len(condition), dtype=common_dtype + ) + elif isinstance(replacement, ABCSeries): + replacement = replacement.astype(common_dtype) + else: + replacement = pd_array(replacement, dtype=common_dtype) + updated_replacements.append(replacement) + replacements = updated_replacements + default = default.astype(common_dtype) + + counter = reversed(range(len(conditions))) + for position, condition, replacement in zip( + counter, conditions[::-1], replacements[::-1] + ): + try: + default = default.mask( + condition, other=replacement, axis=0, inplace=False, level=None + ) + except Exception as error: + raise ValueError( + f"Failed to apply condition{position} and replacement{position}." + ) from error + return default + + # error: Cannot determine type of 'isna' + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type] + def isna(self) -> Series: + return NDFrame.isna(self) + + # error: Cannot determine type of 'isna' + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type] + def isnull(self) -> Series: + """ + Series.isnull is an alias for Series.isna. + """ + return super().isnull() + + # error: Cannot determine type of 'notna' + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type] + def notna(self) -> Series: + return super().notna() + + # error: Cannot determine type of 'notna' + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type] + def notnull(self) -> Series: + """ + Series.notnull is an alias for Series.notna. + """ + return super().notnull() + + @overload + def dropna( + self, + *, + axis: Axis = ..., + inplace: Literal[False] = ..., + how: AnyAll | None = ..., + ignore_index: bool = ..., + ) -> Series: + ... + + @overload + def dropna( + self, + *, + axis: Axis = ..., + inplace: Literal[True], + how: AnyAll | None = ..., + ignore_index: bool = ..., + ) -> None: + ... + + def dropna( + self, + *, + axis: Axis = 0, + inplace: bool = False, + how: AnyAll | None = None, + ignore_index: bool = False, + ) -> Series | None: + """ + Return a new Series with missing values removed. + + See the :ref:`User Guide ` for more on which values are + considered missing, and how to work with missing data. + + Parameters + ---------- + axis : {0 or 'index'} + Unused. Parameter needed for compatibility with DataFrame. + inplace : bool, default False + If True, do operation inplace and return None. + how : str, optional + Not in use. Kept for compatibility. + ignore_index : bool, default ``False`` + If ``True``, the resulting axis will be labeled 0, 1, …, n - 1. + + .. versionadded:: 2.0.0 + + Returns + ------- + Series or None + Series with NA entries dropped from it or None if ``inplace=True``. + + See Also + -------- + Series.isna: Indicate missing values. + Series.notna : Indicate existing (non-missing) values. + Series.fillna : Replace missing values. + DataFrame.dropna : Drop rows or columns which contain NA values. + Index.dropna : Drop missing indices. + + Examples + -------- + >>> ser = pd.Series([1., 2., np.nan]) + >>> ser + 0 1.0 + 1 2.0 + 2 NaN + dtype: float64 + + Drop NA values from a Series. + + >>> ser.dropna() + 0 1.0 + 1 2.0 + dtype: float64 + + Empty strings are not considered NA values. ``None`` is considered an + NA value. + + >>> ser = pd.Series([np.nan, 2, pd.NaT, '', None, 'I stay']) + >>> ser + 0 NaN + 1 2 + 2 NaT + 3 + 4 None + 5 I stay + dtype: object + >>> ser.dropna() + 1 2 + 3 + 5 I stay + dtype: object + """ + inplace = validate_bool_kwarg(inplace, "inplace") + ignore_index = validate_bool_kwarg(ignore_index, "ignore_index") + # Validate the axis parameter + self._get_axis_number(axis or 0) + + if self._can_hold_na: + result = remove_na_arraylike(self) + else: + if not inplace: + result = self.copy(deep=None) + else: + result = self + + if ignore_index: + result.index = default_index(len(result)) + + if inplace: + return self._update_inplace(result) + else: + return result + + # ---------------------------------------------------------------------- + # Time series-oriented methods + + def to_timestamp( + self, + freq: Frequency | None = None, + how: Literal["s", "e", "start", "end"] = "start", + copy: bool | None = None, + ) -> Series: + """ + Cast to DatetimeIndex of Timestamps, at *beginning* of period. + + Parameters + ---------- + freq : str, default frequency of PeriodIndex + Desired frequency. + how : {'s', 'e', 'start', 'end'} + Convention for converting period to timestamp; start of period + vs. end. + copy : bool, default True + Whether or not to return a copy. + + .. note:: + The `copy` keyword will change behavior in pandas 3.0. + `Copy-on-Write + `__ + will be enabled by default, which means that all methods with a + `copy` keyword will use a lazy copy mechanism to defer the copy and + ignore the `copy` keyword. The `copy` keyword will be removed in a + future version of pandas. + + You can already get the future behavior and improvements through + enabling copy on write ``pd.options.mode.copy_on_write = True`` + + Returns + ------- + Series with DatetimeIndex + + Examples + -------- + >>> idx = pd.PeriodIndex(['2023', '2024', '2025'], freq='Y') + >>> s1 = pd.Series([1, 2, 3], index=idx) + >>> s1 + 2023 1 + 2024 2 + 2025 3 + Freq: Y-DEC, dtype: int64 + + The resulting frequency of the Timestamps is `YearBegin` + + >>> s1 = s1.to_timestamp() + >>> s1 + 2023-01-01 1 + 2024-01-01 2 + 2025-01-01 3 + Freq: YS-JAN, dtype: int64 + + Using `freq` which is the offset that the Timestamps will have + + >>> s2 = pd.Series([1, 2, 3], index=idx) + >>> s2 = s2.to_timestamp(freq='M') + >>> s2 + 2023-01-31 1 + 2024-01-31 2 + 2025-01-31 3 + Freq: YE-JAN, dtype: int64 + """ + if not isinstance(self.index, PeriodIndex): + raise TypeError(f"unsupported Type {type(self.index).__name__}") + + new_obj = self.copy(deep=copy and not using_copy_on_write()) + new_index = self.index.to_timestamp(freq=freq, how=how) + setattr(new_obj, "index", new_index) + return new_obj + + def to_period(self, freq: str | None = None, copy: bool | None = None) -> Series: + """ + Convert Series from DatetimeIndex to PeriodIndex. + + Parameters + ---------- + freq : str, default None + Frequency associated with the PeriodIndex. + copy : bool, default True + Whether or not to return a copy. + + .. note:: + The `copy` keyword will change behavior in pandas 3.0. + `Copy-on-Write + `__ + will be enabled by default, which means that all methods with a + `copy` keyword will use a lazy copy mechanism to defer the copy and + ignore the `copy` keyword. The `copy` keyword will be removed in a + future version of pandas. + + You can already get the future behavior and improvements through + enabling copy on write ``pd.options.mode.copy_on_write = True`` + + Returns + ------- + Series + Series with index converted to PeriodIndex. + + Examples + -------- + >>> idx = pd.DatetimeIndex(['2023', '2024', '2025']) + >>> s = pd.Series([1, 2, 3], index=idx) + >>> s = s.to_period() + >>> s + 2023 1 + 2024 2 + 2025 3 + Freq: Y-DEC, dtype: int64 + + Viewing the index + + >>> s.index + PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]') + """ + if not isinstance(self.index, DatetimeIndex): + raise TypeError(f"unsupported Type {type(self.index).__name__}") + + new_obj = self.copy(deep=copy and not using_copy_on_write()) + new_index = self.index.to_period(freq=freq) + setattr(new_obj, "index", new_index) + return new_obj + + # ---------------------------------------------------------------------- + # Add index + _AXIS_ORDERS: list[Literal["index", "columns"]] = ["index"] + _AXIS_LEN = len(_AXIS_ORDERS) + _info_axis_number: Literal[0] = 0 + _info_axis_name: Literal["index"] = "index" + + index = properties.AxisProperty( + axis=0, + doc=""" + The index (axis labels) of the Series. + + The index of a Series is used to label and identify each element of the + underlying data. The index can be thought of as an immutable ordered set + (technically a multi-set, as it may contain duplicate labels), and is + used to index and align data in pandas. + + Returns + ------- + Index + The index labels of the Series. + + See Also + -------- + Series.reindex : Conform Series to new index. + Index : The base pandas index type. + + Notes + ----- + For more information on pandas indexing, see the `indexing user guide + `__. + + Examples + -------- + To create a Series with a custom index and view the index labels: + + >>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon'] + >>> populations = [14.85, 2.71, 2.93, 0.51] + >>> city_series = pd.Series(populations, index=cities) + >>> city_series.index + Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object') + + To change the index labels of an existing Series: + + >>> city_series.index = ['KOL', 'CHI', 'TOR', 'LIS'] + >>> city_series.index + Index(['KOL', 'CHI', 'TOR', 'LIS'], dtype='object') + """, + ) + + # ---------------------------------------------------------------------- + # Accessor Methods + # ---------------------------------------------------------------------- + str = CachedAccessor("str", StringMethods) + dt = CachedAccessor("dt", CombinedDatetimelikeProperties) + cat = CachedAccessor("cat", CategoricalAccessor) + plot = CachedAccessor("plot", pandas.plotting.PlotAccessor) + sparse = CachedAccessor("sparse", SparseAccessor) + struct = CachedAccessor("struct", StructAccessor) + list = CachedAccessor("list", ListAccessor) + + # ---------------------------------------------------------------------- + # Add plotting methods to Series + hist = pandas.plotting.hist_series + + # ---------------------------------------------------------------------- + # Template-Based Arithmetic/Comparison Methods + + def _cmp_method(self, other, op): + res_name = ops.get_op_result_name(self, other) + + if isinstance(other, Series) and not self._indexed_same(other): + raise ValueError("Can only compare identically-labeled Series objects") + + lvalues = self._values + rvalues = extract_array(other, extract_numpy=True, extract_range=True) + + res_values = ops.comparison_op(lvalues, rvalues, op) + + return self._construct_result(res_values, name=res_name) + + def _logical_method(self, other, op): + res_name = ops.get_op_result_name(self, other) + self, other = self._align_for_op(other, align_asobject=True) + + lvalues = self._values + rvalues = extract_array(other, extract_numpy=True, extract_range=True) + + res_values = ops.logical_op(lvalues, rvalues, op) + return self._construct_result(res_values, name=res_name) + + def _arith_method(self, other, op): + self, other = self._align_for_op(other) + return base.IndexOpsMixin._arith_method(self, other, op) + + def _align_for_op(self, right, align_asobject: bool = False): + """align lhs and rhs Series""" + # TODO: Different from DataFrame._align_for_op, list, tuple and ndarray + # are not coerced here + # because Series has inconsistencies described in GH#13637 + left = self + + if isinstance(right, Series): + # avoid repeated alignment + if not left.index.equals(right.index): + if align_asobject: + if left.dtype not in (object, np.bool_) or right.dtype not in ( + object, + np.bool_, + ): + warnings.warn( + "Operation between non boolean Series with different " + "indexes will no longer return a boolean result in " + "a future version. Cast both Series to object type " + "to maintain the prior behavior.", + FutureWarning, + stacklevel=find_stack_level(), + ) + # to keep original value's dtype for bool ops + left = left.astype(object) + right = right.astype(object) + + left, right = left.align(right, copy=False) + + return left, right + + def _binop(self, other: Series, func, level=None, fill_value=None) -> Series: + """ + Perform generic binary operation with optional fill value. + + Parameters + ---------- + other : Series + func : binary operator + fill_value : float or object + Value to substitute for NA/null values. If both Series are NA in a + location, the result will be NA regardless of the passed fill value. + level : int or level name, default None + Broadcast across a level, matching Index values on the + passed MultiIndex level. + + Returns + ------- + Series + """ + this = self + + if not self.index.equals(other.index): + this, other = self.align(other, level=level, join="outer", copy=False) + + this_vals, other_vals = ops.fill_binop(this._values, other._values, fill_value) + + with np.errstate(all="ignore"): + result = func(this_vals, other_vals) + + name = ops.get_op_result_name(self, other) + out = this._construct_result(result, name) + return cast(Series, out) + + def _construct_result( + self, result: ArrayLike | tuple[ArrayLike, ArrayLike], name: Hashable + ) -> Series | tuple[Series, Series]: + """ + Construct an appropriately-labelled Series from the result of an op. + + Parameters + ---------- + result : ndarray or ExtensionArray + name : Label + + Returns + ------- + Series + In the case of __divmod__ or __rdivmod__, a 2-tuple of Series. + """ + if isinstance(result, tuple): + # produced by divmod or rdivmod + + res1 = self._construct_result(result[0], name=name) + res2 = self._construct_result(result[1], name=name) + + # GH#33427 assertions to keep mypy happy + assert isinstance(res1, Series) + assert isinstance(res2, Series) + return (res1, res2) + + # TODO: result should always be ArrayLike, but this fails for some + # JSONArray tests + dtype = getattr(result, "dtype", None) + out = self._constructor(result, index=self.index, dtype=dtype, copy=False) + out = out.__finalize__(self) + + # Set the result's name after __finalize__ is called because __finalize__ + # would set it back to self.name + out.name = name + return out + + def _flex_method(self, other, op, *, level=None, fill_value=None, axis: Axis = 0): + if axis is not None: + self._get_axis_number(axis) + + res_name = ops.get_op_result_name(self, other) + + if isinstance(other, Series): + return self._binop(other, op, level=level, fill_value=fill_value) + elif isinstance(other, (np.ndarray, list, tuple)): + if len(other) != len(self): + raise ValueError("Lengths must be equal") + other = self._constructor(other, self.index, copy=False) + result = self._binop(other, op, level=level, fill_value=fill_value) + result._name = res_name + return result + else: + if fill_value is not None: + if isna(other): + return op(self, fill_value) + self = self.fillna(fill_value) + + return op(self, other) + + @Appender(ops.make_flex_doc("eq", "series")) + def eq( + self, + other, + level: Level | None = None, + fill_value: float | None = None, + axis: Axis = 0, + ) -> Series: + return self._flex_method( + other, operator.eq, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("ne", "series")) + def ne(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.ne, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("le", "series")) + def le(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.le, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("lt", "series")) + def lt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.lt, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("ge", "series")) + def ge(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.ge, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("gt", "series")) + def gt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.gt, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("add", "series")) + def add(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.add, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("radd", "series")) + def radd(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.radd, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("sub", "series")) + def sub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.sub, level=level, fill_value=fill_value, axis=axis + ) + + subtract = sub + + @Appender(ops.make_flex_doc("rsub", "series")) + def rsub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rsub, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("mul", "series")) + def mul( + self, + other, + level: Level | None = None, + fill_value: float | None = None, + axis: Axis = 0, + ) -> Series: + return self._flex_method( + other, operator.mul, level=level, fill_value=fill_value, axis=axis + ) + + multiply = mul + + @Appender(ops.make_flex_doc("rmul", "series")) + def rmul(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rmul, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("truediv", "series")) + def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.truediv, level=level, fill_value=fill_value, axis=axis + ) + + div = truediv + divide = truediv + + @Appender(ops.make_flex_doc("rtruediv", "series")) + def rtruediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rtruediv, level=level, fill_value=fill_value, axis=axis + ) + + rdiv = rtruediv + + @Appender(ops.make_flex_doc("floordiv", "series")) + def floordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.floordiv, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("rfloordiv", "series")) + def rfloordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rfloordiv, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("mod", "series")) + def mod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.mod, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("rmod", "series")) + def rmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rmod, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("pow", "series")) + def pow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, operator.pow, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("rpow", "series")) + def rpow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rpow, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("divmod", "series")) + def divmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, divmod, level=level, fill_value=fill_value, axis=axis + ) + + @Appender(ops.make_flex_doc("rdivmod", "series")) + def rdivmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: + return self._flex_method( + other, roperator.rdivmod, level=level, fill_value=fill_value, axis=axis + ) + + # ---------------------------------------------------------------------- + # Reductions + + def _reduce( + self, + op, + # error: Variable "pandas.core.series.Series.str" is not valid as a type + name: str, # type: ignore[valid-type] + *, + axis: Axis = 0, + skipna: bool = True, + numeric_only: bool = False, + filter_type=None, + **kwds, + ): + """ + Perform a reduction operation. + + If we have an ndarray as a value, then simply perform the operation, + otherwise delegate to the object. + """ + delegate = self._values + + if axis is not None: + self._get_axis_number(axis) + + if isinstance(delegate, ExtensionArray): + # dispatch to ExtensionArray interface + return delegate._reduce(name, skipna=skipna, **kwds) + + else: + # dispatch to numpy arrays + if numeric_only and self.dtype.kind not in "iufcb": + # i.e. not is_numeric_dtype(self.dtype) + kwd_name = "numeric_only" + if name in ["any", "all"]: + kwd_name = "bool_only" + # GH#47500 - change to TypeError to match other methods + raise TypeError( + f"Series.{name} does not allow {kwd_name}={numeric_only} " + "with non-numeric dtypes." + ) + return op(delegate, skipna=skipna, **kwds) + + @Appender(make_doc("any", ndim=1)) + # error: Signature of "any" incompatible with supertype "NDFrame" + def any( # type: ignore[override] + self, + *, + axis: Axis = 0, + bool_only: bool = False, + skipna: bool = True, + **kwargs, + ) -> bool: + nv.validate_logical_func((), kwargs, fname="any") + validate_bool_kwarg(skipna, "skipna", none_allowed=False) + return self._reduce( + nanops.nanany, + name="any", + axis=axis, + numeric_only=bool_only, + skipna=skipna, + filter_type="bool", + ) + + @Appender(make_doc("all", ndim=1)) + def all( + self, + axis: Axis = 0, + bool_only: bool = False, + skipna: bool = True, + **kwargs, + ) -> bool: + nv.validate_logical_func((), kwargs, fname="all") + validate_bool_kwarg(skipna, "skipna", none_allowed=False) + return self._reduce( + nanops.nanall, + name="all", + axis=axis, + numeric_only=bool_only, + skipna=skipna, + filter_type="bool", + ) + + @doc(make_doc("min", ndim=1)) + def min( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.min(self, axis, skipna, numeric_only, **kwargs) + + @doc(make_doc("max", ndim=1)) + def max( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.max(self, axis, skipna, numeric_only, **kwargs) + + @doc(make_doc("sum", ndim=1)) + def sum( + self, + axis: Axis | None = None, + skipna: bool = True, + numeric_only: bool = False, + min_count: int = 0, + **kwargs, + ): + return NDFrame.sum(self, axis, skipna, numeric_only, min_count, **kwargs) + + @doc(make_doc("prod", ndim=1)) + def prod( + self, + axis: Axis | None = None, + skipna: bool = True, + numeric_only: bool = False, + min_count: int = 0, + **kwargs, + ): + return NDFrame.prod(self, axis, skipna, numeric_only, min_count, **kwargs) + + @doc(make_doc("mean", ndim=1)) + def mean( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.mean(self, axis, skipna, numeric_only, **kwargs) + + @doc(make_doc("median", ndim=1)) + def median( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.median(self, axis, skipna, numeric_only, **kwargs) + + @doc(make_doc("sem", ndim=1)) + def sem( + self, + axis: Axis | None = None, + skipna: bool = True, + ddof: int = 1, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.sem(self, axis, skipna, ddof, numeric_only, **kwargs) + + @doc(make_doc("var", ndim=1)) + def var( + self, + axis: Axis | None = None, + skipna: bool = True, + ddof: int = 1, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.var(self, axis, skipna, ddof, numeric_only, **kwargs) + + @doc(make_doc("std", ndim=1)) + def std( + self, + axis: Axis | None = None, + skipna: bool = True, + ddof: int = 1, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.std(self, axis, skipna, ddof, numeric_only, **kwargs) + + @doc(make_doc("skew", ndim=1)) + def skew( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.skew(self, axis, skipna, numeric_only, **kwargs) + + @doc(make_doc("kurt", ndim=1)) + def kurt( + self, + axis: Axis | None = 0, + skipna: bool = True, + numeric_only: bool = False, + **kwargs, + ): + return NDFrame.kurt(self, axis, skipna, numeric_only, **kwargs) + + kurtosis = kurt + product = prod + + @doc(make_doc("cummin", ndim=1)) + def cummin(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + return NDFrame.cummin(self, axis, skipna, *args, **kwargs) + + @doc(make_doc("cummax", ndim=1)) + def cummax(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + return NDFrame.cummax(self, axis, skipna, *args, **kwargs) + + @doc(make_doc("cumsum", ndim=1)) + def cumsum(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) + + @doc(make_doc("cumprod", 1)) + def cumprod(self, axis: Axis | None = None, skipna: bool = True, *args, **kwargs): + return NDFrame.cumprod(self, axis, skipna, *args, **kwargs) diff --git a/shared/package-files/0b/0bacb5bf50bb933ef75827e5dcc4be2a57b2953e1a61d5540ddb4fd11071ae0f/test_arithmetic.py b/shared/package-files/0b/0bacb5bf50bb933ef75827e5dcc4be2a57b2953e1a61d5540ddb4fd11071ae0f/test_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4fcf149eb20bfa124d7387d1c6b243febdf14f --- /dev/null +++ b/shared/package-files/0b/0bacb5bf50bb933ef75827e5dcc4be2a57b2953e1a61d5540ddb4fd11071ae0f/test_arithmetic.py @@ -0,0 +1,139 @@ +import operator + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture +def data(): + """Fixture returning boolean array with valid and missing values.""" + return pd.array( + [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False], + dtype="boolean", + ) + + +@pytest.fixture +def left_array(): + """Fixture returning boolean array with valid and missing values.""" + return pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") + + +@pytest.fixture +def right_array(): + """Fixture returning boolean array with valid and missing values.""" + return pd.array([True, False, None] * 3, dtype="boolean") + + +# Basic test for the arithmetic array ops +# ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "opname, exp", + [ + ("add", [True, True, None, True, False, None, None, None, None]), + ("mul", [True, False, None, False, False, None, None, None, None]), + ], + ids=["add", "mul"], +) +def test_add_mul(left_array, right_array, opname, exp): + op = getattr(operator, opname) + result = op(left_array, right_array) + expected = pd.array(exp, dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + +def test_sub(left_array, right_array): + msg = ( + r"numpy boolean subtract, the `-` operator, is (?:deprecated|not supported), " + r"use the bitwise_xor, the `\^` operator, or the logical_xor function instead\." + ) + with pytest.raises(TypeError, match=msg): + left_array - right_array + + +def test_div(left_array, right_array): + msg = "operator '.*' not implemented for bool dtypes" + with pytest.raises(NotImplementedError, match=msg): + # check that we are matching the non-masked Series behavior + pd.Series(left_array._data) / pd.Series(right_array._data) + + with pytest.raises(NotImplementedError, match=msg): + left_array / right_array + + +@pytest.mark.parametrize( + "opname", + [ + "floordiv", + "mod", + "pow", + ], +) +def test_op_int8(left_array, right_array, opname): + op = getattr(operator, opname) + if opname != "mod": + msg = "operator '.*' not implemented for bool dtypes" + with pytest.raises(NotImplementedError, match=msg): + result = op(left_array, right_array) + return + result = op(left_array, right_array) + expected = op(left_array.astype("Int8"), right_array.astype("Int8")) + tm.assert_extension_array_equal(result, expected) + + +# Test generic characteristics / errors +# ----------------------------------------------------------------------------- + + +def test_error_invalid_values(data, all_arithmetic_operators, using_infer_string): + # invalid ops + + if using_infer_string: + import pyarrow as pa + + err = (TypeError, pa.lib.ArrowNotImplementedError, NotImplementedError) + else: + err = TypeError + + op = all_arithmetic_operators + s = pd.Series(data) + ops = getattr(s, op) + + # invalid scalars + msg = ( + "did not contain a loop with signature matching types|" + "BooleanArray cannot perform the operation|" + "not supported for the input types, and the inputs could not be safely coerced " + "to any supported types according to the casting rule ''safe''" + ) + with pytest.raises(TypeError, match=msg): + ops("foo") + msg = "|".join( + [ + r"unsupported operand type\(s\) for", + "Concatenation operation is not implemented for NumPy arrays", + "has no kernel", + ] + ) + with pytest.raises(err, match=msg): + ops(pd.Timestamp("20180101")) + + # invalid array-likes + if op not in ("__mul__", "__rmul__"): + # TODO(extension) numpy's mul with object array sees booleans as numbers + msg = "|".join( + [ + r"unsupported operand type\(s\) for", + "can only concatenate str", + "not all arguments converted during string formatting", + "has no kernel", + "not implemented", + ] + ) + with pytest.raises(err, match=msg): + ops(pd.Series("foo", index=s.index)) diff --git a/shared/package-files/0b/0badd7a118bf9dcb68f1a23f3e0796858d8088fbc95d5fd5b1ce21d7ab795dd3/to_mkldnn_backward_native.h b/shared/package-files/0b/0badd7a118bf9dcb68f1a23f3e0796858d8088fbc95d5fd5b1ce21d7ab795dd3/to_mkldnn_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4e7d221203e58040da48e652ed4a599b47abe912 --- /dev/null +++ b/shared/package-files/0b/0badd7a118bf9dcb68f1a23f3e0796858d8088fbc95d5fd5b1ce21d7ab795dd3/to_mkldnn_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor to_mkldnn_backward(const at::Tensor & grad, const at::Tensor & input); +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0bb032c9d485a960bee83d7ad734e5b2bd0701279b4bb8cfe1a4bac48193a990/__init__.cpython-311.pyc b/shared/package-files/0b/0bb032c9d485a960bee83d7ad734e5b2bd0701279b4bb8cfe1a4bac48193a990/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d05e6489b9a5aecb96c7659d17c5f65ffb3082 Binary files /dev/null and b/shared/package-files/0b/0bb032c9d485a960bee83d7ad734e5b2bd0701279b4bb8cfe1a4bac48193a990/__init__.cpython-311.pyc differ diff --git a/shared/package-files/0b/0bb7d4f6051579f00d96b2a68263e6053c8ddbb53d2158117f0d8bfa56b2875a/empty.h b/shared/package-files/0b/0bb7d4f6051579f00d96b2a68263e6053c8ddbb53d2158117f0d8bfa56b2875a/empty.h new file mode 100644 index 0000000000000000000000000000000000000000..80780639fafafcc1ca8384ce747e47d6916b7077 --- /dev/null +++ b/shared/package-files/0b/0bb7d4f6051579f00d96b2a68263e6053c8ddbb53d2158117f0d8bfa56b2875a/empty.h @@ -0,0 +1,132 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty(at::IntArrayRef size, ::std::optional names, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_names::call(size, names, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +// aten::empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty(at::IntArrayRef size, ::std::optional names, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format) { + return at::_ops::empty_names::call(size, names, dtype, layout, device, pin_memory, memory_format); +} + +// aten::empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty(at::IntArrayRef size, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_memory_format::call(c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template >> + at::Tensor empty(at::IntArrayRef size, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_memory_format::call(c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty(at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format) { + return at::_ops::empty_memory_format::call(c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template >> + at::Tensor empty(at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format) { + return at::_ops::empty_memory_format::call(c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty_symint(c10::SymIntArrayRef size, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_memory_format::call(size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template >> + at::Tensor empty(c10::SymIntArrayRef size, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_memory_format::call(size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor empty_symint(c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format) { + return at::_ops::empty_memory_format::call(size, dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template >> + at::Tensor empty(c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format) { + return at::_ops::empty_memory_format::call(size, dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_out(at::Tensor & out, at::IntArrayRef size, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_out::call(c10::fromIntArrayRefSlow(size), memory_format, out); +} +namespace symint { + template >> + at::Tensor & empty_out(at::Tensor & out, at::IntArrayRef size, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_out::call(c10::fromIntArrayRefSlow(size), memory_format, out); + } +} + +// aten::empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_outf(at::IntArrayRef size, ::std::optional memory_format, at::Tensor & out) { + return at::_ops::empty_out::call(c10::fromIntArrayRefSlow(size), memory_format, out); +} +namespace symint { + template >> + at::Tensor & empty_outf(at::IntArrayRef size, ::std::optional memory_format, at::Tensor & out) { + return at::_ops::empty_out::call(c10::fromIntArrayRefSlow(size), memory_format, out); + } +} + +// aten::empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_symint_out(at::Tensor & out, c10::SymIntArrayRef size, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_out::call(size, memory_format, out); +} +namespace symint { + template >> + at::Tensor & empty_out(at::Tensor & out, c10::SymIntArrayRef size, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_out::call(size, memory_format, out); + } +} + +// aten::empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_symint_outf(c10::SymIntArrayRef size, ::std::optional memory_format, at::Tensor & out) { + return at::_ops::empty_out::call(size, memory_format, out); +} +namespace symint { + template >> + at::Tensor & empty_outf(c10::SymIntArrayRef size, ::std::optional memory_format, at::Tensor & out) { + return at::_ops::empty_out::call(size, memory_format, out); + } +} + +// aten::empty.names_out(int[] size, *, Dimname[]? names, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_out(at::Tensor & out, at::IntArrayRef size, ::std::optional names, ::std::optional memory_format=::std::nullopt) { + return at::_ops::empty_names_out::call(size, names, memory_format, out); +} +// aten::empty.names_out(int[] size, *, Dimname[]? names, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & empty_outf(at::IntArrayRef size, ::std::optional names, ::std::optional memory_format, at::Tensor & out) { + return at::_ops::empty_names_out::call(size, names, memory_format, out); +} + +} diff --git a/shared/package-files/0b/0bbce9feaaf056eca35b6703b36e54d420a29c6db564dfecd0444e168cc90be4/_functions.py b/shared/package-files/0b/0bbce9feaaf056eca35b6703b36e54d420a29c6db564dfecd0444e168cc90be4/_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..ef232aa1805475c50c6f3745cda77cad0477e290 --- /dev/null +++ b/shared/package-files/0b/0bbce9feaaf056eca35b6703b36e54d420a29c6db564dfecd0444e168cc90be4/_functions.py @@ -0,0 +1,135 @@ +import warnings +from itertools import chain +from typing import Optional + +import torch +from torch._utils import _get_device_index +from torch.autograd import Function +from torch.nn.parallel import comm + + +class Broadcast(Function): + @staticmethod + def forward(ctx, target_gpus, *inputs): + assert all( + i.device.type != "cpu" for i in inputs + ), "Broadcast function not implemented for CPU tensors" + target_gpus = [_get_device_index(x, True) for x in target_gpus] + ctx.target_gpus = target_gpus + if len(inputs) == 0: + return () + ctx.num_inputs = len(inputs) + ctx.input_device = inputs[0].get_device() + outputs = comm.broadcast_coalesced(inputs, ctx.target_gpus) + non_differentiables = [] + for idx, input_requires_grad in enumerate(ctx.needs_input_grad[1:]): + if not input_requires_grad: + non_differentiables.extend(output[idx] for output in outputs) + ctx.mark_non_differentiable(*non_differentiables) + return tuple(chain.from_iterable(outputs)) + + @staticmethod + def backward(ctx, *grad_outputs): + return (None,) + ReduceAddCoalesced.apply( + ctx.input_device, ctx.num_inputs, *grad_outputs + ) + + +class ReduceAddCoalesced(Function): + @staticmethod + def forward(ctx, destination, num_inputs, *grads): + ctx.target_gpus = [ + grads[i].get_device() for i in range(0, len(grads), num_inputs) + ] + + grads_ = [grads[i : i + num_inputs] for i in range(0, len(grads), num_inputs)] + return comm.reduce_add_coalesced(grads_, destination) + + @staticmethod + def backward(ctx, *grad_outputs): + return ( + None, + None, + ) + Broadcast.apply(ctx.target_gpus, *grad_outputs) + + +class Gather(Function): + @staticmethod + def forward(ctx, target_device, dim, *inputs): + assert all( + i.device.type != "cpu" for i in inputs + ), "Gather function not implemented for CPU tensors" + if target_device == "cpu": + ctx.target_device = "cpu" + else: + target_device = _get_device_index(target_device, True) + ctx.target_device = target_device + ctx.dim = dim + ctx.input_gpus = tuple(i.get_device() for i in inputs) + if all(t.dim() == 0 for t in inputs) and dim == 0: + inputs = tuple(t.view(1) for t in inputs) + warnings.warn( + "Was asked to gather along dimension 0, but all " + "input tensors were scalars; will instead unsqueeze " + "and return a vector." + ) + ctx.unsqueezed_scalar = True + else: + ctx.unsqueezed_scalar = False + ctx.input_sizes = tuple(i.size(ctx.dim) for i in inputs) + return comm.gather(inputs, ctx.dim, ctx.target_device) + + @staticmethod + def backward(ctx, grad_output): + scattered_grads = Scatter.apply( + ctx.input_gpus, ctx.input_sizes, ctx.dim, grad_output + ) + if ctx.unsqueezed_scalar: + scattered_grads = tuple(g[0] for g in scattered_grads) + return (None, None) + scattered_grads + + +class Scatter(Function): + @staticmethod + def forward(ctx, target_gpus, chunk_sizes, dim, input): + target_gpus = [_get_device_index(x, True) for x in target_gpus] + ctx.dim = dim + ctx.input_device = input.get_device() if input.device.type != "cpu" else -1 + streams = None + if torch.cuda.is_available() and ctx.input_device == -1: + # Perform CPU to GPU copies in a background stream + streams = [ + _get_stream(torch.device("cuda", device)) for device in target_gpus + ] + outputs = comm.scatter(input, target_gpus, chunk_sizes, ctx.dim, streams) + # Synchronize with the copy stream + if streams is not None: + for i, output in enumerate(outputs): + with torch.cuda.device(target_gpus[i]): + main_stream = torch.cuda.current_stream() + main_stream.wait_stream(streams[i]) + output.record_stream(main_stream) + return outputs + + @staticmethod + def backward(ctx, *grad_output): + return None, None, None, Gather.apply(ctx.input_device, ctx.dim, *grad_output) + + +# background streams used for copying +_streams: Optional[list[Optional[torch.Stream]]] = None + + +def _get_stream(device: torch.device): + """Get a background stream for copying between CPU and target device.""" + global _streams + if device.type == "cpu": + return None + device_mod = getattr(torch, device.type, None) + if device_mod is None: + return None + if _streams is None: + _streams = [None] * device_mod.device_count() + if _streams[device.index] is None: + _streams[device.index] = device_mod.Stream(device.index) + return _streams[device.index] diff --git a/shared/package-files/0b/0bbe275e4b95635704fef8f75b3228496d9349ae12dd9278d4f3f268ebd07545/NestedTensorUtils.h b/shared/package-files/0b/0bbe275e4b95635704fef8f75b3228496d9349ae12dd9278d4f3f268ebd07545/NestedTensorUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..6a66a7f43e820af24aa392626b304a6059b9900d --- /dev/null +++ b/shared/package-files/0b/0bbe275e4b95635704fef8f75b3228496d9349ae12dd9278d4f3f268ebd07545/NestedTensorUtils.h @@ -0,0 +1,449 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS + +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include + +namespace at::native { +struct NestedTensorImpl; + +// The following functions are used to construct nested tensors from buffers and +// metadata. + +inline at::Tensor wrap_buffer(const at::Tensor& buffer, const at::Tensor& nested_sizes) { + TORCH_CHECK( + buffer.dim() == 1, + "Expected given buffer to be 1dim, but got ", + buffer.dim(), + " instead."); + TORCH_CHECK( + buffer.is_contiguous(), "Expected given buffer to be contiguous."); + return at::detail::make_tensor( + buffer, nested_sizes); +} + +// TODO: Figure out if we need a non-moving wrap_buffer() +inline at::Tensor wrap_buffer( + const at::Tensor& buffer, + at::Tensor nested_sizes, + at::Tensor nested_strides, + at::Tensor storage_offsets) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + buffer.is_contiguous(), "Given buffer must be contiguous."); + return at::detail::make_tensor( + buffer, + std::move(nested_sizes), + std::move(nested_strides), + std::move(storage_offsets)); +} + +inline at::Tensor get_buffer(const at::Tensor& tensor) { + return get_nested_tensor_impl(tensor)->get_buffer(); +} + +/** + * Create a new nested tensor that is a view of a base nested tensor + * + * create_view_tensor calls a specialized constructor that copies the + * keys from base onto the new view tensor being created. + * The storage is shared between the base and the returned view tensor + * + * All callers of this helper must: + * - Only return a view of the input + * - Must be explicit and define a derivative + * + * @param base Base tensor to construct view from. + * @param nested_sizes View tensors' sizes. + * @param nested_strides View tensors' strides. + * @param storage_offsets View tensors' offsets. + * @return A newly constructed view tensor + */ +inline at::Tensor create_nested_view_tensor( + const at::Tensor& base, + at::Tensor nested_sizes, + at::Tensor nested_strides, + at::Tensor storage_offsets) { + TORCH_INTERNAL_ASSERT( + base.is_nested(), + "This function can only be used to create nested tensor views"); + TORCH_INTERNAL_ASSERT( + c10::impl::tls_local_dispatch_key_set().excluded_.has( + c10::DispatchKey::AutogradFunctionality), + "Creating a non differentiable nested tensor view in a CompositeImplicit function is not allowed."); + return at::detail::make_tensor( + c10::TensorImpl::VIEW, + base, + std::move(nested_sizes), + std::move(nested_strides), + std::move(storage_offsets)); +} +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// Helper functions for getting information about a nested tensor's shape. + +int64_t get_consistent_last_dim_of_nested_tensor(const NestedTensorImpl& nt); + +// The sizes of the underlying tensors +inline std::vector NestedTensor_get_sizes( + const NestedTensorImpl* self_ptr) { + int64_t ntensors = self_ptr->size(0); + std::vector sizes(ntensors); + if (ntensors == 0) { + return sizes; + } + const Tensor& sizemat = self_ptr->get_nested_sizes(); + int64_t orig_dim = sizemat.size(1); + // nesting scalars has empty sizes + if (orig_dim == 0) { + return sizes; + } + const int64_t* sizemat_ptr = sizemat.const_data_ptr(); + + for (const auto i : c10::irange(ntensors)) { + sizes[i] = IntArrayRef(sizemat_ptr, sizemat_ptr + orig_dim); + sizemat_ptr += orig_dim; + } + return sizes; +} + +TORCH_API std::vector NestedTensor_get_max_size( + const NestedTensorImpl& nt); + +std::vector NestedTensor_get_max_size_from_size_tensor( + const Tensor& sizes); + +inline std::vector NestedTensor_get_sizes(const at::Tensor& self) { + const NestedTensorImpl* self_ptr = get_nested_tensor_impl(self); + return NestedTensor_get_sizes(self_ptr); +} +// The strides of the underlying tensors +inline std::vector NestedTensor_get_strides( + const NestedTensorImpl* self_ptr) { + int64_t ntensors = self_ptr->size(0); + std::vector strides(ntensors); + if (ntensors == 0) { + return strides; + } + const Tensor& stridemat = self_ptr->get_nested_strides(); + int64_t orig_dim = stridemat.size(1); + // nesting scalars has empty strides + if (orig_dim == 0) { + return strides; + } + const int64_t* stridemat_ptr = stridemat.const_data_ptr(); + for (const auto i : c10::irange(ntensors)) { + strides[i] = IntArrayRef(stridemat_ptr, stridemat_ptr + orig_dim); + stridemat_ptr += orig_dim; + } + return strides; +} + +inline std::vector NestedTensor_get_strides( + const at::Tensor& self) { + const NestedTensorImpl* self_ptr = get_nested_tensor_impl(self); + return NestedTensor_get_strides(self_ptr); +} + +inline void check_numel_equals_buffer_size(const at::Tensor& self) { + auto self_impl = get_nested_tensor_impl(self); + TORCH_CHECK( + self.numel() == static_cast(self_impl->get_buffer_size()), + "Number of elements in nested tensor must match number of elements in buffer."); +} + +inline void check_numel_equals_buffer_size(const NestedTensorImpl* self_ptr) { + TORCH_CHECK( + self_ptr->numel() == static_cast(self_ptr->get_buffer_size()), + "Number of elements in nested tensor must match number of elements in buffer."); +} + +// Helper function to get size / stride / offset for a nested/normal tensor. +inline IntArrayRef get_size_for_index(const Tensor& tensor, int64_t i) { + if (tensor.is_nested()) { + std::vector tensor_sizes = + NestedTensor_get_sizes(get_nested_tensor_impl(tensor)); + return tensor_sizes[i]; + } else { + return tensor.sizes().slice(1); + } +} + +inline IntArrayRef get_stride_for_index(const Tensor& tensor, int64_t i) { + if (tensor.is_nested()) { + std::vector tensor_strides = + NestedTensor_get_strides(get_nested_tensor_impl(tensor)); + return tensor_strides[i]; + } else { + return tensor.strides().slice(1); + } +} + +inline int64_t get_offset_for_index(const Tensor& tensor, int64_t i) { + if (tensor.is_nested()) { + int64_t* offsets_ptr = get_nested_tensor_impl(tensor) + ->get_storage_offsets() + .data_ptr(); + return offsets_ptr[i]; + + } else { + int64_t offset = tensor.storage_offset(); + return offset + tensor.strides()[0] * i; + } +} +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Data structures and functions for generically applying a function on a nested +// tensor. +namespace impl { + +template +struct NestedNode { + NestedNode() = delete; + explicit NestedNode(std::vector children) + : _is_leaf(false), _children(std::move(children)) {} + explicit NestedNode(TensorList children) + : _is_leaf(false), _children(children.vec()) {} + explicit NestedNode(T payload) + : _is_leaf(true), _payload(std::move(payload)) {} + NestedNode(const NestedNode&) = delete; + NestedNode& operator=(const NestedNode&) = delete; + NestedNode(NestedNode&&) noexcept = default; + NestedNode& operator=(NestedNode&&) noexcept = default; + ~NestedNode() = default; + inline bool is_leaf() const { + return _is_leaf; + } + inline size_t degree() const { + return _children.size(); + } + inline const std::vector unbind() const { + return _children; + } + inline T children(size_t i) const { + return _children[i]; + } + inline const T& payload() const { + return _payload; + } + inline T& payload() { + return _payload; + } + + private: + bool _is_leaf; + std::vector _children; + T _payload{}; +}; + +using TensorNode = NestedNode; + +template +class _map; + +template +class _map> { + public: + static A function_one(const F& fn, const Args&... nested_node) { + return fn(nested_node...); + } + static NestedNode function( + const F& fn, + const NestedNode&... nested_node) { + size_t degree = 0; + bool all_leaf = true; + c10::guts::tuple_map( + std::forward_as_tuple(nested_node...), [&all_leaf, °ree](auto n) { + all_leaf = all_leaf && (n.is_leaf()); + if (degree > 1 && n.degree() > 1) { + TORCH_CHECK( + degree == n.degree(), "NestedNodes must match in degree."); + } + if (n.degree() > degree) { + degree = n.degree(); + } + return nullptr; + }); + // All NestedNodes just wrap regular objects. + if (all_leaf) { + return NestedNode(std::forward(fn)(nested_node.payload()...)); + } + // Some NestedNodes wrap regular Tensors, some NestedTensors and some other + // types. + std::vector result; + for (size_t i = 0; i < degree; i++) { + auto children = c10::guts::tuple_map( + std::forward_as_tuple(nested_node...), [&i](auto a) { + static_assert( + c10::guts::is_instantiation_of::value, + "Internal error."); + // Broadcast regular arguments across NestedTensor constituents. + // This could be a Tensor, integer or anything else really. + if (a.is_leaf()) { + return a.payload(); + } + // Broadcast NestedTensors with one constituent. + if (a.degree() == 1 && !a.is_leaf()) { + return a.children(0); + } + TORCH_CHECK(a.degree() > 0, "Internal assert."); + return a.children(i); + }); + std::apply( + [&result, &fn](Args... filtered) { + result.emplace_back(function_one(fn, filtered...)); + }, + std::move(children)); + } + return NestedNode(std::move(result)); + } +}; + +// TODO: Add static assert to verify lambda arguments match nested_node types +template +static inline NestedNode< + typename c10::guts::infer_function_traits::type::return_type> +map(F&& fn, const NestedNode&... nested_node) { + return _map< + F, + typename c10::guts::infer_function_traits::type::return_type, + typename c10::guts::infer_function_traits::type::parameter_types>:: + function(std::forward(fn), nested_node...); +} + +inline TensorNode get_nested_tensor_structure(at::Tensor tensor) { + if (get_nested_tensor_impl_or_null(tensor) == nullptr) { + return TensorNode(std::move(tensor)); + } + return TensorNode(tensor.unbind()); +} + +inline Tensor wrap_tensor_node( + TensorNode tensor_node, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) { + TORCH_CHECK( + !tensor_node.is_leaf(), "Expected TensorNode to wrap a list of Tensors."); + TensorOptions options_ = + TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory( + pin_memory); + if (tensor_node.degree() == 0) { + return wrap_buffer(ones({0}, dtype, layout, device), ones({})); + } + + // Fast path: if all tensors are on CPU, have contiguous memory, and the same + // dtype, copying can be done much faster. + bool all_tensors_cpu = true; + bool all_tensors_contiguous = true; + bool all_tensors_same_dtype = true; + auto first_dtype = tensor_node.children(0).dtype(); + std::vector start_offsets(tensor_node.degree()); + start_offsets[0] = 0; + long total_size = 0; + for (const auto i : c10::irange(tensor_node.degree())) { + all_tensors_cpu = all_tensors_cpu && tensor_node.children(i).is_cpu(); + all_tensors_contiguous = + all_tensors_contiguous && tensor_node.children(i).is_contiguous(); + all_tensors_same_dtype = all_tensors_same_dtype && + (first_dtype == tensor_node.children(i).dtype()); + if (!(all_tensors_cpu && all_tensors_contiguous && + all_tensors_same_dtype)) { + break; + } + if (i > 0) { + start_offsets[i] = + start_offsets[i - 1] + tensor_node.children(i - 1).numel(); + } + total_size += tensor_node.children(i).numel(); + } + + TensorOptions options; + Tensor nt_buffer, nt_sizes; + if (all_tensors_cpu && all_tensors_contiguous && all_tensors_same_dtype) { + nt_buffer = at::empty({total_size}, tensor_node.children(0).options()); + nt_sizes = at::empty( + {static_cast(tensor_node.degree()), + static_cast(tensor_node.children(0).sizes().size())}, + TensorOptions().dtype(kLong)); + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + at::ScalarType::Half, + at::ScalarType::Bool, + at::ScalarType::BFloat16, + c10::typeMetaToScalarType(first_dtype), + "create_nt_buffer", + [&]() { + at::parallel_for( + 0, tensor_node.degree(), 1, [&](int64_t begin, int64_t end) { + for (int64_t i = begin; i < end; ++i) { + // Only try copying memory if there is more than 0 elements + // for a certain tensor + if (tensor_node.children(i).numel() > 0) { + memcpy( + nt_buffer.mutable_data_ptr() + start_offsets[i], + tensor_node.children(i).const_data_ptr(), + tensor_node.children(i).numel() * sizeof(scalar_t)); + } + } + }); + }); + long sizes_offset = 0; + for (size_t i = 0; i < tensor_node.degree(); ++i) { + auto tensor_sizes = tensor_node.children(i).sizes(); + for (int64_t tensor_size : tensor_sizes) { + nt_sizes.mutable_data_ptr()[sizes_offset++] = tensor_size; + } + } + options = nt_buffer.options().merge_in(options_); + } else { // Slow path + std::vector flat_tensors; + std::vector sizes; + for (const auto i : c10::irange(tensor_node.degree())) { + flat_tensors.push_back(tensor_node.children(i).reshape(-1).contiguous()); + sizes.push_back( + tensor(c10::IntArrayRef(tensor_node.children(i).sizes()))); + } + options = flat_tensors[0].options().merge_in(options_); + nt_buffer = at::cat(flat_tensors); + nt_sizes = at::native::stack(sizes); + } + + return wrap_buffer(nt_buffer.to(options), nt_sizes); +} + +} // namespace impl + +// This function is meant to ease rapid operator coverage for +// NestedTensor kernels. It is not meant to be efficient. Use it judiciously. +template +inline at::Tensor map_nested_tensor(F&& fn, A... a) { + return wrap_tensor_node( + impl::map(std::forward(fn), impl::get_nested_tensor_structure(a)...), + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt); +} + +} // namespace at::native diff --git a/shared/package-files/0b/0bc7ac4707f81304b4fa6ad3577daa8dde5c9d51ac8652677329e4b9c06674b9/_foreach_clamp_max_compositeexplicitautograd_dispatch.h b/shared/package-files/0b/0bc7ac4707f81304b4fa6ad3577daa8dde5c9d51ac8652677329e4b9c06674b9/_foreach_clamp_max_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b8346f746faeedeef344832b87830437aa882cef --- /dev/null +++ b/shared/package-files/0b/0bc7ac4707f81304b4fa6ad3577daa8dde5c9d51ac8652677329e4b9c06674b9/_foreach_clamp_max_compositeexplicitautograd_dispatch.h @@ -0,0 +1,34 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::vector _foreach_clamp_max(at::TensorList self, const at::Scalar & scalar); +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out); +TORCH_API void _foreach_clamp_max_(at::TensorList self, const at::Scalar & scalar); +TORCH_API ::std::vector _foreach_clamp_max(at::TensorList self, at::TensorList other); +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::TensorList other); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, at::TensorList other, at::TensorList out); +TORCH_API void _foreach_clamp_max_(at::TensorList self, at::TensorList other); +TORCH_API ::std::vector _foreach_clamp_max(at::TensorList self, at::ArrayRef scalars); +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::ArrayRef scalars); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, at::ArrayRef scalars, at::TensorList out); +TORCH_API void _foreach_clamp_max_(at::TensorList self, at::ArrayRef scalars); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/0b/0bc936bcedb71fa492ba3908ccda381be8fa1b62ab74d48e1fd7992e96b62962/fuser_method_mappings.cpython-311.pyc b/shared/package-files/0b/0bc936bcedb71fa492ba3908ccda381be8fa1b62ab74d48e1fd7992e96b62962/fuser_method_mappings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a16c11ee27106eedf0dfff748ad56edcbfb2b0 Binary files /dev/null and b/shared/package-files/0b/0bc936bcedb71fa492ba3908ccda381be8fa1b62ab74d48e1fd7992e96b62962/fuser_method_mappings.cpython-311.pyc differ diff --git a/shared/package-files/0b/0bc98f197feece998f0a5b1008802d75fdeb162ef5abc6f2453255b2ac9ff8f4/socket.h b/shared/package-files/0b/0bc98f197feece998f0a5b1008802d75fdeb162ef5abc6f2453255b2ac9ff8f4/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..81659f11f049f3bd2fd7a2957febf2dd9af3ab95 --- /dev/null +++ b/shared/package-files/0b/0bc98f197feece998f0a5b1008802d75fdeb162ef5abc6f2453255b2ac9ff8f4/socket.h @@ -0,0 +1,105 @@ +// Copyright (c) Meta Platforms, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace c10d::detail { + +class SocketOptions { + public: + SocketOptions& prefer_ipv6(bool value) noexcept { + prefer_ipv6_ = value; + + return *this; + } + + bool prefer_ipv6() const noexcept { + return prefer_ipv6_; + } + + SocketOptions& connect_timeout(std::chrono::milliseconds value) noexcept { + connect_timeout_ = value; + + return *this; + } + + std::chrono::milliseconds connect_timeout() const noexcept { + return connect_timeout_; + } + + // Sets the backoff policy to use for socket connect ops. + SocketOptions& connect_backoff(std::shared_ptr value) noexcept { + connect_backoff_ = std::move(value); + + return *this; + } + + const std::shared_ptr& connect_backoff() const noexcept { + return connect_backoff_; + } + + private: + bool prefer_ipv6_ = true; + std::chrono::milliseconds connect_timeout_{std::chrono::seconds{30}}; + std::shared_ptr connect_backoff_{ + std::make_shared(std::chrono::milliseconds(1000))}; +}; + +class SocketImpl; + +class Socket { + public: + // This function initializes the underlying socket library and must be called + // before any other socket function. + static void initialize(); + + static Socket listen(std::uint16_t port, const SocketOptions& opts = {}); + + static Socket listenFromFd(int fd, std::uint16_t expected_port); + + static Socket connect( + const std::string& host, + std::uint16_t port, + const SocketOptions& opts = {}); + + Socket() noexcept = default; + + Socket(const Socket& other) = delete; + + Socket& operator=(const Socket& other) = delete; + + Socket(Socket&& other) noexcept; + + Socket& operator=(Socket&& other) noexcept; + + ~Socket(); + + Socket accept() const; + + int handle() const noexcept; + + std::uint16_t port() const; + + bool waitForInput(std::chrono::milliseconds timeout); + + std::string repr() const; + + private: + explicit Socket(std::unique_ptr&& impl) noexcept; + + std::unique_ptr impl_; +}; +} // namespace c10d::detail diff --git a/shared/package-files/0b/0bcad0a2c5591776844b023822f662b5deb4b1d1a8bfa92f0a590302d9f1dce7/NativeFunction.h b/shared/package-files/0b/0bcad0a2c5591776844b023822f662b5deb4b1d1a8bfa92f0a590302d9f1dce7/NativeFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..a5441ad85d1d5e28c4e31dd3f0dc7f66dfbff9e7 --- /dev/null +++ b/shared/package-files/0b/0bcad0a2c5591776844b023822f662b5deb4b1d1a8bfa92f0a590302d9f1dce7/NativeFunction.h @@ -0,0 +1,17 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +${extra_includes} + +${native_function_declarations} diff --git a/shared/package-files/0b/0bce6ca0db82c8c8b21bddcb1f00c05b966bc36fa0e2a2431c94c1d997e16d28/test_multidigraph.cpython-311.pyc b/shared/package-files/0b/0bce6ca0db82c8c8b21bddcb1f00c05b966bc36fa0e2a2431c94c1d997e16d28/test_multidigraph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0a2481c4077087c11d6a92dc93f7ce836e2a327 Binary files /dev/null and b/shared/package-files/0b/0bce6ca0db82c8c8b21bddcb1f00c05b966bc36fa0e2a2431c94c1d997e16d28/test_multidigraph.cpython-311.pyc differ diff --git a/shared/package-files/0b/0bcf26b14709575694a8aed8057cf964051b91979f83a7afc618c7ad34ce88eb/_msvccompiler.py b/shared/package-files/0b/0bcf26b14709575694a8aed8057cf964051b91979f83a7afc618c7ad34ce88eb/_msvccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..97b067c68611694e2c291eb77c156c016285ec64 --- /dev/null +++ b/shared/package-files/0b/0bcf26b14709575694a8aed8057cf964051b91979f83a7afc618c7ad34ce88eb/_msvccompiler.py @@ -0,0 +1,604 @@ +"""distutils._msvccompiler + +Contains MSVCCompiler, an implementation of the abstract CCompiler class +for Microsoft Visual Studio 2015. + +This module requires VS 2015 or later. +""" + +# Written by Perry Stoll +# hacked by Robin Becker and Thomas Heller to do a better job of +# finding DevStudio (through the registry) +# ported to VS 2005 and VS 2008 by Christian Heimes +# ported to VS 2015 by Steve Dower + +import contextlib +import os +import subprocess +import unittest.mock as mock +import warnings + +with contextlib.suppress(ImportError): + import winreg + +from itertools import count + +from ._log import log +from .ccompiler import CCompiler, gen_lib_options +from .errors import ( + CompileError, + DistutilsExecError, + DistutilsPlatformError, + LibError, + LinkError, +) +from .util import get_host_platform, get_platform + + +def _find_vc2015(): + try: + key = winreg.OpenKeyEx( + winreg.HKEY_LOCAL_MACHINE, + r"Software\Microsoft\VisualStudio\SxS\VC7", + access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY, + ) + except OSError: + log.debug("Visual C++ is not registered") + return None, None + + best_version = 0 + best_dir = None + with key: + for i in count(): + try: + v, vc_dir, vt = winreg.EnumValue(key, i) + except OSError: + break + if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir): + try: + version = int(float(v)) + except (ValueError, TypeError): + continue + if version >= 14 and version > best_version: + best_version, best_dir = version, vc_dir + return best_version, best_dir + + +def _find_vc2017(): + """Returns "15, path" based on the result of invoking vswhere.exe + If no install is found, returns "None, None" + + The version is returned to avoid unnecessarily changing the function + result. It may be ignored when the path is not None. + + If vswhere.exe is not available, by definition, VS 2017 is not + installed. + """ + root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles") + if not root: + return None, None + + variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64' + suitable_components = ( + f"Microsoft.VisualStudio.Component.VC.Tools.{variant}", + "Microsoft.VisualStudio.Workload.WDExpress", + ) + + for component in suitable_components: + # Workaround for `-requiresAny` (only available on VS 2017 > 15.6) + with contextlib.suppress( + subprocess.CalledProcessError, OSError, UnicodeDecodeError + ): + path = ( + subprocess.check_output([ + os.path.join( + root, "Microsoft Visual Studio", "Installer", "vswhere.exe" + ), + "-latest", + "-prerelease", + "-requires", + component, + "-property", + "installationPath", + "-products", + "*", + ]) + .decode(encoding="mbcs", errors="strict") + .strip() + ) + + path = os.path.join(path, "VC", "Auxiliary", "Build") + if os.path.isdir(path): + return 15, path + + return None, None # no suitable component found + + +PLAT_SPEC_TO_RUNTIME = { + 'x86': 'x86', + 'x86_amd64': 'x64', + 'x86_arm': 'arm', + 'x86_arm64': 'arm64', +} + + +def _find_vcvarsall(plat_spec): + # bpo-38597: Removed vcruntime return value + _, best_dir = _find_vc2017() + + if not best_dir: + best_version, best_dir = _find_vc2015() + + if not best_dir: + log.debug("No suitable Visual C++ version found") + return None, None + + vcvarsall = os.path.join(best_dir, "vcvarsall.bat") + if not os.path.isfile(vcvarsall): + log.debug("%s cannot be found", vcvarsall) + return None, None + + return vcvarsall, None + + +def _get_vc_env(plat_spec): + if os.getenv("DISTUTILS_USE_SDK"): + return {key.lower(): value for key, value in os.environ.items()} + + vcvarsall, _ = _find_vcvarsall(plat_spec) + if not vcvarsall: + raise DistutilsPlatformError( + 'Microsoft Visual C++ 14.0 or greater is required. ' + 'Get it with "Microsoft C++ Build Tools": ' + 'https://visualstudio.microsoft.com/visual-cpp-build-tools/' + ) + + try: + out = subprocess.check_output( + f'cmd /u /c "{vcvarsall}" {plat_spec} && set', + stderr=subprocess.STDOUT, + ).decode('utf-16le', errors='replace') + except subprocess.CalledProcessError as exc: + log.error(exc.output) + raise DistutilsPlatformError(f"Error executing {exc.cmd}") + + env = { + key.lower(): value + for key, _, value in (line.partition('=') for line in out.splitlines()) + if key and value + } + + return env + + +def _find_exe(exe, paths=None): + """Return path to an MSVC executable program. + + Tries to find the program in several places: first, one of the + MSVC program search paths from the registry; next, the directories + in the PATH environment variable. If any of those work, return an + absolute path that is known to exist. If none of them work, just + return the original program name, 'exe'. + """ + if not paths: + paths = os.getenv('path').split(os.pathsep) + for p in paths: + fn = os.path.join(os.path.abspath(p), exe) + if os.path.isfile(fn): + return fn + return exe + + +_vcvars_names = { + 'win32': 'x86', + 'win-amd64': 'amd64', + 'win-arm32': 'arm', + 'win-arm64': 'arm64', +} + + +def _get_vcvars_spec(host_platform, platform): + """ + Given a host platform and platform, determine the spec for vcvarsall. + + Uses the native MSVC host if the host platform would need expensive + emulation for x86. + + >>> _get_vcvars_spec('win-arm64', 'win32') + 'arm64_x86' + >>> _get_vcvars_spec('win-arm64', 'win-amd64') + 'arm64_amd64' + + Otherwise, always cross-compile from x86 to work with the + lighter-weight MSVC installs that do not include native 64-bit tools. + + >>> _get_vcvars_spec('win32', 'win32') + 'x86' + >>> _get_vcvars_spec('win-arm32', 'win-arm32') + 'x86_arm' + >>> _get_vcvars_spec('win-amd64', 'win-arm64') + 'x86_arm64' + """ + if host_platform != 'win-arm64': + host_platform = 'win32' + vc_hp = _vcvars_names[host_platform] + vc_plat = _vcvars_names[platform] + return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}' + + +class MSVCCompiler(CCompiler): + """Concrete class that implements an interface to Microsoft Visual C++, + as defined by the CCompiler abstract class.""" + + compiler_type = 'msvc' + + # Just set this so CCompiler's constructor doesn't barf. We currently + # don't use the 'set_executables()' bureaucracy provided by CCompiler, + # as it really isn't necessary for this sort of single-compiler class. + # Would be nice to have a consistent interface with UnixCCompiler, + # though, so it's worth thinking about. + executables = {} + + # Private class data (need to distinguish C from C++ source for compiler) + _c_extensions = ['.c'] + _cpp_extensions = ['.cc', '.cpp', '.cxx'] + _rc_extensions = ['.rc'] + _mc_extensions = ['.mc'] + + # Needed for the filename generation methods provided by the + # base class, CCompiler. + src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions + res_extension = '.res' + obj_extension = '.obj' + static_lib_extension = '.lib' + shared_lib_extension = '.dll' + static_lib_format = shared_lib_format = '%s%s' + exe_extension = '.exe' + + def __init__(self, verbose=False, dry_run=False, force=False): + super().__init__(verbose, dry_run, force) + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.initialized = False + + @classmethod + def _configure(cls, vc_env): + """ + Set class-level include/lib dirs. + """ + cls.include_dirs = cls._parse_path(vc_env.get('include', '')) + cls.library_dirs = cls._parse_path(vc_env.get('lib', '')) + + @staticmethod + def _parse_path(val): + return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir] + + def initialize(self, plat_name=None): + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + if plat_name not in _vcvars_names: + raise DistutilsPlatformError( + f"--plat-name must be one of {tuple(_vcvars_names)}" + ) + + plat_spec = _get_vcvars_spec(get_host_platform(), plat_name) + + vc_env = _get_vc_env(plat_spec) + if not vc_env: + raise DistutilsPlatformError( + "Unable to find a compatible Visual Studio installation." + ) + self._configure(vc_env) + + self._paths = vc_env.get('path', '') + paths = self._paths.split(os.pathsep) + self.cc = _find_exe("cl.exe", paths) + self.linker = _find_exe("link.exe", paths) + self.lib = _find_exe("lib.exe", paths) + self.rc = _find_exe("rc.exe", paths) # resource compiler + self.mc = _find_exe("mc.exe", paths) # message compiler + self.mt = _find_exe("mt.exe", paths) # message compiler + + self.preprocess_options = None + # bpo-38597: Always compile with dynamic linking + # Future releases of Python 3.x will include all past + # versions of vcruntime*.dll for compatibility. + self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD'] + + self.compile_options_debug = [ + '/nologo', + '/Od', + '/MDd', + '/Zi', + '/W3', + '/D_DEBUG', + ] + + ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG'] + + ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL'] + + self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1'] + self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1'] + self.ldflags_shared = [ + *ldflags, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_shared_debug = [ + *ldflags_debug, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_static = [*ldflags] + self.ldflags_static_debug = [*ldflags_debug] + + self._ldflags = { + (CCompiler.EXECUTABLE, None): self.ldflags_exe, + (CCompiler.EXECUTABLE, False): self.ldflags_exe, + (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug, + (CCompiler.SHARED_OBJECT, None): self.ldflags_shared, + (CCompiler.SHARED_OBJECT, False): self.ldflags_shared, + (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug, + (CCompiler.SHARED_LIBRARY, None): self.ldflags_static, + (CCompiler.SHARED_LIBRARY, False): self.ldflags_static, + (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug, + } + + self.initialized = True + + # -- Worker methods ------------------------------------------------ + + @property + def out_extensions(self): + return { + **super().out_extensions, + **{ + ext: self.res_extension + for ext in self._rc_extensions + self._mc_extensions + }, + } + + def compile( # noqa: C901 + self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + if not self.initialized: + self.initialize() + compile_info = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + macros, objects, extra_postargs, pp_opts, build = compile_info + + compile_opts = extra_preargs or [] + compile_opts.append('/c') + if debug: + compile_opts.extend(self.compile_options_debug) + else: + compile_opts.extend(self.compile_options) + + add_cpp_opts = False + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + if debug: + # pass the full pathname to MSVC in debug mode, + # this allows the debugger to find the source file + # without asking the user to browse for it + src = os.path.abspath(src) + + if ext in self._c_extensions: + input_opt = "/Tc" + src + elif ext in self._cpp_extensions: + input_opt = "/Tp" + src + add_cpp_opts = True + elif ext in self._rc_extensions: + # compile .RC to .RES file + input_opt = src + output_opt = "/fo" + obj + try: + self.spawn([self.rc] + pp_opts + [output_opt, input_opt]) + except DistutilsExecError as msg: + raise CompileError(msg) + continue + elif ext in self._mc_extensions: + # Compile .MC to .RC file to .RES file. + # * '-h dir' specifies the directory for the + # generated include file + # * '-r dir' specifies the target directory of the + # generated RC file and the binary message resource + # it includes + # + # For now (since there are no options to change this), + # we use the source-directory for the include file and + # the build directory for the RC file and message + # resources. This works at least for win32all. + h_dir = os.path.dirname(src) + rc_dir = os.path.dirname(obj) + try: + # first compile .MC to .RC and .H file + self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src]) + base, _ = os.path.splitext(os.path.basename(src)) + rc_file = os.path.join(rc_dir, base + '.rc') + # then compile .RC to .RES file + self.spawn([self.rc, "/fo" + obj, rc_file]) + + except DistutilsExecError as msg: + raise CompileError(msg) + continue + else: + # how to handle this file? + raise CompileError(f"Don't know how to compile {src} to {obj}") + + args = [self.cc] + compile_opts + pp_opts + if add_cpp_opts: + args.append('/EHsc') + args.extend((input_opt, "/Fo" + obj)) + args.extend(extra_postargs) + + try: + self.spawn(args) + except DistutilsExecError as msg: + raise CompileError(msg) + + return objects + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + output_filename = self.library_filename(output_libname, output_dir=output_dir) + + if self._need_link(objects, output_filename): + lib_args = objects + ['/OUT:' + output_filename] + if debug: + pass # XXX what goes here? + try: + log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args)) + self.spawn([self.lib] + lib_args) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + + if runtime_library_dirs: + self.warn( + "I don't know what to do with 'runtime_library_dirs': " + + str(runtime_library_dirs) + ) + + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + ldflags = self._ldflags[target_desc, debug] + + export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])] + + ld_args = ( + ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename] + ) + + # The MSVC linker generates .lib and .exp files, which cannot be + # suppressed by any linker switches. The .lib files may even be + # needed! Make sure they are generated in the temporary build + # directory. Since they have different names for debug and release + # builds, they can go into the same directory. + build_temp = os.path.dirname(objects[0]) + if export_symbols is not None: + (dll_name, dll_ext) = os.path.splitext( + os.path.basename(output_filename) + ) + implib_file = os.path.join(build_temp, self.library_filename(dll_name)) + ld_args.append('/IMPLIB:' + implib_file) + + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + + output_dir = os.path.dirname(os.path.abspath(output_filename)) + self.mkpath(output_dir) + try: + log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args)) + self.spawn([self.linker] + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def spawn(self, cmd): + env = dict(os.environ, PATH=self._paths) + with self._fallback_spawn(cmd, env) as fallback: + return super().spawn(cmd, env=env) + return fallback.value + + @contextlib.contextmanager + def _fallback_spawn(self, cmd, env): + """ + Discovered in pypa/distutils#15, some tools monkeypatch the compiler, + so the 'env' kwarg causes a TypeError. Detect this condition and + restore the legacy, unsafe behavior. + """ + bag = type('Bag', (), {})() + try: + yield bag + except TypeError as exc: + if "unexpected keyword argument 'env'" not in str(exc): + raise + else: + return + warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.") + with mock.patch.dict('os.environ', env): + bag.value = super().spawn(cmd) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "/LIBPATH:" + dir + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError( + "don't know how to set runtime library search path for MSVC" + ) + + def library_option(self, lib): + return self.library_filename(lib) + + def find_library_file(self, dirs, lib, debug=False): + # Prefer a debugging library if found (and requested), but deal + # with it if we don't have one. + if debug: + try_names = [lib + "_d", lib] + else: + try_names = [lib] + for dir in dirs: + for name in try_names: + libfile = os.path.join(dir, self.library_filename(name)) + if os.path.isfile(libfile): + return libfile + else: + # Oops, didn't find it in *any* of 'dirs' + return None diff --git a/shared/package-files/0b/0bd16728abcde7d0dce48268264993330bc26c978b6b936a98bc2ef821810a18/bam_rmdup.c b/shared/package-files/0b/0bd16728abcde7d0dce48268264993330bc26c978b6b936a98bc2ef821810a18/bam_rmdup.c new file mode 100644 index 0000000000000000000000000000000000000000..293a140dcb40224b967b0d4c0d6d97594c74faad --- /dev/null +++ b/shared/package-files/0b/0bd16728abcde7d0dce48268264993330bc26c978b6b936a98bc2ef821810a18/bam_rmdup.c @@ -0,0 +1,325 @@ +/* bam_rmdup.c -- duplicate read detection. + + Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd. + Portions copyright (C) 2009 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/sam.h" +#include "sam_opts.h" +#include "samtools.h" +#include "bam.h" // for bam_get_library + +typedef bam1_t *bam1_p; + +#include "htslib/khash.h" +KHASH_SET_INIT_STR(name) +KHASH_MAP_INIT_INT64(pos, bam1_p) + +#define BUFFER_SIZE 0x40000 + +typedef struct { + uint64_t n_checked, n_removed; + khash_t(pos) *best_hash; +} lib_aux_t; +KHASH_MAP_INIT_STR(lib, lib_aux_t) + +typedef struct { + int n, max; + bam1_t **a; +} tmp_stack_t; + +static inline void stack_insert(tmp_stack_t *stack, bam1_t *b) +{ + if (stack->n == stack->max) { + stack->max = stack->max? stack->max<<1 : 0x10000; + stack->a = (bam1_t**)realloc(stack->a, sizeof(bam1_t*) * stack->max); + } + stack->a[stack->n++] = b; +} + +static inline int dump_best(tmp_stack_t *stack, samFile *out, sam_hdr_t *hdr) +{ + int i; + for (i = 0; i != stack->n; ++i) { + if (sam_write1(out, hdr, stack->a[i]) < 0) return -1; + bam_destroy1(stack->a[i]); + stack->a[i] = NULL; + } + stack->n = 0; + return 0; +} + +static inline void clear_stack(tmp_stack_t *stack) { + int i; + if (!stack->a) return; + for (i = 0; i != stack->n; ++i) { + bam_destroy1(stack->a[i]); + } +} + +static void clear_del_set(khash_t(name) *del_set) +{ + khint_t k; + for (k = kh_begin(del_set); k < kh_end(del_set); ++k) + if (kh_exist(del_set, k)) + free((char*)kh_key(del_set, k)); + kh_clear(name, del_set); +} + +static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) +{ + khint_t k = kh_get(lib, aux, lib); + if (k == kh_end(aux)) { + int ret; + char *p = strdup(lib); + lib_aux_t *q; + k = kh_put(lib, aux, p, &ret); + q = &kh_val(aux, k); + q->n_checked = q->n_removed = 0; + q->best_hash = kh_init(pos); + return q; + } else return &kh_val(aux, k); +} + +static void clear_best(khash_t(lib) *aux, int max) +{ + khint_t k; + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + if (kh_size(q->best_hash) >= max) + kh_clear(pos, q->best_hash); + } + } +} + +static inline int sum_qual(const bam1_t *b) +{ + int i, q; + uint8_t *qual = bam_get_qual(b); + for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; + return q; +} + +int bam_rmdup_core(samFile *in, sam_hdr_t *hdr, samFile *out) +{ + bam1_t *b = NULL; + int last_tid = -1, last_pos = -1, r; + tmp_stack_t stack; + khint_t k; + khash_t(lib) *aux = NULL; + khash_t(name) *del_set = NULL; + + memset(&stack, 0, sizeof(tmp_stack_t)); + aux = kh_init(lib); + del_set = kh_init(name); + b = bam_init1(); + if (!aux || !del_set || !b) { + perror(__func__); + goto fail; + } + + kh_resize(name, del_set, 4 * BUFFER_SIZE); + while ((r = sam_read1(in, hdr, b)) >= 0) { + bam1_core_t *c = &b->core; + if (c->tid != last_tid || last_pos != c->pos) { + if (dump_best(&stack, out, hdr) < 0) goto write_fail; // write the result + clear_best(aux, BUFFER_SIZE); + if (c->tid != last_tid) { + clear_best(aux, 0); + if (kh_size(del_set)) { // check + fprintf(stderr, "[bam_rmdup_core] %llu unmatched pairs\n", (long long)kh_size(del_set)); + clear_del_set(del_set); + } + if ((int)c->tid == -1) { // append unmapped reads + if (sam_write1(out, hdr, b) < 0) goto write_fail; + while ((r = sam_read1(in, hdr, b)) >= 0) { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } + break; + } + last_tid = c->tid; + fprintf(stderr, "[bam_rmdup_core] processing reference %s...\n", sam_hdr_tid2name(hdr, c->tid)); + } + } + if (!(c->flag&BAM_FPAIRED) || (c->flag&(BAM_FUNMAP|BAM_FMUNMAP)) || (c->mtid >= 0 && c->tid != c->mtid)) { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } else if (c->isize > 0) { // paired, head + uint64_t key = (uint64_t)c->pos<<32 | c->isize; + const char *lib; + lib_aux_t *q; + int ret; + lib = bam_get_library(hdr, b); + q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); + ++q->n_checked; + k = kh_put(pos, q->best_hash, key, &ret); + if (ret < 0) goto fail; + if (ret == 0) { // found in best_hash + bam1_t *p = kh_val(q->best_hash, k); + ++q->n_removed; + if (sum_qual(p) < sum_qual(b)) { // the current alignment is better; this can be accelerated in principle + kh_put(name, del_set, strdup(bam_get_qname(p)), &ret); // p will be removed + if (ret < 0) goto fail; + if (bam_copy1(p, b) == NULL) goto fail; // replaced as b + } else kh_put(name, del_set, strdup(bam_get_qname(b)), &ret); // b will be removed + if (ret < 0) goto fail; + if (ret == 0) + fprintf(stderr, "[bam_rmdup_core] inconsistent BAM file for pair '%s'. Continue anyway.\n", bam_get_qname(b)); + } else { // not found in best_hash + kh_val(q->best_hash, k) = bam_dup1(b); + stack_insert(&stack, kh_val(q->best_hash, k)); + } + } else { // paired, tail + k = kh_get(name, del_set, bam_get_qname(b)); + if (k != kh_end(del_set)) { + free((char*)kh_key(del_set, k)); + kh_del(name, del_set, k); + } else { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } + } + last_pos = c->pos; + } + if (r < -1) { + fprintf(stderr, "[%s] failed to read input file\n", __func__); + goto fail; + } + + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + if (dump_best(&stack, out, hdr) < 0) goto write_fail; + fprintf(stderr, "[bam_rmdup_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, + (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); + kh_destroy(pos, q->best_hash); + free((char*)kh_key(aux, k)); + kh_del(lib, aux, k); + } + } + kh_destroy(lib, aux); + + clear_del_set(del_set); + kh_destroy(name, del_set); + free(stack.a); + bam_destroy1(b); + return 0; + + write_fail: + print_error_errno("rmdup", "failed to write record"); + fail: + clear_stack(&stack); + free(stack.a); + if (aux) { + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + kh_destroy(pos, q->best_hash); + free((char*)kh_key(aux, k)); + } + } + kh_destroy(lib, aux); + } + if (del_set) { + clear_del_set(del_set); + kh_destroy(name, del_set); + } + bam_destroy1(b); + return 1; +} + +int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se); + +static int rmdup_usage(void) { + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: samtools rmdup [-sS] \n\n"); + fprintf(stderr, "Option: -s rmdup for SE reads\n"); + fprintf(stderr, " -S treat PE reads as SE in rmdup (force -s)\n"); + + sam_global_opt_help(stderr, "-....--."); + return 1; +} + +int bam_rmdup(int argc, char *argv[]) +{ + int c, ret, is_se = 0, force_se = 0; + samFile *in, *out; + sam_hdr_t *header; + char wmode[3] = {'w', 'b', 0}; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'), + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "sS", lopts, NULL)) >= 0) { + switch (c) { + case 's': is_se = 1; break; + case 'S': force_se = is_se = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': return rmdup_usage(); + } + } + if (optind + 2 > argc) + return rmdup_usage(); + + in = sam_open_format(argv[optind], "r", &ga.in); + if (!in) { + print_error_errno("rmdup", "failed to open \"%s\" for input", argv[optind]); + return 1; + } + header = sam_hdr_read(in); + if (header == NULL || sam_hdr_nref(header) == 0) { + fprintf(stderr, "[bam_rmdup] input SAM does not have header. Abort!\n"); + return 1; + } + + sam_open_mode(wmode+1, argv[optind+1], NULL); + out = sam_open_format(argv[optind+1], wmode, &ga.out); + if (!out) { + print_error_errno("rmdup", "failed to open \"%s\" for output", argv[optind+1]); + return 1; + } + if (sam_hdr_write(out, header) < 0) { + print_error_errno("rmdup", "failed to write header"); + return 1; + } + + if (is_se) ret = bam_rmdupse_core(in, header, out, force_se); + else ret = bam_rmdup_core(in, header, out); + + sam_hdr_destroy(header); + sam_close(in); + if (sam_close(out) < 0) { + fprintf(stderr, "[bam_rmdup] error closing output file\n"); + ret = 1; + } + return ret; +} diff --git a/shared/package-files/0b/0bd6036ecc6dc6238a5da8ebbffbbb2d9025acdf981a7f4dc80864db394261f0/_cast_Double.h b/shared/package-files/0b/0bd6036ecc6dc6238a5da8ebbffbbb2d9025acdf981a7f4dc80864db394261f0/_cast_Double.h new file mode 100644 index 0000000000000000000000000000000000000000..ab3d72ea8622cfeb17a3c942024b3edc7cd88e2a --- /dev/null +++ b/shared/package-files/0b/0bd6036ecc6dc6238a5da8ebbffbbb2d9025acdf981a7f4dc80864db394261f0/_cast_Double.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cast_Double(Tensor self, bool non_blocking=False) -> Tensor +inline at::Tensor _cast_Double(const at::Tensor & self, bool non_blocking=false) { + return at::_ops::_cast_Double::call(self, non_blocking); +} + +} diff --git a/shared/package-files/0b/0bd9c5badab6cd27c030df6b3875cc96a881f423ef29b2c18bc4c356c0dc9a37/HPUHooksInterface.h b/shared/package-files/0b/0bd9c5badab6cd27c030df6b3875cc96a881f423ef29b2c18bc4c356c0dc9a37/HPUHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..8cf9502a7e1b90c369329985d88d96c36f640582 --- /dev/null +++ b/shared/package-files/0b/0bd9c5badab6cd27c030df6b3875cc96a881f423ef29b2c18bc4c356c0dc9a37/HPUHooksInterface.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace at { + +struct TORCH_API HPUHooksInterface : AcceleratorHooksInterface { + ~HPUHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize HPU without HPU backend"); + } + + virtual bool hasHPU() const { + return false; + } + + Device getDeviceFromPtr(void* /*data*/) const override { + TORCH_CHECK( + false, "Cannot get device of pointer on HPU without HPU backend"); + } + + bool isPinnedPtr(const void*) const override { + return false; + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK( + false, + "You should register `HPUHooksInterface` for HPU before call `getPinnedMemoryAllocator`."); + } + + bool hasPrimaryContext( + [[maybe_unused]] DeviceIndex device_index) const override { + TORCH_CHECK( + false, + "You should register `HPUHooksInterface` for HPU before call `hasPrimaryContext`."); + } +}; + +struct TORCH_API HPUHooksArgs {}; + +TORCH_DECLARE_REGISTRY(HPUHooksRegistry, HPUHooksInterface, HPUHooksArgs); +#define REGISTER_HPU_HOOKS(clsname) \ + C10_REGISTER_CLASS(HPUHooksRegistry, clsname, clsname) + +namespace detail { + +TORCH_API const at::HPUHooksInterface& getHPUHooks(); + +} // namespace detail +} // namespace at diff --git a/shared/package-files/0b/0bde0cc182a1a7897fbf24b6a8a28da98e875a1071f50516381cb0c4deaca06f/pysam_util.c b/shared/package-files/0b/0bde0cc182a1a7897fbf24b6a8a28da98e875a1071f50516381cb0c4deaca06f/pysam_util.c new file mode 100644 index 0000000000000000000000000000000000000000..349af44d89ca6b2d134579fcad99f69d06c867ac --- /dev/null +++ b/shared/package-files/0b/0bde0cc182a1a7897fbf24b6a8a28da98e875a1071f50516381cb0c4deaca06f/pysam_util.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include +#include + +#include "htslib/khash.h" +#include "htslib/ksort.h" +#include "htslib/knetfile.h" + +#if !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) +/* + * A rudimentary emulation of getline() for systems that dont support it + * natively. Since this is used for PPD file reading, it assumes (possibly + * falsely) that BUFSIZ is big enough. + */ +ssize_t +getline(char **line, size_t *linelen, FILE *fp) +{ + if (*linelen == 0) + { + *linelen = BUFSIZ; + *line = malloc(*linelen); + } + + memset(*line, 0, *linelen); + fgets(*line, *linelen, fp); + + return (strlen(*line)); + +} +#endif + + + diff --git a/shared/package-files/0b/0be43b7a96faff502ea81b56512ceac52aa14c7abe4ae59e49d7d415885af1d9/test_monotonic.cpython-311.pyc b/shared/package-files/0b/0be43b7a96faff502ea81b56512ceac52aa14c7abe4ae59e49d7d415885af1d9/test_monotonic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a59430684ddb940bf7adc38b85fb6bc0686b6c Binary files /dev/null and b/shared/package-files/0b/0be43b7a96faff502ea81b56512ceac52aa14c7abe4ae59e49d7d415885af1d9/test_monotonic.cpython-311.pyc differ diff --git a/shared/package-files/0b/0be715aa5d40c03458ae4ae3c8de0478a9086a9c61062fc5d6d0a38e5377f384/msvccompiler.cpython-311.pyc b/shared/package-files/0b/0be715aa5d40c03458ae4ae3c8de0478a9086a9c61062fc5d6d0a38e5377f384/msvccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08a3b231cfa48562a08a2d0796e8d15e07216377 Binary files /dev/null and b/shared/package-files/0b/0be715aa5d40c03458ae4ae3c8de0478a9086a9c61062fc5d6d0a38e5377f384/msvccompiler.cpython-311.pyc differ diff --git a/shared/package-files/0b/0be72dc54412e4ac662d57e4e8eeea44ee5aba104a46fcf04ae2b3d7e426173c/intelccompiler.cpython-311.pyc b/shared/package-files/0b/0be72dc54412e4ac662d57e4e8eeea44ee5aba104a46fcf04ae2b3d7e426173c/intelccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..896811f9ec05f8fba416f8eecbb9a743be599c08 Binary files /dev/null and b/shared/package-files/0b/0be72dc54412e4ac662d57e4e8eeea44ee5aba104a46fcf04ae2b3d7e426173c/intelccompiler.cpython-311.pyc differ diff --git a/shared/package-files/0b/0bee45cf1a33ff74187b600cfbd32f8a1bec63d5edd639e08c4ef88c1eab8f62/uniform_cuda_dispatch.h b/shared/package-files/0b/0bee45cf1a33ff74187b600cfbd32f8a1bec63d5edd639e08c4ef88c1eab8f62/uniform_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7b003b202de45f0a2e30782cd1394df41b18bfb2 --- /dev/null +++ b/shared/package-files/0b/0bee45cf1a33ff74187b600cfbd32f8a1bec63d5edd639e08c4ef88c1eab8f62/uniform_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor & uniform_(at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/0b/0bef49b965fbccf21c1136ead20d9d43cde77b8ff11034083e60be7123168b12/WHEEL b/shared/package-files/0b/0bef49b965fbccf21c1136ead20d9d43cde77b8ff11034083e60be7123168b12/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..04b8de3f7d6f51022dab208980b75eabd347388a --- /dev/null +++ b/shared/package-files/0b/0bef49b965fbccf21c1136ead20d9d43cde77b8ff11034083e60be7123168b12/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.2) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/shared/package-files/0b/0bf12b5765f22157cf3cab78a9bd7ce965db4261948167b2712f332ba940bd4d/_nested_view_from_jagged_ops.h b/shared/package-files/0b/0bf12b5765f22157cf3cab78a9bd7ce965db4261948167b2712f332ba940bd4d/_nested_view_from_jagged_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..df37d507a9d75b4d34661fa2b4942d8382031b59 --- /dev/null +++ b/shared/package-files/0b/0bf12b5765f22157cf3cab78a9bd7ce965db4261948167b2712f332ba940bd4d/_nested_view_from_jagged_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_view_from_jagged { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const ::std::optional &, int64_t, const ::std::optional &, const ::std::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_nested_view_from_jagged"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const ::std::optional & lengths, int64_t ragged_idx, const ::std::optional & min_seqlen, const ::std::optional & max_seqlen); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const ::std::optional & lengths, int64_t ragged_idx, const ::std::optional & min_seqlen, const ::std::optional & max_seqlen); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0bfb071481f7c56e28f11aa3c3808e26730a9b9842808d2f7e0782b8977fe687/_foreach_floor_ops.h b/shared/package-files/0b/0bfb071481f7c56e28f11aa3c3808e26730a9b9842808d2f7e0782b8977fe687/_foreach_floor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ff858d80d58516be06e5d2f9d6f89defac04e526 --- /dev/null +++ b/shared/package-files/0b/0bfb071481f7c56e28f11aa3c3808e26730a9b9842808d2f7e0782b8977fe687/_foreach_floor_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_floor { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_floor"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_floor(Tensor[] self) -> Tensor[]"; + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_floor_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_floor_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_floor_(Tensor(a!)[] self) -> ()"; + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_floor_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_floor"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_foreach_floor.out(Tensor[] self, *, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/0b/0bfdbe070b439cbb3833115eee36e7e3babbbdd9694b5e271e07408db96cde99/fmin_meta.h b/shared/package-files/0b/0bfdbe070b439cbb3833115eee36e7e3babbbdd9694b5e271e07408db96cde99/fmin_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..059748dc1f2956d48c8e23b354226fa9801613da --- /dev/null +++ b/shared/package-files/0b/0bfdbe070b439cbb3833115eee36e7e3babbbdd9694b5e271e07408db96cde99/fmin_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_fmin : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & other); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/0b/0bff7e0d35c9bbae989957b7caf77c01c37bf1b7f4db6e665db1f96719545061/_tensor.cpython-311.pyc b/shared/package-files/0b/0bff7e0d35c9bbae989957b7caf77c01c37bf1b7f4db6e665db1f96719545061/_tensor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d637e90716ca34733d638624c348f67292db0499 Binary files /dev/null and b/shared/package-files/0b/0bff7e0d35c9bbae989957b7caf77c01c37bf1b7f4db6e665db1f96719545061/_tensor.cpython-311.pyc differ diff --git a/shared/package-files/18/180324c3abb237bd07e7d8bc45f86951bc060443cfa7a7026d240931e3b721d8/__init__.py b/shared/package-files/18/180324c3abb237bd07e7d8bc45f86951bc060443cfa7a7026d240931e3b721d8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00d95445c6f354e731bb7b3c4d5cd9b891efedc6 --- /dev/null +++ b/shared/package-files/18/180324c3abb237bd07e7d8bc45f86951bc060443cfa7a7026d240931e3b721d8/__init__.py @@ -0,0 +1,309 @@ +# mypy: allow-untyped-defs +from functools import partial +from typing import Optional, Union + +import torch +import torch._prims as prims +import torch._prims_common as utils +import torch._refs as refs +import torch._refs.linalg as linalg +from torch import Tensor +from torch._prims_common import ( + check_fp_or_complex, + check_is_matrix, + Dim, + DimsType, + ELEMENTWISE_TYPE_PROMOTION_KIND, + IntLike, + TensorLikeType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + elementwise_type_promotion_wrapper, + out_wrapper, +) + + +__all__ = [ + "diagonal", + "matrix_norm", + "norm", + "svd", + "svdvals", + "vector_norm", + "vecdot", + "cross", +] + + +def _check_norm_dtype(dtype: Optional[torch.dtype], x_dtype: torch.dtype, fn_name: str): + """ + Checks related to the dtype kwarg in `linalg.*norm` functions + """ + if dtype is not None: + torch._check( + utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype), + lambda: f"{fn_name}: dtype should be floating point or complex. Got {dtype}", + ) + torch._check( + utils.is_complex_dtype(dtype) == utils.is_complex_dtype(x_dtype), + lambda: "{fn_name}: dtype should be {d} for {d} inputs. Got {dtype}".format( + fn_name=fn_name, + d="complex" if utils.is_complex_dtype(x_dtype) else "real", + dtype=dtype, + ), + ) + torch._check( + utils.get_higher_dtype(dtype, x_dtype) == dtype, + lambda: f"{fn_name}: the dtype of the input ({x_dtype}) should be convertible " + "without narrowing to the specified dtype ({dtype})", + ) + + +import operator + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition +from torch._decomp.decompositions import pw_cast_for_opmath + + +@register_decomposition(torch._ops.ops.aten.linalg_cross) +@out_wrapper() +@pw_cast_for_opmath +def cross(a: Tensor, b: Tensor, dim: int = -1): + torch._check( + a.ndim == b.ndim, + lambda: "linalg.cross: inputs must have the same number of dimensions.", + ) + torch._check( + a.size(dim) == 3 and b.size(dim) == 3, + lambda: f"linalg.cross: inputs dim {dim} must have length 3, got {a.size(dim)} and {b.size(dim)}", + ) + a, b = torch.broadcast_tensors(a, b) + dim = utils.canonicalize_dim(a.ndim, dim) + idx = torch.arange(3, device=a.device) + return a.index_select(dim, (idx + 1) % 3) * b.index_select( + dim, (idx + 2) % 3 + ) - a.index_select(dim, (idx + 2) % 3) * b.index_select(dim, (idx + 1) % 3) + + +def diagonal( + input: TensorLikeType, + *, + offset: int = 0, + dim1: int = -2, + dim2: int = -1, +) -> TensorLikeType: + return torch.diagonal(input, offset=offset, dim1=dim1, dim2=dim2) + + +@register_decomposition(torch._ops.ops.aten.linalg_vector_norm) +@out_wrapper(exact_dtype=True) +def vector_norm( + x: TensorLikeType, + ord: Union[float, int] = 2, + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + dtype: Optional[torch.dtype] = None, +) -> Tensor: + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + # Checks + check_fp_or_complex(x.dtype, "linalg.vector_norm") + + if isinstance(dim, Dim): + dim = [dim] # type: ignore[assignment] + + if guard_size_oblivious(x.numel() == 0) and (ord < 0.0 or ord == float("inf")): + torch._check( + dim is not None and len(dim) != 0, + lambda: f"linalg.vector_norm cannot compute the {ord} norm on an empty tensor " + "because the operation does not have an identity", + ) + shape = x.shape + assert dim is not None # mypy does not seem to be able to see through check? + for d in dim: + torch._check( + shape[d] != 0, + lambda: f"linalg.vector_norm cannot compute the {ord} norm on the " + f"dimension {d} because this dimension is empty and the " + "operation does not have an identity", + ) + _check_norm_dtype(dtype, x.dtype, "linalg.vector_norm") + + computation_dtype, result_dtype = utils.reduction_dtypes( + x, utils.REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, dtype + ) + + to_result_dtype = partial(_maybe_convert_to_dtype, dtype=result_dtype) + + # Implementation + if ord == 0.0: + return torch.sum(torch.ne(x, 0.0), dim=dim, keepdim=keepdim, dtype=result_dtype) + elif ord == float("inf"): + return to_result_dtype(torch.amax(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type] + elif ord == float("-inf"): + return to_result_dtype(torch.amin(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type] + else: + # From here on the computation dtype is important as the reduction is non-trivial + x = _maybe_convert_to_dtype(x, computation_dtype) # type: ignore[assignment] + reduce_sum = partial(torch.sum, dim=dim, keepdim=keepdim) + + is_ord_even = ord % 2 == 0 if isinstance(ord, IntLike) else ord % 2.0 == 0.0 + if not (is_ord_even and utils.is_float_dtype(x.dtype)): + x = torch.abs(x) + return to_result_dtype(torch.pow(reduce_sum(torch.pow(x, ord)), 1.0 / ord)) # type: ignore[return-value] + + +def _backshift_permutation(dim0, dim1, ndim): + # Auxiliary function for matrix_norm + # Computes the permutation that moves the two given dimensions to the back + ret = [i for i in range(ndim) if i != dim0 and i != dim1] + ret.extend((dim0, dim1)) + return ret + + +def _inverse_permutation(perm): + # Given a permutation, returns its inverse. It's equivalent to argsort on an array + return [i for i, j in sorted(enumerate(perm), key=operator.itemgetter(1))] + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def matrix_norm( + A: TensorLikeType, + ord: Union[float, str] = "fro", + dim: DimsType = (-2, -1), + keepdim: bool = False, + *, + dtype: Optional[torch.dtype] = None, +) -> TensorLikeType: + # shape + check_is_matrix(A, "linalg.matrix_norm") + # dim + dim = utils.canonicalize_dims(A.ndim, dim) + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + torch._check( + len(dim) == 2, lambda: "linalg.matrix_norm: dim must be a 2-tuple. Got {dim}" + ) + torch._check( + dim[0] != dim[1], + lambda: "linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})", + ) + # dtype arg + _check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm") + + if isinstance(ord, str): + # ord + torch._check( + ord in ("fro", "nuc"), + lambda: "linalg.matrix_norm: Order {ord} not supported.", + ) + # dtype + check_fp_or_complex( + A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc" + ) + + if ord == "fro": + return vector_norm(A, 2, dim, keepdim, dtype=dtype) + else: # ord == "nuc" + if dtype is not None: + A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment] + perm = _backshift_permutation(dim[0], dim[1], A.ndim) + result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim) + if keepdim: + inv_perm = _inverse_permutation(perm) + result = prims.transpose(torch.unsqueeze(result, -1), inv_perm) + return result + else: + # ord + abs_ord = abs(ord) + torch._check( + abs_ord in (2, 1, float("inf")), + lambda: "linalg.matrix_norm: Order {ord} not supported.", + ) + # dtype + check_fp_or_complex( + A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2 + ) + + max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim) + + if abs_ord == 2.0: + if dtype is not None: + A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment] + perm = _backshift_permutation(dim[0], dim[1], A.ndim) + result = max_min(svdvals(prims.transpose(A, perm)), dim=-1) + if keepdim: + inv_perm = _inverse_permutation(perm) + result = prims.transpose(torch.unsqueeze(result, -1), inv_perm) + return result + else: # 1, -1, inf, -inf + dim0, dim1 = dim + if abs_ord == float("inf"): + dim0, dim1 = dim1, dim0 + if not keepdim and (dim0 < dim1): + dim1 -= 1 + return max_min( + vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1 + ) + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def norm( + A: TensorLikeType, + ord: Optional[Union[float, str]] = None, + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + dtype: Optional[torch.dtype] = None, +) -> TensorLikeType: + if dim is not None: + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + torch._check( + len(dim) in (1, 2), + lambda: "linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}", + ) + elif ord is not None: + torch._check( + A.ndim in (1, 2), + lambda: "linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D", + ) + + if ord is not None and ( + (dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2) + ): + if dim is None: + dim = (0, 1) + return matrix_norm(A, ord, dim, keepdim, dtype=dtype) + else: + if ord is None: + ord = 2.0 + return vector_norm(A, ord, dim, keepdim, dtype=dtype) # type: ignore[arg-type] + + +# CompositeImplicitAutograd +@out_wrapper("U", "S", "Vh", exact_dtype=True) +def svd(A: TensorLikeType, full_matrices: bool = True) -> tuple[Tensor, Tensor, Tensor]: + return prims.svd(A, full_matrices=full_matrices) + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def svdvals(A: TensorLikeType) -> Tensor: + return svd(A, full_matrices=False)[1] + + +# CompositeImplicitAutograd +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("x", "y"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor: + check_fp_or_complex(x.dtype, "linalg.vecdot") + return (x.conj() * y).sum(dim=dim) diff --git a/shared/package-files/18/180390354f8dc6a34d54385eb1bfe8d6ff6cbc96f255df43a00b724ca57101a7/multi_wait.h b/shared/package-files/18/180390354f8dc6a34d54385eb1bfe8d6ff6cbc96f255df43a00b724ca57101a7/multi_wait.h new file mode 100644 index 0000000000000000000000000000000000000000..a3a33ee3975f99285230619ee688e6a22605e975 --- /dev/null +++ b/shared/package-files/18/180390354f8dc6a34d54385eb1bfe8d6ff6cbc96f255df43a00b724ca57101a7/multi_wait.h @@ -0,0 +1,60 @@ +/** + * This file is adapted from PyTorch/XLA + * https://github.com/pytorch/xla/blob/master/third_party/xla_client/multi_wait.h + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace torch::lazy { + +// Support waiting for a number of tasks to complete. +class TORCH_API MultiWait { + public: + explicit MultiWait(size_t count) : count_(count) {} + + // Signal the completion of a single task. + void Done(); + + // Waits until at least count (passed as constructor value) completions + // happened. + void Wait(); + + // Same as above, but waits up to wait_seconds. + void Wait(double wait_seconds); + + // Resets the threshold counter for the MultiWait object. The completed count + // is also reset to zero. + void Reset(size_t count); + + // Creates a completer functor which signals the mult wait object once func + // has completed. Handles exceptions by signaling the multi wait with the + // proper status value. This API returns a function which captures a MultiWait + // reference, so care must be taken such that the reference remains valid for + // the whole lifetime of the returned function. + std::function Completer(std::function func); + + // Similar as the above API, but with explicit capture of the MultiWait shared + // pointer. + static std::function Completer( + std::shared_ptr mwait, + std::function func); + + private: + void Complete(const std::function& func); + + std::mutex mutex_; + std::condition_variable cv_; + size_t count_ = 0; + size_t completed_count_ = 0; + std::exception_ptr exptr_; +}; + +} // namespace torch::lazy diff --git a/shared/package-files/18/1806663383fa51eff0bc9d806b5d8d6dd095a0834e1b9c1e5af50a1cb0873089/fft_fft2_ops.h b/shared/package-files/18/1806663383fa51eff0bc9d806b5d8d6dd095a0834e1b9c1e5af50a1cb0873089/fft_fft2_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..db10eeb8018a355efda400e3675ac284b42a4780 --- /dev/null +++ b/shared/package-files/18/1806663383fa51eff0bc9d806b5d8d6dd095a0834e1b9c1e5af50a1cb0873089/fft_fft2_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fft_fft2 { + using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, at::IntArrayRef, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fft_fft2"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm); +}; + +struct TORCH_API fft_fft2_out { + using schema = at::Tensor & (const at::Tensor &, at::OptionalSymIntArrayRef, at::IntArrayRef, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fft_fft2"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/18069187fa3e7ca93e4d3cda2890672702efbdc9fc5e62e996bebb93ac90b9fc/redirects.cpython-311.pyc b/shared/package-files/18/18069187fa3e7ca93e4d3cda2890672702efbdc9fc5e62e996bebb93ac90b9fc/redirects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a599f61c50f9a6dda88c2fd3e91eb842a569ed01 Binary files /dev/null and b/shared/package-files/18/18069187fa3e7ca93e4d3cda2890672702efbdc9fc5e62e996bebb93ac90b9fc/redirects.cpython-311.pyc differ diff --git a/shared/package-files/18/181327e554057eb2bb12d69d827e9c4e731a09603f637e5b00d998caf41284cc/_core.py b/shared/package-files/18/181327e554057eb2bb12d69d827e9c4e731a09603f637e5b00d998caf41284cc/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..f33e384e050327c20a77699af24c6ea356132014 --- /dev/null +++ b/shared/package-files/18/181327e554057eb2bb12d69d827e9c4e731a09603f637e5b00d998caf41284cc/_core.py @@ -0,0 +1,1579 @@ +# mypy: allow-untyped-defs +# flake8: noqa: B950 We do not need flake8 as it complains line length +from __future__ import annotations + +import ctypes +import datetime +import inspect +import itertools +import logging +import operator +import pathlib +import textwrap +import traceback +import typing +from collections.abc import Mapping, Sequence +from typing import Any, Callable, Literal + +import onnxscript +import onnxscript.evaluator +from onnxscript import ir +from onnxscript.ir import convenience as ir_convenience + +import torch +import torch.fx +from torch.export import graph_signature +from torch.onnx._internal._lazy_import import onnxscript_apis +from torch.onnx._internal.exporter import ( + _analysis, + _building, + _capture_strategies, + _constants, + _dispatching, + _errors, + _fx_passes, + _ir_passes, + _onnx_program, + _registration, + _reporting, + _tensors, + _verification, +) + + +if typing.TYPE_CHECKING: + import os + + import numpy.typing as npt + + +# Define utilities to convert PyTorch data types so users do not need to specify manually +_TORCH_DTYPE_TO_ONNX: dict[torch.dtype, ir.DataType] = { + torch.bfloat16: ir.DataType.BFLOAT16, + torch.bool: ir.DataType.BOOL, + torch.complex128: ir.DataType.COMPLEX128, + torch.complex64: ir.DataType.COMPLEX64, + torch.float16: ir.DataType.FLOAT16, + torch.float32: ir.DataType.FLOAT, + torch.float64: ir.DataType.DOUBLE, + torch.float8_e4m3fn: ir.DataType.FLOAT8E4M3FN, + torch.float8_e4m3fnuz: ir.DataType.FLOAT8E4M3FNUZ, + torch.float8_e5m2: ir.DataType.FLOAT8E5M2, + torch.float8_e5m2fnuz: ir.DataType.FLOAT8E5M2FNUZ, + torch.int16: ir.DataType.INT16, + torch.int32: ir.DataType.INT32, + torch.int64: ir.DataType.INT64, + torch.int8: ir.DataType.INT8, + torch.uint8: ir.DataType.UINT8, + torch.uint16: ir.DataType.UINT16, + torch.uint32: ir.DataType.UINT32, + torch.uint64: ir.DataType.UINT64, +} +_BLUE = "\033[96m" +_END = "\033[0m" + +_STEP_ONE_ERROR_MESSAGE = textwrap.dedent( + f"""\ + Failed to export the model with torch.export. {_BLUE}This is step 1/3{_END} of exporting the model to ONNX. Next steps: + - Modify the model code for `torch.export.export` to succeed. Refer to https://pytorch.org/docs/stable/generated/exportdb/index.html for more information. + - Debug `torch.export.export` and summit a PR to PyTorch. + - Create an issue in the PyTorch GitHub repository against the {_BLUE}*torch.export*{_END} component and attach the full error stack as well as reproduction scripts.""" +) + +_STEP_TWO_ERROR_MESSAGE = textwrap.dedent( + f"""\ + Failed to decompose the FX graph for ONNX compatibility. {_BLUE}This is step 2/3{_END} of exporting the model to ONNX. Next steps: + - Create an issue in the PyTorch GitHub repository against the {_BLUE}*torch.export*{_END} component and attach the full error stack as well as reproduction scripts. + - Create an error report with `torch.onnx.export(..., report=True)`, and save the ExportedProgram as a pt2 file. Create an issue in the PyTorch GitHub repository against the {_BLUE}*onnx*{_END} component. Attach the error report and the pt2 model.""" +) + +_STEP_THREE_ERROR_MESSAGE = textwrap.dedent( + f"""\ + Failed to convert the exported program to an ONNX model. {_BLUE}This is step 3/3{_END} of exporting the model to ONNX. Next steps: + - If there is a missing ONNX function, implement it and register it to the registry. + - If there is an internal error during ONNX conversion, debug the error and summit a PR to PyTorch. + - Create an error report with `torch.onnx.export(..., report=True)`, and save the ExportedProgram as a pt2 file. Create an issue in the PyTorch GitHub repository against the {_BLUE}*onnx*{_END} component. Attach the error report and the pt2 model.""" +) + +logger = logging.getLogger(__name__) +# The current tracer that is being used to trace the operators, +# used by torch/onnx/_internal/exporter/_torchlib/ops/hop.py +current_tracer: _building.OpRecorder | None = None + + +def _torch_dtype_to_onnx_dtype(dtype: torch.dtype) -> ir.DataType: + return _TORCH_DTYPE_TO_ONNX[dtype] + + +class TorchTensor(ir.Tensor): + def __init__(self, tensor: torch.Tensor, name: str | None = None): + # Pass the tensor as the raw data to ir.Tensor's constructor + super().__init__( + tensor, dtype=_torch_dtype_to_onnx_dtype(tensor.dtype), name=name + ) + + def numpy(self) -> npt.NDArray: + self.raw: torch.Tensor + if self.dtype == ir.DataType.BFLOAT16: + return self.raw.view(torch.uint16).numpy(force=True) + if self.dtype in { + ir.DataType.FLOAT8E4M3FN, + ir.DataType.FLOAT8E4M3FNUZ, + ir.DataType.FLOAT8E5M2, + ir.DataType.FLOAT8E5M2FNUZ, + }: + # TODO: Use ml_dtypes + return self.raw.view(torch.uint8).numpy(force=True) + return self.raw.numpy(force=True) + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> npt.NDArray: + del copy # Unused, but needed for the signature + if dtype is None: + return self.numpy() + return self.numpy().__array__(dtype) + + def tobytes(self) -> bytes: + # Implement tobytes to support native PyTorch types so we can use types like bloat16 + # Reading from memory directly is also more efficient because + # it avoids copying to a NumPy array + import torch._subclasses.fake_tensor + + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + # Disable any fake mode so calling detach() etc. will return a real tensor + tensor = self.raw.detach().cpu().contiguous() + + if isinstance(tensor, torch._subclasses.fake_tensor.FakeTensor): + raise TypeError( + f"Cannot take content out from the FakeTensor ('{self.name}'). Please replace the tensor " + "with a tensor backed by real data using ONNXProgram.apply_weights() " + "or save the model without initializers by setting include_initializers=False." + ) + + return bytes( + (ctypes.c_ubyte * tensor.element_size() * tensor.numel()).from_address( + tensor.data_ptr() + ) + ) + + +# https://github.com/pytorch/pytorch/blob/ee6cb6daa173896f8ea1876266a19775aaa4f610/torch/export/graph_signature.py#L56C1-L62C19 +# class InputKind(Enum): +# USER_INPUT = auto() +# PARAMETER = auto() +# BUFFER = auto() +# CONSTANT_TENSOR = auto() +# CUSTOM_OBJ = auto() +# TOKEN = auto() + +# https://github.com/pytorch/pytorch/blob/ee6cb6daa173896f8ea1876266a19775aaa4f610/torch/export/graph_signature.py#L89C1-L96C19 +# class OutputKind(Enum): +# USER_OUTPUT = auto() +# LOSS_OUTPUT = auto() +# BUFFER_MUTATION = auto() +# GRADIENT_TO_PARAMETER = auto() +# GRADIENT_TO_USER_INPUT = auto() +# USER_INPUT_MUTATION = auto() +# TOKEN = auto() + + +def _set_shape_types( + values: Sequence[ir.Value], + meta_vals: Sequence[torch.Tensor], + complex_to_float: bool = True, +) -> None: + if not isinstance(meta_vals, Sequence): + logger.warning( + "Expected meta_vals to be a sequence, but got %s. There may be an internal error.", + meta_vals, + ) + meta_vals = (meta_vals,) + for value, meta_val in zip(values, meta_vals): + _set_shape_type(value, meta_val, complex_to_float=complex_to_float) + + +def _set_shape_type( + value: ir.Value, + meta_val: torch.Tensor + | torch.SymBool + | torch.SymInt + | torch.SymFloat + | tuple[torch.Tensor], + complex_to_float: bool, +) -> None: + # TODO: Consider using meta["tensor_meta"] for this? Would it be faster? + if isinstance(meta_val, tuple): + logger.warning("Setting shape and type of tensors is not supported yet") + if isinstance(meta_val, torch.Tensor): + # FIXME: Consider shape for complex values + dims = [] + for dim in meta_val.shape: + if isinstance(dim, int): + dims.append(dim) + else: + dims.append(str(dim.node)) + value.dtype = _torch_dtype_to_onnx_dtype(meta_val.dtype) + if complex_to_float: + if meta_val.dtype == torch.complex64: + value.dtype = ir.DataType.FLOAT + # Add 2 as the last dimension if the tensor is complex to hold the real/imag parts + dims.append(2) + elif meta_val.dtype == torch.complex128: + value.dtype = ir.DataType.DOUBLE + # Add 2 as the last dimension if the tensor is complex to hold the real/imag parts + dims.append(2) + + value.shape = ir.Shape(dims) + elif isinstance(meta_val, (int, torch.SymInt)): + # aten::sym_size output is a int, not a tensor, which stands + # for the size of one dim. We treat it as a scalar. + value.dtype = ir.DataType.INT64 + value.shape = ir.Shape([]) + elif isinstance(meta_val, (bool, torch.SymBool)): + value.dtype = ir.DataType.BOOL + value.shape = ir.Shape([]) + elif isinstance(meta_val, (float, torch.SymFloat)): + value.dtype = ir.DataType.FLOAT + value.shape = ir.Shape([]) + else: + pass + + +def _get_qualified_module_name(cls: Any) -> str: + if isinstance(cls, str): + return cls + module = cls.__module__ + if module is None or module == str.__class__.__module__: + return cls.__name__ + return module + "." + cls.__name__ + + +def _get_node_namespace(node: torch.fx.Node) -> tuple[str, list[str], list[str]]: + """Get the namespace and scope of the node. + + Example:: + + { + 'L__self__': ('', ), + 'L__self___avgpool': ('avgpool', ) + } + + Will yield + + namespace: ": torchvision.models.resnet.ResNet/avgpool: torch.nn.modules.pooling.AdaptiveAvgPool2d/node_name: node_target" + class_hierarchy: ["torchvision.models.resnet.ResNet", "torch.nn.modules.pooling.AdaptiveAvgPool2d", ] + name_scopes: ["", "avgpool", ] + + Args: + node: The node to get the namespace and scope of. + + Returns: + (namespace, class_hierarchy, name_scope) + """ + nn_module_stack = node.meta.get("nn_module_stack") + logger.debug("%s", nn_module_stack) + if nn_module_stack is None: + logger.warning( + "nn_module_stack not found for node '%s'. Skip adding metadata...", + node.name, + ) + return f"{node.name}: {node.target}", [str(node.target)], [node.name] + namespaces = [] + class_hierarchy = [] + name_scopes = [] + for name, nn_module in nn_module_stack.values(): + name_scopes.append(name) + nn_module_name = _get_qualified_module_name(nn_module) + class_hierarchy.append(nn_module_name) + namespaces.append(f"{name}: {_get_qualified_module_name(nn_module)}") + namespaces.append(f"{node.name}: {node.target}") + class_hierarchy.append(str(node.target)) + name_scopes.append(node.name) + + return "/".join(namespaces), class_hierarchy, name_scopes + + +def _set_node_metadata(fx_node: torch.fx.Node, ir_node: ir.Node) -> None: + """Adds namespace and other node metadata to the ONNX node.""" + namespace, class_hierarchy, name_scopes = _get_node_namespace(fx_node) + ir_node.metadata_props["namespace"] = namespace + ir_node.metadata_props["pkg.torch.onnx.class_hierarchy"] = repr(class_hierarchy) + ir_node.metadata_props["pkg.torch.onnx.name_scopes"] = repr(name_scopes) + ir_node.metadata_props["pkg.torch.onnx.fx_node"] = str(fx_node.format_node()) + ir_node.metadata_props["pkg.torch.onnx.stack_trace"] = fx_node.meta.get( + "stack_trace", "" + ) + + +def _handle_getitem_node( + node: torch.fx.Node, node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]] +) -> ir.Value: + """Handle a getitem node. + + Add the input value it is getting to the mapping, then return the value. + + There are two cases for this node: + 1. The output is a Sequence (traced), we can simply get the value from the sequence + 2. The output is produced by a SplitToSequence node, we need to get the value from the sequence value + This function only handles the first case + """ + assert len(node.all_input_nodes) == 1 + source = node.all_input_nodes[0] + source_outputs = node_name_to_values[source.name] + assert isinstance(source_outputs, Sequence), ( + f"Expected {source.name} to output sequence, got {node_name_to_values[source.name]}" + ) + index = typing.cast(int, node.args[1]) + value = source_outputs[index] + # Save the getitem value to the values mapping to in case + # it is one of the graph outputs + node_name_to_values[node.name] = value + # Rename the name of value with the getitem name. + value.name = node.name + return value + + +def _handle_call_function_node( + graph_like: ir.Graph | ir.Function, + node: torch.fx.Node, + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]], +) -> None: + """Handle a call_function node. + + Args: + graph: The ONNX graph at construction. + node: The FX node to translate. + node_name_to_values: A mapping of FX node names to their produced ir.Value. + """ + if node.target == operator.getitem: + _handle_getitem_node(node, node_name_to_values) + # Add op to the graph + op = str(node.target) + fx_inputs, attributes, input_names, output_names = _get_inputs_and_attributes(node) + inputs: list[ir.Value | None] = [] + for i, input_ in enumerate(fx_inputs): + if input_ is None: + inputs.append(None) + elif hasattr(input_, "name"): + if isinstance(input_, torch.fx.Node) and input_.target == operator.getitem: + actual_input = _handle_getitem_node(input_, node_name_to_values) + inputs.append(actual_input) + else: + value = node_name_to_values[input_.name] + assert not isinstance(value, Sequence) + inputs.append(value) + else: + attributes[f"arg_{i}"] = input_ + + outputs = [ir.Value(name=name) for name in output_names] + if len(outputs) > 1: + _set_shape_types(outputs, node.meta["val"], complex_to_float=False) + node_name_to_values[node.name] = outputs + else: + _set_shape_type(outputs[0], node.meta["val"], complex_to_float=False) + node_name_to_values[node.name] = outputs[0] + ir_node = ir.Node( + "pkg.torch.ops", + op, + inputs, + attributes=ir_convenience.convert_attributes(attributes), + outputs=outputs, + name=node.name, + ) + ir_node.meta["node"] = node + ir_node.metadata_props["pkg.torch.onnx.input_names"] = repr(input_names) + # Record the nn.Module stack for the node + _set_node_metadata(node, ir_node) + + graph_like.append(ir_node) + + +def _convert_fx_arg_to_onnx_arg( + arg, + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]], + node_name_to_local_functions: dict[str, ir.Function], +) -> Any: + """Convert an FX argument to an ONNX compatible argument. + + This function + - Converts a torch dtype to an integer + - Converts a torch device/memory_format/layout to a string + - Converts a torch.fx.Node to an ir.Value + - Converts a sequence of torch.fx.Node to a sequence of ir.Value + - Converts a get_attr node to an ir.Function + """ + if arg is None: + # None arguments are not modified because when the arg is an ONNX input + # we need to preserve the None value; when the arg is an ONNX attribute, + # we want to drop the value. + # The actual dropping of a None attribute value is done by OpRecorder + return None + if hasattr(arg, "name"): + if isinstance(arg, torch.fx.Node) and arg.target == operator.getitem: + source = arg.all_input_nodes[0] + source_outputs = node_name_to_values[source.name] + if isinstance(source_outputs, Sequence): + # If the node is getting an input from another node, get the actual value the node is retrieving + return _handle_getitem_node(arg, node_name_to_values) + else: + # `source_outputs` is a sequence(tensor()) value and we need to + # use SequenceAt to get the value. This is handled by torchlib + pass + if isinstance(arg, torch.fx.Node) and arg.op == "get_attr": + return node_name_to_local_functions[arg.name] + # If the input is a node, get the value from the mapping + return node_name_to_values[arg.name] + if isinstance(arg, (list, tuple)): + return [ + _convert_fx_arg_to_onnx_arg( + elem, node_name_to_values, node_name_to_local_functions + ) + for elem in arg + ] + if isinstance(arg, (torch.device, torch.memory_format, torch.layout)): + return str(arg) + if isinstance(arg, torch.dtype): + return _torch_dtype_to_onnx_dtype(arg) + # Maybe a Python value + return arg + + +def _get_onnxscript_opset(opset_version: int) -> onnxscript.values.Opset: + return onnxscript.values.Opset("", opset_version) + + +def _handle_call_function_node_with_lowering( + model: ir.Model, + node: torch.fx.Node, + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]], + *, + graph_like: ir.Graph | ir.Function, + constant_farm: dict[Any, ir.Value], + registry: _registration.ONNXRegistry, + opset: onnxscript.values.Opset, + node_name_to_local_functions: dict[str, ir.Function], +) -> None: + """Translate a call_function node to an ONNX node. + + Args: + model: The ONNX model at construction. + node: The FX node to translate. + node_name_to_values: A mapping of FX node names to their produced ONNX ``Value``. + graph_like: The current ONNX graph at construction. + Must add nodes to this graph because it can be a subgraph that is currently being constructed. + constant_farm: A mapping of constant values to existing ONNX ``Value``s. + registry: The registry of all aten to ONNX decomposition functions. + opset: The ONNX Script opset object for constructing ONNX nodes. + node_name_to_local_functions: A mapping of subgraph names to the corresponding ONNX functions. + """ + if node.target == operator.getitem: + source = node.all_input_nodes[0] + source_outputs = node_name_to_values[source.name] + if isinstance(source_outputs, Sequence): + _handle_getitem_node(node, node_name_to_values) + return + else: + # `source_outputs` is a sequence(tensor()) value and we need to + # use SequenceAt to get the value. This is handled by torchlib + pass + + # Find the matching ONNX overload for the node + # NOTE: Create different registries for different ONNX opset versions + # TODO: Log the message here to expose false positives + onnx_function, message = _dispatching.dispatch(node, registry) + + if onnx_function is None: + # TODO(justinchuby): Fall back to ATen op or do something else? + raise _errors.DispatchError( + f"No ONNX function found for {node.target!r}. Failure message: {message}" + ) + + # Map FX inputs to ONNX inputs and fill optional inputs. + # torch_args and torch_kwargs are for op-level validation + fx_args = node.args + fx_kwargs = node.kwargs + + # Replace the input FX nodes with ONNX values + onnx_args = [ + _convert_fx_arg_to_onnx_arg( + input_, node_name_to_values, node_name_to_local_functions + ) + for input_ in fx_args + ] + + onnx_kwargs = {} + for key, value in fx_kwargs.items(): + onnx_kwargs[key] = _convert_fx_arg_to_onnx_arg( + value, node_name_to_values, node_name_to_local_functions + ) + if key == "dtype" and onnx_kwargs[key] is None: + # Set dtype to -1 if it is None + # TODO(justinchuby): Maybe keep it as None? + onnx_kwargs[key] = -1 + + with onnxscript.evaluator.default_as( + tracer := _building.OpRecorder(opset, constant_farm) + ): + global current_tracer + current_tracer = tracer + try: + outputs = onnx_function(*onnx_args, **onnx_kwargs) + except Exception as e: + raise _errors.GraphConstructionError( + f"Error when calling function '{onnx_function}' with args '{onnx_args}' and kwargs '{onnx_kwargs}'" + ) from e + finally: + current_tracer = None + + # NOTE: Instead of using the output names from node.target._schema, + # we always use the index if there are more than one outputs so the + # names can be programmatically reconstructed. This is useful for + # comparing values from the ONNX graph with those from the FX graph. + # + # When there are multiple outputs, the output names will be + # node_name__0, node_name__1, etc. + if isinstance(outputs, Sequence): + _set_shape_types(outputs, node.meta["val"], complex_to_float=True) + node_name_to_values[node.name] = outputs + for i, output in enumerate(outputs): + output.name = f"{node.name}__{i}" + else: + _set_shape_type(outputs, node.meta["val"], complex_to_float=True) + node_name_to_values[node.name] = outputs + outputs.name = node.name + + for ir_node in tracer.nodes: + ir_node.meta["node"] = node + # Record the nn.Module stack for the node + _set_node_metadata(node, ir_node) + + # Add the traced nodes to the current graph + # Must add nodes to this graph, not model.graph, because it can be a subgraph that is currently being constructed + graph_like.extend(tracer.nodes) + # Add the defined functions to the model + for identifier, onnxscript_function in tracer.functions.items(): + if identifier in model.functions: + continue + if isinstance(onnxscript_function, ir.Function): + ir_function = onnxscript_function + else: + # TODO: Get IR function directly when onnxscript is updated + proto = onnxscript_function.to_function_proto() + ir_function = ir.serde.deserialize_function(proto) + model.functions[identifier] = ir_function + # Opset imports are added to the model in the final add_opset_imports pass + + +def _handle_placeholder_node( + node: torch.fx.Node, + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]], + *, + graph_like: ir.Graph | ir.Function, + lower: str, + opset: onnxscript.values.Opset, +) -> None: + # Placeholder nodes are user inputs + # We need to create a new tensor for each user input + # and add it to the graph's inputs + name = node.name + input_ = _tensors.SymbolicTensor(opset, name=name) + input_.meta["node"] = node + _set_shape_type(input_, node.meta["val"], complex_to_float=lower != "none") + node_name_to_values[name] = input_ + # The inputs should be add to the graph here + graph_like.inputs.append(input_) + + +def _handle_get_attr_node( + node: torch.fx.Node, + *, + owned_graphs: Mapping[str, ir.Function], + node_name_to_local_functions: dict[str, ir.Function], +) -> None: + """Handle a get_attr node by assigning the corresponding ONNX function to the node name. + + An example ExportedProgram that has uses get_attr nodes is: + + ExportedProgram: + class GraphModule(torch.nn.Module): + def forward(self, arg0_1: "f32[5]"): + true_graph_0 = self.true_graph_0 # get_attr + false_graph_0 = self.false_graph_0 # get_attr + conditional = torch.ops.higher_order.cond(False, true_graph_0, false_graph_0, [arg0_1]); true_graph_0 = false_graph_0 = arg0_1 = None + getitem: "f32[5]" = conditional[0]; conditional = None + return (getitem,) + + class (torch.nn.Module): + def forward(self, arg0_1: "f32[5]"): + cos: "f32[5]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None + return (cos,) + + class (torch.nn.Module): + def forward(self, arg0_1: "f32[5]"): + sin: "f32[5]" = torch.ops.aten.sin.default(arg0_1); arg0_1 = None + return (sin,) + + Args: + node: The FX node to translate. + owned_graphs: A mapping of subgraph names to the corresponding ONNX functions. + node_name_to_local_functions: A mapping of local function names to their corresponding ONNX functions. + """ + if not isinstance(node.target, str): + logger.warning( + "Expected node.target for the node %s to be a string, but got '%s'. There may be an internal error.", + node, + type(node.target), + ) + return + function = owned_graphs[node.target] + node_name_to_local_functions[node.name] = function + + +def _handle_output_node( + node: torch.fx.Node, + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]], + graph_like: ir.Graph | ir.Function, +) -> None: + """Handle an output node by adding the output to the graph's outputs. + + Args: + node: The FX node to translate. + node_name_to_values: A mapping of FX node names to their produced ONNX ``Value``. + graph_like: The ONNX graph at construction. + """ + # node.args[0] can be a tuple with more than one elements. This happens when, + # for example, a subgraph has multiple outputs. We flatten them all as ONNX graph outputs + for output in node.args[0]: # type: ignore[index,union-attr] + output_value_name = output.name # type: ignore[union-attr] + assert isinstance(output_value_name, str), ( + f"Bug: Expected {output_value_name!r} to be a string" + ) + values = node_name_to_values[output_value_name] + if isinstance(values, Sequence): + graph_like.outputs.extend(values) + return + graph_like.outputs.append(values) + + +def _translate_fx_graph( + fx_graph: torch.fx.Graph, + model: ir.Model, + *, + graph_like: ir.Graph | ir.Function, + owned_graphs: Mapping[str, ir.Function], + lower: Literal["at_conversion", "none"], + registry: _registration.ONNXRegistry, +) -> dict[str, ir.Value | Sequence[ir.Value]]: + """Translate a submodule to an ONNX function. + + Any functions used by the traced functions will be added to the model. + + Args: + fx_graph: The FX graph module to translate. + model: The ONNX model at construction. + current_scope: The current name scope of the submodule, excluding the current module name. + E.g. "true_graph_0.false_graph_0". + graph_name: The name of the submodule. E.g. "true_graph_0". + graph: The ONNX graph at construction. + owned_graphs: The subgraphs owned by the current graph. + lower: The lowering strategy to use. + registry: The registry of all aten to ONNX decomposition functions. + + Returns: + A mapping of FX node names to their produced ONNX ``Value``. + """ + node_name_to_values: dict[str, ir.Value | Sequence[ir.Value]] = {} + # The reason we need node_name_to_local_functions in addition to owned_graphs + # is because the get_attr nodes may assign a different name than the GraphModule name + # to the subgraph. This is not typical but is valid Python. + node_name_to_local_functions: dict[str, ir.Function] = {} + constant_farm: dict[Any, ir.Value] = {} + opset = _get_onnxscript_opset(registry.opset_version) + + for node in fx_graph.nodes: + logger.debug( + "%s", (node.name, node.args, node.target, node.op, node.type, node.kwargs) + ) + try: + if node.op == "placeholder": + _handle_placeholder_node( + node, + node_name_to_values, + graph_like=graph_like, + lower=lower, + opset=opset, + ) + elif node.op == "call_function": + if lower == "at_conversion": + _handle_call_function_node_with_lowering( + model, + node, + node_name_to_values, + graph_like=graph_like, + constant_farm=constant_farm, + registry=registry, + opset=opset, + node_name_to_local_functions=node_name_to_local_functions, + ) + else: + # No lowering + _handle_call_function_node(graph_like, node, node_name_to_values) + elif node.op == "get_attr": + _handle_get_attr_node( + node, + owned_graphs=owned_graphs, + node_name_to_local_functions=node_name_to_local_functions, + ) + elif node.op == "output": + _handle_output_node( + node, + node_name_to_values, + graph_like=graph_like, + ) + except Exception as e: + raise _errors.ConversionError( + f"Error when translating node {node.format_node()}. See the stack trace for more information." + ) from e + return node_name_to_values + + +def _get_inputs_and_attributes( + node: torch.fx.Node, +) -> tuple[list[torch.fx.Node | None], dict[str, Any], list[str], list[str]]: + """Find and Fill in the not provided kwargs with default values. + + Returns: + (inputs, attributes, input_names, output_names) + """ + if inspect.isbuiltin(node.target) or isinstance(node.target, str): + inputs = list(node.args) + return inputs, {}, [], [node.name] # type: ignore[return-value] + + # The target should be an ATen operator now + assert hasattr(node.target, "_schema"), ( + f"The target should be an ATen operator now, but node target {node.target} has no schema" + ) + node_schema: torch.FunctionSchema = node.target._schema + + # This function assumes the order of arguments in FX op is the + # same as the order of arguments in TorchScript op. + inputs: list[Any] = [] # type: ignore[no-redef] + input_names: list[str] = [] + attributes: dict[str, Any] = {} + + if inspect.isbuiltin(node.target): + inputs = list(node.args) + else: + for arg, schema_arg in zip(node.args, node_schema.arguments): + if arg is None or isinstance(arg, torch.fx.Node): + inputs.append(arg) + input_names.append(schema_arg.name) + elif isinstance(arg, Sequence) and all( + elem is None or isinstance(elem, torch.fx.Node) for elem in arg + ): + inputs.extend(arg) + input_names.extend([schema_arg.name] * len(arg)) + elif isinstance(arg, torch.device): + attributes[schema_arg.name] = str(arg) + elif isinstance(arg, torch.dtype): + attributes[schema_arg.name] = _torch_dtype_to_onnx_dtype(arg) + else: + attributes[schema_arg.name] = arg + for schema_arg in node_schema.arguments: + if schema_arg.name not in node.kwargs: + continue + kwarg = node.kwargs[schema_arg.name] + if schema_arg.name in { + "layout", + "device", + "requires_grad", + "memory_format", + "implicit", + } or isinstance(kwarg, torch.device): + attr = str(kwarg) + elif isinstance(kwarg, torch.dtype): + attr = _torch_dtype_to_onnx_dtype(kwarg) # type: ignore[assignment] + else: + attr = kwarg # type: ignore[assignment] + + attributes[schema_arg.name] = attr + + output_names = [f"{node.name}_{output.name}" for output in node_schema.returns] + + return inputs, attributes, input_names, output_names # type: ignore[return-value] + + +def _maybe_start_profiler(should_profile: bool) -> Any: + if should_profile: + import pyinstrument # type: ignore[import-not-found] + + profiler = pyinstrument.Profiler(async_mode="disabled") + profiler.start() + return profiler + return None + + +def _maybe_stop_profiler_and_get_result(profiler) -> str | None: + if profiler is None: + return None + profiler.stop() + return profiler.output_text(unicode=True) + + +def _format_exception(e: Exception) -> str: + """Format the full traceback as Python would show it.""" + return "\n".join(traceback.format_exception(type(e), e, e.__traceback__)) + + +def _summarize_exception_stack(e: BaseException) -> str: + """Format the exception stack by showing the text of each exception.""" + causes = [e] + while e.__cause__ is not None: + causes.append(e.__cause__) + e = e.__cause__ + return ( + "\n\n## Exception summary\n\n" + + "⬆️\n".join([f"{type(e)}: {e}\n" for e in reversed(causes)]) + + "\n(Refer to the full stack trace above for more information.)" + ) + + +def _format_exceptions_for_all_strategies( + results: list[_capture_strategies.Result], +) -> str: + """Format all the exceptions from the capture strategies.""" + return "\n".join( + [ + f"# ⚠️ Errors from strategy '{result.strategy}': -----------------------\n\n" + f"{_format_exception(result.exception)}\n" + for result in results + if result.exception is not None + ] + ) + + +def exported_program_to_ir( + exported_program: torch.export.ExportedProgram, + *, + registry: _registration.ONNXRegistry | None = None, + lower: Literal["at_conversion", "none"] = "at_conversion", +) -> ir.Model: + """Convert an exported program to an ONNX IR model. + + Reference: + - ExportedProgram spec: https://pytorch.org/docs/stable/export.ir_spec.html + + Args: + exported_program: The exported program to convert. + lower: Whether to lower the graph to core ONNX operators. + at_conversion: Lower whe translating the FX graph to ONNX IR. + none: Do not lower the graph. + registry: The registry of all ONNX Script decomposition. + """ + if registry is None: + registry = _registration.ONNXRegistry.from_torchlib() + if lower != "none": + exported_program = _prepare_exported_program_for_export( + exported_program, registry=registry + ) + return _exported_program_to_onnx_program( + exported_program, registry=registry, lower=lower + ).model + + +def _prepare_exported_program_for_export( + exported_program: torch.export.ExportedProgram, + *, + registry: _registration.ONNXRegistry, +) -> torch.export.ExportedProgram: + """Decompose and apply pre-export transformations to the exported program.""" + + # Decompose the graph given the implemented torch ops in ONNX + exported_program = _fx_passes.decompose_with_registry(exported_program, registry) + + graph_module = exported_program.graph_module + # Include explicit type promotion nodes + _fx_passes.insert_type_promotion_nodes(graph_module) + graph_module = _fx_passes.remove_assertion_nodes(graph_module) + # Reassign the graph module to save some runtime. + exported_program._graph_module = graph_module + return exported_program + + +def _get_scope_name(scoped_name: str) -> tuple[str, str]: + """Get the scope and name of a node. + + Examples:: + >>> _get_scope_name('') + ('', '') + >>> _get_scope_name('true_graph') + ('', 'true_graph') + >>> _get_scope_name('true_graph.false_graph') + ('true_graph', 'false_graph') + >>> _get_scope_name('true_graph.false_graph.some_graph') + ('true_graph.false_graph', 'some_graph') + + Args: + scoped_name: The scoped name of the node. + + Returns: + (scope, name) + """ + if "." in scoped_name: + scope, name = scoped_name.rsplit(".", 1) + else: + scope, name = "", scoped_name + return scope, name + + +def _exported_program_to_onnx_program( + exported_program: torch.export.ExportedProgram, + *, + registry: _registration.ONNXRegistry, + lower: Literal["at_conversion", "none"] = "at_conversion", +) -> _onnx_program.ONNXProgram: + """Convert an exported program to an ONNX Program. + + The exported_program field in the returned ONNXProgram is one that is after + decompositions have been applied. + + Reference: + - ExportedProgram spec: https://pytorch.org/docs/stable/export.ir_spec.html + + Args: + exported_program: The exported program to convert. The exported program + should be the one that is after decompositions have been applied. + lower: Whether to lower the graph to core ONNX operators. + at_conversion: Lower whe translating the FX graph to ONNX IR. + none: Do not lower the graph. + registry: The registry of all ONNX Script decomposition. + """ + model = ir.Model( + graph=ir.Graph( + [], + [], + nodes=[], + # Opset imports are added to the model in the final add_opset_imports pass + name="main_graph", + metadata_props={ + "pkg.torch.export.ExportedProgram.graph_signature": str( + exported_program.graph_signature + ), + "pkg.torch.export.ExportedProgram.range_constraints": str( + exported_program.range_constraints + ), + }, + ), + ir_version=_constants.ONNX_IR_VERSION, + producer_name="pytorch", + producer_version=torch.__version__, + ) + + # A dictionary storing the translated subgraphs as ONNX functions made available to outer graphs + # {: {: }} + scoped_subgraphs: dict[str, dict[str, ir.Function]] = {} + values = None + + # 1. Translate all nodes in all subgraphs and the main graph + # Create a dictionary of values for the main graph for step 2-3 to add inputs and outputs + module: torch.fx.GraphModule + # Reverse the order of the modules so that the innermost module is processed first + # and made available to the outer module + for name, module in reversed( + tuple(exported_program.graph_module.named_modules(remove_duplicate=False)) + ): + # Obtain the graphs (previously built) owned by the current module + owned_graphs = scoped_subgraphs.setdefault(name, {}) + fx_graph = module.graph + + graph_like: ir.Graph | ir.Function + if name == "": + # Root graph + graph_like = model.graph + else: + function_name = name.replace(".", "__") + # Inputs and outputs will be created within _translate_fx_graph + func = ir.Function( + domain=_constants.LOCAL_FUNCTION_DOMAIN, + name=function_name, + graph=ir.Graph((), (), nodes=()), + attributes=(), + ) + # Make this function available to the outer graph + scope, subgraph_name = _get_scope_name(name) + scoped_subgraphs.setdefault(scope, {})[subgraph_name] = func + model.functions[func.identifier()] = func + graph_like = func + + values = _translate_fx_graph( + fx_graph, + model, + graph_like=graph_like, + owned_graphs=owned_graphs, + lower=lower, + registry=registry, + ) + + assert name == "", "The last module processed should be the root module" + assert values is not None + + # Clear the input/output of the main graph and add them back in step 2-3 + # using the more accurate graph signature + model.graph.inputs.clear() + model.graph.outputs.clear() + + # 2. Add user inputs and all parameters/buffers to the graph. + # Since the node names and the tensor names are different, we need to rename + # the nodes to match the tensor names later. For now we will just use the node names. + user_inputs = [ + spec + for spec in exported_program.graph_signature.input_specs + if spec.kind == graph_signature.InputKind.USER_INPUT + ] + non_user_inputs = [ + spec + for spec in exported_program.graph_signature.input_specs + if spec.kind != graph_signature.InputKind.USER_INPUT + ] + + for spec in itertools.chain(user_inputs, non_user_inputs): + # Put the user inputs first and then the parameters/buffers + if isinstance(spec.arg, graph_signature.ConstantArgument): + logger.debug("Skipping constant argument %s", spec.arg) + continue + value_name = spec.arg.name + input_kind = spec.kind + persistent = spec.persistent + value = values[value_name] + + assert not isinstance(value, Sequence), ( + f"Input '{value_name}' should not be a sequence. This is unexpected." + ) + + value.metadata_props["pkg.torch.export.graph_signature.InputSpec.kind"] = ( + input_kind.name + ) + value.metadata_props[ + "pkg.torch.export.graph_signature.InputSpec.persistent" + ] = str(persistent) + + if input_kind == graph_signature.InputKind.USER_INPUT: + # Add only user inputs to the graph + # Subsequent passes can decide if they want to add initializers as inputs + model.graph.inputs.append(value) + else: + model.graph.initializers[value_name] = value + + # 3. Add user outputs to the graph and assign metadata to all outputs + user_outputs = [ + spec + for spec in exported_program.graph_signature.output_specs + if spec.kind == graph_signature.OutputKind.USER_OUTPUT + ] + non_user_outputs = [ + spec + for spec in exported_program.graph_signature.output_specs + if spec.kind != graph_signature.OutputKind.USER_OUTPUT + ] + for spec in itertools.chain(user_outputs, non_user_outputs): + if isinstance(spec.arg, graph_signature.ConstantArgument): + logger.warning("Skipping constant argument %s", spec.arg) + continue + value_name = spec.arg.name + output_kind = spec.kind + value = values[value_name] + + if not isinstance(value, (ir.Value, Sequence)): + raise TypeError( + f"Output '{value_name}' should be an ir.Value. Actual type is '{type(value)}': {value!r}. " + "This may be due to an incorrect implementation of the ONNX function that produced this output." + ) + + # The output value may be a sequence, meaning the operator has multiple outputs + _values = (value,) if not isinstance(value, Sequence) else value + + if len(_values) > 1: + logger.warning( + "Model output '%s' has multiple values: %s (output spec: %s). Please make sure this is expected.", + value_name, + _values, + spec, + ) + + for value in _values: + value.metadata_props["pkg.torch.export.graph_signature.OutputSpec.kind"] = ( + output_kind.name + ) + if output_kind == graph_signature.OutputKind.USER_OUTPUT: + model.graph.outputs.append(value) + + # 4. Rename the initializers to match the tensor names + for name, param_name in itertools.chain( + exported_program.graph_signature.inputs_to_parameters.items(), + exported_program.graph_signature.inputs_to_buffers.items(), + exported_program.graph_signature.inputs_to_lifted_tensor_constants.items(), + ): + initializer = model.graph.initializers.pop(name) + initializer.name = param_name + # Record the original name so users can search the metadata and correspond + # with the FX graph + initializer.metadata_props["pkg.torch.onnx.original_node_name"] = name + model.graph.initializers[param_name] = initializer + + # 5. Add initializers to the graph + # ExportedProgram stores parameters and buffers in state_dict, + # but non_persistent_buffers and lifted_tensor_constants are not there + # so we need to get them from the name_* apis. + for name, torch_tensor in itertools.chain( + exported_program.named_parameters(), + exported_program.named_buffers(), + exported_program.constants.items(), + ): + initializer = model.graph.initializers.get(name) # type: ignore[assignment] + if initializer is None: + logger.warning("Tensor '%s' is not one of the initializers", name) + continue + if not isinstance(torch_tensor, torch.Tensor): + raise NotImplementedError( + f"Tensor '{name}' should be a torch.Tensor. Actual type is '{type(torch_tensor)}': {torch_tensor!r}. " + "This is unexpected and not yet supported." + ) + ir_tensor = TorchTensor(torch_tensor, name=name) + initializer.const_value = ir_tensor + _set_shape_type( + initializer, + torch_tensor, + complex_to_float=lower != "none", + ) + + # TODO: Decide if we should keep mutated buffers as inputs/outputs + + # TODO(justinchuby): Remove the hack + _ir_passes.add_torchlib_common_imports(model) + + # Collect and add opset imports to the model + _ir_passes.add_opset_imports(model) + + return _onnx_program.ONNXProgram(model, exported_program) + + +def _verbose_printer(verbose: bool | None) -> Callable[..., None]: + """Prints messages based on `verbose`.""" + if verbose is False: + return lambda *_, **__: None + return lambda *args, **kwargs: print("[torch.onnx]", *args, **kwargs) + + +def export( + model: torch.nn.Module + | torch.export.ExportedProgram + | torch.fx.GraphModule + | torch.jit.ScriptModule + | torch.jit.ScriptFunction, + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + *, + registry: _registration.ONNXRegistry | None = None, + dynamic_shapes: dict[str, Any] | tuple[Any, ...] | list[Any] | None = None, + input_names: Sequence[str] | None = None, + output_names: Sequence[str] | None = None, + report: bool = False, + verify: bool = False, + profile: bool = False, + dump_exported_program: bool = False, + artifacts_dir: str | os.PathLike = ".", + verbose: bool | None = None, +) -> _onnx_program.ONNXProgram: + """Export a PyTorch model to ONNXProgram. + + Args: + model: The model to export. This can be a PyTorch nn.Module or an ExportedProgram. + args: The arguments to pass to the model. + kwargs: The keyword arguments to pass to the model. + registry: The registry of all ONNX decompositions. + dynamic_shapes: Dynamic shapes in the graph. + input_names: If provided, rename the inputs. + output_names: If provided, rename the outputs. + report: Whether to generate an error report if the export fails. + verify: Whether to verify the ONNX model after exporting. + profile: Whether to profile the export process. When report is True, + the profile result will be saved in the report. Otherwise, the profile + result will be printed. + dump_exported_program: Whether to save the exported program to a file. + artifacts_dir: The directory to save the exported program and error reports. + verbose: Whether to print verbose messages. If None (default), some messages will be printed. + + Returns: + The ONNXProgram with the exported IR graph. + + Raises: + TorchExportError: If the export process fails with torch.export. + ConversionError: If the ExportedProgram to ONNX translation fails. + """ + # Set up the error reporting facilities + timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S-%f") + profiler = _maybe_start_profiler(profile) + + # Create the artifacts directory if it does not exist + artifacts_dir = pathlib.Path(artifacts_dir) + if report or profile or dump_exported_program: + artifacts_dir.mkdir(parents=True, exist_ok=True) + + verbose_print = _verbose_printer(verbose) + export_status = _reporting.ExportStatus() + failed_results: list[_capture_strategies.Result] = [] + + program: torch.export.ExportedProgram | None = None + capture_strategy: str | None = None + # Step 1: Export the model with torch.export.export if the model is not already an ExportedProgram + if isinstance(model, torch.export.ExportedProgram): + # We know the model is already exported program, so the args, kwargs, and dynamic_shapes + # are not used. + program = model + export_status.torch_export = True + else: + # Convert an nn.Module to an ExportedProgram + # Try everything 🐰 (all paths for getting an ExportedProgram) + # When input is a JIT module, the last strategy will succeed so it is handled + result: _capture_strategies.Result | None = None + for strategy_class in _capture_strategies.CAPTURE_STRATEGIES: + strategy = strategy_class( # type: ignore[abstract] + verbose=verbose is not False, # Treat None as verbose + dump=dump_exported_program, + artifacts_dir=artifacts_dir, + timestamp=timestamp, + ) + result = strategy(model, args, kwargs, dynamic_shapes=dynamic_shapes) + + # Record the status + if strategy_class is _capture_strategies.TorchExportNonStrictStrategy: + export_status.torch_export_non_strict = result.success + elif strategy_class is _capture_strategies.TorchExportStrategy: + export_status.torch_export = result.success + elif strategy_class is _capture_strategies.JitTraceConvertStrategy: + export_status.torch_jit = result.success + + if result.exported_program is not None: + program = result.exported_program + break + else: + failed_results.append(result) + + assert result is not None + capture_strategy = result.strategy + if result.exported_program is None: + # If all strategies fail, produce an error report and raise the first error + profile_result = _maybe_stop_profiler_and_get_result(profiler) + + if report: + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + + try: + _reporting.create_torch_export_error_report( + report_path, + _format_exceptions_for_all_strategies(failed_results), + export_status=export_status, + profile_result=profile_result, + ) + except Exception as e_report: + verbose_print( + f"Failed to save error report due to an error: {e_report}" + ) + else: + report_path = None + + first_error = failed_results[0].exception + assert first_error is not None + + # NOTE: We only throw the torch.export (first) exception because we want to + # focus on the torch.export.export error. Errors from other strategies like + # torch.jit.trace is due to the fallback and can be confusing to users. + # We save all errors in the error report. + raise _errors.TorchExportError( + _STEP_ONE_ERROR_MESSAGE + + ( + f"\nError report has been saved to '{report_path}'." + if report + else "" + ) + + _summarize_exception_stack(first_error) + ) from first_error + + assert program is not None + + if dump_exported_program: + verbose_print("Dumping ExportedProgram because `dump_exported_program=True`...") + program_path = artifacts_dir / f"onnx_export_{timestamp}.pt2" + try: + torch.export.save(program, program_path) + except Exception as e: + verbose_print(f"Failed to save ExportedProgram due to an error: {e}") + else: + verbose_print(f"ExportedProgram has been saved to '{program_path}'.") + + # Step 2: Decompose the exported program and insert type promotion nodes + verbose_print("Run decomposition...") + + try: + # Build the ONNX function registry + if registry is None: + registry = _registration.ONNXRegistry.from_torchlib() + + # Process the exported program to run decompositions and type promotions etc. + decomposed_program = _prepare_exported_program_for_export( + program, registry=registry + ) + except Exception as e: + export_status.decomposition = False + verbose_print("Run decomposition... ❌") + profile_result = _maybe_stop_profiler_and_get_result(profiler) + + if report: + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + + # Run the analysis to get the error report + try: + _reporting.create_onnx_export_report( + report_path, + f"{_format_exceptions_for_all_strategies(failed_results)}\n\n{_format_exception(e)}", + program, + export_status=export_status, + profile_result=profile_result, + registry=registry, + ) + except Exception: + logger.exception("Failed to save report due to an error.") + else: + report_path = None + + raise _errors.ConversionError( + _STEP_TWO_ERROR_MESSAGE + + (f"\nError report has been saved to '{report_path}'." if report else "") + + _summarize_exception_stack(e) + ) from e + else: + export_status.decomposition = True + verbose_print("Run decomposition... ✅") + + # Step 3: Translate the decomposed program to ONNX and produce ONNXProgram + verbose_print("Translate the graph into ONNX...") + if report or profile: + pre_decomp_unique_ops, post_decomp_unique_ops = _analysis.compare_ops( + program, decomposed_program + ) + else: + pre_decomp_unique_ops = None + post_decomp_unique_ops = None + + try: + # Convert the exported program to an ONNX model + onnx_program = _exported_program_to_onnx_program( + decomposed_program, registry=registry + ) + # Record the strategy used for getting the exported program for unit test assertions + onnx_program._capture_strategy = capture_strategy + + # Run the ONNX passes + if input_names: + _ir_passes.rename_inputs(onnx_program.model, input_names) + if output_names: + _ir_passes.rename_outputs(onnx_program.model, output_names) + + export_status.onnx_translation = True + verbose_print("Translate the graph into ONNX... ✅") + except Exception as e: + export_status.onnx_translation = False + verbose_print("Translate the graph into ONNX... ❌") + profile_result = _maybe_stop_profiler_and_get_result(profiler) + + if report: + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + + try: + assert pre_decomp_unique_ops is not None + assert post_decomp_unique_ops is not None + + # Run the analysis to get the error report + _reporting.create_onnx_export_report( + report_path, + f"{_format_exceptions_for_all_strategies(failed_results)}\n\n{_format_exception(e)}", + decomposed_program, + decomp_comparison=_reporting.format_decomp_comparison( + pre_decomp_unique_ops, post_decomp_unique_ops + ), + export_status=export_status, + profile_result=profile_result, + registry=registry, + ) + verbose_print(f"Export report has been saved to '{report_path}'.") + except Exception: + logger.exception("Failed to save report due to an error.") + else: + report_path = None + + raise _errors.ConversionError( + _STEP_THREE_ERROR_MESSAGE + + (f"\nError report has been saved to '{report_path}'." if report else "") + + _summarize_exception_stack(e) + ) from e + + profile_result = _maybe_stop_profiler_and_get_result(profiler) + + assert onnx_program.exported_program is not None + + if not verify: + # Return if verification is not requested + if report: + try: + assert pre_decomp_unique_ops is not None + assert post_decomp_unique_ops is not None + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + _reporting.create_onnx_export_report( + report_path, + "No errors" + if not failed_results + else _format_exceptions_for_all_strategies(failed_results), + onnx_program.exported_program, + decomp_comparison=_reporting.format_decomp_comparison( + pre_decomp_unique_ops, post_decomp_unique_ops + ), + export_status=export_status, + profile_result=profile_result, + model=onnx_program.model, + registry=registry, + ) + verbose_print(f"Export report has been saved to '{report_path}'.") + except Exception: + logger.exception("Failed to save report due to an error.") + elif profile and profile_result is not None: + verbose_print("Profile result:") + verbose_print(profile_result) + return onnx_program + + # Step 4: (verify=True) Check the ONNX model with ONNX checker + try: + verbose_print("Check the ONNX model...") + onnxscript_apis.check_model(onnx_program.model) + export_status.onnx_checker = True + verbose_print("Check the ONNX model... ✅") + except Exception as e: + export_status.onnx_checker = False + verbose_print("Check the ONNX model... ❌") + if report: + try: + assert pre_decomp_unique_ops is not None + assert post_decomp_unique_ops is not None + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + _reporting.create_onnx_export_report( + report_path, + f"{_format_exceptions_for_all_strategies(failed_results)}\n\n{_format_exception(e)}", + onnx_program.exported_program, + decomp_comparison=_reporting.format_decomp_comparison( + pre_decomp_unique_ops, post_decomp_unique_ops + ), + export_status=export_status, + profile_result=profile_result, + model=onnx_program.model, + registry=registry, + ) + verbose_print(f"Export report has been saved to '{report_path}'.") + except Exception: + logger.exception("Failed to save report due to an error.") + logger.warning( + "Conversion successful but the ONNX model fails ONNX checker. " # noqa: G004 + "Please create an issue " + f"in the PyTorch GitHub repository against the {_BLUE}*onnx*{_END} component and " + "attach the full error stack as well as reproduction scripts. ", + exc_info=e, + ) + return onnx_program + + # Step 5: (verify=True) Execute the model with ONNX Runtime + try: + verbose_print("Execute the model with ONNX Runtime...") + verification_results = _verification.verify_onnx_program(onnx_program) + verbose_print("Execute the model with ONNX Runtime... ✅") + export_status.onnx_runtime = True + onnx_runtime_error_message = None + except Exception as e: + verbose_print("Execute the model with ONNX Runtime... ❌") + export_status.onnx_runtime = False + onnx_runtime_error_message = _format_exception(e) + verification_message = None + + else: + # Step 6: (verify=True) Validate the output values + verbose_print("Verify output accuracy...") + export_status.output_accuracy = True + for verification_result in verification_results: + # TODO(justinchuby): The threshold is arbitrary right now + if verification_result.max_abs_diff >= 5e-3: + logger.warning( + "Output '%s' has a large absolute difference of %f. ", + verification_result.name, + verification_result.max_abs_diff, + ) + export_status.output_accuracy = False + if verification_result.max_rel_diff >= 1e-1: + logger.warning( + "Output '%s' has a large relative difference of %f. ", + verification_result.name, + verification_result.max_rel_diff, + ) + export_status.output_accuracy = False + if export_status.output_accuracy: + verbose_print("Verify output accuracy... ✅") + else: + verbose_print("Verify output accuracy... ❌") + verification_message = _reporting.format_verification_infos( + verification_results + ) + + if report: + try: + assert pre_decomp_unique_ops is not None + assert post_decomp_unique_ops is not None + + traceback_lines = [] + if failed_results: + traceback_lines.append( + _format_exceptions_for_all_strategies(failed_results) + ) + if onnx_runtime_error_message: + traceback_lines.append("# ⚠️ ONNX Runtime error -----------------------") + traceback_lines.append(onnx_runtime_error_message) + if not traceback_lines: + traceback_lines.append("No errors") + + report_path = artifacts_dir / _reporting.construct_report_file_name( + timestamp, export_status + ) + _reporting.create_onnx_export_report( + report_path, + "\n\n".join(traceback_lines), + onnx_program.exported_program, + profile_result=profile_result, + export_status=export_status, + decomp_comparison=_reporting.format_decomp_comparison( + pre_decomp_unique_ops, post_decomp_unique_ops + ), + model=onnx_program.model, + registry=registry, + verification_result=verification_message, + ) + verbose_print(f"Export report has been saved to '{report_path}'.") + except Exception: + logger.exception("Failed to save report due to an error.") + + # Release the inference session created during verification + onnx_program.release() + return onnx_program diff --git a/shared/package-files/18/1814c3c2d16833610c37891c54e274ae70b4a38466a77202744e6d564fa8b815/generator.cpython-311.pyc b/shared/package-files/18/1814c3c2d16833610c37891c54e274ae70b4a38466a77202744e6d564fa8b815/generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f8a99a3db0874bc62284f8caeb17855c3f36bf1 Binary files /dev/null and b/shared/package-files/18/1814c3c2d16833610c37891c54e274ae70b4a38466a77202744e6d564fa8b815/generator.cpython-311.pyc differ diff --git a/shared/package-files/18/1819d82e373f7449777a3bbd33c9cd8e2606c2348563869f745c8c8e6aeefc3e/svd_ops.h b/shared/package-files/18/1819d82e373f7449777a3bbd33c9cd8e2606c2348563869f745c8c8e6aeefc3e/svd_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0c579e397dcf3d7313fea2ece090ebb95edfc889 --- /dev/null +++ b/shared/package-files/18/1819d82e373f7449777a3bbd33c9cd8e2606c2348563869f745c8c8e6aeefc3e/svd_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API svd_U { + using schema = ::std::tuple (const at::Tensor &, bool, bool, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::svd"; + static constexpr const char* overload_name = "U"; + static constexpr const char* schema_str = "svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V)"; + static ::std::tuple call(const at::Tensor & self, bool some, bool compute_uv, at::Tensor & U, at::Tensor & S, at::Tensor & V); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool some, bool compute_uv, at::Tensor & U, at::Tensor & S, at::Tensor & V); +}; + +struct TORCH_API svd { + using schema = ::std::tuple (const at::Tensor &, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::svd"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V)"; + static ::std::tuple call(const at::Tensor & self, bool some, bool compute_uv); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool some, bool compute_uv); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/1822cd89939b1f6b2dd4846e27973291f72a4f8d667657565f73e472d95e5f62/common.py b/shared/package-files/18/1822cd89939b1f6b2dd4846e27973291f72a4f8d667657565f73e472d95e5f62/common.py new file mode 100644 index 0000000000000000000000000000000000000000..152d2ef36197fc46d8a820cfc8faf64f37fe7667 --- /dev/null +++ b/shared/package-files/18/1822cd89939b1f6b2dd4846e27973291f72a4f8d667657565f73e472d95e5f62/common.py @@ -0,0 +1,2596 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import enum +import functools +import itertools +import logging +import math +import operator +import re +import typing +from enum import auto, Enum +from itertools import chain +from typing import ( + Any, + Callable, + cast, + ClassVar, + Generic, + NamedTuple, + Optional, + TYPE_CHECKING, + Union, +) +from typing_extensions import TypeVar + +import sympy + +import torch +import torch.fx +from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.printers import PythonPrinter as _PythonPrinter +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT +from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + +from .. import config, metrics +from ..dtype_propagation import DtypePropagationOpsHandler +from ..ops_handler import BasicMathOpsMixin, DefaultHandler +from ..utils import ( + boolean_ops, + DeferredLineBase, + generate_assert, + IndentedBuffer, + ir_dataclass, + ScopedDict, + sympy_dot, + sympy_index_symbol, + sympy_subs, + triton_type, + unique, +) +from ..virtualized import ops, OpsHandler, OpsValue, ReductionType, StoreMode, V + + +if TYPE_CHECKING: + from collections.abc import Iterator, MutableMapping, Sequence + + from ..ir import Buffer, ChoiceCaller, FixedLayout, IRNode + from ..loop_body import LoopBody + from ..scheduler import BaseScheduling, Scheduler, SchedulerNode + from .wrapper import PythonWrapperCodegen + + _T = TypeVar("_T") + SchedulingConstructor = Callable[[Optional[Scheduler]], BaseScheduling] + WrapperConstructor = type[PythonWrapperCodegen] + SymbolLike = Union[str, sympy.Symbol] + + # OpVarT should really be Union[CSEVariable, str], however this + # causes typing errors in subclasses (defined in other files). + OpVarT = str + +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") +log = logging.getLogger(__name__) + + +def data_type_logger(msg: str) -> None: + if schedule_log.isEnabledFor(logging.DEBUG): + schedule_log.debug("Data type propagation: %s", msg) + + +class WorkspaceZeroMode(enum.Enum): + UNINITIALIZED = 0 + ZERO_ON_CALL = 1 # kernel may leave workspace dirty + ZERO_PER_GRAPH = 2 # must be re-zeroed by kernel + + @staticmethod + def combine(a: WorkspaceZeroMode, b: WorkspaceZeroMode) -> WorkspaceZeroMode: + if a == b or b == WorkspaceZeroMode.UNINITIALIZED: + return a + if a == WorkspaceZeroMode.UNINITIALIZED: + return b + raise NotImplementedError(f"WorkspaceZeroMode.combine({a!r}, {b!r})") + + @staticmethod + def from_bool(zero_fill: bool) -> WorkspaceZeroMode: + if zero_fill: + return WorkspaceZeroMode.ZERO_ON_CALL + return WorkspaceZeroMode.UNINITIALIZED + + +@ir_dataclass(frozen=True) +class WorkspaceArg: + """A temporary buffer used for a single kernel, then discarded. + + Not registered as a traditional buffer since there are no users, + so it would be dead code eliminated. + + Args: + nbytes: The size of the buffer in bytes. + zero_fill: Whether the buffer should be initialized to zero. + + """ + + count: sympy.Expr + zero_mode: WorkspaceZeroMode + device: torch.device + outer_name: str + inner_name: str = "ws_ptr" + dtype: torch.dtype = torch.uint8 + + @staticmethod + def unique_name(prefix: str = "workspace_") -> str: + return f"{prefix}{next(V.graph.workspace_id)}" + + @staticmethod + def can_join(a: WorkspaceArg, b: WorkspaceArg) -> bool: + return ( + a.inner_name == b.inner_name and a.dtype == b.dtype and a.device == b.device + ) + + @staticmethod + def join(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + return WorkspaceArg( + count=a.count + b.count, + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + @staticmethod + def maximum(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + assert ( + a.dtype == b.dtype and a.device == b.device and a.inner_name == b.inner_name + ) + return WorkspaceArg( + count=sympy.Max(a.count, b.count), + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + # These methods let WorkspaceArg pretend it is a buffer to reuse allocation code + def get_device(self) -> torch.device: + return self.device + + get_device_or_error = get_device + + def get_dtype(self) -> torch.dtype: + return self.dtype + + def get_layout(self) -> FixedLayout: + from ..ir import FixedLayout + + return FixedLayout( + device=self.device, + dtype=self.dtype, + size=[self.count], + stride=[1], + ) + + @property + def layout(self) -> FixedLayout: + return self.get_layout() + + get_output_spec = get_layout + maybe_get_output_spec = get_layout + maybe_get_layout = get_layout + + def get_size(self) -> list[sympy.Expr]: + return [self.count] + + def get_stride(self) -> list[sympy.Expr]: + return [sympy.S.One] + + def get_name(self) -> str: + return self.outer_name + + def get_inputs_that_alias_output(self) -> list[str]: + return [] + + +@dataclasses.dataclass +class TensorArg: + name: str + buffer: str + dtype: torch.dtype + offset: sympy.Expr = sympy.S.Zero # c++ only + alias_of: Optional[str] = None # halide only + + +@dataclasses.dataclass +class SizeArg: + name: str + expr: sympy.Expr + + @property + def alias_of(self) -> Optional[str]: + return None + + +@dataclasses.dataclass +class ConstexprArg: + name: str + + +@dataclasses.dataclass +class TMADescriptorArg: + name: str + + +@dataclasses.dataclass +class DeviceCodegen: + scheduling: SchedulingConstructor + wrapper_codegen: WrapperConstructor + cpp_wrapper_codegen: Optional[WrapperConstructor] = None + + +KernelArgType = Union[WorkspaceArg, TensorArg, SizeArg, TMADescriptorArg, ConstexprArg] + +device_codegens: dict[str, DeviceCodegen] = {} + + +class DeviceOpOverrides: + def import_get_raw_stream_as(self, name: str) -> str: + raise NotImplementedError + + def set_device(self, device_idx: int) -> str: + raise NotImplementedError + + def synchronize(self) -> str: + raise NotImplementedError + + def device_guard(self, device_idx: int) -> str: + raise NotImplementedError + + def cpp_device_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_device_guard(self) -> str: + raise NotImplementedError + + def cpp_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_getStreamFromExternal(self) -> str: + raise NotImplementedError + + def kernel_header(self) -> str: + raise NotImplementedError + + def kernel_driver(self) -> str: + raise NotImplementedError + + def cpp_stream_type(self) -> str: + raise NotImplementedError + + def aoti_get_stream(self) -> str: + raise NotImplementedError + + def cpp_kernel_type(self) -> str: + raise NotImplementedError + + def cpp_device_ptr(self) -> str: + raise NotImplementedError + + def tma_descriptor_helpers(self) -> str: + raise NotImplementedError + + def cpp_global_scratch(self, idx: int) -> Optional[tuple[str, str]]: + # optionally return (scratch definition, arg name) + raise NotImplementedError + + +device_op_overrides_dict: dict[str, DeviceOpOverrides] = {} + + +# The code generated by Inductor consists of two main parts: kernel code and wrapper code. +# For any new backend looking to integrate with Inductor, customization of these two main +# parts are necessary to generate its specific code. +# +# Kernel code generation is determined by different Scheduling. Consequently, a new +# backend needs to provide a custom Scheduling for its unique kernel code generation. Currently, +# CppScheduling and TritonScheduling serve the C++/OpenMP and Triton backends, respectively. +# +# For the Wrapper, Inductor provides a PythonWrapperCodegen class to generate the Python wrapper code +# that bridges kernels. This allows out-of-tree backends to inherit from PythonWrapperCodegen, +# and override specific member functions to create backend-specific Python wrapper code. +# +# Other classes, such as CppKernel and TritonKernel, used for code generation, typically form part +# of the logic for either Scheduling or PythonWrapperCodegen. So the Scheduling and PythonWrapperCodegen interfaces +# provide flexibility to the backend. A backend can choose to implement these classes from scratch, +# or reuse them by extending and overriding as necessary. And Inductor provides the registration API, +# register_backend_for_device, to equip a new backend at runtime. +# +# Intel has developed a new backend on top of Triton to support Intel GPUs, leveraging these interfaces. +# This backend can be used as a reference: +# https://github.com/intel/intel-extension-for-pytorch/blob/5dcc9d57e5422cf295e1a1ee97896d6b6a554a85/intel_extension_for_pytorch/_inductor/__init__.py#L9 +def register_backend_for_device( + device: str, + device_scheduling: SchedulingConstructor, + device_wrapper_codegen: WrapperConstructor, + device_cpp_wrapper_codegen: Optional[WrapperConstructor] = None, +) -> None: + device_codegens[device] = DeviceCodegen( + device_scheduling, device_wrapper_codegen, device_cpp_wrapper_codegen + ) + + +class BackendFeature(Enum): + FOREACH = auto() + BUCKETIZE = auto() + INPLACE_BUFFERS = auto() + MASKED_SCATTER_WITH_INDEX = auto() + SCAN = auto() + SORT = auto() + TUPLE_REDUCTION = auto() + PREFER_STORE_LOOP_ORDER = auto() + TRITON_TEMPLATES = auto() + REDUCE_TO_SINGLE_ELEMENT = auto() + + +def get_backend_features( + device: Union[torch.device, str, None], +) -> OrderedSet[BackendFeature]: + if device is None: + return OrderedSet() + init_backend_registration() + if isinstance(device, torch.device): + device_type = device.type + else: + assert isinstance(device, str) + device_type = device + device = torch.device(device_type) + scheduling_ctor = get_scheduling_for_device(device_type) + assert scheduling_ctor + scheduling = scheduling_ctor(None) + return scheduling.get_backend_features(device) + + +def has_backend_feature( + device: Union[torch.device, str, None], feature: BackendFeature +) -> bool: + """See also V.graph.has_feature""" + assert isinstance(feature, BackendFeature) + return feature in get_backend_features(device) + + +def get_scheduling_for_device(device: str) -> Optional[SchedulingConstructor]: + return device_codegens[device].scheduling if device in device_codegens else None + + +def get_wrapper_codegen_for_device( + device: str, cpp_wrapper: bool = False +) -> Optional[WrapperConstructor]: + if device in device_codegens: + wrapper_codegen_obj: DeviceCodegen = device_codegens[device] + return ( + wrapper_codegen_obj.cpp_wrapper_codegen + if cpp_wrapper + else wrapper_codegen_obj.wrapper_codegen + ) + return None + + +@functools.lru_cache(None) +def init_backend_registration() -> None: + from .cpp import CppScheduling + from .cpp_wrapper_cpu import CppWrapperCpu + from .cpp_wrapper_cpu_array_ref import CppWrapperCpuArrayRef + from .cpp_wrapper_gpu import CppWrapperGpu + from .cuda_combined_scheduling import CUDACombinedScheduling + from .halide import HalideScheduling + from .mps import MetalScheduling + from .triton import TritonScheduling + from .wrapper import PythonWrapperCodegen + + if get_scheduling_for_device("cpu") is None: + cpu_backends = { + "cpp": CppScheduling, + "halide": HalideScheduling, + "triton": TritonScheduling, + } + register_backend_for_device( + "cpu", + lambda scheduling: cpu_backends[config.cpu_backend](scheduling), + PythonWrapperCodegen, + CppWrapperCpuArrayRef + if config.aot_inductor.allow_stack_allocation + else CppWrapperCpu, + ) + + if get_scheduling_for_device("cuda") is None: + # CUDACombinedScheduling combines Triton and CUDA C++ scheduling for CUDA devices via delegation + cuda_backends = { + "triton": CUDACombinedScheduling, + "halide": HalideScheduling, + } + register_backend_for_device( + "cuda", + lambda scheduling: cuda_backends[config.cuda_backend](scheduling), + PythonWrapperCodegen, + CppWrapperGpu, + ) + + if get_scheduling_for_device("xpu") is None: + register_backend_for_device( + "xpu", + TritonScheduling, + PythonWrapperCodegen, + CppWrapperGpu, + ) + + if get_scheduling_for_device("mps") is None: + register_backend_for_device( + "mps", + MetalScheduling, + PythonWrapperCodegen, + CppWrapperGpu, + ) + + private_backend = torch._C._get_privateuse1_backend_name() + if ( + private_backend != "privateuseone" + and get_scheduling_for_device(private_backend) is None + ): + from torch.utils.backend_registration import _get_custom_mod_func + + try: + device_scheduling = _get_custom_mod_func("Scheduling") + wrapper_codegen = _get_custom_mod_func("PythonWrapperCodegen") + cpp_wrapper_codegen = _get_custom_mod_func("CppWrapperCodegen") + if device_scheduling and wrapper_codegen and cpp_wrapper_codegen: + register_backend_for_device( + private_backend, + device_scheduling, + wrapper_codegen, + cpp_wrapper_codegen, + ) + except RuntimeError: + pass + + +def index_prevent_reordering( + index: Sequence[sympy.Expr], + index_vars: Sequence[sympy.Expr], + sizes: Sequence[sympy.Expr], +) -> list[sympy.Expr]: + from ..ir import FlexibleLayout + + # added contiguous index prevents reordering + return [*index, sympy_dot(index_vars, FlexibleLayout.contiguous_strides(sizes))] + + +def register_device_op_overrides( + device: str, device_op_overrides: DeviceOpOverrides +) -> None: + device_op_overrides_dict[device] = device_op_overrides + + +def get_device_op_overrides(device: str) -> DeviceOpOverrides: + assert isinstance(device, str) + + if not device_op_overrides_dict: + from . import cpu_device_op_overrides, mps_device_op_overrides # noqa: F401 + from .cuda import device_op_overrides # noqa: F401 + from .xpu import device_op_overrides as xpu_op_overrides # noqa: F401 + + return device_op_overrides_dict[device] + + +DTYPE_TO_COMPUTATION_DTYPE: dict[torch.dtype, torch.dtype] = { + torch.bfloat16: torch.float, + torch.float16: torch.float, + **{ + dtype: dtype + for dtype in [ + torch.bool, + torch.float32, + torch.float64, + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ] + }, +} + + +def deduce_output_dtype_by_name( + op_name: str, + *args: Any, + **kwargs: Any, +) -> Optional[torch.dtype]: + """ + Given op name and a list of input dtypes, deduce the output dtype + """ + if op_name in boolean_ops(): + return torch.bool + elif op_name in ( + "to_dtype", + "index_expr", + ): + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "rand", + "randn", + ): + return torch.float + elif op_name in ( + "get_index", + "randint64", + "load_seed", + ): + return torch.int64 + elif op_name == "reduction": + return kwargs["dtype"] if "dtype" in kwargs else args[1] + elif op_name == "constant": + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "load", + "store", + "store_reduction", + ): + buf_name = args[1] + return V.graph.get_dtype(buf_name) # type: ignore[arg-type] + elif op_name == "to_dtype_bitcast": + return kwargs["dtype"] if "dtype" in kwargs else args[-2] + return None + + +class DataTypePropagation: + def __init__(self, body: LoopBody) -> None: + self.body = body + self.graphs: dict[Union[Callable[..., Any], str], Any] = { + "root": body.root_block.graph + } + for k, v in body.subblocks.items(): + self.graphs[k] = v.graph + + def deduce_node_dtype_by_inputs(self, node: torch.fx.Node) -> Optional[torch.dtype]: + inputs = node.all_input_nodes + input_nodes = [ + n for n in inputs if isinstance(n, torch.fx.Node) and n.op != "placeholder" + ] + if len(input_nodes) == 0: + return None + + all_input_nodes_propagated = all( + OptimizationContext.key in n.meta + and n.meta[OptimizationContext.key].dtype is not None + for n in input_nodes + ) + if not all_input_nodes_propagated: + return None + + return functools.reduce( + torch.promote_types, + [n.meta[OptimizationContext.key].dtype for n in input_nodes], + ) + + def deduce_node_dtype_by_subgraph(self, node: torch.fx.Node) -> torch.dtype: + sub_graph = self.graphs[node.target] + dtype = self.propagate_graph(sub_graph) + assert dtype + return dtype + + def deduce_node_dtype(self, node: torch.fx.Node) -> Optional[torch.dtype]: + if node.op == "placeholder": + return None + + if node.target == "output" and len(node.args) != 1: + # we can infer output node if it only have 1 arg + return None + + if node.target == operator.getitem: + return self.deduce_node_dtype(node.args[0]) # type: ignore[arg-type] + + assert isinstance(node.target, str) + + if node.target.startswith("masked_subblock"): + return self.deduce_node_dtype_by_subgraph(node) + + if ( + output_dtype := deduce_output_dtype_by_name( + node.target, + *node.args, + **node.kwargs, + ) + ) is not None: + return output_dtype + + return self.deduce_node_dtype_by_inputs(node) + + def propagate_graph(self, graph: torch.fx.Graph) -> Optional[torch.dtype]: + assert graph.nodes + graph_dtype: Optional[torch.dtype] = None + # For masked_subblock, we use output's dtype to represent + # the dtype of this subgraph. For other cases, graph_dtype + # might be None + for node in graph.nodes: + if OptimizationContext.key in node.meta: + opt_ctx = node.meta[OptimizationContext.key] + else: + opt_ctx = OptimizationContext() + + opt_ctx.dtype = self.deduce_node_dtype(node) + node.meta[OptimizationContext.key] = opt_ctx + if node.target == "output": + graph_dtype = opt_ctx.dtype + return graph_dtype + + def propagate(self) -> Optional[torch.dtype]: + return self.propagate_graph(self.graphs["root"]) + + @classmethod + def propagate_loopbody(cls, body: LoopBody) -> Optional[torch.dtype]: + return cls(body).propagate() + + @classmethod + def propagate_scheduler_node(cls, node: SchedulerNode) -> Optional[torch.dtype]: + from ..loop_body import LoopBody + from ..scheduler import SchedulerNode + + assert isinstance(node, SchedulerNode) + assert isinstance(node._body, LoopBody) + return DataTypePropagation.propagate_loopbody(node._body) + + +class PythonPrinter(_PythonPrinter): + def doprint( + self, expr: sympy.Expr, *, simplify: bool = True, p: bool = True + ) -> str: + # TODO: why are people passing strings to the printer here :think: + if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"): + expr = V.graph.sizevars.simplify(expr) + return super().doprint(expr) + + +class OpDecompositions: + """ + Decomposes inductor ops + """ + + @staticmethod + def identity(value: OpVarT) -> OpVarT: + # used to trigger cse + return value + + @staticmethod + def reciprocal(x: OpVarT) -> OpVarT: + return ops.truediv(ops.constant(1, torch.int32), x) + + @staticmethod + def square(x: OpVarT) -> OpVarT: + return ops.mul(x, x) + + @staticmethod + def erfc(x: OpVarT) -> OpVarT: + return ops.sub(ops.constant(1, torch.float32), ops.erf(x)) + + @staticmethod + def erfcx(x: OpVarT) -> OpVarT: + return ops.mul(ops.exp(ops.square(x)), ops.erfc(x)) + + @staticmethod + def expm1(x: OpVarT) -> OpVarT: + return ops.sub(ops.exp(x), ops.constant(1, torch.float32)) + + @staticmethod + def log10(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(10), torch.float32)) + + @staticmethod + def log2(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(2), torch.float32)) + + @staticmethod + def exp2(x: OpVarT) -> OpVarT: + return ops.exp(ops.mul(x, ops.constant(math.log(2), torch.float32))) + + @staticmethod + def log1p(x: OpVarT) -> OpVarT: + return ops.log(ops.add(x, ops.constant(1, torch.int32))) + + @staticmethod + def sigmoid(x: OpVarT) -> OpVarT: + one = ops.constant(1, torch.int32) + return ops.truediv(one, ops.add(one, ops.exp(ops.neg(x)))) + + @staticmethod + def relu(x: OpVarT) -> OpVarT: + return ops.maximum(x, ops.constant(0, torch.int32)) + + @staticmethod + def fma(x: OpVarT, y: OpVarT, z: OpVarT) -> OpVarT: + # for backends that don't override this (halide) + return ops.add(ops.mul(x, y), z) + + @staticmethod + def floor_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.floor(a), dtype) + + @staticmethod + def ceil_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.ceil(a), dtype) + + @staticmethod + def trunc_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.trunc(a), dtype) + + @staticmethod + def remainder(a: OpVarT, b: OpVarT) -> OpVarT: + r = ops.mod(a, b) + cond = ops.and_( + ops.ne(r, ops.constant(0, torch.int32)), + ops.ne(ops.signbit(r), ops.signbit(b)), + ) + return ops.where(cond, ops.add(r, b), r) + + @staticmethod + def round_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.round(a), dtype) + + +_RE_PAREN_NOT_NEEDED = re.compile(r"[a-z0-9_.]+|\([^)]*\)|", flags=re.IGNORECASE) + + +def _all_in_parens(string: str) -> bool: + if string[0] != "(" or len(string) < 2: + return False + count = 1 + for i, char in enumerate(string[1:]): + if char == "(": + count += 1 + elif char == ")": + count -= 1 + if count == 0 and i != len(string) - 2: + return False + assert count == 0 + return True + + +class OpOverrides(BasicMathOpsMixin, OpDecompositions, OpsHandler[Any]): + @staticmethod + def paren(string: OpVarT) -> OpVarT: + if ( + isinstance(string, CSEVariable) + or _RE_PAREN_NOT_NEEDED.fullmatch(string) + or _all_in_parens(string) + ): + # don't put extra parens for strings that are already wrapped in parens + return string + return f"({string})" + + @staticmethod + def constant(value: Union[bool, float, int], dtype: torch.dtype) -> OpVarT: + return repr(value) + + @staticmethod + def libdevice_sigmoid(x: OpVarT) -> OpVarT: + one = ops.constant(1, torch.int32) + return ops.truediv(one, ops.add(one, ops.libdevice_exp(ops.neg(x)))) + + @staticmethod + def libdevice_abs(x: OpVarT) -> OpVarT: + return ops.abs(x) + + @staticmethod + def libdevice_sqrt(x: OpVarT) -> OpVarT: + return ops.sqrt(x) + + @staticmethod + def libdevice_cos(x: OpVarT) -> OpVarT: + return ops.cos(x) + + @staticmethod + def libdevice_sin(x: OpVarT) -> OpVarT: + return ops.sin(x) + + @staticmethod + def libdevice_log(x: OpVarT) -> OpVarT: + return ops.log(x) + + @staticmethod + def libdevice_exp(x: OpVarT) -> OpVarT: + return ops.exp(x) + + @staticmethod + def bitwise_not(x: OpVarT) -> OpVarT: + return f"~{OpOverrides.paren(x)}" + + @staticmethod + def logical_not(a: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(a)} == 0" + + @staticmethod + def bitwise_and(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} & {OpOverrides.paren(y)}" + + @staticmethod + def bitwise_or(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} | {OpOverrides.paren(y)}" + + @staticmethod + def bitwise_xor(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} ^ {OpOverrides.paren(y)}" + + @staticmethod + def bitwise_left_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} << {OpOverrides.paren(y)}" + + @staticmethod + def bitwise_right_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} >> {OpOverrides.paren(y)}" + + @staticmethod + def int_truediv(a: OpVarT, b: OpVarT) -> OpVarT: + # TODO: this is wrong + # TODO: an easy bandaid is to generate runtime asserts that it's + # <= 2**53, which is when this equation is correct + return ops.truediv(a, b) + + @staticmethod + def load_seed(name: str, offset: OpVarT) -> OpVarT: + return ops.load(name, sympy.Integer(offset)) + + def indirect_indexing( + self, + var: OpVarT, + size: Union[sympy.Expr, int], + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + return sympy_index_symbol(str(var)) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: check_bounds should be handled by CSEProxy" + ) + + def load(self, name: str, index: sympy.Expr) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: load should be handled by CSEProxy" + ) + + def store( + self, name: str, index: sympy.Expr, value: OpVarT, mode: StoreMode = None + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store should be handled by CSEProxy" + ) + + def store_reduction(self, name: str, index: sympy.Expr, value: OpVarT) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store_reduction should be handled by CSEProxy" + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: Union[OpVarT, tuple[OpVarT, ...]], + ) -> Union[OpVarT, tuple[OpVarT, ...]]: + raise NotImplementedError( + f"{type(self).__name__}: reduction should be handled by CSEProxy" + ) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[OpVarT, ...], tuple[OpVarT, ...]], + tuple[OpVarT, ...], + ], + values: tuple[OpVarT, ...], + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: scan should be handled by CSEProxy" + ) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[OpVarT, ...], + stable: bool, + descending: bool, + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: sort should be handled by CSEProxy" + ) + + def bucketize( + self, + values: OpVarT, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: OpVarT, + indexing_dtype: torch.dtype, + right: bool, + sorter: Optional[tuple[str, sympy.Expr]] = None, + sorter_indices: Optional[OpVarT] = None, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: bucketize should be handled by CSEProxy" + ) + + def halide_clamp(self, value: OpVarT, size: sympy.Expr, check: bool) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: halide_clamp only implemented for Halide backend" + ) + + def inline_asm_elementwise( + self, + *inputs: OpVarT, + asm: str, + constraints: Optional[str] = None, + dtype: torch.dtype = torch.float32, + is_pure: bool = True, + pack: int = 1, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: inline_asm_elementwise only implemented for Triton backend" + ) + + def output(self, *args: OpVarT) -> None: + raise AssertionError( + f"{type(self).__name__}: ops.output should not appear at codegen time" + ) + + def placeholder(self, index: int) -> OpVarT: + raise AssertionError( + f"{type(self).__name__}: ops.placeholder should not appear at codegen time" + ) + + @staticmethod + def _unimplemented(name: str) -> Callable[..., OpVarT]: + def unimplemented(self: OpOverrides, *args: Any, **kwargs: Any) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__} does not implement ops.{name}" + ) + + unimplemented.__name__ = name + unimplemented.is_unimplemented = True # type: ignore[attr-defined] + return unimplemented + + @classmethod + def _is_unimplemented(cls, name: str) -> bool: + fn = getattr(cls, name, None) + default_fn = getattr(OpsHandler, name, None) + return not fn or fn == default_fn or getattr(fn, "is_unimplemented", False) + + @classmethod + def _initialize_pointwise_overrides(cls, target: str) -> None: + assert target in ("triton", "cpp", "cppvec", "halide", "mps"), target + + for funcname, data in pointwise_overrides_data.items(): + impl = getattr(data, target) + if impl is None: + if cls._is_unimplemented(funcname): + setattr(cls, funcname, cls._unimplemented(funcname)) + else: + assert funcname not in cls.__dict__, ( + f"multiple definitions of {funcname} on {cls.__name__}" + ) + impl.__name__ = funcname + setattr(cls, funcname, staticmethod(impl)) + + +@dataclasses.dataclass +class OverridesData: + name: str + cpp: Callable[..., str] + # None when not impl in libdevice/triton + triton: Optional[Callable[..., str]] = None + # None when not impl in aten/.../vec + cppvec: Optional[Callable[..., str]] = None + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + halide: Optional[Callable[..., str]] = None + mps: Optional[Callable[..., str]] = None + + +# NB: if you add a new special function, don't forget to update +# torch._inductor.ops_handler too +pointwise_overrides_data: dict[str, OverridesData] = dict( + airy_ai=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"airy_ai_forward({x})", + name="special_airy_ai", + ), + bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j0_forward({x})", + triton=lambda x: f"libdevice.j0({x})", + name="special_bessel_j0", + ), + bessel_j1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j1_forward({x})", + triton=lambda x: f"libdevice.j1({x})", + name="special_bessel_j1", + ), + bessel_y0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y0_forward({x})", + triton=lambda x: f"libdevice.y0({x})", + name="special_bessel_y0", + ), + bessel_y1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y1_forward({x})", + triton=lambda x: f"libdevice.y1({x})", + name="special_bessel_y1", + ), + digamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_digamma({x})", + cppvec=lambda x: f"{x}.digamma()", + name="digamma", + ), + # no cpp nor triton implementation for entr, it is defined as decomposition + # erf, erfc + erfcx=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_erfcx({x})", + triton=lambda x: f"libdevice.erfcx({x})", + name="special_erfcx", + ), + fma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y, z: f"std::fma({x}, {y}, {z})", + cppvec=lambda x, y, z: f"fmadd({x}, {y}, {z})", + triton=lambda x, y, z: f"libdevice.fma({x}, {y}, {z})", + name="fma", + ), + # erfinv, exp2, expit, gammaln + igamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="igamma", + ), + igammac=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="igammac", + ), + gammainc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="special_gammainc", + ), + gammaincc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="special_gammaincc", + ), + i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0({x})", + triton=lambda x: f"libdevice.cyl_bessel_i0({x})", + cppvec=lambda x: f"{x}.i0()", + name="i0", + ), + i0e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0e({x})", + cppvec=lambda x: f"{x}.i0e()", + name="special_i0e", + ), + i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1({x})", + triton=lambda x: f"libdevice.cyl_bessel_i1({x})", + name="special_i1", + ), + i1e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1e({x})", + name="special_i1e", + ), + log_ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_log_ndtr({x})", + name="special_log_ndtr", + ), + # logit + modified_bessel_i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i0_forward({x})", + triton=lambda x: f"libdevice.cyl_bessel_i0({x})", + name="special_modified_bessel_i0", + ), + modified_bessel_i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i1_forward({x})", + triton=lambda x: f"libdevice.cyl_bessel_i1({x})", + name="special_modified_bessel_i1", + ), + modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k0_forward({x})", + name="special_modified_bessel_k0", + ), + modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k1_forward({x})", + name="special_modified_bessel_k1", + ), + # multigamma + ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtr({x})", + name="special_ndtr", + ), + ndtri=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtri({x})", + name="special_ndtri", + ), + polygamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"{x} == 0 ? calc_digamma({y}) : calc_polygamma({y}, {x})", + name="polygamma", + ), + # psi - alias to digamma + # round + scaled_modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k0_forward({x})", + name="special_scaled_modified_bessel_k0", + ), + scaled_modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k1_forward({x})", + name="special_scaled_modified_bessel_k1", + ), + # sinc + spherical_bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"spherical_bessel_j0_forward({x})", + name="special_spherical_bessel_j0", + ), + zeta=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"zeta({x}, {y})", + name="special_zeta", + ), + chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_t_forward({x}, {y})", + name="special_chebyshev_polynomial_t", + ), + chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_u_forward({x}, {y})", + name="special_chebyshev_polynomial_u", + ), + chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_v_forward({x}, {y})", + name="special_chebyshev_polynomial_v", + ), + chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_w_forward({x}, {y})", + name="special_chebyshev_polynomial_w", + ), + legendre_polynomial_p=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"legendre_polynomial_p_forward({x}, {y})", + name="special_legendre_polynomial_p", + ), + shifted_chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_t_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_t", + ), + shifted_chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_u_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_u", + ), + shifted_chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_v_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_v", + ), + shifted_chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_w_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_w", + ), + hermite_polynomial_h=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_h_forward({x}, {y})", + name="special_hermite_polynomial_h", + ), + hermite_polynomial_he=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_he_forward({x}, {y})", + name="special_hermite_polynomial_he", + ), + laguerre_polynomial_l=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"laguerre_polynomial_l_forward({x}, {y})", + name="special_laguerre_polynomial_l", + ), +) + + +def is_buffer_removed(name: str) -> bool: + return any( + name in x + for x in ( + V.graph.removed_buffers, + V.kernel.removed_buffers, + V.graph.inplaced_to_remove, + V.kernel.inplaced_to_remove, + ) + ) + + +class DeferredLine(DeferredLineBase): + """A line that can be 'unwritten' by adding name to V.graph.removed_buffers""" + + def __init__(self, name: str, line: str): + super().__init__(line) + self.name = name + assert not isinstance(line, DeferredLineBase) + + def __call__(self) -> Optional[str]: + if not is_buffer_removed(self.name): + return self.line + return None + + def _new_line(self, line: str) -> DeferredLine: + return DeferredLine(self.name, line) + + +class BracesBuffer(IndentedBuffer): + def indent(self, offset: int = 1) -> contextlib.AbstractContextManager[None]: + @contextlib.contextmanager + def ctx() -> Iterator[None]: + for _ in range(offset): + self.writeline("{") + self._indent += 1 + for _ in range(-offset): + self._indent -= 1 + self.writeline("}") + yield + for _ in range(-offset): + self.writeline("{") + self._indent += 1 + for _ in range(offset): + self._indent -= 1 + self.writeline("}") + + return ctx() + + +class InplacedBuffer(NamedTuple): + inner_name: str + other_names: list[str] + + +@dataclasses.dataclass +class ArgName: + name: str + # is_constexpr=True is used to attach a " : tl.constexpr" into the argument list + is_constexpr: bool = False + + def full_name(self) -> str: + return f"{self.name}{' : tl.constexpr' if self.is_constexpr else ''}" + + +class RemovedArg: + def __str__(self) -> str: + return "REMOVED" + + +REMOVED = RemovedArg() + + +class KernelArgs: + @staticmethod + def _lookup( + prefix: str, + odict: Union[dict[_T, Union[str, RemovedArg]], dict[_T, str]], + name: _T, + ) -> str: + result: Union[str, RemovedArg] = odict.get(name, REMOVED) + if isinstance(result, RemovedArg): + odict[name] = new_result = f"{prefix}{len(odict)}" + return new_result + return result + + def __init__(self) -> None: + self.input_buffers: dict[str, str] = {} + self.output_buffers: dict[str, Union[str, RemovedArg]] = {} + self.inplace_buffers: dict[str, Union[InplacedBuffer, RemovedArg]] = {} + self.sizevars: dict[sympy.Expr, str] = {} + self.workspace_args: list[WorkspaceArg] = [] + + def __repr__(self) -> str: + return "KernelArgs({})".format( + ", ".join( + map( + repr, + [ + self.input_buffers, + self.output_buffers, + self.inplace_buffers, + self.sizevars, + ], + ) + ) + ) + + @staticmethod + def _buffer_is_marked_removed(name: Any) -> bool: + # this function is needed by MTIA + return isinstance(name, RemovedArg) + + def input(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + assert name not in V.graph.removed_buffers, name + if name in self.output_buffers: + return cast(str, self.output_buffers[name]) + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + if name.startswith("seed"): + return self._lookup("seed", self.input_buffers, name) + return self._lookup("in_ptr", self.input_buffers, name) + + def output(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + assert name not in V.graph.removed_buffers, name + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + return self._lookup("out_ptr", self.output_buffers, name) + + def make_inplace(self, input_name: str, output_name: str) -> None: + assert output_name not in self.inplace_buffers + if input_name in self.inplace_buffers: + buf = self.inplace_buffers[input_name] + assert not isinstance(buf, RemovedArg) + buf.other_names.append(output_name) + self.inplace_buffers[output_name] = buf + else: + alive_buffers = [ + val + for val in self.inplace_buffers.values() + if not isinstance(val, RemovedArg) + ] + removed_buffers = [ + val + for val in self.inplace_buffers.values() + if isinstance(val, RemovedArg) + ] + inplace_buffer_idx = len(unique(alive_buffers)) + len(removed_buffers) + buf = InplacedBuffer( + f"in_out_ptr{inplace_buffer_idx}", + [input_name, output_name], + ) + self.inplace_buffers[input_name] = buf + self.inplace_buffers[output_name] = buf + + def workspace(self, nbytes: sympy.Expr, zero_fill: bool) -> tuple[str, int]: + """ + Allocate or extend a workspace buffer of nbytes bytes. + + This function manages the allocation of a workspace buffer. It either creates + a new WorkspaceArg or extends an existing one. + + Note: + - Calling this function will in-place mutate the args by adding or updating + a WorkspaceArg. + - The codegen for generating the Python argdefs and call_defs will check + this field and allocate the buffer accordingly. + - A new argument "ws_ptr" will be present in the generated code. + + Args: + nbytes (sympy.Expr): The number of bytes to allocate. + zero_fill (bool): Whether to initialize the buffer to zero. + + Returns: + Tuple[str, int]: A tuple containing: + - "ws_ptr": A string identifier for the workspace pointer. + - offset: An integer representing the byte offset in the workspace. + """ + arg = WorkspaceArg( + count=nbytes, + zero_mode=WorkspaceZeroMode.from_bool(zero_fill), + device=V.graph.get_current_device_or_throw(), + outer_name=WorkspaceArg.unique_name(), + ) + for i, existing_arg in enumerate(self.workspace_args): + if WorkspaceArg.can_join(existing_arg, arg): + offset = existing_arg.count + self.workspace_args[i] = WorkspaceArg.join(existing_arg, arg) + return existing_arg.inner_name, offset + assert ( + existing_arg.inner_name != arg.inner_name + and existing_arg.outer_name != arg.outer_name + ) + self.workspace_args.append(arg) + return arg.inner_name, 0 + + def semaphores(self, min_size: sympy.Expr) -> str: + """ + Lazily allocate a graph-wide semaphores buffer with at least min_size. This is a single buffer shared by + all kernels and zero initialized once at graph start. Each kernel must leave the buffer zeroed on exit. + + Warning: multiple calls to this function will return the same buffer. + + Args: + min_size: the number of int32 semaphores required + + Returns: + name of the semaphores buffer + """ + current_device = V.graph.get_current_device_or_throw() + arg = WorkspaceArg( + count=min_size, + zero_mode=WorkspaceZeroMode.ZERO_PER_GRAPH, + dtype=torch.uint32, + inner_name="sem_ptr", + outer_name=f"semaphores_{current_device.type}_{current_device.index}", + device=current_device, + ) + for existing_arg in self.workspace_args: + if existing_arg.inner_name == arg.inner_name: + assert arg == existing_arg + self.workspace_args.append(arg) + return arg.inner_name + + def seed_offset(self, name: str, value: int) -> str: + assert isinstance(value, int), (type(value), value) + # here we are lifting a constant integer into an arg to the kernel to try to get additional cache hits + value = sympy.Integer(value) + if value in self.sizevars: + return self.sizevars[value] + if name in self.sizevars.values(): + name = ( + f"{name}{sum(1 for v in self.sizevars.values() if v.startswith(name))}" + ) + self.sizevars[value] = name + return name + + def size(self, name: sympy.Symbol) -> str: + assert isinstance(name, sympy.Symbol), (type(name), name) + if name.name == "seed": + self.sizevars[name] = "seed" # dont' mange the name of seeds + return "seed" + return self._lookup("ks", self.sizevars, name) + + def call_names(self) -> Iterator[str]: + return chain( + self.input_buffers.keys(), self.output_buffers.keys(), self.sizevars.keys() + ) + + def arg_name(self, name: str) -> Optional[str]: + """ + Returns inner name of a given outer name. + """ + inplaced = self.inplace_buffers.get(name, None) + if inplaced is not None and not isinstance(inplaced, RemovedArg): + return inplaced.inner_name + output_name = self.output_buffers.get(name, None) + if output_name is not None and not isinstance(output_name, RemovedArg): + return output_name + return self.input_buffers.get(name, None) + + def wrap_ptr_arg(self, buf: str, dtype: torch.dtype) -> str: + return buf + + def wrap_size_arg(self, size: SymbolLike) -> str: + return str(size) + + def cpp_argdefs(self) -> tuple[list[str], list[str], list[str]]: + from .cpp_utils import DTYPE_TO_CPP, INDEX_TYPE + + call_args = [] + arg_defs = [] + arg_types = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + outer = inplaced.other_names[-1] + inner = inplaced.inner_name + dtype = V.graph.get_dtype(outer) + cpp_dtype = DTYPE_TO_CPP[dtype] + arg_defs.append(f"{cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.input_buffers.items(): + if outer in self.inplace_buffers: + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = DTYPE_TO_CPP[dtype] + arg_defs.append(f"const {cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"const {cpp_dtype}*") + for outer, maybe_inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(maybe_inner, RemovedArg): + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = DTYPE_TO_CPP[dtype] + arg_defs.append(f"{cpp_dtype}* {maybe_inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.sizevars.items(): + arg_defs.append(f"const {INDEX_TYPE} {inner}") + call_args.append(self.wrap_size_arg(outer)) + arg_types.append(f"const {INDEX_TYPE}") + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + assert not self.workspace_args, "Workspace not supported on CPU " + return arg_defs, call_args, arg_types + + def python_argdefs( + self, + ) -> tuple[list[ArgName], list[str], list[KernelArgType], list[Any]]: + arg_defs: list[ArgName] = [] + call_args: list[str] = [] + arg_types: list[torch.dtype] = [] + precompile_args: list[KernelArgType] = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + arg_defs.append(ArgName(inplaced.inner_name)) + call_args.append(inplaced.other_names[-1]) + arg_types.append(V.graph.get_dtype(inplaced.other_names[-1])) + precompile_args.append( + TensorArg( + name=inplaced.inner_name, + buffer=inplaced.other_names[-1], + dtype=V.graph.get_dtype(inplaced.other_names[-1]), + ) + ) + for outer, inner in chain( + self.input_buffers.items(), self.output_buffers.items() + ): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(V.graph.get_dtype(outer)) + precompile_args.append( + TensorArg( + name=inner, + buffer=outer, + dtype=V.graph.get_dtype(outer), + ) + ) + for outer, inner in self.sizevars.items(): + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(type(outer)) # type: ignore[arg-type] + precompile_args.append(SizeArg(inner, outer)) + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + for arg in self.workspace_args: + arg_defs.append(ArgName(arg.inner_name)) + call_args.append(arg.outer_name) + precompile_args.append(arg) + arg_types.append(arg.dtype) + return arg_defs, call_args, precompile_args, arg_types + + def aliases(self) -> Iterator[tuple[str, str]]: + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + for other in inplaced.other_names: + if ( + other in V.graph.inplaced_to_remove + or other in V.kernel.inplaced_to_remove + ): + continue + if other in self.input_buffers: + yield self.input_buffers[other], inplaced.inner_name + if other in self.output_buffers: + yield cast(str, self.output_buffers[other]), inplaced.inner_name + + def is_removed(self, name: str) -> bool: + return isinstance( + self.output_buffers.get(name, REMOVED), RemovedArg + ) and isinstance(self.inplace_buffers.get(name, REMOVED), RemovedArg) + + # Includes inplace buffers, excludes removed buffers. Essentially, + # after you do a call into this kernel, which buffers actually contain + # updated data? Modeled off of python_argdefs. + def live_output_buffers(self) -> OrderedSet[str]: + live_outs = OrderedSet() # type: ignore[var-annotated] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + live_outs.add(inplaced.other_names[-1]) + for outer, inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + live_outs.add(outer) + return live_outs + + +class CSEVariable: + """A CSEVariable is just a name for an expression but it is useful to be able to annotate them on a backend dependent basis. + To do so, the backends can simply overload `Kernel.create_cse_var` + The "CSEVariable.update_on_args" method gives you a hook for annotations + See example of TritonCSEVariable in triton.py + """ + + def __init__( + self, + name: str, + bounds: ValueRanges[Any], + dtype: Optional[torch.dtype] = None, + ): + super().__init__() + assert isinstance(bounds, ValueRanges) + self.name = name + self.bounds = bounds + self.use_count = 1 # track how many times this expression is used + self.dtype = dtype + + def __str__(self) -> str: + return self.name + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: object) -> bool: + return isinstance(other, CSEVariable) and other.name == self.name + + def update_on_args(self, name: str, args: Any, kwargs: Any) -> None: + pass + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.name!r})" + + +AugmentedKeyT = TypeVar("AugmentedKeyT", default=str) +CSEVariableType = TypeVar("CSEVariableType", bound=CSEVariable, default=CSEVariable) + +if TYPE_CHECKING: + ReductionCacheKey = tuple[ + torch.dtype, + ReductionType, + Union[CSEVariable, tuple[CSEVariable, ...]], + ] + + +class CSE(Generic[CSEVariableType, AugmentedKeyT]): + """Common subexpression elimination""" + + def __init__( + self, + prefix: str = "", + suffix: str = "", + name_prefix: str = "tmp", + iter_buffers: Optional[itertools.count[int]] = None, + store_cache: Optional[MutableMapping[str, CSEVariableType]] = None, + reduction_cache: Optional[ + MutableMapping[ReductionCacheKey, CSEVariableType] + ] = None, + varname_map: Optional[dict[str, CSEVariableType]] = None, + ): + self.prefix = prefix + self.suffix = suffix + self._cache: MutableMapping[AugmentedKeyT, CSEVariableType] = {} + self.name_prefix = name_prefix + self.store_cache: MutableMapping[str, CSEVariableType] = store_cache or {} + self.reduction_cache: MutableMapping[ReductionCacheKey, CSEVariableType] = ( + reduction_cache or {} + ) + self.iter_buffer_ids: itertools.count[int] = iter_buffers or itertools.count() + self.invalidated_stores: OrderedSet[str] = OrderedSet() + self.varname_map: dict[str, CSEVariableType] = varname_map or {} + + def invalidate(self, keep_vars: OrderedSet[CSEVariable]) -> None: + for name, tmp in [*self.store_cache.items()]: + if tmp not in keep_vars: + del self.store_cache[name] + self.invalidated_stores.add(name) + if keep_vars: + self._cache = {k: v for k, v in self._cache.items() if v in keep_vars} + else: + self._cache = {} + + def clone(self) -> typing.Self: + return type(self)( + prefix=self.prefix, + suffix=self.suffix, + name_prefix=self.name_prefix, + iter_buffers=self.iter_buffer_ids, + store_cache=self.store_cache, + varname_map=self.varname_map, + reduction_cache=self.reduction_cache, + ) + + def scoped_copy(self) -> typing.Self: + """Return a copy of using ScopedDict so changes to *_cache aren't visible in self""" + new_cse = self.clone() + new_cse._cache = ScopedDict(self._cache) + new_cse.reduction_cache = ScopedDict(self.reduction_cache) + new_cse.store_cache = ScopedDict(self.store_cache) + return new_cse + + def augment_key(self, cache_key: str) -> AugmentedKeyT: + "Override this method to augment cache key with backend specifics" + return cast(AugmentedKeyT, cache_key) + + def put(self, cache_key: str, val: CSEVariableType) -> None: + self._cache[self.augment_key(cache_key)] = val + + def contains(self, cache_key: str) -> bool: + return self.augment_key(cache_key) in self._cache + + def try_get(self, cache_key: str) -> Optional[CSEVariableType]: + return self._cache.get(self.augment_key(cache_key), None) + + def get(self, cache_key: str) -> CSEVariableType: + return self._cache[self.augment_key(cache_key)] + + def generate( + self, + buffer: IndentedBuffer, + expr: Union[str, CSEVariable, OpsValue, IndentedBuffer, DeferredLineBase], + *, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + write: bool = True, + assignment: bool = True, + dtype: Optional[torch.dtype] = None, + ) -> CSEVariableType: + if isinstance(expr, OpsValue): + expr = expr.value + + assert write or assignment + if isinstance(expr, CSEVariable): + # If the expressions were always created with all the information, we could + # assert expr.bounds == bounds, but sometimes the expression is created + # with the loose ValueRanges.unknown(), so we need to tighten the bounds + expr.bounds = expr.bounds.tighten(bounds) + expr.use_count += 1 + return cast(CSEVariableType, expr) + elif isinstance(expr, IndentedBuffer): + cache_key = expr.getvalue() + elif isinstance(expr, DeferredLineBase): + cache_key = expr.line + else: + assert isinstance(expr, str) + cache_key = expr + var = self.try_get(cache_key) + if not var: + var = self.newvar(bounds, dtype) + self.put(cache_key, var) + if write: + if V.kernel.current_node: + V.kernel.current_node.codegen_originating_info( + buffer, only_once=True + ) + if isinstance(expr, IndentedBuffer): + if assignment: + buffer.writeline(f"{self.prefix}{var} =") + buffer.splice(expr) + buffer.writeline(self.suffix) + elif isinstance(expr, DeferredLineBase): + assert assignment + buffer.writeline( + expr._new_line(f"{self.prefix}{var} = {expr.line}{self.suffix}") + ) + else: + if assignment: + line = f"{self.prefix}{var} = {expr}{self.suffix}" + else: + line = f"{expr}{self.suffix}" + buffer.writeline(line) + + if ( + assignment + and config.test_configs.runtime_triton_dtype_assert + and dtype is not None + ): + assert_line = f"tl.static_assert({self.prefix}{var}.dtype == {triton_type(dtype)})" + buffer.writeline(assert_line) + + else: + var.bounds = var.bounds.tighten(bounds) + var.use_count += 1 + + return var + + def newvar( + self, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: Optional[torch.dtype] = None, + ) -> CSEVariableType: + var_name = f"{self.name_prefix}{next(self.iter_buffer_ids)}" + var = V.kernel.create_cse_var(var_name, bounds, dtype) + self.varname_map[var_name] = var + return var + + def namedvar( + self, + name: str, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: Optional[torch.dtype] = None, + ) -> CSEVariableType: + torch._check_value( + name not in self.varname_map, lambda: f"duplicate name: {name}" + ) + var = V.kernel.create_cse_var(name, bounds, dtype) + self.varname_map[name] = var + return var + + +class CodeGen: + def __init__(self) -> None: + super().__init__() + self.exit_stack = contextlib.ExitStack() + + def __enter__(self) -> typing.Self: + self.exit_stack.__enter__() + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.exit_stack.__exit__(exc_type, exc_val, exc_tb) + + +class Kernel(CodeGen, Generic[CSEVariableType]): + newvar_prefix: str = "" + suffix: str = "" + overrides: Optional[Callable[[], OpsHandler[Any]]] = None + + def __init__( + self, args: Optional[KernelArgs] = None, increase_kernel_count: bool = True + ) -> None: + super().__init__() + if increase_kernel_count: + metrics.generated_kernel_count += 1 + self.args = args or KernelArgs() + self.loads = IndentedBuffer() + self.compute = IndentedBuffer() + self.stores = IndentedBuffer() + + self.num_load = 0 + self.num_reduction = 0 + + self.cse: CSE[CSEVariableType, Any] = CSE(self.newvar_prefix, self.suffix) + self.must_keep_buffers = OrderedSet[str]() + self.store_buffer_names = OrderedSet[str]() + self._load_mask: Optional[str] = None + self._load_other: Union[None, int, float] = None + # OrderedSet in set_current_node + self.current_node: Optional[SchedulerNode] = None + self.node_to_bounds: Optional[dict[torch.fx.Node, ValueRanges[Any]]] = None + + self.removed_buffers = OrderedSet[str]() + self.inplaced_to_remove = OrderedSet[str]() + + # key: the buffer to write + # value: the buffer to read and whose memory can be reused for + # the buffer specified by key + self.inplace_update_buffers: dict[str, str] = {} + # Set minimum number of elements processed per thread. + self.min_elem_per_thread = 1 + self.kernel_name: Optional[str] = None + + @contextlib.contextmanager + def set_current_node(self, node: SchedulerNode) -> Iterator[None]: + prior = self.current_node + self.current_node = node + self.node_to_bounds = node._body.bounds().get_bounds() + try: + yield + finally: + self.current_node = prior + + @contextlib.contextmanager + def swap_buffers( + self, + lb: IndentedBuffer, + cb: Optional[IndentedBuffer] = None, + sb: Optional[IndentedBuffer] = None, + ) -> Iterator[None]: + if cb is None: + cb = lb + if disallow_stores := sb is None: + sb = IndentedBuffer() + loads = self.loads + compute = self.compute + stores = self.stores + cse = self.cse + self.loads = lb + self.compute = cb + self.stores = sb + self.cse = cse.scoped_copy() + try: + yield + finally: + self.loads = loads + self.compute = compute + self.stores = stores + self.cse = cse + if disallow_stores: + assert not sb, "unexpected store inside swap_buffers" + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + raise NotImplementedError + + def indirect_load(self, name: str, index: sympy.Expr) -> CSEVariable: + """A load the depends on an index we have read""" + prior = self.loads + try: + # put the load in the compute section as it might have deps + self.loads = self.compute + return self.load(name, index) + finally: + self.loads = prior + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + raise NotImplementedError + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + raise NotImplementedError + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: Union[CSEVariable, tuple[CSEVariable, ...]], + ) -> Union[CSEVariable, tuple[CSEVariable, ...]]: + raise NotImplementedError + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def var_ranges(self) -> dict[sympy.Symbol, sympy.Expr]: + raise NotImplementedError + + def bucketize( + self, + values: CSEVariable, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: CSEVariable, + indexing_dtype: torch.dtype, + right: bool, + sorter: Optional[tuple[str, sympy.Expr]] = None, + sorter_indices: Optional[CSEVariable] = None, + ) -> CSEVariable: + """ + See [Note: Inductor bucketize op] + """ + raise NotImplementedError + + @property + def assert_function(self) -> str: + raise NotImplementedError + + def indirect_assert( + self, + var: Union[CSEVariable, str], + lower: Optional[str], + upper: Optional[str], + mask: Optional[Union[CSEVariable, str]] = None, + ) -> str: + if isinstance(var, CSEVariable): + var = str(var) + assert isinstance(var, str) + assert lower is None or isinstance(lower, str) + assert upper is None or isinstance(upper, str) + if lower and upper: + # The conditions need to be in parens because of Python's operator precedence. + # It'd be less error-prone to use and/or/not, which is suported by triton + cond = f"({lower} <= {var}) & ({var} < {upper})" + cond_print = f"{lower} <= {var} < {upper}" + elif lower: + cond = f"{lower} <= {var}" + cond_print = cond + else: + assert upper + cond = f"{var} < {upper}" + cond_print = cond + + if mask: + cond = f"({cond}) | ~({mask})" + + return f'{self.assert_function}({cond}, "index out of bounds: {cond_print}")' + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError + + def index_to_str(self, index: sympy.Expr) -> str: + raise NotImplementedError + + def __enter__(self) -> typing.Self: + super().__enter__() + assert self.overrides + self.exit_stack.enter_context( + V.set_ops_handler(CSEProxy(self, self.overrides())) + ) + self.exit_stack.enter_context(V.set_kernel_handler(self)) + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.remove_kernel_local_buffers() + super().__exit__(exc_type, exc_val, exc_tb) + + def remove_kernel_local_buffers(self) -> None: + """ + Any buffers that are both created and have a last use in the + same kernel can be removed. + + Note that V.graph.scheduler can be None when codegening triton template + kernels. + """ + scheduler = V.graph.scheduler + if not scheduler: + return + fused_node_names = OrderedSet( + scheduler.name_to_buf[buf].defining_op_name() + for buf in self.store_buffer_names + if buf in scheduler.name_to_buf + ) + names_to_remove = OrderedSet[str]() + for name in self.store_buffer_names: + if ( + name not in self.must_keep_buffers + and name not in self.args.input_buffers + and scheduler.can_buffer_be_removed_through_fusion( + name, fused_node_names + ) + ): + names_to_remove.add(name) + + for name in names_to_remove: + if name in self.args.inplace_buffers: + buf = self.args.inplace_buffers[name] + if isinstance(buf, RemovedArg): + continue + remove = all(n in names_to_remove for n in buf.other_names) + if remove: + self.remove_inplace_buffer(name) + self.inplaced_to_remove.add(name) + else: + self.remove_buffer(name) + + def remove_buffer(self, name: str) -> None: + # Assign a special value instead of deleting the entry + # because we still rely on output_buffers's length to + # generate unique arg name. + log.debug("remove_buffer(%r)", name) + self.args.output_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def remove_inplace_buffer(self, name: str) -> None: + log.debug("removing_inplace_buffer(%r)", name) + self.args.inplace_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def rename_indexing( + self, index: Union[list[sympy.Expr], tuple[sympy.Expr, ...], sympy.Expr] + ) -> sympy.Expr: + # adds the necessary kernel args for index expressions + # and renames variables in index expressions to kernel arg names + if isinstance(index, (list, tuple)): + return [self.rename_indexing(x) for x in index] # type: ignore[return-value] + index = V.graph.sizevars.simplify(index) + sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) + replacements = { + x: self.args.size(x) + for x in sorted_symbols + if symbol_is_type( + x, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + ), + ) + } + return sympy_subs(index, replacements) + + def create_cse_var(self, *args: Any, **kwargs: Any) -> CSEVariable: + return CSEVariable(*args, **kwargs) + + def arg_name(self, node: IRNode) -> Optional[str]: + """ + Returns arg name of a given input or output node. + """ + if node is None: + return None + return self.args.arg_name(node.get_name()) + + +@dataclasses.dataclass +class OptimizationContext: + key: ClassVar[str] = "opt_ctx" + + dtype: Optional[torch.dtype] = None + ops_name: str = "" + + +@functools.lru_cache(None) +def jinja2_env() -> Any: + try: + import jinja2 + + return jinja2.Environment( + undefined=jinja2.StrictUndefined, + ) + except ImportError: + return None + + +class KernelTemplate: + """ + Base class for defining kernel templates. + + Children classes: TritonTemplate, CUDATemplate + """ + + @staticmethod + def indent_except_first( + source: str, num_indents: int, indents_spacing: int = 4 + ) -> str: + lines = source.splitlines(True) + if len(lines) > 1: + lines[1:] = [ + (" " * indents_spacing * num_indents) + line for line in lines[1:] + ] + return "".join(lines) + + @staticmethod + def _template_from_string(source: str) -> Any: + env = jinja2_env() + if env is None: + return None + env.filters["indent_except_first"] = KernelTemplate.indent_except_first + from jinja2 import TemplateSyntaxError + + try: + return env.from_string(source) + except TemplateSyntaxError as e: + + class DetailedTemplateSyntaxError(TemplateSyntaxError): + def __init__(self, original_error: TemplateSyntaxError) -> None: + super().__init__( + original_error.message, + original_error.lineno, + original_error.name, + original_error.filename, + ) + self.original_error = original_error + + def __str__(self) -> str: + error_info = f"Error in template at line {self.lineno}\n" + error_info += f"Error message: {self.message}\n" + if hasattr(self.original_error, "source"): + lines = self.original_error.source.split("\n") + error_info += "Context:\n" + start = max(0, self.lineno - 2) + end = min(len(lines), self.lineno + 2) + for i in range(start, end): + if i == self.lineno - 1: + error_info += f"{i + 1}: --> {lines[i]}\n" + if hasattr(self.original_error, "column"): + error_info += ( + " " + + " " * (self.original_error.column - 1) + + "^\n" + ) + else: + error_info += f"{i + 1}: {lines[i]}\n" + return error_info + + raise DetailedTemplateSyntaxError(e) from e + + @staticmethod + def _fake_get_dtype( + fake_outs: Union[list[Buffer], Buffer], + ) -> Callable[[str], torch.dtype]: + _get_dtype_real = V.graph.get_dtype + if isinstance(fake_outs, (list, tuple)): + lookup = {buf.get_name(): buf.get_dtype() for buf in fake_outs} + else: + lookup = {fake_outs.get_name(): fake_outs.get_dtype()} + + def get_dtype(name: str) -> torch.dtype: + result = lookup.get(name) + if result is not None: + return result + return _get_dtype_real(name) + + return get_dtype + + def __init__(self, name: str) -> None: + self.name = name + + def maybe_append_choice( + self, choices: list[Any], **kwargs: Any + ) -> Optional[NotImplementedError]: + """ + Maybe generates a new ChoiceCaller and appends it into existing choices. + Returns None if success, otherwise returns the error. + + choices: A list of ChoiceCallers. + kwargs: Additional kwargs to be passed to self.generate() to generate a new ChoiceCaller. + """ + + try: + choices.append(self.generate(**kwargs)) + return None + except NotImplementedError as e: + log.info( + "Cannot Append Choice: %s. KernelTemplate type is %s", + e, + type(self), + stack_info=log.getEffectiveLevel() < logging.INFO, + ) + return e + + def generate(self, **kwargs: Any) -> ChoiceCaller: + """ + Generates a ChoiceCaller instance from the given arguments. + """ + + raise NotImplementedError + + +class CSEProxy(DefaultHandler): + name = "CSEProxy" + + def __init__(self, kernel: Kernel[Any], parent_handler: OpsHandler[Any]): + super().__init__() + from ..bounds import ValueRangeAnalysis + + self.vr_analysis = ValueRangeAnalysis() + self.kernel = kernel + self.parent_handler = parent_handler + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + bounds = self._bound_variable(name, *args, **kwargs) + + value = getattr(self.parent_handler, name)(*args, **kwargs) # type: ignore[has-type] + dtype_handler = DtypePropagationOpsHandler() + + output_idx = 0 + + def do_cse(v: str) -> CSEVariable: + # cpp backend doesnt set current device - TODO: fix + if V.graph.current_device is not None: + device_str = V.graph.get_current_device_or_throw().type + triton_backend = ( + config.cpu_backend == "triton" + if device_str == "cpu" + else config.cuda_backend == "triton" + if device_str != "mps" + else False + ) + else: + triton_backend = False + + # only triton backend tracks dtype currently + if triton_backend: + if name == "masked": + output_dtype = value.dtype + else: + output_dtype = getattr( + dtype_handler, + name, + )(*args, **kwargs) + else: + # cpp backend doesnt track dtype yet + output_dtype = None + + csevar = V.kernel.cse.generate( + V.kernel.compute, + v, + bounds=bounds, + dtype=output_dtype, + ) + + nonlocal output_idx + if config.test_configs.runtime_triton_dtype_assert and triton_backend: + from torch._inductor.codegen.triton import triton_type + + # we tree_map over the output, so we need to fetch corresponding dtype + if isinstance(output_dtype, (list, tuple)): + output_dtype = output_dtype[output_idx] + + V.kernel.compute.writeline( + f"tl.static_assert({csevar}.dtype == {triton_type(output_dtype)})" + ) + output_idx += 1 + + csevar.update_on_args(name, args, kwargs) + + return csevar + + return pytree.tree_map(do_cse, value) + + def _bound_variable(self, name: str, *args: Any, **kwargs: Any) -> ValueRanges[Any]: + """ + If the variable comes from an FX node, we forward the bound we have already computed + Else, if the variable when codegen'ing another op, we try to compute its bounds + """ + from ..bounds import ValueRangeAnalysis + from ..select_algorithm import TritonTemplateKernel + + if isinstance(V.kernel, TritonTemplateKernel): + return ValueRanges.unknown() + + fx_node = V.interpreter.current_node + if fx_node.target == name and self.kernel.node_to_bounds is not None: + assert isinstance(self.kernel.node_to_bounds, dict) + return self.kernel.node_to_bounds.get(fx_node, ValueRanges.unknown()) + elif config.compute_all_bounds and hasattr(ValueRangeAnalysis, name): + # These create lots of inner strings. We would need to compute the bounds at the ops + # We will also likely not get much from computing VRs on these nodes + if any(s in fx_node.target for s in ("set_indirect", "reduction", "scan")): + return ValueRanges.unknown() + + # We assume that the inputs come from `ops.` and are not strings. If you want to generate + # intermediary strings, wrap them in CSE variables with properly initialised bounds. + + # If there is no FX bound but we know how to compute one we do so + assert not kwargs + + def arg_to_bound(x: Any) -> Any: + if isinstance(x, CSEVariable): + return x.bounds + elif isinstance(x, sympy.Expr): + return bound_sympy(x) + else: + return x + + arg_bounds = list(map(arg_to_bound, args)) + return getattr(self.vr_analysis, name)(*arg_bounds) + return ValueRanges.unknown() + + def indirect_indexing( + self, + var: CSEVariable, + size: Union[sympy.Expr, int], + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + if isinstance(size, int): + size = sympy.Integer(size) + assert isinstance(size, sympy.Expr), size + # Skip CSE since this doesn't return an expression + + if var.bounds.lower < 0: # type: ignore[operator] + if wrap_neg: + stm = ops.add(var, ops.index_expr(size, torch.long)) + # Mixed negative and non-negative + if var.bounds.upper >= 0: # type: ignore[operator] + lt = ops.lt(var, 0) + stm = ops.where(lt, stm, var) + else: + stm = var + + # Propagate bounds as we know how to compute them properly + new_bounds = ValueRanges.unknown() + if var.bounds != ValueRanges.unknown() and isinstance(size, sympy.Number): + # Take the negative part of the bound and add size to it + # Then take union of that and the positive part + # This is a tighter bound than that of a generic ops.where, as we have info on the cond + neg_bounds = var.bounds & ValueRanges(-int_oo, -1) + new_bounds = ValueRanges( + neg_bounds.lower + size, neg_bounds.upper + size + ) + # We don't have a good way of representing the empty range + if var.bounds.upper >= 0: # type: ignore[operator] + pos = var.bounds & ValueRanges(0, int_oo) + new_bounds = new_bounds | pos + + var = self.kernel.cse.generate(self.kernel.compute, stm, bounds=new_bounds) + + sympy_var = self.parent_handler.indirect_indexing(var, size, check) + if generate_assert(check): + assert_lower = not (var.bounds.lower >= 0) + # value ranges cannot x < s when x and s are symbols + assert_upper = not isinstance(size, sympy.Number) or not ( + var.bounds.upper < size + ) + self.kernel.check_bounds(sympy_var, size, assert_lower, assert_upper) + return sympy_var + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + return self.kernel.check_bounds(expr, size, lower, upper) + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + if name in self.kernel.cse.invalidated_stores: + # A load from an invalidated store requires us to + # keep the actual buffer around + V.kernel.must_keep_buffers.add(name) + if free_symbol_is_type(index, SymT.TMP): + return self.kernel.indirect_load(name, index) + store_cache = self.kernel.cse.store_cache + if name in store_cache: + return store_cache[name] + out = self.kernel.load(name, index) + # count load that is not in the store_cache, and also not in the + # cse cache. + if out.use_count == 1: + self.kernel.num_load += 1 + return out + + def _update_store_cache(self, name: str, value: CSEVariable) -> None: + self.kernel.cse.store_cache[name] = value + if self.kernel.current_node and name in V.graph.name_to_buffer: + buf = self.kernel.current_node.get_output(name) + for other_name in buf.get_mutations(): + self.kernel.cse.store_cache[other_name] = value + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + self.kernel.store_buffer_names.add(name) + if mode is None: + self._update_store_cache(name, value) + if name not in V.graph.removed_buffers: + return self.kernel.store(name, index, value, mode=mode) + return None # type: ignore[return-value] + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + self.kernel.store_buffer_names.add(name) + self._update_store_cache(name, value) + + if name not in V.graph.removed_buffers: + return self.kernel.store_reduction(name, index, value) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: Union[CSEVariable, tuple[CSEVariable, ...]], + ) -> Union[CSEVariable, tuple[CSEVariable, ...]]: + self.kernel.num_reduction += 1 + return self.kernel.reduction(dtype, src_dtype, reduction_type, value) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], + tuple[CSEVariable, ...], + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + return self.kernel.scan(dtypes, combine_fn, values) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + return self.kernel.sort(dtypes, values, stable, descending) + + def bucketize( + self, + values: CSEVariable, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: CSEVariable, + indexing_dtype: torch.dtype, + right: bool, + sorter: Optional[tuple[str, sympy.Expr]] = None, + sorter_indices: Optional[CSEVariable] = None, + ) -> CSEVariable: + """ + [Note: Inductor bucketize op] + + Inputs: + ------- + values: the values to be bucketized. + boundaries: a tuple containing + (a) the name of the boundaries tensor (which must be sorted, unless + the sorting tensor is present), + (b) the length of the tensor in the last dimension (i.e. the length of + one set of boundaries), + (c) the number of elements in the underlying storage (i.e. the length + of the flattened tensor, ignoring striding), and + (d) the stride of the tensor in the last dimension. + boundary_indices: indices into a flattened version of the boundaries + tensor, of the same size and shape as "values". Each index points to + the first element in the set of boundaries to be used for the + corresponding value. + indexing_dtype: the dtype to use when indexing into the boundaries + tensor. This must be int64 or int32. This additionally specifies the + dtype of the return value. + right: see "Details" below. + sorter: an optional tuple containing + (a) the name of an optional sorting tensor, used to access unsorted + boundaries without reordering the boundaries tensor, and + (b) the stride of the tensor in the last dimension. + The values in the sorting tensor are used as indices into the *last* + dimension of the boundaries tensor, with all other indices matching. + The size of the sorting and boundaries tensors must be equivalent. + sorter_indices: must be present if the sorting array is present; see + "boundary_indices" for the equivalent definition for the boundaries + tensor. + + Output: + ------- + The buckets each value belongs in, within a given set of boundaries. 0 + indicates a position before the first boundary, and len(boundaries_set) + represents a position after the last boundary. + + Details: + -------- + Given a value and a set of boundaries, calculate the bucket that each + value belongs to. This works differently in 1-D and N-D cases. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [0, 4, 4, 8], right=True + return = [[ 0, 1, 1, 1], [1, 3, 3, 4]]. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [[0, 4], [4, 8]], right=True + return = [[ 0, 1, 1, 1], [0, 1, 1, 2]] + + Note that in the N-D boundaries case, the shape of "values" and + "boundaries" must match in every dimension _except_ the last. + + When right == False, bucket i refers to range (boundaries[i], boundaries[i+1]]. + When right == True, bucket i refers to range [boundaries[i], boundaries[i+1]). + + Boundaries must be non-decreasing, or a sorter must be provided which + would re-index offsets in a non-decreasing order (e.g. the second output + of torch.sort(offsets)). Otherwise, the result is undefined. + """ + return self.kernel.bucketize( + values, + boundaries, + boundary_indices, + indexing_dtype, + right, + sorter, + sorter_indices, + ) diff --git a/shared/package-files/18/18232cd51e4313af502c1fa01af7a5c2be6b052d037c411960cf36e5c7a0689f/_sparse_broadcast_to_copy_ops.h b/shared/package-files/18/18232cd51e4313af502c1fa01af7a5c2be6b052d037c411960cf36e5c7a0689f/_sparse_broadcast_to_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7512c844403b89069ec829e40d782fe81a600a8f --- /dev/null +++ b/shared/package-files/18/18232cd51e4313af502c1fa01af7a5c2be6b052d037c411960cf36e5c7a0689f/_sparse_broadcast_to_copy_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_broadcast_to_copy { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_broadcast_to_copy"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_sparse_broadcast_to_copy(Tensor self, int[] size) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::IntArrayRef size); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size); +}; + +struct TORCH_API _sparse_broadcast_to_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_broadcast_to_copy"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_sparse_broadcast_to_copy.out(Tensor self, int[] size, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/18238cf7020f82a4096078c1b3bfacf485451e1f20298bf0522a42345282d04d/pairs.cpython-311.pyc b/shared/package-files/18/18238cf7020f82a4096078c1b3bfacf485451e1f20298bf0522a42345282d04d/pairs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..953fc6d11b3b691278ac7d556f26dc091cf015ac Binary files /dev/null and b/shared/package-files/18/18238cf7020f82a4096078c1b3bfacf485451e1f20298bf0522a42345282d04d/pairs.cpython-311.pyc differ diff --git a/shared/package-files/18/1826e20c329ca25fde81264dba4aca3fdcf13fe2e8ee2f1a805a702bd54f317a/mkldnn_adaptive_avg_pool2d.h b/shared/package-files/18/1826e20c329ca25fde81264dba4aca3fdcf13fe2e8ee2f1a805a702bd54f317a/mkldnn_adaptive_avg_pool2d.h new file mode 100644 index 0000000000000000000000000000000000000000..dda29ae0143a5bbec89e2ac8ab496dccea61faa5 --- /dev/null +++ b/shared/package-files/18/1826e20c329ca25fde81264dba4aca3fdcf13fe2e8ee2f1a805a702bd54f317a/mkldnn_adaptive_avg_pool2d.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor +inline at::Tensor mkldnn_adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::mkldnn_adaptive_avg_pool2d::call(self, output_size); +} + +// aten::mkldnn_adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mkldnn_adaptive_avg_pool2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size) { + return at::_ops::mkldnn_adaptive_avg_pool2d_out::call(self, output_size, out); +} +// aten::mkldnn_adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mkldnn_adaptive_avg_pool2d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out) { + return at::_ops::mkldnn_adaptive_avg_pool2d_out::call(self, output_size, out); +} + +} diff --git a/shared/package-files/18/182f31cdb59846aea2ea6b3f623a3859fd67f6e01d1f84fc4508d8de206692f9/_utils.py b/shared/package-files/18/182f31cdb59846aea2ea6b3f623a3859fd67f6e01d1f84fc4508d8de206692f9/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a7b05786ab171ba2c01635495e03279828cbefef --- /dev/null +++ b/shared/package-files/18/182f31cdb59846aea2ea6b3f623a3859fd67f6e01d1f84fc4508d8de206692f9/_utils.py @@ -0,0 +1,114 @@ +# mypy: allow-untyped-defs +"""Common utility functions for FX passes. + +These functions should NOT be directly invoked outside of `passes` package. +""" + +from __future__ import annotations + +import collections +import re +from typing import Callable + +import torch.fx +import torch.fx.traceback as fx_traceback + + +def wrap_graph_module_for_node_meta_preservation( + graph_module: torch.fx.GraphModule, +) -> Callable: + """Wrap a GraphModule with contexts to preserve node meta information, such as stacktrace info. + + This is typically useful before calling `make_fx`. Without this wrapper, the + stacktrace information will be lost afterwards. + """ + + def wrapped(*args): + with fx_traceback.preserve_node_meta(): + return torch.fx.Interpreter(graph_module).run(*args) + + return wrapped + + +def _get_node_base_name(node_name: str) -> tuple[str, int | None]: + pattern = r"(.*)\.(\d+)" + match = re.match(pattern, node_name) + if match is not None: + base_name, count_str = match.groups() + return base_name, int(count_str) + return node_name, None + + +def set_node_name( + node: torch.fx.Node, + new_name: str, + name_to_node_cache: dict[str, torch.fx.Node], +): + """Safely set the unique name of a node. + + If the new name is already taken by another node, the name of the other node will be + updated. If `new_name` is a string of format f"{base_name}.{count}", where `count` + is an integer, the other node will be renamed as f"{base_name}.{count+1}". If not, + the other node will be renamed as "{new_name}.1". This function will iteratively + update the names until there is no conflict. + + ``name_to_node_cache`` is required as an argument to avoid recomputation. The caller + is responsible for ensuring the cache is accurate and in sync with the owning module + of the node. The values in the cache will be updated accordingly. + + Args: + node: The node to update. + new_name: The new name to use. + name_to_node_cache: A cache of node names to nodes. + """ + node_name_to_set = collections.deque([(node, new_name)]) + + while node_name_to_set: + node, new_name = node_name_to_set.pop() + if new_name in name_to_node_cache and name_to_node_cache[new_name] != node: + base_name, postfix_count = _get_node_base_name(new_name) + if postfix_count is None: + postfix_count = 0 + node_name_to_set.append( + (name_to_node_cache[new_name], f"{base_name}.{postfix_count + 1}") + ) + node.name = new_name + name_to_node_cache[new_name] = node + + +def replace_placeholder_name_and_target( + module: torch.fx.GraphModule, reference_module: torch.fx.GraphModule +): + """Replace the argument names in module with those in reference_module. + + This function assumes the two modules have the same signature structure. + The caller is responsible for ensuring this. Otherwise, the behavior of this + function is undefined. This function only does minimal sanity check that the two + modules have the same number of arguments. + + Name conflicts between new names and existing node names in the graph are handled. + Check the documentation of :func:`set_node_name` for more details. + + Raises: + RuntimeError: If the two modules have different number of arguments. + """ + placeholders = [node for node in module.graph.nodes if node.op == "placeholder"] + reference_placeholders = [ + node for node in reference_module.graph.nodes if node.op == "placeholder" + ] + + if len(placeholders) != len(reference_placeholders): + raise RuntimeError( + "The two modules have different number of arguments. " + f"module: {len(placeholders)}, reference_module: {len(reference_placeholders)}" + ) + + name_to_node: dict[str, torch.fx.Node] = {} + for node in module.graph.nodes: + name_to_node[node.name] = node + + for placeholder, reference_placeholder in zip(placeholders, reference_placeholders): + placeholder.target = reference_placeholder.target + set_node_name(placeholder, reference_placeholder.name, name_to_node) + + module.recompile() diff --git a/shared/package-files/18/1838992aaca6c6780f6b1e03e22fb8475b45613c85e09a5988a43bf04301dc4c/mkldnn_reorder_conv2d_weight_ops.h b/shared/package-files/18/1838992aaca6c6780f6b1e03e22fb8475b45613c85e09a5988a43bf04301dc4c/mkldnn_reorder_conv2d_weight_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..fb5fb058d6e6df390ce3ab90097ae756c8d480e3 --- /dev/null +++ b/shared/package-files/18/1838992aaca6c6780f6b1e03e22fb8475b45613c85e09a5988a43bf04301dc4c/mkldnn_reorder_conv2d_weight_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mkldnn_reorder_conv2d_weight { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, at::OptionalSymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_reorder_conv2d_weight"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "mkldnn_reorder_conv2d_weight(Tensor self, SymInt[2] padding=0, SymInt[2] stride=1, SymInt[2] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::OptionalSymIntArrayRef input_size); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::OptionalSymIntArrayRef input_size); +}; + +struct TORCH_API mkldnn_reorder_conv2d_weight_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, at::OptionalSymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_reorder_conv2d_weight"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "mkldnn_reorder_conv2d_weight.out(Tensor self, SymInt[2] padding=0, SymInt[2] stride=1, SymInt[2] dilation=1, SymInt groups=1, SymInt[]? input_size=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::OptionalSymIntArrayRef input_size, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::OptionalSymIntArrayRef input_size, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/18410ef358417138759c6d60c60adb09bdb2f32c6cb48f9693133096376c785d/cut_target.c b/shared/package-files/18/18410ef358417138759c6d60c60adb09bdb2f32c6cb48f9693133096376c785d/cut_target.c new file mode 100644 index 0000000000000000000000000000000000000000..7c8387ca6848f6be8adf8ae6a794f0b3b6073d38 --- /dev/null +++ b/shared/package-files/18/18410ef358417138759c6d60c60adb09bdb2f32c6cb48f9693133096376c785d/cut_target.c @@ -0,0 +1,257 @@ +/* cut_target.c -- targetcut subcommand. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2012-2013, 2015, 2016, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "samtools.h" +#include "sam_opts.h" + +#define ERR_DEP 0.83 + +typedef struct { + int e[2][3], p[2][2]; +} score_param_t; + +/* Note that although the two matrics have 10 parameters in total, only 4 + * (probably 3) are free. Changing the scoring matrices in a sort of symmetric + * way will not change the result. */ +static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} }; + +typedef struct { + int min_baseQ, tid, max_bases; + uint16_t *bases; + samFile *fp; + sam_hdr_t *h; + char *ref; + hts_pos_t len; + faidx_t *fai; + errmod_t *em; +} ct_t; + +static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp) +{ + int i, j, ret, tmp, k, sum[4], qual; + float q[16]; + if (n > g->max_bases) { // enlarge g->bases + g->max_bases = n; + kroundup32(g->max_bases); + g->bases = realloc(g->bases, (size_t) g->max_bases * 2); + } + for (i = k = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint8_t *seq; + int q, baseQ, b; + if (p->is_refskip || p->is_del) continue; + baseQ = bam_get_qual(p->b)[p->qpos]; + if (baseQ < g->min_baseQ) continue; + seq = bam_get_seq(p->b); + b = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (b > 3) continue; + q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; + if (q < 4) q = 4; + if (q > 63) q = 63; + g->bases[k++] = q<<5 | bam_is_rev(p->b)<<4 | b; + } + if (k == 0) return 0; + errmod_cal(g->em, k, 4, g->bases, q); + for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i; + for (i = 1; i < 4; ++i) // insertion sort + for (j = i; j > 0 && sum[j] < sum[j-1]; --j) + tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp; + qual = (sum[1]>>2) - (sum[0]>>2); + k = k < 256? k : 255; + ret = (qual < 63? qual : 63) << 2 | (sum[0]&3); + return ret<<8|k; +} + +static void process_cns(sam_hdr_t *h, int tid, hts_pos_t l, uint16_t *cns) +{ + int64_t i, s; + int f[2][2], *prev, *curr, *swap_tmp; + uint8_t *b; // backtrack array + b = calloc(l, 1); + f[0][0] = f[0][1] = 0; + prev = f[0]; curr = f[1]; + // fill the backtrack matrix + for (i = 0; i < l; ++i) { + int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2; + int tmp0, tmp1; + // compute f[0] + tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0) + tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1) + if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0; + else curr[0] = tmp1, b[i] = 1; + // compute f[1] + tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0) + tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1) + if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1; + else curr[1] = tmp1, b[i] |= 1<<1; + // swap + swap_tmp = prev; prev = curr; curr = swap_tmp; + } + // backtrack + s = prev[0] > prev[1]? 0 : 1; + for (i = l - 1; i > 0; --i) { + b[i] |= s<<2; + s = b[i]>>s&1; + } + // print + for (i = 0, s = -1; i < INT64_MAX && i <= l; ++i) { + if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) { + if (s >= 0) { + int64_t j; + printf("%s:%"PRId64"-%"PRId64"\t0\t%s\t%"PRId64"\t60\t%"PRId64"M\t*\t0\t0\t", sam_hdr_tid2name(h, tid), s+1, i, sam_hdr_tid2name(h, tid), s+1, i-s); + for (j = s; j < i; ++j) { + int c = cns[j]>>8; + if (c == 0) putchar('N'); + else putchar("ACGT"[c&3]); + } + putchar('\t'); + for (j = s; j < i; ++j) + putchar(33 + (cns[j]>>8>>2)); + putchar('\n'); + } + //if (s >= 0) printf("%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s); + s = -1; + } else if ((b[i]>>2&3) && s < 0) s = i; + } + free(b); +} + +static int read_aln(void *data, bam1_t *b) +{ + ct_t *g = (ct_t*)data; + int ret; + while (1) + { + ret = sam_read1(g->fp, g->h, b); + if ( ret<0 ) break; + if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue; + if ( g->fai && b->core.tid >= 0 ) { + if (b->core.tid != g->tid) { // then load the sequence + free(g->ref); + g->ref = fai_fetch64(g->fai, sam_hdr_tid2name(g->h, b->core.tid), &g->len); + g->tid = b->core.tid; + } + sam_prob_realn(b, g->ref, g->len, 1<<1|1); + } + break; + } + return ret; +} + +int main_cut_target(int argc, char *argv[]) +{ + int c, tid, pos, n, lasttid = -1, usage = 0, status = EXIT_SUCCESS; + hts_pos_t l, max_l; + const bam_pileup1_t *p; + bam_plp_t plp; + uint16_t *cns; + ct_t g; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'f', '-'), + { NULL, 0, NULL, 0 } + }; + + memset(&g, 0, sizeof(ct_t)); + g.min_baseQ = 13; g.tid = -1; + while ((c = getopt_long(argc, argv, "f:Q:i:o:0:1:2:", lopts, NULL)) >= 0) { + switch (c) { + case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff + case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY + case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE + case '1': g_param.e[1][1] = atoi(optarg); break; + case '2': g_param.e[1][2] = atoi(optarg); break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + } + if (ga.reference) { + g.fai = fai_load(ga.reference); + if (g.fai == 0) fprintf(stderr, "[%s] fail to load the fasta index.\n", __func__); + } + if (usage || argc == optind) { + fprintf(stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] \n"); + sam_global_opt_help(stderr, "-.--f--."); + return 1; + } + l = max_l = 0; cns = 0; + g.fp = sam_open_format(argv[optind], "r", &ga.in); + if (g.fp == NULL) { + print_error_errno("targetcut", "can't open \"%s\"", argv[optind]); + return 1; + } + + g.h = sam_hdr_read(g.fp); + if (g.h == NULL) { + print_error("targetcut", "couldn't read header for \"%s\"", argv[optind]); + sam_close(g.fp); + return 1; + } + g.em = errmod_init(1. - ERR_DEP); + plp = bam_plp_init(read_aln, &g); + while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) { + if (tid < 0) break; + if (tid != lasttid) { // change of chromosome + if (cns) process_cns(g.h, lasttid, l, cns); + if (max_l < sam_hdr_tid2len(g.h, tid)) { + max_l = sam_hdr_tid2len(g.h, tid); + kroundup32(max_l); + cns = realloc(cns, max_l * 2); + } + l = sam_hdr_tid2len(g.h, tid); + memset(cns, 0, max_l * 2); + lasttid = tid; + } + cns[pos] = gencns(&g, n, p); + } + process_cns(g.h, lasttid, l, cns); + + if (n < 0) { + print_error("targetcut", "error reading from \"%s\"", argv[optind]); + status = EXIT_FAILURE; + } + + free(cns); + sam_hdr_destroy(g.h); + bam_plp_destroy(plp); + sam_close(g.fp); + if (g.fai) { + fai_destroy(g.fai); free(g.ref); + } + errmod_destroy(g.em); + free(g.bases); + sam_global_args_free(&ga); + return status; +} diff --git a/shared/package-files/18/1842734050cb0dd34685d23948cc9cc71a370b09e999d5206a8f1a32f36aa237/_to_sparse_bsc.h b/shared/package-files/18/1842734050cb0dd34685d23948cc9cc71a370b09e999d5206a8f1a32f36aa237/_to_sparse_bsc.h new file mode 100644 index 0000000000000000000000000000000000000000..ec5e748fbfc97874ddaceedf80b7bd769dfa96ad --- /dev/null +++ b/shared/package-files/18/1842734050cb0dd34685d23948cc9cc71a370b09e999d5206a8f1a32f36aa237/_to_sparse_bsc.h @@ -0,0 +1,35 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_to_sparse_bsc.out(Tensor self, int[2] blocksize, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _to_sparse_bsc_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef blocksize, ::std::optional dense_dim=::std::nullopt) { + return at::_ops::_to_sparse_bsc_out::call(self, blocksize, dense_dim, out); +} +// aten::_to_sparse_bsc.out(Tensor self, int[2] blocksize, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _to_sparse_bsc_outf(const at::Tensor & self, at::IntArrayRef blocksize, ::std::optional dense_dim, at::Tensor & out) { + return at::_ops::_to_sparse_bsc_out::call(self, blocksize, dense_dim, out); +} + +} diff --git a/shared/package-files/18/1845f31c7791e45d2cc2b673845ee9106474b64f55a7755ed9cfac138592a6c6/test_singularity_functions.py b/shared/package-files/18/1845f31c7791e45d2cc2b673845ee9106474b64f55a7755ed9cfac138592a6c6/test_singularity_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd85cb0c7e5524d4fe1441615879b9776ad1693 --- /dev/null +++ b/shared/package-files/18/1845f31c7791e45d2cc2b673845ee9106474b64f55a7755ed9cfac138592a6c6/test_singularity_functions.py @@ -0,0 +1,129 @@ +from sympy.core.function import (Derivative, diff) +from sympy.core.numbers import (Float, I, nan, oo, pi) +from sympy.core.relational import Eq +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) +from sympy.functions.special.singularity_functions import SingularityFunction +from sympy.series.order import O + + +from sympy.core.expr import unchanged +from sympy.core.function import ArgumentIndexError +from sympy.testing.pytest import raises + +x, y, a, n = symbols('x y a n') + + +def test_fdiff(): + assert SingularityFunction(x, 4, 5).fdiff() == 5*SingularityFunction(x, 4, 4) + assert SingularityFunction(x, 4, -1).fdiff() == SingularityFunction(x, 4, -2) + assert SingularityFunction(x, 4, -2).fdiff() == SingularityFunction(x, 4, -3) + assert SingularityFunction(x, 4, -3).fdiff() == SingularityFunction(x, 4, -4) + assert SingularityFunction(x, 4, 0).fdiff() == SingularityFunction(x, 4, -1) + + assert SingularityFunction(y, 6, 2).diff(y) == 2*SingularityFunction(y, 6, 1) + assert SingularityFunction(y, -4, -1).diff(y) == SingularityFunction(y, -4, -2) + assert SingularityFunction(y, 4, 0).diff(y) == SingularityFunction(y, 4, -1) + assert SingularityFunction(y, 4, 0).diff(y, 2) == SingularityFunction(y, 4, -2) + + n = Symbol('n', positive=True) + assert SingularityFunction(x, a, n).fdiff() == n*SingularityFunction(x, a, n - 1) + assert SingularityFunction(y, a, n).diff(y) == n*SingularityFunction(y, a, n - 1) + + expr_in = 4*SingularityFunction(x, a, n) + 3*SingularityFunction(x, a, -1) + -10*SingularityFunction(x, a, 0) + expr_out = n*4*SingularityFunction(x, a, n - 1) + 3*SingularityFunction(x, a, -2) - 10*SingularityFunction(x, a, -1) + assert diff(expr_in, x) == expr_out + + assert SingularityFunction(x, -10, 5).diff(evaluate=False) == ( + Derivative(SingularityFunction(x, -10, 5), x)) + + raises(ArgumentIndexError, lambda: SingularityFunction(x, 4, 5).fdiff(2)) + + +def test_eval(): + assert SingularityFunction(x, a, n).func == SingularityFunction + assert unchanged(SingularityFunction, x, 5, n) + assert SingularityFunction(5, 3, 2) == 4 + assert SingularityFunction(3, 5, 1) == 0 + assert SingularityFunction(3, 3, 0) == 1 + assert SingularityFunction(3, 3, 1) == 0 + assert SingularityFunction(Symbol('z', zero=True), 0, 1) == 0 # like sin(z) == 0 + assert SingularityFunction(4, 4, -1) is oo + assert SingularityFunction(4, 2, -1) == 0 + assert SingularityFunction(4, 7, -1) == 0 + assert SingularityFunction(5, 6, -2) == 0 + assert SingularityFunction(4, 2, -2) == 0 + assert SingularityFunction(4, 4, -2) is oo + assert SingularityFunction(4, 2, -3) == 0 + assert SingularityFunction(8, 8, -3) is oo + assert SingularityFunction(4, 2, -4) == 0 + assert SingularityFunction(8, 8, -4) is oo + assert (SingularityFunction(6.1, 4, 5)).evalf(5) == Float('40.841', '5') + assert SingularityFunction(6.1, pi, 2) == (-pi + 6.1)**2 + assert SingularityFunction(x, a, nan) is nan + assert SingularityFunction(x, nan, 1) is nan + assert SingularityFunction(nan, a, n) is nan + + raises(ValueError, lambda: SingularityFunction(x, a, I)) + raises(ValueError, lambda: SingularityFunction(2*I, I, n)) + raises(ValueError, lambda: SingularityFunction(x, a, -5)) + + +def test_leading_term(): + l = Symbol('l', positive=True) + assert SingularityFunction(x, 3, 2).as_leading_term(x) == 0 + assert SingularityFunction(x, -2, 1).as_leading_term(x) == 2 + assert SingularityFunction(x, 0, 0).as_leading_term(x) == 1 + assert SingularityFunction(x, 0, 0).as_leading_term(x, cdir=-1) == 0 + assert SingularityFunction(x, 0, -1).as_leading_term(x) == 0 + assert SingularityFunction(x, 0, -2).as_leading_term(x) == 0 + assert SingularityFunction(x, 0, -3).as_leading_term(x) == 0 + assert SingularityFunction(x, 0, -4).as_leading_term(x) == 0 + assert (SingularityFunction(x + l, 0, 1)/2\ + - SingularityFunction(x + l, l/2, 1)\ + + SingularityFunction(x + l, l, 1)/2).as_leading_term(x) == -x/2 + + +def test_series(): + l = Symbol('l', positive=True) + assert SingularityFunction(x, -3, 2).series(x) == x**2 + 6*x + 9 + assert SingularityFunction(x, -2, 1).series(x) == x + 2 + assert SingularityFunction(x, 0, 0).series(x) == 1 + assert SingularityFunction(x, 0, 0).series(x, dir='-') == 0 + assert SingularityFunction(x, 0, -1).series(x) == 0 + assert SingularityFunction(x, 0, -2).series(x) == 0 + assert SingularityFunction(x, 0, -3).series(x) == 0 + assert SingularityFunction(x, 0, -4).series(x) == 0 + assert (SingularityFunction(x + l, 0, 1)/2\ + - SingularityFunction(x + l, l/2, 1)\ + + SingularityFunction(x + l, l, 1)/2).nseries(x) == -x/2 + O(x**6) + + +def test_rewrite(): + assert SingularityFunction(x, 4, 5).rewrite(Piecewise) == ( + Piecewise(((x - 4)**5, x - 4 >= 0), (0, True))) + assert SingularityFunction(x, -10, 0).rewrite(Piecewise) == ( + Piecewise((1, x + 10 >= 0), (0, True))) + assert SingularityFunction(x, 2, -1).rewrite(Piecewise) == ( + Piecewise((oo, Eq(x - 2, 0)), (0, True))) + assert SingularityFunction(x, 0, -2).rewrite(Piecewise) == ( + Piecewise((oo, Eq(x, 0)), (0, True))) + + n = Symbol('n', nonnegative=True) + p = SingularityFunction(x, a, n).rewrite(Piecewise) + assert p == ( + Piecewise(((x - a)**n, x - a >= 0), (0, True))) + assert p.subs(x, a).subs(n, 0) == 1 + + expr_in = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2) + expr_out = (x - 4)**5*Heaviside(x - 4, 1) + DiracDelta(x + 3) - DiracDelta(x, 1) + assert expr_in.rewrite(Heaviside) == expr_out + assert expr_in.rewrite(DiracDelta) == expr_out + assert expr_in.rewrite('HeavisideDiracDelta') == expr_out + + expr_in = SingularityFunction(x, a, n) + SingularityFunction(x, a, -1) - SingularityFunction(x, a, -2) + expr_out = (x - a)**n*Heaviside(x - a, 1) + DiracDelta(x - a) + DiracDelta(a - x, 1) + assert expr_in.rewrite(Heaviside) == expr_out + assert expr_in.rewrite(DiracDelta) == expr_out + assert expr_in.rewrite('HeavisideDiracDelta') == expr_out diff --git a/shared/package-files/18/184d1ebb65da97ada36447f3c028f2fd4890b874f17b18c023ce200dd96639af/LICENSE b/shared/package-files/18/184d1ebb65da97ada36447f3c028f2fd4890b874f17b18c023ce200dd96639af/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c2d88a17f11fcda74bab669045e28e1324159f91 --- /dev/null +++ b/shared/package-files/18/184d1ebb65da97ada36447f3c028f2fd4890b874f17b18c023ce200dd96639af/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Marc Brinkmann + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/shared/package-files/18/18633c39fd689c57c04fddb0de247645d6ac48ade677e071a8534ebbca5da7f6/RECORD b/shared/package-files/18/18633c39fd689c57c04fddb0de247645d6ac48ade677e071a8534ebbca5da7f6/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7d47ba13ef91ecda09e2c2df9617d2781ff69871 --- /dev/null +++ b/shared/package-files/18/18633c39fd689c57c04fddb0de247645d6ac48ade677e071a8534ebbca5da7f6/RECORD @@ -0,0 +1,1407 @@ +../../../bin/f2py,sha256=mDicT8CHkrIDb5iypCXPADX6g0i6C5Y-ZoQVIv8PvBc,221 +numpy-1.26.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +numpy-1.26.4.dist-info/LICENSE.txt,sha256=EQewyDHpGNTx28KKMxkMdyFe8njUpMQAlXIIh3DUM0o,47721 +numpy-1.26.4.dist-info/METADATA,sha256=sJc0p_7UToS0yBYZNM5TLf8ed57Ggi1BVkTRF_Y4EHA,61041 +numpy-1.26.4.dist-info/RECORD,, +numpy-1.26.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy-1.26.4.dist-info/WHEEL,sha256=6uXuBuTHKYVHX38njLnDjCYRk1Z5gwaXJtzFqt6LRKw,137 +numpy-1.26.4.dist-info/entry_points.txt,sha256=zddyYJuUw9Uud7LeLfynXk62_ry0lGihDwCIgugBdZM,144 +numpy.libs/libgfortran-040039e1.so.5.0.0,sha256=FK-zEpsai1C8QKOwggx_EVLqm8EBIaqxUpQ_cFdHKIY,2686065 +numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so,sha256=klTQhU3XYV4R3ijXca5AiHjKgSOnrCBPIeTMejdswuU,35123345 +numpy.libs/libquadmath-96973f99.so.0.0.0,sha256=k0wi3tDn0WnE1GeIdslgUa3z2UVF2pYvYLQWWbB12js,247609 +numpy/__config__.py,sha256=Ouf-jsQKC0ljXwtIU2FahDMm4AnbXAQ9ZPVRLDkcB-E,4902 +numpy/__init__.cython-30.pxd,sha256=yk2a3etxRNlBgj5uLfIho2RYDYDzhRW8oagAG-wzbPI,36690 +numpy/__init__.pxd,sha256=Pa0VYRSeQRSFepQ6ROgZrNtGY5TzBXIddWsMHtK0OkM,35066 +numpy/__init__.py,sha256=Is0VNfoU10729FfMoUn_3ICHX0YL4xO4-JUnP3i8QC4,17005 +numpy/__init__.pyi,sha256=9kK465XL9oS_X3fJLv0Na29NEYnWvtdMhXPtrnF_cG8,154080 +numpy/__pycache__/__config__.cpython-311.pyc,, +numpy/__pycache__/__init__.cpython-311.pyc,, +numpy/__pycache__/_distributor_init.cpython-311.pyc,, +numpy/__pycache__/_globals.cpython-311.pyc,, +numpy/__pycache__/_pytesttester.cpython-311.pyc,, +numpy/__pycache__/conftest.cpython-311.pyc,, +numpy/__pycache__/ctypeslib.cpython-311.pyc,, +numpy/__pycache__/dtypes.cpython-311.pyc,, +numpy/__pycache__/exceptions.cpython-311.pyc,, +numpy/__pycache__/matlib.cpython-311.pyc,, +numpy/__pycache__/version.cpython-311.pyc,, +numpy/_core/__init__.py,sha256=C8_7wbHqUkB35JouY_XKsas1KLpRZ7JHWuZ7VGOPVpU,136 +numpy/_core/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_core/__pycache__/__init__.cpython-311.pyc,, +numpy/_core/__pycache__/_dtype.cpython-311.pyc,, +numpy/_core/__pycache__/_dtype_ctypes.cpython-311.pyc,, +numpy/_core/__pycache__/_internal.cpython-311.pyc,, +numpy/_core/__pycache__/_multiarray_umath.cpython-311.pyc,, +numpy/_core/__pycache__/multiarray.cpython-311.pyc,, +numpy/_core/__pycache__/umath.cpython-311.pyc,, +numpy/_core/_dtype.py,sha256=vE16-yiwUSYsAIbq7FlEY1GbXZAp8wjADDxJg3eBX-U,126 +numpy/_core/_dtype_ctypes.py,sha256=i5EhoWPUhu4kla3Xu4ZvXF1lVLPiI6Zg4h6o8jaiamo,147 +numpy/_core/_internal.py,sha256=g5ugmqDgUhSlie5-onOctcm4p0gcMHSIRLHVYtFTk1M,135 +numpy/_core/_multiarray_umath.py,sha256=VPtoT2uHnyU3rKL0G27CgmNmB1WRHM0mtc7Y9L85C3U,159 +numpy/_core/multiarray.py,sha256=kZxC_7P3Jwz1RApzQU2QGmqSq4MAEvKmaJEYnAsbSOs,138 +numpy/_core/umath.py,sha256=YcV0cdbGcem6D5P3yX7cR9HGYBrT8VMoAgCBzGwPhgg,123 +numpy/_distributor_init.py,sha256=IKy2THwmu5UgBjtVbwbD9H-Ap8uaUJoPJ2btQ4Jatdo,407 +numpy/_globals.py,sha256=neEdcfLZoHLwber_1Xyrn26LcXy0MrSta03Ze7aKa6g,3094 +numpy/_pyinstaller/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/__pycache__/__init__.cpython-311.pyc,, +numpy/_pyinstaller/__pycache__/hook-numpy.cpython-311.pyc,, +numpy/_pyinstaller/__pycache__/pyinstaller-smoke.cpython-311.pyc,, +numpy/_pyinstaller/__pycache__/test_pyinstaller.cpython-311.pyc,, +numpy/_pyinstaller/hook-numpy.py,sha256=PUQ-mNWje6bFALB-mLVFRPkvbM4JpLXunB6sjBbTy5g,1409 +numpy/_pyinstaller/pyinstaller-smoke.py,sha256=6iL-eHMQaG3rxnS5EgcvrCqElm9aKL07Cjr1FZJSXls,1143 +numpy/_pyinstaller/test_pyinstaller.py,sha256=8K-7QxmfoXCG0NwR0bhIgCNrDjGlrTzWnrR1sR8btgU,1135 +numpy/_pytesttester.py,sha256=lQUTvKVz6kT8b4yiMV-uW-vG9KSv9UzqAmxaEMezTd8,6731 +numpy/_pytesttester.pyi,sha256=OtyXSiuSy8o_78w3QNQRjMLpvvNyEdC0aMsx6T-vRxU,489 +numpy/_typing/__init__.py,sha256=6w9E9V9VaT7vTM-veua8XcySv50Je5qSPJzK9HTocIg,7003 +numpy/_typing/__pycache__/__init__.cpython-311.pyc,, +numpy/_typing/__pycache__/_add_docstring.cpython-311.pyc,, +numpy/_typing/__pycache__/_array_like.cpython-311.pyc,, +numpy/_typing/__pycache__/_char_codes.cpython-311.pyc,, +numpy/_typing/__pycache__/_dtype_like.cpython-311.pyc,, +numpy/_typing/__pycache__/_extended_precision.cpython-311.pyc,, +numpy/_typing/__pycache__/_nbit.cpython-311.pyc,, +numpy/_typing/__pycache__/_nested_sequence.cpython-311.pyc,, +numpy/_typing/__pycache__/_scalars.cpython-311.pyc,, +numpy/_typing/__pycache__/_shape.cpython-311.pyc,, +numpy/_typing/__pycache__/setup.cpython-311.pyc,, +numpy/_typing/_add_docstring.py,sha256=xQhQX372aN_m3XN95CneMxOST2FdPcovR-MXM-9ep58,3922 +numpy/_typing/_array_like.py,sha256=L4gnx2KWG8yYcouz5b9boJIkkFNtOJV6QjcnGCrbnRY,4298 +numpy/_typing/_callable.pyi,sha256=Mf57BwohRn9ye6ixJqjNEnK0gKqnVPE9Gy8vK-6_zxo,11121 +numpy/_typing/_char_codes.py,sha256=LR51O5AUBDbCmJvlMoxyUvsfvb1p7WHrexgtTGtuWTc,5916 +numpy/_typing/_dtype_like.py,sha256=21Uxy0UgIawGM82xjDF_ifMq-nP-Bkhn_LpiK_HvWC4,5661 +numpy/_typing/_extended_precision.py,sha256=dGios-1k-QBGew7YFzONZTzVWxz-aYAaqlccl2_h5Bo,777 +numpy/_typing/_nbit.py,sha256=-EQOShHpB3r30b4RVEcruQRTcTaFAZwtqCJ4BsvpEzA,345 +numpy/_typing/_nested_sequence.py,sha256=5eNaVZAV9tZQLFWHYOuVs336JjoiaWxyZQ7cMKb6m1I,2566 +numpy/_typing/_scalars.py,sha256=eVP8PjlcTIlY7v0fRI3tFXPogWtpLJZ8nFvRRrLjDqs,980 +numpy/_typing/_shape.py,sha256=JPy7jJMkISGFTnkgiEifYM-4xTcjb7JMRkLIIjZLw08,211 +numpy/_typing/_ufunc.pyi,sha256=e74LtOP9e8kkRhvrIJ_RXz9Ua_L43Pd9IixwNwermnM,12638 +numpy/_typing/setup.py,sha256=SE0Q6HPqDjWUfceA4yXgkII8y3z7EiSF0Z-MNwOIyG4,337 +numpy/_utils/__init__.py,sha256=Hhetwsi3eTBe8HdWbG51zXmcrX1DiPLxkYSrslMLYcc,723 +numpy/_utils/__pycache__/__init__.cpython-311.pyc,, +numpy/_utils/__pycache__/_convertions.cpython-311.pyc,, +numpy/_utils/__pycache__/_inspect.cpython-311.pyc,, +numpy/_utils/__pycache__/_pep440.cpython-311.pyc,, +numpy/_utils/_convertions.py,sha256=0xMxdeLOziDmHsRM_8luEh4S-kQdMoMg6GxNDDas69k,329 +numpy/_utils/_inspect.py,sha256=8Ma7QBRwfSWKeK1ShJpFNc7CDhE6fkIE_wr1FxrG1A8,7447 +numpy/_utils/_pep440.py,sha256=Vr7B3QsijR5p6h8YAz2LjNGUyzHUJ5gZ4v26NpZAKDc,14069 +numpy/array_api/__init__.py,sha256=XtttWbDf6Yh0_m4zp-L_us4HKnV3oGwdlB6n-01Q9M8,10375 +numpy/array_api/__pycache__/__init__.cpython-311.pyc,, +numpy/array_api/__pycache__/_array_object.cpython-311.pyc,, +numpy/array_api/__pycache__/_constants.cpython-311.pyc,, +numpy/array_api/__pycache__/_creation_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_data_type_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_dtypes.cpython-311.pyc,, +numpy/array_api/__pycache__/_elementwise_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_indexing_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_manipulation_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_searching_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_set_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_sorting_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_statistical_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/_typing.cpython-311.pyc,, +numpy/array_api/__pycache__/_utility_functions.cpython-311.pyc,, +numpy/array_api/__pycache__/linalg.cpython-311.pyc,, +numpy/array_api/__pycache__/setup.cpython-311.pyc,, +numpy/array_api/_array_object.py,sha256=rfCBzE6vUjk4HElQGTVwe6Tw2vxiUx7tmBpQEmm1iBk,43794 +numpy/array_api/_constants.py,sha256=AYayN2jf1Dp5rXZ7WPBdUhtPBo_JMCi-pD9oW5zmFkI,87 +numpy/array_api/_creation_functions.py,sha256=6SqHdzZqHOJFEyWFtqnj6KIKRivrGXxROlgnez_3Mt0,10050 +numpy/array_api/_data_type_functions.py,sha256=P57FOsNdXahNUriVtdldonbvBQrrZkVzxZbcqkR_8AA,6288 +numpy/array_api/_dtypes.py,sha256=kDU1NLvEQN-W2HPmJ2wGPx8jiNkFbrvTCD1T1RT8Pwo,4823 +numpy/array_api/_elementwise_functions.py,sha256=0kGuDX3Ur_Qp6tBMBWTO7LPUxzXNGAlA2SSJhdAp4DU,25992 +numpy/array_api/_indexing_functions.py,sha256=d-gzqzyvR45FQerRYJrbBzCWFnDsZWSI9pggA5QWRO4,715 +numpy/array_api/_manipulation_functions.py,sha256=qCoW5B5FXcFOWKPU9D9MXHdMeXIuzvnHUUvprNlwfjc,3317 +numpy/array_api/_searching_functions.py,sha256=mGZiqheYXGWiDK9rqXFiDKX0_B0mJ1OjdA-9FC2o5lA,1715 +numpy/array_api/_set_functions.py,sha256=ULpfK1zznW9joX1DXSiP0R3ahcDB_po7mZlpsRqi7Fs,2948 +numpy/array_api/_sorting_functions.py,sha256=7pszlxNN7-DNqEZlonGLFQrlXPP7evVA8jN31NShg00,2031 +numpy/array_api/_statistical_functions.py,sha256=HspfYteZWSa3InMs10KZz-sk3ZuW6teX6fNdo829T84,3584 +numpy/array_api/_typing.py,sha256=uKidRp6nYxgHnEPaqXXZsDDZ6tw1LshpbwLvy-09eeM,1347 +numpy/array_api/_utility_functions.py,sha256=HwycylbPAgRVz4nZvjvwqN3mQnJbqKA-NRMaAvIP-CE,824 +numpy/array_api/linalg.py,sha256=QPpG2tG1pZgzjrtTjjOu2GDu3cI6UpSsLrsG_o1jXYk,18411 +numpy/array_api/setup.py,sha256=Wx6qD7GU_APiqKolYPO0OHv4eHGYrjPZmDAgjWhOEhM,341 +numpy/array_api/tests/__init__.py,sha256=t_2GZ3lKcsu4ec4GMKPUDYaeMUJyDquBlQAcPgj7kFE,282 +numpy/array_api/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_array_object.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_creation_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_data_type_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_elementwise_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_indexing_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_manipulation_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_set_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_sorting_functions.cpython-311.pyc,, +numpy/array_api/tests/__pycache__/test_validation.cpython-311.pyc,, +numpy/array_api/tests/test_array_object.py,sha256=FQoAxP4CLDiv6iih8KKUDSLuYM6dtnDcB1f0pMHw4-M,17035 +numpy/array_api/tests/test_creation_functions.py,sha256=s3A1COWmXIAJdhzd8v7VtL-jbiSspskTqwYy0BTpmpw,5023 +numpy/array_api/tests/test_data_type_functions.py,sha256=qc8ktRlVXWC3PKhxPVWI_UF9f1zZtpmzHjdCtf3e16E,1018 +numpy/array_api/tests/test_elementwise_functions.py,sha256=CTj4LLwtusI51HkpzD0JPohP1ffNxogAVFz8WLuWFzM,3800 +numpy/array_api/tests/test_indexing_functions.py,sha256=AbuBGyEufEAf24b7fy8JQhdJtGPdP9XEIxPTJAfAFFo,627 +numpy/array_api/tests/test_manipulation_functions.py,sha256=wce25dSJjubrGhFxmiatzR_IpmNYp9ICJ9PZBBnZTOQ,1087 +numpy/array_api/tests/test_set_functions.py,sha256=D016G7v3ko49bND5sVERP8IqQXZiwr-2yrKbBPJ-oqg,546 +numpy/array_api/tests/test_sorting_functions.py,sha256=INPiYnuGBcsmWtYqdTTX3ENHmM4iUx4zs9KdwDaSmdA,602 +numpy/array_api/tests/test_validation.py,sha256=QUG9yWC3QhkPxNhbQeakwBbl-0Rr0iTuZ41_0sfVIGU,676 +numpy/compat/__init__.py,sha256=iAHrmsZWzouOMSyD9bdSE0APWMlRpqW92MQgF8y6x3E,448 +numpy/compat/__pycache__/__init__.cpython-311.pyc,, +numpy/compat/__pycache__/py3k.cpython-311.pyc,, +numpy/compat/__pycache__/setup.cpython-311.pyc,, +numpy/compat/py3k.py,sha256=Je74CVk_7qI_qX7pLbYcuQJsxlMq1poGIfRIrH99kZQ,3833 +numpy/compat/setup.py,sha256=36X1kF0C_NVROXfJ7w3SQeBm5AIDBuJbM5qT7cvSDgU,335 +numpy/compat/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/compat/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/compat/tests/__pycache__/test_compat.cpython-311.pyc,, +numpy/compat/tests/test_compat.py,sha256=YqV67pSN8nXPbXaEdjhmyaoVetNyFupVv57OMEgCwKA,579 +numpy/conftest.py,sha256=HZyWo_wJyrbgnyXxI8t05WOg_IrzNAMnEV7O8koHous,4623 +numpy/core/__init__.py,sha256=CNsO-Ab4ywM2Wz3AbqWOH3ig1q5Bno9PsUMrCv-HNS4,5780 +numpy/core/__init__.pyi,sha256=xtd9OFYza-ZG3jyEJrlzRPT-SkVoB_qYmVCe6FxRks0,126 +numpy/core/__pycache__/__init__.cpython-311.pyc,, +numpy/core/__pycache__/_add_newdocs.cpython-311.pyc,, +numpy/core/__pycache__/_add_newdocs_scalars.cpython-311.pyc,, +numpy/core/__pycache__/_asarray.cpython-311.pyc,, +numpy/core/__pycache__/_dtype.cpython-311.pyc,, +numpy/core/__pycache__/_dtype_ctypes.cpython-311.pyc,, +numpy/core/__pycache__/_exceptions.cpython-311.pyc,, +numpy/core/__pycache__/_internal.cpython-311.pyc,, +numpy/core/__pycache__/_machar.cpython-311.pyc,, +numpy/core/__pycache__/_methods.cpython-311.pyc,, +numpy/core/__pycache__/_string_helpers.cpython-311.pyc,, +numpy/core/__pycache__/_type_aliases.cpython-311.pyc,, +numpy/core/__pycache__/_ufunc_config.cpython-311.pyc,, +numpy/core/__pycache__/arrayprint.cpython-311.pyc,, +numpy/core/__pycache__/cversions.cpython-311.pyc,, +numpy/core/__pycache__/defchararray.cpython-311.pyc,, +numpy/core/__pycache__/einsumfunc.cpython-311.pyc,, +numpy/core/__pycache__/fromnumeric.cpython-311.pyc,, +numpy/core/__pycache__/function_base.cpython-311.pyc,, +numpy/core/__pycache__/getlimits.cpython-311.pyc,, +numpy/core/__pycache__/memmap.cpython-311.pyc,, +numpy/core/__pycache__/multiarray.cpython-311.pyc,, +numpy/core/__pycache__/numeric.cpython-311.pyc,, +numpy/core/__pycache__/numerictypes.cpython-311.pyc,, +numpy/core/__pycache__/overrides.cpython-311.pyc,, +numpy/core/__pycache__/records.cpython-311.pyc,, +numpy/core/__pycache__/shape_base.cpython-311.pyc,, +numpy/core/__pycache__/umath.cpython-311.pyc,, +numpy/core/__pycache__/umath_tests.cpython-311.pyc,, +numpy/core/_add_newdocs.py,sha256=39JFaeDPN2OQlSwfpY6_Jq9fO5vML8ZMF8J4ZTx_nrs,208972 +numpy/core/_add_newdocs_scalars.py,sha256=PF9v8POcSNH6ELYltkx9e07DWgMmft6NJy9zER3Jk44,12106 +numpy/core/_asarray.py,sha256=P2ddlZAsg1iGleRRfoQv_aKs2N7AGwpo5K4ZQv4Ujlk,3884 +numpy/core/_asarray.pyi,sha256=gNNxUVhToNU_F1QpgeEvUYddpUFN-AKP0QWa4gqcTGw,1086 +numpy/core/_dtype.py,sha256=SihUz41pHRB3Q2LiYYkug6LgMBKh6VV89MOpLxnXQdo,10606 +numpy/core/_dtype_ctypes.py,sha256=Vug4i7xKhznK2tdIjmn4ebclClpaCJwSZUlvEoYl0Eg,3673 +numpy/core/_exceptions.py,sha256=dZWKqfdLRvJvbAEG_fof_8ikEKxjakADMty1kLC_l_M,5379 +numpy/core/_internal.py,sha256=f9kNDuT-FGxF1EtVOVIxXWnH9gM9n-J5V2zwHMv4HEk,28348 +numpy/core/_internal.pyi,sha256=_mCTOX6Su8D4R9fV4HNeohPJx7515B-WOlv4uq6mry8,1032 +numpy/core/_machar.py,sha256=G3a3TXu8VDW_1EMxKKLnGMbvUShEIUEve3ealBlJJ3E,11565 +numpy/core/_methods.py,sha256=m31p0WjcFUGckbJiHnCpSaIQGqv-Lq5niIYkdd33YMo,8613 +numpy/core/_multiarray_tests.cpython-311-x86_64-linux-gnu.so,sha256=fEGVCH8AVkwTzX47VoK-9-sgWeUazDwXRQwO5GUK6r8,175912 +numpy/core/_multiarray_umath.cpython-311-x86_64-linux-gnu.so,sha256=pzXk6DVbdcgAESr4pbFzG4kbIBbtVwZzUu6myrCqALw,7426817 +numpy/core/_operand_flag_tests.cpython-311-x86_64-linux-gnu.so,sha256=fSsrco1Kut3UaGZZ5f-w9gOw6iil4v5es4h0jjsgM0c,16856 +numpy/core/_rational_tests.cpython-311-x86_64-linux-gnu.so,sha256=JhmDykdI9J_hx_swy42UxeFjFGDF-MEj6u3jKL32770,59768 +numpy/core/_simd.cpython-311-x86_64-linux-gnu.so,sha256=q_9ih9WkB5d9ydsFAU5lSOH1SnxPId7jGYGcSbtrxTI,3527040 +numpy/core/_string_helpers.py,sha256=-fQM8z5s8_yX440PmgNEH3SUjEoXMPpPSysZwWZNbuo,2852 +numpy/core/_struct_ufunc_tests.cpython-311-x86_64-linux-gnu.so,sha256=CSlDZ5gi01I5v-N7jHvSfRLyOJSR9JMcIV2cIq5InGo,16960 +numpy/core/_type_aliases.py,sha256=qV6AZlsUWHMWTydmZya73xuBkKXiUKq_WXLj7q2CbZ0,7534 +numpy/core/_type_aliases.pyi,sha256=lguMSqMwvqAFHuRtm8YZSdKbikVz985BdKo_lo7GQCg,404 +numpy/core/_ufunc_config.py,sha256=-Twpe8dnd45ccXH-w-B9nvU8yCOd1E0e3Wpsts3g_bQ,13944 +numpy/core/_ufunc_config.pyi,sha256=-615enOVQMBhVx7Pln7DY_s4H6JjSgSnBy89YkpvuLg,1066 +numpy/core/_umath_tests.cpython-311-x86_64-linux-gnu.so,sha256=G_1pjqWX0wE-CBY1CeWdfvaHNGEfOREmgJkzFTNYX9Q,42272 +numpy/core/arrayprint.py,sha256=ySZj4TZFFVCa5yhMmJKFYQYhuQTabZTRBb1YoiCD-ac,63608 +numpy/core/arrayprint.pyi,sha256=21pOWjTSfJOBaKgOOPzRox1ERb3c9ydufqL0b11_P_Q,4428 +numpy/core/cversions.py,sha256=H_iNIpx9-hY1cQNxqjT2d_5SXZhJbMo_caq4_q6LB7I,347 +numpy/core/defchararray.py,sha256=G1LExk-dMeVTYRhtYgcCZEsHk5tkawk7giXcK4Q5KVM,73617 +numpy/core/defchararray.pyi,sha256=ib3aWFcM7F4KooU57mWUNi4GlosNjdfgrLKBVSIKDvU,9216 +numpy/core/einsumfunc.py,sha256=TrL6t79F0H0AQH0y5Cj7Tq0_pzk4fVFi-4q4jJmujYQ,51868 +numpy/core/einsumfunc.pyi,sha256=IJZNdHHG_soig8XvCbXZl43gMr3MMKl9dckTYWecqLs,4860 +numpy/core/fromnumeric.py,sha256=YMtxOBg51VMem39AHXFs-4_vOb1p48ei7njXdYTRJ_Q,128821 +numpy/core/fromnumeric.pyi,sha256=KATMFeFxUJ8YNRaC-jd_dTOt3opz2ng6lHgke5u5COk,23726 +numpy/core/function_base.py,sha256=tHg1qSHTz1eO_wHXNFRt3Q40uqVtPT2eyQdrWbIi4wQ,19836 +numpy/core/function_base.pyi,sha256=3ZYad3cdaGwNEyP8VwK97IYMqk2PDoVjpjQzhIYHjk0,4725 +numpy/core/getlimits.py,sha256=AopcTZDCUXMPcEKIZE1botc3mEhmLb2p1_ejlq1CLqY,25865 +numpy/core/getlimits.pyi,sha256=qeIXUEtognTHr_T-tv-VcZI7n8Z2VzAyIpIgKXzsLkc,82 +numpy/core/include/numpy/__multiarray_api.c,sha256=nPRzTez_Wy3YXy3zZNJNPMspAzxbLOdohqhXwouwMLM,12116 +numpy/core/include/numpy/__multiarray_api.h,sha256=ZM--FKMhIaSQS39cPW0hj5dx8ngNMmbcy6SbgXZBd8U,61450 +numpy/core/include/numpy/__ufunc_api.c,sha256=670Gcz-vhkF4taBDmktCpFRBrZ9CHJnPRx7ag7Z6HsI,1714 +numpy/core/include/numpy/__ufunc_api.h,sha256=0MBOl7dgO3ldqdDi-SdciEOuqGv1UNsmk7mp7tEy4AY,12456 +numpy/core/include/numpy/_dtype_api.h,sha256=4veCexGvx9KNWMIUuEUAVOfcsei9GqugohDY5ud16pA,16697 +numpy/core/include/numpy/_neighborhood_iterator_imp.h,sha256=s-Hw_l5WRwKtYvsiIghF0bg-mA_CgWnzFFOYVFJ-q4k,1857 +numpy/core/include/numpy/_numpyconfig.h,sha256=o0fV_jb-wgVtRxnVIWvUttiZafyrWYFm2ab9Uixz1Cw,855 +numpy/core/include/numpy/arrayobject.h,sha256=-BlWQ7kfVbzCqzHn0qaeMe0_08AbwliuG98XWG57lT8,282 +numpy/core/include/numpy/arrayscalars.h,sha256=C3vDRndZTZRbppiDyV5jp8sV3dRKsrwBIZcNlh9gSTA,3944 +numpy/core/include/numpy/experimental_dtype_api.h,sha256=tlehD5r_pYhHbGzIrUea6vtOgf6IQ8Txblnhx7455h8,15532 +numpy/core/include/numpy/halffloat.h,sha256=TRZfXgipa-dFppX2uNgkrjrPli-1BfJtadWjAembJ4s,1959 +numpy/core/include/numpy/ndarrayobject.h,sha256=PhY4NjRZDoU5Zbc8MW0swPEm81hwgWZ63gAU93bLVVI,10183 +numpy/core/include/numpy/ndarraytypes.h,sha256=EjWXv-J8C5JET4AlIbJRdctycL7-dyJZcnoWgnlCPc8,68009 +numpy/core/include/numpy/noprefix.h,sha256=d83l1QpCCVqMV2k29NMkL3Ld1qNjiC6hzOPWZAivEjQ,6830 +numpy/core/include/numpy/npy_1_7_deprecated_api.h,sha256=y0MJ8Qw7Bkt4H_4VxIzHzpkw5JqAdj5ECgtn08fZFrI,4327 +numpy/core/include/numpy/npy_3kcompat.h,sha256=SvN9yRA3i02O4JFMXxZz0Uq_vJ5ZpvC-pC2sfF56A5I,15883 +numpy/core/include/numpy/npy_common.h,sha256=apWBsCJeP8P5T0exgzhFcGohbASsUF8vtFdS2jc1VfU,37746 +numpy/core/include/numpy/npy_cpu.h,sha256=pcVRtj-Y6120C5kWB1VAiAjZoxkTPDEg0gGm5IAt3jM,4629 +numpy/core/include/numpy/npy_endian.h,sha256=we7X9fPeWzNpo_YTh09MPGDwdE0Rw_WDM4c9y4nBj5I,2786 +numpy/core/include/numpy/npy_interrupt.h,sha256=DQZIxi6FycLXD8drdHn2SSmLoRhIpo6osvPv13vowUA,1948 +numpy/core/include/numpy/npy_math.h,sha256=SbKRoc7O3gVuDl7HOZjk424O049I0zn-7i9GwBwNmmk,18945 +numpy/core/include/numpy/npy_no_deprecated_api.h,sha256=0yZrJcQEJ6MCHJInQk5TP9_qZ4t7EfBuoLOJ34IlJd4,678 +numpy/core/include/numpy/npy_os.h,sha256=hlQsg_7-RkvS3s8OM8KXy99xxyJbCm-W1AYVcdnO1cw,1256 +numpy/core/include/numpy/numpyconfig.h,sha256=Nr59kE3cXmen6y0UymIBaU7F1BSIuPwgKZ4gdV5Q5JU,5308 +numpy/core/include/numpy/old_defines.h,sha256=xuYQDDlMywu0Zsqm57hkgGwLsOFx6IvxzN2eiNF-gJY,6405 +numpy/core/include/numpy/random/LICENSE.txt,sha256=-8U59H0M-DvGE3gID7hz1cFGMBJsrL_nVANcOSbapew,1018 +numpy/core/include/numpy/random/bitgen.h,sha256=49AwKOR552r-NkhuSOF1usb_URiMSRMvD22JF5pKIng,488 +numpy/core/include/numpy/random/distributions.h,sha256=W5tOyETd0m1W0GdaZ5dJP8fKlBtsTpG23V2Zlmrlqpg,9861 +numpy/core/include/numpy/random/libdivide.h,sha256=ew9MNhPQd1LsCZiWiFmj9IZ7yOnA3HKOXffDeR9X1jw,80138 +numpy/core/include/numpy/ufuncobject.h,sha256=Xmnny_ulZo9VwxkfkXF-1HCTKDavIp9PV_H7XWhi0Z8,12070 +numpy/core/include/numpy/utils.h,sha256=wMNomSH3Dfj0q78PrjLVtFtN-FPo7UJ4o0ifCUO-6Es,1185 +numpy/core/lib/libnpymath.a,sha256=mb8EluEp8SLpEeCTQJ0VshL-CqeZfWxSbS5ItM-9POc,93960 +numpy/core/lib/npy-pkg-config/mlib.ini,sha256=_LsWV1eStNqwhdiYPa2538GL46dnfVwT4MrI1zbsoFw,147 +numpy/core/lib/npy-pkg-config/npymath.ini,sha256=kamUNrYKAmXqQa8BcNv7D5sLqHh6bnChM0_5rZCsTfY,360 +numpy/core/memmap.py,sha256=yWBJLeVClHsD8BYusnf9bdqypOMPrj3_zoO_lQ2zVMc,11771 +numpy/core/memmap.pyi,sha256=sxIQ7T5hPLG-RBNndAc8JPvrsKEX1amBSH2HGg48Obo,55 +numpy/core/multiarray.py,sha256=zXaWf_DSkFEWjUQqVRCGeevwsI6kjQ3x6_MUwA1Y8fk,56097 +numpy/core/multiarray.pyi,sha256=_0X4W90U5ZiKt2n-9OscK-pcQyV6oGK-8jwGy5k1qxA,24768 +numpy/core/numeric.py,sha256=DgajaCDXiiQR-zuW_rrx_QhApSsa5k5FONK3Uk9mfTs,77014 +numpy/core/numeric.pyi,sha256=oVQkI4ABayFl_ZzCiGH4DxfYASL-3aETi-3B93THnEQ,14315 +numpy/core/numerictypes.py,sha256=qIf9v1OpNjjVQzXnKpD-3V01y5Bj9huw5F-U5Wa4glc,18098 +numpy/core/numerictypes.pyi,sha256=dEqtq9MLrGaqqeAF1sdXBgnEwDWOzlK02A6MTg1PS5g,3267 +numpy/core/overrides.py,sha256=YUZFS8RCBvOJ27sH-jDRcyMjOCn9VigMyuQY4J21JBI,7093 +numpy/core/records.py,sha256=4mpIjUp2XtZxY5cD2S8mgfn8GCzQGGrrkqLBqAJwM-Q,37533 +numpy/core/records.pyi,sha256=uYwE6cAoGKgN6U4ryfGZx_3m-3sY006jytjWLrDRRy0,5692 +numpy/core/shape_base.py,sha256=RPMKxA7_FCAgg_CruExl0LehnczSTFaxA6hrcfrUzns,29743 +numpy/core/shape_base.pyi,sha256=Ilb4joJmbjkIZLzKww7NJeaxg2FP3AfFib3HtfOsrC0,2774 +numpy/core/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/core/tests/__pycache__/_locales.cpython-311.pyc,, +numpy/core/tests/__pycache__/test__exceptions.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_abc.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_api.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_argparse.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_array_coercion.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_array_interface.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_arraymethod.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_arrayprint.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_casting_floatingpoint_errors.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_casting_unittests.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_conversion_utils.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_cpu_dispatcher.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_cpu_features.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_custom_dtypes.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_cython.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_datetime.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_defchararray.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_deprecations.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_dlpack.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_dtype.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_einsum.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_errstate.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_extint128.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_function_base.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_getlimits.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_half.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_hashtable.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_indexerrors.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_indexing.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_item_selection.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_limited_api.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_longdouble.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_machar.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_mem_overlap.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_mem_policy.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_memmap.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_multiarray.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_nditer.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_nep50_promotions.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_numeric.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_numerictypes.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_numpy_2_0_compat.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_overrides.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_print.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_protocols.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_records.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalar_ctors.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalar_methods.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalarbuffer.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalarinherit.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalarmath.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_scalarprint.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_shape_base.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_simd.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_simd_module.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_strings.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_ufunc.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_umath.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_umath_accuracy.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_umath_complex.cpython-311.pyc,, +numpy/core/tests/__pycache__/test_unicode.cpython-311.pyc,, +numpy/core/tests/_locales.py,sha256=S4x5soqF0oxpBYOE8J9Iky72O9J25IiZ8349m93pWC4,2206 +numpy/core/tests/data/astype_copy.pkl,sha256=lWSzCcvzRB_wpuRGj92spGIw-rNPFcd9hwJaRVvfWdk,716 +numpy/core/tests/data/generate_umath_validation_data.cpp,sha256=fyhQPNhIX9hzjeXujn6mhi1MVc133zELSV_hlSQ7BQU,5842 +numpy/core/tests/data/numpy_2_0_array.pkl,sha256=Vh02tdyCypa8Nb4QzdVhnDAiXEO2WQrcwcvOdDDFF5w,718 +numpy/core/tests/data/recarray_from_file.fits,sha256=NA0kliz31FlLnYxv3ppzeruONqNYkuEvts5wzXEeIc4,8640 +numpy/core/tests/data/umath-validation-set-README.txt,sha256=pxWwOaGGahaRd-AlAidDfocLyrAiDp0whf5hC7hYwqM,967 +numpy/core/tests/data/umath-validation-set-arccos.csv,sha256=W_aL99bjzVjlVyd5omfDUORag8jHzx6uctedPVZgOHQ,61365 +numpy/core/tests/data/umath-validation-set-arccosh.csv,sha256=Uko_d0kDXr1YlN-6Ii-fQQxUvbXAhRfC7Un4gJ23GJk,61365 +numpy/core/tests/data/umath-validation-set-arcsin.csv,sha256=15Aenze4WD2a2dF2aOBXpv9B7u3wwAeUVJdEm4TjOkQ,61339 +numpy/core/tests/data/umath-validation-set-arcsinh.csv,sha256=uDwx4PStpfV21IaPF8pmzQpul6i72g7zDwlfcynWaVQ,60289 +numpy/core/tests/data/umath-validation-set-arctan.csv,sha256=mw5tYze_BMs6ugGEZfg5mcXoInGYdn7fvSCYSUi9Bqw,60305 +numpy/core/tests/data/umath-validation-set-arctanh.csv,sha256=95l4Uu5RmZajljabfqlv5U34RVrifCMhhkop6iLeNBo,61339 +numpy/core/tests/data/umath-validation-set-cbrt.csv,sha256=v855MTZih-fZp_GuEDst2qaIsxU4a7vlAbeIJy2xKpc,60846 +numpy/core/tests/data/umath-validation-set-cos.csv,sha256=0PNnDqKkokZ7ERVDgbes8KNZc-ISJrZUlVZc5LkW18E,59122 +numpy/core/tests/data/umath-validation-set-cosh.csv,sha256=FGCNeUSUTAeASsb_j18iRSsCxXLxmzF-_C7tq1elVrQ,60869 +numpy/core/tests/data/umath-validation-set-exp.csv,sha256=BKg1_cyrKD2GXYMX_EB0DnXua8DI2O1KWODXf_BRhrk,17491 +numpy/core/tests/data/umath-validation-set-exp2.csv,sha256=f1b05MRXPOXihC9M-yi52udKBzVXalhbTuIcqoDAk-g,58624 +numpy/core/tests/data/umath-validation-set-expm1.csv,sha256=_ghc1xiUECNsBGrKCFUAy2lvu01_lkpeYJN0zDtCYWk,60299 +numpy/core/tests/data/umath-validation-set-log.csv,sha256=z9ej1ykKUoMRqYMUIJENWXbYi_A_x_RKs7K_GuXZJus,11692 +numpy/core/tests/data/umath-validation-set-log10.csv,sha256=RJgpruL16FVPgUT3-3xW4eppS_tn6o5yEW79KnITn48,68922 +numpy/core/tests/data/umath-validation-set-log1p.csv,sha256=IZZI-hi55HGCOvBat3vSBVha_8Nt-5alf2fqz6QeTG0,60303 +numpy/core/tests/data/umath-validation-set-log2.csv,sha256=HL2rOCsrEi378rNrbsXHPqlWlEGkXQq8R4e63YeTksU,68917 +numpy/core/tests/data/umath-validation-set-sin.csv,sha256=8PUjnQ_YfmxFb42XJrvpvmkeSpEOlEXSmNvIK4VgfAM,58611 +numpy/core/tests/data/umath-validation-set-sinh.csv,sha256=CYiibE8aX7MQnBatl__5k_PWc_9vHUifwS-sFZzzKk0,60293 +numpy/core/tests/data/umath-validation-set-tan.csv,sha256=Oq7gxMvblRVBrQ23kMxc8iT0bHnCWKg9EE4ZqzbJbOA,60299 +numpy/core/tests/data/umath-validation-set-tanh.csv,sha256=iolZF_MOyWRgYSa-SsD4df5mnyFK18zrICI740SWoTc,60299 +numpy/core/tests/examples/cython/__pycache__/setup.cpython-311.pyc,, +numpy/core/tests/examples/cython/checks.pyx,sha256=rKAhPSGHJ9oPK9Q_85YoUQyRTftEP1jcYOR5lSPB6oQ,662 +numpy/core/tests/examples/cython/meson.build,sha256=Qk4Q6OkpZ0xsLUkcGQVVrYkzb0ozoyL6YlSZ8_5tH1I,1088 +numpy/core/tests/examples/cython/setup.py,sha256=aAR-TvQabUabnCzuB6UdWdmRXaaPfIG7MzTIfMF-0tk,496 +numpy/core/tests/examples/limited_api/__pycache__/setup.cpython-311.pyc,, +numpy/core/tests/examples/limited_api/limited_api.c,sha256=mncE8TjjXmYpkwli433G0jB2zGQO_5NqWmGKdzRJZug,344 +numpy/core/tests/examples/limited_api/setup.py,sha256=p2w7F1ardi_GRXSrnNIR8W1oeH_pgmw_1P2wS0A2I6M,435 +numpy/core/tests/test__exceptions.py,sha256=QqxQSLXboPXEVwHz-TyE2JeIl_TC-rPugzfo25nbcns,2846 +numpy/core/tests/test_abc.py,sha256=FfgYA_HjYAi8XWGK_oOh6Zw86chB_KG_XoW_7ZlFp4c,2220 +numpy/core/tests/test_api.py,sha256=UMc7SvczAQ5ngHxE-NoXVvNpVzYRrn8oMwFNta1yMS0,22995 +numpy/core/tests/test_argparse.py,sha256=C0zBbwQ9xzzymXe_hHpWnnWQPwOi2ZdQB78gBAgJHvU,1969 +numpy/core/tests/test_array_coercion.py,sha256=zY4Pjlt4QZ0w71WxWGLHcrPnnhEF51yXYVLg5HMIy5c,34379 +numpy/core/tests/test_array_interface.py,sha256=8tGgj1Nzi76H_WF5GULkxqWL7Yu_Xf0lvTJZOwOBKsI,7774 +numpy/core/tests/test_arraymethod.py,sha256=VpjDYTmoMDTZcY7CsGzinBh0R_OICuwOykWCbmCRQZU,3244 +numpy/core/tests/test_arrayprint.py,sha256=cKaIoD9ZvsjJH0PHwZyOxmcRcBt1kN1WfFneqVqs0b8,40462 +numpy/core/tests/test_casting_floatingpoint_errors.py,sha256=W3Fgk0oKtXFv684fEZ7POwj6DHTYK0Jj_oGRLZ8UdyA,5063 +numpy/core/tests/test_casting_unittests.py,sha256=9-vkR0oXczQz8ED8DxGVPmalC8IZXe2jKgOCMGr8hIg,34298 +numpy/core/tests/test_conversion_utils.py,sha256=jNhbNNI-T8qtQnsIMEax7KFN30kjh0ICntLMwTyxJ5Q,6559 +numpy/core/tests/test_cpu_dispatcher.py,sha256=v_SlhUpENuoe7QYXizzYITLGXa7WfZ7jqcqmbSBg7JU,1542 +numpy/core/tests/test_cpu_features.py,sha256=mieGx7dxXFiyTYatbcCCjIjR67Un2hVcbJx4GEf2yFo,14892 +numpy/core/tests/test_custom_dtypes.py,sha256=JogRmttDLwfQ3PTbewEnGLKco9zV2Nu3yIfrMeCsx_I,9401 +numpy/core/tests/test_cython.py,sha256=t5-h4XSIFNLyw_9BIAQDYl8_80t_pH0SCfEa1Vf_3aI,3755 +numpy/core/tests/test_datetime.py,sha256=2vAGbrCQmsrWNXCVXOMZqUGZn2c-cQT-eZ1wTprYbcM,116211 +numpy/core/tests/test_defchararray.py,sha256=F88HUkByEP4H6cJ_ITvIe0a_T1BH2JOdRysMCu1XIn0,24997 +numpy/core/tests/test_deprecations.py,sha256=w2lhHb-W8hh7RoE_0Ftg8thpG86jvbFAJgior22DY2Q,31076 +numpy/core/tests/test_dlpack.py,sha256=cDlwFmTombb2rDeB8RHEAJ4eVMUiDbw8Oz5Jo1NQwk0,3522 +numpy/core/tests/test_dtype.py,sha256=J09pJF59v7UO6iNuJFISKP2DLPgdkQ_df5OAMDRLikU,75702 +numpy/core/tests/test_einsum.py,sha256=QzQAPIC-IjTV3Dxz97hBnvLBCmF8kpsBTBckThhgRjQ,53712 +numpy/core/tests/test_errstate.py,sha256=U3GT9I058jkF725mx4GdWUr9RoceCkGDV7Go79VA4wY,2219 +numpy/core/tests/test_extint128.py,sha256=gCZfAwPOb-F1TLsEEeDI0amQYwHk-60-OXi0ccZrrZ8,5643 +numpy/core/tests/test_function_base.py,sha256=Ibs6-WXZE5hsRx4VCnX-cZOWYKU-5PFXjouwAQzgnqQ,15595 +numpy/core/tests/test_getlimits.py,sha256=apdxr0zKkxaVHIUpLrqAvO39q54JKN14sV4xSbK2Ifs,6718 +numpy/core/tests/test_half.py,sha256=VYPyap9GYOWZuphsfFofcIRl-oa5Ufrtv83OTp6azdU,24593 +numpy/core/tests/test_hashtable.py,sha256=ZV8HL8NkDnoQZfnje7BP0fyIp4fSFqjKsQc40PaTggc,1011 +numpy/core/tests/test_indexerrors.py,sha256=kN9xLl6FVTzmI7fumn_cuZ3k0omXnTetgtCnPY44cvw,5130 +numpy/core/tests/test_indexing.py,sha256=x0ojWuhOwWD5MZuiJ9Ncim3CgkwI-GldWxrSCmjmFJM,54314 +numpy/core/tests/test_item_selection.py,sha256=kI30kiX8mIrZYPn0jw3lGGw1ruZF4PpE9zw-aai9EPA,6458 +numpy/core/tests/test_limited_api.py,sha256=5yO0nGmCKZ9b3S66QP7vY-HIgAoyOtHZmp8mvzKuOHI,1172 +numpy/core/tests/test_longdouble.py,sha256=jO8YMm_Hsz-XPKbmv6iMcOdHgTlIFkKTwAtxpy3Q1pE,13905 +numpy/core/tests/test_machar.py,sha256=_5_TDUVtAJvJI5jBfEFKpCZtAfKCsCFt7tXlWSkWzzc,1067 +numpy/core/tests/test_mem_overlap.py,sha256=QJ0unWD_LOoAGAo4ra0IvYenj56IYUtiz1fEJEmTY9Q,29086 +numpy/core/tests/test_mem_policy.py,sha256=CXa10FQw2Qj6MqJuaC8Fm4slsoipKFjCIpYF6c5IIAU,16801 +numpy/core/tests/test_memmap.py,sha256=tZ5lJs_4ZFsJmg392ZQ33fX0m8tdfZ8ZtY9Lq41LNtk,7477 +numpy/core/tests/test_multiarray.py,sha256=GPv4IJR9dijNG-icUsQsX2tBD2RdP3EhUehY4cxvVQU,380106 +numpy/core/tests/test_nditer.py,sha256=nVQ00aNxPHqf4ZcFs3e9AVDK64TCqlO0TzfocTAACZQ,130818 +numpy/core/tests/test_nep50_promotions.py,sha256=2TwtFvj1LBpYTtdR6NFe1RAAGXIJltLqwpA1vhQCVY4,8840 +numpy/core/tests/test_numeric.py,sha256=ZGNW5NKgShEjZC_TcPOtTuRaTM_GbuM21u82D205UPs,137294 +numpy/core/tests/test_numerictypes.py,sha256=f_xMjZJnyDwlc6XCrd71b6x1_6dAWOv-kZ3-NEq37hU,21687 +numpy/core/tests/test_numpy_2_0_compat.py,sha256=kVCTAXska7Xi5w_TYduWhid0nlCqI6Nvmt-gDnYsuKI,1630 +numpy/core/tests/test_overrides.py,sha256=t0gOZOzu7pevE58HA-npFYJqnInHR-LLBklnzKJWHqo,26080 +numpy/core/tests/test_print.py,sha256=ErZAWd88b0ygSEoYpd0BL2tFjkerMtn1vZ7dWvaNqTc,6837 +numpy/core/tests/test_protocols.py,sha256=fEXE9K9s22oiVWkX92BY-g00-uXCK-HxjZhZxxYAKFc,1168 +numpy/core/tests/test_records.py,sha256=pluit5x6jkWoPEIrHXM13L3xZuuSSiaxoXFsOdkakCU,20269 +numpy/core/tests/test_regression.py,sha256=SJo9cPTVr2SNjhgtW7boUMyNQlXxygsZ5g0oyqC8Eks,91595 +numpy/core/tests/test_scalar_ctors.py,sha256=qDIZV-tBukwAxNDhUmGtH3CemDXlS3xd_q3L52touuA,6115 +numpy/core/tests/test_scalar_methods.py,sha256=Uj-zU0zzzKAjMBdpkzsWZ3nSFj5gJkUlqi_euhOYdnU,7541 +numpy/core/tests/test_scalarbuffer.py,sha256=FSL94hriWX1_uV6Z33wB3ZXUrpmmX2-x87kNjIxUeBk,5580 +numpy/core/tests/test_scalarinherit.py,sha256=fMInDGKsiH3IS_2ejZtIcmJZ0Ry8c7kVsHx7wp5XDoM,2368 +numpy/core/tests/test_scalarmath.py,sha256=XZj_m2I2TLktJdFD1SWj2XtV8hT26VIxasDz3cAFvgA,43247 +numpy/core/tests/test_scalarprint.py,sha256=1599W5X0tjGhBnSQjalXkg6AY8eHXnr6PMqs4vYZQqs,18771 +numpy/core/tests/test_shape_base.py,sha256=D9haeuUVx3x3pOLmFQ9vUz7iU4T2bFTsPoI8HgSncFU,29723 +numpy/core/tests/test_simd.py,sha256=-L1UhIn9Eu_euLwaSU7bPRfYpWWOTb43qovoJS7Ws7w,48696 +numpy/core/tests/test_simd_module.py,sha256=OSpYhH_3QDxItyQcaW6SjXW57k2m-weRwpYOnJjCqN0,3902 +numpy/core/tests/test_strings.py,sha256=A9t1B65lFrYRLXgDJSg3mMDAe_hypIPcTMVOdAYIbU0,3835 +numpy/core/tests/test_ufunc.py,sha256=5pS2x3LACHn8GogYYad8LRAjByK7Gg9xTD9ik3d0Fm0,124907 +numpy/core/tests/test_umath.py,sha256=huHpclJqkO32k7BTflRHj8nImzg3p6yyryeS9LyHKWU,186482 +numpy/core/tests/test_umath_accuracy.py,sha256=mFcVdzXhhD9mqhzLDJVZsWfCHbjbFQ6XeEl5G8l-PTc,3897 +numpy/core/tests/test_umath_complex.py,sha256=WvZZZWeijo52RiOfx-G83bxzQOp_IJ3i9fEnUDVukLQ,23247 +numpy/core/tests/test_unicode.py,sha256=hUXIwMmoq89y_KXWzuXVyQaXvRwGjfY4TvKJsCbygEI,12775 +numpy/core/umath.py,sha256=JbT_SxnZ_3MEmjOI9UtX3CcAzX5Q-4RDlnnhDAEJ5Vo,2040 +numpy/core/umath_tests.py,sha256=TIzaDfrEHHgSc2J5kxFEibq8MOPhwSuyOZOUBsZNVSM,389 +numpy/ctypeslib.py,sha256=Po4XCWfxhwFQ1Q8x8DeayGiMCJLxREaCDkVyeladxBU,17247 +numpy/ctypeslib.pyi,sha256=A9te473aRO920iDVuyKypeVIQp-ueZK6EiI-qLSwJNg,7972 +numpy/distutils/__init__.py,sha256=BU1C21439HRo7yH1SsN9me6WCDPpOwRQ37ZpNwDMqCw,2074 +numpy/distutils/__init__.pyi,sha256=D8LRE6BNOmuBGO-oakJGnjT9UJTk9zSR5rxMfZzlX64,119 +numpy/distutils/__pycache__/__init__.cpython-311.pyc,, +numpy/distutils/__pycache__/_shell_utils.cpython-311.pyc,, +numpy/distutils/__pycache__/armccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/ccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/ccompiler_opt.cpython-311.pyc,, +numpy/distutils/__pycache__/conv_template.cpython-311.pyc,, +numpy/distutils/__pycache__/conv_template.cpython-311.pyc,sha256=zd9yf0Ycn-ffRFlFlSAZzXZuBjj2t-2rX1pwgtsyCPk,14202 +numpy/distutils/__pycache__/core.cpython-311.pyc,, +numpy/distutils/__pycache__/cpuinfo.cpython-311.pyc,, +numpy/distutils/__pycache__/exec_command.cpython-311.pyc,, +numpy/distutils/__pycache__/extension.cpython-311.pyc,, +numpy/distutils/__pycache__/from_template.cpython-311.pyc,, +numpy/distutils/__pycache__/fujitsuccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/intelccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/lib2def.cpython-311.pyc,, +numpy/distutils/__pycache__/line_endings.cpython-311.pyc,, +numpy/distutils/__pycache__/log.cpython-311.pyc,, +numpy/distutils/__pycache__/mingw32ccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/misc_util.cpython-311.pyc,, +numpy/distutils/__pycache__/msvc9compiler.cpython-311.pyc,, +numpy/distutils/__pycache__/msvccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/npy_pkg_config.cpython-311.pyc,, +numpy/distutils/__pycache__/numpy_distribution.cpython-311.pyc,, +numpy/distutils/__pycache__/pathccompiler.cpython-311.pyc,, +numpy/distutils/__pycache__/setup.cpython-311.pyc,, +numpy/distutils/__pycache__/system_info.cpython-311.pyc,, +numpy/distutils/__pycache__/unixccompiler.cpython-311.pyc,, +numpy/distutils/_shell_utils.py,sha256=kMLOIoimB7PdFRgoVxCIyCFsIl1pP3d0hkm_s3E9XdA,2613 +numpy/distutils/armccompiler.py,sha256=8qUaYh8QHOJlz7MNvkuJNyYdCOCivuW0pbmf_2OPZu0,962 +numpy/distutils/ccompiler.py,sha256=6I-zQBLJCyZUZaYdmK23pmucM8MAn2OsvyzEdghPpW0,28618 +numpy/distutils/ccompiler_opt.py,sha256=diDOkSKj_j0xY08kP7-NoQsefxJgsN5clEirqXlavGY,100390 +numpy/distutils/checks/cpu_asimd.c,sha256=nXUsTLrSlhRL-UzDM8zMqn1uqJnR7TRlJi3Ixqw539w,818 +numpy/distutils/checks/cpu_asimddp.c,sha256=E4b9zT1IdSfGR2ACZJiQoR-BqaeDtzFqRNW8lBOXAaY,432 +numpy/distutils/checks/cpu_asimdfhm.c,sha256=6tXINVEpmA-lYRSbL6CrBu2ejNFmd9WONFGgg-JFXZE,529 +numpy/distutils/checks/cpu_asimdhp.c,sha256=SfwrEEA_091tmyI4vN3BNLs7ypUnrF_VbTg6gPl-ocs,379 +numpy/distutils/checks/cpu_avx.c,sha256=LuZW8o93VZZi7cYEP30dvKWTm7Mw1TLmCt5UaXDxCJg,779 +numpy/distutils/checks/cpu_avx2.c,sha256=jlDlea393op0JOiMJgmmPyKmyAXztLcObPOp9F9FaS0,749 +numpy/distutils/checks/cpu_avx512_clx.c,sha256=P-YHjj2XE4SithBkPwDgShOxGWnVSNUXg72h8O3kpbs,842 +numpy/distutils/checks/cpu_avx512_cnl.c,sha256=f_c2Z0xwAKTJeK3RYMIp1dgXYV8QyeOxUgKkMht4qko,948 +numpy/distutils/checks/cpu_avx512_icl.c,sha256=isI35-gm7Hqn2Qink5hP1XHWlh52a5vwKhEdW_CRviE,1004 +numpy/distutils/checks/cpu_avx512_knl.c,sha256=PVTkczTpHlXbTc7IQKlCFU9Cq4VGG-_JhVnT0_n-t1A,959 +numpy/distutils/checks/cpu_avx512_knm.c,sha256=eszPGr3XC9Js7mQUB0gFxlrNjQwfucQFz_UwFyNLjes,1132 +numpy/distutils/checks/cpu_avx512_skx.c,sha256=59VD8ebEJJHLlbY-4dakZV34bmq_lr9mBKz8BAcsdYc,1010 +numpy/distutils/checks/cpu_avx512_spr.c,sha256=i8DpADB8ZhIucKc8lt9JfYbQANRvR67u59oQf5winvg,904 +numpy/distutils/checks/cpu_avx512cd.c,sha256=Qfh5FJUv9ZWd_P5zxkvYYIkvqsPptgaDuKkeX_F8vyA,759 +numpy/distutils/checks/cpu_avx512f.c,sha256=d97NRcbJhqpvURnw7zyG0TOuEijKXvU0g4qOTWHbwxY,755 +numpy/distutils/checks/cpu_f16c.c,sha256=nzZzpUc8AfTtw-INR3KOxcjx9pyzVUM8OhsrdH2dO_w,868 +numpy/distutils/checks/cpu_fma3.c,sha256=YN6IDwuZALJHVVmpQ2tj-14HI_PcxH_giV8-XjzlmkU,817 +numpy/distutils/checks/cpu_fma4.c,sha256=qKdgTNNFg-n8vSB1Txco60HBLCcOi1aH23gZOX7yKqs,301 +numpy/distutils/checks/cpu_neon.c,sha256=Y0SjuVLzh3upcbY47igHjmKgjHbXxbvzncwB7acfjxw,600 +numpy/distutils/checks/cpu_neon_fp16.c,sha256=E7YOGyYP41u1sqiCHpCGGqjmo7Cs6yUkmJ46K7LZloc,251 +numpy/distutils/checks/cpu_neon_vfpv4.c,sha256=qFY1C_fQYz7M_a_8j0KTdn7vaE3NNVmWY2JGArDGM3w,609 +numpy/distutils/checks/cpu_popcnt.c,sha256=vRcXHVw2j1F9I_07eIZ_xzDX3fd3mqgiQXL1w3pULJk,1049 +numpy/distutils/checks/cpu_sse.c,sha256=6MHITtC76UpSR9uh0SiURpnkpPkLzT5tbrcXT4xBFxo,686 +numpy/distutils/checks/cpu_sse2.c,sha256=yUZzdjDtBS-vYlhfP-pEzj3m0UPmgZs-hA99TZAEACU,697 +numpy/distutils/checks/cpu_sse3.c,sha256=j5XRHumUuccgN9XPZyjWUUqkq8Nu8XCSWmvUhmJTJ08,689 +numpy/distutils/checks/cpu_sse41.c,sha256=y_k81P-1b-Hx8OeRVDE9V1O9JakS0zPvlFKJ3VbSmEw,675 +numpy/distutils/checks/cpu_sse42.c,sha256=3PXucdI2mII-txO7zFN99TlVveT_QUAETTGvRk-_hYw,692 +numpy/distutils/checks/cpu_ssse3.c,sha256=X6VWxIXMRpdSCBsHPXvot3yTZ4d5yK9Bi1ScQP3WC-Q,705 +numpy/distutils/checks/cpu_vsx.c,sha256=FVmR4iliKjcihzMCwloR1F2JYwSZK9P4f_hvIRLHSDQ,478 +numpy/distutils/checks/cpu_vsx2.c,sha256=yESs25Rt5ztb5-stuYbu3TbiyJKmllMpMLu01GOAHqE,263 +numpy/distutils/checks/cpu_vsx3.c,sha256=omC50tbEZNigsKMFPtE3zGRlIS2VuDTm3vZ9TBZWo4U,250 +numpy/distutils/checks/cpu_vsx4.c,sha256=ngezA1KuINqJkLAcMrZJR7bM0IeA25U6I-a5aISGXJo,305 +numpy/distutils/checks/cpu_vx.c,sha256=OpLU6jIfwvGJR4JPVVZLlUfvo7oAZ0YvsjafM2qtPlk,461 +numpy/distutils/checks/cpu_vxe.c,sha256=rYW_nKwXnlB0b8xCrJEr4TmvrEvS-NToxwyqqOHV8Bk,788 +numpy/distutils/checks/cpu_vxe2.c,sha256=Hv4wO23kwC2G6lqqercq4NE4K0nrvBxR7RIzr5HTXCc,624 +numpy/distutils/checks/cpu_xop.c,sha256=7uabsGeqvmVJQvuSEjs8-Sm8kpmvl6uZ9YHMF5h2opQ,234 +numpy/distutils/checks/extra_avx512bw_mask.c,sha256=pVPOhcu80yJVnIhOcHHXOlZ2proJ1MUf0XgccqhPoNk,636 +numpy/distutils/checks/extra_avx512dq_mask.c,sha256=nMfIvepISGFDexPrMYl5LWtdmt6Uy9TKPzF4BVayw2I,504 +numpy/distutils/checks/extra_avx512f_reduce.c,sha256=_NfbtfSAkm_A67umjR1oEb9yRnBL5EnTA76fvQIuNVk,1595 +numpy/distutils/checks/extra_vsx3_half_double.c,sha256=shHvIQZfR0o-sNefOt49BOh4WCmA0BpJvj4b7F9UdvQ,354 +numpy/distutils/checks/extra_vsx4_mma.c,sha256=GiQGZ9-6wYTgH42bJgSlXhWcTIrkjh5xv4uymj6rglk,499 +numpy/distutils/checks/extra_vsx_asm.c,sha256=BngiMVS9nyr22z6zMrOrHLeCloe_5luXhf5T5mYucgI,945 +numpy/distutils/checks/test_flags.c,sha256=uAIbhfAhyGe4nTdK_mZmoCefj9P0TGHNF9AUv_Cdx5A,16 +numpy/distutils/command/__init__.py,sha256=fW49zUB3syMFsKpf1oRBO0h8tmnTwRP3zUPrsB0R22M,1032 +numpy/distutils/command/__pycache__/__init__.cpython-311.pyc,, +numpy/distutils/command/__pycache__/autodist.cpython-311.pyc,, +numpy/distutils/command/__pycache__/bdist_rpm.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build_clib.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build_ext.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build_py.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build_scripts.cpython-311.pyc,, +numpy/distutils/command/__pycache__/build_src.cpython-311.pyc,, +numpy/distutils/command/__pycache__/config.cpython-311.pyc,, +numpy/distutils/command/__pycache__/config_compiler.cpython-311.pyc,, +numpy/distutils/command/__pycache__/develop.cpython-311.pyc,, +numpy/distutils/command/__pycache__/egg_info.cpython-311.pyc,, +numpy/distutils/command/__pycache__/install.cpython-311.pyc,, +numpy/distutils/command/__pycache__/install_clib.cpython-311.pyc,, +numpy/distutils/command/__pycache__/install_data.cpython-311.pyc,, +numpy/distutils/command/__pycache__/install_headers.cpython-311.pyc,, +numpy/distutils/command/__pycache__/sdist.cpython-311.pyc,, +numpy/distutils/command/autodist.py,sha256=8KWwr5mnjX20UpY4ITRDx-PreApyh9M7B92IwsEtTsQ,3718 +numpy/distutils/command/bdist_rpm.py,sha256=-tkZupIJr_jLqeX7xbRhE8-COXHRI0GoRpAKchVte54,709 +numpy/distutils/command/build.py,sha256=aj1SUGsDUTxs4Tch2ALLcPnuAVhaPjEPIZIobzMajm0,2613 +numpy/distutils/command/build_clib.py,sha256=TCuZDpRd8ZPZH6SRwIZcWZC3aoGc18Rll6FYcawS6qY,19317 +numpy/distutils/command/build_ext.py,sha256=UcyG8KKyrd5v1s6qDdKEkzwLwmoMlfHA893Lj-OOgl0,32983 +numpy/distutils/command/build_py.py,sha256=XiLZ2d_tmCE8uG5VAU5OK2zlzQayBfeY4l8FFEltbig,1144 +numpy/distutils/command/build_scripts.py,sha256=P2ytmZb3UpwfmbMXkFB2iMQk15tNUCynzMATllmp-Gs,1665 +numpy/distutils/command/build_src.py,sha256=sxsnfc8KBsnsSvI-8sKIKNo2KA2uvrrvW0WYZCqyjyk,31178 +numpy/distutils/command/config.py,sha256=SdN-Cxvwx3AD5k-Xx_VyS2WWpVGmflnYGiTIyruj_xM,20670 +numpy/distutils/command/config_compiler.py,sha256=Cp9RTpW72gg8XC_3-9dCTlLYr352pBfBRZA8YBWvOoY,4369 +numpy/distutils/command/develop.py,sha256=9SbbnFnVbSJVZxTFoV9pwlOcM1D30GnOWm2QonQDvHI,575 +numpy/distutils/command/egg_info.py,sha256=i-Zk4sftK5cMQVQ2jqSxTMpVI-gYyXN16-p5TvmjURc,921 +numpy/distutils/command/install.py,sha256=nkW2fl7OABcE3sUcoNM7iONkF64CBESdVlRjTLg3hVA,3073 +numpy/distutils/command/install_clib.py,sha256=1xv0_lPVu3g16GgICjjlh7T8zQ6PSlevCuq8Bocx5YM,1399 +numpy/distutils/command/install_data.py,sha256=Y59EBG61MWP_5C8XJvSCVfzYpMNVNVcH_Z6c0qgr9KA,848 +numpy/distutils/command/install_headers.py,sha256=tVpOGqkmh8AA_tam0K0SeCd4kvZj3UqSOjWKm6Kz4jY,919 +numpy/distutils/command/sdist.py,sha256=8Tsju1RwXNbPyQcjv8GRMFveFQqYlbNdSZh2X1OV-VU,733 +numpy/distutils/conv_template.py,sha256=F-4vkkfAjCb-fN79WYrXX3BMHMoiQO-W2u09q12OPuI,9536 +numpy/distutils/core.py,sha256=C-_z7rODE_12olz0dwtlKqwfaSLXEV3kZ1CyDJMsQh8,8200 +numpy/distutils/cpuinfo.py,sha256=XuNhsx_-tyrui_AOgn10yfZ9p4YBM68vW2_bGmKj07I,22639 +numpy/distutils/exec_command.py,sha256=0EGasX7tM47Q0k8yJA1q-BvIcjV_1UAC-zDmen-j6Lg,10283 +numpy/distutils/extension.py,sha256=YgeB8e2fVc2l_1etuRBv0P8c1NULOz4SaudHgsVBc30,3568 +numpy/distutils/fcompiler/__init__.py,sha256=DqfaiKGVagOFuL0v3VZxZZkRnWWvly0_lYHuLjaZTBo,40625 +numpy/distutils/fcompiler/__pycache__/__init__.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/absoft.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/arm.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/compaq.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/environment.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/fujitsu.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/g95.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/gnu.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/hpux.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/ibm.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/intel.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/lahey.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/mips.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/nag.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/none.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/nv.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/pathf95.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/pg.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/sun.cpython-311.pyc,, +numpy/distutils/fcompiler/__pycache__/vast.cpython-311.pyc,, +numpy/distutils/fcompiler/absoft.py,sha256=yPUHBNZHOr_gxnte16I_X85o1iL9FI4RLHjG9JOuyYU,5516 +numpy/distutils/fcompiler/arm.py,sha256=MCri346qo1bYwjlm32xHRyRl-bAINTlfVIubN6HDz68,2090 +numpy/distutils/fcompiler/compaq.py,sha256=sjU2GKHJGuChtRb_MhnouMqvkIOQflmowFE6ErCWZhE,3903 +numpy/distutils/fcompiler/environment.py,sha256=DOD2FtKDk6O9k6U0h9UKWQ-65wU8z1tSPn3gUlRwCso,3080 +numpy/distutils/fcompiler/fujitsu.py,sha256=yK3wdHoF5qq25UcnIM6FzTXsJGJxdfKa_f__t04Ne7M,1333 +numpy/distutils/fcompiler/g95.py,sha256=FH4uww6re50OUT_BfdoWSLCDUqk8LvmQ2_j5RhF5nLQ,1330 +numpy/distutils/fcompiler/gnu.py,sha256=ag8v_pp-fYpDPKJsVmNaFwN621b1MFQAxew0T1KdE_Y,20502 +numpy/distutils/fcompiler/hpux.py,sha256=gloUjWGo7MgJmukorDq7ZxDnnUKXx-C6AQfryQshVM4,1353 +numpy/distutils/fcompiler/ibm.py,sha256=Ts2PXg2ocrXtX9eguvcHeQ4JB2ktpd5isXtRTpU9F5Y,3534 +numpy/distutils/fcompiler/intel.py,sha256=XYF0GLVhJWjS8noEx4TJ704Eqt-JGBolRZEOkwgNItE,6570 +numpy/distutils/fcompiler/lahey.py,sha256=U63KMfN8zDAd_jnvMkS2N-dvP4UiSRB9Ces290qLNXw,1327 +numpy/distutils/fcompiler/mips.py,sha256=LAwT0DY5yqlYh20hNMYR1-OKu8A9GNw-TbUfI8pvglM,1714 +numpy/distutils/fcompiler/nag.py,sha256=9pQCMUlwjRVHGKwZxvwd4bW5p-9v7VXcflELEImHg1g,2777 +numpy/distutils/fcompiler/none.py,sha256=6RX2X-mV1HuhJZnVfQmDmLVhIUWseIT4P5wf3rdLq9Y,758 +numpy/distutils/fcompiler/nv.py,sha256=LGBQY417zibQ-fnPis5rNtP_I1Qk9OlhEFOnPvmwXHI,1560 +numpy/distutils/fcompiler/pathf95.py,sha256=MiHVar6-beUEYVEpqXORIX4f8G29I47D36kreltdfoQ,1061 +numpy/distutils/fcompiler/pg.py,sha256=NOB1stzrjvQMZS7bIPTgWTcAFe3cjNveA5-SztUZqD0,3568 +numpy/distutils/fcompiler/sun.py,sha256=mfS3RTj9uYT6K9Ikp8RjmsEPIWAtUTzMhX9sGjEyF6I,1577 +numpy/distutils/fcompiler/vast.py,sha256=Xuxa4sNraUPcQmt45SogAfN0kDHFb6C73uNZNmX3RBE,1667 +numpy/distutils/from_template.py,sha256=hpoFQortsLZdMSr_fJILzXzrIwFlZoFjsDSo6jNtvWs,7913 +numpy/distutils/fujitsuccompiler.py,sha256=JDuUUE-GyPahkNnDZLWNHyAmJ2lJPCnLuIUFfHkjMzA,834 +numpy/distutils/intelccompiler.py,sha256=N_pvWjlLORdlH34cs97oU4LBNr_s9r5ddsmme7XEvs4,4234 +numpy/distutils/lib2def.py,sha256=-3rDf9FXsDik3-Qpp-A6N_cYZKTlmVjVi4Jzyo-pSlY,3630 +numpy/distutils/line_endings.py,sha256=a8ZZECrPRffsbs0UygeR47_fOUlZppnx-QPssrIXtB0,2032 +numpy/distutils/log.py,sha256=m8caNBwPhIG7YTnD9iq9jjc6_yJOeU9FHuau2CSulds,2879 +numpy/distutils/mingw/gfortran_vs2003_hack.c,sha256=cbsN3Lk9Hkwzr9c-yOP2xEBg1_ml1X7nwAMDWxGjzc8,77 +numpy/distutils/mingw32ccompiler.py,sha256=4G8t_6plw7xqoF0icDaWGNSBgbyDaHQn3GB5l9gikEA,22067 +numpy/distutils/misc_util.py,sha256=2MxXE4rex_wSUhpLuwxOFeeor-WxZLjisVvXWycNaq4,89359 +numpy/distutils/msvc9compiler.py,sha256=FCtP7g34AVuMIaqQlH8AV1ZBdIUXbk5G7eBeeTSr1zE,2192 +numpy/distutils/msvccompiler.py,sha256=ILookUifVJF9tAtPJoVCqZ673m5od6MVKuAHuA3Rcfk,2647 +numpy/distutils/npy_pkg_config.py,sha256=fIFyWLTqRySO3hn-0i0FNdHeblRN_hDv-wc68-sa3hQ,12972 +numpy/distutils/numpy_distribution.py,sha256=10Urolg1aDAG0EHYfcvObzOgqRV0ARh2GhDklEg4vS0,634 +numpy/distutils/pathccompiler.py,sha256=KnJEA5H4cXg7SLrMjwWtidD24VSvOdu72d17votiY9E,713 +numpy/distutils/setup.py,sha256=l9ke_Bws431UdBfysaq7ZeGtZ8dix76oh9Huq5qqbkU,634 +numpy/distutils/system_info.py,sha256=SCk1ku0HnZNwConQBJN8FVidbeKVnrMxUyNWUVx73pY,114022 +numpy/distutils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/distutils/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_build_ext.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_ccompiler_opt.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_ccompiler_opt_conf.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_exec_command.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_gnu.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_intel.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_nagfor.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_from_template.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_log.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_mingw32ccompiler.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_misc_util.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_npy_pkg_config.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_shell_utils.cpython-311.pyc,, +numpy/distutils/tests/__pycache__/test_system_info.cpython-311.pyc,, +numpy/distutils/tests/test_build_ext.py,sha256=RNrEi-YMTGQG5YDi5GWL8iJRkk_bQHBQKcqp43TdJco,2769 +numpy/distutils/tests/test_ccompiler_opt.py,sha256=N3pN-9gxPY1KvvMEjoXr7kLxTGN8aQOr8qo5gmlrm90,28778 +numpy/distutils/tests/test_ccompiler_opt_conf.py,sha256=maXytv39amuojbQIieIGIXMV4Cv-s0fsPMZeFEh9XyY,6347 +numpy/distutils/tests/test_exec_command.py,sha256=BK-hHfIIrkCep-jNmS5_Cwq5oESvsvX3V_0XDAkT1Ok,7395 +numpy/distutils/tests/test_fcompiler.py,sha256=mJXezTXDUbduhCwVGAfABHpEARWhnj8hLW9EOU3rn84,1277 +numpy/distutils/tests/test_fcompiler_gnu.py,sha256=nmfaFCVzbViIOQ2-MjgXt-bN8Uj674hCgiwr5Iol-_U,2136 +numpy/distutils/tests/test_fcompiler_intel.py,sha256=mxkfFD2rNfg8nn1pp_413S0uCdYXydPWBcz9ilgGkA0,1058 +numpy/distutils/tests/test_fcompiler_nagfor.py,sha256=CKEjik7YVfSJGL4abuctkmlkIUhAhv-x2aUcXiTR9b0,1102 +numpy/distutils/tests/test_from_template.py,sha256=SDYoe0XUpAayyEQDq7ZhrvEEz7U9upJDLYzhcdoVifc,1103 +numpy/distutils/tests/test_log.py,sha256=0tSM4q-00CjbMIRb9QOJzI4A7GHUiRGOG1SOOLz8dnM,868 +numpy/distutils/tests/test_mingw32ccompiler.py,sha256=rMC8-IyBOiuZVfAoklV_KnD9qVeB_hFVvb5dStxfk08,1609 +numpy/distutils/tests/test_misc_util.py,sha256=Qs96vTr8GZSyVCWuamzcNlVMRa15vt0Y-T2yZSUm_QA,3218 +numpy/distutils/tests/test_npy_pkg_config.py,sha256=apGrmViPcXoPCEOgDthJgL13C9N0qQMs392QjZDxJd4,2557 +numpy/distutils/tests/test_shell_utils.py,sha256=UKU_t5oIa_kVMv89Ys9KN6Z_Fy5beqPDUsDAWPmcoR8,2114 +numpy/distutils/tests/test_system_info.py,sha256=wMV7bH5oB0luLDR2tunHrLaUxsD_-sIhLnNpj1blQPs,11405 +numpy/distutils/unixccompiler.py,sha256=fN4-LH6JJp44SLE7JkdG2kKQlK4LC8zuUpVC-RtmJ-U,5426 +numpy/doc/__init__.py,sha256=OYmE-F6x0CD05PCDY2MiW1HLlwB6i9vhDpk-a3r4lHY,508 +numpy/doc/__pycache__/__init__.cpython-311.pyc,, +numpy/doc/__pycache__/constants.cpython-311.pyc,, +numpy/doc/__pycache__/ufuncs.cpython-311.pyc,, +numpy/doc/constants.py,sha256=PlXoj7b4A8Aa9nADbg83uzTBRJaX8dvJmEdbn4FDPPo,9155 +numpy/doc/ufuncs.py,sha256=i1alLg19mNyCFZ2LYSOZGm--RsRN1x63U_UYU-N3x60,5357 +numpy/dtypes.py,sha256=BuBztrPQRasUmVZhXr2_NgJujdUTNhNwd59pZZHk3lA,2229 +numpy/dtypes.pyi,sha256=tIHniAYP7ALg2iT7NgSXO67jvE-zRlDod3MazEmD4M8,1315 +numpy/exceptions.py,sha256=7j7tv8cwXGZYgldyMisGmnAxAl2s4YU0vexME81yYlA,7339 +numpy/exceptions.pyi,sha256=KsZqWNvyPUEXUGR9EhZCUQF2f9EVSpBRlJUlGqRT02k,600 +numpy/f2py/__init__.py,sha256=m-ty_WiJZ4GVfV5--kJ3MFJaLXestz5Eo-4H0FPscK4,5565 +numpy/f2py/__init__.pyi,sha256=eA7uYXZr0p0aaz5rBW-EypLx9RchrvqDYtSnkEJQsYw,1087 +numpy/f2py/__main__.py,sha256=6i2jVH2fPriV1aocTY_dUFvWK18qa-zjpnISA-OpF3w,130 +numpy/f2py/__pycache__/__init__.cpython-311.pyc,, +numpy/f2py/__pycache__/__main__.cpython-311.pyc,, +numpy/f2py/__pycache__/__version__.cpython-311.pyc,, +numpy/f2py/__pycache__/_isocbind.cpython-311.pyc,, +numpy/f2py/__pycache__/_src_pyf.cpython-311.pyc,, +numpy/f2py/__pycache__/auxfuncs.cpython-311.pyc,, +numpy/f2py/__pycache__/capi_maps.cpython-311.pyc,, +numpy/f2py/__pycache__/cb_rules.cpython-311.pyc,, +numpy/f2py/__pycache__/cfuncs.cpython-311.pyc,, +numpy/f2py/__pycache__/common_rules.cpython-311.pyc,, +numpy/f2py/__pycache__/crackfortran.cpython-311.pyc,, +numpy/f2py/__pycache__/diagnose.cpython-311.pyc,, +numpy/f2py/__pycache__/f2py2e.cpython-311.pyc,, +numpy/f2py/__pycache__/f90mod_rules.cpython-311.pyc,, +numpy/f2py/__pycache__/func2subr.cpython-311.pyc,, +numpy/f2py/__pycache__/rules.cpython-311.pyc,, +numpy/f2py/__pycache__/setup.cpython-311.pyc,, +numpy/f2py/__pycache__/symbolic.cpython-311.pyc,, +numpy/f2py/__pycache__/use_rules.cpython-311.pyc,, +numpy/f2py/__version__.py,sha256=7HHdjR82FCBmftwMRyrlhcEj-8mGQb6oCH-wlUPH4Nw,34 +numpy/f2py/_backends/__init__.py,sha256=7_bA7c_xDpLc4_8vPfH32-Lxn9fcUTgjQ25srdvwvAM,299 +numpy/f2py/_backends/__pycache__/__init__.cpython-311.pyc,, +numpy/f2py/_backends/__pycache__/_backend.cpython-311.pyc,, +numpy/f2py/_backends/__pycache__/_distutils.cpython-311.pyc,, +numpy/f2py/_backends/__pycache__/_meson.cpython-311.pyc,, +numpy/f2py/_backends/_backend.py,sha256=GKb9-UaFszT045vUgVukPs1n97iyyjqahrWKxLOKNYo,1187 +numpy/f2py/_backends/_distutils.py,sha256=pxh2YURFYYSykIOvBFwVvhoNX1oSk-c30IPPhzlko-0,2383 +numpy/f2py/_backends/_meson.py,sha256=gi-nbnPFDC38sumfAjg-Q5FPu6nNkyQXTjEuVf9W9Cc,6916 +numpy/f2py/_backends/meson.build.template,sha256=oTPNMAQzS4CJ_lfEzYv-oBeJTtQuThUYVN5R6ROWpNU,1579 +numpy/f2py/_isocbind.py,sha256=zaBgpfPNRmxVG3doUIlbZIiyB990MsXiwDabrSj9HnQ,2360 +numpy/f2py/_src_pyf.py,sha256=4t6TN4ZKWciC4f1z6fwaGrpIGhHKRiwHfcrNj4FIzCg,7654 +numpy/f2py/auxfuncs.py,sha256=dNs4b2KDIcG4M1hPBvD09-Vh7CDzlPIrFscOdvL3p1o,26539 +numpy/f2py/capi_maps.py,sha256=ENjYyeZ3CCJcLwJJgmKOSYrD1KPuhpwauXqeizdV55o,30563 +numpy/f2py/cb_rules.py,sha256=5TuHbJWGjsF6yVNzKuV2tAnwdLyhcWlmdsjYlDOZOv4,24992 +numpy/f2py/cfuncs.py,sha256=KJyW7mdjmFSmxssfeegGJs5NZyF3mZMgNvOxN9-vYHQ,51913 +numpy/f2py/common_rules.py,sha256=gHB76WypbkVmhaD_RWhy8Od4zDTgj8cbDOdUdIp6PIQ,5131 +numpy/f2py/crackfortran.py,sha256=ErLdkWP8MxeyW5vVPGXwyvrxZAwymlvIBC0th2rvK74,148553 +numpy/f2py/diagnose.py,sha256=0SRXBE2hJgKJN_Rf4Zn00oKXC_Tka3efPWM47zg6BoY,5197 +numpy/f2py/f2py2e.py,sha256=5t093ZQ4xs0_0UbyaYVd2yA2EVOaOAcuU29JI-IU2Ag,27717 +numpy/f2py/f90mod_rules.py,sha256=otm3_dmVIna0eBVHLu_693s3a_82lU3pqeqDacWI37s,9594 +numpy/f2py/func2subr.py,sha256=6d2R5awuHRT4xzgfUfwS7JHTqhhAieSXcENlssD_2c4,10298 +numpy/f2py/rules.py,sha256=B4FxSYEfZ_1j_z9GulQNZ1BNrPrUvlU3ybxwTkrIxjI,62727 +numpy/f2py/setup.cfg,sha256=Fpn4sjqTl5OT5sp8haqKIRnUcTPZNM6MIvUJBU7BIhg,48 +numpy/f2py/setup.py,sha256=MmAVspT8DDTqDuL8ZJhxK62g0lcso4vqI6QNQ9CsfoQ,2422 +numpy/f2py/src/fortranobject.c,sha256=g4BKDO1_9pCu6hithKXD2oH_Mt-HH1NTnP6leCqJrzc,46017 +numpy/f2py/src/fortranobject.h,sha256=neMKotYWbHvrhW9KXz4QzQ8fzPkiQXLHHjy82vLSeog,5835 +numpy/f2py/symbolic.py,sha256=jWBoAwECCxRdWczR9r7O6UERcYmH_GbdcAReNp7cmJY,53270 +numpy/f2py/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/f2py/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_assumed_shape.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_block_docstring.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_callback.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_character.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_common.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_compile_function.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_crackfortran.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_data.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_docs.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_f2cmap.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_f2py2e.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_isoc.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_kind.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_mixed.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_module_doc.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_parameter.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_pyf_src.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_quoted_character.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_return_character.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_return_complex.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_return_integer.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_return_logical.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_return_real.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_size.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_string.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_symbolic.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-311.pyc,, +numpy/f2py/tests/__pycache__/util.cpython-311.pyc,, +numpy/f2py/tests/src/abstract_interface/foo.f90,sha256=JFU2w98cB_XNwfrqNtI0yDTmpEdxYO_UEl2pgI_rnt8,658 +numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90,sha256=gvQJIzNtvacWE0dhysxn30-iUeI65Hpq7DiE9oRauz8,105 +numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c,sha256=Ff5wHYV9-OJnZuelfFWcjAibRvDkEIlbTVczTyv6TG8,7299 +numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap,sha256=But9r9m4iL7EGq_haMW8IiQ4VivH0TgUozxX4pPvdpE,29 +numpy/f2py/tests/src/assumed_shape/foo_free.f90,sha256=oBwbGSlbr9MkFyhVO2aldjc01dr9GHrMrSiRQek8U64,460 +numpy/f2py/tests/src/assumed_shape/foo_mod.f90,sha256=rfzw3QdI-eaDSl-hslCgGpd5tHftJOVhXvb21Y9Gf6M,499 +numpy/f2py/tests/src/assumed_shape/foo_use.f90,sha256=rmT9k4jP9Ru1PLcGqepw9Jc6P9XNXM0axY7o4hi9lUw,269 +numpy/f2py/tests/src/assumed_shape/precision.f90,sha256=r08JeTVmTTExA-hYZ6HzaxVwBn1GMbPAuuwBhBDtJUk,130 +numpy/f2py/tests/src/block_docstring/foo.f,sha256=y7lPCPu7_Fhs_Tf2hfdpDQo1bhtvNSKRaZAOpM_l3dg,97 +numpy/f2py/tests/src/callback/foo.f,sha256=C1hjfpRCQWiOVVzIHqnsYcnLrqQcixrnHCn8hd9GhVk,1254 +numpy/f2py/tests/src/callback/gh17797.f90,sha256=_Nrl0a2HgUbtymGU0twaJ--7rMa1Uco2A3swbWvHoMo,148 +numpy/f2py/tests/src/callback/gh18335.f90,sha256=NraOyKIXyvv_Y-3xGnmTjtNjW2Znsnlk8AViI8zfovc,506 +numpy/f2py/tests/src/callback/gh25211.f,sha256=a2sxlQhtDVbYn8KOKHUYqwc-aCFt7sDPSnJsXFG35uI,179 +numpy/f2py/tests/src/callback/gh25211.pyf,sha256=FWxo0JWQlw519BpZV8PoYeI_FZ_K6C-3Wk6gLrfBPlw,447 +numpy/f2py/tests/src/cli/gh_22819.pyf,sha256=5rvOfCv-wSosB354LC9pExJmMoSHnbGZGl_rtA2fogA,142 +numpy/f2py/tests/src/cli/hi77.f,sha256=ttyI6vAP3qLnDqy82V04XmoqrXNM6uhMvvLri2p0dq0,71 +numpy/f2py/tests/src/cli/hiworld.f90,sha256=QWOLPrTxYQu1yrEtyQMbM0fE9M2RmXe7c185KnD5x3o,51 +numpy/f2py/tests/src/common/block.f,sha256=GQ0Pd-VMX3H3a-__f2SuosSdwNXHpBqoGnQDjf8aG9g,224 +numpy/f2py/tests/src/common/gh19161.f90,sha256=BUejyhqpNVfHZHQ-QC7o7ZSo7lQ6YHyX08lSmQqs6YM,193 +numpy/f2py/tests/src/crackfortran/accesstype.f90,sha256=-5Din7YlY1TU7tUHD2p-_DSTxGBpDsWYNeT9WOwGhno,208 +numpy/f2py/tests/src/crackfortran/data_common.f,sha256=ZSUAh3uhn9CCF-cYqK5TNmosBGPfsuHBIEfudgysun4,193 +numpy/f2py/tests/src/crackfortran/data_multiplier.f,sha256=jYrJKZWF_59JF9EMOSALUjn0UupWvp1teuGpcL5s1Sc,197 +numpy/f2py/tests/src/crackfortran/data_stmts.f90,sha256=19YO7OGj0IksyBlmMLZGRBQLjoE3erfkR4tFvhznvvE,693 +numpy/f2py/tests/src/crackfortran/data_with_comments.f,sha256=hoyXw330VHh8duMVmAQZjr1lgLVF4zFCIuEaUIrupv0,175 +numpy/f2py/tests/src/crackfortran/foo_deps.f90,sha256=CaH7mnWTG7FcnJe2vXN_0zDbMadw6NCqK-JJ2HmDjK8,128 +numpy/f2py/tests/src/crackfortran/gh15035.f,sha256=jJly1AzF5L9VxbVQ0vr-sf4LaUo4eQzJguhuemFxnvg,375 +numpy/f2py/tests/src/crackfortran/gh17859.f,sha256=7K5dtOXGuBDAENPNCt-tAGJqTfNKz5OsqVSk16_e7Es,340 +numpy/f2py/tests/src/crackfortran/gh22648.pyf,sha256=qZHPRNQljIeYNwbqPLxREnOrSdVV14f3fnaHqB1M7c0,241 +numpy/f2py/tests/src/crackfortran/gh23533.f,sha256=w3tr_KcY3s7oSWGDmjfMHv5h0RYVGUpyXquNdNFOJQg,126 +numpy/f2py/tests/src/crackfortran/gh23598.f90,sha256=41W6Ire-5wjJTTg6oAo7O1WZfd1Ug9vvNtNgHS5MhEU,101 +numpy/f2py/tests/src/crackfortran/gh23598Warn.f90,sha256=1v-hMCT_K7prhhamoM20nMU9zILam84Hr-imck_dYYk,205 +numpy/f2py/tests/src/crackfortran/gh23879.f90,sha256=LWDJTYR3t9h1IsrKC8dVXZlBfWX7clLeU006X6Ow8oI,332 +numpy/f2py/tests/src/crackfortran/gh2848.f90,sha256=gPNasx98SIf7Z9ibk_DHiGKCvl7ERtsfoGXiFDT7FbM,282 +numpy/f2py/tests/src/crackfortran/operators.f90,sha256=-Fc-qjW1wBr3Dkvdd5dMTrt0hnjnV-1AYo-NFWcwFSo,1184 +numpy/f2py/tests/src/crackfortran/privatemod.f90,sha256=7bubZGMIn7iD31wDkjF1TlXCUM7naCIK69M9d0e3y-U,174 +numpy/f2py/tests/src/crackfortran/publicmod.f90,sha256=Pnwyf56Qd6W3FUH-ZMgnXEYkb7gn18ptNTdwmGan0Jo,167 +numpy/f2py/tests/src/crackfortran/pubprivmod.f90,sha256=eYpJwBYLKGOxVbKgEqfny1znib-b7uYhxcRXIf7uwXg,165 +numpy/f2py/tests/src/crackfortran/unicode_comment.f90,sha256=aINLh6GlfTwFewxvDoqnMqwuCNb4XAqi5Nj5vXguXYs,98 +numpy/f2py/tests/src/f2cmap/.f2py_f2cmap,sha256=iUOtfHd3OuT1Rz2-yiSgt4uPKGvCt5AzQ1iygJt_yjg,82 +numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90,sha256=iJCD8a8MUTmuPuedbcmxW54Nr4alYuLhksBe1sHS4K0,298 +numpy/f2py/tests/src/isocintrin/isoCtests.f90,sha256=jcw-fzrFh0w5U66uJYfeUW4gv94L5MnWQ_NpsV9y0oI,998 +numpy/f2py/tests/src/kind/foo.f90,sha256=zIHpw1KdkWbTzbXb73hPbCg4N2Htj3XL8DIwM7seXpo,347 +numpy/f2py/tests/src/mixed/foo.f,sha256=90zmbSHloY1XQYcPb8B5d9bv9mCZx8Z8AMTtgDwJDz8,85 +numpy/f2py/tests/src/mixed/foo_fixed.f90,sha256=pxKuPzxF3Kn5khyFq9ayCsQiolxB3SaNtcWaK5j6Rv4,179 +numpy/f2py/tests/src/mixed/foo_free.f90,sha256=fIQ71wrBc00JUAVUj_r3QF9SdeNniBiMw6Ly7CGgPWU,139 +numpy/f2py/tests/src/module_data/mod.mod,sha256=EkjrU7NTZrOH68yKrz6C_eyJMSFSxGgC2yMQT9Zscek,412 +numpy/f2py/tests/src/module_data/module_data_docstring.f90,sha256=tDZ3fUlazLL8ThJm3VwNGJ75QIlLcW70NnMFv-JA4W0,224 +numpy/f2py/tests/src/negative_bounds/issue_20853.f90,sha256=fdOPhRi7ipygwYCXcda7p_dlrws5Hd2GlpF9EZ-qnck,157 +numpy/f2py/tests/src/parameter/constant_both.f90,sha256=-bBf2eqHb-uFxgo6Q7iAtVUUQzrGFqzhHDNaxwSICfQ,1939 +numpy/f2py/tests/src/parameter/constant_compound.f90,sha256=re7pfzcuaquiOia53UT7qNNrTYu2euGKOF4IhoLmT6g,469 +numpy/f2py/tests/src/parameter/constant_integer.f90,sha256=nEmMLitKoSAG7gBBEQLWumogN-KS3DBZOAZJWcSDnFw,612 +numpy/f2py/tests/src/parameter/constant_non_compound.f90,sha256=IcxESVLKJUZ1k9uYKoSb8Hfm9-O_4rVnlkiUU2diy8Q,609 +numpy/f2py/tests/src/parameter/constant_real.f90,sha256=quNbDsM1Ts2rN4WtPO67S9Xi_8l2cXabWRO00CPQSSQ,610 +numpy/f2py/tests/src/quoted_character/foo.f,sha256=WjC9D9171fe2f7rkUAZUvik9bkIf9adByfRGzh6V0cM,482 +numpy/f2py/tests/src/regression/gh25337/data.f90,sha256=9Uz8CHB9i3_mjC3cTOmkTgPAF5tWSwYacG3MUrU-SY0,180 +numpy/f2py/tests/src/regression/gh25337/use_data.f90,sha256=WATiDGAoCKnGgMzm_iMgmfVU0UKOQlk5Fm0iXCmPAkE,179 +numpy/f2py/tests/src/regression/inout.f90,sha256=CpHpgMrf0bqA1W3Ozo3vInDz0RP904S7LkpdAH6ODck,277 +numpy/f2py/tests/src/return_character/foo77.f,sha256=WzDNF3d_hUDSSZjtxd3DtE-bSx1ilOMEviGyYHbcFgM,980 +numpy/f2py/tests/src/return_character/foo90.f90,sha256=ULcETDEt7gXHRzmsMhPsGG4o3lGrcx-FEFaJsPGFKyA,1248 +numpy/f2py/tests/src/return_complex/foo77.f,sha256=8ECRJkfX82oFvGWKbIrCvKjf5QQQClx4sSEvsbkB6A8,973 +numpy/f2py/tests/src/return_complex/foo90.f90,sha256=c1BnrtWwL2dkrTr7wvlEqNDg59SeNMo3gyJuGdRwcDw,1238 +numpy/f2py/tests/src/return_integer/foo77.f,sha256=_8k1evlzBwvgZ047ofpdcbwKdF8Bm3eQ7VYl2Y8b5kA,1178 +numpy/f2py/tests/src/return_integer/foo90.f90,sha256=bzxbYtofivGRYH35Ang9ScnbNsVERN8-6ub5-eI-LGQ,1531 +numpy/f2py/tests/src/return_logical/foo77.f,sha256=FxiF_X0HkyXHzJM2rLyTubZJu4JB-ObLnVqfZwAQFl8,1188 +numpy/f2py/tests/src/return_logical/foo90.f90,sha256=9KmCe7yJYpi4ftkKOM3BCDnPOdBPTbUNrKxY3p37O14,1531 +numpy/f2py/tests/src/return_real/foo77.f,sha256=ZTrzb6oDrIDPlrVWP3Bmtkbz3ffHaaSQoXkfTGtCuFE,933 +numpy/f2py/tests/src/return_real/foo90.f90,sha256=gZuH5lj2lG6gqHlH766KQ3J4-Ero-G4WpOOo2MG3ohU,1194 +numpy/f2py/tests/src/size/foo.f90,sha256=IlFAQazwBRr3zyT7v36-tV0-fXtB1d7WFp6S1JVMstg,815 +numpy/f2py/tests/src/string/char.f90,sha256=ihr_BH9lY7eXcQpHHDQhFoKcbu7VMOX5QP2Tlr7xlaM,618 +numpy/f2py/tests/src/string/fixed_string.f90,sha256=5n6IkuASFKgYICXY9foCVoqndfAY0AQZFEK8L8ARBGM,695 +numpy/f2py/tests/src/string/gh24008.f,sha256=UA8Pr-_yplfOFmc6m4v9ryFQ8W9OulaglulefkFWD68,217 +numpy/f2py/tests/src/string/gh24662.f90,sha256=-Tp9Kd1avvM7AIr8ZukFA9RVr-wusziAnE8AvG9QQI4,197 +numpy/f2py/tests/src/string/gh25286.f90,sha256=2EpxvC-0_dA58MBfGQcLyHzpZgKcMf_W9c73C_Mqnok,304 +numpy/f2py/tests/src/string/gh25286.pyf,sha256=GjgWKh1fHNdPGRiX5ek60i1XSeZsfFalydWqjISPVV8,381 +numpy/f2py/tests/src/string/gh25286_bc.pyf,sha256=6Y9zU66NfcGhTXlFOdFjCSMSwKXpq5ZfAe3FwpkAsm4,384 +numpy/f2py/tests/src/string/scalar_string.f90,sha256=ACxV2i6iPDk-a6L_Bs4jryVKYJMEGUTitEIYTjbJes4,176 +numpy/f2py/tests/src/string/string.f,sha256=shr3fLVZaa6SyUJFYIF1OZuhff8v5lCwsVNBU2B-3pk,248 +numpy/f2py/tests/src/value_attrspec/gh21665.f90,sha256=JC0FfVXsnB2lZHb-nGbySnxv_9VHAyD0mKaLDowczFU,190 +numpy/f2py/tests/test_abstract_interface.py,sha256=C8-ly0_TqkmpQNZmwPHwo2IV2MBH0jQEjAhpqHrg8Y4,832 +numpy/f2py/tests/test_array_from_pyobj.py,sha256=Txff89VUeEhWqUCRVybIqsqH4YQvpk4Uyjmh_XjyMi0,24049 +numpy/f2py/tests/test_assumed_shape.py,sha256=FeaqtrWyBf5uyArcmI0D2e_f763aSMpgU3QmdDXe-tA,1466 +numpy/f2py/tests/test_block_docstring.py,sha256=SEpuq73T9oVtHhRVilFf1xF7nb683d4-Kv7V0kfL4AA,564 +numpy/f2py/tests/test_callback.py,sha256=cReSlVjgnoT74wmtNn-oEIZiJUTfRX7ljjlqJi716IQ,6494 +numpy/f2py/tests/test_character.py,sha256=3ugjM1liymMRbY8wub1eiap-jdyNYVHxlNZBqNoRLe4,21868 +numpy/f2py/tests/test_common.py,sha256=m7TTSJt5zUZKJF-MQUeTtCyxW7YwRBSETINXGPFu8S4,896 +numpy/f2py/tests/test_compile_function.py,sha256=9d_FZ8P2wbIlQ2qPDRrsFqPb4nMH8tiWqYZN-P_shCs,4186 +numpy/f2py/tests/test_crackfortran.py,sha256=y1x3U-jlQWD5rmTXz1I2RlTz7LEfbI6qxCDkR5fzPwY,13441 +numpy/f2py/tests/test_data.py,sha256=HFcmPYbiveKa-swJ8x8XlRR9sM0ESB9FEN-txZnHTok,2876 +numpy/f2py/tests/test_docs.py,sha256=jqtuHE5ZjxP4D8Of3Fkzz36F8_0qKbeS040_m0ac4v4,1662 +numpy/f2py/tests/test_f2cmap.py,sha256=p-Sylbr3ctdKT3UQV9FzpCuYPH5U7Vyn8weXFAjiI9o,391 +numpy/f2py/tests/test_f2py2e.py,sha256=eoswH-daMEBlueoVpxXrDloahCpr0RLzHbr3zBHOsjk,25423 +numpy/f2py/tests/test_isoc.py,sha256=_nPTPxNEEagiKriZBeFNesOattIlHDzaNKmj35xxDBY,1406 +numpy/f2py/tests/test_kind.py,sha256=aOMQSBoD_dw49acKN25_abEvQBLI27DsnWIb9CNpSAE,1671 +numpy/f2py/tests/test_mixed.py,sha256=Ctuw-H7DxhPjSt7wZdJ2xffawIoEBCPWc5F7PSkY4HY,848 +numpy/f2py/tests/test_module_doc.py,sha256=sjCXWIKrqMD1NQ1DUAzgQqkjS5w9h9gvM_Lj29Rdcrg,863 +numpy/f2py/tests/test_parameter.py,sha256=ADI7EV_CM4ztICpqHqeq8LI-WdB6cX0ttatdRdjbsUA,3941 +numpy/f2py/tests/test_pyf_src.py,sha256=eD0bZu_GWfoCq--wWqEKRf-F2h5AwoTyO6GMA9wJPr4,1135 +numpy/f2py/tests/test_quoted_character.py,sha256=cpjMdrHwimnkoJkXd_W_FSlh43oWytY5VHySW9oskO4,454 +numpy/f2py/tests/test_regression.py,sha256=v_6RDQr6IcMmbCMElfzRSLPgZhHnH5l99uztrbJAzqE,2532 +numpy/f2py/tests/test_return_character.py,sha256=18HJtiRwQ7a_2mdPUonD5forKWZJEapD-Vi1DsbTjVs,1493 +numpy/f2py/tests/test_return_complex.py,sha256=BZIIqQ1abdiPLgVmu03_q37yCtND0ijxGSMhGz2Wf-o,2397 +numpy/f2py/tests/test_return_integer.py,sha256=t--9UsdLF9flLTQv7a0KTSVoBuoDtTnmOG2QIFPINVc,1758 +numpy/f2py/tests/test_return_logical.py,sha256=XCmp8E8I6BOeNYF59HjSFAdv1hM9WaDvl8UDS10_05o,2017 +numpy/f2py/tests/test_return_real.py,sha256=ATek5AM7dCCPeIvoMOQIt5yFNFzKrFb1Kno8B4M0rn4,3235 +numpy/f2py/tests/test_semicolon_split.py,sha256=_Mdsi84lES18pPjl9J-QsbGttV4tPFFjZvJvejNcqPc,1635 +numpy/f2py/tests/test_size.py,sha256=q6YqQvcyqdXJeWbGijTiCbxyEG3EkPcvT8AlAW6RCMo,1164 +numpy/f2py/tests/test_string.py,sha256=5xZOfdReoHnId0950XfmtfduPPfBbtMkzBoXMtygvMk,2962 +numpy/f2py/tests/test_symbolic.py,sha256=28quk2kTKfWhKe56n4vINJ8G9weKBfc7HysMlE9J3_g,18341 +numpy/f2py/tests/test_value_attrspec.py,sha256=rWwJBfE2qGzqilZZurJ-7ucNoJDICye6lLetQSLFees,323 +numpy/f2py/tests/util.py,sha256=bEhG699c4bLVPR2WR8fV67avgX6kH5I74SicGb7Z7T4,11167 +numpy/f2py/use_rules.py,sha256=3pTDOPur6gbPHPtwuMJPQvpnUMw39Law1KFSH0coB_0,3527 +numpy/fft/__init__.py,sha256=HqjmF6s_dh0Ri4UZzUDtOKbNUyfAfJAWew3e3EL_KUk,8175 +numpy/fft/__init__.pyi,sha256=vD9Xzz5r13caF4AVL87Y4U9KOj9ic25Vci_wb3dmgpk,550 +numpy/fft/__pycache__/__init__.cpython-311.pyc,, +numpy/fft/__pycache__/_pocketfft.cpython-311.pyc,, +numpy/fft/__pycache__/helper.cpython-311.pyc,, +numpy/fft/_pocketfft.py,sha256=Xkm8wcP4JyBNMbp0ZoHIWhNDlgliX24RzrDuo29uRks,52897 +numpy/fft/_pocketfft.pyi,sha256=S6-ylUuHbgm8vNbh7tLru6K2R5SJzE81BC_Sllm6QrQ,2371 +numpy/fft/_pocketfft_internal.cpython-311-x86_64-linux-gnu.so,sha256=XzaFDzxI6s8RqdHjtZV6NrK33T630h9owQF8-rT9AAY,97008 +numpy/fft/helper.py,sha256=aNj1AcLvtfoX26RiLOwcR-k2QSMuBZkGj2Fu0CeFPJs,6154 +numpy/fft/helper.pyi,sha256=NLTEjy2Gz1aAMDZwCgssIyUne0ubjJqukfYkpsL3gXM,1176 +numpy/fft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/fft/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/fft/tests/__pycache__/test_helper.cpython-311.pyc,, +numpy/fft/tests/__pycache__/test_pocketfft.cpython-311.pyc,, +numpy/fft/tests/test_helper.py,sha256=whgeaQ8PzFf3B1wkbXobGZ5sF4WxPp4gf1UPUVZest8,6148 +numpy/fft/tests/test_pocketfft.py,sha256=RdeCCvUQmJYVvccOJwToobTKDg9yzUL06o9MkPmRfmI,12895 +numpy/lib/__init__.py,sha256=XMPNJkG_mQ__xuvbf0OcpotgMbA9owt10ZHYVnYHq8E,2713 +numpy/lib/__init__.pyi,sha256=y5ANokFm7EkrlNoHdeQm1FsUhLFxkYtLuanCbsWrGio,5596 +numpy/lib/__pycache__/__init__.cpython-311.pyc,, +numpy/lib/__pycache__/_datasource.cpython-311.pyc,, +numpy/lib/__pycache__/_iotools.cpython-311.pyc,, +numpy/lib/__pycache__/_version.cpython-311.pyc,, +numpy/lib/__pycache__/arraypad.cpython-311.pyc,, +numpy/lib/__pycache__/arraysetops.cpython-311.pyc,, +numpy/lib/__pycache__/arrayterator.cpython-311.pyc,, +numpy/lib/__pycache__/format.cpython-311.pyc,, +numpy/lib/__pycache__/function_base.cpython-311.pyc,, +numpy/lib/__pycache__/histograms.cpython-311.pyc,, +numpy/lib/__pycache__/index_tricks.cpython-311.pyc,, +numpy/lib/__pycache__/mixins.cpython-311.pyc,, +numpy/lib/__pycache__/nanfunctions.cpython-311.pyc,, +numpy/lib/__pycache__/npyio.cpython-311.pyc,, +numpy/lib/__pycache__/polynomial.cpython-311.pyc,, +numpy/lib/__pycache__/recfunctions.cpython-311.pyc,, +numpy/lib/__pycache__/scimath.cpython-311.pyc,, +numpy/lib/__pycache__/setup.cpython-311.pyc,, +numpy/lib/__pycache__/shape_base.cpython-311.pyc,, +numpy/lib/__pycache__/stride_tricks.cpython-311.pyc,, +numpy/lib/__pycache__/twodim_base.cpython-311.pyc,, +numpy/lib/__pycache__/type_check.cpython-311.pyc,, +numpy/lib/__pycache__/ufunclike.cpython-311.pyc,, +numpy/lib/__pycache__/user_array.cpython-311.pyc,, +numpy/lib/__pycache__/utils.cpython-311.pyc,, +numpy/lib/_datasource.py,sha256=CDF3im6IxdY3Mu6fwRQmkSEBmXS3kQVInQ4plXsoX9c,22631 +numpy/lib/_iotools.py,sha256=Yg9HCfPg4tbhbdgLPcxSMiZXq1xDprvJKLebLwhDszY,30868 +numpy/lib/_version.py,sha256=6vK7czNSB_KrWx2rZJzJ1pyOc73Q07hAgfLB5ItUCnU,4855 +numpy/lib/_version.pyi,sha256=B572hyWrUWG-TAAAXrNNAT4AgyUAmJ4lvgpwMkDzunk,633 +numpy/lib/arraypad.py,sha256=bKP7ZS9NYFYzqSk8OnpFLFrMsua4m_hcqFsi7cGkrJE,31803 +numpy/lib/arraypad.pyi,sha256=ADXphtAORYl3EqvE5qs_u32B_TALKSOtF43jOLmoxRw,1728 +numpy/lib/arraysetops.py,sha256=GJ2RhkzIJmIbwyG6h3LOFTPXg62kM9tcV1a-7tdbVuU,33655 +numpy/lib/arraysetops.pyi,sha256=6X-5l5Yss_9y10LYyIsDLbGX77vt7PtVLDqxOlSRPfY,8372 +numpy/lib/arrayterator.py,sha256=BQ97S00zvfURUZfes0GZo-5hydYNRuvwX1I1bLzeRik,7063 +numpy/lib/arrayterator.pyi,sha256=f7Pwp83_6DiMYmJGUsffncM-FRAynB1iYGvhmHM_SZE,1537 +numpy/lib/format.py,sha256=T8qJMyG2DDVjjYNNpUvBgfA9tCo23IS0w9byRB6twwQ,34769 +numpy/lib/format.pyi,sha256=YWBxC3GdsZ7SKBN8I7nMwWeVuFD1aT9d-VJ8zE4-P-o,748 +numpy/lib/function_base.py,sha256=IhhgfSmYJE-dHoUOMXHPiGYXso-NdXPpLXF9y0gEA6I,189172 +numpy/lib/function_base.pyi,sha256=KWaC5UOBANU4hiIoN2eptE4HYsm4vgp_8BMFV1Y3JX4,16585 +numpy/lib/histograms.py,sha256=xsj_qpaZoI2Bv1FBpY8mIMPJrYRiuIBszn_6kO7YFRA,37778 +numpy/lib/histograms.pyi,sha256=hNwR2xYWkgJCP-nfRGxc-EgHLTD3qm4zmWXthZLt08M,995 +numpy/lib/index_tricks.py,sha256=4PEvXk6VFTkttMViYBVC4yDhyOiKIon6JpIm0d_CmNg,31346 +numpy/lib/index_tricks.pyi,sha256=D2nkNXOB9Vea1PfMaTn94OGBGayjTaQ-bKMsjDmYpak,4251 +numpy/lib/mixins.py,sha256=y6_MzQuiNjv-1EFVROqv2y2cAJi5X4rQYzbZCyUyXgw,7071 +numpy/lib/mixins.pyi,sha256=h9N1kbZsUntF0zjOxPYeD_rCB2dMiG35TYYPl9ymkI4,3117 +numpy/lib/nanfunctions.py,sha256=6EjzydZlugIzfiENKtC4ycZ2Nckt8ZQg5v6D6tX1SiU,65775 +numpy/lib/nanfunctions.pyi,sha256=oPqAfCinmBL85Ji7ko4QlzAzLAK9nZL0t2_CllEbCEU,606 +numpy/lib/npyio.py,sha256=NUjtFvAmPdTjwJQ-ia-xbCr849M_M6NilP5IHfkKaRg,97316 +numpy/lib/npyio.pyi,sha256=SUFWJh90vWZCdd6GCSGbfYeXKlWut0XY_SHvZJc8yqY,9728 +numpy/lib/polynomial.py,sha256=6Aw3_2vdbh4urERQ6NaPhf9a_T1o1o6cjm3fb5Z3_YE,44133 +numpy/lib/polynomial.pyi,sha256=GerIpQnf5LdtFMOy9AxhOTqUyfn57k4MxqEYrfdckWE,6958 +numpy/lib/recfunctions.py,sha256=-90AbWWvVFOqVUPLh9K9NYdKUHYIgSEyg2Y35MnOVUA,59423 +numpy/lib/scimath.py,sha256=T4ITysZgqhY1J8IxyXCtioHjMTg2ci-4i3mr9TBF2UA,15037 +numpy/lib/scimath.pyi,sha256=E2roKJzMFwWSyhLu8UPUr54WOpxF8jp_pyXYBgsUSQ8,2883 +numpy/lib/setup.py,sha256=0K5NJKuvKvNEWp-EX7j0ODi3ZQQgIMHobzSFJq3G7yM,405 +numpy/lib/shape_base.py,sha256=AhCO9DEyysE-P-QJF9ryUtJ1ghU4_0mORhAJ59poObU,38947 +numpy/lib/shape_base.pyi,sha256=bGJhLA_RvUpVTiDFgCV-1rUjV8e1qCh0gK_3PLgXA_U,5341 +numpy/lib/stride_tricks.py,sha256=brY5b-0YQJuIH2CavfpIinMolyTUv5k9DUvLoZ-imis,17911 +numpy/lib/stride_tricks.pyi,sha256=0pQ4DP9l6g21q2Ajv6dJFRWMr9auPGTNV9BmZUbogPY,1747 +numpy/lib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/lib/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test__datasource.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test__iotools.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test__version.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_arraypad.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_arraysetops.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_arrayterator.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_financial_expired.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_format.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_function_base.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_histograms.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_index_tricks.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_io.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_loadtxt.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_mixins.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_nanfunctions.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_packbits.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_polynomial.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_recfunctions.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_shape_base.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_stride_tricks.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_twodim_base.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_type_check.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_ufunclike.cpython-311.pyc,, +numpy/lib/tests/__pycache__/test_utils.cpython-311.pyc,, +numpy/lib/tests/data/py2-objarr.npy,sha256=F4cyUC-_TB9QSFLAo2c7c44rC6NUYIgrfGx9PqWPSKk,258 +numpy/lib/tests/data/py2-objarr.npz,sha256=xo13HBT0FbFZ2qvZz0LWGDb3SuQASSaXh7rKfVcJjx4,366 +numpy/lib/tests/data/py3-objarr.npy,sha256=pTTVh8ezp-lwAK3fkgvdKU8Arp5NMKznVD-M6Ex_uA0,341 +numpy/lib/tests/data/py3-objarr.npz,sha256=qQR0gS57e9ta16d_vCQjaaKM74gPdlwCPkp55P-qrdw,449 +numpy/lib/tests/data/python3.npy,sha256=X0ad3hAaLGXig9LtSHAo-BgOvLlFfPYMnZuVIxRmj-0,96 +numpy/lib/tests/data/win64python2.npy,sha256=agOcgHVYFJrV-nrRJDbGnUnF4ZTPYXuSeF-Mtg7GMpc,96 +numpy/lib/tests/test__datasource.py,sha256=65KXfUUvp8wXSqgQisuYlkhg-qHjBV5FXYetL8Ba-rc,10571 +numpy/lib/tests/test__iotools.py,sha256=HerCqvDE07JxjFQlWEfpZO7lC9z0Sbr3z20GSutoCPs,13743 +numpy/lib/tests/test__version.py,sha256=aO3YgkAohLsLzCNQ7vjIwdpFUMz0cPLbcuuxIkjuN74,1999 +numpy/lib/tests/test_arraypad.py,sha256=obohHbyM0gPYPUkd7iJSOSiDqyqtJsjDNtQX68NC4lM,54830 +numpy/lib/tests/test_arraysetops.py,sha256=5-T1MVhfIMivat8Z47GZw0ZaR811W_FskM1bAXnFyLU,35912 +numpy/lib/tests/test_arrayterator.py,sha256=AYs2SwV5ankgwnvKI9RSO1jZck118nu3SyZ4ngzZNso,1291 +numpy/lib/tests/test_financial_expired.py,sha256=yq5mqGMvqpkiiw9CuZhJgrYa7Squj1mXr_G-IvAFgwI,247 +numpy/lib/tests/test_format.py,sha256=xV0oi1eoRnVwAAhSOcPFQHQWF7TfsROtDYShQLPtdaA,41028 +numpy/lib/tests/test_function_base.py,sha256=DBKugIUEFTMP7g6iL1bk986E6ldCrcNdBCWOJbQla_Y,157830 +numpy/lib/tests/test_histograms.py,sha256=16_XJp-eFgsuM8B4mDQpQ4w_Ib29Hg0EPO-WFsdaFWA,32815 +numpy/lib/tests/test_index_tricks.py,sha256=Vjz25Y6H_ih0iEE2AG0kaxO9U8PwcXSrofzqnN4XBwI,20256 +numpy/lib/tests/test_io.py,sha256=3Tow1pucrQ7z7osNN4a2grBYUoBGNkQEhjmCjXT6Vag,107891 +numpy/lib/tests/test_loadtxt.py,sha256=gwcDJDJmLJRMLpg322yjQ1IzI505w9EqJoq4DmDPCdI,38560 +numpy/lib/tests/test_mixins.py,sha256=Wivwz3XBWsEozGzrzsyyvL3qAuE14t1BHk2LPm9Z9Zc,7030 +numpy/lib/tests/test_nanfunctions.py,sha256=01r_mmTCvKVdZuOGTEHNDZXrMS724us_jwZANzCd74A,47609 +numpy/lib/tests/test_packbits.py,sha256=OWGAd5g5GG0gl7WHqNfwkZ7G-2rrtLt2sI854PG4nnw,17546 +numpy/lib/tests/test_polynomial.py,sha256=URouxJpr8FQ5hiKybqhtOcLA7e-3hj4kWzjLBROByyA,11395 +numpy/lib/tests/test_recfunctions.py,sha256=6jzouPEQ7Uhtj8_-W5yTI6ymNp2nLgmdHzxdd74jVuM,44001 +numpy/lib/tests/test_regression.py,sha256=KzGFkhTcvEG97mymoOQ2hP2CEr2nPZou0Ztf4-WaXCs,8257 +numpy/lib/tests/test_shape_base.py,sha256=2iQCEFR6evVpF8woaenxUOzooHkfuMYkBaUj8ecyJ-E,26817 +numpy/lib/tests/test_stride_tricks.py,sha256=wprpWWH5eq07DY7rzG0WDv5fMtLxzRQz6fm6TZWlScQ,22849 +numpy/lib/tests/test_twodim_base.py,sha256=ll-72RhqCItIPB97nOWhH7H292h4nVIX_w1toKTPMUg,18841 +numpy/lib/tests/test_type_check.py,sha256=lxCH5aApWVYhhSoDQSLDTCHLVHuK2c-jBbnfnZUrOaA,15114 +numpy/lib/tests/test_ufunclike.py,sha256=4hSnXGlSC8HE-_pRRMzD8-HI4hGHqsAWu1pD0o2kPI0,2982 +numpy/lib/tests/test_utils.py,sha256=RVAxrzSFu6N3C4_jIgAlTDOWF_B7wr2v1Y20dX5upYM,6218 +numpy/lib/twodim_base.py,sha256=Mvzn_PyShIb9m7nJjJ4IetdxwmLYEsCPHvJoK7n2viU,32947 +numpy/lib/twodim_base.pyi,sha256=xFRcEVJdDj4mrXW_6iVP1lTMoJx4QJjYRD3o2_9f2eY,5370 +numpy/lib/type_check.py,sha256=_EOtB296nFYlNT7ztBYoC_yK9aycIb0KTmRjvzVdZNg,19954 +numpy/lib/type_check.pyi,sha256=LPvAvIxU-p5i_Qe-ic7hEvo4OTfSrNpplxMG7OAZe8Q,5571 +numpy/lib/ufunclike.py,sha256=_ceBGbGCMOd3u_h2UVzyaRK6ZY7ryoJ0GJB7zqcJG3w,6325 +numpy/lib/ufunclike.pyi,sha256=hLxcYfQprh1tTY_UO2QscA3Hd9Zd7cVGXIINZLhMFqY,1293 +numpy/lib/user_array.py,sha256=LE958--CMkBI2r3l1SQxmCHdCSw6HY6-RhWCnduzGA4,7721 +numpy/lib/utils.py,sha256=6NdleaELZiqARdj-ECZjxtwLf1bqklOcK43m9yoZefs,37804 +numpy/lib/utils.pyi,sha256=mVHVzWuc2-M3Oz60lFsbok0v8LH_HRHMjZpXwrtzF_c,2360 +numpy/linalg/__init__.py,sha256=mpdlEXWtTvpF7In776ONLwp6RIyo4U_GLPT1L1eIJnw,1813 +numpy/linalg/__init__.pyi,sha256=XBy4ocuypsRVflw_mbSTUhR4N5Roemu6w5SfeVwbkAc,620 +numpy/linalg/__pycache__/__init__.cpython-311.pyc,, +numpy/linalg/__pycache__/linalg.cpython-311.pyc,, +numpy/linalg/_umath_linalg.cpython-311-x86_64-linux-gnu.so,sha256=BYffhO2XUQkIZ6ShRB0sOUw5c1QgqjiLi_aYtyVfJL0,216793 +numpy/linalg/lapack_lite.cpython-311-x86_64-linux-gnu.so,sha256=zWHsImcTCxEkZbyF2rgrclRTDzz5E7poiDOwhOKaVRs,29849 +numpy/linalg/linalg.py,sha256=kDVK1GBxbUjlRgxXCoEfkRJm8yrNr1Iu7hMn2rKK8RE,90923 +numpy/linalg/linalg.pyi,sha256=zD9U5BUCB1uQggSxfZaTGX_uB2Hkp75sttGmZbCGgBI,7505 +numpy/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/linalg/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/linalg/tests/__pycache__/test_deprecations.cpython-311.pyc,, +numpy/linalg/tests/__pycache__/test_linalg.cpython-311.pyc,, +numpy/linalg/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/linalg/tests/test_deprecations.py,sha256=9p_SRmtxj2zc1doY9Ie3dyy5JzWy-tCQWFoajcAJUmM,640 +numpy/linalg/tests/test_linalg.py,sha256=rgvmK6Or70u8mN04puetL3FgSxZ8fJrOlI5ptTgCU5k,78085 +numpy/linalg/tests/test_regression.py,sha256=qbugUmrENybkEaM1GhfA01RXQUy8AkzalbrfzSIgUmM,5434 +numpy/ma/API_CHANGES.txt,sha256=F_4jW8X5cYBbzpcwteymkonTmvzgKKY2kGrHF1AtnrI,3405 +numpy/ma/LICENSE,sha256=BfO4g1GYjs-tEKvpLAxQ5YdcZFLVAJoAhMwpFVH_zKY,1593 +numpy/ma/README.rst,sha256=q-gCsZ4Cw_gUGGvEjog556sJUHIm8WTAwkFK5Qnz9XA,9872 +numpy/ma/__init__.py,sha256=dgP0WdnOpph28Fd6UiqoyDKhfrct0H6QWqbCcETsk6M,1404 +numpy/ma/__init__.pyi,sha256=ppCg_TS0POutNB3moJE4kBabWURnc0WGXyYPquXZxS4,6063 +numpy/ma/__pycache__/__init__.cpython-311.pyc,, +numpy/ma/__pycache__/core.cpython-311.pyc,, +numpy/ma/__pycache__/extras.cpython-311.pyc,, +numpy/ma/__pycache__/mrecords.cpython-311.pyc,, +numpy/ma/__pycache__/setup.cpython-311.pyc,, +numpy/ma/__pycache__/testutils.cpython-311.pyc,, +numpy/ma/__pycache__/timer_comparison.cpython-311.pyc,, +numpy/ma/core.py,sha256=4MglVRJtmQ9_iIVaQ2b-_Vmw1TjAhEsMJdtKOhyBFXQ,278213 +numpy/ma/core.pyi,sha256=YfgyuBuKxZ5v4I2JxZDvCLhnztOCRgzTeDg-JGTon_M,14305 +numpy/ma/extras.py,sha256=MC7QPS34PC4wxNbOp7pTy57dqF9B-L6L1KMI6rrfe2w,64383 +numpy/ma/extras.pyi,sha256=BBsiCZbaPpGCY506fkmqZdBkJNCXcglc3wcSBuAACNk,2646 +numpy/ma/mrecords.py,sha256=degd6dLaDEvEWNHmvSnUZXos1csIzaqjR_jAutm8JfI,27232 +numpy/ma/mrecords.pyi,sha256=r1a2I662ywnhGS6zvfcyK-9RHVvb4sHxiCx9Dhf5AE4,1934 +numpy/ma/setup.py,sha256=MqmMicr_xHkAGoG-T7NJ4YdUZIJLO4ZFp6AmEJDlyhw,418 +numpy/ma/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/ma/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_core.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_deprecations.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_extras.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_mrecords.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_old_ma.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/ma/tests/__pycache__/test_subclassing.cpython-311.pyc,, +numpy/ma/tests/test_core.py,sha256=xd5S3oa0jObo8jnsJk0-o46d-KNC3RtgNRKinJeY_kE,215100 +numpy/ma/tests/test_deprecations.py,sha256=nq_wFVt2EBHcT3AHxattfKXx2JDf1K5D-QBzUU0_15A,2566 +numpy/ma/tests/test_extras.py,sha256=lX4cbdGDEXaBHzA3q8hJxve4635XCJw4AP7FO7zhOfk,74858 +numpy/ma/tests/test_mrecords.py,sha256=PsJhUlABgdpSsPUeijonfyFNqz5AfNSGQTtJUte7yts,19890 +numpy/ma/tests/test_old_ma.py,sha256=h4BncexBcBigqvZMA6RjDjpHPurWtt99A7KTag2rmOs,32690 +numpy/ma/tests/test_regression.py,sha256=foMpI0luAvwkkRpAfPDV_810h1URISXDZhmaNhxb50k,3287 +numpy/ma/tests/test_subclassing.py,sha256=HeTIE_n1I8atwzF8tpvNtGHp-0dmM8PT8AS4IDWbcso,16967 +numpy/ma/testutils.py,sha256=RQw0RyS7hOSVTk4KrCGleq0VHlnDqzwwaLtuZbRE4_I,10235 +numpy/ma/timer_comparison.py,sha256=pIGSZG-qYYYlRWSTgzPlyCAINbGKhXrZrDZBBjiM080,15658 +numpy/matlib.py,sha256=-54vTuGIgeTMg9ZUmElRPZ4Hr-XZ-om9xLzAsSoTvnc,10465 +numpy/matrixlib/__init__.py,sha256=BHBpQKoQv4EjT0UpWBA-Ck4L5OsMqTI2IuY24p-ucXk,242 +numpy/matrixlib/__init__.pyi,sha256=-t3ZuvbzRuRwWfZOeN4xlNWdm7gQEprhUsWzu8MRvUE,252 +numpy/matrixlib/__pycache__/__init__.cpython-311.pyc,, +numpy/matrixlib/__pycache__/defmatrix.cpython-311.pyc,, +numpy/matrixlib/__pycache__/setup.cpython-311.pyc,, +numpy/matrixlib/defmatrix.py,sha256=JXdJGm1LayOOXfKpp7OVZfb0pzzP4Lwh45sTJrleALc,30656 +numpy/matrixlib/defmatrix.pyi,sha256=lmBMRahKcMOl2PHDo79J67VRAZOkI54BzfDaTLpE0LI,451 +numpy/matrixlib/setup.py,sha256=1r7JRkSM4HyVorgtjoKJGWLcOcPO3wmvivpeEsVtAEg,426 +numpy/matrixlib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/matrixlib/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_interaction.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_numeric.cpython-311.pyc,, +numpy/matrixlib/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/matrixlib/tests/test_defmatrix.py,sha256=8E_-y7VD2vsq1y8CcI8km37pp5qcAtkciO16xqf2UIs,14982 +numpy/matrixlib/tests/test_interaction.py,sha256=PpjmgjEKighDXvt38labKE6L7f2jP74UEmp3JRb_iOY,11875 +numpy/matrixlib/tests/test_masked_matrix.py,sha256=7YO_LCO8DOhW3CuXJuxH93rnmttfvHnU7El-MBzxzFw,8932 +numpy/matrixlib/tests/test_matrix_linalg.py,sha256=ObbSUXU4R2pWajH__xAdizADrU2kBKDDCxkDV-oVBXc,2059 +numpy/matrixlib/tests/test_multiarray.py,sha256=jB3XCBmAtcqf-Wb9PwBW6uIykPpMPthuXLJ0giTKzZE,554 +numpy/matrixlib/tests/test_numeric.py,sha256=MP70qUwgshTtThKZaZDp7_6U-Z66NIV1geVhasGXejQ,441 +numpy/matrixlib/tests/test_regression.py,sha256=8sHDtO8Zi8p3a1eQKEWxtCmKrXmHoD3qxlIokg2AIAU,927 +numpy/polynomial/__init__.py,sha256=braLh6zP2QwuNKRKAaZGdC_qKWZ-tJlc3BN83LeuE_0,6781 +numpy/polynomial/__init__.pyi,sha256=W8szYtVUy0RUi83jmFLK58BN8CKVSoHA2CW7IcdUl1c,701 +numpy/polynomial/__pycache__/__init__.cpython-311.pyc,, +numpy/polynomial/__pycache__/_polybase.cpython-311.pyc,, +numpy/polynomial/__pycache__/chebyshev.cpython-311.pyc,, +numpy/polynomial/__pycache__/hermite.cpython-311.pyc,, +numpy/polynomial/__pycache__/hermite_e.cpython-311.pyc,, +numpy/polynomial/__pycache__/laguerre.cpython-311.pyc,, +numpy/polynomial/__pycache__/legendre.cpython-311.pyc,, +numpy/polynomial/__pycache__/polynomial.cpython-311.pyc,, +numpy/polynomial/__pycache__/polyutils.cpython-311.pyc,, +numpy/polynomial/__pycache__/setup.cpython-311.pyc,, +numpy/polynomial/_polybase.py,sha256=YEnnQwlTgbn3dyD89ueraUx5nxx3x_pH6K6mmyEmhi8,39271 +numpy/polynomial/_polybase.pyi,sha256=J7yU9PPZW4W8mkqAltDfnL4ZNwljuM-bDEj4DPTJZpY,2321 +numpy/polynomial/chebyshev.py,sha256=NZCKjIblcX99foqZyp51i0_r8p0r1VKVGZFmQ1__kEk,62796 +numpy/polynomial/chebyshev.pyi,sha256=035CNdOas4dnb6lFLzRiBrYT_VnWh2T1-A3ibm_HYkI,1387 +numpy/polynomial/hermite.py,sha256=t5CFM-qE4tszYJiQZ301VcMn7IM67y2rUZPFPtnVRAc,52514 +numpy/polynomial/hermite.pyi,sha256=hdsvTULow8bIjnATudf0i6brpLHV7vbOoHzaMvbjMy0,1217 +numpy/polynomial/hermite_e.py,sha256=jRR3f8Oth8poV2Ix8c0eLEQR3UZary-2RupOrEAEUMY,52642 +numpy/polynomial/hermite_e.pyi,sha256=zV7msb9v9rV0iv_rnD3SjP-TGyc6pd3maCqiPCj3PbA,1238 +numpy/polynomial/laguerre.py,sha256=mcVw0ckWVX-kzJ1QIhdcuuxzPjuFmA3plQLkloQMOYM,50858 +numpy/polynomial/laguerre.pyi,sha256=Gxc9SLISNKMWrKdsVJ9fKFFFwfxxZzfF-Yc-2r__z5M,1178 +numpy/polynomial/legendre.py,sha256=wjtgFajmKEbYkSUk3vWSCveMHDP6UymK28bNUk4Ov0s,51550 +numpy/polynomial/legendre.pyi,sha256=9dmANwkxf7EbOHV3XQBPoaDtc56cCkf75Wo7FG9Zfj4,1178 +numpy/polynomial/polynomial.py,sha256=XsaZPHmLGJFqpJs7rPvO5E0loWQ1L3YHLIUybVu4dU8,49112 +numpy/polynomial/polynomial.pyi,sha256=bOPRnub4xXxsUwNGeiQLTT4PCfN1ysSrf6LBZIcAN2Y,1132 +numpy/polynomial/polyutils.py,sha256=Xy5qjdrjnRaqSlClG1ROmwWccLkAPC7IcHaNJLvhCf4,23237 +numpy/polynomial/polyutils.pyi,sha256=cFAyZ9Xzuw8Huhn9FEz4bhyD00m2Dp-2DiUSyogJwSo,264 +numpy/polynomial/setup.py,sha256=dXQfzVUMP9OcB6iKv5yo1GLEwFB3gJ48phIgo4N-eM0,373 +numpy/polynomial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/polynomial/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_chebyshev.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_classes.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite_e.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_laguerre.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_legendre.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_polynomial.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_polyutils.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_printing.cpython-311.pyc,, +numpy/polynomial/tests/__pycache__/test_symbol.cpython-311.pyc,, +numpy/polynomial/tests/test_chebyshev.py,sha256=6tMsFP1h7K8Zf72mNOta6Tv52_fVTlXknseuffj080c,20522 +numpy/polynomial/tests/test_classes.py,sha256=DFyY2IQBj3r2GZkvbRIeZO2EEY466xbuwc4PShAl4Sw,18331 +numpy/polynomial/tests/test_hermite.py,sha256=N9b2dx2UWPyja5v02dSoWYPnKvb6H-Ozgtrx-xjWz2k,18577 +numpy/polynomial/tests/test_hermite_e.py,sha256=_A3ohAWS4HXrQG06S8L47dImdZGTwYosCXnoyw7L45o,18911 +numpy/polynomial/tests/test_laguerre.py,sha256=BZOgs49VBXOFBepHopxuEDkIROHEvFBfWe4X73UZhn8,17511 +numpy/polynomial/tests/test_legendre.py,sha256=b_bblHs0F_BWw9ESuSq52ZsLKcQKFR5eqPf_SppWFqo,18673 +numpy/polynomial/tests/test_polynomial.py,sha256=4cuO8-5wdIxcz5CrucB5Ix7ySuMROokUF12F7ogQ_hc,20529 +numpy/polynomial/tests/test_polyutils.py,sha256=IxkbVfpcBqe5lOZluHFUPbLATLu1rwVg7ghLASpfYrY,3579 +numpy/polynomial/tests/test_printing.py,sha256=rfP4MaQbjGcO52faHmYrgsaarkm3Ndi3onwr6DDuapE,20525 +numpy/polynomial/tests/test_symbol.py,sha256=msTPv7B1niaKujU33kuZmdxJvLYvOjfl1oykmlL0dXo,5371 +numpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/LICENSE.md,sha256=EDFmtiuARDr7nrNIjgUuoGvgz_VmuQjxmeVh_eSa8Z8,3511 +numpy/random/__init__.pxd,sha256=9JbnX540aJNSothGs-7e23ozhilG6U8tINOUEp08M_k,431 +numpy/random/__init__.py,sha256=81Thnexg5umN5WZwD5TRyzNc2Yp-d14B6UC7NBgVKh8,7506 +numpy/random/__init__.pyi,sha256=RfW8mco48UaWDL1UC5ROv9vXiFZ9EGho62avhgEAHPc,2143 +numpy/random/__pycache__/__init__.cpython-311.pyc,, +numpy/random/__pycache__/_pickle.cpython-311.pyc,, +numpy/random/_bounded_integers.cpython-311-x86_64-linux-gnu.so,sha256=8cRHM_FvexvjO6DIiKKiojEHjPZQ9APE9u4goSnCrdU,379288 +numpy/random/_bounded_integers.pxd,sha256=hcoucPH5hkFEM2nm12zYO-5O_Rt8RujEXT5YWuAzl1Q,1669 +numpy/random/_common.cpython-311-x86_64-linux-gnu.so,sha256=6tzubSzf184pTLaVVMQQ2NyddFf2uoYr9OnV1_KFH5w,272272 +numpy/random/_common.pxd,sha256=s2_IdIQ0MhNbogamulvXe-b93wbx882onmYkxqswwpo,4939 +numpy/random/_examples/cffi/__pycache__/extending.cpython-311.pyc,, +numpy/random/_examples/cffi/__pycache__/parse.cpython-311.pyc,, +numpy/random/_examples/cffi/extending.py,sha256=xSla3zWqxi6Hj48EvnYfD3WHfE189VvC4XsKu4_T_Iw,880 +numpy/random/_examples/cffi/parse.py,sha256=Bnb7t_6S_c5-3dZrQ-XX9EazOKhftUfcCejXXWyd1EU,1771 +numpy/random/_examples/cython/extending.pyx,sha256=4IE692pq1V53UhPZqQiQGcIHXDoNyqTx62x5a36puVg,2290 +numpy/random/_examples/cython/extending_distributions.pyx,sha256=oazFVWeemfE0eDzax7r7MMHNL1_Yofws2m-c_KT2Hbo,3870 +numpy/random/_examples/cython/meson.build,sha256=rXtugURMEo-ef4bPE1QIv4mzvWbeGjmcTdKCBvjxjtw,1443 +numpy/random/_examples/numba/__pycache__/extending.cpython-311.pyc,, +numpy/random/_examples/numba/__pycache__/extending_distributions.cpython-311.pyc,, +numpy/random/_examples/numba/extending.py,sha256=Ipyzel_h5iU_DMJ_vnXUgQC38uMDMn7adUpWSeEQLFE,1957 +numpy/random/_examples/numba/extending_distributions.py,sha256=Jnr9aWkHyIWygNbdae32GVURK-5T9BTGhuExRpvve98,2034 +numpy/random/_generator.cpython-311-x86_64-linux-gnu.so,sha256=jCP45If0dBhfEfKPx7jrLrvGBxL2jD61888BTyx-xGw,980520 +numpy/random/_generator.pyi,sha256=zRvo_y6g0pWkE4fO1M9jLYUkxDfGdA6Enreb3U2AADM,22442 +numpy/random/_mt19937.cpython-311-x86_64-linux-gnu.so,sha256=05sOWp6QYT3u3ll4V_ir7CnPsszMr_btbxHLwQ9oSoI,120312 +numpy/random/_mt19937.pyi,sha256=_iZKaAmuKBQ4itSggfQvYYj_KjktcN4rt-YpE6bqFAM,724 +numpy/random/_pcg64.cpython-311-x86_64-linux-gnu.so,sha256=xhelp-wYLQTjwrr5PlBXBa8yrEENDzMshXU21HPDJ5M,126448 +numpy/random/_pcg64.pyi,sha256=uxr5CbEJetN6lv9vBG21jlRhuzOK8SQnXrwqAQBxj_c,1091 +numpy/random/_philox.cpython-311-x86_64-linux-gnu.so,sha256=CwCXKEDF6zwNqsN_w1xmsWVz7jGlwFkM8vkosCXNapI,107480 +numpy/random/_philox.pyi,sha256=OKlaiIU-hj72Bp04zjNifwusOD_3-mYxIfvyuys8c_o,978 +numpy/random/_pickle.py,sha256=4NhdT-yk7C0m3tyZWmouYAs3ZGNPdPVNGfUIyuh8HDY,2318 +numpy/random/_sfc64.cpython-311-x86_64-linux-gnu.so,sha256=I7xfexABps5usg_K0NaIhdnaP6bShX6xXDfrbpx3lDE,76760 +numpy/random/_sfc64.pyi,sha256=09afHTedVW-519493ZXtGcl-H-_zluj-B_yfEJG8MMs,709 +numpy/random/bit_generator.cpython-311-x86_64-linux-gnu.so,sha256=tEmMEHOT1xAnuIuBUFunsAWRsQhdq4bwgmLKZ1QHqZA,242584 +numpy/random/bit_generator.pxd,sha256=lArpIXSgTwVnJMYc4XX0NGxegXq3h_QsUDK6qeZKbNc,1007 +numpy/random/bit_generator.pyi,sha256=aXv7a_hwa0nkjY8P2YENslwWp89UcFRn09woXh7Uoc0,3510 +numpy/random/c_distributions.pxd,sha256=7DE-mV3H_Dihk4OK4gMHHkyD4tPX1cAi4570zi5CI30,6344 +numpy/random/lib/libnpyrandom.a,sha256=xUcvOvieju5PThPQ8q0-uGJ5fjsCd5umnjIerIc85Sg,71926 +numpy/random/mtrand.cpython-311-x86_64-linux-gnu.so,sha256=LvmGvpTMXtGsrYdNMj-GSpwPiKDE3SsXHa-1EsCspJY,783904 +numpy/random/mtrand.pyi,sha256=3vAGOXsvyFFv0yZl34pVVPP7Dgt22COyfn4tUoi_hEQ,19753 +numpy/random/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_direct.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_extending.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937_regressions.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_random.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_randomstate.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_randomstate_regression.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_regression.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_seed_sequence.cpython-311.pyc,, +numpy/random/tests/__pycache__/test_smoke.cpython-311.pyc,, +numpy/random/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/data/__pycache__/__init__.cpython-311.pyc,, +numpy/random/tests/data/mt19937-testset-1.csv,sha256=Xkef402AVB-eZgYQkVtoxERHkxffCA9Jyt_oMbtJGwY,15844 +numpy/random/tests/data/mt19937-testset-2.csv,sha256=nsBEQNnff-aFjHYK4thjvUK4xSXDSfv5aTbcE59pOkE,15825 +numpy/random/tests/data/pcg64-testset-1.csv,sha256=xB00DpknGUTTCxDr9L6aNo9Hs-sfzEMbUSS4t11TTfE,23839 +numpy/random/tests/data/pcg64-testset-2.csv,sha256=NTdzTKvG2U7_WyU_IoQUtMzU3kEvDH39CgnR6VzhTkw,23845 +numpy/random/tests/data/pcg64dxsm-testset-1.csv,sha256=vNSUT-gXS_oEw_awR3O30ziVO4seNPUv1UIZ01SfVnI,23833 +numpy/random/tests/data/pcg64dxsm-testset-2.csv,sha256=uylS8PU2AIKZ185OC04RBr_OePweGRtvn-dE4YN0yYA,23839 +numpy/random/tests/data/philox-testset-1.csv,sha256=SedRaIy5zFadmk71nKrGxCFZ6BwKz8g1A9-OZp3IkkY,23852 +numpy/random/tests/data/philox-testset-2.csv,sha256=dWECt-sbfvaSiK8-Ygp5AqyjoN5i26VEOrXqg01rk3g,23838 +numpy/random/tests/data/sfc64-testset-1.csv,sha256=iHs6iX6KR8bxGwKk-3tedAdMPz6ZW8slDSUECkAqC8Q,23840 +numpy/random/tests/data/sfc64-testset-2.csv,sha256=FIDIDFCaPZfWUSxsJMAe58hPNmMrU27kCd9FhCEYt_k,23833 +numpy/random/tests/test_direct.py,sha256=6vLpCyeKnAWFEZei7l2YihVLQ0rSewO1hJBWt7A5fyQ,17779 +numpy/random/tests/test_extending.py,sha256=S3Wrzu3di4uBhr-Pxnx5dOPvlBY0FRdZqVX6CC1IN6s,4038 +numpy/random/tests/test_generator_mt19937.py,sha256=35LBwV6TtWPnxhefutxTQmhLzAQ5Ee4YiY8ziDXM-eQ,115477 +numpy/random/tests/test_generator_mt19937_regressions.py,sha256=xGkdz76BMX1EK0QPfabVxpNx9qQ9OC-1ZStWOs6N_M8,6387 +numpy/random/tests/test_random.py,sha256=kEkQs3i7zcpm9MozIRIz1FIx5B6fmXk0QqX0l6l-u_Y,70087 +numpy/random/tests/test_randomstate.py,sha256=DxF7rMUSxaAlL4h1qC3onHcHR7T_6rKWPbr0nJH84nE,85031 +numpy/random/tests/test_randomstate_regression.py,sha256=VucYWIjA7sAquWsalvZMnfkmYLM1O6ysyWnLl931-lA,7917 +numpy/random/tests/test_regression.py,sha256=trntK51UvajOVELiluEO85l64CKSw5nvBSc5SqYyr9w,5439 +numpy/random/tests/test_seed_sequence.py,sha256=GNRJ4jyzrtfolOND3gUWamnbvK6-b_p1bBK_RIG0sfU,3311 +numpy/random/tests/test_smoke.py,sha256=jjNz0aEGD1_oQl9a9UWt6Mz_298alG7KryLT1pgHljw,28183 +numpy/testing/__init__.py,sha256=InpVKoDAzMKO_l_HNcatziW_u1k9_JZze__t2nybrL0,595 +numpy/testing/__init__.pyi,sha256=AhK5NuOpdD-JjIzXOlssE8_iSLyFAAHzyGV_w1BT7vA,1674 +numpy/testing/__pycache__/__init__.cpython-311.pyc,, +numpy/testing/__pycache__/overrides.cpython-311.pyc,, +numpy/testing/__pycache__/print_coercion_tables.cpython-311.pyc,, +numpy/testing/__pycache__/setup.cpython-311.pyc,, +numpy/testing/_private/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/__pycache__/__init__.cpython-311.pyc,, +numpy/testing/_private/__pycache__/extbuild.cpython-311.pyc,, +numpy/testing/_private/__pycache__/utils.cpython-311.pyc,, +numpy/testing/_private/extbuild.py,sha256=nG2dwP4nUmQS3e5eIRinxt0s_f4sxxA1YfohCg-navo,8017 +numpy/testing/_private/utils.py,sha256=3FrSTMi0OdpDODBDoncgiDQzdo5NKA6YVfQ3uKRSQnc,85242 +numpy/testing/_private/utils.pyi,sha256=MMNrvwEeSTYzZFWawSSzHnTFYG-cSAIiID-1FuJ1f8U,10123 +numpy/testing/overrides.py,sha256=u6fcKSBC8HIzMPWKAbdyowU71h2Fx2ekDQxpG5NhIr8,2123 +numpy/testing/print_coercion_tables.py,sha256=ndxOsS4XfrZ4UY_9nqRTCnxhkzgdqcuUHL8nezd7Op4,6180 +numpy/testing/setup.py,sha256=GPKAtTTBRsNW4kmR7NjP6mmBR_GTdpaTvkTm10_VcLg,709 +numpy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/testing/tests/__pycache__/test_utils.cpython-311.pyc,, +numpy/testing/tests/test_utils.py,sha256=IDOr-GXuNGlrsb-XzGSYUHXEqcGYJ78p60jOpBqyPM4,55740 +numpy/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/tests/__pycache__/test__all__.cpython-311.pyc,, +numpy/tests/__pycache__/test_ctypeslib.cpython-311.pyc,, +numpy/tests/__pycache__/test_lazyloading.cpython-311.pyc,, +numpy/tests/__pycache__/test_matlib.cpython-311.pyc,, +numpy/tests/__pycache__/test_numpy_config.cpython-311.pyc,, +numpy/tests/__pycache__/test_numpy_version.cpython-311.pyc,, +numpy/tests/__pycache__/test_public_api.cpython-311.pyc,, +numpy/tests/__pycache__/test_reloading.cpython-311.pyc,, +numpy/tests/__pycache__/test_scripts.cpython-311.pyc,, +numpy/tests/__pycache__/test_warnings.cpython-311.pyc,, +numpy/tests/test__all__.py,sha256=L3mCnYPTpzAgNfedVuq9g7xPWbc0c1Pot94k9jZ9NpI,221 +numpy/tests/test_ctypeslib.py,sha256=B06QKeFRgDIEbkEPBy_zYA1H5E2exuhTi7IDkzV8gfo,12257 +numpy/tests/test_lazyloading.py,sha256=YETrYiDLAqLX04K_u5_3NVxAfxDoeguxwkIRfz6qKcY,1162 +numpy/tests/test_matlib.py,sha256=gwhIXrJJo9DiecaGLCHLJBjhx2nVGl6yHq80AOUQSRM,1852 +numpy/tests/test_numpy_config.py,sha256=qHvepgi9oyAbQuZD06k7hpcCC2MYhdzcY6D1iQDPNMI,1241 +numpy/tests/test_numpy_version.py,sha256=A8cXFzp4k-p6J5zkOxlDfDvkoFMxDW2hpTFVXcaQRVo,1479 +numpy/tests/test_public_api.py,sha256=DTq7SO84uBjC2tKPoqX17xazc-SLkTAbQ2fLZwGM2jc,18170 +numpy/tests/test_reloading.py,sha256=QuVaPQulcNLg4Fl31Lw-O89L42KclYCK68n5GVy0PNQ,2354 +numpy/tests/test_scripts.py,sha256=jluCLfG94VM1cuX-5RcLFBli_yaJZpIvmVuMxRKRJrc,1645 +numpy/tests/test_warnings.py,sha256=ZEtXqHI1iyeVeLfVxDcMfN5qw67Ti2u54709hvBG4eY,2284 +numpy/typing/__init__.py,sha256=VoTILNDrUWvZx0LK9_97lBLQFKtSGmDt4QLOH8zYvlo,5234 +numpy/typing/__pycache__/__init__.cpython-311.pyc,, +numpy/typing/__pycache__/mypy_plugin.cpython-311.pyc,, +numpy/typing/__pycache__/setup.cpython-311.pyc,, +numpy/typing/mypy_plugin.py,sha256=24zVk4Ei3qH4Hc3SSz3v0XtIsycTo8HKoY6ilhB_7AQ,6376 +numpy/typing/setup.py,sha256=Cnz9q53w-vJNyE6vYxqYvQXx0pJbrG9quHyz9sqxfek,374 +numpy/typing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/typing/tests/__pycache__/__init__.cpython-311.pyc,, +numpy/typing/tests/__pycache__/test_isfile.cpython-311.pyc,, +numpy/typing/tests/__pycache__/test_runtime.cpython-311.pyc,, +numpy/typing/tests/__pycache__/test_typing.cpython-311.pyc,, +numpy/typing/tests/data/fail/arithmetic.pyi,sha256=4rY_ASCERAl8WCus1RakOe0Aw-8vvjilL29mgdD4lv0,3850 +numpy/typing/tests/data/fail/array_constructors.pyi,sha256=X9y_jUYS17WfYmXW5NwkVudyiR6ouUaAwEh0JRte42o,1089 +numpy/typing/tests/data/fail/array_like.pyi,sha256=OVAlEJZ5k8ZRKt0aGpZQwIjlUGpy0PzOOYqfI-IMqBQ,455 +numpy/typing/tests/data/fail/array_pad.pyi,sha256=57oK0Yp53rtKjjIrRFYLcxa-IfIGhtI-bEem7ggJKwI,132 +numpy/typing/tests/data/fail/arrayprint.pyi,sha256=-Fs9VnQfxyfak008Hq8kJWfB0snA6jGDXZz8ljQnwGE,549 +numpy/typing/tests/data/fail/arrayterator.pyi,sha256=FoU4ahHkJZ67dwWXer5FXLjjjesKKg-w2Jq1X1bHymA,480 +numpy/typing/tests/data/fail/bitwise_ops.pyi,sha256=GN9dVqk4_HFXn7zbRrHzJq_UGRFBccoYVUG1UuE7bXs,515 +numpy/typing/tests/data/fail/char.pyi,sha256=-vgN6EmfQ8VaA4SOZ5Ol9u4-Z7Q5I7G78LmaxZOuZ90,2615 +numpy/typing/tests/data/fail/chararray.pyi,sha256=jrNryZFpr8nxG2IHb9e0x3ranpvJpBy_RDex-WpT5rU,2296 +numpy/typing/tests/data/fail/comparisons.pyi,sha256=U4neWzwwtxG6QXsKlNGJuKXHBtwzYBQOa47_7SKF5Wg,888 +numpy/typing/tests/data/fail/constants.pyi,sha256=YSqNbXdhbdMmYbs7ntH0FCKbnm8IFeqsDlZBqcU43iw,286 +numpy/typing/tests/data/fail/datasource.pyi,sha256=PRT2hixR-mVxr2UILvHa99Dr54EF2h3snJXE-v3rWcc,395 +numpy/typing/tests/data/fail/dtype.pyi,sha256=OAGABqdXNB8gClJFEGMckoycuZcIasMaAlS2RkiKROI,334 +numpy/typing/tests/data/fail/einsumfunc.pyi,sha256=RS7GZqUCT_vEFJoyUx4gZlPO8GNFFNFWidxl-wLyRv0,539 +numpy/typing/tests/data/fail/false_positives.pyi,sha256=Q61qMsSsNCtmO0EMRxHj5Z7RYTyrELVpkzfJY5eK8Z0,366 +numpy/typing/tests/data/fail/flatiter.pyi,sha256=qLM4qm7gvJtEZ0rTHcyasUzoP5JbX4FREtqV3g1w6Lo,843 +numpy/typing/tests/data/fail/fromnumeric.pyi,sha256=FH2mjkgtCbA9soqlJRhYN7IIfRRrUL1i9mwqcbYKZSc,5591 +numpy/typing/tests/data/fail/histograms.pyi,sha256=yAPVt0rYTwtxnigoGT-u7hhKCE9iYxsXc24x2HGBrmA,367 +numpy/typing/tests/data/fail/index_tricks.pyi,sha256=moINir9iQoi6Q1ZuVg5BuSB9hSBtbg_uzv-Qm_lLYZk,509 +numpy/typing/tests/data/fail/lib_function_base.pyi,sha256=6y9T773CBLX-jUry1sCQGVuKVKM2wMuQ56Ni5V5j4Dw,2081 +numpy/typing/tests/data/fail/lib_polynomial.pyi,sha256=Ur7Y4iZX6WmoH5SDm0ePi8C8LPsuPs2Yr7g7P5O613g,899 +numpy/typing/tests/data/fail/lib_utils.pyi,sha256=VFpE6_DisvlDByyp1PiNPJEe5IcZp8cH0FlAJyoZipo,276 +numpy/typing/tests/data/fail/lib_version.pyi,sha256=7-ZJDZwDcB-wzpMN8TeYtZAgaqc7xnQ8Dnx2ISiX2Ts,158 +numpy/typing/tests/data/fail/linalg.pyi,sha256=yDd05aK1dI37RPt3pD2eJYo4dZFaT2yB1PEu3K0y9Tg,1322 +numpy/typing/tests/data/fail/memmap.pyi,sha256=HSTCQYNuW1Y6X1Woj361pN4rusSPs4oDCXywqk20yUo,159 +numpy/typing/tests/data/fail/modules.pyi,sha256=_ek4zKcdP-sIh_f-IDY0tP-RbLORKCSWelM9AOYxsyA,670 +numpy/typing/tests/data/fail/multiarray.pyi,sha256=XCdBxufNhR8ZtG8UMzk8nt9_NC5gJTKP9-xTqKO_K9I,1693 +numpy/typing/tests/data/fail/ndarray.pyi,sha256=YnjXy16RHs_esKelMjB07865CQ7gLyQnXhnitq5Kv5c,405 +numpy/typing/tests/data/fail/ndarray_misc.pyi,sha256=w-10xTDDWoff9Lq0dBO-jBeiBR-XjCz2qmes0dLx238,1372 +numpy/typing/tests/data/fail/nditer.pyi,sha256=w7emjnOxnf3NcvLktNLlke6Cuivn2gU3sVmGCfbG6rw,325 +numpy/typing/tests/data/fail/nested_sequence.pyi,sha256=em4GZwLDFE0QSxxg081wVwhh-Dmtkn8f7wThI0DiXVs,427 +numpy/typing/tests/data/fail/npyio.pyi,sha256=56QuHo9SvVR3Uhzl6gQZncCpX575Gy5wugjMICh20m0,620 +numpy/typing/tests/data/fail/numerictypes.pyi,sha256=fevH9x80CafYkiyBJ7LMLVl6GyTvQrZ34trBu6O8TtM,276 +numpy/typing/tests/data/fail/random.pyi,sha256=p5WsUGyOL-MGIeALh9Y0dVhYSRQLaUwMdjXc3G6C_7Q,2830 +numpy/typing/tests/data/fail/rec.pyi,sha256=Ws3TyesnoQjt7Q0wwtpShRDJmZCs2jjP17buFMomVGA,704 +numpy/typing/tests/data/fail/scalars.pyi,sha256=o91BwSfzPTczYVtbXsirqQUoUoYP1C_msGjc2GYsV04,2952 +numpy/typing/tests/data/fail/shape_base.pyi,sha256=Y_f4buHtX2Q2ZA4kaDTyR8LErlPXTzCB_-jBoScGh_Q,152 +numpy/typing/tests/data/fail/stride_tricks.pyi,sha256=IjA0Xrnx0lG3m07d1Hjbhtyo1Te5cXgjgr5fLUo4LYQ,315 +numpy/typing/tests/data/fail/testing.pyi,sha256=e7b5GKTWCtKGoB8z2a8edsW0Xjl1rMheALsvzEJjlCw,1370 +numpy/typing/tests/data/fail/twodim_base.pyi,sha256=ZqbRJfy5S_pW3fFLuomy4L5SBNqj6Nklexg9KDTo65c,899 +numpy/typing/tests/data/fail/type_check.pyi,sha256=CIyI0j0Buxv0QgCvNG2urjaKpoIZ-ZNawC2m6NzGlbo,379 +numpy/typing/tests/data/fail/ufunc_config.pyi,sha256=ukA0xwfJHLoGfoOIpWIN-91wj-DG8oaIjYbO72ymjg4,733 +numpy/typing/tests/data/fail/ufunclike.pyi,sha256=lbxjJyfARmt_QK1HxhxFxvwQTqCEZwJ9I53Wp8X3KIY,679 +numpy/typing/tests/data/fail/ufuncs.pyi,sha256=YaDTL7QLmGSUxE6JVMzpOlZTjHWrgbOo0UIlkX-6ZQk,1347 +numpy/typing/tests/data/fail/warnings_and_errors.pyi,sha256=PrbYDFI7IGN3Gf0OPBkVfefzQs4AXHwDQ495pvrX3RY,174 +numpy/typing/tests/data/misc/extended_precision.pyi,sha256=bS8bBeCFqjgtOiy-8_y39wfa7rwhdjLz2Vmo-RXAYD4,884 +numpy/typing/tests/data/mypy.ini,sha256=Ynv1VSx_kXTD2mFC3ZpgEFuCOg1F2VJXxPk0dxUnF2M,108 +numpy/typing/tests/data/pass/__pycache__/arithmetic.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_constructors.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_like.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayprint.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayterator.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/bitwise_ops.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/comparisons.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/dtype.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/einsumfunc.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/flatiter.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/fromnumeric.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/index_tricks.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_utils.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_version.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/literal.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/mod.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/modules.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/multiarray.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_conversion.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_misc.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_shape_manipulation.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/numeric.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/numerictypes.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/random.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/scalars.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/simple.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/simple_py3.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunc_config.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunclike.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufuncs.cpython-311.pyc,, +numpy/typing/tests/data/pass/__pycache__/warnings_and_errors.cpython-311.pyc,, +numpy/typing/tests/data/pass/arithmetic.py,sha256=2z3dmuysQQmiPz8x0bg8SOOKW62mVJn97uMa9T0L7Vk,7455 +numpy/typing/tests/data/pass/array_constructors.py,sha256=3GrhfBcmWX53pJHD0NvhXjwr2-uNKREbR1I9WCcZ7rI,2419 +numpy/typing/tests/data/pass/array_like.py,sha256=ce_IVubBd7J6FkSpJmD7qMlRLuwmiidhOqhYfZb16Wo,916 +numpy/typing/tests/data/pass/arrayprint.py,sha256=y_KkuLz1uM7pv53qfq7GQOuud4LoXE3apK1wtARdVyM,766 +numpy/typing/tests/data/pass/arrayterator.py,sha256=FqcpKdUQBQ0FazHFxr9MsLEZG-jnJVGKWZX2owRr4DQ,393 +numpy/typing/tests/data/pass/bitwise_ops.py,sha256=UnmxVr9HwI8ifdrutGm_u3EZU4iOOPQhrOku7hTaH0c,970 +numpy/typing/tests/data/pass/comparisons.py,sha256=nTE-fvraLK6xTZcP4uPV02wOShzYKWDaoapx35AeDOY,2992 +numpy/typing/tests/data/pass/dtype.py,sha256=MqDKC6Ywv6jNkWsR8rdLuabzHUco5w1OylDHEdxve_I,1069 +numpy/typing/tests/data/pass/einsumfunc.py,sha256=eXj5L5MWPtQHgrHPsJ36qqrmBHqct9UoujjJCvHnF1k,1370 +numpy/typing/tests/data/pass/flatiter.py,sha256=0BnbuLMBC7MQlprNZ0QhNSscfYwPhEhXOhWoyiRACWU,174 +numpy/typing/tests/data/pass/fromnumeric.py,sha256=Xd_nJVVDoONdztUX8ddgo7EXJ2FD8AX51MO_Yujnmog,3742 +numpy/typing/tests/data/pass/index_tricks.py,sha256=oaFD9vY01_RI5OkrXt-xTk1n_dd-SpuPp-eZ58XR3c8,1492 +numpy/typing/tests/data/pass/lib_utils.py,sha256=sDQCjHVGUwct0RQqAtH5_16y241siSY4bXKZRsuJ8xA,434 +numpy/typing/tests/data/pass/lib_version.py,sha256=HnuGOx7tQA_bcxFIJ3dRoMAR0fockxg4lGqQ4g7LGIw,299 +numpy/typing/tests/data/pass/literal.py,sha256=DLzdWHD6ttW4S0NEvGQbsH_UEJjhZyhvO4OXJjoyvZQ,1331 +numpy/typing/tests/data/pass/mod.py,sha256=HB9aK4_wGJbc44tomaoroNy0foIL5cI9KIjknvMTbkk,1578 +numpy/typing/tests/data/pass/modules.py,sha256=t0KJxYWbrWd7HbbgIDFb3LAhJBiNNb6QPjjFDAgC2mU,576 +numpy/typing/tests/data/pass/multiarray.py,sha256=MxHax6l94yqlTVZleAqG77ILEbW6wU5osPcHzxJ85ns,1331 +numpy/typing/tests/data/pass/ndarray_conversion.py,sha256=yPgzXG6paY1uF_z-QyHYrcmrZvhX7qtvTUh7ANLseCA,1626 +numpy/typing/tests/data/pass/ndarray_misc.py,sha256=z3mucbn9fLM1gxmbUhWlp2lcrOv4zFjqZFze0caE2EA,2715 +numpy/typing/tests/data/pass/ndarray_shape_manipulation.py,sha256=37eYwMNqMLwanIW9-63hrokacnSz2K_qtPUlkdpsTjo,640 +numpy/typing/tests/data/pass/numeric.py,sha256=SdnsD5zv0wm8T2hnIylyS14ig2McSz6rG9YslckbNQ4,1490 +numpy/typing/tests/data/pass/numerictypes.py,sha256=r0_s-a0-H2MdWIn4U4P6W9RQO0V1xrDusgodHNZeIYM,750 +numpy/typing/tests/data/pass/random.py,sha256=uJCnzlsOn9hr_G1TpHLdsweJI4EdhUSEQ4dxROPjqAs,61881 +numpy/typing/tests/data/pass/scalars.py,sha256=En0adCZAwEigZrzdQ0JQwDEmrS0b-DMd1vvjkFcvwo8,3479 +numpy/typing/tests/data/pass/simple.py,sha256=HmAfCOdZBWQF211YaZFrIGisMgu5FzTELApKny08n3Y,2676 +numpy/typing/tests/data/pass/simple_py3.py,sha256=HuLrc5aphThQkLjU2_19KgGFaXwKOfSzXe0p2xMm8ZI,96 +numpy/typing/tests/data/pass/ufunc_config.py,sha256=_M8v-QWAeT1-2MkfSeAbNl_ZwyPvYfPTsLl6c1X8d_w,1204 +numpy/typing/tests/data/pass/ufunclike.py,sha256=Gve6cJ2AT3TAwOjUOQQDIUnqsRCGYq70_tv_sgODiiA,1039 +numpy/typing/tests/data/pass/ufuncs.py,sha256=xGuKuqPetUTS4io5YDHaki5nbYRu-wC29SGU32tzVIg,462 +numpy/typing/tests/data/pass/warnings_and_errors.py,sha256=Pcg-QWfY4PAhTKyehae8q6LhtbUABxa2Ye63-3h1f4w,150 +numpy/typing/tests/data/reveal/arithmetic.pyi,sha256=Ndmi_IFAl8z28RHsYTbOouf-B5FH91x_9ky-JwsdXVg,19765 +numpy/typing/tests/data/reveal/array_constructors.pyi,sha256=DcT8Z2rEpqYfjXySBejk8cGOUidUmizZGE5ZEy7r14E,10600 +numpy/typing/tests/data/reveal/arraypad.pyi,sha256=Q1pcU4B3eRsw5jsv-S0MsEfNUbp_4aMdO_o3n0rtA2A,776 +numpy/typing/tests/data/reveal/arrayprint.pyi,sha256=YyzzkL-wj4Rs-fdo3brpoaWtb5g3yk4Vn2HKu5KRo4w,876 +numpy/typing/tests/data/reveal/arraysetops.pyi,sha256=ApCFQcZzQ08zV32SJ86Xyv_7jazl3XKMmJmULtNquJ8,4155 +numpy/typing/tests/data/reveal/arrayterator.pyi,sha256=TF_1eneHoT0v9HqS9dKc5Xiv3iY3E330GR1RNcJ7s2Q,1111 +numpy/typing/tests/data/reveal/bitwise_ops.pyi,sha256=nRkyUGrBB_Es7TKyDxS_s3u2dFgBfzjocInI9Ea-J10,3919 +numpy/typing/tests/data/reveal/char.pyi,sha256=M_iTa9Pn8F7jQ1k6RN9KvbhEn00g7UYJZ5PV57ikcZM,7289 +numpy/typing/tests/data/reveal/chararray.pyi,sha256=O0EfwnKc3W1Fnx1c7Yotb1O84kVMuqJLlMBXd2duvjI,6093 +numpy/typing/tests/data/reveal/comparisons.pyi,sha256=huaf-seaF5ndTqfoaBfPtMMkOYovq7ibJl5-CRoQW7s,7468 +numpy/typing/tests/data/reveal/constants.pyi,sha256=P9vFEMkPpJ5KeUnzqPOuyHlh3zAFl9lzB4WxyB2od7A,1949 +numpy/typing/tests/data/reveal/ctypeslib.pyi,sha256=-Pk2rLEGCzz3B_y8Mu10JSVA8gPFztl5fV1dspPzqig,4727 +numpy/typing/tests/data/reveal/datasource.pyi,sha256=e8wjn60tO5EdnkBF34JrZT5XvdyW7kRWD2abtgr6qUg,671 +numpy/typing/tests/data/reveal/dtype.pyi,sha256=TKrYyxMu5IGobs0SDTIRcPuWsZ5X7zMYB4pmUlTTJxA,2872 +numpy/typing/tests/data/reveal/einsumfunc.pyi,sha256=pbtSfzIWUJRkDpe2riHBlvFlNSC3CqVM-SbYtBgX9H0,2044 +numpy/typing/tests/data/reveal/emath.pyi,sha256=-muNpWOv_niIn-zS3gUnFO4qBZAouNlVGue2x1L5Ris,2423 +numpy/typing/tests/data/reveal/false_positives.pyi,sha256=AplTmZV7TS7nivU8vegbstMN5MdMv4U0JJdZ4IeeA5M,482 +numpy/typing/tests/data/reveal/fft.pyi,sha256=ReQ9qn5frvJEy-g0RWpUGlPBntUS1cFSIu6WfPotHzE,1749 +numpy/typing/tests/data/reveal/flatiter.pyi,sha256=e1OQsVxQpgyfqMNw2puUTATl-w3swvdknlctAiWxf_E,882 +numpy/typing/tests/data/reveal/fromnumeric.pyi,sha256=PNtGQR1VmGk_xNbd0eP7k7B2oNCMBz2XOJ17-_SdE5M,12101 +numpy/typing/tests/data/reveal/getlimits.pyi,sha256=nUGOMFpWj3pMgqLy6ZbR7A4G2q7iLIl5zEFBGf-Qcfw,1592 +numpy/typing/tests/data/reveal/histograms.pyi,sha256=MxKWoa7UoJRRLim53H6OoyYfz87P3_9YUXGYPTknGVQ,1303 +numpy/typing/tests/data/reveal/index_tricks.pyi,sha256=HpD7lU7hcyDoLdZbeqskPXnX7KYwPtll7uJKYUzrlE8,3177 +numpy/typing/tests/data/reveal/lib_function_base.pyi,sha256=eSiSZUlmPXqVPKknM7GcEv76BDgj0IJRu3FXcZXpmqc,8318 +numpy/typing/tests/data/reveal/lib_polynomial.pyi,sha256=TOzOdMPDqveDv3vDKSjtq6RRvN-j_s2J7aud2ySDAB0,5986 +numpy/typing/tests/data/reveal/lib_utils.pyi,sha256=_zj7WGYGYMFXAHLK-F11aeFfDvjRvFARUjoXhbXn8V0,1049 +numpy/typing/tests/data/reveal/lib_version.pyi,sha256=UCioUeykot8-nWL6goKxZnKZxtgB4lFEi9wdN_xyF1U,672 +numpy/typing/tests/data/reveal/linalg.pyi,sha256=LPaY-RyYL7Xt3djCgNaWEgI8beI9Eo_XnvOwi6Y7-eo,4877 +numpy/typing/tests/data/reveal/matrix.pyi,sha256=ciJXsn5v2O1IZ3VEn5Ilp8-40NTQokfrOOgVXMFsvLo,2922 +numpy/typing/tests/data/reveal/memmap.pyi,sha256=A5PovMzjRp2zslF1vw3TdTQjj4Y0dIEJ__HDBV_svGM,842 +numpy/typing/tests/data/reveal/mod.pyi,sha256=-CNWft2jQGSdrO8dYRgwbl7OhL3a78Zo60JVmiY-gQI,5666 +numpy/typing/tests/data/reveal/modules.pyi,sha256=0WPq7A-aqWkJsV-IA1_7dFNCcxBacj1AWExaXbXErG4,1958 +numpy/typing/tests/data/reveal/multiarray.pyi,sha256=6MvfNKihK-oN6QwG9HFNelgheo4lnL0FCrmIF_qxdoA,5326 +numpy/typing/tests/data/reveal/nbit_base_example.pyi,sha256=DRUMGatQvQXTuovKEMF4dzazIU6it6FU53LkOEo2vNo,657 +numpy/typing/tests/data/reveal/ndarray_conversion.pyi,sha256=BfjQD8U756l4gOfY0LD47HhDRxbq0yCFfEFKvbXs7Rs,1791 +numpy/typing/tests/data/reveal/ndarray_misc.pyi,sha256=0EN-a47Msn4pZgKVdD-GrXCCmt-oxjlov5rszchBmOI,7126 +numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi,sha256=QDQ9g6l-e73pTJp-Dosiynb-okbqi91D4KirjhIjcv4,1233 +numpy/typing/tests/data/reveal/nditer.pyi,sha256=VFXnT75BgWSUpb-dD-q5cZkfeOqsk-x9cH626g9FWT4,2021 +numpy/typing/tests/data/reveal/nested_sequence.pyi,sha256=IQyRlXduk-ZEakOtoliMLCqNgGbeg0mzZf-a-a3Gq_0,734 +numpy/typing/tests/data/reveal/npyio.pyi,sha256=YXagt2J-1suu5WXZ_si5NuJf7sHj_7NlaSLqQkam1Po,4209 +numpy/typing/tests/data/reveal/numeric.pyi,sha256=aJKnav-X45tjSFfgGD4iCetwEFcJXdNgU7valktjiCg,6160 +numpy/typing/tests/data/reveal/numerictypes.pyi,sha256=-YQRhwjBjsFJHjpGCRqzafNnKDdsmbBHbmPwccP0pLI,2487 +numpy/typing/tests/data/reveal/random.pyi,sha256=s6T074ZIpGAUqHnA-yAlozTLvt7PNBjCBqd-nGMqWGg,104091 +numpy/typing/tests/data/reveal/rec.pyi,sha256=DbRVk6lc7-3qPe-7Q26tUWpdaH9B4UVoQSYrRGJUo1Q,3858 +numpy/typing/tests/data/reveal/scalars.pyi,sha256=Qn3B3rsqSN397Jh25xs4odt2pfCQtWkoJe-e0-oX8d4,4790 +numpy/typing/tests/data/reveal/shape_base.pyi,sha256=YjiVukrK6OOydvopOaOmeAIIa0YQ2hn9_I_-FyYkHVU,2427 +numpy/typing/tests/data/reveal/stride_tricks.pyi,sha256=EBZR8gSP385nhotwJ3GH9DOUD2q5nUEYbXfhLo5xrPo,1542 +numpy/typing/tests/data/reveal/testing.pyi,sha256=_WOAj_t5SWYiqN0KG26Mza8RvaD3WAa7rFUlgksjLms,8611 +numpy/typing/tests/data/reveal/twodim_base.pyi,sha256=ZdNVo2HIJcx8iF9PA-z5W3Bs0hWM2nlVdbhLuAQlljM,3132 +numpy/typing/tests/data/reveal/type_check.pyi,sha256=yZSp50TtvPqv_PN7zmVcNOVUTUXMNYFGcguMNj25E9Y,3044 +numpy/typing/tests/data/reveal/ufunc_config.pyi,sha256=buwSvat3SVFAFl5k8TL6Mgpi32o6hHZYZ2Lpn6AHdEU,1327 +numpy/typing/tests/data/reveal/ufunclike.pyi,sha256=V_gLcZVrTXJ21VkUMwA0HyxUgA1r6OzjsdJegaKL2GE,1329 +numpy/typing/tests/data/reveal/ufuncs.pyi,sha256=VnwYr5KT_FLKfc0wV7dtNz7bNtaC9VIQt-oz56Hb5EE,2798 +numpy/typing/tests/data/reveal/warnings_and_errors.pyi,sha256=ImMlPt2PQBtX8Qf1EZFmLjNWm8fPE6IWQ_deaq_-85s,538 +numpy/typing/tests/test_isfile.py,sha256=BhKZs4-LrhFUfKjcG0yelySjE6ZITMxGIBYWGDHMRb8,864 +numpy/typing/tests/test_runtime.py,sha256=2qu8JEliITnZCBJ_QJpohacj_OQ08o73ixS2w2ooNXI,3275 +numpy/typing/tests/test_typing.py,sha256=Da1ZOFjtPh_Mvb5whpI-okBJdgLOAfJtJNyG6leGFoQ,8743 +numpy/version.py,sha256=OTLnSh0NGfWyL8VrnIj0Ndt_KZOTl1Z-kD9Cf-jRMmY,216 diff --git a/shared/package-files/18/186d703cd31c2f47cc24eebcbc5e77c0a31dc277de84371a23eafd3694df8a50/specifiers.py b/shared/package-files/18/186d703cd31c2f47cc24eebcbc5e77c0a31dc277de84371a23eafd3694df8a50/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..b30926af8bf4f47efe98eea44d5ded4cb6f7e07d --- /dev/null +++ b/shared/package-files/18/186d703cd31c2f47cc24eebcbc5e77c0a31dc277de84371a23eafd3694df8a50/specifiers.py @@ -0,0 +1,1020 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import itertools +import re +from typing import Callable, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version: + if not isinstance(version, Version): + version = Version(version) + return version + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + self._spec: tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 + @property # type: ignore[override] + def prereleases(self) -> bool: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "===", ">", "<"]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if Version(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + canonical_version = canonicalize_version( + self._spec[1], + strip_trailing_zero=(self._spec[0] != "~="), + ) + return self._spec[0], canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + prospective.public, strip_trailing_zero=False + ) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by bangs and dots, and pretend that there is + # an implicit dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = Version(prospective.public) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) <= Version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) >= Version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + False + >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") + True + >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) + True + """ + + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version, this allows us to have a shortcut for + # "2.0" in Specifier(">=2") + normalized_item = _coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if normalized_item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + operator_callable: CallableOperator = self._get_operator(self.operator) + return operator_callable(normalized_item, self.version) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(Specifier().contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = _coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later in case nothing + # else matches this specifier. + if parsed_version.is_prerelease and not ( + prereleases or self.prereleases + ): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the beginning. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return ( + list(itertools.chain.from_iterable(left_split)), + list(itertools.chain.from_iterable(right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Make each individual specifier a Specifier and save in a frozen set + # for later. + self._specs = frozenset(map(Specifier, split_specifiers)) + else: + # Save the supplied specifiers in a frozen set. + self._specs = frozenset(specifiers) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease " + "overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + # Ensure that our item is a Version instance. + if not isinstance(item, Version): + item = Version(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + if installed and item.is_prerelease: + item = Version(item.base_version) + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all(s.contains(item, prereleases=prereleases) for s in self._specs) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + [] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iter(iterable) + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases. + else: + filtered: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + + for item in iterable: + parsed_version = _coerce_version(item) + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return iter(found_prereleases) + + return iter(filtered) diff --git a/shared/package-files/18/186f25eb2cb94c6b5987743c7a71ab68ea11ad9fc7299cabbdad7fec83f302a9/test_quotientring.cpython-311.pyc b/shared/package-files/18/186f25eb2cb94c6b5987743c7a71ab68ea11ad9fc7299cabbdad7fec83f302a9/test_quotientring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a52e2852ad4bf9abeda5260e23fb1d32c1795534 Binary files /dev/null and b/shared/package-files/18/186f25eb2cb94c6b5987743c7a71ab68ea11ad9fc7299cabbdad7fec83f302a9/test_quotientring.cpython-311.pyc differ diff --git a/shared/package-files/18/187531803ceb8e9d4ea5a7fb98e3b25398624a58bce0abea0dff34f13e7db57b/CUDAEvent.h b/shared/package-files/18/187531803ceb8e9d4ea5a7fb98e3b25398624a58bce0abea0dff34f13e7db57b/CUDAEvent.h new file mode 100644 index 0000000000000000000000000000000000000000..94ce34645b02bf21d30eef42191560962a6c40a3 --- /dev/null +++ b/shared/package-files/18/187531803ceb8e9d4ea5a7fb98e3b25398624a58bce0abea0dff34f13e7db57b/CUDAEvent.h @@ -0,0 +1,211 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace at::cuda { + +/* +* CUDAEvents are movable not copyable wrappers around CUDA's events. +* +* CUDAEvents are constructed lazily when first recorded unless it is +* reconstructed from a cudaIpcEventHandle_t. The event has a device, and this +* device is acquired from the first recording stream. However, if reconstructed +* from a handle, the device should be explicitly specified; or if ipc_handle() is +* called before the event is ever recorded, it will use the current device. +* Later streams that record the event must match this device. +*/ +struct TORCH_CUDA_CPP_API CUDAEvent { + // Constructors + // Default value for `flags` is specified below - it's cudaEventDisableTiming + CUDAEvent() noexcept = default; + CUDAEvent(unsigned int flags) noexcept : flags_{flags} {} + + CUDAEvent( + DeviceIndex device_index, const cudaIpcEventHandle_t* handle) : device_index_(device_index) { + CUDAGuard guard(device_index_); + + AT_CUDA_CHECK(cudaIpcOpenEventHandle(&event_, *handle)); + is_created_ = true; + } + + // Note: event destruction done on creating device to avoid creating a + // CUDA context on other devices. + ~CUDAEvent() { + try { + if (is_created_) { + CUDAGuard guard(device_index_); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_deletion(at::kCUDA, reinterpret_cast(event_)); + } + AT_CUDA_CHECK(cudaEventDestroy(event_)); + } + } catch (...) { /* No throw */ } + } + + CUDAEvent(const CUDAEvent&) = delete; + CUDAEvent& operator=(const CUDAEvent&) = delete; + + CUDAEvent(CUDAEvent&& other) noexcept { moveHelper(std::move(other)); } + CUDAEvent& operator=(CUDAEvent&& other) noexcept { + if (this != &other) { + moveHelper(std::move(other)); + } + return *this; + } + + operator cudaEvent_t() const { return event(); } + + // Less than operator (to allow use in sets) + friend bool operator<(const CUDAEvent& left, const CUDAEvent& right) { + return left.event_ < right.event_; + } + + std::optional device() const { + if (is_created_) { + return at::Device(at::kCUDA, device_index_); + } else { + return {}; + } + } + + bool isCreated() const { return is_created_; } + DeviceIndex device_index() const {return device_index_;} + cudaEvent_t event() const { return event_; } + + // Note: cudaEventQuery can be safely called from any device + bool query() const { + if (!is_created_) { + return true; + } + + cudaError_t err = cudaEventQuery(event_); + if (err == cudaSuccess) { + return true; + } else if (err != cudaErrorNotReady) { + C10_CUDA_CHECK(err); + } else { + // ignore and clear the error if not ready + (void)cudaGetLastError(); + } + + return false; + } + + void record() { record(getCurrentCUDAStream()); } + + void recordOnce(const CUDAStream& stream) { + if (!was_recorded_) record(stream); + } + + // Note: cudaEventRecord must be called on the same device as the event. + void record(const CUDAStream& stream) { + if (!is_created_) { + createEvent(stream.device_index()); + } + + TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_, + " does not match recording stream's device ", stream.device_index(), "."); + CUDAGuard guard(device_index_); + AT_CUDA_CHECK(cudaEventRecord(event_, stream)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_record(at::kCUDA, + reinterpret_cast(event_), + reinterpret_cast(stream.stream()) + ); + } + was_recorded_ = true; + } + + // Note: cudaStreamWaitEvent must be called on the same device as the stream. + // The event has no actual GPU resources associated with it. + void block(const CUDAStream& stream) { + if (is_created_) { + CUDAGuard guard(stream.device_index()); + AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_, 0)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_wait(at::kCUDA, + reinterpret_cast(event_), + reinterpret_cast(stream.stream()) + ); + } + } + } + + // Note: cudaEventElapsedTime can be safely called from any device + float elapsed_time(const CUDAEvent& other) const { + TORCH_CHECK(is_created_ && other.isCreated(), + "Both events must be recorded before calculating elapsed time."); + float time_ms = 0; + // We do not strictly have to set the device index to the same as our event, + // but if we don't and the current device is not initialized, it will + // create a new cuda context, which will consume a lot of memory. + CUDAGuard guard(device_index_); + // raise cudaErrorNotReady if either event is recorded but not yet completed + AT_CUDA_CHECK(cudaEventElapsedTime(&time_ms, event_, other.event_)); + return time_ms; + } + + // Note: cudaEventSynchronize can be safely called from any device + void synchronize() const { + if (is_created_) { + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_synchronization(at::kCUDA, reinterpret_cast(event_)); + } + AT_CUDA_CHECK(cudaEventSynchronize(event_)); + } + } + + // Note: cudaIpcGetEventHandle must be called on the same device as the event + void ipc_handle(cudaIpcEventHandle_t * handle) { + if (!is_created_) { + // this CUDAEvent object was initially constructed from flags but event_ + // is not created yet. + createEvent(getCurrentCUDAStream().device_index()); + } + CUDAGuard guard(device_index_); + AT_CUDA_CHECK(cudaIpcGetEventHandle(handle, event_)); + } + +private: + unsigned int flags_ = cudaEventDisableTiming; + bool is_created_ = false; + bool was_recorded_ = false; + DeviceIndex device_index_ = -1; + cudaEvent_t event_{}; + + void createEvent(DeviceIndex device_index) { + device_index_ = device_index; + CUDAGuard guard(device_index_); + AT_CUDA_CHECK(cudaEventCreateWithFlags(&event_, flags_)); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_creation(at::kCUDA, reinterpret_cast(event_)); + } + is_created_ = true; + } + + void moveHelper(CUDAEvent&& other) { + std::swap(flags_, other.flags_); + std::swap(is_created_, other.is_created_); + std::swap(was_recorded_, other.was_recorded_); + std::swap(device_index_, other.device_index_); + std::swap(event_, other.event_); + } +}; + +} // namespace at::cuda diff --git a/shared/package-files/18/187e8162fca3f2a040c769a0ccc618e5458526071b3564b73d0ff2ccb773dcd4/core.cpython-311.pyc b/shared/package-files/18/187e8162fca3f2a040c769a0ccc618e5458526071b3564b73d0ff2ccb773dcd4/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f595fcf3413ce865a4164bb0010ddcc1bbc539cf Binary files /dev/null and b/shared/package-files/18/187e8162fca3f2a040c769a0ccc618e5458526071b3564b73d0ff2ccb773dcd4/core.cpython-311.pyc differ diff --git a/shared/package-files/18/187f9df2edb248df6227498a30acbfadc1f3f5753bc37893d6aad99545142d21/_nested_select_backward_ops.h b/shared/package-files/18/187f9df2edb248df6227498a30acbfadc1f3f5753bc37893d6aad99545142d21/_nested_select_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..fe66ce83df0fb8ca77f07ed665b4164a1cb590ff --- /dev/null +++ b/shared/package-files/18/187f9df2edb248df6227498a30acbfadc1f3f5753bc37893d6aad99545142d21/_nested_select_backward_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_select_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_nested_select_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_nested_select_backward(Tensor grad_output, Tensor self, int dim, SymInt index) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, c10::SymInt index); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, c10::SymInt index); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/18813360459ec6fcb8ee3c04b7976d72614b91cbd4726d486482eb2f9b3fe4f8/QScheme.h b/shared/package-files/18/18813360459ec6fcb8ee3c04b7976d72614b91cbd4726d486482eb2f9b3fe4f8/QScheme.h new file mode 100644 index 0000000000000000000000000000000000000000..af8f64520323284e3029de69852929fbf6f58aa2 --- /dev/null +++ b/shared/package-files/18/18813360459ec6fcb8ee3c04b7976d72614b91cbd4726d486482eb2f9b3fe4f8/QScheme.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include + +#include + +constexpr int QSCHEME_NAME_LEN = 64; + +struct THPQScheme { + PyObject_HEAD + at::QScheme qscheme; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + char name[QSCHEME_NAME_LEN + 1]; +}; + +TORCH_PYTHON_API extern PyTypeObject THPQSchemeType; + +inline bool THPQScheme_Check(PyObject* obj) { + return Py_TYPE(obj) == &THPQSchemeType; +} + +PyObject* THPQScheme_New(at::QScheme qscheme, const std::string& name); + +void THPQScheme_init(PyObject* module); diff --git a/shared/package-files/18/18824c8241ca46c1096491c7ce7ce236c27b43b30fb187701d021c811397415e/run.cpython-311.pyc b/shared/package-files/18/18824c8241ca46c1096491c7ce7ce236c27b43b30fb187701d021c811397415e/run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a855b3a093a47e8aa7bc7d0e943b5ceaf555df06 Binary files /dev/null and b/shared/package-files/18/18824c8241ca46c1096491c7ce7ce236c27b43b30fb187701d021c811397415e/run.cpython-311.pyc differ diff --git a/shared/package-files/18/188376a25f04432152faa36a545af69703b560bab109a6f01343856e6694e722/reduction.cpython-311.pyc b/shared/package-files/18/188376a25f04432152faa36a545af69703b560bab109a6f01343856e6694e722/reduction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3280f72f1bc2380c5ef356bbf94e143438216387 Binary files /dev/null and b/shared/package-files/18/188376a25f04432152faa36a545af69703b560bab109a6f01343856e6694e722/reduction.cpython-311.pyc differ diff --git a/shared/package-files/18/188896151b2e591fe37c7aaf62aa955018de19b95c4a4e90a245f19282d31326/test_parse_dates.cpython-311.pyc b/shared/package-files/18/188896151b2e591fe37c7aaf62aa955018de19b95c4a4e90a245f19282d31326/test_parse_dates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..255ff21ec5be42c9c071b1c5301c6e436ffbd820 Binary files /dev/null and b/shared/package-files/18/188896151b2e591fe37c7aaf62aa955018de19b95c4a4e90a245f19282d31326/test_parse_dates.cpython-311.pyc differ diff --git a/shared/package-files/18/1888b94940acf7124a69304ec41f1adf6dba0d2004278d9b05b60da0f77beaa2/test_structuralholes.cpython-311.pyc b/shared/package-files/18/1888b94940acf7124a69304ec41f1adf6dba0d2004278d9b05b60da0f77beaa2/test_structuralholes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5251d96b3d75767c78300bb6de19036646b89d9 Binary files /dev/null and b/shared/package-files/18/1888b94940acf7124a69304ec41f1adf6dba0d2004278d9b05b60da0f77beaa2/test_structuralholes.cpython-311.pyc differ diff --git a/shared/package-files/18/1889427d7bf3153acb77b3e979a458a0ce67034fc457afed8e40115b97239361/_fused_adamw.h b/shared/package-files/18/1889427d7bf3153acb77b3e979a458a0ce67034fc457afed8e40115b97239361/_fused_adamw.h new file mode 100644 index 0000000000000000000000000000000000000000..8d0ddc12bf17e8671c9f41f4ba79fae3445634e7 --- /dev/null +++ b/shared/package-files/18/1889427d7bf3153acb77b3e979a458a0ce67034fc457afed8e40115b97239361/_fused_adamw.h @@ -0,0 +1,64 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_fused_adamw_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () +inline void _fused_adamw_(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw_::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () +inline void _fused_adamw_(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw__tensor_lr::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} +// aten::_fused_adamw.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_outf(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale, const ::std::optional & found_inf, at::TensorList out) { + return at::_ops::_fused_adamw_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} + +// aten::_fused_adamw(Tensor[] self, Tensor[] grads, Tensor[] exp_avgs, Tensor[] exp_avg_sqs, Tensor[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] exp_avgs_out, Tensor[] exp_avg_sqs_out, Tensor[] max_exp_avg_sqs_out) +inline ::std::tuple<::std::vector,::std::vector,::std::vector,::std::vector,::std::vector> _fused_adamw(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw_tensor_lr_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} +// aten::_fused_adamw.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_outf(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale, const ::std::optional & found_inf, at::TensorList out) { + return at::_ops::_fused_adamw_tensor_lr_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} + +// aten::_fused_adamw.tensor_lr(Tensor[] self, Tensor[] grads, Tensor[] exp_avgs, Tensor[] exp_avg_sqs, Tensor[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] exp_avgs_out, Tensor[] exp_avg_sqs_out, Tensor[] max_exp_avg_sqs_out) +inline ::std::tuple<::std::vector,::std::vector,::std::vector,::std::vector,::std::vector> _fused_adamw(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const ::std::optional & grad_scale={}, const ::std::optional & found_inf={}) { + return at::_ops::_fused_adamw_tensor_lr::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +} diff --git a/shared/package-files/18/188d070bf13f33cb627f6fdd65d125d8e459dac6e4271cf631b9253fb0379d8f/test_multivariate_resultants.cpython-311.pyc b/shared/package-files/18/188d070bf13f33cb627f6fdd65d125d8e459dac6e4271cf631b9253fb0379d8f/test_multivariate_resultants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95b2db9bf676dc6fc27e1ba0985d95dae60cabff Binary files /dev/null and b/shared/package-files/18/188d070bf13f33cb627f6fdd65d125d8e459dac6e4271cf631b9253fb0379d8f/test_multivariate_resultants.cpython-311.pyc differ diff --git a/shared/package-files/18/1890dc9b229ef2b8b759d964ae96d5793a65949e5ef4303ef3609ef9e6ed1140/common.cpython-311.pyc b/shared/package-files/18/1890dc9b229ef2b8b759d964ae96d5793a65949e5ef4303ef3609ef9e6ed1140/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23e39c6c3f4e9f90394d5c9d36b48fc32fecdda3 Binary files /dev/null and b/shared/package-files/18/1890dc9b229ef2b8b759d964ae96d5793a65949e5ef4303ef3609ef9e6ed1140/common.cpython-311.pyc differ diff --git a/shared/package-files/18/1895f1e20b6024a7c12aa2b2a590472148d1cee29a3377dda31ae694bc75a627/hamming_window.h b/shared/package-files/18/1895f1e20b6024a7c12aa2b2a590472148d1cee29a3377dda31ae694bc75a627/hamming_window.h new file mode 100644 index 0000000000000000000000000000000000000000..180243e120c870f55aadfbc24dfb8b6b4f9e44b5 --- /dev/null +++ b/shared/package-files/18/1895f1e20b6024a7c12aa2b2a590472148d1cee29a3377dda31ae694bc75a627/hamming_window.h @@ -0,0 +1,98 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, at::TensorOptions options={}) { + return at::_ops::hamming_window::call(window_length, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::hamming_window::call(window_length, dtype, layout, device, pin_memory); +} + +// aten::hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, at::TensorOptions options={}) { + return at::_ops::hamming_window_periodic::call(window_length, periodic, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::hamming_window_periodic::call(window_length, periodic, dtype, layout, device, pin_memory); +} + +// aten::hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, at::TensorOptions options={}) { + return at::_ops::hamming_window_periodic_alpha::call(window_length, periodic, alpha, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::hamming_window_periodic_alpha::call(window_length, periodic, alpha, dtype, layout, device, pin_memory); +} + +// aten::hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, double beta, at::TensorOptions options={}) { + return at::_ops::hamming_window_periodic_alpha_beta::call(window_length, periodic, alpha, beta, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, double beta, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::hamming_window_periodic_alpha_beta::call(window_length, periodic, alpha, beta, dtype, layout, device, pin_memory); +} + +// aten::hamming_window.out(int window_length, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_out(at::Tensor & out, int64_t window_length) { + return at::_ops::hamming_window_out::call(window_length, out); +} +// aten::hamming_window.out(int window_length, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_outf(int64_t window_length, at::Tensor & out) { + return at::_ops::hamming_window_out::call(window_length, out); +} + +// aten::hamming_window.periodic_out(int window_length, bool periodic, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_out(at::Tensor & out, int64_t window_length, bool periodic) { + return at::_ops::hamming_window_periodic_out::call(window_length, periodic, out); +} +// aten::hamming_window.periodic_out(int window_length, bool periodic, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_outf(int64_t window_length, bool periodic, at::Tensor & out) { + return at::_ops::hamming_window_periodic_out::call(window_length, periodic, out); +} + +// aten::hamming_window.periodic_alpha_out(int window_length, bool periodic, float alpha, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_out(at::Tensor & out, int64_t window_length, bool periodic, double alpha) { + return at::_ops::hamming_window_periodic_alpha_out::call(window_length, periodic, alpha, out); +} +// aten::hamming_window.periodic_alpha_out(int window_length, bool periodic, float alpha, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_outf(int64_t window_length, bool periodic, double alpha, at::Tensor & out) { + return at::_ops::hamming_window_periodic_alpha_out::call(window_length, periodic, alpha, out); +} + +// aten::hamming_window.periodic_alpha_beta_out(int window_length, bool periodic, float alpha, float beta, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_out(at::Tensor & out, int64_t window_length, bool periodic, double alpha, double beta) { + return at::_ops::hamming_window_periodic_alpha_beta_out::call(window_length, periodic, alpha, beta, out); +} +// aten::hamming_window.periodic_alpha_beta_out(int window_length, bool periodic, float alpha, float beta, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hamming_window_outf(int64_t window_length, bool periodic, double alpha, double beta, at::Tensor & out) { + return at::_ops::hamming_window_periodic_alpha_beta_out::call(window_length, periodic, alpha, beta, out); +} + +} diff --git a/shared/package-files/18/18a26de900285631f1dc6a5c24b8a5e2fbf4f9b585468a22a2e855a929dc7390/win.cpython-311.pyc b/shared/package-files/18/18a26de900285631f1dc6a5c24b8a5e2fbf4f9b585468a22a2e855a929dc7390/win.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..221003582b47e8a9d143f729ee32525af1508bca Binary files /dev/null and b/shared/package-files/18/18a26de900285631f1dc6a5c24b8a5e2fbf4f9b585468a22a2e855a929dc7390/win.cpython-311.pyc differ diff --git a/shared/package-files/18/18abc58a57f1f47a8faf7fc9922fea7d77a541020742dba913b879f051697264/rand_like_compositeexplicitautograd_dispatch.h b/shared/package-files/18/18abc58a57f1f47a8faf7fc9922fea7d77a541020742dba913b879f051697264/rand_like_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..524e2331b72726c3299ae5fcb208feffb8b7ac47 --- /dev/null +++ b/shared/package-files/18/18abc58a57f1f47a8faf7fc9922fea7d77a541020742dba913b879f051697264/rand_like_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor rand_like(const at::Tensor & self, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt); +TORCH_API at::Tensor rand_like(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +TORCH_API at::Tensor & rand_like_out(at::Tensor & out, const at::Tensor & self, ::std::optional memory_format=::std::nullopt); +TORCH_API at::Tensor & rand_like_outf(const at::Tensor & self, ::std::optional memory_format, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/18/18add6d0e9588d71de5bf8709a3ae4df800eedea76350706494f5d735ee287e3/slow_conv_transpose2d_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/18/18add6d0e9588d71de5bf8709a3ae4df800eedea76350706494f5d735ee287e3/slow_conv_transpose2d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..025e422eb2f8eb1b8060a585cce090551727864c --- /dev/null +++ b/shared/package-files/18/18add6d0e9588d71de5bf8709a3ae4df800eedea76350706494f5d735ee287e3/slow_conv_transpose2d_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor slow_conv_transpose2d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_transpose2d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/18/18adfce7af93b2c3ef2739397dfbb5a9baec4ceef261f91116c90a4c93dcdef1/test_bdist_wheel.cpython-311.pyc b/shared/package-files/18/18adfce7af93b2c3ef2739397dfbb5a9baec4ceef261f91116c90a4c93dcdef1/test_bdist_wheel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a46f40b45cad005fcbd0f04a849eb3a5866c03d Binary files /dev/null and b/shared/package-files/18/18adfce7af93b2c3ef2739397dfbb5a9baec4ceef261f91116c90a4c93dcdef1/test_bdist_wheel.cpython-311.pyc differ diff --git a/shared/package-files/18/18b28258a7a706532cc5e97549a0f1beb39ba7b299c085904367c4930d4f8b94/METADATA b/shared/package-files/18/18b28258a7a706532cc5e97549a0f1beb39ba7b299c085904367c4930d4f8b94/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c5075e17f92f8d3076a290f5eb5b6b8b737ebef4 --- /dev/null +++ b/shared/package-files/18/18b28258a7a706532cc5e97549a0f1beb39ba7b299c085904367c4930d4f8b94/METADATA @@ -0,0 +1,167 @@ +Metadata-Version: 2.4 +Name: networkx +Version: 3.5 +Summary: Python package for creating and manipulating graphs and networks +Author-email: Aric Hagberg +Maintainer-email: NetworkX Developers +Project-URL: Homepage, https://networkx.org/ +Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues +Project-URL: Documentation, https://networkx.org/documentation/stable/ +Project-URL: Source Code, https://github.com/networkx/networkx +Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math +Platform: Linux +Platform: Mac OSX +Platform: Windows +Platform: Unix +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Scientific/Engineering :: Bio-Informatics +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Physics +Requires-Python: >=3.11 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Provides-Extra: default +Requires-Dist: numpy>=1.25; extra == "default" +Requires-Dist: scipy>=1.11.2; extra == "default" +Requires-Dist: matplotlib>=3.8; extra == "default" +Requires-Dist: pandas>=2.0; extra == "default" +Provides-Extra: developer +Requires-Dist: pre-commit>=4.1; extra == "developer" +Requires-Dist: mypy>=1.15; extra == "developer" +Provides-Extra: doc +Requires-Dist: sphinx>=8.0; extra == "doc" +Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc" +Requires-Dist: sphinx-gallery>=0.18; extra == "doc" +Requires-Dist: numpydoc>=1.8.0; extra == "doc" +Requires-Dist: pillow>=10; extra == "doc" +Requires-Dist: texext>=0.6.7; extra == "doc" +Requires-Dist: myst-nb>=1.1; extra == "doc" +Requires-Dist: intersphinx-registry; extra == "doc" +Provides-Extra: example +Requires-Dist: osmnx>=2.0.0; extra == "example" +Requires-Dist: momepy>=0.7.2; extra == "example" +Requires-Dist: contextily>=1.6; extra == "example" +Requires-Dist: seaborn>=0.13; extra == "example" +Requires-Dist: cairocffi>=1.7; extra == "example" +Requires-Dist: igraph>=0.11; extra == "example" +Requires-Dist: scikit-learn>=1.5; extra == "example" +Provides-Extra: extra +Requires-Dist: lxml>=4.6; extra == "extra" +Requires-Dist: pygraphviz>=1.14; extra == "extra" +Requires-Dist: pydot>=3.0.1; extra == "extra" +Requires-Dist: sympy>=1.10; extra == "extra" +Provides-Extra: test +Requires-Dist: pytest>=7.2; extra == "test" +Requires-Dist: pytest-cov>=4.0; extra == "test" +Requires-Dist: pytest-xdist>=3.0; extra == "test" +Provides-Extra: test-extras +Requires-Dist: pytest-mpl; extra == "test-extras" +Requires-Dist: pytest-randomly; extra == "test-extras" +Dynamic: license-file + +NetworkX +======== + + +.. image:: + https://github.com/networkx/networkx/workflows/test/badge.svg?branch=main + :target: https://github.com/networkx/networkx/actions?query=workflow%3Atest + +.. image:: + https://codecov.io/gh/networkx/networkx/branch/main/graph/badge.svg? + :target: https://app.codecov.io/gh/networkx/networkx/branch/main + +.. image:: + https://img.shields.io/pypi/v/networkx.svg? + :target: https://pypi.python.org/pypi/networkx + +.. image:: + https://img.shields.io/pypi/l/networkx.svg? + :target: https://github.com/networkx/networkx/blob/main/LICENSE.txt + +.. image:: + https://img.shields.io/pypi/pyversions/networkx.svg? + :target: https://pypi.python.org/pypi/networkx + +.. image:: + https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute + :target: https://github.com/networkx/networkx/contribute + + +NetworkX is a Python package for the creation, manipulation, +and study of the structure, dynamics, and functions +of complex networks. + +- **Website (including documentation):** https://networkx.org +- **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss +- **Source:** https://github.com/networkx/networkx +- **Bug reports:** https://github.com/networkx/networkx/issues +- **Report a security vulnerability:** https://tidelift.com/security +- **Tutorial:** https://networkx.org/documentation/latest/tutorial.html +- **GitHub Discussions:** https://github.com/networkx/networkx/discussions +- **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz +- **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics + +Simple example +-------------- + +Find the shortest path between two nodes in an undirected graph: + +.. code:: pycon + + >>> import networkx as nx + >>> G = nx.Graph() + >>> G.add_edge("A", "B", weight=4) + >>> G.add_edge("B", "D", weight=2) + >>> G.add_edge("A", "C", weight=3) + >>> G.add_edge("C", "D", weight=4) + >>> nx.shortest_path(G, "A", "D", weight="weight") + ['A', 'B', 'D'] + +Install +------- + +Install the latest released version of NetworkX: + +.. code:: shell + + $ pip install networkx + +Install with all optional dependencies: + +.. code:: shell + + $ pip install networkx[default] + +For additional details, +please see the `installation guide `_. + +Bugs +---- + +Please report any bugs that you find `here `_. +Or, even better, fork the repository on `GitHub `_ +and create a pull request (PR). We welcome all changes, big or small, and we +will help you make the PR if you are new to `git` (just ask on the issue and/or +see the `contributor guide `_). + +License +------- + +Released under the `3-clause BSD license `_:: + + Copyright (c) 2004-2025, NetworkX Developers + Aric Hagberg + Dan Schult + Pieter Swart diff --git a/shared/package-files/18/18b3ba5853ae9d9f24d0e9b483555b196d98e6e38fd08544a3fa4818ef07a0dc/repr.py b/shared/package-files/18/18b3ba5853ae9d9f24d0e9b483555b196d98e6e38fd08544a3fa4818ef07a0dc/repr.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4b756abbab77c3eb0fd77ee1f0bd97382c36fb --- /dev/null +++ b/shared/package-files/18/18b3ba5853ae9d9f24d0e9b483555b196d98e6e38fd08544a3fa4818ef07a0dc/repr.py @@ -0,0 +1,339 @@ +""" +A Printer for generating executable code. + +The most important function here is srepr that returns a string so that the +relation eval(srepr(expr))=expr holds in an appropriate environment. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core.function import AppliedUndef +from sympy.core.mul import Mul +from mpmath.libmp import repr_dps, to_str as mlib_to_str + +from .printer import Printer, print_function + + +class ReprPrinter(Printer): + printmethod = "_sympyrepr" + + _default_settings: dict[str, Any] = { + "order": None, + "perm_cyclic" : True, + } + + def reprify(self, args, sep): + """ + Prints each item in `args` and joins them with `sep`. + """ + return sep.join([self.doprint(item) for item in args]) + + def emptyPrinter(self, expr): + """ + The fallback printer. + """ + if isinstance(expr, str): + return expr + elif hasattr(expr, "__srepr__"): + return expr.__srepr__() + elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"): + l = [] + for o in expr.args: + l.append(self._print(o)) + return expr.__class__.__name__ + '(%s)' % ', '.join(l) + elif hasattr(expr, "__module__") and hasattr(expr, "__name__"): + return "<'%s.%s'>" % (expr.__module__, expr.__name__) + else: + return str(expr) + + def _print_Add(self, expr, order=None): + args = self._as_ordered_terms(expr, order=order) + args = map(self._print, args) + clsname = type(expr).__name__ + return clsname + "(%s)" % ", ".join(args) + + def _print_Cycle(self, expr): + return expr.__repr__() + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation, Cycle + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=7, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + if not expr.size: + return 'Permutation()' + # before taking Cycle notation, see if the last element is + # a singleton and move it to the head of the string + s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] + last = s.rfind('(') + if not last == 0 and ',' not in s[last:]: + s = s[last:] + s[:last] + return 'Permutation%s' %s + else: + s = expr.support() + if not s: + if expr.size < 5: + return 'Permutation(%s)' % str(expr.array_form) + return 'Permutation([], size=%s)' % expr.size + trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size + use = full = str(expr.array_form) + if len(trim) < len(full): + use = trim + return 'Permutation(%s)' % use + + def _print_Function(self, expr): + r = self._print(expr.func) + r += '(%s)' % ', '.join([self._print(a) for a in expr.args]) + return r + + def _print_Heaviside(self, expr): + # Same as _print_Function but uses pargs to suppress default value for + # 2nd arg. + r = self._print(expr.func) + r += '(%s)' % ', '.join([self._print(a) for a in expr.pargs]) + return r + + def _print_FunctionClass(self, expr): + if issubclass(expr, AppliedUndef): + return 'Function(%r)' % (expr.__name__) + else: + return expr.__name__ + + def _print_Half(self, expr): + return 'Rational(1, 2)' + + def _print_RationalConstant(self, expr): + return str(expr) + + def _print_AtomicExpr(self, expr): + return str(expr) + + def _print_NumberSymbol(self, expr): + return str(expr) + + def _print_Integer(self, expr): + return 'Integer(%i)' % expr.p + + def _print_Complexes(self, expr): + return 'Complexes' + + def _print_Integers(self, expr): + return 'Integers' + + def _print_Naturals(self, expr): + return 'Naturals' + + def _print_Naturals0(self, expr): + return 'Naturals0' + + def _print_Rationals(self, expr): + return 'Rationals' + + def _print_Reals(self, expr): + return 'Reals' + + def _print_EmptySet(self, expr): + return 'EmptySet' + + def _print_UniversalSet(self, expr): + return 'UniversalSet' + + def _print_EmptySequence(self, expr): + return 'EmptySequence' + + def _print_list(self, expr): + return "[%s]" % self.reprify(expr, ", ") + + def _print_dict(self, expr): + sep = ", " + dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()] + return "{%s}" % sep.join(dict_kvs) + + def _print_set(self, expr): + if not expr: + return "set()" + return "{%s}" % self.reprify(expr, ", ") + + def _print_MatrixBase(self, expr): + # special case for some empty matrices + if (expr.rows == 0) ^ (expr.cols == 0): + return '%s(%s, %s, %s)' % (expr.__class__.__name__, + self._print(expr.rows), + self._print(expr.cols), + self._print([])) + l = [] + for i in range(expr.rows): + l.append([]) + for j in range(expr.cols): + l[-1].append(expr[i, j]) + return '%s(%s)' % (expr.__class__.__name__, self._print(l)) + + def _print_BooleanTrue(self, expr): + return "true" + + def _print_BooleanFalse(self, expr): + return "false" + + def _print_NaN(self, expr): + return "nan" + + def _print_Mul(self, expr, order=None): + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + args = map(self._print, args) + clsname = type(expr).__name__ + return clsname + "(%s)" % ", ".join(args) + + def _print_Rational(self, expr): + return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q)) + + def _print_PythonRational(self, expr): + return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q) + + def _print_Fraction(self, expr): + return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator)) + + def _print_Float(self, expr): + r = mlib_to_str(expr._mpf_, repr_dps(expr._prec)) + return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec) + + def _print_Sum2(self, expr): + return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i), + self._print(expr.a), self._print(expr.b)) + + def _print_Str(self, s): + return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) + + def _print_Symbol(self, expr): + d = expr._assumptions_orig + # print the dummy_index like it was an assumption + if expr.is_Dummy: + d = d.copy() + d['dummy_index'] = expr.dummy_index + + if d == {}: + return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name)) + else: + attr = ['%s=%s' % (k, v) for k, v in d.items()] + return "%s(%s, %s)" % (expr.__class__.__name__, + self._print(expr.name), ', '.join(attr)) + + def _print_CoordinateSymbol(self, expr): + d = expr._assumptions.generator + + if d == {}: + return "%s(%s, %s)" % ( + expr.__class__.__name__, + self._print(expr.coord_sys), + self._print(expr.index) + ) + else: + attr = ['%s=%s' % (k, v) for k, v in d.items()] + return "%s(%s, %s, %s)" % ( + expr.__class__.__name__, + self._print(expr.coord_sys), + self._print(expr.index), + ', '.join(attr) + ) + + def _print_Predicate(self, expr): + return "Q.%s" % expr.name + + def _print_AppliedPredicate(self, expr): + # will be changed to just expr.args when args overriding is removed + args = expr._args + return "%s(%s)" % (expr.__class__.__name__, self.reprify(args, ", ")) + + def _print_str(self, expr): + return repr(expr) + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.reprify(expr, ", ") + + def _print_WildFunction(self, expr): + return "%s('%s')" % (expr.__class__.__name__, expr.name) + + def _print_AlgebraicNumber(self, expr): + return "%s(%s, %s)" % (expr.__class__.__name__, + self._print(expr.root), self._print(expr.coeffs())) + + def _print_PolyRing(self, ring): + return "%s(%s, %s, %s)" % (ring.__class__.__name__, + self._print(ring.symbols), self._print(ring.domain), self._print(ring.order)) + + def _print_FracField(self, field): + return "%s(%s, %s, %s)" % (field.__class__.__name__, + self._print(field.symbols), self._print(field.domain), self._print(field.order)) + + def _print_PolyElement(self, poly): + terms = list(poly.terms()) + terms.sort(key=poly.ring.order, reverse=True) + return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms)) + + def _print_FracElement(self, frac): + numer_terms = list(frac.numer.terms()) + numer_terms.sort(key=frac.field.order, reverse=True) + denom_terms = list(frac.denom.terms()) + denom_terms.sort(key=frac.field.order, reverse=True) + numer = self._print(numer_terms) + denom = self._print(denom_terms) + return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom) + + def _print_FractionField(self, domain): + cls = domain.__class__.__name__ + field = self._print(domain.field) + return "%s(%s)" % (cls, field) + + def _print_PolynomialRingBase(self, ring): + cls = ring.__class__.__name__ + dom = self._print(ring.domain) + gens = ', '.join(map(self._print, ring.gens)) + order = str(ring.order) + if order != ring.default_order: + orderstr = ", order=" + order + else: + orderstr = "" + return "%s(%s, %s%s)" % (cls, dom, gens, orderstr) + + def _print_DMP(self, p): + cls = p.__class__.__name__ + rep = self._print(p.to_list()) + dom = self._print(p.dom) + return "%s(%s, %s)" % (cls, rep, dom) + + def _print_MonogenicFiniteExtension(self, ext): + # The expanded tree shown by srepr(ext.modulus) + # is not practical. + return "FiniteExtension(%s)" % str(ext.modulus) + + def _print_ExtensionElement(self, f): + rep = self._print(f.rep) + ext = self._print(f.ext) + return "ExtElem(%s, %s)" % (rep, ext) + +@print_function(ReprPrinter) +def srepr(expr, **settings): + """return expr in repr form""" + return ReprPrinter(settings).doprint(expr) diff --git a/shared/package-files/18/18b42056c4c37401e0499f12659e1c3807376b374ee64775569af4065876fd38/dsplit.h b/shared/package-files/18/18b42056c4c37401e0499f12659e1c3807376b374ee64775569af4065876fd38/dsplit.h new file mode 100644 index 0000000000000000000000000000000000000000..b4a8b33381bfcf688ba11edfb8117e1770b31bae --- /dev/null +++ b/shared/package-files/18/18b42056c4c37401e0499f12659e1c3807376b374ee64775569af4065876fd38/dsplit.h @@ -0,0 +1,36 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] +inline ::std::vector dsplit(const at::Tensor & self, int64_t sections) { + return at::_ops::dsplit_int::call(self, sections); +} + +// aten::dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] +inline ::std::vector dsplit(const at::Tensor & self, at::IntArrayRef indices) { + return at::_ops::dsplit_array::call(self, indices); +} + +} diff --git a/shared/package-files/18/18bdbe7fdcde52ec7b8239f91bd0da783ef54fa3ef505ce80ec293fc54e469f1/mm.py b/shared/package-files/18/18bdbe7fdcde52ec7b8239f91bd0da783ef54fa3ef505ce80ec293fc54e469f1/mm.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f91dc342f05ce0f336d2c16546db37dcb5bd31 --- /dev/null +++ b/shared/package-files/18/18bdbe7fdcde52ec7b8239f91bd0da783ef54fa3ef505ce80ec293fc54e469f1/mm.py @@ -0,0 +1,907 @@ +# mypy: allow-untyped-defs +import functools +import logging +import re +from typing import Optional + +import torch +from torch._dynamo.utils import counters +from torch._inductor.autoheuristic.autoheuristic import AutoHeuristicSelectAlgorithm +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + context_add_strides, + context_add_using_tf32, + mm_operations, +) +from torch._inductor.codegen.cpp_gemm_template import CppGemmTemplate +from torch._inductor.virtualized import V + +from .. import config as inductor_config, ir +from ..codegen.cuda.gemm_template import CUTLASS2xGemmTemplate, CUTLASS3xGemmTemplate +from ..codegen.rocm.ck_universal_gemm_template import CKGemmTemplate +from ..codegen.wrapper import PythonWrapperCodegen +from ..ir import FlexibleLayout, is_triton +from ..lowering import register_lowering +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import ( + get_gpu_shared_memory, + get_tma_workspace_arg, + use_aten_gemm_kernels, + use_ck_gemm_template, + use_cpp_gemm_template, + use_cutlass_template, + use_max_autotune, + use_triton_template, + use_triton_tma_template, +) +from .mm_common import ( + _is_static_problem, + addmm_epilogue, + extra_mm_configs, + int8_mm_configs, + mm_args, + mm_configs, + mm_grid, + mm_options, + persistent_mm_configs, + persistent_mm_grid, + persistent_mm_options, + should_fallback_to_aten, + triton_config, +) + + +def parse_version(version_string: str) -> Optional[tuple[int, ...]]: + pattern = r"(\d+)\.(\d+)?" + match = re.match(pattern, version_string) + + if match: + return tuple(int(group) for group in match.groups()) + else: + return None + + +try: + import triton + + triton_version = parse_version(triton.__version__) + has_triton = True + if triton_version is not None: + triton_major, triton_minor = triton_version + else: + triton_major = 0 + triton_minor = 0 +except ImportError: + triton_version = None + has_triton = False + triton_major = 0 + triton_minor = 0 + +log = logging.getLogger(__name__) +aten = torch.ops.aten + +mm_template = TritonTemplate( + name="mm", + grid=mm_grid, + source=( + r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + if ((stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1)) and M >= BLOCK_M: + offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + offs_a_m = rm % M + if ((stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1)) and N >= BLOCK_N: + offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + offs_b_n = rn % N + offs_k = tl.arange(0, BLOCK_K) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for k_idx in range(0, tl.cdiv(K, BLOCK_K)): + {% if not EVEN_K %} + a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K) + b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K) + {% endif %} + a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K) + b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K) + + idx_m = offs_a_m[:, None] + idx_n = a_k_idx_vals + {{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask", indent_width=8)}} + + idx_m = b_k_idx_vals + idx_n = offs_b_n[None, :] + {{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask", indent_width=8)}} + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""" + if (torch.version.hip is None) + or (has_triton and triton_major >= 3 and triton_minor >= 3) + # FIXME: To get around rocm failures like https://github.com/pytorch/pytorch/actions/runs/13123783322/job/36617154943 + # The only difference between the two templates is M >= BLOCK_M and N >= BLOCK_N checking. + # See more details in https://github.com/pytorch/pytorch/pull/146293 + else r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + if (stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1): + offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + offs_a_m = rm % M + if (stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1): + offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + offs_b_n = rn % N + offs_k = tl.arange(0, BLOCK_K) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for k_idx in range(0, tl.cdiv(K, BLOCK_K)): + {% if not EVEN_K %} + a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K) + b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K) + {% endif %} + a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K) + b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K) + + idx_m = offs_a_m[:, None] + idx_n = a_k_idx_vals + {{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask", indent_width=8)}} + + idx_m = b_k_idx_vals + idx_n = offs_b_n[None, :] + {{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask", indent_width=8)}} + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""" + ), +) + +persistent_tma_mm_template = TritonTemplate( + name="mm_persistent_tma", + grid=persistent_mm_grid, + source=r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + + start_pid = tl.program_id(0) + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + k_tiles = tl.cdiv(K, BLOCK_K) + num_tiles = grid_m * grid_n + tiles_per_SM = num_tiles // NUM_SMS + if start_pid < num_tiles % NUM_SMS: + tiles_per_SM += 1 + + tile_id = start_pid - NUM_SMS + ki = -1 + + width = GROUP_M * grid_n + rk_for_mask = tl.arange(0, BLOCK_K) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + workspace_base = ws_ptr + start_pid * 2 * TMA_SIZE + a_desc_ptr = workspace_base + b_desc_ptr = workspace_base + TMA_SIZE + + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=a_desc_ptr, + global_address=A, + load_size=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + global_size=[M, K] if A_ROW_MAJOR else [K, M], + element_ty=A.dtype.element_ty, + ) + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=b_desc_ptr, + global_address=B, + load_size=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + global_size=[K, N] if B_ROW_MAJOR else [N, K], + element_ty=B.dtype.element_ty, + ) + + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(a_desc_ptr) + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(b_desc_ptr) + + pid_m = 0 + pid_n = 0 + rm = 0 + rn = 0 + + for _ in range(0, k_tiles * tiles_per_SM): + ki = tl.where(ki == k_tiles - 1, 0, ki + 1) + if ki == 0: + tile_id += NUM_SMS + # re-order program ID for better L2 performance + group_id = tile_id // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (tile_id % group_size) + pid_n = (tile_id % width) // (group_size) + + rm = pid_m * BLOCK_M + rn = pid_n * BLOCK_N + + rk = ki * BLOCK_K + + a = tl._experimental_descriptor_load( + a_desc_ptr, + [rm, rk] if A_ROW_MAJOR else [rk, rm], + [BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + A.dtype.element_ty, + ) + b = tl._experimental_descriptor_load( + b_desc_ptr, + [rk, rn] if B_ROW_MAJOR else [rn, rk], + [BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + B.dtype.element_ty, + ) + acc += tl.dot( + a if A_ROW_MAJOR else a.T, + b if B_ROW_MAJOR else b.T, + allow_tf32=ALLOW_TF32, + ) + + if ki == k_tiles - 1: + # rematerialize rm and rn to save registers + rcm = rm + tl.arange(0, BLOCK_M) + rcn = rn + tl.arange(0, BLOCK_N) + idx_m = rcm[:, None] + idx_n = rcn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask", indent_width=12)}} + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) +""", +) + + +# prevent duplication registration of extern functions +@functools.lru_cache(None) +def lazy_register_extern_choice(fn): + return ExternKernelChoice(fn) + + +aten_mm = ExternKernelChoice(torch.mm, "at::mm_out") + +aten_addmm = ExternKernelChoice( + torch.addmm, "at::addmm_out", op_overload=aten.addmm.default +) + +aten__int_mm = ExternKernelChoice(torch._int_mm, "at::_int_mm_out") + +aten__sparse_semi_structured_mm = ExternKernelChoice( + torch._sparse_semi_structured_mm, + "at::_sparse_semi_structured_mm", + has_out_variant=False, +) + + +def _is_int8_mat(mat): + return mat.get_dtype() in (torch.int8, torch.uint8) + + +def _is_large_block_for_cpu(m, n, k): + # Thresholds are experimentally determined to reduce Triton CPU compile times + return m * n > 2**13 + + +def mm_config_kwargs(device): + if device == "cpu": + return { + "scale": 0.5, + "exclude": _is_large_block_for_cpu, + } + return {} + + +def bias_addmm(inp, mat1, mat2, *, out=None, alpha=1, beta=1): + """ + Giving torch.addmm a 1D tensor calls a different (faster) cublasLt + kernel under the hood. There are a few shapes where this is slower, + but they are rare. + """ + if inp.stride(0) == 0 or inp.size(0) == 1: + return torch.addmm(inp[0], mat1, mat2, out=out, alpha=alpha, beta=beta) + return torch.addmm(inp, mat1, mat2, out=out, alpha=alpha, beta=beta) + + +aten_bias_addmm = ExternKernelChoice(bias_addmm, None) + + +@register_lowering(aten.mm, type_promotion_kind=None) +def tuned_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + name = "mm" + + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten.mm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.mm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + aten_layout = layout + if not use_max_autotune(): + aten_layout = FlexibleLayout( + device=layout.device, dtype=layout.dtype, size=layout.size + ) + + # options to tune from + choices = ( + [aten_mm.bind((mat1, mat2), aten_layout)] if use_aten_gemm_kernels() else [] + ) + static_shape, is_nonzero = _is_static_problem(layout) + if is_nonzero and use_triton_template(layout): + for config in mm_configs(m, n, k, **mm_config_kwargs(ir.get_device_type(mat1))): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + ) + if use_triton_tma_template(mat1, mat2): + for config in persistent_mm_configs( + m, n, k, **mm_config_kwargs(ir.get_device_type(mat1)) + ): + persistent_tma_mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + workspace_arg=get_tma_workspace_arg( + num_tma_descriptors=2, + device=mat1.get_device(), + ), + **mm_options(config, m, n, k, layout), + **persistent_mm_options(mat1, mat2), + ) + + if is_nonzero and use_cutlass_template(layout, m, n, k): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices(choices, layout, [mat1, mat2]) + + if is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices(choices, layout, [mat1, mat2]) + + if use_cpp_gemm_template(layout, mat1, mat2): + CppGemmTemplate.add_choices( + choices, + layout, + [mat1, mat2], + ) + + input_nodes = [mat1, mat2] + if ( + is_nonzero + and use_triton_template(layout) + and torch._inductor.config.run_autoheuristic(name) + and is_triton(mat1) + ): + always_included = [] + if use_aten_gemm_kernels(): + always_included.append("extern_mm") + num_choices_before_extra_configs = len(choices) + for config in extra_mm_configs( + m, n, k, **mm_config_kwargs(ir.get_device_type(mat1)) + ): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + ) + + # using AutoHeuristic for ranking + ah_choices = mm_autoheuristic( + mat1, + mat2, + m, + n, + k, + choices, + name, + input_nodes, + mm_operations(), + None, + top_k=10, + always_included=always_included, + ) + if not torch._inductor.config.collect_autoheuristic(name): + # if we are collecting data, we do not want to modify choices + if ah_choices is not None and len(ah_choices) > 0: + # the order in which autoheuristic returns choices is not the same as + # as the order of choices, which affects things like epilogue fusion. + # once epilogue fusion benchmarks choices in sorted order, I think we can + # just use the order returned by autoheuristic + choices = [choice for choice in choices if choice in ah_choices] + else: + choices = choices[:num_choices_before_extra_configs] + + for k in inductor_config.external_matmul: + choices.append(lazy_register_extern_choice(k).bind((mat1, mat2), layout)) + + if should_fallback_to_aten(choices): + return aten_mm.bind((mat1, mat2), aten_layout).output_node() + + return autotune_select_algorithm(name, choices, [mat1, mat2], layout) + + +@register_lowering(aten._int_mm, type_promotion_kind=None) +def tuned_int_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=torch.int32 + ) + + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten._int_mm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten._int_mm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + static_shape, is_nonzero = _is_static_problem(layout) + use_cutlass = static_shape and is_nonzero and use_cutlass_template(layout, m, n, k) + + choices = ( + [aten__int_mm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + ) + + if use_cutlass: + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, [mat1, mat2], fuseable=True, non_fuseable=True + ) + if is_nonzero and use_triton_template(layout, enable_int32=True): + for config in int8_mm_configs( + m, n, k, **mm_config_kwargs(ir.get_device_type(mat1)) + ): + mm_template.maybe_append_choice( + choices, + input_nodes=(mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + ) + + if should_fallback_to_aten(choices): + return aten__int_mm.bind((mat1, mat2), layout).output_node() + + return autotune_select_algorithm("int_mm", choices, [mat1, mat2], layout) + + +@register_lowering(aten.addmm, type_promotion_kind=None) +def tuned_addmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + ordered_kwargs_for_cpp_kernel = ("beta", "alpha") + m, n, k, layout, mat1, mat2, inp_expanded = mm_args(mat1, mat2, inp, layout=layout) + static_shape, is_nonzero = _is_static_problem(layout) + + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten.addmm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.addmm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + if (not is_nonzero) or (not use_max_autotune()): + # Use a FlexibleLayout if we are not autotuning. + # This allows padding strides for the output. + from torch._inductor.ir import FixedLayout, FlexibleLayout + + if isinstance(layout, FixedLayout): + layout = FlexibleLayout( + device=layout.device, dtype=layout.dtype, size=layout.size + ) + choices = ( + [ + aten_addmm.bind( + (inp, mat1, mat2), + layout, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + return autotune_select_algorithm("addmm", choices, [inp, mat1, mat2], layout) + + choices = ( + [ + aten_addmm.bind( + (inp_expanded, mat1, mat2), + layout, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + + if ( + use_aten_gemm_kernels() + and inp_expanded.get_stride()[0] == 0 + and inp_expanded.get_device().type == "cuda" + and inductor_config.triton.autotune_cublasLt + ): + # unexpand inp to make sure fused addmm from cublasLt is used + choices.insert( + 0, + aten_bias_addmm.bind( + (inp_expanded, mat1, mat2), layout, alpha=alpha, beta=beta + ), + ) + + if is_nonzero and use_triton_template(layout): + for config in mm_configs(m, n, k, **mm_config_kwargs(ir.get_device_type(mat1))): + mm_template.maybe_append_choice( + choices, + input_nodes=(inp_expanded, mat1, mat2), + layout=layout, + **mm_options(config, m, n, k, layout), + prefix_args=1, + epilogue_fn=addmm_epilogue(layout.dtype, alpha, beta), + ) + + if use_triton_tma_template(mat1, mat2): + for config in persistent_mm_configs( + m, n, k, **mm_config_kwargs(ir.get_device_type(mat1)) + ): + persistent_tma_mm_template.maybe_append_choice( + choices, + input_nodes=(inp_expanded, mat1, mat2), + layout=layout, + workspace_arg=get_tma_workspace_arg( + num_tma_descriptors=2, + device=mat1.get_device(), + ), + **mm_options(config, m, n, k, layout), + **persistent_mm_options(mat1, mat2), + prefix_args=1, + epilogue_fn=addmm_epilogue(layout.dtype, alpha, beta), + ) + + if static_shape and is_nonzero and use_cutlass_template(layout, m, n, k): + # Filter out a known cause of CUDA illegal memory access errors + # broadcasting on the last dim of the bias term seems not to be working + # in the linear GEMM epilogue used by addmm. + if ( + PythonWrapperCodegen.statically_known_int_or_none( + inp_expanded.layout.stride[-1] + ) + != 0 + ): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, + layout, + [mat1, mat2, inp_expanded], + alpha=alpha, + beta=beta, + input_reorder=[2, 0, 1], + ) + + if is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices( + choices, + layout, + [mat1, mat2, inp_expanded], + alpha=alpha, + beta=beta, + input_reorder=[2, 0, 1], + ) + + if use_cpp_gemm_template(layout, mat1, mat2): + CppGemmTemplate.add_choices( + choices, + layout, + [inp_expanded, mat1, mat2], + alpha=alpha, + beta=beta, + has_bias=True, + ) + + if should_fallback_to_aten(choices): + choices.append( + aten_addmm.bind( + (inp_expanded, mat1, mat2), + layout, + ordered_kwargs_for_cpp_kernel, + alpha=alpha, + beta=beta, + ) + ) + + if ( + inp_expanded.get_stride()[0] == 0 + and inp_expanded.get_device().type == "cuda" + and inductor_config.triton.autotune_cublasLt + ): + # unexpand inp to make sure fused addmm from cublasLt is used + choices.insert( + 0, + aten_bias_addmm.bind( + (inp_expanded, mat1, mat2), layout, alpha=alpha, beta=beta + ), + ) + + return autotune_select_algorithm( + "addmm", choices, [inp_expanded, mat1, mat2], layout + ) + + +@register_lowering(aten._sparse_semi_structured_mm, type_promotion_kind=None) +def tuned_sparse_semi_structured_mm( + mat1, mat1_meta, mat2, *, out_dtype=None, layout=None +): + from torch._inductor.select_algorithm import realize_inputs + + mat1, mat1_meta, mat2 = realize_inputs(mat1, mat1_meta, mat2) + m1, k1 = mat1.get_size() + m2, _ = mat1_meta.get_size() + k2, n = mat2.get_size() + m = V.graph.sizevars.guard_equals(m1, m2) + k = V.graph.sizevars.guard_equals(2 * k1, k2) + + if layout is None: + from torch._inductor.ir import FixedLayout + + layout = FixedLayout( + mat2.get_device(), + out_dtype if out_dtype else mat2.get_dtype(), + [m, n], + [n, 1], + ) + else: + assert out_dtype is None, "out_dtype is ignored if layout is specified." + + choices = ( + [ + aten__sparse_semi_structured_mm.bind( + (mat1, mat1_meta, mat2), layout, out_dtype=out_dtype + ) + ] + if use_aten_gemm_kernels() + else [] + ) + + if m * n != 0 and use_cutlass_template(layout, m, n, k): + CUTLASS2xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, [mat1, mat2, mat1_meta], fuseable=True, non_fuseable=True + ) + + return autotune_select_algorithm( + "sparse_semi_structured_mm", choices, [mat1, mat1_meta, mat2], layout + ) + + +@functools.lru_cache(None) +def _is_sm7x_or_older_gpu(index: Optional[int]) -> bool: + props = torch.cuda.get_device_properties(index or 0) + return props.major <= 7 + + +def dims_are_int(dims): + return all(isinstance(dim, int) for dim in dims) + + +def try_heuristic(m, n, k, choices, mat1, mat2, mat2_dtype, layout): + m, n, k = get_size_hints(mat1, mat2, m, n, k) + if not dims_are_int([m, n, k]): + return None + + if mat1.dtype != torch.float16: + return None + + # only use heuristic if we are running on an A100 + # torch.cuda.get_device_capability() >= (8, 0) returns true for A10G + # which does not have enough shared memory for one of the configs + if ( + not torch.cuda.get_device_capability() >= (8, 0) + ) or get_gpu_shared_memory() != 166912: + return None + + if m == 1 and (n % 16 != 0 or k % 16 != 0): + return None + + if m <= 16 and n >= 4096 and k >= 4096: + return triton_config( + BLOCK_M=16, + BLOCK_N=64, + BLOCK_K=128, + num_stages=5, + num_warps=4, + ) + elif m > 16 and m <= 32 and n >= 4096 and k >= 4096: + return triton_config( + BLOCK_M=32, + BLOCK_N=32, + BLOCK_K=128, + num_stages=5, + num_warps=4, + ) + elif m > 32 and m <= 64 and n >= 4096 and k >= 4096: + return triton_config( + BLOCK_M=64, + BLOCK_N=32, + BLOCK_K=128, + num_stages=5, + num_warps=4, + ) + return None + + +def mm_autoheuristic( + mat1, + mat2, + m, + n, + k, + choices, + name, + input_nodes, + ops, + precondition, + top_k: Optional[int] = None, + always_included=None, +): + m, n, k = get_size_hints(mat1, mat2, m, n, k) + if not dims_are_int([m, n, k]): + return None + mat1_stride, mat2_stride = get_size_hints_strides(mat1, mat2) + + def get_context(m, k, n, mat1, mat2, mat1_stride, mat2_stride): + context = AHContext() + context.add_feature("m", m) + context.add_feature("k", k) + context.add_feature("n", n) + context.add_feature("mat1_dtype", mat1.layout.dtype, is_categorical=True) + context.add_feature("mat2_dtype", mat2.layout.dtype, is_categorical=True) + context_add_strides(context, "mat1", mat1_stride) + context_add_strides(context, "mat2", mat2_stride) + context.add_feature( + "mat1_iscontig", mat1.layout.is_contiguous(), is_categorical=True + ) + context.add_feature( + "mat2_iscontig", mat2.layout.is_contiguous(), is_categorical=True + ) + if name == "mm": + # for mixed_mm, we only consider fp16 + context_add_using_tf32(context, mat1.layout.dtype) + return context + + def fallback(): + return None + + context = get_context(m, k, n, mat1, mat2, mat1_stride, mat2_stride) + autoheuristic = AutoHeuristicSelectAlgorithm( + fallback=fallback, + choices=choices, + input_nodes=input_nodes, + context=context, + name=name, + augment_context=ops, + precondition=precondition, + ) + + if top_k is not None: + # TODO: is there a cleaner way to ensure aten.mm is always included? + return autoheuristic.get_top_k_choices_caller( + top_k, always_included=always_included + ) + + return autoheuristic.get_choice_caller() + + +def get_size_hints(mat1, mat2, m, n, k): + if not isinstance(m, int) or not isinstance(k, int): + (m, k) = V.graph.sizevars.size_hints( + mat1.get_size(), + fallback=torch._inductor.config.unbacked_symint_fallback, + ) + + if not isinstance(n, int) or not isinstance(k, int): + (k, n) = V.graph.sizevars.size_hints( + mat2.get_size(), + fallback=torch._inductor.config.unbacked_symint_fallback, + ) + return m, n, k + + +def get_size_hints_strides(mat1, mat2): + mat1_stride = mat1.layout.stride + mat2_stride = mat2.layout.stride + strides = [mat1_stride, mat2_stride] + strides_hints = [] + for stride in strides: + if not isinstance(stride, int): + stride = V.graph.sizevars.size_hints( + stride, + fallback=torch._inductor.config.unbacked_symint_fallback, + ) + strides_hints.append(stride) + return strides_hints[0], strides_hints[1] diff --git a/shared/package-files/18/18cdece8a1d664be7d7f959bc73de325696f069901742b7a85ce8b184a31af45/to_padded_tensor_ops.h b/shared/package-files/18/18cdece8a1d664be7d7f959bc73de325696f069901742b7a85ce8b184a31af45/to_padded_tensor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2c5d7826dbbf131e2751f10d3e6828868e641f26 --- /dev/null +++ b/shared/package-files/18/18cdece8a1d664be7d7f959bc73de325696f069901742b7a85ce8b184a31af45/to_padded_tensor_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API to_padded_tensor { + using schema = at::Tensor (const at::Tensor &, double, at::OptionalSymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::to_padded_tensor"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size); +}; + +struct TORCH_API to_padded_tensor_out { + using schema = at::Tensor & (const at::Tensor &, double, at::OptionalSymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::to_padded_tensor"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "to_padded_tensor.out(Tensor self, float padding, SymInt[]? output_size=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/18/18cdfeb95b105dd9b91758b538f3ba31678863be2f96dc874d989a4a14db6387/test_filelist.cpython-311.pyc b/shared/package-files/18/18cdfeb95b105dd9b91758b538f3ba31678863be2f96dc874d989a4a14db6387/test_filelist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d8ae80303c2cf15c6a49038c7659bb6ba5c4ff2 Binary files /dev/null and b/shared/package-files/18/18cdfeb95b105dd9b91758b538f3ba31678863be2f96dc874d989a4a14db6387/test_filelist.cpython-311.pyc differ diff --git a/shared/package-files/18/18cee2ad59a0bf2bec7d88dc66df60c4c7d948a509836cccd985542326b2cb48/_thnn_differentiable_lstm_cell_backward_native.h b/shared/package-files/18/18cee2ad59a0bf2bec7d88dc66df60c4c7d948a509836cccd985542326b2cb48/_thnn_differentiable_lstm_cell_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..fb3222fbb5b51cf2530c65221bff1b16c9127740 --- /dev/null +++ b/shared/package-files/18/18cee2ad59a0bf2bec7d88dc66df60c4c7d948a509836cccd985542326b2cb48/_thnn_differentiable_lstm_cell_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _thnn_differentiable_lstm_cell_backward(const ::std::optional & grad_hy, const ::std::optional & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const ::std::optional & input_bias, const ::std::optional & hidden_bias, const at::Tensor & cx, const at::Tensor & cy); +} // namespace native +} // namespace at diff --git a/shared/package-files/18/18d299f8e24155e14eaeec965222ab983b1564e4ebf210cef9cef96c7d66e6c3/_named_member_accessor.cpython-311.pyc b/shared/package-files/18/18d299f8e24155e14eaeec965222ab983b1564e4ebf210cef9cef96c7d66e6c3/_named_member_accessor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64d19716308dbcc3848d056931ee9e67f551c971 Binary files /dev/null and b/shared/package-files/18/18d299f8e24155e14eaeec965222ab983b1564e4ebf210cef9cef96c7d66e6c3/_named_member_accessor.cpython-311.pyc differ diff --git a/shared/package-files/18/18d663665b758cd23d23ca17ef3ea0a1ae55636ca32226cffaf923bbdbed2882/impl.cpython-311.pyc b/shared/package-files/18/18d663665b758cd23d23ca17ef3ea0a1ae55636ca32226cffaf923bbdbed2882/impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19a82cd86e3437cc641dea3f1857a4b93a8a035a Binary files /dev/null and b/shared/package-files/18/18d663665b758cd23d23ca17ef3ea0a1ae55636ca32226cffaf923bbdbed2882/impl.cpython-311.pyc differ diff --git a/shared/package-files/18/18da90c989aec886a37e339b00c9a2b8dfceb413c40b0cd6895c839b3a1efa77/clamp_max_native.h b/shared/package-files/18/18da90c989aec886a37e339b00c9a2b8dfceb413c40b0cd6895c839b3a1efa77/clamp_max_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4d60cf31c53f6c0f73c57ff2bda9ed456b0848f8 --- /dev/null +++ b/shared/package-files/18/18da90c989aec886a37e339b00c9a2b8dfceb413c40b0cd6895c839b3a1efa77/clamp_max_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_clamp_max_out : public at::meta::structured_clamp_max { +void impl(const at::Tensor & self, const at::Scalar & max, const at::Tensor & out); +}; +struct TORCH_API structured_clamp_max_Tensor_out : public at::meta::structured_clamp_max_Tensor { +void impl(const at::Tensor & self, const at::Tensor & max, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/18/18df6c8490de5c76824ac027bc156260b1e0bf9f090315ac6c0009c5b6ada9fb/build_clib.cpython-311.pyc b/shared/package-files/18/18df6c8490de5c76824ac027bc156260b1e0bf9f090315ac6c0009c5b6ada9fb/build_clib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6855fc0b8d6c0b0275d2aa37eda853395a2afe33 Binary files /dev/null and b/shared/package-files/18/18df6c8490de5c76824ac027bc156260b1e0bf9f090315ac6c0009c5b6ada9fb/build_clib.cpython-311.pyc differ diff --git a/shared/package-files/18/18e968109660ae710c1b29d2c5318467038578353fff08da1ba0d51ddf54e4fa/test_libalgos.cpython-311.pyc b/shared/package-files/18/18e968109660ae710c1b29d2c5318467038578353fff08da1ba0d51ddf54e4fa/test_libalgos.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4692288ec49814362c8e80461b0d009f5549ab Binary files /dev/null and b/shared/package-files/18/18e968109660ae710c1b29d2c5318467038578353fff08da1ba0d51ddf54e4fa/test_libalgos.cpython-311.pyc differ diff --git a/shared/package-files/18/18e9edf36d887add5ff87c0da1ac1ee80675f5230390403db70b0fc8d8985b3f/python_symnode.h b/shared/package-files/18/18e9edf36d887add5ff87c0da1ac1ee80675f5230390403db70b0fc8d8985b3f/python_symnode.h new file mode 100644 index 0000000000000000000000000000000000000000..43ef85ad8fce87a3d902c033ea14bacbb9e72184 --- /dev/null +++ b/shared/package-files/18/18e9edf36d887add5ff87c0da1ac1ee80675f5230390403db70b0fc8d8985b3f/python_symnode.h @@ -0,0 +1,313 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch { + +TORCH_PYTHON_API py::handle get_symint_class(); +TORCH_PYTHON_API py::handle get_symfloat_class(); +TORCH_PYTHON_API py::handle get_symbool_class(); + +// NB: These functions must not be called too early, otherwise torch not setup. +// Alternate design is to have torch "register" the object to us +inline bool is_symint(py::handle obj) { + return py::isinstance(obj, get_symint_class()); +} +inline bool is_symfloat(py::handle obj) { + return py::isinstance(obj, get_symfloat_class()); +} +inline bool is_symbool(py::handle obj) { + return py::isinstance(obj, get_symbool_class()); +} + +namespace impl { + +// This c10::SymNodeImpl simply backends to a Python object that +// implements the API. The Python object is the source of truth, +// this is just an adapter so C++ calls can get to the object. +class PythonSymNodeImpl : public c10::SymNodeImpl { + public: + PythonSymNodeImpl(py::object pyobj) : c10::SymNodeImpl() { + pyobj_ = std::make_shared( + pyobj.release().ptr(), getPyInterpreter()); + } + + c10::SymNode wrap_int(int64_t num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_int")(num); + return c10::make_intrusive(std::move(r)); + } + + c10::SymNode wrap_float(double num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_float")(num); + return c10::make_intrusive(std::move(r)); + } + + c10::SymNode wrap_bool(bool num) override { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr("wrap_bool")(num); + return c10::make_intrusive(std::move(r)); + } + +#define TORCH_SYMNODE_SIZES_STRIDES(n) \ + c10::SymNode n( \ + c10::ArrayRef sizes, c10::ArrayRef strides) \ + override { \ + py::gil_scoped_acquire acquire; \ + auto r = getPyObj().attr(#n)(sizes, strides); \ + return c10::make_intrusive(std::move(r)); \ + } + + // clang-format off + TORCH_SYMNODE_SIZES_STRIDES(is_contiguous) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_contiguous_2d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_contiguous_3d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_strides_2d) + TORCH_SYMNODE_SIZES_STRIDES(is_channels_last_strides_3d) + TORCH_SYMNODE_SIZES_STRIDES(is_non_overlapping_and_dense) + // clang-format on + +#undef TORCH_SYMNODE_SIZES_STRIDES + + bool bool_() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("bool_")().is(py::handle(Py_True)); + } + + bool is_int() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_int")().is(py::handle(Py_True)); + } + + bool is_float() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_float")().is(py::handle(Py_True)); + } + + bool is_bool() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_bool")().is(py::handle(Py_True)); + } + + bool is_nested_int() const override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("is_nested_int")().is(py::handle(Py_True)); + } + + bool has_hint() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("has_hint")().is(py::handle(Py_True)); + } + + int64_t guard_int(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_int")(file, line).cast(); + } + + double guard_float(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_float")(file, line).cast(); + } + + bool guard_bool(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_bool")(file, line).cast(); + } + + bool expect_true(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("expect_true")(file, line).cast(); + } + + bool expect_size(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("expect_size")(file, line).cast(); + } + + bool guard_size_oblivious(const char* file, int64_t line) override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("guard_size_oblivious")(file, line).cast(); + } + + int64_t int_() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("int_")().cast(); + } + + std::optional maybe_as_int() override { + py::gil_scoped_acquire acquire; + const auto& r = getPyObj().attr("maybe_as_int")(); + if (r.is_none()) { + return std::nullopt; + } else { + return r.cast(); + } + } + + std::string str() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("str")().cast(); + } + + std::string _graph_repr() override { + py::gil_scoped_acquire acquire; + return getPyObj().attr("_graph_repr")().cast(); + } + + c10::SymNode dispatch_sym_ite_( + const char* fname, + const c10::SymNode& other, + const c10::SymNode& third) { + auto pother = dynamic_cast(other.get()); + auto pthird = dynamic_cast(third.get()); + TORCH_CHECK(pother); + TORCH_CHECK(pthird); + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(pother->getPyObj(), pthird->getPyObj()); + return c10::make_intrusive(r); + } + + c10::SymNode dispatch_common_(const char* fname, const c10::SymNode& other) { + auto pother = dynamic_cast(other.get()); + TORCH_CHECK(pother); + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(pother->getPyObj()); + return c10::make_intrusive(r); + } + + c10::SymNode dispatch_common_(const char* fname) { + py::gil_scoped_acquire acquire; + auto r = getPyObj().attr(fname)(); + return c10::make_intrusive(r); + } + + c10::SymNode add(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sub(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode mul(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode float_truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode int_truediv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode pow(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode float_pow(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode pow_by_natural(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode floordiv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode int_floordiv(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode mod(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode eq(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode ne(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode gt(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode lt(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode le(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode ge(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_min(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + c10::SymNode sym_max(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_and(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_or(const c10::SymNode& other) override { + return dispatch_common_(__func__, other); + } + + c10::SymNode sym_ite(const c10::SymNode& other, const c10::SymNode& third) + override { + return dispatch_sym_ite_(__func__, other, third); + } + + c10::SymNode sym_not() override { + return dispatch_common_(__func__); + } + + c10::SymNode ceil() override { + return dispatch_common_(__func__); + } + + c10::SymNode floor() override { + return dispatch_common_(__func__); + } + + c10::SymNode neg() override { + return dispatch_common_(__func__); + } + + c10::SymNode clone() override { + return dispatch_common_(__func__); + } + + c10::SymNode sym_float() override { + return dispatch_common_(__func__); + } + + py::handle getPyObj() const { + return py::handle(pyobj_->ptr(getPyInterpreter())); + } + std::shared_ptr pyobj_ = nullptr; +}; + +} // namespace impl +} // namespace torch diff --git a/shared/package-files/18/18ee188b3aad2f6f95ee42eaf9ed912d6f65a27dc6b9b011524113dcdeee27bb/combining.cpython-311.pyc b/shared/package-files/18/18ee188b3aad2f6f95ee42eaf9ed912d6f65a27dc6b9b011524113dcdeee27bb/combining.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e336e079b709a470ee455c91a4cbdf5be45d1054 Binary files /dev/null and b/shared/package-files/18/18ee188b3aad2f6f95ee42eaf9ed912d6f65a27dc6b9b011524113dcdeee27bb/combining.cpython-311.pyc differ diff --git a/shared/package-files/18/18f67dcfdbf5137c186130fefc9833d723673085abe3884d61aba366fff42c85/is_inference.h b/shared/package-files/18/18f67dcfdbf5137c186130fefc9833d723673085abe3884d61aba366fff42c85/is_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..0260fce5872e785375d811b2ca2937731248e326 --- /dev/null +++ b/shared/package-files/18/18f67dcfdbf5137c186130fefc9833d723673085abe3884d61aba366fff42c85/is_inference.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::is_inference(Tensor self) -> bool +inline bool __dispatch_is_inference(const at::Tensor & self) { + return at::_ops::is_inference::call(self); +} + +} diff --git a/shared/package-files/26/260270618cc8aa960a820f27b46c8dab6d55a56e834de942288743252f7842e0/cycling_iterator.py b/shared/package-files/26/260270618cc8aa960a820f27b46c8dab6d55a56e834de942288743252f7842e0/cycling_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3b79f18dfe4ac614b4ac764562be7c34b93f6b --- /dev/null +++ b/shared/package-files/26/260270618cc8aa960a820f27b46c8dab6d55a56e834de942288743252f7842e0/cycling_iterator.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +from collections.abc import Iterator +from typing import Callable, TypeVar +from typing_extensions import Self + + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +_T = TypeVar("_T") + +__all__ = ["CyclingIterator"] + + +class CyclingIterator(Iterator[_T]): + """ + An iterator decorator that cycles through the + underlying iterator "n" times. Useful to "unroll" + the dataset across multiple training epochs. + + The generator function is called as ``generator_fn(epoch)`` + to obtain the underlying iterator, where ``epoch`` is a + number less than or equal to ``n`` representing the ``k``th cycle + + For example if ``generator_fn`` always returns ``[1,2,3]`` + then ``CyclingIterator(n=2, generator_fn)`` will iterate through + ``[1,2,3,1,2,3]`` + """ + + def __init__( + self, + n: int, + generator_fn: Callable[[int], Iterator[_T]], + start_epoch: int = 0, + ): + self._n = n + self._epoch = start_epoch + self._generator_fn = generator_fn + self._iter = generator_fn(self._epoch) + + def __iter__(self) -> Self: + return self + + def __next__(self) -> _T: + try: + return next(self._iter) + except StopIteration as eod: # eod == end of data + if self._epoch < self._n - 1: + self._epoch += 1 + self._iter = self._generator_fn(self._epoch) + return self.__next__() + else: + raise eod diff --git a/shared/package-files/26/26033f6ccad8c971a7dbaf6fdab648a50d62c50220c8c92ed3dbc72d2af765c5/_monkeytype_config.py b/shared/package-files/26/26033f6ccad8c971a7dbaf6fdab648a50d62c50220c8c92ed3dbc72d2af765c5/_monkeytype_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7a324fda8af88050469a9e68b13492be746303c3 --- /dev/null +++ b/shared/package-files/26/26033f6ccad8c971a7dbaf6fdab648a50d62c50220c8c92ed3dbc72d2af765c5/_monkeytype_config.py @@ -0,0 +1,195 @@ +# mypy: allow-untyped-defs +import inspect +import sys +import typing +from collections import defaultdict +from collections.abc import Iterable +from pathlib import Path +from types import CodeType +from typing import Optional + +import torch + + +_IS_MONKEYTYPE_INSTALLED = True +try: + import monkeytype # type: ignore[import] + from monkeytype import trace as monkeytype_trace + from monkeytype.config import _startswith, LIB_PATHS # type: ignore[import] + from monkeytype.db.base import ( # type: ignore[import] + CallTraceStore, + CallTraceStoreLogger, + CallTraceThunk, + ) + from monkeytype.tracing import CallTrace, CodeFilter # type: ignore[import] +except ImportError: + _IS_MONKEYTYPE_INSTALLED = False + + +# Checks whether a class is defind in `torch.*` modules +def is_torch_native_class(cls): + if not hasattr(cls, "__module__"): + return False + + parent_modules = cls.__module__.split(".") + if not parent_modules: + return False + + root_module = sys.modules.get(parent_modules[0]) + return root_module is torch + + +def get_type(type): + """Convert the given type to a torchScript acceptable format.""" + if isinstance(type, str): + return type + elif inspect.getmodule(type) == typing: + # If the type is a type imported from typing + # like Tuple, List, Dict then replace `typing.` + # with a null string. This needs to be done since + # typing.List is not accepted by TorchScript. + type_to_string = str(type) + return type_to_string.replace(type.__module__ + ".", "") + elif is_torch_native_class(type): + # If the type is a subtype of torch module, then TorchScript expects a fully qualified name + # for the type which is obtained by combining the module name and type name. + return type.__module__ + "." + type.__name__ + else: + # For all other types use the name for the type. + return type.__name__ + + +def get_optional_of_element_type(types): + """Extract element type, return as `Optional[element type]` from consolidated types. + + Helper function to extracts the type of the element to be annotated to Optional + from the list of consolidated types and returns `Optional[element type]`. + TODO: To remove this check once Union support lands. + """ + elem_type = types[1] if type(None) == types[0] else types[0] + elem_type = get_type(elem_type) + + # Optional type is internally converted to Union[type, NoneType], which + # is not supported yet in TorchScript. Hence, representing the optional type as string. + return "Optional[" + elem_type + "]" + + +def get_qualified_name(func): + return func.__qualname__ + + +if _IS_MONKEYTYPE_INSTALLED: + + class JitTypeTraceStoreLogger(CallTraceStoreLogger): + """A JitTypeCallTraceLogger that stores logged traces in a CallTraceStore.""" + + def __init__(self, store: CallTraceStore): + super().__init__(store) + + def log(self, trace: CallTrace) -> None: + self.traces.append(trace) + + class JitTypeTraceStore(CallTraceStore): + def __init__(self) -> None: + super().__init__() + # A dictionary keeping all collected CallTrace + # key is fully qualified name of called function + # value is list of all CallTrace + self.trace_records: dict[str, list] = defaultdict(list) + + def add(self, traces: Iterable[CallTrace]): + for t in traces: + qualified_name = get_qualified_name(t.func) + self.trace_records[qualified_name].append(t) + + def filter( + self, + qualified_name: str, + qualname_prefix: Optional[str] = None, + limit: int = 2000, + ) -> list[CallTraceThunk]: + return self.trace_records[qualified_name] + + def analyze(self, qualified_name: str) -> dict: + # Analyze the types for the given module + # and create a dictionary of all the types + # for arguments. + records = self.trace_records[qualified_name] + all_args = defaultdict(set) + for record in records: + for arg, arg_type in record.arg_types.items(): + all_args[arg].add(arg_type) + return all_args + + def consolidate_types(self, qualified_name: str) -> dict: + all_args = self.analyze(qualified_name) + # If there are more types for an argument, + # then consolidate the type to `Any` and replace the entry + # by type `Any`. + for arg, types in all_args.items(): + types = list(types) + type_length = len(types) + if type_length == 2 and type(None) in types: + # TODO: To remove this check once Union suppport in TorchScript lands. + all_args[arg] = get_optional_of_element_type(types) + elif type_length > 1: + all_args[arg] = "Any" + elif type_length == 1: + all_args[arg] = get_type(types[0]) + return all_args + + def get_args_types(self, qualified_name: str) -> dict: + return self.consolidate_types(qualified_name) + + class JitTypeTraceConfig(monkeytype.config.Config): + def __init__(self, s: JitTypeTraceStore): + super().__init__() + self.s = s + + def trace_logger(self) -> JitTypeTraceStoreLogger: + """Return a JitCallTraceStoreLogger that logs to the configured trace store.""" + return JitTypeTraceStoreLogger(self.trace_store()) + + def trace_store(self) -> CallTraceStore: + return self.s + + def code_filter(self) -> Optional[CodeFilter]: + return jit_code_filter + +else: + # When MonkeyType is not installed, we provide dummy class definitions + # for the below classes. + class JitTypeTraceStoreLogger: # type: ignore[no-redef] + def __init__(self) -> None: + pass + + class JitTypeTraceStore: # type: ignore[no-redef] + def __init__(self) -> None: + self.trace_records = None + + class JitTypeTraceConfig: # type: ignore[no-redef] + def __init__(self) -> None: + pass + + monkeytype_trace = None # type: ignore[assignment] # noqa: F811 + + +def jit_code_filter(code: CodeType) -> bool: + """Codefilter for Torchscript to trace forward calls. + + The custom CodeFilter is required while scripting a FX Traced forward calls. + FX Traced forward calls have `code.co_filename` start with '<' which is used + to exclude tracing of stdlib and site-packages in the default code filter. + Since we need all forward calls to be traced, this custom code filter + checks for code.co_name to be 'forward' and enables tracing for all such calls. + The code filter is similar to default code filter for monkeytype and + excludes tracing of stdlib and site-packages. + """ + # Filter code without a source file and exclude this check for 'forward' calls. + if code.co_name != "forward" and ( + not code.co_filename or code.co_filename[0] == "<" + ): + return False + + filename = Path(code.co_filename).resolve() + return not any(_startswith(filename, lib_path) for lib_path in LIB_PATHS) diff --git a/shared/package-files/26/2603bc519cd7459572c8883f2561eeeca32a46a80a4a4a23605d259d76911ac8/__init__.cpython-311.pyc b/shared/package-files/26/2603bc519cd7459572c8883f2561eeeca32a46a80a4a4a23605d259d76911ac8/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efd89844d1c76316c4a2a409a6166bee3606e93c Binary files /dev/null and b/shared/package-files/26/2603bc519cd7459572c8883f2561eeeca32a46a80a4a4a23605d259d76911ac8/__init__.cpython-311.pyc differ diff --git a/shared/package-files/26/260b0667b571ad60450f5a34226a81a55a32be5f98dca5397aca64398e6861f9/__init__.cpython-311.pyc b/shared/package-files/26/260b0667b571ad60450f5a34226a81a55a32be5f98dca5397aca64398e6861f9/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5458016572d626c2f8faf416f0f599b5b8b326b1 Binary files /dev/null and b/shared/package-files/26/260b0667b571ad60450f5a34226a81a55a32be5f98dca5397aca64398e6861f9/__init__.cpython-311.pyc differ diff --git a/shared/package-files/26/260df9ad147b06d5ce4b5d35d9114e74b562165542df395757efb0f1a1337fc2/python_test.cc b/shared/package-files/26/260df9ad147b06d5ce4b5d35d9114e74b562165542df395757efb0f1a1337fc2/python_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..eea6bf9459d1f2d7d709dbf04ba1179e45dcf89f --- /dev/null +++ b/shared/package-files/26/260df9ad147b06d5ce4b5d35d9114e74b562165542df395757efb0f1a1337fc2/python_test.cc @@ -0,0 +1,895 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include +#include +#include + +#include "platform.h" + +#include "arrow/array.h" +#include "arrow/array/builder_binary.h" +#include "arrow/table.h" +#include "arrow/util/decimal.h" +#include "arrow/util/logging.h" + +#include "arrow/python/arrow_to_pandas.h" +#include "arrow/python/decimal.h" +#include "arrow/python/helpers.h" +#include "arrow/python/numpy_convert.h" +#include "arrow/python/numpy_interop.h" +#include "arrow/python/python_test.h" +#include "arrow/python/python_to_arrow.h" + +#define ASSERT_EQ(x, y) \ + { \ + auto&& _left = (x); \ + auto&& _right = (y); \ + if (_left != _right) { \ + return Status::Invalid("Expected equality between `", #x, "` and `", #y, \ + "`, but ", arrow::py::testing::ToString(_left), \ + " != ", arrow::py::testing::ToString(_right)); \ + } \ + } + +#define ASSERT_NE(x, y) \ + { \ + auto&& _left = (x); \ + auto&& _right = (y); \ + if (_left == _right) { \ + return Status::Invalid("Expected inequality between `", #x, "` and `", #y, \ + "`, but ", arrow::py::testing::ToString(_left), \ + " == ", arrow::py::testing::ToString(_right)); \ + } \ + } + +#define ASSERT_FALSE(v) \ + { \ + auto&& _v = (v); \ + if (!!_v) { \ + return Status::Invalid("Expected `", #v, "` to evaluate to false, but got ", \ + arrow::py::testing::ToString(_v)); \ + } \ + } + +#define ASSERT_TRUE(v) \ + { \ + auto&& _v = (v); \ + if (!_v) { \ + return Status::Invalid("Expected `", #v, "` to evaluate to true, but got ", \ + arrow::py::testing::ToString(_v)); \ + } \ + } + +#define ASSERT_FALSE_MSG(v, msg) \ + { \ + auto&& _v = (v); \ + if (!!_v) { \ + return Status::Invalid("Expected `", #v, "` to evaluate to false, but got ", \ + arrow::py::testing::ToString(_v), ": ", msg); \ + } \ + } + +#define ASSERT_TRUE_MSG(v, msg) \ + { \ + auto&& _v = (v); \ + if (!_v) { \ + return Status::Invalid("Expected `", #v, "` to evaluate to true, but got ", \ + arrow::py::testing::ToString(_v), ": ", msg); \ + } \ + } + +#define ASSERT_OK(expr) \ + { \ + for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); !_st.ok();) \ + return Status::Invalid("`", #expr, "` failed with ", _st.ToString()); \ + } + +#define ASSERT_RAISES(code, expr) \ + { \ + for (::arrow::Status _st_expr = ::arrow::internal::GenericToStatus((expr)); \ + !_st_expr.Is##code();) \ + return Status::Invalid("Expected `", #expr, "` to fail with ", #code, \ + ", but got ", _st_expr.ToString()); \ + } + +namespace arrow { + +using internal::checked_cast; + +namespace py { +namespace testing { + +// ARROW-17938: Some standard libraries have ambiguous operator<<(nullptr_t), +// work around it using a custom printer function. + +template +std::string ToString(const T& t) { + std::stringstream ss; + ss << t; + return ss.str(); +} + +template <> +std::string ToString(const std::nullptr_t&) { + return "nullptr"; +} + +namespace { + +Status TestOwnedRefMoves() { + std::vector vec; + PyObject *u, *v; + u = PyList_New(0); + v = PyList_New(0); + + { + OwnedRef ref(u); + vec.push_back(std::move(ref)); + ASSERT_EQ(ref.obj(), nullptr); + } + vec.emplace_back(v); + ASSERT_EQ(Py_REFCNT(u), 1); + ASSERT_EQ(Py_REFCNT(v), 1); + return Status::OK(); +} + +Status TestOwnedRefNoGILMoves() { + PyAcquireGIL lock; + lock.release(); + + { + std::vector vec; + PyObject *u, *v; + { + lock.acquire(); + u = PyList_New(0); + v = PyList_New(0); + lock.release(); + } + { + OwnedRefNoGIL ref(u); + vec.push_back(std::move(ref)); + ASSERT_EQ(ref.obj(), nullptr); + } + vec.emplace_back(v); + ASSERT_EQ(Py_REFCNT(u), 1); + ASSERT_EQ(Py_REFCNT(v), 1); + return Status::OK(); + } +} + +std::string FormatPythonException(const std::string& exc_class_name, + const std::string& exc_value) { + std::stringstream ss; + ss << "Python exception: "; + ss << exc_class_name; + ss << ": "; + ss << exc_value; + ss << "\n"; + return ss.str(); +} + +Status TestCheckPyErrorStatus() { + Status st; + std::string expected_detail = ""; + + auto check_error = [](Status& st, const char* expected_message = "some error", + std::string expected_detail = "") { + st = CheckPyError(); + ASSERT_EQ(st.message(), expected_message); + ASSERT_FALSE(PyErr_Occurred()); + if (expected_detail.size() > 0) { + auto detail = st.detail(); + ASSERT_NE(detail, nullptr); + ASSERT_EQ(detail->ToString(), expected_detail); + } + return Status::OK(); + }; + + for (PyObject* exc_type : {PyExc_Exception, PyExc_SyntaxError}) { + PyErr_SetString(exc_type, "some error"); + ASSERT_OK(check_error(st)); + ASSERT_TRUE(st.IsUnknownError()); + } + + PyErr_SetString(PyExc_TypeError, "some error"); + ASSERT_OK( + check_error(st, "some error", FormatPythonException("TypeError", "some error"))); + ASSERT_TRUE(st.IsTypeError()); + + PyErr_SetString(PyExc_ValueError, "some error"); + ASSERT_OK(check_error(st)); + ASSERT_TRUE(st.IsInvalid()); + + PyErr_SetString(PyExc_KeyError, "some error"); + ASSERT_OK(check_error(st, "'some error'")); + ASSERT_TRUE(st.IsKeyError()); + + for (PyObject* exc_type : {PyExc_OSError, PyExc_IOError}) { + PyErr_SetString(exc_type, "some error"); + ASSERT_OK(check_error(st)); + ASSERT_TRUE(st.IsIOError()); + } + + PyErr_SetString(PyExc_NotImplementedError, "some error"); + ASSERT_OK(check_error(st, "some error", + FormatPythonException("NotImplementedError", "some error"))); + ASSERT_TRUE(st.IsNotImplemented()); + + // No override if a specific status code is given + PyErr_SetString(PyExc_TypeError, "some error"); + st = CheckPyError(StatusCode::SerializationError); + ASSERT_TRUE(st.IsSerializationError()); + ASSERT_EQ(st.message(), "some error"); + ASSERT_FALSE(PyErr_Occurred()); + + return Status::OK(); +} + +Status TestCheckPyErrorStatusNoGIL() { + PyAcquireGIL lock; + { + Status st; + PyErr_SetString(PyExc_ZeroDivisionError, "zzzt"); + st = ConvertPyError(); + ASSERT_FALSE(PyErr_Occurred()); + lock.release(); + ASSERT_TRUE(st.IsUnknownError()); + ASSERT_EQ(st.message(), "zzzt"); + ASSERT_EQ(st.detail()->ToString(), + FormatPythonException("ZeroDivisionError", "zzzt")); + return Status::OK(); + } +} + +Status TestRestorePyErrorBasics() { + PyErr_SetString(PyExc_ZeroDivisionError, "zzzt"); + auto st = ConvertPyError(); + ASSERT_FALSE(PyErr_Occurred()); + ASSERT_TRUE(st.IsUnknownError()); + ASSERT_EQ(st.message(), "zzzt"); + ASSERT_EQ(st.detail()->ToString(), FormatPythonException("ZeroDivisionError", "zzzt")); + + RestorePyError(st); + ASSERT_TRUE(PyErr_Occurred()); + PyObject* exc_type; + PyObject* exc_value; + PyObject* exc_traceback; + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + ASSERT_TRUE(PyErr_GivenExceptionMatches(exc_type, PyExc_ZeroDivisionError)); + std::string py_message; + ASSERT_OK(internal::PyObject_StdStringStr(exc_value, &py_message)); + ASSERT_EQ(py_message, "zzzt"); + + return Status::OK(); +} + +Status TestPyBufferInvalidInputObject() { + std::shared_ptr res; + PyObject* input = Py_None; + auto old_refcnt = Py_REFCNT(input); + { + Status st = PyBuffer::FromPyObject(input).status(); + ASSERT_TRUE_MSG(IsPyError(st), st.ToString()); + ASSERT_FALSE(PyErr_Occurred()); + } + ASSERT_EQ(old_refcnt, Py_REFCNT(input)); + return Status::OK(); +} + +// Because of how it is declared, the Numpy C API instance initialized +// within libarrow_python.dll may not be visible in this test under Windows +// ("unresolved external symbol arrow_ARRAY_API referenced"). +#ifndef _WIN32 +Status TestPyBufferNumpyArray() { + npy_intp dims[1] = {10}; + + OwnedRef arr_ref(PyArray_SimpleNew(1, dims, NPY_FLOAT)); + PyObject* arr = arr_ref.obj(); + ASSERT_NE(arr, nullptr); + auto old_refcnt = Py_REFCNT(arr); + auto buf = std::move(PyBuffer::FromPyObject(arr)).ValueOrDie(); + + ASSERT_TRUE(buf->is_cpu()); + ASSERT_EQ(buf->data(), PyArray_DATA(reinterpret_cast(arr))); + ASSERT_TRUE(buf->is_mutable()); + ASSERT_EQ(buf->mutable_data(), buf->data()); + ASSERT_EQ(old_refcnt + 1, Py_REFCNT(arr)); + buf.reset(); + ASSERT_EQ(old_refcnt, Py_REFCNT(arr)); + + // Read-only + PyArray_CLEARFLAGS(reinterpret_cast(arr), NPY_ARRAY_WRITEABLE); + buf = std::move(PyBuffer::FromPyObject(arr)).ValueOrDie(); + ASSERT_TRUE(buf->is_cpu()); + ASSERT_EQ(buf->data(), PyArray_DATA(reinterpret_cast(arr))); + ASSERT_FALSE(buf->is_mutable()); + ASSERT_EQ(old_refcnt + 1, Py_REFCNT(arr)); + buf.reset(); + ASSERT_EQ(old_refcnt, Py_REFCNT(arr)); + + return Status::OK(); +} + +Status TestNumPyBufferNumpyArray() { + npy_intp dims[1] = {10}; + + OwnedRef arr_ref(PyArray_SimpleNew(1, dims, NPY_FLOAT)); + PyObject* arr = arr_ref.obj(); + ASSERT_NE(arr, nullptr); + auto old_refcnt = Py_REFCNT(arr); + + auto buf = std::make_shared(arr); + ASSERT_TRUE(buf->is_cpu()); + ASSERT_EQ(buf->data(), PyArray_DATA(reinterpret_cast(arr))); + ASSERT_TRUE(buf->is_mutable()); + ASSERT_EQ(buf->mutable_data(), buf->data()); + ASSERT_EQ(old_refcnt + 1, Py_REFCNT(arr)); + buf.reset(); + ASSERT_EQ(old_refcnt, Py_REFCNT(arr)); + + // Read-only + PyArray_CLEARFLAGS(reinterpret_cast(arr), NPY_ARRAY_WRITEABLE); + buf = std::make_shared(arr); + ASSERT_TRUE(buf->is_cpu()); + ASSERT_EQ(buf->data(), PyArray_DATA(reinterpret_cast(arr))); + ASSERT_FALSE(buf->is_mutable()); + ASSERT_EQ(old_refcnt + 1, Py_REFCNT(arr)); + buf.reset(); + ASSERT_EQ(old_refcnt, Py_REFCNT(arr)); + + return Status::OK(); +} +#endif + +Status TestPythonDecimalToString() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("-39402950693754869342983"); + PyObject* python_object = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + ASSERT_NE(python_object, nullptr); + + std::string string_result; + ASSERT_OK(internal::PythonDecimalToString(python_object, &string_result)); + + return Status::OK(); +} + +Status TestInferPrecisionAndScale() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("-394029506937548693.42983"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + + const auto expected_precision = + static_cast(decimal_string.size() - 2); // 1 for -, 1 for . + const int32_t expected_scale = 5; + + ASSERT_EQ(expected_precision, metadata.precision()); + ASSERT_EQ(expected_scale, metadata.scale()); + + return Status::OK(); +} + +Status TestInferPrecisionAndNegativeScale() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("-3.94042983E+10"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + + const auto expected_precision = 11; + const int32_t expected_scale = 0; + + ASSERT_EQ(expected_precision, metadata.precision()); + ASSERT_EQ(expected_scale, metadata.scale()); + + return Status::OK(); +} + +Status TestInferAllLeadingZeros() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("0.001"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + ASSERT_EQ(3, metadata.precision()); + ASSERT_EQ(3, metadata.scale()); + + return Status::OK(); +} + +Status TestInferAllLeadingZerosExponentialNotationPositive() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("0.01E5"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + ASSERT_EQ(4, metadata.precision()); + ASSERT_EQ(0, metadata.scale()); + + return Status::OK(); +} + +Status TestInferAllLeadingZerosExponentialNotationNegative() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("0.01E3"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + ASSERT_EQ(2, metadata.precision()); + ASSERT_EQ(0, metadata.scale()); + + return Status::OK(); +} + +Status TestObjectBlockWriteFails() { + StringBuilder builder; + const char value[] = {'\xf1', '\0'}; + + for (int i = 0; i < 1000; ++i) { + ASSERT_OK(builder.Append(value, static_cast(strlen(value)))); + } + + std::shared_ptr arr; + ASSERT_OK(builder.Finish(&arr)); + + auto f1 = field("f1", utf8()); + auto f2 = field("f2", utf8()); + auto f3 = field("f3", utf8()); + std::vector> fields = {f1, f2, f3}; + std::vector> cols = {arr, arr, arr}; + + auto schema = ::arrow::schema(fields); + auto table = Table::Make(schema, cols); + + Status st; + Py_BEGIN_ALLOW_THREADS; + PyObject* out; + PandasOptions options; + options.use_threads = true; + st = ConvertTableToPandas(options, table, &out); + Py_END_ALLOW_THREADS; + ASSERT_RAISES(UnknownError, st); + + return Status::OK(); +} + +Status TestMixedTypeFails() { + OwnedRef list_ref(PyList_New(3)); + PyObject* list = list_ref.obj(); + + ASSERT_NE(list, nullptr); + + PyObject* str = PyUnicode_FromString("abc"); + ASSERT_NE(str, nullptr); + + PyObject* integer = PyLong_FromLong(1234L); + ASSERT_NE(integer, nullptr); + + PyObject* doub = PyFloat_FromDouble(123.0234); + ASSERT_NE(doub, nullptr); + + // This steals a reference to each object, so we don't need to decref them later + // just the list + ASSERT_EQ(PyList_SetItem(list, 0, str), 0); + ASSERT_EQ(PyList_SetItem(list, 1, integer), 0); + ASSERT_EQ(PyList_SetItem(list, 2, doub), 0); + + ASSERT_RAISES(TypeError, ConvertPySequence(list, nullptr, {})); + + return Status::OK(); +} + +template +Status DecimalTestFromPythonDecimalRescale(std::shared_ptr type, + PyObject* python_decimal, + std::optional expected) { + DecimalValue value; + const auto& decimal_type = checked_cast(*type); + + if (expected.has_value()) { + ASSERT_OK(internal::DecimalFromPythonDecimal(python_decimal, decimal_type, &value)); + ASSERT_EQ(expected.value(), value); + + ASSERT_OK(internal::DecimalFromPyObject(python_decimal, decimal_type, &value)); + ASSERT_EQ(expected.value(), value); + } else { + ASSERT_RAISES(Invalid, internal::DecimalFromPythonDecimal(python_decimal, + decimal_type, &value)); + ASSERT_RAISES(Invalid, + internal::DecimalFromPyObject(python_decimal, decimal_type, &value)); + } + return Status::OK(); +} + +Status TestFromPythonDecimalRescaleNotTruncateable() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("1.001"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + // We fail when truncating values that would lose data if cast to a decimal type with + // lower scale + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal128(10, 2), + python_decimal, {})); + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal256(10, 2), + python_decimal, {})); + + return Status::OK(); +} + +Status TestFromPythonDecimalRescaleTruncateable() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("1.000"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + // We allow truncation of values that do not lose precision when dividing by 10 * the + // difference between the scales, e.g., 1.000 -> 1.00 + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal128(10, 2), + python_decimal, 100)); + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal256(10, 2), + python_decimal, 100)); + + return Status::OK(); +} + +Status TestFromPythonNegativeDecimalRescale() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("-1.000"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal128(10, 9), + python_decimal, -1000000000)); + ASSERT_OK(DecimalTestFromPythonDecimalRescale(::arrow::decimal256(10, 9), + python_decimal, -1000000000)); + + return Status::OK(); +} + +Status TestDecimal128FromPythonInteger() { + Decimal128 value; + OwnedRef python_long(PyLong_FromLong(42)); + auto type = ::arrow::decimal128(10, 2); + const auto& decimal_type = checked_cast(*type); + ASSERT_OK(internal::DecimalFromPyObject(python_long.obj(), decimal_type, &value)); + ASSERT_EQ(4200, value); + return Status::OK(); +} + +Status TestDecimal256FromPythonInteger() { + Decimal256 value; + OwnedRef python_long(PyLong_FromLong(42)); + auto type = ::arrow::decimal256(10, 2); + const auto& decimal_type = checked_cast(*type); + ASSERT_OK(internal::DecimalFromPyObject(python_long.obj(), decimal_type, &value)); + ASSERT_EQ(4200, value); + return Status::OK(); +} + +Status TestDecimal128OverflowFails() { + Decimal128 value; + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("9999999999999999999999999999999999999.9"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + ASSERT_EQ(38, metadata.precision()); + ASSERT_EQ(1, metadata.scale()); + + auto type = ::arrow::decimal(38, 38); + const auto& decimal_type = checked_cast(*type); + ASSERT_RAISES(Invalid, + internal::DecimalFromPythonDecimal(python_decimal, decimal_type, &value)); + return Status::OK(); +} + +Status TestDecimal256OverflowFails() { + Decimal256 value; + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string( + "999999999999999999999999999999999999999999999999999999999999999999999999999.9"); + PyObject* python_decimal = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(python_decimal)); + ASSERT_EQ(76, metadata.precision()); + ASSERT_EQ(1, metadata.scale()); + + auto type = ::arrow::decimal(76, 76); + const auto& decimal_type = checked_cast(*type); + ASSERT_RAISES(Invalid, + internal::DecimalFromPythonDecimal(python_decimal, decimal_type, &value)); + return Status::OK(); +} + +Status TestNoneAndNaN() { + OwnedRef list_ref(PyList_New(4)); + PyObject* list = list_ref.obj(); + + ASSERT_NE(list, nullptr); + + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + PyObject* constructor = decimal_constructor_.obj(); + PyObject* decimal_value = internal::DecimalFromString(constructor, "1.234"); + ASSERT_NE(decimal_value, nullptr); + + Py_INCREF(Py_None); + PyObject* missing_value1 = Py_None; + ASSERT_NE(missing_value1, nullptr); + + PyObject* missing_value2 = PyFloat_FromDouble(NPY_NAN); + ASSERT_NE(missing_value2, nullptr); + + PyObject* missing_value3 = internal::DecimalFromString(constructor, "nan"); + ASSERT_NE(missing_value3, nullptr); + + // This steals a reference to each object, so we don't need to decref them later, + // just the list + ASSERT_EQ(0, PyList_SetItem(list, 0, decimal_value)); + ASSERT_EQ(0, PyList_SetItem(list, 1, missing_value1)); + ASSERT_EQ(0, PyList_SetItem(list, 2, missing_value2)); + ASSERT_EQ(0, PyList_SetItem(list, 3, missing_value3)); + + PyConversionOptions options; + ASSERT_RAISES(TypeError, ConvertPySequence(list, nullptr, options)); + + options.from_pandas = true; + auto chunked = std::move(ConvertPySequence(list, nullptr, options)).ValueOrDie(); + ASSERT_EQ(chunked->num_chunks(), 1); + + auto arr = chunked->chunk(0); + ASSERT_TRUE(arr->IsValid(0)); + ASSERT_TRUE(arr->IsNull(1)); + ASSERT_TRUE(arr->IsNull(2)); + ASSERT_TRUE(arr->IsNull(3)); + + return Status::OK(); +} + +Status TestMixedPrecisionAndScale() { + std::vector strings{{"0.001", "1.01E5", "1.01E5"}}; + + OwnedRef list_ref(PyList_New(static_cast(strings.size()))); + PyObject* list = list_ref.obj(); + + ASSERT_NE(list, nullptr); + + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + // PyList_SetItem steals a reference to the item so we don't decref it later + PyObject* decimal_constructor = decimal_constructor_.obj(); + for (Py_ssize_t i = 0; i < static_cast(strings.size()); ++i) { + const int result = PyList_SetItem( + list, i, internal::DecimalFromString(decimal_constructor, strings.at(i))); + ASSERT_EQ(0, result); + } + + auto arr = std::move(ConvertPySequence(list, nullptr, {})).ValueOrDie(); + const auto& type = checked_cast(*arr->type()); + + int32_t expected_precision = 9; + int32_t expected_scale = 3; + ASSERT_EQ(expected_precision, type.precision()); + ASSERT_EQ(expected_scale, type.scale()); + + return Status::OK(); +} + +Status TestMixedPrecisionAndScaleSequenceConvert() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string_1("0.01"); + PyObject* value1 = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string_1); + ASSERT_NE(value1, nullptr); + + std::string decimal_string_2("0.001"); + PyObject* value2 = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string_2); + ASSERT_NE(value2, nullptr); + + OwnedRef list_ref(PyList_New(2)); + PyObject* list = list_ref.obj(); + + // This steals a reference to each object, so we don't need to decref them later + // just the list + ASSERT_EQ(PyList_SetItem(list, 0, value1), 0); + ASSERT_EQ(PyList_SetItem(list, 1, value2), 0); + + auto arr = std::move(ConvertPySequence(list, nullptr, {})).ValueOrDie(); + const auto& type = checked_cast(*arr->type()); + ASSERT_EQ(3, type.precision()); + ASSERT_EQ(3, type.scale()); + + return Status::OK(); +} + +Status TestSimpleInference() { + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + + std::string decimal_string("0.01"); + PyObject* value = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + ASSERT_NE(value, nullptr); + internal::DecimalMetadata metadata; + ASSERT_OK(metadata.Update(value)); + ASSERT_EQ(2, metadata.precision()); + ASSERT_EQ(2, metadata.scale()); + + return Status::OK(); +} + +Status TestUpdateWithNaN() { + internal::DecimalMetadata metadata; + OwnedRef decimal_constructor_; + OwnedRef decimal_module; + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal_module)); + RETURN_NOT_OK( + internal::ImportFromModule(decimal_module.obj(), "Decimal", &decimal_constructor_)); + std::string decimal_string("nan"); + PyObject* nan_value = + internal::DecimalFromString(decimal_constructor_.obj(), decimal_string); + + ASSERT_OK(metadata.Update(nan_value)); + ASSERT_EQ(std::numeric_limits::min(), metadata.precision()); + ASSERT_EQ(std::numeric_limits::min(), metadata.scale()); + + return Status::OK(); +} + +} // namespace + +std::vector GetCppTestCases() { + return { + {"test_owned_ref_moves", TestOwnedRefMoves}, + {"test_owned_ref_nogil_moves", TestOwnedRefNoGILMoves}, + {"test_check_pyerror_status", TestCheckPyErrorStatus}, + {"test_check_pyerror_status_nogil", TestCheckPyErrorStatusNoGIL}, + {"test_restore_pyerror_basics", TestRestorePyErrorBasics}, + {"test_pybuffer_invalid_input_object", TestPyBufferInvalidInputObject}, +#ifndef _WIN32 + {"test_pybuffer_numpy_array", TestPyBufferNumpyArray}, + {"test_numpybuffer_numpy_array", TestNumPyBufferNumpyArray}, +#endif + {"test_python_decimal_to_string", TestPythonDecimalToString}, + {"test_infer_precision_and_scale", TestInferPrecisionAndScale}, + {"test_infer_precision_and_negative_scale", TestInferPrecisionAndNegativeScale}, + {"test_infer_all_leading_zeros", TestInferAllLeadingZeros}, + {"test_infer_all_leading_zeros_exponential_notation_positive", + TestInferAllLeadingZerosExponentialNotationPositive}, + {"test_infer_all_leading_zeros_exponential_notation_negative", + TestInferAllLeadingZerosExponentialNotationNegative}, + {"test_object_block_write_fails_pandas_convert", TestObjectBlockWriteFails}, + {"test_mixed_type_fails", TestMixedTypeFails}, + {"test_from_python_decimal_rescale_not_truncateable", + TestFromPythonDecimalRescaleNotTruncateable}, + {"test_from_python_decimal_rescale_truncateable", + TestFromPythonDecimalRescaleTruncateable}, + {"test_from_python_negative_decimal_rescale", TestFromPythonNegativeDecimalRescale}, + {"test_decimal128_from_python_integer", TestDecimal128FromPythonInteger}, + {"test_decimal256_from_python_integer", TestDecimal256FromPythonInteger}, + {"test_decimal128_overflow_fails", TestDecimal128OverflowFails}, + {"test_decimal256_overflow_fails", TestDecimal256OverflowFails}, + {"test_none_and_nan", TestNoneAndNaN}, + {"test_mixed_precision_and_scale", TestMixedPrecisionAndScale}, + {"test_mixed_precision_and_scale_sequence_convert", + TestMixedPrecisionAndScaleSequenceConvert}, + {"test_simple_inference", TestSimpleInference}, + {"test_update_with_nan", TestUpdateWithNaN}, + }; +} + +} // namespace testing +} // namespace py +} // namespace arrow diff --git a/shared/package-files/26/2614963fd33315d2bd70bcef4c5a52b8946f392011d507a3b16cffad288445cb/test_codegen.cpython-311.pyc b/shared/package-files/26/2614963fd33315d2bd70bcef4c5a52b8946f392011d507a3b16cffad288445cb/test_codegen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42d48c02c1812f6eb79fbf69270d948da3be4d6c Binary files /dev/null and b/shared/package-files/26/2614963fd33315d2bd70bcef4c5a52b8946f392011d507a3b16cffad288445cb/test_codegen.cpython-311.pyc differ diff --git a/shared/package-files/26/2615e2cd516277da0274372ec77d21a80b4851cbb8440ea7e2229f7dbd54bc61/test_map.cpython-311.pyc b/shared/package-files/26/2615e2cd516277da0274372ec77d21a80b4851cbb8440ea7e2229f7dbd54bc61/test_map.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5099c20be33505c8166705abdb73e2bb0c5396a Binary files /dev/null and b/shared/package-files/26/2615e2cd516277da0274372ec77d21a80b4851cbb8440ea7e2229f7dbd54bc61/test_map.cpython-311.pyc differ diff --git a/shared/package-files/26/261983ca4748f49fe1c7fb30cb8d94c5e1631460c5f8c123eaede328bdf6efbd/_rational_tests.cpython-311-x86_64-linux-gnu.so b/shared/package-files/26/261983ca4748f49fe1c7fb30cb8d94c5e1631460c5f8c123eaede328bdf6efbd/_rational_tests.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..88ae1fbc7c171d8b69a2f46317560b1a6d86a7b2 Binary files /dev/null and b/shared/package-files/26/261983ca4748f49fe1c7fb30cb8d94c5e1631460c5f8c123eaede328bdf6efbd/_rational_tests.cpython-311-x86_64-linux-gnu.so differ diff --git a/shared/package-files/26/261c97d96decc173983c0e7781942cd64f18c7d7af3afceb8a73f7541193413c/batch_norm_backward_reduce_cuda_dispatch.h b/shared/package-files/26/261c97d96decc173983c0e7781942cd64f18c7d7af3afceb8a73f7541193413c/batch_norm_backward_reduce_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..cc63ebf8a3958bd16a58ae4c5f3a1c338a422845 --- /dev/null +++ b/shared/package-files/26/261c97d96decc173983c0e7781942cd64f18c7d7af3afceb8a73f7541193413c/batch_norm_backward_reduce_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple batch_norm_backward_reduce(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional & weight, bool input_g, bool weight_g, bool bias_g); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/26/261cc89dd9d376dd023098846e501b83eb4e7550e116fead324d34fd68c13cc2/utils.py b/shared/package-files/26/261cc89dd9d376dd023098846e501b83eb4e7550e116fead324d34fd68c13cc2/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c7075edd2e5210f1dc3d50aaa09688a4a4e1d09c --- /dev/null +++ b/shared/package-files/26/261cc89dd9d376dd023098846e501b83eb4e7550e116fead324d34fd68c13cc2/utils.py @@ -0,0 +1,65 @@ +# mypy: allow-untyped-defs + +from torch import optim + +from .functional_adadelta import _FunctionalAdadelta +from .functional_adagrad import _FunctionalAdagrad +from .functional_adam import _FunctionalAdam +from .functional_adamax import _FunctionalAdamax +from .functional_adamw import _FunctionalAdamW +from .functional_rmsprop import _FunctionalRMSprop +from .functional_rprop import _FunctionalRprop +from .functional_sgd import _FunctionalSGD + + +# dict to map a user passed in optimizer_class to a functional +# optimizer class if we have already defined inside the +# distributed.optim package, this is so that we hide the +# functional optimizer to user and still provide the same API. +functional_optim_map = { + optim.Adagrad: _FunctionalAdagrad, + optim.Adam: _FunctionalAdam, + optim.AdamW: _FunctionalAdamW, + optim.SGD: _FunctionalSGD, + optim.Adadelta: _FunctionalAdadelta, + optim.RMSprop: _FunctionalRMSprop, + optim.Rprop: _FunctionalRprop, + optim.Adamax: _FunctionalAdamax, +} + + +def register_functional_optim(key, optim): + """ + Interface to insert a new functional optimizer to functional_optim_map + ``fn_optim_key`` and ``fn_optimizer`` are user defined. The optimizer and key + need not be of :class:`torch.optim.Optimizer` (e.g. for custom optimizers) + Example:: + >>> # import the new functional optimizer + >>> # xdoctest: +SKIP + >>> from xyz import fn_optimizer + >>> from torch.distributed.optim.utils import register_functional_optim + >>> fn_optim_key = "XYZ_optim" + >>> register_functional_optim(fn_optim_key, fn_optimizer) + """ + if key not in functional_optim_map: + functional_optim_map[key] = optim + + +def as_functional_optim(optim_cls: type, *args, **kwargs): + try: + functional_cls = functional_optim_map[optim_cls] + except KeyError as e: + raise ValueError( + f"Optimizer {optim_cls} does not have a functional counterpart!" + ) from e + + return _create_functional_optim(functional_cls, *args, **kwargs) + + +def _create_functional_optim(functional_optim_cls: type, *args, **kwargs): + return functional_optim_cls( + [], + *args, + **kwargs, + _allow_empty_param_list=True, + ) diff --git a/shared/package-files/26/261dcac3018794ebf971948f9c830170568a9a215ed4c06e53f1b80e61565c92/linear.h b/shared/package-files/26/261dcac3018794ebf971948f9c830170568a9a215ed4c06e53f1b80e61565c92/linear.h new file mode 100644 index 0000000000000000000000000000000000000000..6c045910b848c909d0d6727709cb4aa1a4932ad3 --- /dev/null +++ b/shared/package-files/26/261dcac3018794ebf971948f9c830170568a9a215ed4c06e53f1b80e61565c92/linear.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include + +namespace torch::nn { + +/// Options for the `Linear` module. +/// +/// Example: +/// ``` +/// Linear model(LinearOptions(5, 2).bias(false)); +/// ``` +struct TORCH_API LinearOptions { + LinearOptions(int64_t in_features, int64_t out_features); + /// size of each input sample + TORCH_ARG(int64_t, in_features); + + /// size of each output sample + TORCH_ARG(int64_t, out_features); + + /// If set to false, the layer will not learn an additive bias. Default: true + TORCH_ARG(bool, bias) = true; +}; + +// ============================================================================ + +/// Options for the `Flatten` module. +/// +/// Example: +/// ``` +/// Flatten model(FlattenOptions().start_dim(2).end_dim(4)); +/// ``` +struct TORCH_API FlattenOptions { + /// first dim to flatten + TORCH_ARG(int64_t, start_dim) = 1; + /// last dim to flatten + TORCH_ARG(int64_t, end_dim) = -1; +}; + +// ============================================================================ + +/// Options for the `Unflatten` module. +/// +/// Note: If input tensor is named, use dimname and namedshape arguments. +/// +/// Example: +/// ``` +/// Unflatten unnamed_model(UnflattenOptions(0, {2, 2})); +/// Unflatten named_model(UnflattenOptions("B", {{"B1", 2}, {"B2", 2}})); +/// ``` +struct TORCH_API UnflattenOptions { + typedef std::vector> namedshape_t; + + UnflattenOptions(int64_t dim, std::vector sizes); + UnflattenOptions(const char* dimname, namedshape_t namedshape); + UnflattenOptions(std::string dimname, namedshape_t namedshape); + + /// dim to unflatten + TORCH_ARG(int64_t, dim); + /// name of dim to unflatten, for use with named tensors + TORCH_ARG(std::string, dimname); + /// new shape of unflattened dim + TORCH_ARG(std::vector, sizes); + /// new shape of unflattened dim with names, for use with named tensors + TORCH_ARG(namedshape_t, namedshape); +}; + +// ============================================================================ + +/// Options for the `Bilinear` module. +/// +/// Example: +/// ``` +/// Bilinear model(BilinearOptions(3, 2, 4).bias(false)); +/// ``` +struct TORCH_API BilinearOptions { + BilinearOptions( + int64_t in1_features, + int64_t in2_features, + int64_t out_features); + /// The number of features in input 1 (columns of the input1 matrix). + TORCH_ARG(int64_t, in1_features); + /// The number of features in input 2 (columns of the input2 matrix). + TORCH_ARG(int64_t, in2_features); + /// The number of output features to produce (columns of the output matrix). + TORCH_ARG(int64_t, out_features); + /// Whether to learn and add a bias after the bilinear transformation. + TORCH_ARG(bool, bias) = true; +}; + +} // namespace torch::nn diff --git a/shared/package-files/26/26239689895b78afedc363616ab1fb6fce544bcce45a44764b3f25af5e49d159/test_compare.cpython-311.pyc b/shared/package-files/26/26239689895b78afedc363616ab1fb6fce544bcce45a44764b3f25af5e49d159/test_compare.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76706d9bae7b81f562555cf2123080028c595569 Binary files /dev/null and b/shared/package-files/26/26239689895b78afedc363616ab1fb6fce544bcce45a44764b3f25af5e49d159/test_compare.cpython-311.pyc differ diff --git a/shared/package-files/26/262634e48bd2fd991853bcfd5f06648790d395cb1d3755fed825c207e4afab6e/_nested_get_offsets_ops.h b/shared/package-files/26/262634e48bd2fd991853bcfd5f06648790d395cb1d3755fed825c207e4afab6e/_nested_get_offsets_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..449fe6876f03b7fa29e44ab5a8c74c7b7e7fb10c --- /dev/null +++ b/shared/package-files/26/262634e48bd2fd991853bcfd5f06648790d395cb1d3755fed825c207e4afab6e/_nested_get_offsets_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_get_offsets { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_nested_get_offsets"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_nested_get_offsets(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/26267139a56ac14b5b97a1d05db3400efc3919705c9243fb868f146ec0fed1ff/consensus_pileup.c b/shared/package-files/26/26267139a56ac14b5b97a1d05db3400efc3919705c9243fb868f146ec0fed1ff/consensus_pileup.c new file mode 100644 index 0000000000000000000000000000000000000000..c9667b3cde25b10b016eda7e69ba77c2b52cec9e --- /dev/null +++ b/shared/package-files/26/26267139a56ac14b5b97a1d05db3400efc3919705c9243fb868f146ec0fed1ff/consensus_pileup.c @@ -0,0 +1,604 @@ +/* consensus__pileup.h -- Pileup orientated data per consensus column + + Copyright (C) 2013-2016, 2020-2022 Genome Research Ltd. + + Author: James Bonfied + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include +#include + +#ifdef __SSE__ +# include +#else +# define _mm_prefetch(a,b) +#endif + +#include "consensus_pileup.h" + +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define bam_strand(b) (((b)->core.flag & BAM_FREVERSE) != 0) + +/* + * START_WITH_DEL is the mode that Gap5 uses when building this. It prepends + * all cigar strings with 1D and decrements the position by one. (And then + * has code to reverse this operation in the pileup handler.) + * + * The reason for this is that it means reads starting with an insertion work. + * Otherwise the inserted bases are silently lost. (Try it with "samtools + * mpileup" and you can see it has the same issue.) + * + * However it's probably not want most people expect. + */ +//#define START_WITH_DEL + +/* -------------------------------------------------------------------------- + * The pileup code itself. + * + * This consists of the external pileup_loop() function, which takes a + * sam/bam samfile_t pointer and a callback function. The callback function + * is called once per column of aligned data (so once per base in an + * insertion). + * + * Current known issues. + * 1) zero length matches, ie 2S2S cause failures. + * 2) Insertions at starts of sequences get included in the soft clip, so + * 2S2I2M is treated as if it's 4S2M + * 3) From 1 and 2 above, 1S1I2S becomes 2S2S which fails. + */ + + +/* + * Fetches the next base => the nth base at unpadded position pos. (Nth can + * be greater than 0 if we have an insertion in this column). Do not call this + * with pos/nth lower than the previous query, although higher is better. + * (This allows it to be initialised at base 0.) + * + * Stores the result in base and also updates is_insert to indicate that + * this sequence still has more bases in this position beyond the current + * nth parameter. + * + * Returns 1 if a base was fetched + * 0 if not (eg ran off the end of sequence) + */ +static int get_next_base(pileup_t *p, hts_pos_t pos, int nth, int *is_insert) { + bam1_t *b = &p->b; + int op = p->cigar_op; + + p->start -= p->start>0; + if (p->first_del && op != BAM_CPAD) + p->first_del = 0; + + *is_insert = 0; + + /* Find pos first */ + while (p->pos < pos) { + p->nth = 0; + + if (p->cigar_len == 0) { + if (p->cigar_ind >= b->core.n_cigar) { + p->eof = 1; + return 0; + } + + op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK; + p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT; + p->cigar_ind++; + } + + if ((op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) + && p->cigar_len <= pos - p->pos) { + p->seq_offset += p->cigar_len; + p->pos += p->cigar_len; + p->cigar_len = 0; + } else { + switch (op) { + case BAM_CMATCH: + case BAM_CEQUAL: + case BAM_CDIFF: + p->seq_offset++; + /* Fall through */ + case BAM_CDEL: + case BAM_CREF_SKIP: + p->pos++; + p->cigar_len--; + break; + + case BAM_CINS: + case BAM_CSOFT_CLIP: + p->seq_offset += p->cigar_len; + /* Fall through */ + case BAM_CPAD: + case BAM_CHARD_CLIP: + p->cigar_len = 0; + break; + + default: + fprintf(stderr, "Unhandled cigar_op %d\n", op); + return -1; + } + } + } + + /* Now at pos, find nth base */ + while (p->nth < nth) { + if (p->cigar_len == 0) { + if (p->cigar_ind >= b->core.n_cigar) { + p->eof = 1; + return 0; /* off end of seq */ + } + + op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK; + p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT; + p->cigar_ind++; + } + + switch (op) { + case BAM_CMATCH: + case BAM_CEQUAL: + case BAM_CDIFF: + case BAM_CSOFT_CLIP: + case BAM_CDEL: + case BAM_CREF_SKIP: + goto at_nth; /* sorry, but it's fast! */ + + case BAM_CINS: + p->seq_offset++; + /* Fall through */ + case BAM_CPAD: + p->cigar_len--; + p->nth++; + break; + + case BAM_CHARD_CLIP: + p->cigar_len = 0; + break; + + default: + fprintf(stderr, "Unhandled cigar_op %d\n", op); + return -1; + } + } + at_nth: + + /* Fill out base & qual fields */ + p->ref_skip = 0; + if (p->nth < nth && op != BAM_CINS) { + //p->base = '-'; + p->base = '*'; + p->base4 = 16; + p->padding = 1; + if (p->seq_offset < b->core.l_qseq) + p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]); + else + p->qual = 0; + } else { + p->padding = 0; + switch(op) { + case BAM_CDEL: + p->base = '*'; + p->base4 = 16; + if (p->seq_offset+1 < b->core.l_qseq) + p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]); + else + p->qual = MIN(p->qual, p->b_qual[p->seq_offset]); + break; + + case BAM_CPAD: + //p->base = '+'; + p->base = '*'; + p->base4 = 16; + if (p->seq_offset+1 < b->core.l_qseq) + p->qual = MIN(p->qual, p->b_qual[p->seq_offset+1]); + else + p->qual = MIN(p->qual, p->b_qual[p->seq_offset]); + break; + + case BAM_CREF_SKIP: + p->base = '.'; + p->base4 = 0; + p->qual = 0; + /* end of fragment, but not sequence */ + p->eof = p->eof ? 2 : 3; + p->ref_skip = 1; + break; + + default: + if (p->seq_offset < b->core.l_qseq) { + p->qual = p->b_qual[p->seq_offset]; + p->base4 = p->b_seq[p->seq_offset/2] >> + ((~p->seq_offset&1)<<2) & 0xf; + p->base = "NACMGRSVTWYHKDBN"[p->base4]; + } else { + p->base = 'N'; + p->base4 = 15; + p->qual = 0xff; + } + + break; + } + } + + /* Handle moving out of N (skip) into sequence again */ + if (p->eof && p->base != '.') { + p->start = 1; + p->ref_skip = 1; + p->eof = 0; + } + + /* Starting with an indel needs a minor fudge */ + if (p->start && p->cigar_op == BAM_CDEL) { + p->first_del = 1; + } + + /* Check if next op is an insertion of some sort */ + if (p->cigar_len == 0) { + if (p->cigar_ind < b->core.n_cigar) { + op=p->cigar_op = p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK; + p->cigar_len = p->b_cigar[p->cigar_ind] >> BAM_CIGAR_SHIFT; + p->cigar_ind++; + if (op == BAM_CREF_SKIP) { + p->eof = 3; + p->ref_skip = 1; + } + } else { + p->eof = 1; + } + } + + switch (op) { + case BAM_CPAD: + case BAM_CINS: + *is_insert = p->cigar_len; + break; + + case BAM_CSOFT_CLIP: + /* Last op 'S' => eof */ + p->eof = (p->cigar_ind == b->core.n_cigar || + (p->cigar_ind+1 == b->core.n_cigar && + (p->b_cigar[p->cigar_ind] & BAM_CIGAR_MASK) + == BAM_CHARD_CLIP)) + ? 1 + : 0; + break; + + case BAM_CHARD_CLIP: + p->eof = 1; + break; + + default: + break; + } + + return 1; +} + +/* + * Loops through a set of supplied ranges producing columns of data. + * When found, it calls func with clientdata as a callback. Func should + * return 0 for success and non-zero for failure. seq_init() is called + * on each new entry before we start processing it. It should return 0 or 1 + * to indicate reject or accept status (eg to filter unmapped data). + * If seq_init() returns -1 we abort the pileup_loop with an error. + * seq_init may be NULL. + * + * Returns 0 on success + * -1 on failure + */ +int pileup_loop(samFile *fp, + sam_hdr_t *h, + int (*seq_fetch)(void *client_data, + samFile *fp, + sam_hdr_t *h, + bam1_t *b), + int (*seq_init)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p), + int (*seq_column)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p, + int depth, + hts_pos_t pos, + int nth, + int is_insert), + void (*seq_free)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p), + void *client_data) { + int ret = -1; + pileup_t *phead = NULL, *p, *pfree = NULL, *last, *next, *ptail = NULL; + pileup_t *pnew = NULL; + int is_insert, nth = 0, r; + hts_pos_t col = 0; + int last_ref = -1; + + /* FIXME: allow for start/stop boundaries rather than consuming all data */ + + if (NULL == (pnew = calloc(1, sizeof(*p)))) + return -1; + + do { + bam1_t *b; + hts_pos_t pos; + + r = seq_fetch(client_data, fp, h, &pnew->b); + if (r < -1) { + fprintf(stderr, "bam_next_seq() failure.\n"); + goto error; + } + + b = &pnew->b; + + /* Force realloc */ + //fp->bs = NULL; + //fp->bs_size = 0; + + //r = samread(fp, pnew->b); + if (r >= 0) { + if (b->core.flag & BAM_FUNMAP) + continue; + + if (b->core.tid == -1) { + /* Another indicator for unmapped */ + continue; + } else if (b->core.tid == last_ref) { + pos = b->core.pos+1; + //printf("New seq at pos %d @ %d %s\n", pos, b->core.tid, + // bam_name(b)); + } else { + //printf("New ctg at pos %ld @ %d\n",b->core.pos+1,b->core.tid); + pos = HTS_POS_MAX; + } + } else { + pos = HTS_POS_MAX; + } + + if (col > pos) { + fprintf(stderr, "BAM/SAM file is not sorted by position. " + "Aborting\n"); + goto error; + } + + /* Process data between the last column and our latest addition */ + while (col < pos && phead) { + struct pileup *eof_head = NULL, *eofp = NULL; + int v, ins, depth = 0; + //printf("Col=%ld pos=%ld nth=%d\n", col, pos, nth); + + /* Pileup */ + is_insert = 0; + pileup_t *pnext = phead ? phead->next : NULL; + for (p = phead, last = NULL; p; p = pnext) { +#if 0 + // Simple prefetching + pnext = p->next; + if (pnext) + _mm_prefetch(pnext, _MM_HINT_T0); +#else + // More complex prefetching => more instructions, but + // usually faster. + pnext = p->next; + if (pnext) { + // start memory fetches; a big help on very deep data + if (pnext->next) + // struct 2 ahead + _mm_prefetch(pnext->next, _MM_HINT_T0); + // seq/qual 1 ahead + _mm_prefetch(pnext->b_qual + pnext->seq_offset, + _MM_HINT_T0); + _mm_prefetch(pnext->b_seq + pnext->seq_offset/2, + _MM_HINT_T0); + } +#endif + + if (!get_next_base(p, col, nth, &ins)) + p->eof = 1; + if (p->eof == 1) { + if (eofp) + eofp->eofn = p; + eofp = p; + eofp->eofl = last; + if (!eof_head) + eof_head = eofp; + } else { + last = p; + } + + if (is_insert < ins) + is_insert = ins; + + depth++; + } + if ((ptail = last) == NULL) + ptail = phead; + + /* Call our function on phead linked list */ + v = seq_column(client_data, fp, h, phead, depth, +#ifdef START_WITH_DEL + col-1, +#else + col, +#endif + nth, is_insert); + + /* Remove dead seqs */ + for (p = eof_head ; p; p = p->eofn) { + if (p->eofl) + p->eofl->next = p->next; + else + phead = p->next; + + p->next = pfree; + pfree = p; + + if (seq_free) + seq_free(client_data, fp, h, p); + } + + if (v == 1) + break; /* early abort */ + + if (v != 0) + goto error; + + /* Next column */ + if (is_insert) { + nth++; + } else { + nth = 0; + col++; + } + } + + /* May happen if we have a hole in the contig */ + col = pos; + + /* New contig */ + if (b && b->core.tid != last_ref) { + last_ref = b->core.tid; + pos = b->core.pos+1; + nth = 0; + col = pos; + } + + /* + * Add this seq. + * Note: cigars starting with I or P ops (eg 2P3I10M) mean we have + * alignment instructions that take place before the designated + * starting location listed in the SAM file. They won't get included + * in the callback function until they officially start, which is + * already too late. + * + * So to workaround this, we prefix all CIGAR with 1D, move the + * position by 1bp, and then force the callback code to remove + * leaving pads (either P or D generated). + * + * Ie it's a level 10 hack! + */ + if (r >= 0) { + p = pnew; + p->next = NULL; + p->cd = NULL; + p->eofn = NULL; + p->eofl = NULL; + p->start = 2; + p->eof = 0; +#ifdef START_WITH_DEL + p->pos = pos-1; + p->cigar_ind = 0; + p->b_cigar = bam_get_cigar(&p->b); + if ((p->b_cigar[0] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { + p->cigar_len = p->b_cigar[0] >> BAM_CIGAR_SHIFT; + p->cigar_op = BAM_CHARD_CLIP; + if ((p->b_cigar[1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) { + /* xHxS... => xHxS1D... */ + p->b_cigar[0] = p->b_cigar[1]; + p->b_cigar[1] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL; + } else { + /* xH... => xH1D... */ + p->b_cigar[0] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL; + } + } else { + if ((p->b_cigar[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) { + /* xS... => xS1D... */ + p->cigar_len = p->b_cigar[0] >> BAM_CIGAR_SHIFT; + p->cigar_op = BAM_CSOFT_CLIP; + p->b_cigar[0] = (1 << BAM_CIGAR_SHIFT) | BAM_CDEL; + } else { + /* ... => 1D... */ + p->cigar_len = 1; /* was 0 */ + p->cigar_op = BAM_CDEL; /* was 'X' */ + } + } + p->seq_offset = -1; + p->first_del = 1; +#else + p->pos = pos-1; + p->cigar_ind = 0; + p->b_cigar = bam_get_cigar(&p->b); + p->cigar_len = 0; + p->cigar_op = -1; + p->seq_offset = -1; + p->first_del = 0; +#endif + p->b_is_rev = bam_is_rev(&p->b); + p->b_qual = (uint8_t *)bam_get_qual(&p->b); + p->b_seq = (uint8_t *)bam_get_seq(&p->b); + + if (seq_init) { + int v; + v = seq_init(client_data, fp, h, p); + if (v == -1) + goto error; + + if (v == 1) { + /* Keep this seq */ + if (phead) { + ptail->next = p; + } else { + phead = p; + } + ptail = p; + } else { + /* Push back on free list */ + p->next = pfree; + pfree = p; + } + } else { + if (phead) + ptail->next = p; + else + phead = p; + ptail = p; + } + + /* Allocate the next pileup rec */ + if (pfree) { + pnew = pfree; + pfree = pfree->next; + } else { + if (NULL == (pnew = calloc(1, sizeof(*pnew)))) + goto error; + } + } + } while (r >= 0); + + ret = 0; + error: + + if (pnew) { + free(pnew->b.data); + free(pnew); + } + + /* Tidy up */ + for (p = pfree; p; p = next) { + next = p->next; + if (seq_free) + seq_free(client_data, fp, h, p); + free(p->b.data); + free(p); + } + + return ret; +} diff --git a/shared/package-files/26/26272862dbdd6344efd5b3c3d1077ee5f8c2f7b9221936e78033ea4b64eef0be/test_riccati.cpython-311.pyc b/shared/package-files/26/26272862dbdd6344efd5b3c3d1077ee5f8c2f7b9221936e78033ea4b64eef0be/test_riccati.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69d7243d3460d2e80baf8e69f622d8451ef4afa2 Binary files /dev/null and b/shared/package-files/26/26272862dbdd6344efd5b3c3d1077ee5f8c2f7b9221936e78033ea4b64eef0be/test_riccati.cpython-311.pyc differ diff --git a/shared/package-files/26/262977182301b015c9d5051d8ac9861eb286f03b4126d3b01e4d6fe36d866f09/test_sidebar.py b/shared/package-files/26/262977182301b015c9d5051d8ac9861eb286f03b4126d3b01e4d6fe36d866f09/test_sidebar.py new file mode 100644 index 0000000000000000000000000000000000000000..605e7a892570d7d7003095551ce1a27c3a8e9e0f --- /dev/null +++ b/shared/package-files/26/262977182301b015c9d5051d8ac9861eb286f03b4126d3b01e4d6fe36d866f09/test_sidebar.py @@ -0,0 +1,775 @@ +"""Test sidebar, coverage 85%""" +from textwrap import dedent +import sys + +from itertools import chain +import unittest +import unittest.mock +from test.support import requires, swap_attr +from test import support +import tkinter as tk +from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop + +from idlelib.delegator import Delegator +from idlelib.editor import fixwordbreaks +from idlelib.percolator import Percolator +import idlelib.pyshell +from idlelib.pyshell import fix_x11_paste, PyShell, PyShellFileList +from idlelib.run import fix_scaling +import idlelib.sidebar +from idlelib.sidebar import get_end_linenumber, get_lineno + + +class Dummy_editwin: + def __init__(self, text): + self.text = text + self.text_frame = self.text.master + self.per = Percolator(text) + self.undo = Delegator() + self.per.insertfilter(self.undo) + + def setvar(self, name, value): + pass + + def getlineno(self, index): + return int(float(self.text.index(index))) + + +class LineNumbersTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + + cls.text_frame = tk.Frame(cls.root) + cls.text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + cls.text_frame.rowconfigure(1, weight=1) + cls.text_frame.columnconfigure(1, weight=1) + + cls.text = tk.Text(cls.text_frame, width=80, height=24, wrap=tk.NONE) + cls.text.grid(row=1, column=1, sticky=tk.NSEW) + + cls.editwin = Dummy_editwin(cls.text) + cls.editwin.vbar = tk.Scrollbar(cls.text_frame) + + @classmethod + def tearDownClass(cls): + cls.editwin.per.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.text, cls.text_frame, cls.editwin, cls.root + + def setUp(self): + self.linenumber = idlelib.sidebar.LineNumbers(self.editwin) + + self.highlight_cfg = {"background": '#abcdef', + "foreground": '#123456'} + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element == 'linenumber': + return self.highlight_cfg + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + self.addCleanup(GetHighlight_patcher.stop) + + self.font_override = 'TkFixedFont' + def mock_idleconf_GetFont(root, configType, section): + return self.font_override + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + self.addCleanup(GetFont_patcher.stop) + + def tearDown(self): + self.text.delete('1.0', 'end') + + def get_selection(self): + return tuple(map(str, self.text.tag_ranges('sel'))) + + def get_line_screen_position(self, line): + bbox = self.linenumber.sidebar_text.bbox(f'{line}.end -1c') + x = bbox[0] + 2 + y = bbox[1] + 2 + return x, y + + def assert_state_disabled(self): + state = self.linenumber.sidebar_text.config()['state'] + self.assertEqual(state[-1], tk.DISABLED) + + def get_sidebar_text_contents(self): + return self.linenumber.sidebar_text.get('1.0', tk.END) + + def assert_sidebar_n_lines(self, n_lines): + expected = '\n'.join(chain(map(str, range(1, n_lines + 1)), [''])) + self.assertEqual(self.get_sidebar_text_contents(), expected) + + def assert_text_equals(self, expected): + return self.assertEqual(self.text.get('1.0', 'end'), expected) + + def test_init_empty(self): + self.assert_sidebar_n_lines(1) + + def test_init_not_empty(self): + self.text.insert('insert', 'foo bar\n'*3) + self.assert_text_equals('foo bar\n'*3 + '\n') + self.assert_sidebar_n_lines(4) + + def test_toggle_linenumbering(self): + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + + def test_insert(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', '\nfoo') + self.assert_text_equals('foobar\nfoo\n') + self.assert_sidebar_n_lines(2) + self.assert_state_disabled() + + self.text.insert('insert', 'hello\n'*2) + self.assert_text_equals('foobar\nfoohello\nhello\n\n') + self.assert_sidebar_n_lines(4) + self.assert_state_disabled() + + self.text.insert('insert', '\nworld') + self.assert_text_equals('foobar\nfoohello\nhello\n\nworld\n') + self.assert_sidebar_n_lines(5) + self.assert_state_disabled() + + def test_delete(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.text.delete('1.1', '1.3') + self.assert_text_equals('fbar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', 'foo\n'*2) + self.assert_text_equals('fbarfoo\nfoo\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + # Deleting up to "2.end" doesn't delete the final newline. + self.text.delete('2.0', '2.end') + self.assert_text_equals('fbarfoo\n\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + self.text.delete('1.3', 'end') + self.assert_text_equals('fba\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end') + self.assert_text_equals('\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + def test_sidebar_text_width(self): + """ + Test that linenumber text widget is always at the minimum + width + """ + def get_width(): + return self.linenumber.sidebar_text.config()['width'][-1] + + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*8) + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(11) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*90) + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(101) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.delete('50.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(49) + self.assertEqual(get_width(), 2) + + self.text.delete('5.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(4) + self.assertEqual(get_width(), 1) + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end -1c') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + # The following tests are temporarily disabled due to relying on + # simulated user input and inspecting which text is selected, which + # are fragile and can fail when several GUI tests are run in parallel + # or when the windows created by the test lose focus. + # + # TODO: Re-work these tests or remove them from the test suite. + + @unittest.skip('test disabled') + def test_click_selection(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\n') + self.root.update() + + # Click on the second line. + x, y = self.get_line_screen_position(2) + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.linenumber.sidebar_text.update() + self.root.update() + + self.assertEqual(self.get_selection(), ('2.0', '3.0')) + + def simulate_drag(self, start_line, end_line): + start_x, start_y = self.get_line_screen_position(start_line) + end_x, end_y = self.get_line_screen_position(end_line) + + self.linenumber.sidebar_text.event_generate('', + x=start_x, y=start_y) + self.root.update() + + def lerp(a, b, steps): + """linearly interpolate from a to b (inclusive) in equal steps""" + last_step = steps - 1 + for i in range(steps): + yield ((last_step - i) / last_step) * a + (i / last_step) * b + + for x, y in zip( + map(int, lerp(start_x, end_x, steps=11)), + map(int, lerp(start_y, end_y, steps=11)), + ): + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.root.update() + + self.linenumber.sidebar_text.event_generate('', + x=end_x, y=end_y) + self.root.update() + + @unittest.skip('test disabled') + def test_drag_selection_down(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the second line to the fourth line. + self.simulate_drag(2, 4) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + @unittest.skip('test disabled') + def test_drag_selection_up(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the fourth line to the second line. + self.simulate_drag(4, 2) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + def test_scroll(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'line\n' * 100) + self.root.update() + + # Scroll down 10 lines. + self.text.yview_scroll(10, 'unit') + self.root.update() + self.assertEqual(self.text.index('@0,0'), '11.0') + self.assertEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + # Generate a mouse-wheel event and make sure it scrolled up or down. + # The meaning of the "delta" is OS-dependent, so this just checks for + # any change. + self.linenumber.sidebar_text.event_generate('', + x=0, y=0, + delta=10) + self.root.update() + self.assertNotEqual(self.text.index('@0,0'), '11.0') + self.assertNotEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + def test_font(self): + ln = self.linenumber + + orig_font = ln.sidebar_text['font'] + test_font = 'TkTextFont' + self.assertNotEqual(orig_font, test_font) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.font_override = test_font + # Nothing breaks when line numbers aren't shown. + ln.update_font() + + # Activate line numbers, previous font change is immediately effective. + ln.show_sidebar() + self.assertEqual(ln.sidebar_text['font'], test_font) + + # Call the font update with line numbers shown, change is picked up. + self.font_override = orig_font + ln.update_font() + self.assertEqual(ln.sidebar_text['font'], orig_font) + + def test_highlight_colors(self): + ln = self.linenumber + + orig_colors = dict(self.highlight_cfg) + test_colors = {'background': '#222222', 'foreground': '#ffff00'} + + def assert_colors_are_equal(colors): + self.assertEqual(ln.sidebar_text['background'], colors['background']) + self.assertEqual(ln.sidebar_text['foreground'], colors['foreground']) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.highlight_cfg = test_colors + # Nothing breaks with inactive line numbers. + ln.update_colors() + + # Show line numbers, previous colors change is immediately effective. + ln.show_sidebar() + assert_colors_are_equal(test_colors) + + # Call colors update with no change to the configured colors. + ln.update_colors() + assert_colors_are_equal(test_colors) + + # Call the colors update with line numbers shown, change is picked up. + self.highlight_cfg = orig_colors + ln.update_colors() + assert_colors_are_equal(orig_colors) + + +class ShellSidebarTest(unittest.TestCase): + root: tk.Tk = None + shell: PyShell = None + + @classmethod + def setUpClass(cls): + requires('gui') + + cls.root = root = tk.Tk() + root.withdraw() + + fix_scaling(root) + fixwordbreaks(root) + fix_x11_paste(root) + + cls.flist = flist = PyShellFileList(root) + # See #43981 about macosx.setupApp(root, flist) causing failure. + root.update_idletasks() + + cls.init_shell() + + @classmethod + def tearDownClass(cls): + if cls.shell is not None: + cls.shell.executing = False + cls.shell.close() + cls.shell = None + cls.flist = None + cls.root.update_idletasks() + cls.root.destroy() + cls.root = None + + @classmethod + def init_shell(cls): + cls.shell = cls.flist.open_shell() + cls.shell.pollinterval = 10 + cls.root.update() + cls.n_preface_lines = get_lineno(cls.shell.text, 'end-1c') - 1 + + @classmethod + def reset_shell(cls): + cls.shell.per.bottom.delete(f'{cls.n_preface_lines+1}.0', 'end-1c') + cls.shell.shell_sidebar.update_sidebar() + cls.root.update() + + def setUp(self): + # In some test environments, e.g. Azure Pipelines (as of + # Apr. 2021), sys.stdout is changed between tests. However, + # PyShell relies on overriding sys.stdout when run without a + # sub-process (as done here; see setUpClass). + self._saved_stdout = None + if sys.stdout != self.shell.stdout: + self._saved_stdout = sys.stdout + sys.stdout = self.shell.stdout + + self.reset_shell() + + def tearDown(self): + if self._saved_stdout is not None: + sys.stdout = self._saved_stdout + + def get_sidebar_lines(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts_by_y_coords = { + canvas.bbox(text)[1]: canvas.itemcget(text, 'text') + for text in texts + } + line_y_coords = self.get_shell_line_y_coords() + return [texts_by_y_coords.get(y, None) for y in line_y_coords] + + def assert_sidebar_lines_end_with(self, expected_lines): + self.shell.shell_sidebar.update_sidebar() + self.assertEqual( + self.get_sidebar_lines()[-len(expected_lines):], + expected_lines, + ) + + def get_shell_line_y_coords(self): + text = self.shell.text + y_coords = [] + index = text.index("@0,0") + if index.split('.', 1)[1] != '0': + index = text.index(f"{index} +1line linestart") + while (lineinfo := text.dlineinfo(index)) is not None: + y_coords.append(lineinfo[1]) + index = text.index(f"{index} +1line") + return y_coords + + def get_sidebar_line_y_coords(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts.sort(key=lambda text: canvas.bbox(text)[1]) + return [canvas.bbox(text)[1] for text in texts] + + def assert_sidebar_lines_synced(self): + self.assertLessEqual( + set(self.get_sidebar_line_y_coords()), + set(self.get_shell_line_y_coords()), + ) + + def do_input(self, input): + shell = self.shell + text = shell.text + for line_index, line in enumerate(input.split('\n')): + if line_index > 0: + text.event_generate('<>') + text.insert('insert', line, 'stdin') + + def test_initial_state(self): + sidebar_lines = self.get_sidebar_lines() + self.assertEqual( + sidebar_lines, + [None] * (len(sidebar_lines) - 1) + ['>>>'], + ) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_single_empty_input(self): + self.do_input('\n') + yield + self.assert_sidebar_lines_end_with(['>>>', '>>>']) + + @run_in_tk_mainloop() + def test_single_line_statement(self): + self.do_input('1\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + + @run_in_tk_mainloop() + def test_multi_line_statement(self): + # Block statements are not indented because IDLE auto-indents. + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + self.assert_sidebar_lines_end_with([ + '>>>', + '...', + '...', + '...', + None, + '>>>', + ]) + + @run_in_tk_mainloop() + def test_single_long_line_wraps(self): + self.do_input('1' * 200 + '\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_squeeze_multi_line_output(self): + shell = self.shell + text = shell.text + + self.do_input('print("a\\nb\\nc")\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + + text.mark_set('insert', f'insert -1line linestart') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + shell.squeezer.expandingbuttons[0].expand() + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_interrupt_recall_undo_redo(self): + text = self.shell.text + # Block statements are not indented because IDLE auto-indents. + initial_sidebar_lines = self.get_sidebar_lines() + + self.do_input(dedent('''\ + if True: + print(1) + ''')) + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...']) + with_block_sidebar_lines = self.get_sidebar_lines() + self.assertNotEqual(with_block_sidebar_lines, initial_sidebar_lines) + + # Control-C + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...', None, '>>>']) + + # Recall previous via history + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', None, '>>>']) + + # Recall previous via recall + text.mark_set('insert', text.index('insert -2l')) + text.event_generate('<>') + yield + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>']) + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...']) + + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with( + ['>>>', '...', '...', '...', None, '>>>'] + ) + + @run_in_tk_mainloop() + def test_very_long_wrapped_line(self): + with support.adjust_int_max_str_digits(11_111), \ + swap_attr(self.shell, 'squeezer', None): + self.do_input('x = ' + '1'*10_000 + '\n') + yield + self.assertEqual(self.get_sidebar_lines(), ['>>>']) + + def test_font(self): + sidebar = self.shell.shell_sidebar + + test_font = 'TkTextFont' + + def mock_idleconf_GetFont(root, configType, section): + return test_font + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + def cleanup(): + GetFont_patcher.stop() + sidebar.update_font() + self.addCleanup(cleanup) + + def get_sidebar_font(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fonts = {canvas.itemcget(text, 'font') for text in texts} + self.assertEqual(len(fonts), 1) + return next(iter(fonts)) + + self.assertNotEqual(get_sidebar_font(), test_font) + sidebar.update_font() + self.assertEqual(get_sidebar_font(), test_font) + + def test_highlight_colors(self): + sidebar = self.shell.shell_sidebar + + test_colors = {"background": '#abcdef', "foreground": '#123456'} + + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element in ['linenumber', 'console']: + return test_colors + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', + mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + def cleanup(): + GetHighlight_patcher.stop() + sidebar.update_colors() + self.addCleanup(cleanup) + + def get_sidebar_colors(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fgs = {canvas.itemcget(text, 'fill') for text in texts} + self.assertEqual(len(fgs), 1) + fg = next(iter(fgs)) + bg = canvas.cget('background') + return {"background": bg, "foreground": fg} + + self.assertNotEqual(get_sidebar_colors(), test_colors) + sidebar.update_colors() + self.assertEqual(get_sidebar_colors(), test_colors) + + @run_in_tk_mainloop() + def test_mousewheel(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + # Enter a 100-line string to scroll the shell screen down. + self.do_input('x = """' + '\n'*100 + '"""\n') + yield + self.assertGreater(get_lineno(text, '@0,0'), 1) + + last_lineno = get_end_linenumber(text) + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Delta for , whose meaning is platform-dependent. + delta = 1 if sidebar.canvas._windowingsystem == 'aqua' else 120 + + # Scroll up. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=delta) + yield + self.assertIsNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Scroll back down. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=-delta) + yield + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + @run_in_tk_mainloop() + def test_copy(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.0', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertTrue(selected_text.startswith('if True:\n')) + self.assertIn('\n1\n', selected_text) + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text) + + @run_in_tk_mainloop() + def test_copy_with_prompts(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.3', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertTrue(selected_text.startswith('True:\n')) + + selected_lines_text = text.get('sel.first linestart', 'sel.last') + selected_lines = selected_lines_text.split('\n') + selected_lines.pop() # Final '' is a split artifact, not a line. + # Expect a block of input and a single output line. + expected_prompts = \ + ['>>>'] + ['...'] * (len(selected_lines) - 2) + [None] + selected_text_with_prompts = '\n'.join( + line if prompt is None else prompt + ' ' + line + for prompt, line in zip(expected_prompts, + selected_lines, + strict=True) + ) + '\n' + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text_with_prompts) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/shared/package-files/26/262d24e73efbf10b4d43433053ac413facfb6a32e4efd55afaf802aab940a6ca/hash_join.h b/shared/package-files/26/262d24e73efbf10b4d43433053ac413facfb6a32e4efd55afaf802aab940a6ca/hash_join.h new file mode 100644 index 0000000000000000000000000000000000000000..a81ff274e5e3a46bab8fe7a12902a1c6c62c0bbd --- /dev/null +++ b/shared/package-files/26/262d24e73efbf10b4d43433053ac413facfb6a32e4efd55afaf802aab940a6ca/hash_join.h @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/accumulation_queue.h" +#include "arrow/acero/bloom_filter.h" +#include "arrow/acero/options.h" +#include "arrow/acero/query_context.h" +#include "arrow/acero/schema_util.h" +#include "arrow/acero/task_util.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/tracing.h" + +namespace arrow { +namespace acero { + +using util::AccumulationQueue; + +class HashJoinImpl { + public: + using OutputBatchCallback = std::function; + using BuildFinishedCallback = std::function; + using FinishedCallback = std::function; + using RegisterTaskGroupCallback = std::function, std::function)>; + using StartTaskGroupCallback = std::function; + using AbortContinuationImpl = std::function; + + virtual ~HashJoinImpl() = default; + virtual Status Init(QueryContext* ctx, JoinType join_type, size_t num_threads, + const HashJoinProjectionMaps* proj_map_left, + const HashJoinProjectionMaps* proj_map_right, + std::vector key_cmp, Expression filter, + RegisterTaskGroupCallback register_task_group_callback, + StartTaskGroupCallback start_task_group_callback, + OutputBatchCallback output_batch_callback, + FinishedCallback finished_callback) = 0; + + virtual Status BuildHashTable(size_t thread_index, AccumulationQueue batches, + BuildFinishedCallback on_finished) = 0; + virtual Status ProbeSingleBatch(size_t thread_index, ExecBatch batch) = 0; + virtual Status ProbingFinished(size_t thread_index) = 0; + virtual void Abort(TaskScheduler::AbortContinuationImpl pos_abort_callback) = 0; + virtual std::string ToString() const = 0; + + static Result> MakeBasic(); + static Result> MakeSwiss(); + + protected: + arrow::util::tracing::Span span_; +}; + +} // namespace acero +} // namespace arrow diff --git a/shared/package-files/26/26351c65324f65c125ee868a45ca4ad619bec11fe06e2ca3e786def7380588fa/FusedAdam.h b/shared/package-files/26/26351c65324f65c125ee868a45ca4ad619bec11fe06e2ca3e786def7380588fa/FusedAdam.h new file mode 100644 index 0000000000000000000000000000000000000000..db93f10bb95f168da44b24cb506ff5c04e3da06e --- /dev/null +++ b/shared/package-files/26/26351c65324f65c125ee868a45ca4ad619bec11fe06e2ca3e786def7380588fa/FusedAdam.h @@ -0,0 +1,27 @@ +#include +#include + +namespace at::native { + +enum class ADAM_MODE : uint8_t { ORIGINAL = 0, ADAMW = 1 }; + +using fused_adam_fn = void (*)( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& exp_avg, + const at::Tensor& exp_avg_sq, + const at::Tensor& max_exp_avg_sq, + const at::Tensor& state_step, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const float* grad_scale_ptr, + const ADAM_MODE); + +DECLARE_DISPATCH(fused_adam_fn, fused_adam_stub) + +} // namespace at::native diff --git a/shared/package-files/26/263efb01597f145e872654201568cb939c198759aecb28eb507f760fcccbbdd5/mod.cpython-311.pyc b/shared/package-files/26/263efb01597f145e872654201568cb939c198759aecb28eb507f760fcccbbdd5/mod.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93386a1b7e1df6d0086c2d224260add1e84359f6 Binary files /dev/null and b/shared/package-files/26/263efb01597f145e872654201568cb939c198759aecb28eb507f760fcccbbdd5/mod.cpython-311.pyc differ diff --git a/shared/package-files/26/2641e5973b7a22e56e760e1393efb017ec9f3cfb1d54e88c4da835b631888a1c/top_level.txt b/shared/package-files/26/2641e5973b7a22e56e760e1393efb017ec9f3cfb1d54e88c4da835b631888a1c/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6aed9737cae31f5f9ca039ea1959883e17c7ae25 --- /dev/null +++ b/shared/package-files/26/2641e5973b7a22e56e760e1393efb017ec9f3cfb1d54e88c4da835b631888a1c/top_level.txt @@ -0,0 +1 @@ +numcodecs diff --git a/shared/package-files/26/264433cc232332db871666b3bb6e4c2cb97b092cb8d5056a45ec2e53daea2b1c/reprlib.py b/shared/package-files/26/264433cc232332db871666b3bb6e4c2cb97b092cb8d5056a45ec2e53daea2b1c/reprlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f3518df105e418a995502b39c669c03b3d013ca7 --- /dev/null +++ b/shared/package-files/26/264433cc232332db871666b3bb6e4c2cb97b092cb8d5056a45ec2e53daea2b1c/reprlib.py @@ -0,0 +1,167 @@ +"""Redo the builtin repr() (representation) but with limits on most sizes.""" + +__all__ = ["Repr", "repr", "recursive_repr"] + +import builtins +from itertools import islice +from _thread import get_ident + +def recursive_repr(fillvalue='...'): + 'Decorator to make a repr function return fillvalue for a recursive call' + + def decorating_function(user_function): + repr_running = set() + + def wrapper(self): + key = id(self), get_ident() + if key in repr_running: + return fillvalue + repr_running.add(key) + try: + result = user_function(self) + finally: + repr_running.discard(key) + return result + + # Can't use functools.wraps() here because of bootstrap issues + wrapper.__module__ = getattr(user_function, '__module__') + wrapper.__doc__ = getattr(user_function, '__doc__') + wrapper.__name__ = getattr(user_function, '__name__') + wrapper.__qualname__ = getattr(user_function, '__qualname__') + wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) + return wrapper + + return decorating_function + +class Repr: + + def __init__(self): + self.fillvalue = '...' + self.maxlevel = 6 + self.maxtuple = 6 + self.maxlist = 6 + self.maxarray = 5 + self.maxdict = 4 + self.maxset = 6 + self.maxfrozenset = 6 + self.maxdeque = 6 + self.maxstring = 30 + self.maxlong = 40 + self.maxother = 30 + + def repr(self, x): + return self.repr1(x, self.maxlevel) + + def repr1(self, x, level): + typename = type(x).__name__ + if ' ' in typename: + parts = typename.split() + typename = '_'.join(parts) + if hasattr(self, 'repr_' + typename): + return getattr(self, 'repr_' + typename)(x, level) + else: + return self.repr_instance(x, level) + + def _repr_iterable(self, x, level, left, right, maxiter, trail=''): + n = len(x) + if level <= 0 and n: + s = self.fillvalue + else: + newlevel = level - 1 + repr1 = self.repr1 + pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)] + if n > maxiter: + pieces.append(self.fillvalue) + s = ', '.join(pieces) + if n == 1 and trail: + right = trail + right + return '%s%s%s' % (left, s, right) + + def repr_tuple(self, x, level): + return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',') + + def repr_list(self, x, level): + return self._repr_iterable(x, level, '[', ']', self.maxlist) + + def repr_array(self, x, level): + if not x: + return "array('%s')" % x.typecode + header = "array('%s', [" % x.typecode + return self._repr_iterable(x, level, header, '])', self.maxarray) + + def repr_set(self, x, level): + if not x: + return 'set()' + x = _possibly_sorted(x) + return self._repr_iterable(x, level, '{', '}', self.maxset) + + def repr_frozenset(self, x, level): + if not x: + return 'frozenset()' + x = _possibly_sorted(x) + return self._repr_iterable(x, level, 'frozenset({', '})', + self.maxfrozenset) + + def repr_deque(self, x, level): + return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque) + + def repr_dict(self, x, level): + n = len(x) + if n == 0: + return '{}' + if level <= 0: + return '{' + self.fillvalue + '}' + newlevel = level - 1 + repr1 = self.repr1 + pieces = [] + for key in islice(_possibly_sorted(x), self.maxdict): + keyrepr = repr1(key, newlevel) + valrepr = repr1(x[key], newlevel) + pieces.append('%s: %s' % (keyrepr, valrepr)) + if n > self.maxdict: + pieces.append(self.fillvalue) + s = ', '.join(pieces) + return '{%s}' % (s,) + + def repr_str(self, x, level): + s = builtins.repr(x[:self.maxstring]) + if len(s) > self.maxstring: + i = max(0, (self.maxstring-3)//2) + j = max(0, self.maxstring-3-i) + s = builtins.repr(x[:i] + x[len(x)-j:]) + s = s[:i] + self.fillvalue + s[len(s)-j:] + return s + + def repr_int(self, x, level): + s = builtins.repr(x) # XXX Hope this isn't too slow... + if len(s) > self.maxlong: + i = max(0, (self.maxlong-3)//2) + j = max(0, self.maxlong-3-i) + s = s[:i] + self.fillvalue + s[len(s)-j:] + return s + + def repr_instance(self, x, level): + try: + s = builtins.repr(x) + # Bugs in x.__repr__() can cause arbitrary + # exceptions -- then make up something + except Exception: + return '<%s instance at %#x>' % (x.__class__.__name__, id(x)) + if len(s) > self.maxother: + i = max(0, (self.maxother-3)//2) + j = max(0, self.maxother-3-i) + s = s[:i] + self.fillvalue + s[len(s)-j:] + return s + + +def _possibly_sorted(x): + # Since not all sequences of items can be sorted and comparison + # functions may raise arbitrary exceptions, return an unsorted + # sequence in that case. + try: + return sorted(x) + except Exception: + return list(x) + +aRepr = Repr() +repr = aRepr.repr diff --git a/shared/package-files/26/2644c61c2bd1d6b7783b68fcde600b6fc4a0ad2e4e273057f983ba6789f4889a/utils.py b/shared/package-files/26/2644c61c2bd1d6b7783b68fcde600b6fc4a0ad2e4e273057f983ba6789f4889a/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cc14a77244f658b9c23b6983be3788635d962c66 --- /dev/null +++ b/shared/package-files/26/2644c61c2bd1d6b7783b68fcde600b6fc4a0ad2e4e273057f983ba6789f4889a/utils.py @@ -0,0 +1,502 @@ +# mypy: allow-untyped-defs +""" +Contains various utils for AOTAutograd, including those for handling collections. +""" + +import dataclasses +import operator +import warnings +from contextlib import nullcontext +from functools import wraps +from typing import Any, Callable, Optional, Union + +import torch +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._logging import getArtifactLogger +from torch._subclasses.fake_tensor import FakeTensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import py_sym_types + + +KNOWN_TYPES = [ + torch.Tensor, + BackwardState, + int, + str, + float, + bool, + type(None), + *py_sym_types, + FakeScriptObject, + torch.ScriptObject, +] + +original_zip = zip + +aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects") + + +def strict_zip(*iterables, strict=True, **kwargs): + if not strict: + return original_zip(*iterables, **kwargs) + + length = len(iterables[0]) + for iterable in iterables[1:]: + if len(iterable) != length: + raise ValueError( + "The iterables have different lengths and strict mode is enabled." + ) + + return original_zip(*iterables, **kwargs) + + +def _get_symint_hints(exprs): + """ + Get the hints of a list/tuple of int/SymInt. + """ + if isinstance(exprs, (list, tuple)): + return type(exprs)(_get_symint_hints(e) for e in exprs) + elif isinstance(exprs, torch.SymInt): + return exprs.node.shape_env.size_hint(exprs.node.expr) + else: + return exprs + + +def partial_flatten_asdict(obj: Any) -> Any: + if dataclasses.is_dataclass(obj): + return { + field.name: getattr(obj, field.name) for field in dataclasses.fields(obj) + } + elif isinstance(obj, (list, tuple)): + return obj.__class__([partial_flatten_asdict(item) for item in obj]) + elif isinstance(obj, dict): + return {k: partial_flatten_asdict(v) for k, v in obj.items()} + else: + return obj + + +def normalize_as_list(x): + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def _get_autocast_states(): + return [ + torch.is_autocast_enabled("cuda"), + torch.is_autocast_enabled("cpu"), + torch.get_autocast_dtype("cuda"), + torch.get_autocast_dtype("cpu"), + torch.is_autocast_cache_enabled(), + ] + + +def make_boxed_func(f): + def g(args): + return f(*args) + + g._boxed_call = True # type: ignore[attr-defined] + return g + + +def make_boxed_compiler(compiler): + @wraps(compiler) + def f(fx_g, inps): + out_f = compiler(fx_g, inps) + fx_g = make_boxed_func(out_f) + return fx_g + + return f + + +def call_func_at_runtime_with_args( + f, args: Union[tuple[Any], list[Any]], steal_args=False, disable_amp=False +): + if not steal_args: + args = list(args) + assert isinstance(args, list) + + context = torch._C._DisableAutocast if disable_amp else nullcontext + with context(): + if hasattr(f, "_boxed_call"): + out = normalize_as_list(f(args)) + else: + # TODO: Please remove soon + # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 + warnings.warn( + "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. " + "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. " + "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale." + ) + out = normalize_as_list(f(*args)) + return out + + +# Inspired by autodidax (thanks!) +class PytreeThunk: + spec: Optional[pytree.TreeSpec] = None + # These are some kinda dumb microoptimizations that save about 3-4 us of overhead. + is_simple: Optional[ + bool + ] = None # if the output spec is a tuple/list, we won't bother unflattening it. + is_really_simple: Optional[bool] = None # if the output spec is a LeafSpec + + def set(self, spec: pytree.TreeSpec) -> None: + assert self.spec is None or self.spec == spec + assert spec is not None + self.spec: pytree.TreeSpec = spec + if self.spec.type in {tuple, list} and all( + child.is_leaf() for child in spec.children_specs + ): + self.is_simple = True + if self.spec.is_leaf(): + self.is_really_simple = True + + def unflatten(self, x: list[Any]) -> Any: + if self.is_really_simple: + return x[0] + if self.is_simple: + return x + assert self.spec is not None + return pytree.tree_unflatten(x, self.spec) + + +# Creates a function that returns flattened inputs and outputs +# Also returns the output tree spec, which is needed to recover the "unflattened" +# output tree structure later. +def create_tree_flattened_fn(fn, args, kwargs=None) -> tuple[Callable, PytreeThunk]: + if kwargs is None: + kwargs = {} + # Save the args_spec for flat_tensor_args to unflatten while tracing + _, tensor_args_spec = pytree.tree_flatten((args, kwargs)) + out_spec = PytreeThunk() + + def flat_fn(*flat_args): + # The input are flattened tensor args. Prepare the args in the + # order that original function expects. Add static args as well. + # They will appear as tensor constants in the traced graph. + nonlocal out_spec + args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec) + tree_out = fn(*args, **kwargs) + flat_out, spec = pytree.tree_flatten(tree_out) + for i in flat_out: + is_known_type = False + for j in KNOWN_TYPES: + if isinstance(i, j): + is_known_type = True + break + if not is_known_type: + raise RuntimeError( + f"Found {type(i)} in output, which is not a known type. " + "If this type holds tensors, you need to register a pytree for it. " + "See https://github.com/pytorch/functorch/issues/475 for a brief " + "explanation why. If you don't need to register a pytree, please " + "leave a comment explaining your use case and we'll make this more " + "ergonomic to deal with" + ) + out_spec.set(spec) + return flat_out + + # Can't use functools.wraps here because the wrapper has different + # calling convention + if hasattr(fn, "_orig_mod"): + flat_fn._orig_mod = fn._orig_mod # type: ignore[attr-defined] + + return flat_fn, out_spec + + +# This function takes in a tensor t, and returns one of t, t.view(), or t.clone(). +# When tracing the joint forward + backward, for any inputs in the graph that are mutated, +# we need to clone them first (and similarly for metadata-only mutations, we need to view them first). +# The idea is that when we trace the backward, we need to pass in the *original* primals +# to autograd.grad(), before they were mutated. +# Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them. +# This means that "idx" here represents the index of the (potentially) synthetic base. +# What we need to do is: +# (1) map the current (post-synthetic-base calling convention) input argument index +# to int index pre-synthetic-base-calling-convention. +# (2) There could be multiple, if this index corresponds to a synthetic base +# that has multiple input aliases. +# (3) If any of those corresponding inputs get metadata mutations, then we clone the base. +def maybe_to_fresh_input(idx, t, meta): + if not isinstance(t, torch.Tensor): + return t + if idx in meta.mutated_inp_runtime_indices: + # We only need to bother cloning mutated inputs that participate in autograd. + if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the mutation + return t.clone() + if meta.input_info[idx] and meta.input_info[idx].mutates_metadata: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the metadata mutation + return t.view(t.shape) + return t + + +def is_with_effects(node): + return ( + node.op == "call_function" + and node.target == torch.ops.higher_order.with_effects + ) + + +def is_with_effects_op(node, op): + return is_with_effects(node) and node.args[1] == op + + +def unlift_tokens(fw_module, fw_metadata, aot_config, bw_module=None): + # Remove the tokens from the inputs/outputs of the graph since inductor does + # not want these extra inputs/outputs, and replace them with + # _make_token() to create a token, and _sink_tokens() to collect the + # tokens. See Note [Side-Effectful Tokens in AOTAutograd] + # Logic: + # 1. Inputs identified as input tokens: + # - If used as a first argument in with_effects + # + # 2. Outputs identified as output tokens: + # - If Produced by getitem(with_effects, 0) + # + # 3. Checks invariants of number input output tokens: + # forward: + # expected_num_erased_inputs == len(fw_metadata.tokens) + # expected_num_erased_outputs == len(fw_metadata.tokens) + # backward: + # expected_num_erased_inputs == fw_metadata.num_backward_tokens + # expected_num_erased_outputs == fw_metadata.num_backward_tokens + num_forward_tokens = len(fw_metadata.tokens) + num_backward_tokens = fw_metadata.num_backward_tokens + + def rewrite_with_effects_input_token(module, node): + with module.graph.inserting_before(node): + new_token_node = module.graph.call_function( + torch.ops.prims._make_token.default, () + ) + new_token_node.meta["val"] = torch.tensor([]) + new_token_node.meta["tensor_meta"] = torch.tensor([]) + + args = list(node.args) + args[0] = new_token_node + node.args = tuple(args) + + def rewrite_output(module, node, output_token_nodes, other_output_args): + for output_token_node in output_token_nodes: + assert ( + output_token_node.op == "call_function" + and output_token_node.target == operator.getitem + and output_token_node.args[1] == 0 + ) + with module.graph.inserting_before(node): + module.graph.call_function( + torch.ops.prims._sink_tokens.default, + (output_token_nodes,), + ) + node.args = (other_output_args,) + + def do(module, subgraph, expected_num_erased): + num_erased_inputs = 0 + num_erased_outs = 0 + input_nodes = [] + input_token_nodes = set() + with_effect_nodes = [] + output_token_nodes = [] + other_output_nodes = [] + for node in module.graph.nodes: + if node.op == "placeholder": + input_nodes.append(node) + elif is_with_effects(node): + with_effect_nodes.append(node) + if node.args[0] in input_nodes: + input_token_nodes.add(node.args[0]) + rewrite_with_effects_input_token(module, node) + elif node.op == "output": + outs = node.args[0] + for out in outs: + if ( + isinstance(out, torch.fx.node.Node) + and out.op == "call_function" + and out.target == operator.getitem + and out.args[1] == 0 + and out.args[0] in with_effect_nodes + ): + output_token_nodes.append(out) + else: + other_output_nodes.append(out) + + rewrite_output(module, node, output_token_nodes, other_output_nodes) + num_erased_outs = len(output_token_nodes) + + for input_token_node in input_token_nodes: + module.graph.erase_node(input_token_node) + + num_erased_inputs = len(input_token_nodes) + + assert ( + num_erased_inputs == expected_num_erased + ), f"{subgraph} num_erased_inputs:{num_erased_inputs} {input_token_nodes}!=expected {expected_num_erased}" + assert ( + num_erased_outs == expected_num_erased + ), f"{subgraph} num_erased_outs:{num_erased_outs} {output_token_nodes}!=expected {expected_num_erased}" + + module.recompile() + + if num_forward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Forward graph before unlifting tokens", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + do( + fw_module, + "forward", + num_forward_tokens, + ) + + if bw_module is not None and num_backward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Backward graph before unlifting tokens", + bw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + do(bw_module, "backward", num_backward_tokens) + + # This is sad, but we need to update the metadata to get rid of + # the tokens. + fw_metadata.tokens = {} + fw_metadata.num_backward_tokens = 0 + + +def root_module_when_exporting_non_strict(flat_fn): + # When exporting in non-strict mode, we wrap the root module in a specific pattern. + # See `_aot_export_non_strict` in torch.export._trace.py. + # We look for that wrapping pattern here. + if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"): + return flat_fn._orig_mod._export_root + else: + return None + + +def copy_fwd_metadata_to_bw_nodes(fx_g): + """ + Input: `fx_g` which contains the joint fwd+bwd FX graph created by + aot_autograd. + + This function walks the graph and copies over metadata from forward nodes + to backward nodes, using the `seq_nr` field as a one-to-many mapping + from forward node to backward node. This metadata is useful for performance + profiling and debugging. + """ + + def _is_forward_node_with_seq_nr(node): + # For now, assume that if nn_module_stack_metadata is populated, this + # node is from the forward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this by walking + # the descendants of graph inputs corresponding to fwd inputs, didn't + # seem obvious at first glance on how to partition graph inputs into + # fwd vs bwd without relying on string names. + return "nn_module_stack" in node.meta and "seq_nr" in node.meta + + def _is_backward_node_with_seq_nr(node): + # For now, assume that if nn_module_stack_metadata is not populated, + # this node is from the backward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this, same + # as with the forward. + return ("nn_module_stack" not in node.meta) and "seq_nr" in node.meta + + fwd_seq_nr_to_node = {} + for node in fx_g.graph.nodes: + if not _is_forward_node_with_seq_nr(node): + continue + seq_nr = node.meta["seq_nr"] + if seq_nr in fwd_seq_nr_to_node: + # If we already saw an op with the current `seq_nr`, that means + # that the current op did not create an autograd node, and there + # is no corresponding backward node, so we skip. + continue + fwd_seq_nr_to_node[node.meta["seq_nr"]] = node + + for node in fx_g.graph.nodes: + if not _is_backward_node_with_seq_nr(node): + continue + # fwd_node should always exist, but handle non-existence just in case + fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"]) + if fwd_node is not None: + node.meta["fwd_nn_module_stack"] = fwd_node.meta["nn_module_stack"] + node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack") + + +def register_buffer_assignment_hook(mod, assigned_buffers): + """ + Register a hook that intercepts buffer assignments. + This is used to detect when a buffer is assigned to, and then we can + map that buffer to the corresponding proxy node in the graph. + """ + + def _map_assigned_buffer_to_proxy(_mod, name, buffer): + # We intercept buffer assignments on the root module through this hook. + if _mod._buffers is mod._buffers: + # either buffer is a functional tensor, which wraps a fake tensor + if isinstance(buffer, FunctionalTensor): + buffer = buffer.from_functional() + # or buffer is a fake tensor + assert isinstance(buffer, FakeTensor) + # The fake tensor in turn is associated with a proxy node. + proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode() + assert proxy_mode is not None + proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot( + buffer, proxy_mode.tracer + ).proxy.node + # We map the assigned buffer to this proxy node. + assigned_buffers[name] = proxy.name + return buffer + + return torch.nn.modules.module.register_module_buffer_registration_hook( + _map_assigned_buffer_to_proxy + ) + + +def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool: + """ + Checks if the module contains any metadata mutation ops. + """ + for node in module.graph.nodes: + if ( + node.op == "call_function" + and hasattr(node.target, "tags") + and torch.Tag.inplace_view in node.target.tags + ): + return True + return False + + +def get_cuda_generator_meta_val(device_idx: int): + """ + Get a generator value to use as a meta val + + newly cloned generator will not contain tensors. it is only Generators that are + registered to a CUDAGraph that contain tensors. since this does not contain Tensor + it is fine to use in the meta. + """ + return torch.cuda.default_generators[device_idx].clone_state() diff --git a/shared/package-files/26/2645720064c8318cf09bad9d7d5a9ab379cc7082e180ffd6773e9f878fcd103d/cupti.h b/shared/package-files/26/2645720064c8318cf09bad9d7d5a9ab379cc7082e180ffd6773e9f878fcd103d/cupti.h new file mode 100644 index 0000000000000000000000000000000000000000..be316531dcfd846bcea8feadf3604437ce2447a1 --- /dev/null +++ b/shared/package-files/26/2645720064c8318cf09bad9d7d5a9ab379cc7082e180ffd6773e9f878fcd103d/cupti.h @@ -0,0 +1,123 @@ +/* + * Copyright 2010-2017 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(_CUPTI_H_) +#define _CUPTI_H_ + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifdef NOMINMAX +#include +#else +#define NOMINMAX +#include +#undef NOMINMAX +#endif +#endif + +#include +#include +#include + +/* Activity, callback, event and metric APIs */ +#include +#include +#include +#include + +/* Runtime, driver, and nvtx function identifiers */ +#include +#include +#include + +/* To support function parameter structures for obsoleted API. See + cuda.h for the actual definition of these structures. */ +typedef unsigned int CUdeviceptr_v1; +typedef struct CUDA_MEMCPY2D_v1_st { int dummy; } CUDA_MEMCPY2D_v1; +typedef struct CUDA_MEMCPY3D_v1_st { int dummy; } CUDA_MEMCPY3D_v1; +typedef struct CUDA_ARRAY_DESCRIPTOR_v1_st { int dummy; } CUDA_ARRAY_DESCRIPTOR_v1; +typedef struct CUDA_ARRAY3D_DESCRIPTOR_v1_st { int dummy; } CUDA_ARRAY3D_DESCRIPTOR_v1; + +/* Function parameter structures */ +#include +#include + +/* The following parameter structures cannot be included unless a + header that defines GL_VERSION is included before including them. + If these are needed then make sure such a header is included + already. */ +#ifdef GL_VERSION +#include +#include +#endif + +//#include + +/* The following parameter structures cannot be included by default as + they are not guaranteed to be available on all systems. Uncomment + the includes that are available, or use the include explicitly. */ +#if defined(__linux__) +//#include +//#include +#endif + +#ifdef _WIN32 +//#include +//#include +//#include +//#include +//#include +//#include +#endif + +#endif /*_CUPTI_H_*/ + + diff --git a/shared/package-files/26/26468ee17216157504f778e23341d5f18d53c40ee622cd04d499b421a0b42a41/test_sparse_tensor.cpython-311.pyc b/shared/package-files/26/26468ee17216157504f778e23341d5f18d53c40ee622cd04d499b421a0b42a41/test_sparse_tensor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..499287001d29029aff12b181388a331a77e21625 Binary files /dev/null and b/shared/package-files/26/26468ee17216157504f778e23341d5f18d53c40ee622cd04d499b421a0b42a41/test_sparse_tensor.cpython-311.pyc differ diff --git a/shared/package-files/26/264734be3c433b5157654596968c7e74130ae9def404e97c8ac9f49cb5fb005b/test_treewidth.cpython-311.pyc b/shared/package-files/26/264734be3c433b5157654596968c7e74130ae9def404e97c8ac9f49cb5fb005b/test_treewidth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ae3d10ba8991712f49f8de2898c8cf71ba837a Binary files /dev/null and b/shared/package-files/26/264734be3c433b5157654596968c7e74130ae9def404e97c8ac9f49cb5fb005b/test_treewidth.cpython-311.pyc differ diff --git a/shared/package-files/26/264f8521fcc1544ce218c5fa69e4f147d6bf4a0d5afcf3e347e2ae0cf9287bba/functions.cpython-311.pyc b/shared/package-files/26/264f8521fcc1544ce218c5fa69e4f147d6bf4a0d5afcf3e347e2ae0cf9287bba/functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4471d6301b9f683672fe9e304cf024dfec4b0db5 Binary files /dev/null and b/shared/package-files/26/264f8521fcc1544ce218c5fa69e4f147d6bf4a0d5afcf3e347e2ae0cf9287bba/functions.cpython-311.pyc differ diff --git a/shared/package-files/26/265067f435735ef1db0ca3d87f217a76df278da34e790ea6911def74915433f2/test_pandas.py b/shared/package-files/26/265067f435735ef1db0ca3d87f217a76df278da34e790ea6911def74915433f2/test_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..5279f3f1cdfbe9fbec62f5685503c28b62f5f872 --- /dev/null +++ b/shared/package-files/26/265067f435735ef1db0ca3d87f217a76df278da34e790ea6911def74915433f2/test_pandas.py @@ -0,0 +1,2202 @@ +import datetime +from datetime import timedelta +from decimal import Decimal +from io import ( + BytesIO, + StringIO, +) +import json +import os +import sys +import time + +import numpy as np +import pytest + +from pandas._config import using_pyarrow_string_dtype + +from pandas.compat import IS64 +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import ( + NA, + DataFrame, + DatetimeIndex, + Index, + RangeIndex, + Series, + Timestamp, + date_range, + read_json, +) +import pandas._testing as tm +from pandas.core.arrays import ( + ArrowStringArray, + StringArray, +) +from pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics + +from pandas.io.json import ujson_dumps + + +def test_literal_json_deprecation(): + # PR 53409 + expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + + jsonl = """{"a": 1, "b": 2} + {"a": 3, "b": 4} + {"a": 5, "b": 6} + {"a": 7, "b": 8}""" + + msg = ( + "Passing literal json to 'read_json' is deprecated and " + "will be removed in a future version. To read from a " + "literal string, wrap it in a 'StringIO' object." + ) + + with tm.assert_produces_warning(FutureWarning, match=msg): + try: + read_json(jsonl, lines=False) + except ValueError: + pass + + with tm.assert_produces_warning(FutureWarning, match=msg): + read_json(expected.to_json(), lines=False) + + with tm.assert_produces_warning(FutureWarning, match=msg): + result = read_json('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n', lines=True) + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=msg): + try: + result = read_json( + '{"a\\\\":"foo\\\\","b":"bar"}\n{"a\\\\":"foo\\"","b":"bar"}\n', + lines=False, + ) + except ValueError: + pass + + with tm.assert_produces_warning(FutureWarning, match=msg): + try: + result = read_json('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n', lines=False) + except ValueError: + pass + tm.assert_frame_equal(result, expected) + + +def assert_json_roundtrip_equal(result, expected, orient): + if orient in ("records", "values"): + expected = expected.reset_index(drop=True) + if orient == "values": + expected.columns = range(len(expected.columns)) + tm.assert_frame_equal(result, expected) + + +class TestPandasContainer: + @pytest.fixture + def categorical_frame(self): + data = { + c: np.random.default_rng(i).standard_normal(30) + for i, c in enumerate(list("ABCD")) + } + cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * 15 + data["E"] = list(reversed(cat)) + data["sort"] = np.arange(30, dtype="int64") + return DataFrame(data, index=pd.CategoricalIndex(cat, name="E")) + + @pytest.fixture + def datetime_series(self): + # Same as usual datetime_series, but with index freq set to None, + # since that doesn't round-trip, see GH#33711 + ser = Series( + 1.1 * np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + ser.index = ser.index._with_freq(None) + return ser + + @pytest.fixture + def datetime_frame(self): + # Same as usual datetime_frame, but with index freq set to None, + # since that doesn't round-trip, see GH#33711 + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=30, freq="B"), + ) + df.index = df.index._with_freq(None) + return df + + def test_frame_double_encoded_labels(self, orient): + df = DataFrame( + [["a", "b"], ["c", "d"]], + index=['index " 1', "index / 2"], + columns=["a \\ b", "y / z"], + ) + + data = StringIO(df.to_json(orient=orient)) + result = read_json(data, orient=orient) + expected = df.copy() + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("orient", ["split", "records", "values"]) + def test_frame_non_unique_index(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"]) + data = StringIO(df.to_json(orient=orient)) + result = read_json(data, orient=orient) + expected = df.copy() + + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("orient", ["index", "columns"]) + def test_frame_non_unique_index_raises(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"]) + msg = f"DataFrame index must be unique for orient='{orient}'" + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient) + + @pytest.mark.parametrize("orient", ["split", "values"]) + @pytest.mark.parametrize( + "data", + [ + [["a", "b"], ["c", "d"]], + [[1.5, 2.5], [3.5, 4.5]], + [[1, 2.5], [3, 4.5]], + [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]], + ], + ) + def test_frame_non_unique_columns(self, orient, data): + df = DataFrame(data, index=[1, 2], columns=["x", "x"]) + + result = read_json( + StringIO(df.to_json(orient=orient)), orient=orient, convert_dates=["x"] + ) + if orient == "values": + expected = DataFrame(data) + if expected.iloc[:, 0].dtype == "datetime64[ns]": + # orient == "values" by default will write Timestamp objects out + # in milliseconds; these are internally stored in nanosecond, + # so divide to get where we need + # TODO: a to_epoch method would also solve; see GH 14772 + expected.isetitem(0, expected.iloc[:, 0].astype(np.int64) // 1000000) + elif orient == "split": + expected = df + expected.columns = ["x", "x.1"] + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("orient", ["index", "columns", "records"]) + def test_frame_non_unique_columns_raises(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 2], columns=["x", "x"]) + + msg = f"DataFrame columns must be unique for orient='{orient}'" + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient) + + def test_frame_default_orient(self, float_frame): + assert float_frame.to_json() == float_frame.to_json(orient="columns") + + @pytest.mark.parametrize("dtype", [False, float]) + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_simple(self, orient, convert_axes, dtype, float_frame): + data = StringIO(float_frame.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes, dtype=dtype) + + expected = float_frame + + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("dtype", [False, np.int64]) + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_intframe(self, orient, convert_axes, dtype, int_frame): + data = StringIO(int_frame.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes, dtype=dtype) + expected = int_frame + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("dtype", [None, np.float64, int, "U3"]) + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_str_axes(self, orient, convert_axes, dtype): + df = DataFrame( + np.zeros((200, 4)), + columns=[str(i) for i in range(4)], + index=[str(i) for i in range(200)], + dtype=dtype, + ) + + data = StringIO(df.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes, dtype=dtype) + + expected = df.copy() + if not dtype: + expected = expected.astype(np.int64) + + # index columns, and records orients cannot fully preserve the string + # dtype for axes as the index and column labels are used as keys in + # JSON objects. JSON keys are by definition strings, so there's no way + # to disambiguate whether those keys actually were strings or numeric + # beforehand and numeric wins out. + if convert_axes and (orient in ("index", "columns")): + expected.columns = expected.columns.astype(np.int64) + expected.index = expected.index.astype(np.int64) + elif orient == "records" and convert_axes: + expected.columns = expected.columns.astype(np.int64) + elif convert_axes and orient == "split": + expected.columns = expected.columns.astype(np.int64) + + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_categorical( + self, request, orient, categorical_frame, convert_axes, using_infer_string + ): + # TODO: create a better frame to test with and improve coverage + if orient in ("index", "columns"): + request.applymarker( + pytest.mark.xfail( + reason=f"Can't have duplicate index values for orient '{orient}')" + ) + ) + + data = StringIO(categorical_frame.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes) + + expected = categorical_frame.copy() + expected.index = expected.index.astype( + str if not using_infer_string else "string[pyarrow_numpy]" + ) # Categorical not preserved + expected.index.name = None # index names aren't preserved in JSON + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_empty(self, orient, convert_axes): + empty_frame = DataFrame() + data = StringIO(empty_frame.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes) + if orient == "split": + idx = Index([], dtype=(float if convert_axes else object)) + expected = DataFrame(index=idx, columns=idx) + elif orient in ["index", "columns"]: + expected = DataFrame() + else: + expected = empty_frame.copy() + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_timestamp(self, orient, convert_axes, datetime_frame): + # TODO: improve coverage with date_format parameter + data = StringIO(datetime_frame.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes) + expected = datetime_frame.copy() + + if not convert_axes: # one off for ts handling + # DTI gets converted to epoch values + idx = expected.index.view(np.int64) // 1000000 + if orient != "split": # TODO: handle consistently across orients + idx = idx.astype(str) + + expected.index = idx + + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_roundtrip_mixed(self, orient, convert_axes): + index = Index(["a", "b", "c", "d", "e"]) + values = { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], + "D": [True, False, True, False, True], + } + + df = DataFrame(data=values, index=index) + + data = StringIO(df.to_json(orient=orient)) + result = read_json(data, orient=orient, convert_axes=convert_axes) + + expected = df.copy() + expected = expected.assign(**expected.select_dtypes("number").astype(np.int64)) + + assert_json_roundtrip_equal(result, expected, orient) + + @pytest.mark.xfail( + reason="#50456 Column multiindex is stored and loaded differently", + raises=AssertionError, + ) + @pytest.mark.parametrize( + "columns", + [ + [["2022", "2022"], ["JAN", "FEB"]], + [["2022", "2023"], ["JAN", "JAN"]], + [["2022", "2022"], ["JAN", "JAN"]], + ], + ) + def test_roundtrip_multiindex(self, columns): + df = DataFrame( + [[1, 2], [3, 4]], + columns=pd.MultiIndex.from_arrays(columns), + ) + data = StringIO(df.to_json(orient="split")) + result = read_json(data, orient="split") + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize( + "data,msg,orient", + [ + ('{"key":b:a:d}', "Expected object or value", "columns"), + # too few indices + ( + '{"columns":["A","B"],' + '"index":["2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + "|".join( + [ + r"Length of values \(3\) does not match length of index \(2\)", + ] + ), + "split", + ), + # too many columns + ( + '{"columns":["A","B","C"],' + '"index":["1","2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + "3 columns passed, passed data had 2 columns", + "split", + ), + # bad key + ( + '{"badkey":["A","B"],' + '"index":["2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + r"unexpected key\(s\): badkey", + "split", + ), + ], + ) + def test_frame_from_json_bad_data_raises(self, data, msg, orient): + with pytest.raises(ValueError, match=msg): + read_json(StringIO(data), orient=orient) + + @pytest.mark.parametrize("dtype", [True, False]) + @pytest.mark.parametrize("convert_axes", [True, False]) + def test_frame_from_json_missing_data(self, orient, convert_axes, dtype): + num_df = DataFrame([[1, 2], [4, 5, 6]]) + + result = read_json( + StringIO(num_df.to_json(orient=orient)), + orient=orient, + convert_axes=convert_axes, + dtype=dtype, + ) + assert np.isnan(result.iloc[0, 2]) + + obj_df = DataFrame([["1", "2"], ["4", "5", "6"]]) + result = read_json( + StringIO(obj_df.to_json(orient=orient)), + orient=orient, + convert_axes=convert_axes, + dtype=dtype, + ) + assert np.isnan(result.iloc[0, 2]) + + @pytest.mark.parametrize("dtype", [True, False]) + def test_frame_read_json_dtype_missing_value(self, dtype): + # GH28501 Parse missing values using read_json with dtype=False + # to NaN instead of None + result = read_json(StringIO("[null]"), dtype=dtype) + expected = DataFrame([np.nan]) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("inf", [np.inf, -np.inf]) + @pytest.mark.parametrize("dtype", [True, False]) + def test_frame_infinity(self, inf, dtype): + # infinities get mapped to nulls which get mapped to NaNs during + # deserialisation + df = DataFrame([[1, 2], [4, 5, 6]]) + df.loc[0, 2] = inf + + data = StringIO(df.to_json()) + result = read_json(data, dtype=dtype) + assert np.isnan(result.iloc[0, 2]) + + @pytest.mark.skipif(not IS64, reason="not compliant on 32-bit, xref #15865") + @pytest.mark.parametrize( + "value,precision,expected_val", + [ + (0.95, 1, 1.0), + (1.95, 1, 2.0), + (-1.95, 1, -2.0), + (0.995, 2, 1.0), + (0.9995, 3, 1.0), + (0.99999999999999944, 15, 1.0), + ], + ) + def test_frame_to_json_float_precision(self, value, precision, expected_val): + df = DataFrame([{"a_float": value}]) + encoded = df.to_json(double_precision=precision) + assert encoded == f'{{"a_float":{{"0":{expected_val}}}}}' + + def test_frame_to_json_except(self): + df = DataFrame([1, 2, 3]) + msg = "Invalid value 'garbage' for option 'orient'" + with pytest.raises(ValueError, match=msg): + df.to_json(orient="garbage") + + def test_frame_empty(self): + df = DataFrame(columns=["jim", "joe"]) + assert not df._is_mixed_type + + data = StringIO(df.to_json()) + result = read_json(data, dtype=dict(df.dtypes)) + tm.assert_frame_equal(result, df, check_index_type=False) + + def test_frame_empty_to_json(self): + # GH 7445 + df = DataFrame({"test": []}, index=[]) + result = df.to_json(orient="columns") + expected = '{"test":{}}' + assert result == expected + + def test_frame_empty_mixedtype(self): + # mixed type + df = DataFrame(columns=["jim", "joe"]) + df["joe"] = df["joe"].astype("i8") + assert df._is_mixed_type + data = df.to_json() + tm.assert_frame_equal( + read_json(StringIO(data), dtype=dict(df.dtypes)), + df, + check_index_type=False, + ) + + def test_frame_mixedtype_orient(self): # GH10289 + vals = [ + [10, 1, "foo", 0.1, 0.01], + [20, 2, "bar", 0.2, 0.02], + [30, 3, "baz", 0.3, 0.03], + [40, 4, "qux", 0.4, 0.04], + ] + + df = DataFrame( + vals, index=list("abcd"), columns=["1st", "2nd", "3rd", "4th", "5th"] + ) + + assert df._is_mixed_type + right = df.copy() + + for orient in ["split", "index", "columns"]: + inp = StringIO(df.to_json(orient=orient)) + left = read_json(inp, orient=orient, convert_axes=False) + tm.assert_frame_equal(left, right) + + right.index = RangeIndex(len(df)) + inp = StringIO(df.to_json(orient="records")) + left = read_json(inp, orient="records", convert_axes=False) + tm.assert_frame_equal(left, right) + + right.columns = RangeIndex(df.shape[1]) + inp = StringIO(df.to_json(orient="values")) + left = read_json(inp, orient="values", convert_axes=False) + tm.assert_frame_equal(left, right) + + def test_v12_compat(self, datapath): + dti = date_range("2000-01-03", "2000-01-07") + # freq doesn't roundtrip + dti = DatetimeIndex(np.asarray(dti), freq=None) + df = DataFrame( + [ + [1.56808523, 0.65727391, 1.81021139, -0.17251653], + [-0.2550111, -0.08072427, -0.03202878, -0.17581665], + [1.51493992, 0.11805825, 1.629455, -1.31506612], + [-0.02765498, 0.44679743, 0.33192641, -0.27885413], + [0.05951614, -2.69652057, 1.28163262, 0.34703478], + ], + columns=["A", "B", "C", "D"], + index=dti, + ) + df["date"] = Timestamp("19920106 18:21:32.12").as_unit("ns") + df.iloc[3, df.columns.get_loc("date")] = Timestamp("20130101") + df["modified"] = df["date"] + df.iloc[1, df.columns.get_loc("modified")] = pd.NaT + + dirpath = datapath("io", "json", "data") + v12_json = os.path.join(dirpath, "tsframe_v012.json") + df_unser = read_json(v12_json) + tm.assert_frame_equal(df, df_unser) + + df_iso = df.drop(["modified"], axis=1) + v12_iso_json = os.path.join(dirpath, "tsframe_iso_v012.json") + df_unser_iso = read_json(v12_iso_json) + tm.assert_frame_equal(df_iso, df_unser_iso, check_column_type=False) + + def test_blocks_compat_GH9037(self, using_infer_string): + index = date_range("20000101", periods=10, freq="h") + # freq doesn't round-trip + index = DatetimeIndex(list(index), freq=None) + + df_mixed = DataFrame( + { + "float_1": [ + -0.92077639, + 0.77434435, + 1.25234727, + 0.61485564, + -0.60316077, + 0.24653374, + 0.28668979, + -2.51969012, + 0.95748401, + -1.02970536, + ], + "int_1": [ + 19680418, + 75337055, + 99973684, + 65103179, + 79373900, + 40314334, + 21290235, + 4991321, + 41903419, + 16008365, + ], + "str_1": [ + "78c608f1", + "64a99743", + "13d2ff52", + "ca7f4af2", + "97236474", + "bde7e214", + "1a6bde47", + "b1190be5", + "7a669144", + "8d64d068", + ], + "float_2": [ + -0.0428278, + -1.80872357, + 3.36042349, + -0.7573685, + -0.48217572, + 0.86229683, + 1.08935819, + 0.93898739, + -0.03030452, + 1.43366348, + ], + "str_2": [ + "14f04af9", + "d085da90", + "4bcfac83", + "81504caf", + "2ffef4a9", + "08e2f5c4", + "07e1af03", + "addbd4a7", + "1f6a09ba", + "4bfc4d87", + ], + "int_2": [ + 86967717, + 98098830, + 51927505, + 20372254, + 12601730, + 20884027, + 34193846, + 10561746, + 24867120, + 76131025, + ], + }, + index=index, + ) + + # JSON deserialisation always creates unicode strings + df_mixed.columns = df_mixed.columns.astype( + np.str_ if not using_infer_string else "string[pyarrow_numpy]" + ) + data = StringIO(df_mixed.to_json(orient="split")) + df_roundtrip = read_json(data, orient="split") + tm.assert_frame_equal( + df_mixed, + df_roundtrip, + check_index_type=True, + check_column_type=True, + by_blocks=True, + check_exact=True, + ) + + def test_frame_nonprintable_bytes(self): + # GH14256: failing column caused segfaults, if it is not the last one + + class BinaryThing: + def __init__(self, hexed) -> None: + self.hexed = hexed + self.binary = bytes.fromhex(hexed) + + def __str__(self) -> str: + return self.hexed + + hexed = "574b4454ba8c5eb4f98a8f45" + binthing = BinaryThing(hexed) + + # verify the proper conversion of printable content + df_printable = DataFrame({"A": [binthing.hexed]}) + assert df_printable.to_json() == f'{{"A":{{"0":"{hexed}"}}}}' + + # check if non-printable content throws appropriate Exception + df_nonprintable = DataFrame({"A": [binthing]}) + msg = "Unsupported UTF-8 sequence length when encoding string" + with pytest.raises(OverflowError, match=msg): + df_nonprintable.to_json() + + # the same with multiple columns threw segfaults + df_mixed = DataFrame({"A": [binthing], "B": [1]}, columns=["A", "B"]) + with pytest.raises(OverflowError, match=msg): + df_mixed.to_json() + + # default_handler should resolve exceptions for non-string types + result = df_nonprintable.to_json(default_handler=str) + expected = f'{{"A":{{"0":"{hexed}"}}}}' + assert result == expected + assert ( + df_mixed.to_json(default_handler=str) + == f'{{"A":{{"0":"{hexed}"}},"B":{{"0":1}}}}' + ) + + def test_label_overflow(self): + # GH14256: buffer length not checked when writing label + result = DataFrame({"bar" * 100000: [1], "foo": [1337]}).to_json() + expected = f'{{"{"bar" * 100000}":{{"0":1}},"foo":{{"0":1337}}}}' + assert result == expected + + def test_series_non_unique_index(self): + s = Series(["a", "b"], index=[1, 1]) + + msg = "Series index must be unique for orient='index'" + with pytest.raises(ValueError, match=msg): + s.to_json(orient="index") + + tm.assert_series_equal( + s, + read_json( + StringIO(s.to_json(orient="split")), orient="split", typ="series" + ), + ) + unserialized = read_json( + StringIO(s.to_json(orient="records")), orient="records", typ="series" + ) + tm.assert_equal(s.values, unserialized.values) + + def test_series_default_orient(self, string_series): + assert string_series.to_json() == string_series.to_json(orient="index") + + def test_series_roundtrip_simple(self, orient, string_series, using_infer_string): + data = StringIO(string_series.to_json(orient=orient)) + result = read_json(data, typ="series", orient=orient) + + expected = string_series + if using_infer_string and orient in ("split", "index", "columns"): + # These schemas don't contain dtypes, so we infer string + expected.index = expected.index.astype("string[pyarrow_numpy]") + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", [False, None]) + def test_series_roundtrip_object(self, orient, dtype, object_series): + data = StringIO(object_series.to_json(orient=orient)) + result = read_json(data, typ="series", orient=orient, dtype=dtype) + + expected = object_series + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None + + tm.assert_series_equal(result, expected) + + def test_series_roundtrip_empty(self, orient): + empty_series = Series([], index=[], dtype=np.float64) + data = StringIO(empty_series.to_json(orient=orient)) + result = read_json(data, typ="series", orient=orient) + + expected = empty_series.reset_index(drop=True) + if orient in ("split"): + expected.index = expected.index.astype(np.float64) + + tm.assert_series_equal(result, expected) + + def test_series_roundtrip_timeseries(self, orient, datetime_series): + data = StringIO(datetime_series.to_json(orient=orient)) + result = read_json(data, typ="series", orient=orient) + + expected = datetime_series + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", [np.float64, int]) + def test_series_roundtrip_numeric(self, orient, dtype): + s = Series(range(6), index=["a", "b", "c", "d", "e", "f"]) + data = StringIO(s.to_json(orient=orient)) + result = read_json(data, typ="series", orient=orient) + + expected = s.copy() + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + + tm.assert_series_equal(result, expected) + + def test_series_to_json_except(self): + s = Series([1, 2, 3]) + msg = "Invalid value 'garbage' for option 'orient'" + with pytest.raises(ValueError, match=msg): + s.to_json(orient="garbage") + + def test_series_from_json_precise_float(self): + s = Series([4.56, 4.56, 4.56]) + result = read_json(StringIO(s.to_json()), typ="series", precise_float=True) + tm.assert_series_equal(result, s, check_index_type=False) + + def test_series_with_dtype(self): + # GH 21986 + s = Series([4.56, 4.56, 4.56]) + result = read_json(StringIO(s.to_json()), typ="series", dtype=np.int64) + expected = Series([4] * 3) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype,expected", + [ + (True, Series(["2000-01-01"], dtype="datetime64[ns]")), + (False, Series([946684800000])), + ], + ) + def test_series_with_dtype_datetime(self, dtype, expected): + s = Series(["2000-01-01"], dtype="datetime64[ns]") + data = StringIO(s.to_json()) + result = read_json(data, typ="series", dtype=dtype) + tm.assert_series_equal(result, expected) + + def test_frame_from_json_precise_float(self): + df = DataFrame([[4.56, 4.56, 4.56], [4.56, 4.56, 4.56]]) + result = read_json(StringIO(df.to_json()), precise_float=True) + tm.assert_frame_equal(result, df) + + def test_typ(self): + s = Series(range(6), index=["a", "b", "c", "d", "e", "f"], dtype="int64") + result = read_json(StringIO(s.to_json()), typ=None) + tm.assert_series_equal(result, s) + + def test_reconstruction_index(self): + df = DataFrame([[1, 2, 3], [4, 5, 6]]) + result = read_json(StringIO(df.to_json())) + tm.assert_frame_equal(result, df) + + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=["A", "B", "C"]) + result = read_json(StringIO(df.to_json())) + tm.assert_frame_equal(result, df) + + def test_path(self, float_frame, int_frame, datetime_frame): + with tm.ensure_clean("test.json") as path: + for df in [float_frame, int_frame, datetime_frame]: + df.to_json(path) + read_json(path) + + def test_axis_dates(self, datetime_series, datetime_frame): + # frame + json = StringIO(datetime_frame.to_json()) + result = read_json(json) + tm.assert_frame_equal(result, datetime_frame) + + # series + json = StringIO(datetime_series.to_json()) + result = read_json(json, typ="series") + tm.assert_series_equal(result, datetime_series, check_names=False) + assert result.name is None + + def test_convert_dates(self, datetime_series, datetime_frame): + # frame + df = datetime_frame + df["date"] = Timestamp("20130101").as_unit("ns") + + json = StringIO(df.to_json()) + result = read_json(json) + tm.assert_frame_equal(result, df) + + df["foo"] = 1.0 + json = StringIO(df.to_json(date_unit="ns")) + + result = read_json(json, convert_dates=False) + expected = df.copy() + expected["date"] = expected["date"].values.view("i8") + expected["foo"] = expected["foo"].astype("int64") + tm.assert_frame_equal(result, expected) + + # series + ts = Series(Timestamp("20130101").as_unit("ns"), index=datetime_series.index) + json = StringIO(ts.to_json()) + result = read_json(json, typ="series") + tm.assert_series_equal(result, ts) + + @pytest.mark.parametrize("date_format", ["epoch", "iso"]) + @pytest.mark.parametrize("as_object", [True, False]) + @pytest.mark.parametrize("date_typ", [datetime.date, datetime.datetime, Timestamp]) + def test_date_index_and_values(self, date_format, as_object, date_typ): + data = [date_typ(year=2020, month=1, day=1), pd.NaT] + if as_object: + data.append("a") + + ser = Series(data, index=data) + result = ser.to_json(date_format=date_format) + + if date_format == "epoch": + expected = '{"1577836800000":1577836800000,"null":null}' + else: + expected = ( + '{"2020-01-01T00:00:00.000":"2020-01-01T00:00:00.000","null":null}' + ) + + if as_object: + expected = expected.replace("}", ',"a":"a"}') + + assert result == expected + + @pytest.mark.parametrize( + "infer_word", + [ + "trade_time", + "date", + "datetime", + "sold_at", + "modified", + "timestamp", + "timestamps", + ], + ) + def test_convert_dates_infer(self, infer_word): + # GH10747 + + data = [{"id": 1, infer_word: 1036713600000}, {"id": 2}] + expected = DataFrame( + [[1, Timestamp("2002-11-08")], [2, pd.NaT]], columns=["id", infer_word] + ) + + result = read_json(StringIO(ujson_dumps(data)))[["id", infer_word]] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "date,date_unit", + [ + ("20130101 20:43:42.123", None), + ("20130101 20:43:42", "s"), + ("20130101 20:43:42.123", "ms"), + ("20130101 20:43:42.123456", "us"), + ("20130101 20:43:42.123456789", "ns"), + ], + ) + def test_date_format_frame(self, date, date_unit, datetime_frame): + df = datetime_frame + + df["date"] = Timestamp(date).as_unit("ns") + df.iloc[1, df.columns.get_loc("date")] = pd.NaT + df.iloc[5, df.columns.get_loc("date")] = pd.NaT + if date_unit: + json = df.to_json(date_format="iso", date_unit=date_unit) + else: + json = df.to_json(date_format="iso") + + result = read_json(StringIO(json)) + expected = df.copy() + tm.assert_frame_equal(result, expected) + + def test_date_format_frame_raises(self, datetime_frame): + df = datetime_frame + msg = "Invalid value 'foo' for option 'date_unit'" + with pytest.raises(ValueError, match=msg): + df.to_json(date_format="iso", date_unit="foo") + + @pytest.mark.parametrize( + "date,date_unit", + [ + ("20130101 20:43:42.123", None), + ("20130101 20:43:42", "s"), + ("20130101 20:43:42.123", "ms"), + ("20130101 20:43:42.123456", "us"), + ("20130101 20:43:42.123456789", "ns"), + ], + ) + def test_date_format_series(self, date, date_unit, datetime_series): + ts = Series(Timestamp(date).as_unit("ns"), index=datetime_series.index) + ts.iloc[1] = pd.NaT + ts.iloc[5] = pd.NaT + if date_unit: + json = ts.to_json(date_format="iso", date_unit=date_unit) + else: + json = ts.to_json(date_format="iso") + + result = read_json(StringIO(json), typ="series") + expected = ts.copy() + tm.assert_series_equal(result, expected) + + def test_date_format_series_raises(self, datetime_series): + ts = Series(Timestamp("20130101 20:43:42.123"), index=datetime_series.index) + msg = "Invalid value 'foo' for option 'date_unit'" + with pytest.raises(ValueError, match=msg): + ts.to_json(date_format="iso", date_unit="foo") + + @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) + def test_date_unit(self, unit, datetime_frame): + df = datetime_frame + df["date"] = Timestamp("20130101 20:43:42").as_unit("ns") + dl = df.columns.get_loc("date") + df.iloc[1, dl] = Timestamp("19710101 20:43:42") + df.iloc[2, dl] = Timestamp("21460101 20:43:42") + df.iloc[4, dl] = pd.NaT + + json = df.to_json(date_format="epoch", date_unit=unit) + + # force date unit + result = read_json(StringIO(json), date_unit=unit) + tm.assert_frame_equal(result, df) + + # detect date unit + result = read_json(StringIO(json), date_unit=None) + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize("unit", ["s", "ms", "us"]) + def test_iso_non_nano_datetimes(self, unit): + # Test that numpy datetimes + # in an Index or a column with non-nano resolution can be serialized + # correctly + # GH53686 + index = DatetimeIndex( + [np.datetime64("2023-01-01T11:22:33.123456", unit)], + dtype=f"datetime64[{unit}]", + ) + df = DataFrame( + { + "date": Series( + [np.datetime64("2022-01-01T11:22:33.123456", unit)], + dtype=f"datetime64[{unit}]", + index=index, + ), + "date_obj": Series( + [np.datetime64("2023-01-01T11:22:33.123456", unit)], + dtype=object, + index=index, + ), + }, + ) + + buf = StringIO() + df.to_json(buf, date_format="iso", date_unit=unit) + buf.seek(0) + + # read_json always reads datetimes in nanosecond resolution + # TODO: check_dtype/check_index_type should be removable + # once read_json gets non-nano support + tm.assert_frame_equal( + read_json(buf, convert_dates=["date", "date_obj"]), + df, + check_index_type=False, + check_dtype=False, + ) + + def test_weird_nested_json(self): + # this used to core dump the parser + s = r"""{ + "status": "success", + "data": { + "posts": [ + { + "id": 1, + "title": "A blog post", + "body": "Some useful content" + }, + { + "id": 2, + "title": "Another blog post", + "body": "More content" + } + ] + } + }""" + read_json(StringIO(s)) + + def test_doc_example(self): + dfj2 = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("AB") + ) + dfj2["date"] = Timestamp("20130101") + dfj2["ints"] = range(5) + dfj2["bools"] = True + dfj2.index = date_range("20130101", periods=5) + + json = StringIO(dfj2.to_json()) + result = read_json(json, dtype={"ints": np.int64, "bools": np.bool_}) + tm.assert_frame_equal(result, result) + + def test_round_trip_exception(self, datapath): + # GH 3867 + path = datapath("io", "json", "data", "teams.csv") + df = pd.read_csv(path) + s = df.to_json() + + result = read_json(StringIO(s)) + res = result.reindex(index=df.index, columns=df.columns) + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = res.fillna(np.nan, downcast=False) + tm.assert_frame_equal(res, df) + + @pytest.mark.network + @pytest.mark.single_cpu + @pytest.mark.parametrize( + "field,dtype", + [ + ["created_at", pd.DatetimeTZDtype(tz="UTC")], + ["closed_at", "datetime64[ns]"], + ["updated_at", pd.DatetimeTZDtype(tz="UTC")], + ], + ) + def test_url(self, field, dtype, httpserver): + data = '{"created_at": ["2023-06-23T18:21:36Z"], "closed_at": ["2023-06-23T18:21:36"], "updated_at": ["2023-06-23T18:21:36Z"]}\n' # noqa: E501 + httpserver.serve_content(content=data) + result = read_json(httpserver.url, convert_dates=True) + assert result[field].dtype == dtype + + def test_timedelta(self): + converter = lambda x: pd.to_timedelta(x, unit="ms") + + ser = Series([timedelta(23), timedelta(seconds=5)]) + assert ser.dtype == "timedelta64[ns]" + + result = read_json(StringIO(ser.to_json()), typ="series").apply(converter) + tm.assert_series_equal(result, ser) + + ser = Series([timedelta(23), timedelta(seconds=5)], index=Index([0, 1])) + assert ser.dtype == "timedelta64[ns]" + result = read_json(StringIO(ser.to_json()), typ="series").apply(converter) + tm.assert_series_equal(result, ser) + + frame = DataFrame([timedelta(23), timedelta(seconds=5)]) + assert frame[0].dtype == "timedelta64[ns]" + tm.assert_frame_equal( + frame, read_json(StringIO(frame.to_json())).apply(converter) + ) + + def test_timedelta2(self): + frame = DataFrame( + { + "a": [timedelta(days=23), timedelta(seconds=5)], + "b": [1, 2], + "c": date_range(start="20130101", periods=2), + } + ) + data = StringIO(frame.to_json(date_unit="ns")) + result = read_json(data) + result["a"] = pd.to_timedelta(result.a, unit="ns") + result["c"] = pd.to_datetime(result.c) + tm.assert_frame_equal(frame, result) + + def test_mixed_timedelta_datetime(self): + td = timedelta(23) + ts = Timestamp("20130101") + frame = DataFrame({"a": [td, ts]}, dtype=object) + + expected = DataFrame( + {"a": [pd.Timedelta(td).as_unit("ns")._value, ts.as_unit("ns")._value]} + ) + data = StringIO(frame.to_json(date_unit="ns")) + result = read_json(data, dtype={"a": "int64"}) + tm.assert_frame_equal(result, expected, check_index_type=False) + + @pytest.mark.parametrize("as_object", [True, False]) + @pytest.mark.parametrize("date_format", ["iso", "epoch"]) + @pytest.mark.parametrize("timedelta_typ", [pd.Timedelta, timedelta]) + def test_timedelta_to_json(self, as_object, date_format, timedelta_typ): + # GH28156: to_json not correctly formatting Timedelta + data = [timedelta_typ(days=1), timedelta_typ(days=2), pd.NaT] + if as_object: + data.append("a") + + ser = Series(data, index=data) + if date_format == "iso": + expected = ( + '{"P1DT0H0M0S":"P1DT0H0M0S","P2DT0H0M0S":"P2DT0H0M0S","null":null}' + ) + else: + expected = '{"86400000":86400000,"172800000":172800000,"null":null}' + + if as_object: + expected = expected.replace("}", ',"a":"a"}') + + result = ser.to_json(date_format=date_format) + assert result == expected + + @pytest.mark.parametrize("as_object", [True, False]) + @pytest.mark.parametrize("timedelta_typ", [pd.Timedelta, timedelta]) + def test_timedelta_to_json_fractional_precision(self, as_object, timedelta_typ): + data = [timedelta_typ(milliseconds=42)] + ser = Series(data, index=data) + if as_object: + ser = ser.astype(object) + + result = ser.to_json() + expected = '{"42":42}' + assert result == expected + + def test_default_handler(self): + value = object() + frame = DataFrame({"a": [7, value]}) + expected = DataFrame({"a": [7, str(value)]}) + result = read_json(StringIO(frame.to_json(default_handler=str))) + tm.assert_frame_equal(expected, result, check_index_type=False) + + def test_default_handler_indirect(self): + def default(obj): + if isinstance(obj, complex): + return [("mathjs", "Complex"), ("re", obj.real), ("im", obj.imag)] + return str(obj) + + df_list = [ + 9, + DataFrame( + {"a": [1, "STR", complex(4, -5)], "b": [float("nan"), None, "N/A"]}, + columns=["a", "b"], + ), + ] + expected = ( + '[9,[[1,null],["STR",null],[[["mathjs","Complex"],' + '["re",4.0],["im",-5.0]],"N\\/A"]]]' + ) + assert ( + ujson_dumps(df_list, default_handler=default, orient="values") == expected + ) + + def test_default_handler_numpy_unsupported_dtype(self): + # GH12554 to_json raises 'Unhandled numpy dtype 15' + df = DataFrame( + {"a": [1, 2.3, complex(4, -5)], "b": [float("nan"), None, complex(1.2, 0)]}, + columns=["a", "b"], + ) + expected = ( + '[["(1+0j)","(nan+0j)"],' + '["(2.3+0j)","(nan+0j)"],' + '["(4-5j)","(1.2+0j)"]]' + ) + assert df.to_json(default_handler=str, orient="values") == expected + + def test_default_handler_raises(self): + msg = "raisin" + + def my_handler_raises(obj): + raise TypeError(msg) + + with pytest.raises(TypeError, match=msg): + DataFrame({"a": [1, 2, object()]}).to_json( + default_handler=my_handler_raises + ) + with pytest.raises(TypeError, match=msg): + DataFrame({"a": [1, 2, complex(4, -5)]}).to_json( + default_handler=my_handler_raises + ) + + def test_categorical(self): + # GH4377 df.to_json segfaults with non-ndarray blocks + df = DataFrame({"A": ["a", "b", "c", "a", "b", "b", "a"]}) + df["B"] = df["A"] + expected = df.to_json() + + df["B"] = df["A"].astype("category") + assert expected == df.to_json() + + s = df["A"] + sc = df["B"] + assert s.to_json() == sc.to_json() + + def test_datetime_tz(self): + # GH4377 df.to_json segfaults with non-ndarray blocks + tz_range = date_range("20130101", periods=3, tz="US/Eastern") + tz_naive = tz_range.tz_convert("utc").tz_localize(None) + + df = DataFrame({"A": tz_range, "B": date_range("20130101", periods=3)}) + + df_naive = df.copy() + df_naive["A"] = tz_naive + expected = df_naive.to_json() + assert expected == df.to_json() + + stz = Series(tz_range) + s_naive = Series(tz_naive) + assert stz.to_json() == s_naive.to_json() + + def test_sparse(self): + # GH4377 df.to_json segfaults with non-ndarray blocks + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + df.loc[:8] = np.nan + + sdf = df.astype("Sparse") + expected = df.to_json() + assert expected == sdf.to_json() + + s = Series(np.random.default_rng(2).standard_normal(10)) + s.loc[:8] = np.nan + ss = s.astype("Sparse") + + expected = s.to_json() + assert expected == ss.to_json() + + @pytest.mark.parametrize( + "ts", + [ + Timestamp("2013-01-10 05:00:00Z"), + Timestamp("2013-01-10 00:00:00", tz="US/Eastern"), + Timestamp("2013-01-10 00:00:00-0500"), + ], + ) + def test_tz_is_utc(self, ts): + exp = '"2013-01-10T05:00:00.000Z"' + + assert ujson_dumps(ts, iso_dates=True) == exp + dt = ts.to_pydatetime() + assert ujson_dumps(dt, iso_dates=True) == exp + + def test_tz_is_naive(self): + ts = Timestamp("2013-01-10 05:00:00") + exp = '"2013-01-10T05:00:00.000"' + + assert ujson_dumps(ts, iso_dates=True) == exp + dt = ts.to_pydatetime() + assert ujson_dumps(dt, iso_dates=True) == exp + + @pytest.mark.parametrize( + "tz_range", + [ + date_range("2013-01-01 05:00:00Z", periods=2), + date_range("2013-01-01 00:00:00", periods=2, tz="US/Eastern"), + date_range("2013-01-01 00:00:00-0500", periods=2), + ], + ) + def test_tz_range_is_utc(self, tz_range): + exp = '["2013-01-01T05:00:00.000Z","2013-01-02T05:00:00.000Z"]' + dfexp = ( + '{"DT":{' + '"0":"2013-01-01T05:00:00.000Z",' + '"1":"2013-01-02T05:00:00.000Z"}}' + ) + + assert ujson_dumps(tz_range, iso_dates=True) == exp + dti = DatetimeIndex(tz_range) + # Ensure datetimes in object array are serialized correctly + # in addition to the normal DTI case + assert ujson_dumps(dti, iso_dates=True) == exp + assert ujson_dumps(dti.astype(object), iso_dates=True) == exp + df = DataFrame({"DT": dti}) + result = ujson_dumps(df, iso_dates=True) + assert result == dfexp + assert ujson_dumps(df.astype({"DT": object}), iso_dates=True) + + def test_tz_range_is_naive(self): + dti = date_range("2013-01-01 05:00:00", periods=2) + + exp = '["2013-01-01T05:00:00.000","2013-01-02T05:00:00.000"]' + dfexp = '{"DT":{"0":"2013-01-01T05:00:00.000","1":"2013-01-02T05:00:00.000"}}' + + # Ensure datetimes in object array are serialized correctly + # in addition to the normal DTI case + assert ujson_dumps(dti, iso_dates=True) == exp + assert ujson_dumps(dti.astype(object), iso_dates=True) == exp + df = DataFrame({"DT": dti}) + result = ujson_dumps(df, iso_dates=True) + assert result == dfexp + assert ujson_dumps(df.astype({"DT": object}), iso_dates=True) + + def test_read_inline_jsonl(self): + # GH9180 + + result = read_json(StringIO('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n'), lines=True) + expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.single_cpu + @td.skip_if_not_us_locale + def test_read_s3_jsonl(self, s3_public_bucket_with_data, s3so): + # GH17200 + + result = read_json( + f"s3n://{s3_public_bucket_with_data.name}/items.jsonl", + lines=True, + storage_options=s3so, + ) + expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + def test_read_local_jsonl(self): + # GH17200 + with tm.ensure_clean("tmp_items.json") as path: + with open(path, "w", encoding="utf-8") as infile: + infile.write('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n') + result = read_json(path, lines=True) + expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + def test_read_jsonl_unicode_chars(self): + # GH15132: non-ascii unicode characters + # \u201d == RIGHT DOUBLE QUOTATION MARK + + # simulate file handle + json = '{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n' + json = StringIO(json) + result = read_json(json, lines=True) + expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + # simulate string + json = StringIO('{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n') + result = read_json(json, lines=True) + expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("bigNum", [sys.maxsize + 1, -(sys.maxsize + 2)]) + def test_to_json_large_numbers(self, bigNum): + # GH34473 + series = Series(bigNum, dtype=object, index=["articleId"]) + json = series.to_json() + expected = '{"articleId":' + str(bigNum) + "}" + assert json == expected + + df = DataFrame(bigNum, dtype=object, index=["articleId"], columns=[0]) + json = df.to_json() + expected = '{"0":{"articleId":' + str(bigNum) + "}}" + assert json == expected + + @pytest.mark.parametrize("bigNum", [-(2**63) - 1, 2**64]) + def test_read_json_large_numbers(self, bigNum): + # GH20599, 26068 + json = StringIO('{"articleId":' + str(bigNum) + "}") + msg = r"Value is too small|Value is too big" + with pytest.raises(ValueError, match=msg): + read_json(json) + + json = StringIO('{"0":{"articleId":' + str(bigNum) + "}}") + with pytest.raises(ValueError, match=msg): + read_json(json) + + def test_read_json_large_numbers2(self): + # GH18842 + json = '{"articleId": "1404366058080022500245"}' + json = StringIO(json) + result = read_json(json, typ="series") + expected = Series(1.404366e21, index=["articleId"]) + tm.assert_series_equal(result, expected) + + json = '{"0": {"articleId": "1404366058080022500245"}}' + json = StringIO(json) + result = read_json(json) + expected = DataFrame(1.404366e21, index=["articleId"], columns=[0]) + tm.assert_frame_equal(result, expected) + + def test_to_jsonl(self): + # GH9180 + df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a":1,"b":2}\n{"a":1,"b":2}\n' + assert result == expected + + df = DataFrame([["foo}", "bar"], ['foo"', "bar"]], columns=["a", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}\n' + assert result == expected + tm.assert_frame_equal(read_json(StringIO(result), lines=True), df) + + # GH15096: escaped characters in columns and data + df = DataFrame([["foo\\", "bar"], ['foo"', "bar"]], columns=["a\\", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a\\\\":"foo\\\\","b":"bar"}\n{"a\\\\":"foo\\"","b":"bar"}\n' + assert result == expected + + tm.assert_frame_equal(read_json(StringIO(result), lines=True), df) + + # TODO: there is a near-identical test for pytables; can we share? + @pytest.mark.xfail(reason="GH#13774 encoding kwarg not supported", raises=TypeError) + @pytest.mark.parametrize( + "val", + [ + [b"E\xc9, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"a", b"b", b"c"], + [b"EE, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"\xf8\xfc", b"a", b"b", b"c"], + [b"", b"a", b"b", b"c"], + [b"\xf8\xfc", b"a", b"b", b"c"], + [b"A\xf8\xfc", b"", b"a", b"b", b"c"], + [np.nan, b"", b"b", b"c"], + [b"A\xf8\xfc", np.nan, b"", b"b", b"c"], + ], + ) + @pytest.mark.parametrize("dtype", ["category", object]) + def test_latin_encoding(self, dtype, val): + # GH 13774 + ser = Series( + [x.decode("latin-1") if isinstance(x, bytes) else x for x in val], + dtype=dtype, + ) + encoding = "latin-1" + with tm.ensure_clean("test.json") as path: + ser.to_json(path, encoding=encoding) + retr = read_json(StringIO(path), encoding=encoding) + tm.assert_series_equal(ser, retr, check_categorical=False) + + def test_data_frame_size_after_to_json(self): + # GH15344 + df = DataFrame({"a": [str(1)]}) + + size_before = df.memory_usage(index=True, deep=True).sum() + df.to_json() + size_after = df.memory_usage(index=True, deep=True).sum() + + assert size_before == size_after + + @pytest.mark.parametrize( + "index", [None, [1, 2], [1.0, 2.0], ["a", "b"], ["1", "2"], ["1.", "2."]] + ) + @pytest.mark.parametrize("columns", [["a", "b"], ["1", "2"], ["1.", "2."]]) + def test_from_json_to_json_table_index_and_columns(self, index, columns): + # GH25433 GH25435 + expected = DataFrame([[1, 2], [3, 4]], index=index, columns=columns) + dfjson = expected.to_json(orient="table") + + result = read_json(StringIO(dfjson), orient="table") + tm.assert_frame_equal(result, expected) + + def test_from_json_to_json_table_dtypes(self): + # GH21345 + expected = DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["5", "6"]}) + dfjson = expected.to_json(orient="table") + result = read_json(StringIO(dfjson), orient="table") + tm.assert_frame_equal(result, expected) + + # TODO: We are casting to string which coerces None to NaN before casting back + # to object, ending up with incorrect na values + @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="incorrect na conversion") + @pytest.mark.parametrize("orient", ["split", "records", "index", "columns"]) + def test_to_json_from_json_columns_dtypes(self, orient): + # GH21892 GH33205 + expected = DataFrame.from_dict( + { + "Integer": Series([1, 2, 3], dtype="int64"), + "Float": Series([None, 2.0, 3.0], dtype="float64"), + "Object": Series([None, "", "c"], dtype="object"), + "Bool": Series([True, False, True], dtype="bool"), + "Category": Series(["a", "b", None], dtype="category"), + "Datetime": Series( + ["2020-01-01", None, "2020-01-03"], dtype="datetime64[ns]" + ), + } + ) + dfjson = expected.to_json(orient=orient) + + result = read_json( + StringIO(dfjson), + orient=orient, + dtype={ + "Integer": "int64", + "Float": "float64", + "Object": "object", + "Bool": "bool", + "Category": "category", + "Datetime": "datetime64[ns]", + }, + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", [True, {"b": int, "c": int}]) + def test_read_json_table_dtype_raises(self, dtype): + # GH21345 + df = DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["5", "6"]}) + dfjson = df.to_json(orient="table") + msg = "cannot pass both dtype and orient='table'" + with pytest.raises(ValueError, match=msg): + read_json(dfjson, orient="table", dtype=dtype) + + @pytest.mark.parametrize("orient", ["index", "columns", "records", "values"]) + def test_read_json_table_empty_axes_dtype(self, orient): + # GH28558 + + expected = DataFrame() + result = read_json(StringIO("{}"), orient=orient, convert_axes=True) + tm.assert_index_equal(result.index, expected.index) + tm.assert_index_equal(result.columns, expected.columns) + + def test_read_json_table_convert_axes_raises(self): + # GH25433 GH25435 + df = DataFrame([[1, 2], [3, 4]], index=[1.0, 2.0], columns=["1.", "2."]) + dfjson = df.to_json(orient="table") + msg = "cannot pass both convert_axes and orient='table'" + with pytest.raises(ValueError, match=msg): + read_json(dfjson, orient="table", convert_axes=True) + + @pytest.mark.parametrize( + "data, expected", + [ + ( + DataFrame([[1, 2], [4, 5]], columns=["a", "b"]), + {"columns": ["a", "b"], "data": [[1, 2], [4, 5]]}, + ), + ( + DataFrame([[1, 2], [4, 5]], columns=["a", "b"]).rename_axis("foo"), + {"columns": ["a", "b"], "data": [[1, 2], [4, 5]]}, + ), + ( + DataFrame( + [[1, 2], [4, 5]], columns=["a", "b"], index=[["a", "b"], ["c", "d"]] + ), + {"columns": ["a", "b"], "data": [[1, 2], [4, 5]]}, + ), + (Series([1, 2, 3], name="A"), {"name": "A", "data": [1, 2, 3]}), + ( + Series([1, 2, 3], name="A").rename_axis("foo"), + {"name": "A", "data": [1, 2, 3]}, + ), + ( + Series([1, 2], name="A", index=[["a", "b"], ["c", "d"]]), + {"name": "A", "data": [1, 2]}, + ), + ], + ) + def test_index_false_to_json_split(self, data, expected): + # GH 17394 + # Testing index=False in to_json with orient='split' + + result = data.to_json(orient="split", index=False) + result = json.loads(result) + + assert result == expected + + @pytest.mark.parametrize( + "data", + [ + (DataFrame([[1, 2], [4, 5]], columns=["a", "b"])), + (DataFrame([[1, 2], [4, 5]], columns=["a", "b"]).rename_axis("foo")), + ( + DataFrame( + [[1, 2], [4, 5]], columns=["a", "b"], index=[["a", "b"], ["c", "d"]] + ) + ), + (Series([1, 2, 3], name="A")), + (Series([1, 2, 3], name="A").rename_axis("foo")), + (Series([1, 2], name="A", index=[["a", "b"], ["c", "d"]])), + ], + ) + def test_index_false_to_json_table(self, data): + # GH 17394 + # Testing index=False in to_json with orient='table' + + result = data.to_json(orient="table", index=False) + result = json.loads(result) + + expected = { + "schema": pd.io.json.build_table_schema(data, index=False), + "data": DataFrame(data).to_dict(orient="records"), + } + + assert result == expected + + @pytest.mark.parametrize("orient", ["index", "columns"]) + def test_index_false_error_to_json(self, orient): + # GH 17394, 25513 + # Testing error message from to_json with index=False + + df = DataFrame([[1, 2], [4, 5]], columns=["a", "b"]) + + msg = ( + "'index=False' is only valid when 'orient' is 'split', " + "'table', 'records', or 'values'" + ) + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient, index=False) + + @pytest.mark.parametrize("orient", ["records", "values"]) + def test_index_true_error_to_json(self, orient): + # GH 25513 + # Testing error message from to_json with index=True + + df = DataFrame([[1, 2], [4, 5]], columns=["a", "b"]) + + msg = ( + "'index=True' is only valid when 'orient' is 'split', " + "'table', 'index', or 'columns'" + ) + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient, index=True) + + @pytest.mark.parametrize("orient", ["split", "table"]) + @pytest.mark.parametrize("index", [True, False]) + def test_index_false_from_json_to_json(self, orient, index): + # GH25170 + # Test index=False in from_json to_json + expected = DataFrame({"a": [1, 2], "b": [3, 4]}) + dfjson = expected.to_json(orient=orient, index=index) + result = read_json(StringIO(dfjson), orient=orient) + tm.assert_frame_equal(result, expected) + + def test_read_timezone_information(self): + # GH 25546 + result = read_json( + StringIO('{"2019-01-01T11:00:00.000Z":88}'), typ="series", orient="index" + ) + exp_dti = DatetimeIndex(["2019-01-01 11:00:00"], dtype="M8[ns, UTC]") + expected = Series([88], index=exp_dti) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "url", + [ + "s3://example-fsspec/", + "gcs://another-fsspec/file.json", + "https://example-site.com/data", + "some-protocol://data.txt", + ], + ) + def test_read_json_with_url_value(self, url): + # GH 36271 + result = read_json(StringIO(f'{{"url":{{"0":"{url}"}}}}')) + expected = DataFrame({"url": [url]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "compression", + ["", ".gz", ".bz2", ".tar"], + ) + def test_read_json_with_very_long_file_path(self, compression): + # GH 46718 + long_json_path = f'{"a" * 1000}.json{compression}' + with pytest.raises( + FileNotFoundError, match=f"File {long_json_path} does not exist" + ): + # path too long for Windows is handled in file_exists() but raises in + # _get_data_from_filepath() + read_json(long_json_path) + + @pytest.mark.parametrize( + "date_format,key", [("epoch", 86400000), ("iso", "P1DT0H0M0S")] + ) + def test_timedelta_as_label(self, date_format, key): + df = DataFrame([[1]], columns=[pd.Timedelta("1D")]) + expected = f'{{"{key}":{{"0":1}}}}' + result = df.to_json(date_format=date_format) + + assert result == expected + + @pytest.mark.parametrize( + "orient,expected", + [ + ("index", "{\"('a', 'b')\":{\"('c', 'd')\":1}}"), + ("columns", "{\"('c', 'd')\":{\"('a', 'b')\":1}}"), + # TODO: the below have separate encoding procedures + pytest.param( + "split", + "", + marks=pytest.mark.xfail( + reason="Produces JSON but not in a consistent manner" + ), + ), + pytest.param( + "table", + "", + marks=pytest.mark.xfail( + reason="Produces JSON but not in a consistent manner" + ), + ), + ], + ) + def test_tuple_labels(self, orient, expected): + # GH 20500 + df = DataFrame([[1]], index=[("a", "b")], columns=[("c", "d")]) + result = df.to_json(orient=orient) + assert result == expected + + @pytest.mark.parametrize("indent", [1, 2, 4]) + def test_to_json_indent(self, indent): + # GH 12004 + df = DataFrame([["foo", "bar"], ["baz", "qux"]], columns=["a", "b"]) + + result = df.to_json(indent=indent) + spaces = " " * indent + expected = f"""{{ +{spaces}"a":{{ +{spaces}{spaces}"0":"foo", +{spaces}{spaces}"1":"baz" +{spaces}}}, +{spaces}"b":{{ +{spaces}{spaces}"0":"bar", +{spaces}{spaces}"1":"qux" +{spaces}}} +}}""" + + assert result == expected + + @pytest.mark.skipif( + using_pyarrow_string_dtype(), + reason="Adjust expected when infer_string is default, no bug here, " + "just a complicated parametrization", + ) + @pytest.mark.parametrize( + "orient,expected", + [ + ( + "split", + """{ + "columns":[ + "a", + "b" + ], + "index":[ + 0, + 1 + ], + "data":[ + [ + "foo", + "bar" + ], + [ + "baz", + "qux" + ] + ] +}""", + ), + ( + "records", + """[ + { + "a":"foo", + "b":"bar" + }, + { + "a":"baz", + "b":"qux" + } +]""", + ), + ( + "index", + """{ + "0":{ + "a":"foo", + "b":"bar" + }, + "1":{ + "a":"baz", + "b":"qux" + } +}""", + ), + ( + "columns", + """{ + "a":{ + "0":"foo", + "1":"baz" + }, + "b":{ + "0":"bar", + "1":"qux" + } +}""", + ), + ( + "values", + """[ + [ + "foo", + "bar" + ], + [ + "baz", + "qux" + ] +]""", + ), + ( + "table", + """{ + "schema":{ + "fields":[ + { + "name":"index", + "type":"integer" + }, + { + "name":"a", + "type":"string" + }, + { + "name":"b", + "type":"string" + } + ], + "primaryKey":[ + "index" + ], + "pandas_version":"1.4.0" + }, + "data":[ + { + "index":0, + "a":"foo", + "b":"bar" + }, + { + "index":1, + "a":"baz", + "b":"qux" + } + ] +}""", + ), + ], + ) + def test_json_indent_all_orients(self, orient, expected): + # GH 12004 + df = DataFrame([["foo", "bar"], ["baz", "qux"]], columns=["a", "b"]) + result = df.to_json(orient=orient, indent=4) + assert result == expected + + def test_json_negative_indent_raises(self): + with pytest.raises(ValueError, match="must be a nonnegative integer"): + DataFrame().to_json(indent=-1) + + def test_emca_262_nan_inf_support(self): + # GH 12213 + data = StringIO( + '["a", NaN, "NaN", Infinity, "Infinity", -Infinity, "-Infinity"]' + ) + result = read_json(data) + expected = DataFrame( + ["a", None, "NaN", np.inf, "Infinity", -np.inf, "-Infinity"] + ) + tm.assert_frame_equal(result, expected) + + def test_frame_int_overflow(self): + # GH 30320 + encoded_json = json.dumps([{"col": "31900441201190696999"}, {"col": "Text"}]) + expected = DataFrame({"col": ["31900441201190696999", "Text"]}) + result = read_json(StringIO(encoded_json)) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dataframe,expected", + [ + ( + DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}), + '{"(0, \'x\')":1,"(0, \'y\')":"a","(1, \'x\')":2,' + '"(1, \'y\')":"b","(2, \'x\')":3,"(2, \'y\')":"c"}', + ) + ], + ) + def test_json_multiindex(self, dataframe, expected): + series = dataframe.stack(future_stack=True) + result = series.to_json(orient="index") + assert result == expected + + @pytest.mark.single_cpu + def test_to_s3(self, s3_public_bucket, s3so): + # GH 28375 + mock_bucket_name, target_file = s3_public_bucket.name, "test.json" + df = DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]}) + df.to_json(f"s3://{mock_bucket_name}/{target_file}", storage_options=s3so) + timeout = 5 + while True: + if target_file in (obj.key for obj in s3_public_bucket.objects.all()): + break + time.sleep(0.1) + timeout -= 0.1 + assert timeout > 0, "Timed out waiting for file to appear on moto" + + def test_json_pandas_nulls(self, nulls_fixture, request): + # GH 31615 + if isinstance(nulls_fixture, Decimal): + mark = pytest.mark.xfail(reason="not implemented") + request.applymarker(mark) + + result = DataFrame([[nulls_fixture]]).to_json() + assert result == '{"0":{"0":null}}' + + def test_readjson_bool_series(self): + # GH31464 + result = read_json(StringIO("[true, true, false]"), typ="series") + expected = Series([True, True, False]) + tm.assert_series_equal(result, expected) + + def test_to_json_multiindex_escape(self): + # GH 15273 + df = DataFrame( + True, + index=date_range("2017-01-20", "2017-01-23"), + columns=["foo", "bar"], + ).stack(future_stack=True) + result = df.to_json() + expected = ( + "{\"(Timestamp('2017-01-20 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-20 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-21 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-21 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-22 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-22 00:00:00'), 'bar')\":true," + "\"(Timestamp('2017-01-23 00:00:00'), 'foo')\":true," + "\"(Timestamp('2017-01-23 00:00:00'), 'bar')\":true}" + ) + assert result == expected + + def test_to_json_series_of_objects(self): + class _TestObject: + def __init__(self, a, b, _c, d) -> None: + self.a = a + self.b = b + self._c = _c + self.d = d + + def e(self): + return 5 + + # JSON keys should be all non-callable non-underscore attributes, see GH-42768 + series = Series([_TestObject(a=1, b=2, _c=3, d=4)]) + assert json.loads(series.to_json()) == {"0": {"a": 1, "b": 2, "d": 4}} + + @pytest.mark.parametrize( + "data,expected", + [ + ( + Series({0: -6 + 8j, 1: 0 + 1j, 2: 9 - 5j}), + '{"0":{"imag":8.0,"real":-6.0},' + '"1":{"imag":1.0,"real":0.0},' + '"2":{"imag":-5.0,"real":9.0}}', + ), + ( + Series({0: -9.39 + 0.66j, 1: 3.95 + 9.32j, 2: 4.03 - 0.17j}), + '{"0":{"imag":0.66,"real":-9.39},' + '"1":{"imag":9.32,"real":3.95},' + '"2":{"imag":-0.17,"real":4.03}}', + ), + ( + DataFrame([[-2 + 3j, -1 - 0j], [4 - 3j, -0 - 10j]]), + '{"0":{"0":{"imag":3.0,"real":-2.0},' + '"1":{"imag":-3.0,"real":4.0}},' + '"1":{"0":{"imag":0.0,"real":-1.0},' + '"1":{"imag":-10.0,"real":0.0}}}', + ), + ( + DataFrame( + [[-0.28 + 0.34j, -1.08 - 0.39j], [0.41 - 0.34j, -0.78 - 1.35j]] + ), + '{"0":{"0":{"imag":0.34,"real":-0.28},' + '"1":{"imag":-0.34,"real":0.41}},' + '"1":{"0":{"imag":-0.39,"real":-1.08},' + '"1":{"imag":-1.35,"real":-0.78}}}', + ), + ], + ) + def test_complex_data_tojson(self, data, expected): + # GH41174 + result = data.to_json() + assert result == expected + + def test_json_uint64(self): + # GH21073 + expected = ( + '{"columns":["col1"],"index":[0,1],' + '"data":[[13342205958987758245],[12388075603347835679]]}' + ) + df = DataFrame(data={"col1": [13342205958987758245, 12388075603347835679]}) + result = df.to_json(orient="split") + assert result == expected + + @pytest.mark.parametrize( + "orient", ["split", "records", "values", "index", "columns"] + ) + def test_read_json_dtype_backend( + self, string_storage, dtype_backend, orient, using_infer_string + ): + # GH#50750 + pa = pytest.importorskip("pyarrow") + df = DataFrame( + { + "a": Series([1, np.nan, 3], dtype="Int64"), + "b": Series([1, 2, 3], dtype="Int64"), + "c": Series([1.5, np.nan, 2.5], dtype="Float64"), + "d": Series([1.5, 2.0, 2.5], dtype="Float64"), + "e": [True, False, None], + "f": [True, False, True], + "g": ["a", "b", "c"], + "h": ["a", "b", None], + } + ) + + if using_infer_string: + string_array = ArrowStringArrayNumpySemantics(pa.array(["a", "b", "c"])) + string_array_na = ArrowStringArrayNumpySemantics(pa.array(["a", "b", None])) + elif string_storage == "python": + string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) + string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_)) + + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["a", "b", "c"])) + string_array_na = ArrowExtensionArray(pa.array(["a", "b", None])) + + else: + string_array = ArrowStringArray(pa.array(["a", "b", "c"])) + string_array_na = ArrowStringArray(pa.array(["a", "b", None])) + + out = df.to_json(orient=orient) + with pd.option_context("mode.string_storage", string_storage): + result = read_json( + StringIO(out), dtype_backend=dtype_backend, orient=orient + ) + + expected = DataFrame( + { + "a": Series([1, np.nan, 3], dtype="Int64"), + "b": Series([1, 2, 3], dtype="Int64"), + "c": Series([1.5, np.nan, 2.5], dtype="Float64"), + "d": Series([1.5, 2.0, 2.5], dtype="Float64"), + "e": Series([True, False, NA], dtype="boolean"), + "f": Series([True, False, True], dtype="boolean"), + "g": string_array, + "h": string_array_na, + } + ) + + if dtype_backend == "pyarrow": + from pandas.arrays import ArrowExtensionArray + + expected = DataFrame( + { + col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True)) + for col in expected.columns + } + ) + + if orient == "values": + expected.columns = list(range(8)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("orient", ["split", "records", "index"]) + def test_read_json_nullable_series(self, string_storage, dtype_backend, orient): + # GH#50750 + pa = pytest.importorskip("pyarrow") + ser = Series([1, np.nan, 3], dtype="Int64") + + out = ser.to_json(orient=orient) + with pd.option_context("mode.string_storage", string_storage): + result = read_json( + StringIO(out), dtype_backend=dtype_backend, orient=orient, typ="series" + ) + + expected = Series([1, np.nan, 3], dtype="Int64") + + if dtype_backend == "pyarrow": + from pandas.arrays import ArrowExtensionArray + + expected = Series(ArrowExtensionArray(pa.array(expected, from_pandas=True))) + + tm.assert_series_equal(result, expected) + + def test_invalid_dtype_backend(self): + msg = ( + "dtype_backend numpy is invalid, only 'numpy_nullable' and " + "'pyarrow' are allowed." + ) + with pytest.raises(ValueError, match=msg): + read_json("test", dtype_backend="numpy") + + +def test_invalid_engine(): + # GH 48893 + ser = Series(range(1)) + out = ser.to_json() + with pytest.raises(ValueError, match="The engine type foo"): + read_json(out, engine="foo") + + +def test_pyarrow_engine_lines_false(): + # GH 48893 + ser = Series(range(1)) + out = ser.to_json() + with pytest.raises(ValueError, match="currently pyarrow engine only supports"): + read_json(out, engine="pyarrow", lines=False) + + +def test_json_roundtrip_string_inference(orient): + pytest.importorskip("pyarrow") + df = DataFrame( + [["a", "b"], ["c", "d"]], index=["row 1", "row 2"], columns=["col 1", "col 2"] + ) + out = df.to_json() + with pd.option_context("future.infer_string", True): + result = read_json(StringIO(out)) + expected = DataFrame( + [["a", "b"], ["c", "d"]], + dtype="string[pyarrow_numpy]", + index=Index(["row 1", "row 2"], dtype="string[pyarrow_numpy]"), + columns=Index(["col 1", "col 2"], dtype="string[pyarrow_numpy]"), + ) + tm.assert_frame_equal(result, expected) + + +def test_json_pos_args_deprecation(): + # GH-54229 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"Starting with pandas version 3.0 all arguments of to_json except for the " + r"argument 'path_or_buf' will be keyword-only." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + buf = BytesIO() + df.to_json(buf, "split") + + +@td.skip_if_no("pyarrow") +def test_to_json_ea_null(): + # GH#57224 + df = DataFrame( + { + "a": Series([1, NA], dtype="int64[pyarrow]"), + "b": Series([2, NA], dtype="Int64"), + } + ) + result = df.to_json(orient="records", lines=True) + expected = """{"a":1,"b":2} +{"a":null,"b":null} +""" + assert result == expected + + +def test_read_json_lines_rangeindex(): + # GH 57429 + data = """ +{"a": 1, "b": 2} +{"a": 3, "b": 4} +""" + result = read_json(StringIO(data), lines=True).index + expected = RangeIndex(2) + tm.assert_index_equal(result, expected, exact=True) diff --git a/shared/package-files/26/2652809f4f305733604a98aba52899ef0b7fd845522cfcb00b023730b73dace4/version.cpython-311.pyc b/shared/package-files/26/2652809f4f305733604a98aba52899ef0b7fd845522cfcb00b023730b73dace4/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7c60ffdb956af9a0f56bbe26577df8086278658 Binary files /dev/null and b/shared/package-files/26/2652809f4f305733604a98aba52899ef0b7fd845522cfcb00b023730b73dace4/version.cpython-311.pyc differ diff --git a/shared/package-files/26/2652bbb5812092533cd77da10f358458c855acccbff519aa01030afd64fd7404/squeeze_copy_native.h b/shared/package-files/26/2652bbb5812092533cd77da10f358458c855acccbff519aa01030afd64fd7404/squeeze_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ee37226e6e711b0d5d8f58ccdc0b3f320a0f50a6 --- /dev/null +++ b/shared/package-files/26/2652bbb5812092533cd77da10f358458c855acccbff519aa01030afd64fd7404/squeeze_copy_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & squeeze_copy_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor squeeze_copy(const at::Tensor & self); +TORCH_API at::Tensor & squeeze_copy_dim_out(const at::Tensor & self, int64_t dim, at::Tensor & out); +TORCH_API at::Tensor squeeze_copy_dim(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & squeeze_copy_dims_out(const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out); +TORCH_API at::Tensor squeeze_copy_dims(const at::Tensor & self, at::IntArrayRef dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/26/265f5451c94ed53a29ab1583467f9e6f2485e50d3277a7ae771a817ee94f6803/_unsafe_index_put_ops.h b/shared/package-files/26/265f5451c94ed53a29ab1583467f9e6f2485e50d3277a7ae771a817ee94f6803/_unsafe_index_put_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..86ebeffcc22c73e7e4fe1c0b0ccd040901f9e360 --- /dev/null +++ b/shared/package-files/26/265f5451c94ed53a29ab1583467f9e6f2485e50d3277a7ae771a817ee94f6803/_unsafe_index_put_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _unsafe_index_put { + using schema = at::Tensor (const at::Tensor &, const c10::List<::std::optional> &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_unsafe_index_put"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const c10::List<::std::optional> & indices, const at::Tensor & values, bool accumulate); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::List<::std::optional> & indices, const at::Tensor & values, bool accumulate); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/265fd081a0149c3b232521cb81356915da648729a2d5335c99d4d5487aadcee6/true_divide.h b/shared/package-files/26/265fd081a0149c3b232521cb81356915da648729a2d5335c99d4d5487aadcee6/true_divide.h new file mode 100644 index 0000000000000000000000000000000000000000..e7725e5b01a00257d678b6b978a213b49e40a9ab --- /dev/null +++ b/shared/package-files/26/265fd081a0149c3b232521cb81356915da648729a2d5335c99d4d5487aadcee6/true_divide.h @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::true_divide.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor true_divide(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::true_divide_Tensor::call(self, other); +} + +// aten::true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & true_divide_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::true_divide_out::call(self, other, out); +} +// aten::true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & true_divide_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::true_divide_out::call(self, other, out); +} + +// aten::true_divide.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor true_divide(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::true_divide_Scalar::call(self, other); +} + +} diff --git a/shared/package-files/26/2662b1254931a200c4f413c8db06669c384691b08b4451a3858188f47a850870/test_transpose.cpython-311.pyc b/shared/package-files/26/2662b1254931a200c4f413c8db06669c384691b08b4451a3858188f47a850870/test_transpose.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a7c5a9160b5fa02e31e75be44d657d17a45db4 Binary files /dev/null and b/shared/package-files/26/2662b1254931a200c4f413c8db06669c384691b08b4451a3858188f47a850870/test_transpose.cpython-311.pyc differ diff --git a/shared/package-files/26/26638e5396409762eb7a427fa49f524cff5522b0b93df1f01df8d16442268dcb/lazy.cpython-311.pyc b/shared/package-files/26/26638e5396409762eb7a427fa49f524cff5522b0b93df1f01df8d16442268dcb/lazy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52e13953eb18cabfd290d3be545fbeaa9717fd9e Binary files /dev/null and b/shared/package-files/26/26638e5396409762eb7a427fa49f524cff5522b0b93df1f01df8d16442268dcb/lazy.cpython-311.pyc differ diff --git a/shared/package-files/26/266588c5469b4c66d30fdd3e3ddcc1628d05ddc2a85f034b72b9d3e8f775d6d8/ck_universal_gemm_template.cpython-311.pyc b/shared/package-files/26/266588c5469b4c66d30fdd3e3ddcc1628d05ddc2a85f034b72b9d3e8f775d6d8/ck_universal_gemm_template.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..924ee10e3bfbae6695d474dc660eec1454f67ace Binary files /dev/null and b/shared/package-files/26/266588c5469b4c66d30fdd3e3ddcc1628d05ddc2a85f034b72b9d3e8f775d6d8/ck_universal_gemm_template.cpython-311.pyc differ diff --git a/shared/package-files/26/266a46ff4fdc23108c02ae57c6c9f8d17faaee3b3e8a63a6b02ded02bfffa566/__init__.cpython-311.pyc b/shared/package-files/26/266a46ff4fdc23108c02ae57c6c9f8d17faaee3b3e8a63a6b02ded02bfffa566/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf321d6b103779af46005692022c71909af42c0 Binary files /dev/null and b/shared/package-files/26/266a46ff4fdc23108c02ae57c6c9f8d17faaee3b3e8a63a6b02ded02bfffa566/__init__.cpython-311.pyc differ diff --git a/shared/package-files/26/26702da7b6110bb5fe677294b66e80fa5364d1b911c2158420b9b989ce899620/import_export_helpers.h b/shared/package-files/26/26702da7b6110bb5fe677294b66e80fa5364d1b911c2158420b9b989ce899620/import_export_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..4cd2bd8c43c8b84c70d1b8bbf009c10bb5a5081a --- /dev/null +++ b/shared/package-files/26/26702da7b6110bb5fe677294b66e80fa5364d1b911c2158420b9b989ce899620/import_export_helpers.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +namespace caffe2::serialize { +class PyTorchStreamReader; +} + +namespace torch::jit { + +struct Source; + +// Convert a class type's qualifier name to the corresponding path the source +// file it should be written to. +// +// Qualifier is like: foo.bar.baz +// Returns: libs/foo/bar/baz.py +std::string qualifierToArchivePath( + const std::string& qualifier, + const std::string& export_prefix); + +std::shared_ptr findSourceInArchiveFromQualifier( + caffe2::serialize::PyTorchStreamReader& reader, + const std::string& export_prefix, + const std::string& qualifier); + +} // namespace torch::jit diff --git a/shared/package-files/26/267bb2cb3b896f13aebb50c5a719bdff0168459218375f409a628d6f5b01a0c3/types.pxi b/shared/package-files/26/267bb2cb3b896f13aebb50c5a719bdff0168459218375f409a628d6f5b01a0c3/types.pxi new file mode 100644 index 0000000000000000000000000000000000000000..3caf068a4c9b1dc8e94e9ce8019fd3d5e5c66c7e --- /dev/null +++ b/shared/package-files/26/267bb2cb3b896f13aebb50c5a719bdff0168459218375f409a628d6f5b01a0c3/types.pxi @@ -0,0 +1,6202 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from cpython.pycapsule cimport ( + PyCapsule_CheckExact, + PyCapsule_GetPointer, + PyCapsule_GetName, + PyCapsule_New, + PyCapsule_IsValid +) + +import atexit +from collections.abc import Mapping +import pickle +import re +import sys +import warnings +from cython import sizeof + +# These are imprecise because the type (in pandas 0.x) depends on the presence +# of nulls +cdef dict _pandas_type_map = {} + + +def _get_pandas_type_map(): + global _pandas_type_map + if not _pandas_type_map: + _pandas_type_map.update({ + _Type_NA: np.object_, # NaNs + _Type_BOOL: np.bool_, + _Type_INT8: np.int8, + _Type_INT16: np.int16, + _Type_INT32: np.int32, + _Type_INT64: np.int64, + _Type_UINT8: np.uint8, + _Type_UINT16: np.uint16, + _Type_UINT32: np.uint32, + _Type_UINT64: np.uint64, + _Type_HALF_FLOAT: np.float16, + _Type_FLOAT: np.float32, + _Type_DOUBLE: np.float64, + # Pandas does not support [D]ay, so default to [ms] for date32 + _Type_DATE32: np.dtype('datetime64[ms]'), + _Type_DATE64: np.dtype('datetime64[ms]'), + _Type_TIMESTAMP: { + 's': np.dtype('datetime64[s]'), + 'ms': np.dtype('datetime64[ms]'), + 'us': np.dtype('datetime64[us]'), + 'ns': np.dtype('datetime64[ns]'), + }, + _Type_DURATION: { + 's': np.dtype('timedelta64[s]'), + 'ms': np.dtype('timedelta64[ms]'), + 'us': np.dtype('timedelta64[us]'), + 'ns': np.dtype('timedelta64[ns]'), + }, + _Type_BINARY: np.object_, + _Type_FIXED_SIZE_BINARY: np.object_, + _Type_STRING: np.object_, + _Type_LIST: np.object_, + _Type_MAP: np.object_, + _Type_DECIMAL32: np.object_, + _Type_DECIMAL64: np.object_, + _Type_DECIMAL128: np.object_, + _Type_DECIMAL256: np.object_, + }) + return _pandas_type_map + + +cdef dict _pep3118_type_map = { + _Type_INT8: b'b', + _Type_INT16: b'h', + _Type_INT32: b'i', + _Type_INT64: b'q', + _Type_UINT8: b'B', + _Type_UINT16: b'H', + _Type_UINT32: b'I', + _Type_UINT64: b'Q', + _Type_HALF_FLOAT: b'e', + _Type_FLOAT: b'f', + _Type_DOUBLE: b'd', +} + + +cdef bytes _datatype_to_pep3118(CDataType* type): + """ + Construct a PEP 3118 format string describing the given datatype. + None is returned for unsupported types. + """ + try: + char = _pep3118_type_map[type.id()] + except KeyError: + return None + else: + if char in b'bBhHiIqQ': + # Use "standard" int widths, not native + return b'=' + char + else: + return char + + +cdef void* _as_c_pointer(v, allow_null=False) except *: + """ + Convert a Python object to a raw C pointer. + + Used mainly for the C data interface. + Integers are accepted as well as capsule objects with a NULL name. + (the latter for compatibility with raw pointers exported by reticulate) + """ + cdef void* c_ptr + cdef const char* capsule_name + if isinstance(v, int): + c_ptr = v + elif isinstance(v, float): + warnings.warn( + "Passing a pointer value as a float is unsafe and only " + "supported for compatibility with older versions of the R " + "Arrow library", UserWarning, stacklevel=2) + c_ptr = v + elif PyCapsule_CheckExact(v): + # An R external pointer was how the R bindings passed pointer values to + # Python from versions 7 to 15 (inclusive); however, the reticulate 1.35.0 + # update changed the name of the capsule from NULL to "r_extptr". + # Newer versions of the R package pass a Python integer; however, this + # workaround ensures that old versions of the R package continue to work + # with newer versions of pyarrow. + capsule_name = PyCapsule_GetName(v) + if capsule_name == NULL or capsule_name == b"r_extptr": + c_ptr = PyCapsule_GetPointer(v, capsule_name) + else: + capsule_name_str = capsule_name.decode() + raise ValueError( + f"Can't convert PyCapsule with name '{capsule_name_str}' to pointer address" + ) + else: + raise TypeError(f"Expected a pointer value, got {type(v)!r}") + if not allow_null and c_ptr == NULL: + raise ValueError(f"Null pointer (value before cast = {v!r})") + return c_ptr + + +def _is_primitive(Type type): + # This is simply a redirect, the official API is in pyarrow.types. + return is_primitive(type) + + +def _get_pandas_type(arrow_type, coerce_to_ns=False): + cdef Type type_id = arrow_type.id + cdef dict pandas_type_map = _get_pandas_type_map() + if type_id not in pandas_type_map: + return None + if coerce_to_ns: + # ARROW-3789: Coerce date/timestamp types to datetime64[ns] + if type_id == _Type_DURATION: + return np.dtype('timedelta64[ns]') + return np.dtype('datetime64[ns]') + pandas_type = pandas_type_map[type_id] + if isinstance(pandas_type, dict): + unit = getattr(arrow_type, 'unit', None) + pandas_type = pandas_type.get(unit, None) + return pandas_type + + +def _get_pandas_tz_type(arrow_type, coerce_to_ns=False): + from pyarrow.pandas_compat import make_datetimetz + unit = 'ns' if coerce_to_ns else arrow_type.unit + return make_datetimetz(unit, arrow_type.tz) + + +def _to_pandas_dtype(arrow_type, options=None): + coerce_to_ns = (options and options.get('coerce_temporal_nanoseconds', False)) or ( + _pandas_api.is_v1() and arrow_type.id in + [_Type_DATE32, _Type_DATE64, _Type_TIMESTAMP, _Type_DURATION]) + + if getattr(arrow_type, 'tz', None): + dtype = _get_pandas_tz_type(arrow_type, coerce_to_ns) + else: + dtype = _get_pandas_type(arrow_type, coerce_to_ns) + + if not dtype: + raise NotImplementedError(str(arrow_type)) + + return dtype + + +# Workaround for Cython parsing bug +# https://github.com/cython/cython/issues/2143 +ctypedef CFixedWidthType* _CFixedWidthTypePtr + + +cdef class DataType(_Weakrefable): + """ + Base class of all Arrow data types. + + Each data type is an *instance* of this class. + + Examples + -------- + Instance of int64 type: + + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError("Do not call {}'s constructor directly, use public " + "functions like pyarrow.int64, pyarrow.list_, etc. " + "instead.".format(self.__class__.__name__)) + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + assert type != nullptr + self.sp_type = type + self.type = type.get() + self.pep3118_format = _datatype_to_pep3118(self.type) + + cpdef Field field(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + """ + if not isinstance(i, int): + raise TypeError(f"Expected int index, got type '{type(i)}'") + cdef int index = _normalize_index(i, self.type.num_fields()) + return pyarrow_wrap_field(self.type.field(index)) + + @property + def id(self): + return self.type.id() + + @property + def bit_width(self): + """ + Bit width for fixed width type. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().bit_width + 64 + """ + cdef _CFixedWidthTypePtr ty + ty = dynamic_cast[_CFixedWidthTypePtr](self.type) + if ty == nullptr: + raise ValueError("Non-fixed width type") + return ty.bit_width() + + @property + def byte_width(self): + """ + Byte width for fixed width type. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().byte_width + 8 + """ + cdef _CFixedWidthTypePtr ty + ty = dynamic_cast[_CFixedWidthTypePtr](self.type) + if ty == nullptr: + raise ValueError("Non-fixed width type") + byte_width = ty.byte_width() + if byte_width == 0 and self.bit_width != 0: + raise ValueError("Less than one byte") + return byte_width + + @property + def num_fields(self): + """ + The number of child fields. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().num_fields + 0 + >>> pa.list_(pa.string()) + ListType(list) + >>> pa.list_(pa.string()).num_fields + 1 + >>> struct = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct.num_fields + 2 + """ + return self.type.num_fields() + + @property + def num_buffers(self): + """ + Number of data buffers required to construct Array type + excluding children. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().num_buffers + 2 + >>> pa.string().num_buffers + 3 + """ + return self.type.layout().buffers.size() + + @property + def has_variadic_buffers(self): + """ + If True, the number of expected buffers is only + lower-bounded by num_buffers. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().has_variadic_buffers + False + >>> pa.string_view().has_variadic_buffers + True + """ + return self.type.layout().variadic_spec.has_value() + + def __str__(self): + return frombytes(self.type.ToString(), safe=True) + + def __hash__(self): + return hash(str(self)) + + def __reduce__(self): + return type_for_alias, (str(self),) + + def __repr__(self): + return '{0.__class__.__name__}({0})'.format(self) + + def __eq__(self, other): + try: + return self.equals(other) + except (TypeError, ValueError): + return NotImplemented + + def equals(self, other, *, check_metadata=False): + """ + Return true if type is equivalent to passed value. + + Parameters + ---------- + other : DataType or string convertible to DataType + check_metadata : bool + Whether nested Field metadata equality should be checked as well. + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().equals(pa.string()) + False + >>> pa.int64().equals(pa.int64()) + True + """ + cdef: + DataType other_type + c_bool c_check_metadata + + other_type = ensure_type(other) + c_check_metadata = check_metadata + return self.type.Equals(deref(other_type.type), c_check_metadata) + + def to_pandas_dtype(self): + """ + Return the equivalent NumPy / Pandas dtype. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().to_pandas_dtype() + + """ + return _to_pandas_dtype(self) + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportType(deref(self.type), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import DataType from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + result = GetResultValue(ImportType( + _as_c_pointer(in_ptr))) + return pyarrow_wrap_data_type(result) + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportType(deref(self.type), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a DataType from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + shared_ptr[CDataType] c_type + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise TypeError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + c_type = GetResultValue(ImportType(c_schema)) + + return pyarrow_wrap_data_type(c_type) + + +cdef class DictionaryMemo(_Weakrefable): + """ + Tracking container for dictionary-encoded fields. + """ + + def __cinit__(self): + self.sp_memo.reset(new CDictionaryMemo()) + self.memo = self.sp_memo.get() + + +cdef class DictionaryType(DataType): + """ + Concrete class for dictionary data types. + + Examples + -------- + Create an instance of dictionary type: + + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()) + DictionaryType(dictionary) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.dict_type = type.get() + + def __reduce__(self): + return dictionary, (self.index_type, self.value_type, self.ordered) + + @property + def ordered(self): + """ + Whether the dictionary is ordered, i.e. whether the ordering of values + in the dictionary is important. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()).ordered + False + """ + return self.dict_type.ordered() + + @property + def index_type(self): + """ + The data type of dictionary indices (a signed integer type). + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int16(), pa.utf8()).index_type + DataType(int16) + """ + return pyarrow_wrap_data_type(self.dict_type.index_type()) + + @property + def value_type(self): + """ + The dictionary value type. + + The dictionary values are found in an instance of DictionaryArray. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int16(), pa.utf8()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.dict_type.value_type()) + + +cdef class ListType(DataType): + """ + Concrete class for list data types. + + Examples + -------- + Create an instance of ListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.string()) + ListType(list) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return list_, (self.value_field,) + + @property + def value_field(self): + """ + The field for list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + +cdef class LargeListType(DataType): + """ + Concrete class for large list data types + (like ListType, but with 64-bit offsets). + + Examples + -------- + Create an instance of LargeListType: + + >>> import pyarrow as pa + >>> pa.large_list(pa.string()) + LargeListType(large_list) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return large_list, (self.value_field,) + + @property + def value_field(self): + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + +cdef class ListViewType(DataType): + """ + Concrete class for list view data types. + + Examples + -------- + Create an instance of ListViewType: + + >>> import pyarrow as pa + >>> pa.list_view(pa.string()) + ListViewType(list_view) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_view_type = type.get() + + def __reduce__(self): + return list_view, (self.value_field,) + + @property + def value_field(self): + """ + The field for list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_view(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_view_type.value_field()) + + @property + def value_type(self): + """ + The data type of list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_view(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_view_type.value_type()) + + +cdef class LargeListViewType(DataType): + """ + Concrete class for large list view data types + (like ListViewType, but with 64-bit offsets). + + Examples + -------- + Create an instance of LargeListViewType: + + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()) + LargeListViewType(large_list_view) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_view_type = type.get() + + def __reduce__(self): + return large_list_view, (self.value_field,) + + @property + def value_field(self): + """ + The field for large list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_view_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_view_type.value_type()) + + +cdef class MapType(DataType): + """ + Concrete class for map data types. + + Examples + -------- + Create an instance of MapType: + + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()) + MapType(map) + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True) + MapType(map) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.map_type = type.get() + + def __reduce__(self): + return map_, (self.key_field, self.item_field) + + @property + def key_field(self): + """ + The field for keys in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).key_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.map_type.key_field()) + + @property + def key_type(self): + """ + The data type of keys in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).key_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.map_type.key_type()) + + @property + def item_field(self): + """ + The field for items in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).item_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.map_type.item_field()) + + @property + def item_type(self): + """ + The data type of items in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).item_type + DataType(int32) + """ + return pyarrow_wrap_data_type(self.map_type.item_type()) + + @property + def keys_sorted(self): + """ + Should the entries be sorted according to keys. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True).keys_sorted + True + """ + return self.map_type.keys_sorted() + + +cdef class FixedSizeListType(DataType): + """ + Concrete class for fixed size list data types. + + Examples + -------- + Create an instance of FixedSizeListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2) + FixedSizeListType(fixed_size_list[2]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return list_, (self.value_type, self.list_size) + + @property + def value_field(self): + """ + The field for list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).value_type + DataType(int32) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + @property + def list_size(self): + """ + The size of the fixed size lists. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).list_size + 2 + """ + return self.list_type.list_size() + + +cdef class StructType(DataType): + """ + Concrete class for struct data types. + + ``StructType`` supports direct indexing using ``[...]`` (implemented via + ``__getitem__``) to access its fields. + It will return the struct field with the given index or name. + + Examples + -------- + >>> import pyarrow as pa + + Accessing fields using direct indexing: + + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct_type[0] + pyarrow.Field + >>> struct_type['y'] + pyarrow.Field + + Accessing fields using ``field()``: + + >>> struct_type.field(1) + pyarrow.Field + >>> struct_type.field('x') + pyarrow.Field + + # Creating a schema from the struct type's fields: + >>> pa.schema(list(struct_type)) + x: int32 + y: string + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.struct_type = type.get() + + cdef Field field_by_name(self, name): + """ + Return a child field by its name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + field : Field + The child field with the given name. + + Raises + ------ + KeyError + If the name isn't found, or if several fields have the given + name. + """ + cdef vector[shared_ptr[CField]] fields + + fields = self.struct_type.GetAllFieldsByName(tobytes(name)) + if fields.size() == 0: + raise KeyError(name) + elif fields.size() > 1: + warnings.warn("Struct field name corresponds to more " + "than one field", UserWarning) + raise KeyError(name) + else: + return pyarrow_wrap_field(fields[0]) + + def get_field_index(self, name): + """ + Return index of the unique field with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + index : int + The index of the field with the given name; -1 if the + name isn't found or there are several fields with the given + name. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + + Index of the field with a name 'y': + + >>> struct_type.get_field_index('y') + 1 + + Index of the field that does not exist: + + >>> struct_type.get_field_index('z') + -1 + """ + return self.struct_type.GetFieldIndex(tobytes(name)) + + cpdef Field field(self, i): + """ + Select a field by its column name or numeric index. + + Parameters + ---------- + i : int or str + + Returns + ------- + pyarrow.Field + + Examples + -------- + + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + + Select the second field: + + >>> struct_type.field(1) + pyarrow.Field + + Select the field named 'x': + + >>> struct_type.field('x') + pyarrow.Field + """ + if isinstance(i, (bytes, str)): + return self.field_by_name(i) + elif isinstance(i, int): + return DataType.field(self, i) + else: + raise TypeError('Expected integer or string index') + + def get_all_field_indices(self, name): + """ + Return sorted list of indices for the fields with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + indices : List[int] + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct_type.get_all_field_indices('x') + [0] + """ + return self.struct_type.GetAllFieldIndices(tobytes(name)) + + def __len__(self): + """ + Like num_fields(). + """ + return self.type.num_fields() + + def __iter__(self): + """ + Iterate over struct fields, in order. + """ + for i in range(len(self)): + yield self[i] + + def __getitem__(self, i): + """ + Return the struct field with the given index or name. + + Alias of ``field``. + """ + return self.field(i) + + def __reduce__(self): + return struct, (list(self),) + + @property + def names(self): + """ + Lists the field names. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())]) + >>> struct_type.names + ['a', 'b', 'c'] + """ + return [f.name for f in self] + + @property + def fields(self): + """ + Lists all fields within the StructType. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())]) + >>> struct_type.fields + [pyarrow.Field, pyarrow.Field, pyarrow.Field] + """ + return list(self) + +cdef class UnionType(DataType): + """ + Base class for union data types. + + Examples + -------- + Create an instance of a dense UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_DENSE), + (DenseUnionType(dense_union),) + + Create an instance of a dense UnionType using ``pa.dense_union``: + + >>> pa.dense_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + DenseUnionType(dense_union) + + Create an instance of a sparse UnionType using ``pa.union``: + + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_SPARSE), + (SparseUnionType(sparse_union),) + + Create an instance of a sparse UnionType using ``pa.sparse_union``: + + >>> pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + SparseUnionType(sparse_union) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + + @property + def mode(self): + """ + The mode of the union ("dense" or "sparse"). + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union.mode + 'sparse' + """ + cdef CUnionType* type = self.sp_type.get() + cdef int mode = type.mode() + if mode == _UnionMode_DENSE: + return 'dense' + if mode == _UnionMode_SPARSE: + return 'sparse' + assert 0 + + @property + def type_codes(self): + """ + The type code to indicate each data type in this union. + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union.type_codes + [0, 1] + """ + cdef CUnionType* type = self.sp_type.get() + return type.type_codes() + + def __len__(self): + """ + Like num_fields(). + """ + return self.type.num_fields() + + def __iter__(self): + """ + Iterate over union members, in order. + """ + for i in range(len(self)): + yield self[i] + + cpdef Field field(self, i): + """ + Return a child field by its numeric index. + + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union[0] + pyarrow.Field + """ + if isinstance(i, int): + return DataType.field(self, i) + else: + raise TypeError('Expected integer') + + def __getitem__(self, i): + """ + Return a child field by its index. + + Alias of ``field``. + """ + return self.field(i) + + def __reduce__(self): + return union, (list(self), self.mode, self.type_codes) + + +cdef class SparseUnionType(UnionType): + """ + Concrete class for sparse union types. + + Examples + -------- + Create an instance of a sparse UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_SPARSE), + (SparseUnionType(sparse_union),) + + Create an instance of a sparse UnionType using ``pa.sparse_union``: + + >>> pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + SparseUnionType(sparse_union) + """ + + +cdef class DenseUnionType(UnionType): + """ + Concrete class for dense union types. + + Examples + -------- + Create an instance of a dense UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_DENSE), + (DenseUnionType(dense_union),) + + Create an instance of a dense UnionType using ``pa.dense_union``: + + >>> pa.dense_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + DenseUnionType(dense_union) + """ + + +cdef class TimestampType(DataType): + """ + Concrete class for timestamp data types. + + Examples + -------- + >>> import pyarrow as pa + + Create an instance of timestamp type: + + >>> pa.timestamp('us') + TimestampType(timestamp[us]) + + Create an instance of timestamp type with timezone: + + >>> pa.timestamp('s', tz='UTC') + TimestampType(timestamp[s, tz=UTC]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.ts_type = type.get() + + @property + def unit(self): + """ + The timestamp unit ('s', 'ms', 'us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.timestamp('us') + >>> t.unit + 'us' + """ + return timeunit_to_string(self.ts_type.unit()) + + @property + def tz(self): + """ + The timestamp time zone, if any, or None. + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.timestamp('s', tz='UTC') + >>> t.tz + 'UTC' + """ + if self.ts_type.timezone().size() > 0: + return frombytes(self.ts_type.timezone()) + else: + return None + + def __reduce__(self): + return timestamp, (self.unit, self.tz) + + +cdef class Time32Type(DataType): + """ + Concrete class for time32 data types. + + Supported time unit resolutions are 's' [second] + and 'ms' [millisecond]. + + Examples + -------- + Create an instance of time32 type: + + >>> import pyarrow as pa + >>> pa.time32('ms') + Time32Type(time32[ms]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.time_type = type.get() + + @property + def unit(self): + """ + The time unit ('s' or 'ms'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.time32('ms') + >>> t.unit + 'ms' + """ + return timeunit_to_string(self.time_type.unit()) + + +cdef class Time64Type(DataType): + """ + Concrete class for time64 data types. + + Supported time unit resolutions are 'us' [microsecond] + and 'ns' [nanosecond]. + + Examples + -------- + Create an instance of time64 type: + + >>> import pyarrow as pa + >>> pa.time64('us') + Time64Type(time64[us]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.time_type = type.get() + + @property + def unit(self): + """ + The time unit ('us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.time64('us') + >>> t.unit + 'us' + """ + return timeunit_to_string(self.time_type.unit()) + + +cdef class DurationType(DataType): + """ + Concrete class for duration data types. + + Examples + -------- + Create an instance of duration type: + + >>> import pyarrow as pa + >>> pa.duration('s') + DurationType(duration[s]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.duration_type = type.get() + + @property + def unit(self): + """ + The duration unit ('s', 'ms', 'us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.duration('s') + >>> t.unit + 's' + """ + return timeunit_to_string(self.duration_type.unit()) + + +cdef class FixedSizeBinaryType(DataType): + """ + Concrete class for fixed-size binary data types. + + Examples + -------- + Create an instance of fixed-size binary type: + + >>> import pyarrow as pa + >>> pa.binary(3) + FixedSizeBinaryType(fixed_size_binary[3]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.fixed_size_binary_type = ( + type.get()) + + def __reduce__(self): + return binary, (self.byte_width,) + + +cdef class Decimal32Type(FixedSizeBinaryType): + """ + Concrete class for decimal32 data types. + + Examples + -------- + Create an instance of decimal32 type: + + >>> import pyarrow as pa + >>> pa.decimal32(5, 2) + Decimal32Type(decimal32(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal32_type = type.get() + + def __reduce__(self): + return decimal32, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal32(5, 2) + >>> t.precision + 5 + """ + return self.decimal32_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal32(5, 2) + >>> t.scale + 2 + """ + return self.decimal32_type.scale() + + +cdef class Decimal64Type(FixedSizeBinaryType): + """ + Concrete class for decimal64 data types. + + Examples + -------- + Create an instance of decimal64 type: + + >>> import pyarrow as pa + >>> pa.decimal64(5, 2) + Decimal64Type(decimal64(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal64_type = type.get() + + def __reduce__(self): + return decimal64, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal64(5, 2) + >>> t.precision + 5 + """ + return self.decimal64_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal64(5, 2) + >>> t.scale + 2 + """ + return self.decimal64_type.scale() + + +cdef class Decimal128Type(FixedSizeBinaryType): + """ + Concrete class for decimal128 data types. + + Examples + -------- + Create an instance of decimal128 type: + + >>> import pyarrow as pa + >>> pa.decimal128(5, 2) + Decimal128Type(decimal128(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal128_type = type.get() + + def __reduce__(self): + return decimal128, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal128(5, 2) + >>> t.precision + 5 + """ + return self.decimal128_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal128(5, 2) + >>> t.scale + 2 + """ + return self.decimal128_type.scale() + + +cdef class Decimal256Type(FixedSizeBinaryType): + """ + Concrete class for decimal256 data types. + + Examples + -------- + Create an instance of decimal256 type: + + >>> import pyarrow as pa + >>> pa.decimal256(76, 38) + Decimal256Type(decimal256(76, 38)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal256_type = type.get() + + def __reduce__(self): + return decimal256, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal256(76, 38) + >>> t.precision + 76 + """ + return self.decimal256_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal256(76, 38) + >>> t.scale + 38 + """ + return self.decimal256_type.scale() + + +cdef class RunEndEncodedType(DataType): + """ + Concrete class for run-end encoded types. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.run_end_encoded_type = type.get() + + def __reduce__(self): + return run_end_encoded, (self.run_end_type, self.value_type) + + @property + def run_end_type(self): + return pyarrow_wrap_data_type(self.run_end_encoded_type.run_end_type()) + + @property + def value_type(self): + return pyarrow_wrap_data_type(self.run_end_encoded_type.value_type()) + + +cdef class BaseExtensionType(DataType): + """ + Concrete base class for extension types. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.ext_type = type.get() + + def __arrow_ext_class__(self): + """ + The associated array extension class + """ + return ExtensionArray + + def __arrow_ext_scalar_class__(self): + """ + The associated scalar class + """ + return ExtensionScalar + + @property + def extension_name(self): + """ + The extension type name. + """ + return frombytes(self.ext_type.extension_name()) + + @property + def storage_type(self): + """ + The underlying storage type. + """ + return pyarrow_wrap_data_type(self.ext_type.storage_type()) + + @property + def byte_width(self): + """ + The byte width of the extension type. + """ + if self.ext_type.byte_width() == -1: + raise ValueError("Non-fixed width type") + return self.ext_type.byte_width() + + @property + def bit_width(self): + """ + The bit width of the extension type. + """ + if self.ext_type.bit_width() == -1: + raise ValueError("Non-fixed width type") + return self.ext_type.bit_width() + + def wrap_array(self, storage): + """ + Wrap the given storage array as an extension array. + + Parameters + ---------- + storage : Array or ChunkedArray + + Returns + ------- + array : Array or ChunkedArray + Extension array wrapping the storage array + """ + cdef: + shared_ptr[CDataType] c_storage_type + + if isinstance(storage, Array): + c_storage_type = ( storage).ap.type() + elif isinstance(storage, ChunkedArray): + c_storage_type = ( storage).chunked_array.type() + else: + raise TypeError( + f"Expected array or chunked array, got {storage.__class__}") + + if not c_storage_type.get().Equals(deref(self.ext_type) + .storage_type(), False): + raise TypeError( + f"Incompatible storage type for {self}: " + f"expected {self.storage_type}, got {storage.type}") + + if isinstance(storage, Array): + return pyarrow_wrap_array( + self.ext_type.WrapArray( + self.sp_type, ( storage).sp_array)) + else: + return pyarrow_wrap_chunked_array( + self.ext_type.WrapArray( + self.sp_type, ( storage).sp_chunked_array)) + + +cdef class ExtensionType(BaseExtensionType): + """ + Concrete base class for Python-defined extension types. + + Parameters + ---------- + storage_type : DataType + The underlying storage type for the extension type. + extension_name : str + A unique name distinguishing this extension type. The name will be + used when deserializing IPC data. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Create an instance of RationalType extension type: + + >>> rational_type = RationalType(pa.int32()) + + Inspect the extension type: + + >>> rational_type.extension_name + 'my_package.rational' + >>> rational_type.storage_type + StructType(struct) + + Wrap an array as an extension array: + + >>> storage_array = pa.array( + ... [ + ... {"numer": 10, "denom": 17}, + ... {"numer": 20, "denom": 13}, + ... ], + ... type=rational_type.storage_type + ... ) + >>> rational_array = rational_type.wrap_array(storage_array) + >>> rational_array + + -- is_valid: all not null + -- child 0 type: int32 + [ + 10, + 20 + ] + -- child 1 type: int32 + [ + 17, + 13 + ] + + Or do the same with creating an ExtensionArray: + + >>> rational_array = pa.ExtensionArray.from_storage(rational_type, storage_array) + >>> rational_array + + -- is_valid: all not null + -- child 0 type: int32 + [ + 10, + 20 + ] + -- child 1 type: int32 + [ + 17, + 13 + ] + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + + Note that even though we registered the concrete type + ``RationalType(pa.int64())``, PyArrow will be able to deserialize + ``RationalType(integer_type)`` for any ``integer_type``, as the deserializer + will reference the name ``my_package.rational`` and the ``@classmethod`` + ``__arrow_ext_deserialize__``. + """ + + def __cinit__(self): + if type(self) is ExtensionType: + raise TypeError("Can only instantiate subclasses of " + "ExtensionType") + + def __init__(self, DataType storage_type, extension_name): + """ + Initialize an extension type instance. + + This should be called at the end of the subclass' + ``__init__`` method. + """ + cdef: + shared_ptr[CExtensionType] cpy_ext_type + c_string c_extension_name + + c_extension_name = tobytes(extension_name) + + assert storage_type is not None + check_status(CPyExtensionType.FromClass( + storage_type.sp_type, c_extension_name, type(self), + &cpy_ext_type)) + self.init( cpy_ext_type) + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.cpy_ext_type = type.get() + # Store weakref and serialized version of self on C++ type instance + check_status(self.cpy_ext_type.SetInstance(self)) + + def __eq__(self, other): + # Default implementation to avoid infinite recursion through + # DataType.__eq__ -> ExtensionType::ExtensionEquals -> DataType.__eq__ + if isinstance(other, ExtensionType): + return (type(self) == type(other) and + self.extension_name == other.extension_name and + self.storage_type == other.storage_type) + else: + return NotImplemented + + def __repr__(self): + fmt = '{0.__class__.__name__}({1})' + return fmt.format(self, repr(self.storage_type)) + + def __arrow_ext_serialize__(self): + """ + Serialized representation of metadata to reconstruct the type object. + + This method should return a bytes object, and those serialized bytes + are stored in the custom metadata of the Field holding an extension + type in an IPC message. + The bytes are passed to ``__arrow_ext_deserialize`` and should hold + sufficient information to reconstruct the data type instance. + """ + return NotImplementedError + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + """ + Return an extension type instance from the storage type and serialized + metadata. + + This method should return an instance of the ExtensionType subclass + that matches the passed storage type and serialized metadata (the + return value of ``__arrow_ext_serialize__``). + """ + return NotImplementedError + + def __reduce__(self): + return self.__arrow_ext_deserialize__, (self.storage_type, self.__arrow_ext_serialize__()) + + def __arrow_ext_class__(self): + """Return an extension array class to be used for building or + deserializing arrays with this extension type. + + This method should return a subclass of the ExtensionArray class. By + default, if not specialized in the extension implementation, an + extension type array will be a built-in ExtensionArray instance. + """ + return ExtensionArray + + def __arrow_ext_scalar_class__(self): + """Return an extension scalar class for building scalars with this + extension type. + + This method should return subclass of the ExtensionScalar class. By + default, if not specialized in the extension implementation, an + extension type scalar will be a built-in ExtensionScalar instance. + """ + return ExtensionScalar + + +cdef class JsonType(BaseExtensionType): + """ + Concrete class for JSON extension type. + + Examples + -------- + Define the extension type for JSON array + + >>> import pyarrow as pa + >>> json_type = pa.json_(pa.large_utf8()) + + Create an extension array + + >>> arr = [None, '{ "id":30, "values":["a", "b"] }'] + >>> storage = pa.array(arr, pa.large_utf8()) + >>> pa.ExtensionArray.from_storage(json_type, storage) + + [ + null, + "{ "id":30, "values":["a", "b"] }" + ] + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.json_ext_type = type.get() + + def __arrow_ext_class__(self): + return JsonArray + + def __reduce__(self): + return json_, (self.storage_type,) + + def __arrow_ext_scalar_class__(self): + return JsonScalar + + +cdef class UuidType(BaseExtensionType): + """ + Concrete class for UUID extension type. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.uuid_ext_type = type.get() + + def __arrow_ext_class__(self): + return UuidArray + + def __reduce__(self): + return uuid, () + + def __arrow_ext_scalar_class__(self): + return UuidScalar + + +cdef class FixedShapeTensorType(BaseExtensionType): + """ + Concrete class for fixed shape tensor extension type. + + Examples + -------- + Create an instance of fixed shape tensor extension type: + + >>> import pyarrow as pa + >>> pa.fixed_shape_tensor(pa.int32(), [2, 2]) + FixedShapeTensorType(extension) + + Create an instance of fixed shape tensor extension type with + permutation: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.tensor_ext_type = type.get() + + @property + def value_type(self): + """ + Data type of an individual tensor. + """ + return pyarrow_wrap_data_type(self.tensor_ext_type.value_type()) + + @property + def shape(self): + """ + Shape of the tensors. + """ + return self.tensor_ext_type.shape() + + @property + def dim_names(self): + """ + Explicit names of the dimensions. + """ + list_of_bytes = self.tensor_ext_type.dim_names() + if len(list_of_bytes) != 0: + return [frombytes(x) for x in list_of_bytes] + else: + return None + + @property + def permutation(self): + """ + Indices of the dimensions ordering. + """ + indices = self.tensor_ext_type.permutation() + if len(indices) != 0: + return indices + else: + return None + + def __arrow_ext_class__(self): + return FixedShapeTensorArray + + def __reduce__(self): + return fixed_shape_tensor, (self.value_type, self.shape, + self.dim_names, self.permutation) + + def __arrow_ext_scalar_class__(self): + return FixedShapeTensorScalar + + +cdef class Bool8Type(BaseExtensionType): + """ + Concrete class for bool8 extension type. + + Bool8 is an alternate representation for boolean + arrays using 8 bits instead of 1 bit per value. The underlying + storage type is int8. + + Examples + -------- + Create an instance of bool8 extension type: + + >>> import pyarrow as pa + >>> pa.bool8() + Bool8Type(extension) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.bool8_ext_type = type.get() + + def __arrow_ext_class__(self): + return Bool8Array + + def __reduce__(self): + return bool8, () + + def __arrow_ext_scalar_class__(self): + return Bool8Scalar + + +cdef class OpaqueType(BaseExtensionType): + """ + Concrete class for opaque extension type. + + Opaque is a placeholder for a type from an external (often non-Arrow) + system that could not be interpreted. + + Examples + -------- + Create an instance of opaque extension type: + + >>> import pyarrow as pa + >>> pa.opaque(pa.int32(), "geometry", "postgis") + OpaqueType(extension) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.opaque_ext_type = type.get() + + @property + def type_name(self): + """ + The name of the type in the external system. + """ + return frombytes(c_string(self.opaque_ext_type.type_name())) + + @property + def vendor_name(self): + """ + The name of the external system. + """ + return frombytes(c_string(self.opaque_ext_type.vendor_name())) + + def __arrow_ext_class__(self): + return OpaqueArray + + def __reduce__(self): + return opaque, (self.storage_type, self.type_name, self.vendor_name) + + def __arrow_ext_scalar_class__(self): + return OpaqueScalar + + +_py_extension_type_auto_load = False + + +cdef class PyExtensionType(ExtensionType): + """ + Concrete base class for Python-defined extension types based on pickle + for (de)serialization. + + .. warning:: + This class is deprecated and its deserialization is disabled by default. + :class:`ExtensionType` is recommended instead. + + Parameters + ---------- + storage_type : DataType + The storage type for which the extension is built. + """ + + def __cinit__(self): + if type(self) is PyExtensionType: + raise TypeError("Can only instantiate subclasses of " + "PyExtensionType") + + def __init__(self, DataType storage_type): + warnings.warn( + "pyarrow.PyExtensionType is deprecated " + "and will refuse deserialization by default. " + "Instead, please derive from pyarrow.ExtensionType and implement " + "your own serialization mechanism.", + FutureWarning) + ExtensionType.__init__(self, storage_type, "arrow.py_extension_type") + + def __reduce__(self): + raise NotImplementedError("Please implement {0}.__reduce__" + .format(type(self).__name__)) + + def __arrow_ext_serialize__(self): + return pickle.dumps(self) + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + if not _py_extension_type_auto_load: + warnings.warn( + "pickle-based deserialization of pyarrow.PyExtensionType subclasses " + "is disabled by default; if you only ingest " + "trusted data files, you may re-enable this using " + "`pyarrow.PyExtensionType.set_auto_load(True)`.\n" + "In the future, Python-defined extension subclasses should " + "derive from pyarrow.ExtensionType (not pyarrow.PyExtensionType) " + "and implement their own serialization mechanism.\n", + RuntimeWarning) + return UnknownExtensionType(storage_type, serialized) + try: + ty = pickle.loads(serialized) + except Exception: + # For some reason, it's impossible to deserialize the + # ExtensionType instance. Perhaps the serialized data is + # corrupt, or more likely the type is being deserialized + # in an environment where the original Python class or module + # is not available. Fall back on a generic BaseExtensionType. + return UnknownExtensionType(storage_type, serialized) + + if ty.storage_type != storage_type: + raise TypeError("Expected storage type {0} but got {1}" + .format(ty.storage_type, storage_type)) + return ty + + # XXX Cython marks extension types as immutable, so cannot expose this + # as a writable class attribute. + @classmethod + def set_auto_load(cls, value): + """ + Enable or disable auto-loading of serialized PyExtensionType instances. + + Parameters + ---------- + value : bool + Whether to enable auto-loading. + """ + global _py_extension_type_auto_load + assert isinstance(value, bool) + _py_extension_type_auto_load = value + + +cdef class UnknownExtensionType(PyExtensionType): + """ + A concrete class for Python-defined extension types that refer to + an unknown Python implementation. + + Parameters + ---------- + storage_type : DataType + The storage type for which the extension is built. + serialized : bytes + The serialised output. + """ + + cdef: + bytes serialized + + def __init__(self, DataType storage_type, serialized): + self.serialized = serialized + PyExtensionType.__init__(self, storage_type) + + def __arrow_ext_serialize__(self): + return self.serialized + + +_python_extension_types_registry = [] + + +def register_extension_type(ext_type): + """ + Register a Python extension type. + + Registration is based on the extension name (so different registered types + need unique extension names). Registration needs an extension type + instance, but then works for any instance of the same subclass regardless + of parametrization of the type. + + Parameters + ---------- + ext_type : BaseExtensionType instance + The ExtensionType subclass to register. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + """ + cdef: + DataType _type = ensure_type(ext_type, allow_none=False) + + if not isinstance(_type, BaseExtensionType): + raise TypeError("Only extension types can be registered") + + # register on the C++ side + check_status( + RegisterPyExtensionType( _type.sp_type)) + + # register on the python side + _python_extension_types_registry.append(_type) + + +def unregister_extension_type(type_name): + """ + Unregister a Python extension type. + + Parameters + ---------- + type_name : str + The name of the ExtensionType subclass to unregister. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + """ + cdef: + c_string c_type_name = tobytes(type_name) + check_status(UnregisterPyExtensionType(c_type_name)) + + +cdef class KeyValueMetadata(_Metadata, Mapping): + """ + KeyValueMetadata + + Parameters + ---------- + __arg0__ : dict + A dict of the key-value metadata + **kwargs : optional + additional key-value metadata + """ + + def __init__(self, __arg0__=None, **kwargs): + cdef: + vector[c_string] keys, values + shared_ptr[const CKeyValueMetadata] result + + items = [] + if __arg0__ is not None: + other = (__arg0__.items() if isinstance(__arg0__, Mapping) + else __arg0__) + items.extend((tobytes(k), v) for k, v in other) + + prior_keys = {k for k, v in items} + for k, v in kwargs.items(): + k = tobytes(k) + if k in prior_keys: + raise KeyError("Duplicate key {}, " + "use pass all items as list of tuples if you " + "intend to have duplicate keys") + items.append((k, v)) + + keys.reserve(len(items)) + for key, value in items: + keys.push_back(tobytes(key)) + values.push_back(tobytes(value)) + result.reset(new CKeyValueMetadata(move(keys), move(values))) + self.init(result) + + cdef void init(self, const shared_ptr[const CKeyValueMetadata]& wrapped): + self.wrapped = wrapped + self.metadata = wrapped.get() + + @staticmethod + cdef wrap(const shared_ptr[const CKeyValueMetadata]& sp): + cdef KeyValueMetadata self = KeyValueMetadata.__new__(KeyValueMetadata) + self.init(sp) + return self + + cdef inline shared_ptr[const CKeyValueMetadata] unwrap(self) nogil: + return self.wrapped + + def equals(self, KeyValueMetadata other): + """ + Parameters + ---------- + other : pyarrow.KeyValueMetadata + + Returns + ------- + bool + """ + return self.metadata.Equals(deref(other.wrapped)) + + def __repr__(self): + return str(self) + + def __str__(self): + return frombytes(self.metadata.ToString(), safe=True) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + pass + + if isinstance(other, Mapping): + try: + other = KeyValueMetadata(other) + return self.equals(other) + except TypeError: + pass + + return NotImplemented + + def __len__(self): + return self.metadata.size() + + def __contains__(self, key): + return self.metadata.Contains(tobytes(key)) + + def __getitem__(self, key): + return GetResultValue(self.metadata.Get(tobytes(key))) + + def __iter__(self): + return self.keys() + + def __reduce__(self): + return KeyValueMetadata, (list(self.items()),) + + def key(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + byte + """ + return self.metadata.key(i) + + def value(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + byte + """ + return self.metadata.value(i) + + def keys(self): + for i in range(self.metadata.size()): + yield self.metadata.key(i) + + def values(self): + for i in range(self.metadata.size()): + yield self.metadata.value(i) + + def items(self): + for i in range(self.metadata.size()): + yield (self.metadata.key(i), self.metadata.value(i)) + + def get_all(self, key): + """ + Parameters + ---------- + key : str + + Returns + ------- + list[byte] + """ + key = tobytes(key) + return [v for k, v in self.items() if k == key] + + def to_dict(self): + """ + Convert KeyValueMetadata to dict. If a key occurs twice, the value for + the first one is returned + """ + cdef object key # to force coercion to Python + result = ordered_dict() + for i in range(self.metadata.size()): + key = self.metadata.key(i) + if key not in result: + result[key] = self.metadata.value(i) + return result + + +cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False): + if allow_none and meta is None: + return None + elif isinstance(meta, KeyValueMetadata): + return meta + else: + return KeyValueMetadata(meta) + + +cdef class Field(_Weakrefable): + """ + A named field, with a data type, nullability, and optional metadata. + + Notes + ----- + Do not use this class's constructor directly; use pyarrow.field + + Examples + -------- + Create an instance of pyarrow.Field: + + >>> import pyarrow as pa + >>> pa.field('key', pa.int32()) + pyarrow.Field + >>> pa.field('key', pa.int32(), nullable=False) + pyarrow.Field + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field + pyarrow.Field + >>> field.metadata + {b'key': b'Something important'} + + Use the field to create a struct type: + + >>> pa.struct([field]) + StructType(struct) + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError("Do not call Field's constructor directly, use " + "`pyarrow.field` instead.") + + cdef void init(self, const shared_ptr[CField]& field): + self.sp_field = field + self.field = field.get() + self.type = pyarrow_wrap_data_type(field.get().type()) + + def equals(self, Field other, bint check_metadata=False): + """ + Test if this field is equal to the other + + Parameters + ---------- + other : pyarrow.Field + check_metadata : bool, default False + Whether Field metadata equality should be checked as well. + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('key', pa.int32()) + >>> f2 = pa.field('key', pa.int32(), nullable=False) + >>> f1.equals(f2) + False + >>> f1.equals(f1) + True + """ + return self.field.Equals(deref(other.field), check_metadata) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def __reduce__(self): + return field, (self.name, self.type, self.nullable, self.metadata) + + def __str__(self): + return 'pyarrow.Field<{0}>'.format( + frombytes(self.field.ToString(), safe=True)) + + def __repr__(self): + return self.__str__() + + def __hash__(self): + return hash((self.field.name(), self.type, self.field.nullable())) + + @property + def nullable(self): + """ + The field nullability. + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('key', pa.int32()) + >>> f2 = pa.field('key', pa.int32(), nullable=False) + >>> f1.nullable + True + >>> f2.nullable + False + """ + return self.field.nullable() + + @property + def name(self): + """ + The field name. + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field.name + 'key' + """ + return frombytes(self.field.name()) + + @property + def metadata(self): + """ + The field metadata (if any is set). + + Returns + ------- + metadata : dict or None + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field.metadata + {b'key': b'Something important'} + """ + wrapped = pyarrow_wrap_metadata(self.field.metadata()) + if wrapped is not None: + return wrapped.to_dict() + else: + return wrapped + + def with_metadata(self, metadata): + """ + Add metadata as dict of string keys and values to Field + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + + Create new field by adding metadata to existing one: + + >>> field_new = field.with_metadata({"key": "Something important"}) + >>> field_new + pyarrow.Field + >>> field_new.metadata + {b'key': b'Something important'} + """ + cdef shared_ptr[CField] c_field + + meta = ensure_metadata(metadata, allow_none=False) + with nogil: + c_field = self.field.WithMetadata(meta.unwrap()) + + return pyarrow_wrap_field(c_field) + + def remove_metadata(self): + """ + Create new field without metadata, if any + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field.metadata + {b'key': b'Something important'} + + Create new field by removing the metadata from the existing one: + + >>> field_new = field.remove_metadata() + >>> field_new.metadata + """ + cdef shared_ptr[CField] new_field + with nogil: + new_field = self.field.RemoveMetadata() + return pyarrow_wrap_field(new_field) + + def with_type(self, DataType new_type): + """ + A copy of this field with the replaced type + + Parameters + ---------- + new_type : pyarrow.DataType + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + + Create new field by replacing type of an existing one: + + >>> field_new = field.with_type(pa.int64()) + >>> field_new + pyarrow.Field + """ + cdef: + shared_ptr[CField] c_field + shared_ptr[CDataType] c_datatype + + c_datatype = pyarrow_unwrap_data_type(new_type) + with nogil: + c_field = self.field.WithType(c_datatype) + + return pyarrow_wrap_field(c_field) + + def with_name(self, name): + """ + A copy of this field with the replaced name + + Parameters + ---------- + name : str + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + + Create new field by replacing the name of an existing one: + + >>> field_new = field.with_name('lock') + >>> field_new + pyarrow.Field + """ + cdef: + shared_ptr[CField] c_field + + c_field = self.field.WithName(tobytes(name)) + + return pyarrow_wrap_field(c_field) + + def with_nullable(self, nullable): + """ + A copy of this field with the replaced nullability + + Parameters + ---------- + nullable : bool + + Returns + ------- + field: pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + >>> field.nullable + True + + Create new field by replacing the nullability of an existing one: + + >>> field_new = field.with_nullable(False) + >>> field_new + pyarrow.Field + >>> field_new.nullable + False + """ + cdef: + shared_ptr[CField] field + c_bool c_nullable + + c_nullable = bool(nullable) + with nogil: + c_field = self.field.WithNullable(c_nullable) + + return pyarrow_wrap_field(c_field) + + def flatten(self): + """ + Flatten this field. If a struct field, individual child fields + will be returned with their names prefixed by the parent's name. + + Returns + ------- + fields : List[pyarrow.Field] + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('bar', pa.float64(), nullable=False) + >>> f2 = pa.field('foo', pa.int32()).with_metadata({"key": "Something important"}) + >>> ff = pa.field('ff', pa.struct([f1, f2]), nullable=False) + + Flatten a struct field: + + >>> ff + pyarrow.Field not null> + >>> ff.flatten() + [pyarrow.Field, pyarrow.Field] + """ + cdef vector[shared_ptr[CField]] flattened + with nogil: + flattened = self.field.Flatten() + return [pyarrow_wrap_field(f) for f in flattened] + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportField(deref(self.field), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import Field from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + cdef void* c_ptr = _as_c_pointer(in_ptr) + with nogil: + result = GetResultValue(ImportField( c_ptr)) + return pyarrow_wrap_field(result) + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportField(deref(self.field), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a Field from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + shared_ptr[CField] c_field + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise ValueError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + c_field = GetResultValue(ImportField(c_schema)) + + return pyarrow_wrap_field(c_field) + + +cdef class Schema(_Weakrefable): + """ + A named collection of types a.k.a schema. A schema defines the + column names and types in a record batch or table data structure. + They also contain metadata about the columns. For example, schemas + converted from Pandas contain metadata about their original Pandas + types so they can be converted back to the same types. + + Warnings + -------- + Do not call this class's constructor directly. Instead use + :func:`pyarrow.schema` factory function which makes a new Arrow + Schema object. + + Examples + -------- + Create a new Arrow Schema object: + + >>> import pyarrow as pa + >>> pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()) + ... ]) + some_int: int32 + some_string: string + + Create Arrow Schema with metadata: + + >>> pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError("Do not call Schema's constructor directly, use " + "`pyarrow.schema` instead.") + + def __len__(self): + return self.schema.num_fields() + + def __getitem__(self, key): + # access by integer index + return self._field(key) + + def __iter__(self): + for i in range(len(self)): + yield self[i] + + cdef void init(self, const vector[shared_ptr[CField]]& fields): + self.schema = new CSchema(fields) + self.sp_schema.reset(self.schema) + + cdef void init_schema(self, const shared_ptr[CSchema]& schema): + self.schema = schema.get() + self.sp_schema = schema + + def __reduce__(self): + return schema, (list(self), self.metadata) + + def __hash__(self): + return hash((tuple(self), self.metadata)) + + def __sizeof__(self): + size = 0 + if self.metadata: + for key, value in self.metadata.items(): + size += sys.getsizeof(key) + size += sys.getsizeof(value) + + return size + super(Schema, self).__sizeof__() + + @property + def pandas_metadata(self): + """ + Return deserialized-from-JSON pandas metadata field (if it exists) + + Examples + -------- + >>> import pyarrow as pa + >>> import pandas as pd + >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], + ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) + >>> schema = pa.Table.from_pandas(df).schema + + Select pandas metadata field from Arrow Schema: + + >>> schema.pandas_metadata + {'index_columns': [{'kind': 'range', 'name': None, 'start': 0, 'stop': 4, 'step': 1}], ... + """ + metadata = self.metadata + key = b'pandas' + if metadata is None or key not in metadata: + return None + + import json + return json.loads(metadata[key].decode('utf8')) + + @property + def names(self): + """ + The schema's field names. + + Returns + ------- + list of str + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the names of the schema's fields: + + >>> schema.names + ['n_legs', 'animals'] + """ + cdef int i + result = [] + for i in range(self.schema.num_fields()): + name = frombytes(self.schema.field(i).get().name()) + result.append(name) + return result + + @property + def types(self): + """ + The schema's field types. + + Returns + ------- + list of DataType + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the types of the schema's fields: + + >>> schema.types + [DataType(int64), DataType(string)] + """ + return [field.type for field in self] + + @property + def metadata(self): + """ + The schema's metadata (if any is set). + + Returns + ------- + metadata: dict or None + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + + Get the metadata of the schema's fields: + + >>> schema.metadata + {b'n_legs': b'Number of legs per animal'} + """ + wrapped = pyarrow_wrap_metadata(self.schema.metadata()) + if wrapped is not None: + return wrapped.to_dict() + else: + return wrapped + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def empty_table(self): + """ + Provide an empty table according to the schema. + + Returns + ------- + table: pyarrow.Table + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Create an empty table with schema's fields: + + >>> schema.empty_table() + pyarrow.Table + n_legs: int64 + animals: string + ---- + n_legs: [[]] + animals: [[]] + """ + arrays = [_empty_array(field.type) for field in self] + return Table.from_arrays(arrays, schema=self) + + def equals(self, Schema other not None, bint check_metadata=False): + """ + Test if this schema is equal to the other + + Parameters + ---------- + other : pyarrow.Schema + check_metadata : bool, default False + Key/value metadata must be equal too + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> schema1 = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema2 = pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()) + ... ]) + + Test two equal schemas: + + >>> schema1.equals(schema1) + True + + Test two unequal schemas: + + >>> schema1.equals(schema2) + False + """ + return self.sp_schema.get().Equals(deref(other.schema), + check_metadata) + + @classmethod + def from_pandas(cls, df, preserve_index=None): + """ + Returns implied schema from dataframe + + Parameters + ---------- + df : pandas.DataFrame + preserve_index : bool, default True + Whether to store the index as an additional column (or columns, for + MultiIndex) in the resulting `Table`. + The default of None will store the index as a column, except for + RangeIndex which is stored as metadata only. Use + ``preserve_index=True`` to force it to be stored as a column. + + Returns + ------- + pyarrow.Schema + + Examples + -------- + >>> import pandas as pd + >>> import pyarrow as pa + >>> df = pd.DataFrame({ + ... 'int': [1, 2], + ... 'str': ['a', 'b'] + ... }) + + Create an Arrow Schema from the schema of a pandas dataframe: + + >>> pa.Schema.from_pandas(df) + int: int64 + str: string + -- schema metadata -- + pandas: '{"index_columns": [{"kind": "range", "name": null, ... + """ + from pyarrow.pandas_compat import dataframe_to_types + names, types, metadata = dataframe_to_types( + df, + preserve_index=preserve_index + ) + fields = [] + for name, type_ in zip(names, types): + fields.append(field(name, type_)) + return schema(fields, metadata) + + def field(self, i): + """ + Select a field by its column name or numeric index. + + Parameters + ---------- + i : int or string + + Returns + ------- + pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Select the second field: + + >>> schema.field(1) + pyarrow.Field + + Select the field of the column named 'n_legs': + + >>> schema.field('n_legs') + pyarrow.Field + """ + if isinstance(i, (bytes, str)): + field_index = self.get_field_index(i) + if field_index < 0: + raise KeyError("Column {} does not exist in schema".format(i)) + else: + return self._field(field_index) + elif isinstance(i, int): + return self._field(i) + else: + raise TypeError("Index must either be string or integer") + + def _field(self, int i): + """ + Select a field by its numeric index. + + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + """ + cdef int index = _normalize_index(i, self.schema.num_fields()) + return pyarrow_wrap_field(self.schema.field(index)) + + def field_by_name(self, name): + """ + DEPRECATED + + Parameters + ---------- + name : str + + Returns + ------- + field: pyarrow.Field + """ + cdef: + vector[shared_ptr[CField]] results + + warnings.warn( + "The 'field_by_name' method is deprecated, use 'field' instead", + FutureWarning, stacklevel=2) + + results = self.schema.GetAllFieldsByName(tobytes(name)) + if results.size() == 0: + return None + elif results.size() > 1: + warnings.warn("Schema field name corresponds to more " + "than one field", UserWarning) + return None + else: + return pyarrow_wrap_field(results[0]) + + def get_field_index(self, name): + """ + Return index of the unique field with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + index : int + The index of the field with the given name; -1 if the + name isn't found or there are several fields with the given + name. + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the index of the field named 'animals': + + >>> schema.get_field_index("animals") + 1 + + Index in case of several fields with the given name: + + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string()), + ... pa.field('animals', pa.bool_())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema.get_field_index("animals") + -1 + """ + return self.schema.GetFieldIndex(tobytes(name)) + + def get_all_field_indices(self, name): + """ + Return sorted list of indices for the fields with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + indices : List[int] + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string()), + ... pa.field('animals', pa.bool_())]) + + Get the indexes of the fields named 'animals': + + >>> schema.get_all_field_indices("animals") + [1, 2] + """ + return self.schema.GetAllFieldIndices(tobytes(name)) + + def append(self, Field field): + """ + Append a field at the end of the schema. + + In contrast to Python's ``list.append()`` it does return a new + object, leaving the original Schema unmodified. + + Parameters + ---------- + field : Field + + Returns + ------- + schema: Schema + New object with appended field. + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Append a field 'extra' at the end of the schema: + + >>> schema_new = schema.append(pa.field('extra', pa.bool_())) + >>> schema_new + n_legs: int64 + animals: string + extra: bool + + Original schema is unmodified: + + >>> schema + n_legs: int64 + animals: string + """ + return self.insert(self.schema.num_fields(), field) + + def insert(self, int i, Field field): + """ + Add a field at position i to the schema. + + Parameters + ---------- + i : int + field : Field + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Insert a new field on the second position: + + >>> schema.insert(1, pa.field('extra', pa.bool_())) + n_legs: int64 + extra: bool + animals: string + """ + cdef: + shared_ptr[CSchema] new_schema + shared_ptr[CField] c_field + + c_field = field.sp_field + + with nogil: + new_schema = GetResultValue(self.schema.AddField(i, c_field)) + + return pyarrow_wrap_schema(new_schema) + + def remove(self, int i): + """ + Remove the field at index i from the schema. + + Parameters + ---------- + i : int + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Remove the second field of the schema: + + >>> schema.remove(1) + n_legs: int64 + """ + cdef shared_ptr[CSchema] new_schema + + with nogil: + new_schema = GetResultValue(self.schema.RemoveField(i)) + + return pyarrow_wrap_schema(new_schema) + + def set(self, int i, Field field): + """ + Replace a field at position i in the schema. + + Parameters + ---------- + i : int + field : Field + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Replace the second field of the schema with a new field 'extra': + + >>> schema.set(1, pa.field('replaced', pa.bool_())) + n_legs: int64 + replaced: bool + """ + cdef: + shared_ptr[CSchema] new_schema + shared_ptr[CField] c_field + + c_field = field.sp_field + + with nogil: + new_schema = GetResultValue(self.schema.SetField(i, c_field)) + + return pyarrow_wrap_schema(new_schema) + + def add_metadata(self, metadata): + """ + DEPRECATED + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + """ + warnings.warn("The 'add_metadata' method is deprecated, use " + "'with_metadata' instead", FutureWarning, stacklevel=2) + return self.with_metadata(metadata) + + def with_metadata(self, metadata): + """ + Add metadata as dict of string keys and values to Schema + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + + Returns + ------- + schema : pyarrow.Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Add metadata to existing schema field: + + >>> schema.with_metadata({"n_legs": "Number of legs per animal"}) + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + """ + cdef shared_ptr[CSchema] c_schema + + meta = ensure_metadata(metadata, allow_none=False) + with nogil: + c_schema = self.schema.WithMetadata(meta.unwrap()) + + return pyarrow_wrap_schema(c_schema) + + def serialize(self, memory_pool=None): + """ + Write Schema to Buffer as encapsulated IPC message + + Parameters + ---------- + memory_pool : MemoryPool, default None + Uses default memory pool if not specified + + Returns + ------- + serialized : Buffer + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Write schema to Buffer: + + >>> schema.serialize() + + """ + cdef: + shared_ptr[CBuffer] buffer + CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool) + + with nogil: + buffer = GetResultValue(SerializeSchema(deref(self.schema), + pool)) + return pyarrow_wrap_buffer(buffer) + + def remove_metadata(self): + """ + Create new schema without metadata, if any + + Returns + ------- + schema : pyarrow.Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + + Create a new schema with removing the metadata from the original: + + >>> schema.remove_metadata() + n_legs: int64 + animals: string + """ + cdef shared_ptr[CSchema] new_schema + with nogil: + new_schema = self.schema.RemoveMetadata() + return pyarrow_wrap_schema(new_schema) + + def to_string(self, truncate_metadata=True, show_field_metadata=True, + show_schema_metadata=True): + """ + Return human-readable representation of Schema + + Parameters + ---------- + truncate_metadata : boolean, default True + Limit metadata key/value display to a single line of ~80 characters + or less + show_field_metadata : boolean, default True + Display Field-level KeyValueMetadata + show_schema_metadata : boolean, default True + Display Schema-level KeyValueMetadata + + Returns + ------- + str : the formatted output + """ + cdef: + c_string result + PrettyPrintOptions options = PrettyPrintOptions.Defaults() + + options.indent = 0 + options.truncate_metadata = truncate_metadata + options.show_field_metadata = show_field_metadata + options.show_schema_metadata = show_schema_metadata + + with nogil: + check_status( + PrettyPrint( + deref(self.schema), + options, + &result + ) + ) + + return frombytes(result, safe=True) + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportSchema(deref(self.schema), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import Schema from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + cdef void* c_ptr = _as_c_pointer(in_ptr) + with nogil: + result = GetResultValue(ImportSchema( c_ptr)) + return pyarrow_wrap_schema(result) + + def __str__(self): + return self.to_string() + + def __repr__(self): + return self.__str__() + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportSchema(deref(self.schema), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a Schema from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise ValueError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + result = GetResultValue(ImportSchema(c_schema)) + + return pyarrow_wrap_schema(result) + + +def unify_schemas(schemas, *, promote_options="default"): + """ + Unify schemas by merging fields by name. + + The resulting schema will contain the union of fields from all schemas. + Fields with the same name will be merged. Note that two fields with + different types will fail merging by default. + + - The unified field will inherit the metadata from the schema where + that field is first defined. + - The first N fields in the schema will be ordered the same as the + N fields in the first schema. + + The resulting schema will inherit its metadata from the first input + schema. + + Parameters + ---------- + schemas : list of Schema + Schemas to merge into a single one. + promote_options : str, default default + Accepts strings "default" and "permissive". + Default: null and only null can be unified with another type. + Permissive: types are promoted to the greater common denominator. + + Returns + ------- + Schema + + Raises + ------ + ArrowInvalid : + If any input schema contains fields with duplicate names. + If Fields of the same name are not mergeable. + """ + cdef: + Schema schema + CField.CMergeOptions c_options + vector[shared_ptr[CSchema]] c_schemas + for schema in schemas: + if not isinstance(schema, Schema): + raise TypeError("Expected Schema, got {}".format(type(schema))) + c_schemas.push_back(pyarrow_unwrap_schema(schema)) + + if promote_options == "default": + c_options = CField.CMergeOptions.Defaults() + elif promote_options == "permissive": + c_options = CField.CMergeOptions.Permissive() + else: + raise ValueError(f"Invalid merge mode: {promote_options}") + + return pyarrow_wrap_schema( + GetResultValue(UnifySchemas(c_schemas, c_options))) + + +cdef dict _type_cache = {} + + +cdef DataType primitive_type(Type type): + if type in _type_cache: + return _type_cache[type] + + cdef DataType out = DataType.__new__(DataType) + out.init(GetPrimitiveType(type)) + + _type_cache[type] = out + return out + + +# ----------------------------------------------------------- +# Type factory functions + + +def field(name, type=None, nullable=None, metadata=None): + """ + Create a pyarrow.Field instance. + + Parameters + ---------- + name : str or bytes + Name of the field. + Alternatively, you can also pass an object that implements the Arrow + PyCapsule Protocol for schemas (has an ``__arrow_c_schema__`` method). + type : pyarrow.DataType or str + Arrow datatype of the field or a string matching one. + nullable : bool, default True + Whether the field's values are nullable. + metadata : dict, default None + Optional field metadata, the keys and values must be coercible to + bytes. + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + Create an instance of pyarrow.Field: + + >>> import pyarrow as pa + >>> pa.field('key', pa.int32()) + pyarrow.Field + >>> pa.field('key', pa.int32(), nullable=False) + pyarrow.Field + + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field + pyarrow.Field + >>> field.metadata + {b'key': b'Something important'} + + Use the field to create a struct type: + + >>> pa.struct([field]) + StructType(struct) + + A str can also be passed for the type parameter: + + >>> pa.field('key', 'int32') + pyarrow.Field + """ + if hasattr(name, "__arrow_c_schema__"): + if type is not None: + raise ValueError( + "cannot specify 'type' when creating a Field from an ArrowSchema" + ) + field = Field._import_from_c_capsule(name.__arrow_c_schema__()) + if metadata is not None: + field = field.with_metadata(metadata) + if nullable is not None: + field = field.with_nullable(nullable) + return field + + cdef: + Field result = Field.__new__(Field) + DataType _type = ensure_type(type, allow_none=False) + shared_ptr[const CKeyValueMetadata] c_meta + + nullable = True if nullable is None else nullable + + metadata = ensure_metadata(metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + if _type.type.id() == _Type_NA and not nullable: + raise ValueError("A null type field may not be non-nullable") + + result.sp_field.reset( + new CField(tobytes(name), _type.sp_type, nullable, c_meta) + ) + result.field = result.sp_field.get() + result.type = _type + + return result + + +cdef set PRIMITIVE_TYPES = set([ + _Type_NA, _Type_BOOL, + _Type_UINT8, _Type_INT8, + _Type_UINT16, _Type_INT16, + _Type_UINT32, _Type_INT32, + _Type_UINT64, _Type_INT64, + _Type_TIMESTAMP, _Type_DATE32, + _Type_TIME32, _Type_TIME64, + _Type_DATE64, + _Type_HALF_FLOAT, + _Type_FLOAT, + _Type_DOUBLE]) + + +def null(): + """ + Create instance of null type. + + Examples + -------- + Create an instance of a null type: + + >>> import pyarrow as pa + >>> pa.null() + DataType(null) + >>> print(pa.null()) + null + + Create a ``Field`` type with a null type and a name: + + >>> pa.field('null_field', pa.null()) + pyarrow.Field + """ + return primitive_type(_Type_NA) + + +def bool_(): + """ + Create instance of boolean type. + + Examples + -------- + Create an instance of a boolean type: + + >>> import pyarrow as pa + >>> pa.bool_() + DataType(bool) + >>> print(pa.bool_()) + bool + + Create a ``Field`` type with a boolean type + and a name: + + >>> pa.field('bool_field', pa.bool_()) + pyarrow.Field + """ + return primitive_type(_Type_BOOL) + + +def uint8(): + """ + Create instance of unsigned int8 type. + + Examples + -------- + Create an instance of unsigned int8 type: + + >>> import pyarrow as pa + >>> pa.uint8() + DataType(uint8) + >>> print(pa.uint8()) + uint8 + + Create an array with unsigned int8 type: + + >>> pa.array([0, 1, 2], type=pa.uint8()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT8) + + +def int8(): + """ + Create instance of signed int8 type. + + Examples + -------- + Create an instance of int8 type: + + >>> import pyarrow as pa + >>> pa.int8() + DataType(int8) + >>> print(pa.int8()) + int8 + + Create an array with int8 type: + + >>> pa.array([0, 1, 2], type=pa.int8()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT8) + + +def uint16(): + """ + Create instance of unsigned uint16 type. + + Examples + -------- + Create an instance of unsigned int16 type: + + >>> import pyarrow as pa + >>> pa.uint16() + DataType(uint16) + >>> print(pa.uint16()) + uint16 + + Create an array with unsigned int16 type: + + >>> pa.array([0, 1, 2], type=pa.uint16()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT16) + + +def int16(): + """ + Create instance of signed int16 type. + + Examples + -------- + Create an instance of int16 type: + + >>> import pyarrow as pa + >>> pa.int16() + DataType(int16) + >>> print(pa.int16()) + int16 + + Create an array with int16 type: + + >>> pa.array([0, 1, 2], type=pa.int16()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT16) + + +def uint32(): + """ + Create instance of unsigned uint32 type. + + Examples + -------- + Create an instance of unsigned int32 type: + + >>> import pyarrow as pa + >>> pa.uint32() + DataType(uint32) + >>> print(pa.uint32()) + uint32 + + Create an array with unsigned int32 type: + + >>> pa.array([0, 1, 2], type=pa.uint32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT32) + + +def int32(): + """ + Create instance of signed int32 type. + + Examples + -------- + Create an instance of int32 type: + + >>> import pyarrow as pa + >>> pa.int32() + DataType(int32) + >>> print(pa.int32()) + int32 + + Create an array with int32 type: + + >>> pa.array([0, 1, 2], type=pa.int32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT32) + + +def uint64(): + """ + Create instance of unsigned uint64 type. + + Examples + -------- + Create an instance of unsigned int64 type: + + >>> import pyarrow as pa + >>> pa.uint64() + DataType(uint64) + >>> print(pa.uint64()) + uint64 + + Create an array with unsigned uint64 type: + + >>> pa.array([0, 1, 2], type=pa.uint64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT64) + + +def int64(): + """ + Create instance of signed int64 type. + + Examples + -------- + Create an instance of int64 type: + + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> print(pa.int64()) + int64 + + Create an array with int64 type: + + >>> pa.array([0, 1, 2], type=pa.int64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT64) + + +cdef dict _timestamp_type_cache = {} +cdef dict _time_type_cache = {} +cdef dict _duration_type_cache = {} + + +cdef timeunit_to_string(TimeUnit unit): + if unit == TimeUnit_SECOND: + return 's' + elif unit == TimeUnit_MILLI: + return 'ms' + elif unit == TimeUnit_MICRO: + return 'us' + elif unit == TimeUnit_NANO: + return 'ns' + + +cdef TimeUnit string_to_timeunit(unit) except *: + if unit == 's': + return TimeUnit_SECOND + elif unit == 'ms': + return TimeUnit_MILLI + elif unit == 'us': + return TimeUnit_MICRO + elif unit == 'ns': + return TimeUnit_NANO + else: + raise ValueError(f"Invalid time unit: {unit!r}") + + +def tzinfo_to_string(tz): + """ + Converts a time zone object into a string indicating the name of a time + zone, one of: + * As used in the Olson time zone database (the "tz database" or + "tzdata"), such as "America/New_York" + * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 + + Parameters + ---------- + tz : datetime.tzinfo + Time zone object + + Returns + ------- + name : str + Time zone name + """ + return frombytes(GetResultValue(TzinfoToString(tz))) + + +def string_to_tzinfo(name): + """ + Convert a time zone name into a time zone object. + + Supported input strings are: + * As used in the Olson time zone database (the "tz database" or + "tzdata"), such as "America/New_York" + * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 + + Parameters + ---------- + name: str + Time zone name. + + Returns + ------- + tz : datetime.tzinfo + Time zone object + """ + cdef PyObject* tz = GetResultValue(StringToTzinfo(name.encode('utf-8'))) + return PyObject_to_object(tz) + + +def timestamp(unit, tz=None): + """ + Create instance of timestamp type with resolution and optional time zone. + + Parameters + ---------- + unit : str + one of 's' [second], 'ms' [millisecond], 'us' [microsecond], or 'ns' + [nanosecond] + tz : str, default None + Time zone name. None indicates time zone naive + + Examples + -------- + Create an instance of timestamp type: + + >>> import pyarrow as pa + >>> pa.timestamp('us') + TimestampType(timestamp[us]) + >>> pa.timestamp('s', tz='America/New_York') + TimestampType(timestamp[s, tz=America/New_York]) + >>> pa.timestamp('s', tz='+07:30') + TimestampType(timestamp[s, tz=+07:30]) + + Use timestamp type when creating a scalar object: + + >>> from datetime import datetime + >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('s', tz='UTC')) + + >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('us')) + + + Returns + ------- + timestamp_type : TimestampType + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + unit_code = string_to_timeunit(unit) + + cdef TimestampType out = TimestampType.__new__(TimestampType) + + if tz is None: + out.init(ctimestamp(unit_code)) + if unit_code in _timestamp_type_cache: + return _timestamp_type_cache[unit_code] + _timestamp_type_cache[unit_code] = out + else: + if not isinstance(tz, (bytes, str)): + tz = tzinfo_to_string(tz) + + c_timezone = tobytes(tz) + out.init(ctimestamp(unit_code, c_timezone)) + + return out + + +def time32(unit): + """ + Create instance of 32-bit time (time of day) type with unit resolution. + + Parameters + ---------- + unit : str + one of 's' [second], or 'ms' [millisecond] + + Returns + ------- + type : pyarrow.Time32Type + + Examples + -------- + >>> import pyarrow as pa + >>> pa.time32('s') + Time32Type(time32[s]) + >>> pa.time32('ms') + Time32Type(time32[ms]) + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + if unit == 's': + unit_code = TimeUnit_SECOND + elif unit == 'ms': + unit_code = TimeUnit_MILLI + else: + raise ValueError(f"Invalid time unit for time32: {unit!r}") + + if unit_code in _time_type_cache: + return _time_type_cache[unit_code] + + cdef Time32Type out = Time32Type.__new__(Time32Type) + + out.init(ctime32(unit_code)) + _time_type_cache[unit_code] = out + + return out + + +def time64(unit): + """ + Create instance of 64-bit time (time of day) type with unit resolution. + + Parameters + ---------- + unit : str + One of 'us' [microsecond], or 'ns' [nanosecond]. + + Returns + ------- + type : pyarrow.Time64Type + + Examples + -------- + >>> import pyarrow as pa + >>> pa.time64('us') + Time64Type(time64[us]) + >>> pa.time64('ns') + Time64Type(time64[ns]) + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + if unit == 'us': + unit_code = TimeUnit_MICRO + elif unit == 'ns': + unit_code = TimeUnit_NANO + else: + raise ValueError(f"Invalid time unit for time64: {unit!r}") + + if unit_code in _time_type_cache: + return _time_type_cache[unit_code] + + cdef Time64Type out = Time64Type.__new__(Time64Type) + + out.init(ctime64(unit_code)) + _time_type_cache[unit_code] = out + + return out + + +def duration(unit): + """ + Create instance of a duration type with unit resolution. + + Parameters + ---------- + unit : str + One of 's' [second], 'ms' [millisecond], 'us' [microsecond], or + 'ns' [nanosecond]. + + Returns + ------- + type : pyarrow.DurationType + + Examples + -------- + Create an instance of duration type: + + >>> import pyarrow as pa + >>> pa.duration('us') + DurationType(duration[us]) + >>> pa.duration('s') + DurationType(duration[s]) + + Create an array with duration type: + + >>> pa.array([0, 1, 2], type=pa.duration('s')) + + [ + 0, + 1, + 2 + ] + """ + cdef: + TimeUnit unit_code + + unit_code = string_to_timeunit(unit) + + if unit_code in _duration_type_cache: + return _duration_type_cache[unit_code] + + cdef DurationType out = DurationType.__new__(DurationType) + + out.init(cduration(unit_code)) + _duration_type_cache[unit_code] = out + + return out + + +def month_day_nano_interval(): + """ + Create instance of an interval type representing months, days and + nanoseconds between two dates. + + Examples + -------- + Create an instance of an month_day_nano_interval type: + + >>> import pyarrow as pa + >>> pa.month_day_nano_interval() + DataType(month_day_nano_interval) + + Create a scalar with month_day_nano_interval type: + + >>> pa.scalar((1, 15, -30), type=pa.month_day_nano_interval()) + + """ + return primitive_type(_Type_INTERVAL_MONTH_DAY_NANO) + + +def date32(): + """ + Create instance of 32-bit date (days since UNIX epoch 1970-01-01). + + Examples + -------- + Create an instance of 32-bit date type: + + >>> import pyarrow as pa + >>> pa.date32() + DataType(date32[day]) + + Create a scalar with 32-bit date type: + + >>> from datetime import date + >>> pa.scalar(date(2012, 1, 1), type=pa.date32()) + + """ + return primitive_type(_Type_DATE32) + + +def date64(): + """ + Create instance of 64-bit date (milliseconds since UNIX epoch 1970-01-01). + + Examples + -------- + Create an instance of 64-bit date type: + + >>> import pyarrow as pa + >>> pa.date64() + DataType(date64[ms]) + + Create a scalar with 64-bit date type: + + >>> from datetime import datetime + >>> pa.scalar(datetime(2012, 1, 1), type=pa.date64()) + + """ + return primitive_type(_Type_DATE64) + + +def float16(): + """ + Create half-precision floating point type. + + Examples + -------- + Create an instance of float16 type: + + >>> import pyarrow as pa + >>> pa.float16() + DataType(halffloat) + >>> print(pa.float16()) + halffloat + + Create an array with float16 type: + + >>> arr = np.array([1.5, np.nan], dtype=np.float16) + >>> a = pa.array(arr, type=pa.float16()) + >>> a + + [ + 15872, + 32256 + ] + + Note that unlike other float types, if you convert this array + to a python list, the types of its elements will be ``np.float16`` + + >>> [type(val) for val in a.to_pylist()] + [, ] + """ + return primitive_type(_Type_HALF_FLOAT) + + +def float32(): + """ + Create single-precision floating point type. + + Examples + -------- + Create an instance of float32 type: + + >>> import pyarrow as pa + >>> pa.float32() + DataType(float) + >>> print(pa.float32()) + float + + Create an array with float32 type: + + >>> pa.array([0.0, 1.0, 2.0], type=pa.float32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_FLOAT) + + +def float64(): + """ + Create double-precision floating point type. + + Examples + -------- + Create an instance of float64 type: + + >>> import pyarrow as pa + >>> pa.float64() + DataType(double) + >>> print(pa.float64()) + double + + Create an array with float64 type: + + >>> pa.array([0.0, 1.0, 2.0], type=pa.float64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_DOUBLE) + + +cpdef DataType decimal32(int precision, int scale=0): + """ + Create decimal type with precision and scale and 32-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal32(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 32-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal32(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 32-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 9 significant digits, consider + using ``decimal64``, ``decimal128``, or ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 9 + scale : int + + Returns + ------- + decimal_type : Decimal32Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal32(5, 2) + Decimal32Type(decimal32(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal32(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 9: + raise ValueError("precision should be between 1 and 9") + decimal_type.reset(new CDecimal32Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal64(int precision, int scale=0): + """ + Create decimal type with precision and scale and 64-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal64(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 64-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal64(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 64-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 18 significant digits, consider + using ``decimal128``, or ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 18 + scale : int + + Returns + ------- + decimal_type : Decimal64Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal64(5, 2) + Decimal64Type(decimal64(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal64(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 18: + raise ValueError("precision should be between 1 and 18") + decimal_type.reset(new CDecimal64Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal128(int precision, int scale=0): + """ + Create decimal type with precision and scale and 128-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal128(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 128-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal128(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 128-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 38 significant digits, consider + using ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 38 + scale : int + + Returns + ------- + decimal_type : Decimal128Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal128(5, 2) + Decimal128Type(decimal128(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal128(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 38: + raise ValueError("precision should be between 1 and 38") + decimal_type.reset(new CDecimal128Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal256(int precision, int scale=0): + """ + Create decimal type with precision and scale and 256-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + For most use cases, the maximum precision offered by ``decimal128`` + is sufficient, and it will result in a more compact and more efficient + encoding. ``decimal256`` is useful if you need a precision higher + than 38 significant digits. + + Parameters + ---------- + precision : int + Must be between 1 and 76 + scale : int + + Returns + ------- + decimal_type : Decimal256Type + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 76: + raise ValueError("precision should be between 1 and 76") + decimal_type.reset(new CDecimal256Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +def string(): + """ + Create UTF8 variable-length string type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.string() + DataType(string) + + and use the string type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.string()) + + [ + "foo", + "bar", + "baz" + ] + """ + return primitive_type(_Type_STRING) + + +def utf8(): + """ + Alias for string(). + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.utf8() + DataType(string) + + and use the string type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.utf8()) + + [ + "foo", + "bar", + "baz" + ] + """ + return string() + + +def binary(int length=-1): + """ + Create variable-length or fixed size binary type. + + Parameters + ---------- + length : int, optional, default -1 + If length == -1 then return a variable length binary type. If length is + greater than or equal to 0 then return a fixed size binary type of + width `length`. + + Examples + -------- + Create an instance of a variable-length binary type: + + >>> import pyarrow as pa + >>> pa.binary() + DataType(binary) + + and use the variable-length binary type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.binary()) + + [ + 666F6F, + 626172, + 62617A + ] + + Create an instance of a fixed-size binary type: + + >>> pa.binary(3) + FixedSizeBinaryType(fixed_size_binary[3]) + + and use the fixed-length binary type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.binary(3)) + + [ + 666F6F, + 626172, + 62617A + ] + """ + if length == -1: + return primitive_type(_Type_BINARY) + + cdef shared_ptr[CDataType] fixed_size_binary_type + fixed_size_binary_type.reset(new CFixedSizeBinaryType(length)) + return pyarrow_wrap_data_type(fixed_size_binary_type) + + +def large_binary(): + """ + Create large variable-length binary type. + + This data type may not be supported by all Arrow implementations. Unless + you need to represent data larger than 2GB, you should prefer binary(). + + Examples + -------- + Create an instance of large variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_binary() + DataType(large_binary) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.large_binary()) + + [ + 666F6F, + 626172, + 62617A + ] + """ + return primitive_type(_Type_LARGE_BINARY) + + +def large_string(): + """ + Create large UTF8 variable-length string type. + + This data type may not be supported by all Arrow implementations. Unless + you need to represent data larger than 2GB, you should prefer string(). + + Examples + -------- + Create an instance of large UTF8 variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_string() + DataType(large_string) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar'] * 50, type=pa.large_string()) + + [ + "foo", + "bar", + ... + "foo", + "bar" + ] + """ + return primitive_type(_Type_LARGE_STRING) + + +def large_utf8(): + """ + Alias for large_string(). + + Examples + -------- + Create an instance of large UTF8 variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_utf8() + DataType(large_string) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar'] * 50, type=pa.large_utf8()) + + [ + "foo", + "bar", + ... + "foo", + "bar" + ] + """ + return large_string() + + +def binary_view(): + """ + Create a variable-length binary view type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.binary_view() + DataType(binary_view) + """ + return primitive_type(_Type_BINARY_VIEW) + + +def string_view(): + """ + Create UTF8 variable-length string view type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.string_view() + DataType(string_view) + """ + return primitive_type(_Type_STRING_VIEW) + + +def list_(value_type, int list_size=-1): + """ + Create ListType instance from child data type or field. + + Parameters + ---------- + value_type : DataType or Field + list_size : int, optional, default -1 + If length == -1 then return a variable length list type. If length is + greater than or equal to 0 then return a fixed size list type. + + Returns + ------- + list_type : DataType + + Examples + -------- + Create an instance of ListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.string()) + ListType(list) + >>> pa.list_(pa.int32(), 2) + FixedSizeListType(fixed_size_list[2]) + + Use the ListType to create a scalar: + + >>> pa.scalar(['foo', None], type=pa.list_(pa.string(), 2)) + + + or an array: + + >>> pa.array([[1, 2], [3, 4]], pa.list_(pa.int32(), 2)) + + [ + [ + 1, + 2 + ], + [ + 3, + 4 + ] + ] + """ + cdef: + Field _field + shared_ptr[CDataType] list_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('List requires DataType or Field') + + if list_size == -1: + list_type.reset(new CListType(_field.sp_field)) + else: + if list_size < 0: + raise ValueError("list_size should be a positive integer") + list_type.reset(new CFixedSizeListType(_field.sp_field, list_size)) + + return pyarrow_wrap_data_type(list_type) + + +cpdef LargeListType large_list(value_type): + """ + Create LargeListType instance from child data type or field. + + This data type may not be supported by all Arrow implementations. + Unless you need to represent data larger than 2**31 elements, you should + prefer list_(). + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_type : DataType + + Examples + -------- + Create an instance of LargeListType: + + >>> import pyarrow as pa + >>> pa.large_list(pa.int8()) + LargeListType(large_list) + + Use the LargeListType to create an array: + + >>> pa.array([[-1, 3]] * 5, type=pa.large_list(pa.int8())) + + [ + [ + -1, + 3 + ], + [ + -1, + 3 + ], + ... + """ + cdef: + DataType data_type + Field _field + shared_ptr[CDataType] list_type + LargeListType out = LargeListType.__new__(LargeListType) + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('List requires DataType or Field') + + list_type.reset(new CLargeListType(_field.sp_field)) + out.init(list_type) + return out + + +cpdef ListViewType list_view(value_type): + """ + Create ListViewType instance from child data type or field. + + This data type may not be supported by all Arrow implementations + because it is an alternative to the ListType. + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_view_type : DataType + + Examples + -------- + Create an instance of ListViewType: + + >>> import pyarrow as pa + >>> pa.list_view(pa.string()) + ListViewType(list_view) + """ + cdef: + Field _field + shared_ptr[CDataType] list_view_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('ListView requires DataType or Field') + + list_view_type = CMakeListViewType(_field.sp_field) + return pyarrow_wrap_data_type(list_view_type) + + +cpdef LargeListViewType large_list_view(value_type): + """ + Create LargeListViewType instance from child data type or field. + + This data type may not be supported by all Arrow implementations + because it is an alternative to the ListType. + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_view_type : DataType + + Examples + -------- + Create an instance of LargeListViewType: + + >>> import pyarrow as pa + >>> pa.large_list_view(pa.int8()) + LargeListViewType(large_list_view) + """ + cdef: + Field _field + shared_ptr[CDataType] list_view_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('LargeListView requires DataType or Field') + + list_view_type = CMakeLargeListViewType(_field.sp_field) + return pyarrow_wrap_data_type(list_view_type) + + +cpdef MapType map_(key_type, item_type, keys_sorted=False): + """ + Create MapType instance from key and item data types or fields. + + Parameters + ---------- + key_type : DataType or Field + item_type : DataType or Field + keys_sorted : bool + + Returns + ------- + map_type : DataType + + Examples + -------- + Create an instance of MapType: + + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()) + MapType(map) + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True) + MapType(map) + + Use MapType to create an array: + + >>> data = [[{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}], [{'key': 'c', 'value': 3}]] + >>> pa.array(data, type=pa.map_(pa.string(), pa.int32(), keys_sorted=True)) + + [ + keys: + [ + "a", + "b" + ] + values: + [ + 1, + 2 + ], + keys: + [ + "c" + ] + values: + [ + 3 + ] + ] + """ + cdef: + Field _key_field + Field _item_field + shared_ptr[CDataType] map_type + MapType out = MapType.__new__(MapType) + + if isinstance(key_type, Field): + if key_type.nullable: + raise TypeError('Map key field should be non-nullable') + _key_field = key_type + else: + _key_field = field('key', ensure_type(key_type, allow_none=False), + nullable=False) + + if isinstance(item_type, Field): + _item_field = item_type + else: + _item_field = field('value', ensure_type(item_type, allow_none=False)) + + map_type.reset(new CMapType(_key_field.sp_field, _item_field.sp_field, + keys_sorted)) + out.init(map_type) + return out + + +cpdef DictionaryType dictionary(index_type, value_type, bint ordered=False): + """ + Dictionary (categorical, or simply encoded) type. + + Parameters + ---------- + index_type : DataType + value_type : DataType + ordered : bool + + Returns + ------- + type : DictionaryType + + Examples + -------- + Create an instance of dictionary type: + + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()) + DictionaryType(dictionary) + + Use dictionary type to create an array: + + >>> pa.array(["a", "b", None, "d"], pa.dictionary(pa.int64(), pa.utf8())) + + ... + -- dictionary: + [ + "a", + "b", + "d" + ] + -- indices: + [ + 0, + 1, + null, + 2 + ] + """ + cdef: + DataType _index_type = ensure_type(index_type, allow_none=False) + DataType _value_type = ensure_type(value_type, allow_none=False) + DictionaryType out = DictionaryType.__new__(DictionaryType) + shared_ptr[CDataType] dict_type + + if _index_type.id not in { + Type_INT8, Type_INT16, Type_INT32, Type_INT64, + Type_UINT8, Type_UINT16, Type_UINT32, Type_UINT64, + }: + raise TypeError("The dictionary index type should be integer.") + + dict_type.reset(new CDictionaryType(_index_type.sp_type, + _value_type.sp_type, ordered == 1)) + out.init(dict_type) + return out + + +def struct(fields): + """ + Create StructType instance from fields. + + A struct is a nested type parameterized by an ordered sequence of types + (which can all be distinct), called its fields. + + Parameters + ---------- + fields : iterable of Fields or tuples, or mapping of strings to DataTypes + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + + Examples + -------- + Create an instance of StructType from an iterable of tuples: + + >>> import pyarrow as pa + >>> fields = [ + ... ('f1', pa.int32()), + ... ('f2', pa.string()), + ... ] + >>> struct_type = pa.struct(fields) + >>> struct_type + StructType(struct) + + Retrieve a field from a StructType: + + >>> struct_type[0] + pyarrow.Field + >>> struct_type['f1'] + pyarrow.Field + + Create an instance of StructType from an iterable of Fields: + + >>> fields = [ + ... pa.field('f1', pa.int32()), + ... pa.field('f2', pa.string(), nullable=False), + ... ] + >>> pa.struct(fields) + StructType(struct) + + Returns + ------- + type : DataType + """ + cdef: + Field py_field + vector[shared_ptr[CField]] c_fields + cdef shared_ptr[CDataType] struct_type + + if isinstance(fields, Mapping): + fields = fields.items() + + for item in fields: + if isinstance(item, tuple): + py_field = field(*item) + else: + py_field = item + c_fields.push_back(py_field.sp_field) + + struct_type.reset(new CStructType(c_fields)) + return pyarrow_wrap_data_type(struct_type) + + +cdef _extract_union_params(child_fields, type_codes, + vector[shared_ptr[CField]]* c_fields, + vector[int8_t]* c_type_codes): + cdef: + Field child_field + + for child_field in child_fields: + c_fields[0].push_back(child_field.sp_field) + + if type_codes is not None: + if len(type_codes) != (c_fields.size()): + raise ValueError("type_codes should have the same length " + "as fields") + for code in type_codes: + c_type_codes[0].push_back(code) + else: + c_type_codes[0] = range(c_fields.size()) + + +def sparse_union(child_fields, type_codes=None): + """ + Create SparseUnionType from child fields. + + A sparse union is a nested type where each logical value is taken from + a single child. A buffer of 8-bit type ids indicates which child + a given logical value is to be taken from. + + In a sparse union, each child array should have the same length as the + union array, regardless of the actual number of union values that + refer to it. + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + type_codes : list of integers, default None + + Returns + ------- + type : SparseUnionType + """ + cdef: + vector[shared_ptr[CField]] c_fields + vector[int8_t] c_type_codes + + _extract_union_params(child_fields, type_codes, + &c_fields, &c_type_codes) + + return pyarrow_wrap_data_type( + CMakeSparseUnionType(move(c_fields), move(c_type_codes))) + + +def dense_union(child_fields, type_codes=None): + """ + Create DenseUnionType from child fields. + + A dense union is a nested type where each logical value is taken from + a single child, at a specific offset. A buffer of 8-bit type ids + indicates which child a given logical value is to be taken from, + and a buffer of 32-bit offsets indicates at which physical position + in the given child array the logical value is to be taken from. + + Unlike a sparse union, a dense union allows encoding only the child array + values which are actually referred to by the union array. This is + counterbalanced by the additional footprint of the offsets buffer, and + the additional indirection cost when looking up values. + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + type_codes : list of integers, default None + + Returns + ------- + type : DenseUnionType + """ + cdef: + vector[shared_ptr[CField]] c_fields + vector[int8_t] c_type_codes + + _extract_union_params(child_fields, type_codes, + &c_fields, &c_type_codes) + + return pyarrow_wrap_data_type( + CMakeDenseUnionType(move(c_fields), move(c_type_codes))) + + +def union(child_fields, mode, type_codes=None): + """ + Create UnionType from child fields. + + A union is a nested type where each logical value is taken from a + single child. A buffer of 8-bit type ids indicates which child + a given logical value is to be taken from. + + Unions come in two flavors: sparse and dense + (see also `pyarrow.sparse_union` and `pyarrow.dense_union`). + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + mode : str + Must be 'sparse' or 'dense' + type_codes : list of integers, default None + + Returns + ------- + type : UnionType + """ + if isinstance(mode, int): + if mode not in (_UnionMode_SPARSE, _UnionMode_DENSE): + raise ValueError("Invalid union mode {0!r}".format(mode)) + else: + if mode == 'sparse': + mode = _UnionMode_SPARSE + elif mode == 'dense': + mode = _UnionMode_DENSE + else: + raise ValueError("Invalid union mode {0!r}".format(mode)) + + if mode == _UnionMode_SPARSE: + return sparse_union(child_fields, type_codes) + else: + return dense_union(child_fields, type_codes) + + +def run_end_encoded(run_end_type, value_type): + """ + Create RunEndEncodedType from run-end and value types. + + Parameters + ---------- + run_end_type : pyarrow.DataType + The integer type of the run_ends array. Must be 'int16', 'int32', or 'int64'. + value_type : pyarrow.DataType + The type of the values array. + + Returns + ------- + type : RunEndEncodedType + """ + cdef: + DataType _run_end_type = ensure_type(run_end_type, allow_none=False) + DataType _value_type = ensure_type(value_type, allow_none=False) + shared_ptr[CDataType] ree_type + + if not _run_end_type.type.id() in [_Type_INT16, _Type_INT32, _Type_INT64]: + raise ValueError("The run_end_type should be 'int16', 'int32', or 'int64'") + ree_type = CMakeRunEndEncodedType(_run_end_type.sp_type, _value_type.sp_type) + return pyarrow_wrap_data_type(ree_type) + + +def json_(DataType storage_type=utf8()): + """ + Create instance of JSON extension type. + + Parameters + ---------- + storage_type : DataType, default pyarrow.string() + The underlying data type. Can be on of the following types: + string, large_string, string_view. + + Returns + ------- + type : JsonType + + Examples + -------- + Create an instance of JSON extension type: + + >>> import pyarrow as pa + >>> pa.json_(pa.utf8()) + JsonType(extension) + + Use the JSON type to create an array: + + >>> pa.array(['{"a": 1}', '{"b": 2}'], type=pa.json_(pa.utf8())) + + [ + "{"a": 1}", + "{"b": 2}" + ] + """ + + cdef JsonType out = JsonType.__new__(JsonType) + c_json_ext_type = GetResultValue(CJsonType.Make(storage_type.sp_type)) + out.init(c_json_ext_type) + return out + + +def uuid(): + """ + Create UuidType instance. + + Returns + ------- + type : UuidType + """ + + cdef UuidType out = UuidType.__new__(UuidType) + c_uuid_ext_type = GetResultValue(CUuidType.Make()) + out.init(c_uuid_ext_type) + return out + + +def fixed_shape_tensor(DataType value_type, shape, dim_names=None, permutation=None): + """ + Create instance of fixed shape tensor extension type with shape and optional + names of tensor dimensions and indices of the desired logical + ordering of dimensions. + + Parameters + ---------- + value_type : DataType + Data type of individual tensor elements. + shape : tuple or list of integers + The physical shape of the contained tensors. + dim_names : tuple or list of strings, default None + Explicit names to tensor dimensions. + permutation : tuple or list integers, default None + Indices of the desired ordering of the original dimensions. + The indices contain a permutation of the values ``[0, 1, .., N-1]`` where + N is the number of dimensions. The permutation indicates which dimension + of the logical layout corresponds to which dimension of the physical tensor. + For more information on this parameter see + :ref:`fixed_shape_tensor_extension`. + + Examples + -------- + Create an instance of fixed shape tensor extension type: + + >>> import pyarrow as pa + >>> tensor_type = pa.fixed_shape_tensor(pa.int32(), [2, 2]) + >>> tensor_type + FixedShapeTensorType(extension) + + Inspect the data type: + + >>> tensor_type.value_type + DataType(int32) + >>> tensor_type.shape + [2, 2] + + Create a table with fixed shape tensor extension array: + + >>> arr = [[1, 2, 3, 4], [10, 20, 30, 40], [100, 200, 300, 400]] + >>> storage = pa.array(arr, pa.list_(pa.int32(), 4)) + >>> tensor = pa.ExtensionArray.from_storage(tensor_type, storage) + >>> pa.table([tensor], names=["tensor_array"]) + pyarrow.Table + tensor_array: extension + ---- + tensor_array: [[[1,2,3,4],[10,20,30,40],[100,200,300,400]]] + + Create an instance of fixed shape tensor extension type with names + of tensor dimensions: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... dim_names=['C', 'H', 'W']) + >>> tensor_type.dim_names + ['C', 'H', 'W'] + + Create an instance of fixed shape tensor extension type with + permutation: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + + Returns + ------- + type : FixedShapeTensorType + """ + + cdef: + vector[int64_t] c_shape + vector[int64_t] c_permutation + vector[c_string] c_dim_names + shared_ptr[CDataType] c_tensor_ext_type + + assert value_type is not None + assert shape is not None + + for i in shape: + c_shape.push_back(i) + + if permutation is not None: + for i in permutation: + c_permutation.push_back(i) + + if dim_names is not None: + for x in dim_names: + c_dim_names.push_back(tobytes(x)) + + cdef FixedShapeTensorType out = FixedShapeTensorType.__new__(FixedShapeTensorType) + + with nogil: + c_tensor_ext_type = GetResultValue(CFixedShapeTensorType.Make( + value_type.sp_type, c_shape, c_permutation, c_dim_names)) + + out.init(c_tensor_ext_type) + + return out + + +def bool8(): + """ + Create instance of bool8 extension type. + + Examples + -------- + Create an instance of bool8 extension type: + + >>> import pyarrow as pa + >>> type = pa.bool8() + >>> type + Bool8Type(extension) + + Inspect the data type: + + >>> type.storage_type + DataType(int8) + + Create a table with a bool8 array: + + >>> arr = [-1, 0, 1, 2, None] + >>> storage = pa.array(arr, pa.int8()) + >>> other = pa.ExtensionArray.from_storage(type, storage) + >>> pa.table([other], names=["unknown_col"]) + pyarrow.Table + unknown_col: extension + ---- + unknown_col: [[-1,0,1,2,null]] + + Returns + ------- + type : Bool8Type + """ + + cdef Bool8Type out = Bool8Type.__new__(Bool8Type) + + c_type = GetResultValue(CBool8Type.Make()) + + out.init(c_type) + + return out + + +def opaque(DataType storage_type, str type_name not None, str vendor_name not None): + """ + Create instance of opaque extension type. + + Parameters + ---------- + storage_type : DataType + The underlying data type. + type_name : str + The name of the type in the external system. + vendor_name : str + The name of the external system. + + Examples + -------- + Create an instance of an opaque extension type: + + >>> import pyarrow as pa + >>> type = pa.opaque(pa.binary(), "other", "jdbc") + >>> type + OpaqueType(extension) + + Inspect the data type: + + >>> type.storage_type + DataType(binary) + >>> type.type_name + 'other' + >>> type.vendor_name + 'jdbc' + + Create a table with an opaque array: + + >>> arr = [None, b"foobar"] + >>> storage = pa.array(arr, pa.binary()) + >>> other = pa.ExtensionArray.from_storage(type, storage) + >>> pa.table([other], names=["unknown_col"]) + pyarrow.Table + unknown_col: extension + ---- + unknown_col: [[null,666F6F626172]] + + Returns + ------- + type : OpaqueType + """ + + cdef: + c_string c_type_name = tobytes(type_name) + c_string c_vendor_name = tobytes(vendor_name) + shared_ptr[COpaqueType] c_opaque_type = make_shared[COpaqueType]( + storage_type.sp_type, c_type_name, c_vendor_name) + shared_ptr[CDataType] c_type = static_pointer_cast[CDataType, COpaqueType](c_opaque_type) + OpaqueType out = OpaqueType.__new__(OpaqueType) + out.init(c_type) + return out + + +cdef dict _type_aliases = { + 'null': null, + 'bool': bool_, + 'boolean': bool_, + 'i1': int8, + 'int8': int8, + 'i2': int16, + 'int16': int16, + 'i4': int32, + 'int32': int32, + 'i8': int64, + 'int64': int64, + 'u1': uint8, + 'uint8': uint8, + 'u2': uint16, + 'uint16': uint16, + 'u4': uint32, + 'uint32': uint32, + 'u8': uint64, + 'uint64': uint64, + 'f2': float16, + 'halffloat': float16, + 'float16': float16, + 'f4': float32, + 'float': float32, + 'float32': float32, + 'f8': float64, + 'double': float64, + 'float64': float64, + 'string': string, + 'str': string, + 'utf8': string, + 'binary': binary, + 'large_string': large_string, + 'large_str': large_string, + 'large_utf8': large_string, + 'large_binary': large_binary, + 'binary_view': binary_view, + 'string_view': string_view, + 'date32': date32, + 'date64': date64, + 'date32[day]': date32, + 'date64[ms]': date64, + 'time32[s]': time32('s'), + 'time32[ms]': time32('ms'), + 'time64[us]': time64('us'), + 'time64[ns]': time64('ns'), + 'timestamp[s]': timestamp('s'), + 'timestamp[ms]': timestamp('ms'), + 'timestamp[us]': timestamp('us'), + 'timestamp[ns]': timestamp('ns'), + 'duration[s]': duration('s'), + 'duration[ms]': duration('ms'), + 'duration[us]': duration('us'), + 'duration[ns]': duration('ns'), + 'month_day_nano_interval': month_day_nano_interval(), +} + + +def type_for_alias(name): + """ + Return DataType given a string alias if one exists. + + Parameters + ---------- + name : str + The alias of the DataType that should be retrieved. + + Returns + ------- + type : DataType + """ + name = name.lower() + try: + alias = _type_aliases[name] + except KeyError: + raise ValueError('No type alias for {0}'.format(name)) + + if isinstance(alias, DataType): + return alias + return alias() + + +cpdef DataType ensure_type(object ty, bint allow_none=False): + if allow_none and ty is None: + return None + elif isinstance(ty, DataType): + return ty + elif isinstance(ty, str): + return type_for_alias(ty) + else: + raise TypeError('DataType expected, got {!r}'.format(type(ty))) + + +def schema(fields, metadata=None): + """ + Construct pyarrow.Schema from collection of fields. + + Parameters + ---------- + fields : iterable of Fields or tuples, or mapping of strings to DataTypes + Can also pass an object that implements the Arrow PyCapsule Protocol + for schemas (has an ``__arrow_c_schema__`` method). + metadata : dict, default None + Keys and values must be coercible to bytes. + + Examples + -------- + Create a Schema from iterable of tuples: + + >>> import pyarrow as pa + >>> pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()), + ... pa.field('some_required_string', pa.string(), nullable=False) + ... ]) + some_int: int32 + some_string: string + some_required_string: string not null + + Create a Schema from iterable of Fields: + + >>> pa.schema([ + ... pa.field('some_int', pa.int32()), + ... pa.field('some_string', pa.string()) + ... ]) + some_int: int32 + some_string: string + + DataTypes can also be passed as strings. The following is equivalent to the + above example: + + >>> pa.schema([ + ... pa.field('some_int', "int32"), + ... pa.field('some_string', "string") + ... ]) + some_int: int32 + some_string: string + + Or more concisely: + + >>> pa.schema([ + ... ('some_int', "int32"), + ... ('some_string', "string") + ... ]) + some_int: int32 + some_string: string + + Returns + ------- + schema : pyarrow.Schema + """ + cdef: + shared_ptr[const CKeyValueMetadata] c_meta + shared_ptr[CSchema] c_schema + Schema result + Field py_field + vector[shared_ptr[CField]] c_fields + + if hasattr(fields, "__arrow_c_schema__"): + result = Schema._import_from_c_capsule(fields.__arrow_c_schema__()) + if metadata is not None: + result = result.with_metadata(metadata) + return result + + if isinstance(fields, Mapping): + fields = fields.items() + + for item in fields: + if isinstance(item, tuple): + py_field = field(*item) + else: + py_field = item + if py_field is None: + raise TypeError("field or tuple expected, got None") + c_fields.push_back(py_field.sp_field) + + metadata = ensure_metadata(metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + c_schema.reset(new CSchema(c_fields, c_meta)) + result = Schema.__new__(Schema) + result.init_schema(c_schema) + + return result + + +def from_numpy_dtype(object dtype): + """ + Convert NumPy dtype to pyarrow.DataType. + + Parameters + ---------- + dtype : the numpy dtype to convert + + + Examples + -------- + Create a pyarrow DataType from NumPy dtype: + + >>> import pyarrow as pa + >>> import numpy as np + >>> pa.from_numpy_dtype(np.dtype('float16')) + DataType(halffloat) + >>> pa.from_numpy_dtype('U') + DataType(string) + >>> pa.from_numpy_dtype(bool) + DataType(bool) + >>> pa.from_numpy_dtype(np.str_) + DataType(string) + """ + dtype = np.dtype(dtype) + return pyarrow_wrap_data_type(GetResultValue(NumPyDtypeToArrow(dtype))) + + +def is_boolean_value(object obj): + """ + Check if the object is a boolean. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyBool(obj) + + +def is_integer_value(object obj): + """ + Check if the object is an integer. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyInt(obj) + + +def is_float_value(object obj): + """ + Check if the object is a float. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyFloat(obj) + + +cdef class _ExtensionRegistryNanny(_Weakrefable): + # Keep the registry alive until we have unregistered PyExtensionType + cdef: + shared_ptr[CExtensionTypeRegistry] registry + + def __cinit__(self): + self.registry = CExtensionTypeRegistry.GetGlobalRegistry() + + def release_registry(self): + self.registry.reset() + + +_registry_nanny = _ExtensionRegistryNanny() + + +def _register_py_extension_type(): + cdef: + DataType storage_type + shared_ptr[CExtensionType] cpy_ext_type + c_string c_extension_name = tobytes("arrow.py_extension_type") + + # Make a dummy C++ ExtensionType + storage_type = null() + check_status(CPyExtensionType.FromClass( + storage_type.sp_type, c_extension_name, PyExtensionType, + &cpy_ext_type)) + check_status( + RegisterPyExtensionType( cpy_ext_type)) + + +def _unregister_py_extension_types(): + # This needs to be done explicitly before the Python interpreter is + # finalized. If the C++ type is destroyed later in the process + # teardown stage, it will invoke CPython APIs such as Py_DECREF + # with a destroyed interpreter. + unregister_extension_type("arrow.py_extension_type") + for ext_type in _python_extension_types_registry: + try: + unregister_extension_type(ext_type.extension_name) + except KeyError: + pass + _registry_nanny.release_registry() + + +_register_py_extension_type() +atexit.register(_unregister_py_extension_types) + + +# +# PyCapsule export utilities +# + +cdef void pycapsule_schema_deleter(object schema_capsule) noexcept: + cdef ArrowSchema* schema = PyCapsule_GetPointer( + schema_capsule, 'arrow_schema' + ) + if schema.release != NULL: + schema.release(schema) + + free(schema) + +cdef object alloc_c_schema(ArrowSchema** c_schema): + c_schema[0] = malloc(sizeof(ArrowSchema)) + # Ensure the capsule destructor doesn't call a random release pointer + c_schema[0].release = NULL + return PyCapsule_New(c_schema[0], 'arrow_schema', &pycapsule_schema_deleter) + + +cdef void pycapsule_array_deleter(object array_capsule) noexcept: + cdef: + ArrowArray* array + # Do not invoke the deleter on a used/moved capsule + array = cpython.PyCapsule_GetPointer( + array_capsule, 'arrow_array' + ) + if array.release != NULL: + array.release(array) + + free(array) + +cdef object alloc_c_array(ArrowArray** c_array): + c_array[0] = malloc(sizeof(ArrowArray)) + # Ensure the capsule destructor doesn't call a random release pointer + c_array[0].release = NULL + return PyCapsule_New(c_array[0], 'arrow_array', &pycapsule_array_deleter) + + +cdef void pycapsule_stream_deleter(object stream_capsule) noexcept: + cdef: + ArrowArrayStream* stream + # Do not invoke the deleter on a used/moved capsule + stream = PyCapsule_GetPointer( + stream_capsule, 'arrow_array_stream' + ) + if stream.release != NULL: + stream.release(stream) + + free(stream) + +cdef object alloc_c_stream(ArrowArrayStream** c_stream): + c_stream[0] = malloc(sizeof(ArrowArrayStream)) + # Ensure the capsule destructor doesn't call a random release pointer + c_stream[0].release = NULL + return PyCapsule_New(c_stream[0], 'arrow_array_stream', &pycapsule_stream_deleter) + + +cdef void pycapsule_device_array_deleter(object array_capsule) noexcept: + cdef: + ArrowDeviceArray* device_array + # Do not invoke the deleter on a used/moved capsule + device_array = cpython.PyCapsule_GetPointer( + array_capsule, 'arrow_device_array' + ) + if device_array.array.release != NULL: + device_array.array.release(&device_array.array) + + free(device_array) + + +cdef object alloc_c_device_array(ArrowDeviceArray** c_array): + c_array[0] = malloc(sizeof(ArrowDeviceArray)) + # Ensure the capsule destructor doesn't call a random release pointer + c_array[0].array.release = NULL + return PyCapsule_New( + c_array[0], 'arrow_device_array', &pycapsule_device_array_deleter) diff --git a/shared/package-files/26/267d82dfa109bcfe4895dae81ab7187fce60b68fca241701d8cc829d8e01e74f/_test_autograd_multiple_dispatch.h b/shared/package-files/26/267d82dfa109bcfe4895dae81ab7187fce60b68fca241701d8cc829d8e01e74f/_test_autograd_multiple_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c229d80aac8cf149b15d581c50b6e67204b99e27 --- /dev/null +++ b/shared/package-files/26/267d82dfa109bcfe4895dae81ab7187fce60b68fca241701d8cc829d8e01e74f/_test_autograd_multiple_dispatch.h @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor +inline at::Tensor _test_autograd_multiple_dispatch(const at::Tensor & self) { + return at::_ops::_test_autograd_multiple_dispatch_fullcoverage::call(self); +} + +// aten::_test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor +inline at::Tensor _test_autograd_multiple_dispatch(const at::Tensor & self, bool b) { + return at::_ops::_test_autograd_multiple_dispatch_ntonly::call(self, b); +} + +// aten::_test_autograd_multiple_dispatch.fullcoverage_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_autograd_multiple_dispatch_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::_test_autograd_multiple_dispatch_fullcoverage_out::call(self, out); +} +// aten::_test_autograd_multiple_dispatch.fullcoverage_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_autograd_multiple_dispatch_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::_test_autograd_multiple_dispatch_fullcoverage_out::call(self, out); +} + +} diff --git a/shared/package-files/26/26801bfd4f601689096a7be60d94c6def40a86b03b7ad1aad71c5c3559bd09ef/embedding_expanded_weights.py b/shared/package-files/26/26801bfd4f601689096a7be60d94c6def40a86b03b7ad1aad71c5c3559bd09ef/embedding_expanded_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..febeecab8b31bfc4ffcf60fdbd1ba23e19fb8c6a --- /dev/null +++ b/shared/package-files/26/26801bfd4f601689096a7be60d94c6def40a86b03b7ad1aad71c5c3559bd09ef/embedding_expanded_weights.py @@ -0,0 +1,83 @@ +# mypy: allow-untyped-defs +from typing import Optional + +import torch +import torch.nn.functional as F + +from .expanded_weights_impl import implements_per_sample_grads +from .expanded_weights_utils import ( + forward_helper, + set_grad_sample_if_exists, + standard_kwargs, +) + + +@implements_per_sample_grads(F.embedding) +class EmbeddingPerSampleGrad(torch.autograd.Function): + @staticmethod + def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs): + expanded_args, expanded_kwargs = standard_kwargs( + kwarg_names, expanded_args_and_kwargs + ) + if len(expanded_args[0].shape) == 1: + raise RuntimeError( + f"Expanded Weights needs an input with a batch size, got a 1D tensor, {expanded_args[0]}" + ) + output = forward_helper(F.embedding, expanded_args, expanded_kwargs) + ctx.input, ctx.weight = expanded_args + ctx.padding_idx, ctx.scale_grad_by_freq = ( + expanded_kwargs["padding_idx"], + expanded_kwargs["scale_grad_by_freq"], + ) + ctx.sparse = expanded_kwargs["sparse"] + return output + + @staticmethod + def backward(ctx, grad_output): + input, weight = ctx.input, ctx.weight + padding_idx, scale_grad_by_freq, sparse = ( + ctx.padding_idx, + ctx.scale_grad_by_freq, + ctx.sparse, + ) + + def weight_per_sample_grad(weight): + batch_size = input.shape[0] + embedding_dim = weight.shape[1] + index = ( + input.unsqueeze(-1) + .expand(*input.shape, embedding_dim) + .reshape(batch_size, -1, embedding_dim) + ) + grad_sample = torch.zeros( + batch_size, *weight.shape, device=weight.device, dtype=grad_output.dtype + ) + return grad_sample.scatter_add_( + 1, index, grad_output.reshape(batch_size, -1, embedding_dim) + ) + + results: list[Optional[torch.Tensor]] = [] + results.append(None) # for kwarg names + results.append(None) # for op reference + + if input.requires_grad: + bw_fn = torch.ops.aten.embedding_backward + results.append( + bw_fn( + grad_output, + input, + weight.shape[0], + padding_idx, + scale_grad_by_freq, + sparse, + ) + ) + else: + results.append(None) + + # weight doesn't compute batched gradients; no other arguments are differentiable (2 not saved from forward) + results = results + [None] * 6 + + # set grad_sample field for weight with per sample gradients + set_grad_sample_if_exists(weight, weight_per_sample_grad) + return tuple(results) diff --git a/shared/package-files/26/2682899a49ccdc91e027279b49e16fa9a3c4666a998557a05503f61302e375fa/masked_scatter_backward_native.h b/shared/package-files/26/2682899a49ccdc91e027279b49e16fa9a3c4666a998557a05503f61302e375fa/masked_scatter_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b30b8328e0b95d3936bd6594ff051be5be27cdcf --- /dev/null +++ b/shared/package-files/26/2682899a49ccdc91e027279b49e16fa9a3c4666a998557a05503f61302e375fa/masked_scatter_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor masked_scatter_backward_symint(const at::Tensor & grad_output, const at::Tensor & mask, c10::SymIntArrayRef sizes); +} // namespace native +} // namespace at diff --git a/shared/package-files/26/2688f1e9ade68c66996cb232e09bb6a5c741064d6b0fd15e457e18467b590cc7/abc.cpython-311.pyc b/shared/package-files/26/2688f1e9ade68c66996cb232e09bb6a5c741064d6b0fd15e457e18467b590cc7/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b5ba62cc1a5cf050cf494971d41214c52a83a51 Binary files /dev/null and b/shared/package-files/26/2688f1e9ade68c66996cb232e09bb6a5c741064d6b0fd15e457e18467b590cc7/abc.cpython-311.pyc differ diff --git a/shared/package-files/26/2696d690d4dd2738a7dbfae04ff52f4465f5f55b393721d81f221c84ee25ed09/_thnn_fused_lstm_cell_backward_native.h b/shared/package-files/26/2696d690d4dd2738a7dbfae04ff52f4465f5f55b393721d81f221c84ee25ed09/_thnn_fused_lstm_cell_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..f29273130b88796c1e7399fc4385e0a1b2e73aa3 --- /dev/null +++ b/shared/package-files/26/2696d690d4dd2738a7dbfae04ff52f4465f5f55b393721d81f221c84ee25ed09/_thnn_fused_lstm_cell_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _thnn_fused_lstm_cell_backward(const ::std::optional & grad_hy, const ::std::optional & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias); +} // namespace native +} // namespace at diff --git a/shared/package-files/26/269fb3e8b4f3fe9f1f291ba57057dd72c908c73719eb26db1e4181f66a496b63/nvtxLinkOnce.h b/shared/package-files/26/269fb3e8b4f3fe9f1f291ba57057dd72c908c73719eb26db1e4181f66a496b63/nvtxLinkOnce.h new file mode 100644 index 0000000000000000000000000000000000000000..6c6eaa732464519fc7d93f98b646729dab0db8b9 --- /dev/null +++ b/shared/package-files/26/269fb3e8b4f3fe9f1f291ba57057dd72c908c73719eb26db1e4181f66a496b63/nvtxLinkOnce.h @@ -0,0 +1,75 @@ +#ifndef __NVTX_LINKONCE_H__ +#define __NVTX_LINKONCE_H__ + +/* This header defines macros to permit making definitions of global variables + * and functions in C/C++ header files which may be included multiple times in + * a translation unit or linkage unit. It allows authoring header-only libraries + * which can be used by multiple other header-only libraries (either as the same + * copy or multiple copies), and does not require any build changes, such as + * adding another .c file, linking a static library, or deploying a dynamic + * library. Globals defined with these macros have the property that they have + * the same address, pointing to a single instance, for the entire linkage unit. + * It is expected but not guaranteed that each linkage unit will have a separate + * instance. + * + * In some situations it is desirable to declare a variable without initializing + * it, refer to it in code or other variables' initializers, and then initialize + * it later. Similarly, functions can be prototyped, have their address taken, + * and then have their body defined later. In such cases, use the FWDDECL macros + * when forward-declaring LINKONCE global variables without initializers and + * function prototypes, and then use the DEFINE macros when later defining them. + * Although in many cases the FWDDECL macro is equivalent to the DEFINE macro, + * following this pattern makes code maximally portable. + */ + +#if defined(__MINGW32__) /* MinGW */ + #define NVTX_LINKONCE_WEAK __attribute__((section(".gnu.linkonce.0."))) + #if defined(__cplusplus) + #define NVTX_LINKONCE_DEFINE_GLOBAL __declspec(selectany) + #define NVTX_LINKONCE_DEFINE_FUNCTION extern "C" inline NVTX_LINKONCE_WEAK + #else + #define NVTX_LINKONCE_DEFINE_GLOBAL __declspec(selectany) + #define NVTX_LINKONCE_DEFINE_FUNCTION NVTX_LINKONCE_WEAK + #endif +#elif defined(_MSC_VER) /* MSVC */ + #if defined(__cplusplus) + #define NVTX_LINKONCE_DEFINE_GLOBAL extern "C" __declspec(selectany) + #define NVTX_LINKONCE_DEFINE_FUNCTION extern "C" inline + #else + #define NVTX_LINKONCE_DEFINE_GLOBAL __declspec(selectany) + #define NVTX_LINKONCE_DEFINE_FUNCTION __inline + #endif +#elif defined(__CYGWIN__) && defined(__clang__) /* Clang on Cygwin */ + #define NVTX_LINKONCE_WEAK __attribute__((section(".gnu.linkonce.0."))) + #if defined(__cplusplus) + #define NVTX_LINKONCE_DEFINE_GLOBAL NVTX_LINKONCE_WEAK + #define NVTX_LINKONCE_DEFINE_FUNCTION extern "C" NVTX_LINKONCE_WEAK + #else + #define NVTX_LINKONCE_DEFINE_GLOBAL NVTX_LINKONCE_WEAK + #define NVTX_LINKONCE_DEFINE_FUNCTION NVTX_LINKONCE_WEAK + #endif +#elif defined(__CYGWIN__) /* Assume GCC or compatible */ + #define NVTX_LINKONCE_WEAK __attribute__((weak)) + #if defined(__cplusplus) + #define NVTX_LINKONCE_DEFINE_GLOBAL __declspec(selectany) + #define NVTX_LINKONCE_DEFINE_FUNCTION extern "C" inline + #else + #define NVTX_LINKONCE_DEFINE_GLOBAL NVTX_LINKONCE_WEAK + #define NVTX_LINKONCE_DEFINE_FUNCTION NVTX_LINKONCE_WEAK + #endif +#else /* All others: Assume GCC, clang, or compatible */ + #define NVTX_LINKONCE_WEAK __attribute__((weak)) + #define NVTX_LINKONCE_HIDDEN __attribute__((visibility("hidden"))) + #if defined(__cplusplus) + #define NVTX_LINKONCE_DEFINE_GLOBAL NVTX_LINKONCE_HIDDEN NVTX_LINKONCE_WEAK + #define NVTX_LINKONCE_DEFINE_FUNCTION extern "C" NVTX_LINKONCE_HIDDEN inline + #else + #define NVTX_LINKONCE_DEFINE_GLOBAL NVTX_LINKONCE_HIDDEN NVTX_LINKONCE_WEAK + #define NVTX_LINKONCE_DEFINE_FUNCTION NVTX_LINKONCE_HIDDEN NVTX_LINKONCE_WEAK + #endif +#endif + +#define NVTX_LINKONCE_FWDDECL_GLOBAL NVTX_LINKONCE_DEFINE_GLOBAL extern +#define NVTX_LINKONCE_FWDDECL_FUNCTION NVTX_LINKONCE_DEFINE_FUNCTION + +#endif /* __NVTX_LINKONCE_H__ */ diff --git a/shared/package-files/26/26a09ff4dcce0eeaaa9c7f6fccacfc5a657e371a95232fda6b2f455c6fd02549/fft_ihfftn.h b/shared/package-files/26/26a09ff4dcce0eeaaa9c7f6fccacfc5a657e371a95232fda6b2f455c6fd02549/fft_ihfftn.h new file mode 100644 index 0000000000000000000000000000000000000000..85d30b49223814765d7e09c2a1a7d1a3e5395cbf --- /dev/null +++ b/shared/package-files/26/26a09ff4dcce0eeaaa9c7f6fccacfc5a657e371a95232fda6b2f455c6fd02549/fft_ihfftn.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::fft_ihfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor +inline at::Tensor fft_ihfftn(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm); +} +namespace symint { + template >> + at::Tensor fft_ihfftn(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm); + } +} + +// aten::fft_ihfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor +inline at::Tensor fft_ihfftn_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn::call(self, s, dim, norm); +} +namespace symint { + template >> + at::Tensor fft_ihfftn(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn::call(self, s, dim, norm); + } +} + +// aten::fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_ihfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_ihfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_ihfftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_ihfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_ihfftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_ihfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_ihfftn_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn_out::call(self, s, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_ihfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_ihfftn_out::call(self, s, dim, norm, out); + } +} + +// aten::fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_ihfftn_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_ihfftn_out::call(self, s, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_ihfftn_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_ihfftn_out::call(self, s, dim, norm, out); + } +} + +} diff --git a/shared/package-files/26/26a2627d6832ee16e1bc1b4932e67417aa7e91c3006b757404203b4011ee4b87/silu_backward_ops.h b/shared/package-files/26/26a2627d6832ee16e1bc1b4932e67417aa7e91c3006b757404203b4011ee4b87/silu_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ed613e3d93332a988ff91b1aad587e4a0ee19664 --- /dev/null +++ b/shared/package-files/26/26a2627d6832ee16e1bc1b4932e67417aa7e91c3006b757404203b4011ee4b87/silu_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API silu_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::silu_backward"; + static constexpr const char* overload_name = "grad_input"; + static constexpr const char* schema_str = "silu_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & grad_input); +}; + +struct TORCH_API silu_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::silu_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "silu_backward(Tensor grad_output, Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/26a6709521fd390342438c3560a643b35dd5779d747e1cee075dda3bed3cd202/remote_module_template.cpython-311.pyc b/shared/package-files/26/26a6709521fd390342438c3560a643b35dd5779d747e1cee075dda3bed3cd202/remote_module_template.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d3e541acdb7174e858b3d10a58e39effca39852 Binary files /dev/null and b/shared/package-files/26/26a6709521fd390342438c3560a643b35dd5779d747e1cee075dda3bed3cd202/remote_module_template.cpython-311.pyc differ diff --git a/shared/package-files/26/26a6740ed0c558b7c3db2d91f6a3a514c76f6c70eda1acb662042c66e0b9b291/test_interp_fillna.cpython-311.pyc b/shared/package-files/26/26a6740ed0c558b7c3db2d91f6a3a514c76f6c70eda1acb662042c66e0b9b291/test_interp_fillna.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7d54887670d7d1fcad7a48e063f6f0fae26f13e Binary files /dev/null and b/shared/package-files/26/26a6740ed0c558b7c3db2d91f6a3a514c76f6c70eda1acb662042c66e0b9b291/test_interp_fillna.cpython-311.pyc differ diff --git a/shared/package-files/26/26b4b4767732ad9b2e1214345f49104ff97412224cc7ab01cbffb2355ba43a06/expat.cpython-311.pyc b/shared/package-files/26/26b4b4767732ad9b2e1214345f49104ff97412224cc7ab01cbffb2355ba43a06/expat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b76bbd7c05ea2bfb5218172a637fe543df45ed4f Binary files /dev/null and b/shared/package-files/26/26b4b4767732ad9b2e1214345f49104ff97412224cc7ab01cbffb2355ba43a06/expat.cpython-311.pyc differ diff --git a/shared/package-files/26/26be692fae14ff1d3c5ad3ac86f4f216d8828b5b29282bfc08802c9ce05d691d/multiarray.cpython-311.pyc b/shared/package-files/26/26be692fae14ff1d3c5ad3ac86f4f216d8828b5b29282bfc08802c9ce05d691d/multiarray.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92e2c7f5c090398e4de54a5ac84927023fc7ae8b Binary files /dev/null and b/shared/package-files/26/26be692fae14ff1d3c5ad3ac86f4f216d8828b5b29282bfc08802c9ce05d691d/multiarray.cpython-311.pyc differ diff --git a/shared/package-files/26/26bfa20fc306ff817a229ff2c5ba04f0eaf59acf9ba376b2ffaa5d8206df578e/_docs.py b/shared/package-files/26/26bfa20fc306ff817a229ff2c5ba04f0eaf59acf9ba376b2ffaa5d8206df578e/_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa130bbefbc5caa7373459ef2fc3dc5292239948 --- /dev/null +++ b/shared/package-files/26/26bfa20fc306ff817a229ff2c5ba04f0eaf59acf9ba376b2ffaa5d8206df578e/_docs.py @@ -0,0 +1,1177 @@ +# This file is generated, do not modify it! +# +# To update this file, run the update masked docs script as follows: +# +# python tools/update_masked_docs.py +# +# The script must be called from an environment where the development +# version of torch package can be imported and is functional. +# + +amax_docstring = """amax(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns maximum of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of maximum operation, which is used to start the +reduction, depends on input dtype. For instance, for float32, uint8, +and int32 dtypes, the identity values are ``-inf``, ``0``, and ``-2147483648``, respectively. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in maximum computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of maximum operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.amax(input, 1, mask=mask) + tensor([ -1, -9223372036854775808]) +""" + +amin_docstring = """amin(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns minimum of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of minimum operation, which is used to start the +reduction, depends on input dtype. For instance, for float32, uint8, +and int32 dtypes, the identity values are ``inf``, ``255``, and ``2147483647``, respectively. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in minimum computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of minimum operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.amin(input, 1, mask=mask) + tensor([ -3, 9223372036854775807]) +""" + +argmax_docstring = """argmax(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor +Returns argmax of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. +The identity value of argmax operation, which is used to start the +reduction, depends on input dtype. For instance, for float32, uint8, +and int32 dtypes, the identity values are ``-inf``, ``0``, and ``-2147483648``, respectively. +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in argmax computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of argmax operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which argmax is computed. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.argmax(input, 1, mask=mask) + tensor([2, 0]) +""" + +argmin_docstring = """argmin(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor +Returns argmin of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. +The identity value of argmin operation, which is used to start the +reduction, depends on input dtype. For instance, for float32, uint8, +and int32 dtypes, the identity values are ``inf``, ``255``, and ``2147483647``, respectively. +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in argmin computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of argmin operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which argmin is computed. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.argmin(input, 1, mask=mask) + tensor([0, 0]) +""" + +cumprod_docstring = """cumprod(input, dim, *, dtype=None, mask=None) -> Tensor + +Returns cumulative_prod of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. Cumsum of i-th element in ``x`` is +defined as ``prod(x[:i])``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +cumulative_prod computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the cumulative_prod output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which cumulative_prod is computed. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.cumprod(input, 1, mask=mask) + tensor([[-3., -3., 3.], + [ 1., 1., 1.]]) +""" + +cumsum_docstring = """cumsum(input, dim, *, dtype=None, mask=None) -> Tensor + +Returns cumulative_sum of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. Cumsum of i-th element in ``x`` is +defined as ``sum(x[:i])``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +cumulative_sum computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the cumulative_sum output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which cumulative_sum is computed. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.cumsum(input, 1, mask=mask) + tensor([[-3., -3., -4.], + [ 0., 0., 0.]]) +""" + +log_softmax_docstring = """log_softmax(input, dim, *, dtype=None, mask=None) -> Tensor + +Returns log_softmax of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. LogSoftmax of i-th element in ``x`` is +defined as ``log(exp(x[i])/sum(exp(x)))``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +log_softmax computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the log_softmax output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which log_softmax is computed. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.log_softmax(input, 1, mask=mask) + tensor([[-2.1269, -inf, -0.1269], + [ nan, nan, nan]]) +""" + +logsumexp_docstring = """logsumexp(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns logsumexp of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of logsumexp operation, which is used to start the reduction, is ``-2147483648``. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in logsumexp computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of logsumexp operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.logsumexp(input, 1, mask=mask) + tensor([ 0, -9223372036854775808]) +""" + +mean_docstring = """mean(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns mean of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +By definition, the identity value of a mean operation is the mean +value of the tensor. If all elements of the input tensor along given +dimension(s) :attr:`dim` are masked-out, the identity value of the +mean is undefined. Due to this ambiguity, the elements of output +tensor with strided layout, that correspond to fully masked-out +elements, have ``nan`` values. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in mean computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of mean operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.mean(input, 1, mask=mask) + tensor([-2., nan]) +""" + +median_docstring = """median(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor +Returns median of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. +By definition, the identity value of a median operation is the median +value of the tensor. If all elements of the input tensor along given +dimension(s) :attr:`dim` are masked-out, the identity value of the +median is undefined. Due to this ambiguity, the elements of output +tensor with strided layout, that correspond to fully masked-out +elements, have ``nan`` values. +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in median computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of median operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which median is computed. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.median(input, 1, mask=mask) + tensor([-3., nan]) +""" + +norm_docstring = """norm(input, ord, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns norm of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of norm operation, which is used to start the +reduction, is ``0.0``, except for ``ord=-inf`` it is +``inf``. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in norm computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of norm operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + ord (int, float, optional): the order of vector norm. Default: 2. + See :func:`torch.linalg.vector_norm` for a list of supported norms. + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.norm(input, 2.0, 1, mask=mask) + tensor([3.1623, 0.0000]) +""" + +normalize_docstring = """normalize(input, ord, dim, *, eps=1e-12, dtype=None, mask=None) -> Tensor + +Returns normalize of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. Normalize of i-th element in ``x`` is +defined as ``x[i]/max(norm(x, p), eps)``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +normalize computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the normalize output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + ord (int, float): the order of vector norm. Default: 2. + See :func:`torch.linalg.vector_norm` for a list of supported norms. + dim (int): the dimension along which normalize is computed. + +Keyword args: + eps (float, optional): small value to avoid division by zero. Default: 1e-12. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.normalize(input, 2.0, 1, mask=mask) + tensor([[-0.9487, 0.0000, -0.3162], + [ 0.0000, 0.0000, 0.0000]]) +""" + +prod_docstring = """prod(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns product of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of product operation, which is used to start the reduction, is ``1``. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in product computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of product operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.prod(input, 1, mask=mask) + tensor([3, 1]) +""" + +softmax_docstring = """softmax(input, dim, *, dtype=None, mask=None) -> Tensor + +Returns softmax of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. Softmax of i-th element in ``x`` is +defined as ``exp(x[i])/sum(exp(x))``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +softmax computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the softmax output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which softmax is computed. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.softmax(input, 1, mask=mask) + tensor([[0.1192, 0.0000, 0.8808], + [ nan, nan, nan]]) +""" + +softmin_docstring = """softmin(input, dim, *, dtype=None, mask=None) -> Tensor + +Returns softmin of all the slices in the :attr:`input` tensor +along :attr:`dim` while the :attr:`input` elements are masked out +according to the boolean tensor :attr:`mask`. + +Let ``x`` be a sequence of unmasked elements of one-dimensional slice +of the :attr:`input` tensor. Softmin of i-th element in ``x`` is +defined as ``exp(-x[i])/sum(exp(-x))``. + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True then +the corresponding element in :attr:`input` tensor will be included in +softmin computation, otherwise the element is ignored. + +The values of masked-out elements of the output tensor have undefined +value: it may or may not be set to zero or nan; the choice may correspond to +the value that leads to the most efficient storage of :attr:`output` +tensor. + +The mask of the softmin output tensor can be computed as +``torch.broadcast_to(mask, input.shape)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int): the dimension along which softmin is computed. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3., -2., -1.], [ 0., 1., 2.]]) + >>> input + tensor([[-3., -2., -1.], + [ 0., 1., 2.]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.softmin(input, 1, mask=mask) + tensor([[0.8808, 0.0000, 0.1192], + [ nan, nan, nan]]) +""" + +std_docstring = """std(input, dim, unbiased, *, keepdim=False, dtype=None, mask=None) -> Tensor +Returns standard_deviation of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. +The identity value of sample standard deviation operation is undefined. The +elements of output tensor with strided layout, that correspond to +fully masked-out elements, have ``nan`` values. +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in standard_deviation computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of standard_deviation operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + unbiased (bool): when True, use Bessel's correction, otherwise, compute + the uncorrected sample variance. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.std(input, 1, False, mask=mask) + tensor([1., nan]) +""" + +sum_docstring = """sum(input, dim, *, keepdim=False, dtype=None, mask=None) -> Tensor + +Returns sum of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. + +The identity value of sum operation, which is used to start the reduction, is ``0``. + +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in sum computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of sum operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. + +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.sum(input, 1, mask=mask) + tensor([-4, 0]) +""" + +var_docstring = """var(input, dim, unbiased, *, keepdim=False, dtype=None, mask=None) -> Tensor +Returns variance of all the elements in the :attr:`input` +tensor along the given dimension(s) :attr:`dim` while the :attr:`input` +elements are masked out according to the boolean tensor +:attr:`mask`. +The identity value of sample variance operation is undefined. The +elements of output tensor with strided layout, that correspond to +fully masked-out elements, have ``nan`` values. +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of +size 1. Otherwise, :attr:`dim` is squeezed (see +:func:`torch.squeeze`), resulting in the output tensor having 1 (or +``len(dim)``) fewer dimension(s). + +The boolean tensor :attr:`mask` defines the "validity" of +:attr:`input` tensor elements: if :attr:`mask` element is True +then the corresponding element in :attr:`input` tensor will be +included in variance computation, otherwise the element is +ignored. + +When all elements of :attr:`input` along the given dimension +:attr:`dim` are ignored (fully masked-out), the corresponding element +of the output tensor will have undefined value: it may or may not +correspond to the identity value of variance operation; the +choice may correspond to the value that leads to the most efficient +storage of :attr:`output` tensor. + +The mask of the output tensor can be computed as +``torch.any(torch.broadcast_to(mask, input.shape), dim, keepdim=keepdim, +dtype=torch.bool)``. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor +don't need to match, but they must be :ref:`broadcastable +` and the dimensionality of the :attr:`mask` +tensor must not be greater than of the :attr:`input` tensor. + +Args: + input (Tensor): the input tensor + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + Default: None that is equivalent to ``tuple(range(input.ndim))``. + unbiased (bool): when True, use Bessel's correction, otherwise, compute + the uncorrected sample variance. + +Keyword args: + keepdim (bool, optional): whether the output tensor has + :attr:`dim` retained or not. Default: False. + dtype (:class:`torch.dtype`, optional): the desired data type + of returned tensor. If specified, the input tensor is + casted to :attr:`dtype` before the operation is + performed. Default: None. + mask (:class:`torch.Tensor`, optional): the boolean tensor + containing the binary mask of validity of input tensor + elements. + Default: None that is equivalent to ``torch.ones(input.shape, dtype=torch.bool)``. +Example:: + + >>> input = tensor([[-3, -2, -1], [ 0, 1, 2]]) + >>> input + tensor([[-3, -2, -1], + [ 0, 1, 2]]) + >>> mask = tensor([[ True, False, True], [False, False, False]]) + >>> mask + tensor([[ True, False, True], + [False, False, False]]) + >>> torch.masked._ops.var(input, 1, False, mask=mask) + tensor([1., nan]) +""" diff --git a/shared/package-files/26/26c2285bd1b7f29a11bac4cb007a01f0d84916fcac55deb828d3678c9ec5e7d5/shard.cpython-311.pyc b/shared/package-files/26/26c2285bd1b7f29a11bac4cb007a01f0d84916fcac55deb828d3678c9ec5e7d5/shard.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..211fb79b03b54420c79e6bdeb6d18029eadfcc94 Binary files /dev/null and b/shared/package-files/26/26c2285bd1b7f29a11bac4cb007a01f0d84916fcac55deb828d3678c9ec5e7d5/shard.cpython-311.pyc differ diff --git a/shared/package-files/26/26c434e4f523c4c17ebda084c735d379584225b4330715388c38e0ece81e9076/sets.cpython-311.pyc b/shared/package-files/26/26c434e4f523c4c17ebda084c735d379584225b4330715388c38e0ece81e9076/sets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74862315dbe3ea1f9b8ce539d86116f80f82a14f Binary files /dev/null and b/shared/package-files/26/26c434e4f523c4c17ebda084c735d379584225b4330715388c38e0ece81e9076/sets.cpython-311.pyc differ diff --git a/shared/package-files/26/26c91948abcaa2da9b792fb6504e614c1e5ec89e6dbaea2da19deee3bbf7dd46/multi.py b/shared/package-files/26/26c91948abcaa2da9b792fb6504e614c1e5ec89e6dbaea2da19deee3bbf7dd46/multi.py new file mode 100644 index 0000000000000000000000000000000000000000..091ddbcc099be87e92926e18bdddea60b88ed68d --- /dev/null +++ b/shared/package-files/26/26c91948abcaa2da9b792fb6504e614c1e5ec89e6dbaea2da19deee3bbf7dd46/multi.py @@ -0,0 +1,4157 @@ +from __future__ import annotations + +from collections.abc import ( + Collection, + Generator, + Hashable, + Iterable, + Sequence, +) +from functools import wraps +from sys import getsizeof +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Literal, + cast, +) +import warnings + +import numpy as np + +from pandas._config import get_option + +from pandas._libs import ( + algos as libalgos, + index as libindex, + lib, +) +from pandas._libs.hashtable import duplicated +from pandas._typing import ( + AnyAll, + AnyArrayLike, + Axis, + DropKeep, + DtypeObj, + F, + IgnoreRaise, + IndexLabel, + Scalar, + Self, + Shape, + npt, +) +from pandas.compat.numpy import function as nv +from pandas.errors import ( + InvalidIndexError, + PerformanceWarning, + UnsortedIndexError, +) +from pandas.util._decorators import ( + Appender, + cache_readonly, + doc, +) +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.cast import coerce_indexer_dtype +from pandas.core.dtypes.common import ( + ensure_int64, + ensure_platform_int, + is_hashable, + is_integer, + is_iterator, + is_list_like, + is_object_dtype, + is_scalar, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + ExtensionDtype, +) +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCSeries, +) +from pandas.core.dtypes.inference import is_array_like +from pandas.core.dtypes.missing import ( + array_equivalent, + isna, +) + +import pandas.core.algorithms as algos +from pandas.core.array_algos.putmask import validate_putmask +from pandas.core.arrays import ( + Categorical, + ExtensionArray, +) +from pandas.core.arrays.categorical import ( + factorize_from_iterables, + recode_for_categories, +) +import pandas.core.common as com +from pandas.core.construction import sanitize_array +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import ( + Index, + _index_shared_docs, + ensure_index, + get_unanimous_names, +) +from pandas.core.indexes.frozen import FrozenList +from pandas.core.ops.invalid import make_invalid_op +from pandas.core.sorting import ( + get_group_index, + lexsort_indexer, +) + +from pandas.io.formats.printing import ( + get_adjustment, + pprint_thing, +) + +if TYPE_CHECKING: + from pandas import ( + CategoricalIndex, + DataFrame, + Series, + ) + +_index_doc_kwargs = dict(ibase._index_doc_kwargs) +_index_doc_kwargs.update( + {"klass": "MultiIndex", "target_klass": "MultiIndex or list of tuples"} +) + + +class MultiIndexUIntEngine(libindex.BaseMultiIndexCodesEngine, libindex.UInt64Engine): + """ + This class manages a MultiIndex by mapping label combinations to positive + integers. + """ + + _base = libindex.UInt64Engine + + def _codes_to_ints(self, codes): + """ + Transform combination(s) of uint64 in one uint64 (each), in a strictly + monotonic way (i.e. respecting the lexicographic order of integer + combinations): see BaseMultiIndexCodesEngine documentation. + + Parameters + ---------- + codes : 1- or 2-dimensional array of dtype uint64 + Combinations of integers (one per row) + + Returns + ------- + scalar or 1-dimensional array, of dtype uint64 + Integer(s) representing one combination (each). + """ + # Shift the representation of each level by the pre-calculated number + # of bits: + codes <<= self.offsets + + # Now sum and OR are in fact interchangeable. This is a simple + # composition of the (disjunct) significant bits of each level (i.e. + # each column in "codes") in a single positive integer: + if codes.ndim == 1: + # Single key + return np.bitwise_or.reduce(codes) + + # Multiple keys + return np.bitwise_or.reduce(codes, axis=1) + + +class MultiIndexPyIntEngine(libindex.BaseMultiIndexCodesEngine, libindex.ObjectEngine): + """ + This class manages those (extreme) cases in which the number of possible + label combinations overflows the 64 bits integers, and uses an ObjectEngine + containing Python integers. + """ + + _base = libindex.ObjectEngine + + def _codes_to_ints(self, codes): + """ + Transform combination(s) of uint64 in one Python integer (each), in a + strictly monotonic way (i.e. respecting the lexicographic order of + integer combinations): see BaseMultiIndexCodesEngine documentation. + + Parameters + ---------- + codes : 1- or 2-dimensional array of dtype uint64 + Combinations of integers (one per row) + + Returns + ------- + int, or 1-dimensional array of dtype object + Integer(s) representing one combination (each). + """ + # Shift the representation of each level by the pre-calculated number + # of bits. Since this can overflow uint64, first make sure we are + # working with Python integers: + codes = codes.astype("object") << self.offsets + + # Now sum and OR are in fact interchangeable. This is a simple + # composition of the (disjunct) significant bits of each level (i.e. + # each column in "codes") in a single positive integer (per row): + if codes.ndim == 1: + # Single key + return np.bitwise_or.reduce(codes) + + # Multiple keys + return np.bitwise_or.reduce(codes, axis=1) + + +def names_compat(meth: F) -> F: + """ + A decorator to allow either `name` or `names` keyword but not both. + + This makes it easier to share code with base class. + """ + + @wraps(meth) + def new_meth(self_or_cls, *args, **kwargs): + if "name" in kwargs and "names" in kwargs: + raise TypeError("Can only provide one of `names` and `name`") + if "name" in kwargs: + kwargs["names"] = kwargs.pop("name") + + return meth(self_or_cls, *args, **kwargs) + + return cast(F, new_meth) + + +class MultiIndex(Index): + """ + A multi-level, or hierarchical, index object for pandas objects. + + Parameters + ---------- + levels : sequence of arrays + The unique labels for each level. + codes : sequence of arrays + Integers for each level designating which label at each location. + sortorder : optional int + Level of sortedness (must be lexicographically sorted by that + level). + names : optional sequence of objects + Names for each of the index levels. (name is accepted for compat). + copy : bool, default False + Copy the meta-data. + verify_integrity : bool, default True + Check that the levels/codes are consistent and valid. + + Attributes + ---------- + names + levels + codes + nlevels + levshape + dtypes + + Methods + ------- + from_arrays + from_tuples + from_product + from_frame + set_levels + set_codes + to_frame + to_flat_index + sortlevel + droplevel + swaplevel + reorder_levels + remove_unused_levels + get_level_values + get_indexer + get_loc + get_locs + get_loc_level + drop + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_product : Create a MultiIndex from the cartesian product + of iterables. + MultiIndex.from_tuples : Convert list of tuples to a MultiIndex. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + Index : The base pandas Index type. + + Notes + ----- + See the `user guide + `__ + for more. + + Examples + -------- + A new ``MultiIndex`` is typically constructed using one of the helper + methods :meth:`MultiIndex.from_arrays`, :meth:`MultiIndex.from_product` + and :meth:`MultiIndex.from_tuples`. For example (using ``.from_arrays``): + + >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] + >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) + MultiIndex([(1, 'red'), + (1, 'blue'), + (2, 'red'), + (2, 'blue')], + names=['number', 'color']) + + See further examples for how to construct a MultiIndex in the doc strings + of the mentioned helper methods. + """ + + _hidden_attrs = Index._hidden_attrs | frozenset() + + # initialize to zero-length tuples to make everything work + _typ = "multiindex" + _names: list[Hashable | None] = [] + _levels = FrozenList() + _codes = FrozenList() + _comparables = ["names"] + + sortorder: int | None + + # -------------------------------------------------------------------- + # Constructors + + def __new__( + cls, + levels=None, + codes=None, + sortorder=None, + names=None, + dtype=None, + copy: bool = False, + name=None, + verify_integrity: bool = True, + ) -> Self: + # compat with Index + if name is not None: + names = name + if levels is None or codes is None: + raise TypeError("Must pass both levels and codes") + if len(levels) != len(codes): + raise ValueError("Length of levels and codes must be the same.") + if len(levels) == 0: + raise ValueError("Must pass non-zero number of levels/codes") + + result = object.__new__(cls) + result._cache = {} + + # we've already validated levels and codes, so shortcut here + result._set_levels(levels, copy=copy, validate=False) + result._set_codes(codes, copy=copy, validate=False) + + result._names = [None] * len(levels) + if names is not None: + # handles name validation + result._set_names(names) + + if sortorder is not None: + result.sortorder = int(sortorder) + else: + result.sortorder = sortorder + + if verify_integrity: + new_codes = result._verify_integrity() + result._codes = new_codes + + result._reset_identity() + result._references = None + + return result + + def _validate_codes(self, level: list, code: list): + """ + Reassign code values as -1 if their corresponding levels are NaN. + + Parameters + ---------- + code : list + Code to reassign. + level : list + Level to check for missing values (NaN, NaT, None). + + Returns + ------- + new code where code value = -1 if it corresponds + to a level with missing values (NaN, NaT, None). + """ + null_mask = isna(level) + if np.any(null_mask): + # error: Incompatible types in assignment + # (expression has type "ndarray[Any, dtype[Any]]", + # variable has type "List[Any]") + code = np.where(null_mask[code], -1, code) # type: ignore[assignment] + return code + + def _verify_integrity( + self, + codes: list | None = None, + levels: list | None = None, + levels_to_verify: list[int] | range | None = None, + ): + """ + Parameters + ---------- + codes : optional list + Codes to check for validity. Defaults to current codes. + levels : optional list + Levels to check for validity. Defaults to current levels. + levels_to_validate: optional list + Specifies the levels to verify. + + Raises + ------ + ValueError + If length of levels and codes don't match, if the codes for any + level would exceed level bounds, or there are any duplicate levels. + + Returns + ------- + new codes where code value = -1 if it corresponds to a + NaN level. + """ + # NOTE: Currently does not check, among other things, that cached + # nlevels matches nor that sortorder matches actually sortorder. + codes = codes or self.codes + levels = levels or self.levels + if levels_to_verify is None: + levels_to_verify = range(len(levels)) + + if len(levels) != len(codes): + raise ValueError( + "Length of levels and codes must match. NOTE: " + "this index is in an inconsistent state." + ) + codes_length = len(codes[0]) + for i in levels_to_verify: + level = levels[i] + level_codes = codes[i] + + if len(level_codes) != codes_length: + raise ValueError( + f"Unequal code lengths: {[len(code_) for code_ in codes]}" + ) + if len(level_codes) and level_codes.max() >= len(level): + raise ValueError( + f"On level {i}, code max ({level_codes.max()}) >= length of " + f"level ({len(level)}). NOTE: this index is in an " + "inconsistent state" + ) + if len(level_codes) and level_codes.min() < -1: + raise ValueError(f"On level {i}, code value ({level_codes.min()}) < -1") + if not level.is_unique: + raise ValueError( + f"Level values must be unique: {list(level)} on level {i}" + ) + if self.sortorder is not None: + if self.sortorder > _lexsort_depth(self.codes, self.nlevels): + raise ValueError( + "Value for sortorder must be inferior or equal to actual " + f"lexsort_depth: sortorder {self.sortorder} " + f"with lexsort_depth {_lexsort_depth(self.codes, self.nlevels)}" + ) + + result_codes = [] + for i in range(len(levels)): + if i in levels_to_verify: + result_codes.append(self._validate_codes(levels[i], codes[i])) + else: + result_codes.append(codes[i]) + + new_codes = FrozenList(result_codes) + return new_codes + + @classmethod + def from_arrays( + cls, + arrays, + sortorder: int | None = None, + names: Sequence[Hashable] | Hashable | lib.NoDefault = lib.no_default, + ) -> MultiIndex: + """ + Convert arrays to MultiIndex. + + Parameters + ---------- + arrays : list / sequence of array-likes + Each array-like gives one level's value for each data point. + len(arrays) is the number of levels. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + + Returns + ------- + MultiIndex + + See Also + -------- + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] + >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) + MultiIndex([(1, 'red'), + (1, 'blue'), + (2, 'red'), + (2, 'blue')], + names=['number', 'color']) + """ + error_msg = "Input must be a list / sequence of array-likes." + if not is_list_like(arrays): + raise TypeError(error_msg) + if is_iterator(arrays): + arrays = list(arrays) + + # Check if elements of array are list-like + for array in arrays: + if not is_list_like(array): + raise TypeError(error_msg) + + # Check if lengths of all arrays are equal or not, + # raise ValueError, if not + for i in range(1, len(arrays)): + if len(arrays[i]) != len(arrays[i - 1]): + raise ValueError("all arrays must be same length") + + codes, levels = factorize_from_iterables(arrays) + if names is lib.no_default: + names = [getattr(arr, "name", None) for arr in arrays] + + return cls( + levels=levels, + codes=codes, + sortorder=sortorder, + names=names, + verify_integrity=False, + ) + + @classmethod + @names_compat + def from_tuples( + cls, + tuples: Iterable[tuple[Hashable, ...]], + sortorder: int | None = None, + names: Sequence[Hashable] | Hashable | None = None, + ) -> MultiIndex: + """ + Convert list of tuples to MultiIndex. + + Parameters + ---------- + tuples : list / sequence of tuple-likes + Each tuple is the index of one row/column. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + + Returns + ------- + MultiIndex + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> tuples = [(1, 'red'), (1, 'blue'), + ... (2, 'red'), (2, 'blue')] + >>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color')) + MultiIndex([(1, 'red'), + (1, 'blue'), + (2, 'red'), + (2, 'blue')], + names=['number', 'color']) + """ + if not is_list_like(tuples): + raise TypeError("Input must be a list / sequence of tuple-likes.") + if is_iterator(tuples): + tuples = list(tuples) + tuples = cast(Collection[tuple[Hashable, ...]], tuples) + + # handling the empty tuple cases + if len(tuples) and all(isinstance(e, tuple) and not e for e in tuples): + codes = [np.zeros(len(tuples))] + levels = [Index(com.asarray_tuplesafe(tuples, dtype=np.dtype("object")))] + return cls( + levels=levels, + codes=codes, + sortorder=sortorder, + names=names, + verify_integrity=False, + ) + + arrays: list[Sequence[Hashable]] + if len(tuples) == 0: + if names is None: + raise TypeError("Cannot infer number of levels from empty list") + # error: Argument 1 to "len" has incompatible type "Hashable"; + # expected "Sized" + arrays = [[]] * len(names) # type: ignore[arg-type] + elif isinstance(tuples, (np.ndarray, Index)): + if isinstance(tuples, Index): + tuples = np.asarray(tuples._values) + + arrays = list(lib.tuples_to_object_array(tuples).T) + elif isinstance(tuples, list): + arrays = list(lib.to_object_array_tuples(tuples).T) + else: + arrs = zip(*tuples) + arrays = cast(list[Sequence[Hashable]], arrs) + + return cls.from_arrays(arrays, sortorder=sortorder, names=names) + + @classmethod + def from_product( + cls, + iterables: Sequence[Iterable[Hashable]], + sortorder: int | None = None, + names: Sequence[Hashable] | Hashable | lib.NoDefault = lib.no_default, + ) -> MultiIndex: + """ + Make a MultiIndex from the cartesian product of multiple iterables. + + Parameters + ---------- + iterables : list / sequence of iterables + Each iterable has unique labels for each level of the index. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + If not explicitly provided, names will be inferred from the + elements of iterables if an element has a name attribute. + + Returns + ------- + MultiIndex + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> numbers = [0, 1, 2] + >>> colors = ['green', 'purple'] + >>> pd.MultiIndex.from_product([numbers, colors], + ... names=['number', 'color']) + MultiIndex([(0, 'green'), + (0, 'purple'), + (1, 'green'), + (1, 'purple'), + (2, 'green'), + (2, 'purple')], + names=['number', 'color']) + """ + from pandas.core.reshape.util import cartesian_product + + if not is_list_like(iterables): + raise TypeError("Input must be a list / sequence of iterables.") + if is_iterator(iterables): + iterables = list(iterables) + + codes, levels = factorize_from_iterables(iterables) + if names is lib.no_default: + names = [getattr(it, "name", None) for it in iterables] + + # codes are all ndarrays, so cartesian_product is lossless + codes = cartesian_product(codes) + return cls(levels, codes, sortorder=sortorder, names=names) + + @classmethod + def from_frame( + cls, + df: DataFrame, + sortorder: int | None = None, + names: Sequence[Hashable] | Hashable | None = None, + ) -> MultiIndex: + """ + Make a MultiIndex from a DataFrame. + + Parameters + ---------- + df : DataFrame + DataFrame to be converted to MultiIndex. + sortorder : int, optional + Level of sortedness (must be lexicographically sorted by that + level). + names : list-like, optional + If no names are provided, use the column names, or tuple of column + names if the columns is a MultiIndex. If a sequence, overwrite + names with the given sequence. + + Returns + ------- + MultiIndex + The MultiIndex representation of the given DataFrame. + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + + Examples + -------- + >>> df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'], + ... ['NJ', 'Temp'], ['NJ', 'Precip']], + ... columns=['a', 'b']) + >>> df + a b + 0 HI Temp + 1 HI Precip + 2 NJ Temp + 3 NJ Precip + + >>> pd.MultiIndex.from_frame(df) + MultiIndex([('HI', 'Temp'), + ('HI', 'Precip'), + ('NJ', 'Temp'), + ('NJ', 'Precip')], + names=['a', 'b']) + + Using explicit names, instead of the column names + + >>> pd.MultiIndex.from_frame(df, names=['state', 'observation']) + MultiIndex([('HI', 'Temp'), + ('HI', 'Precip'), + ('NJ', 'Temp'), + ('NJ', 'Precip')], + names=['state', 'observation']) + """ + if not isinstance(df, ABCDataFrame): + raise TypeError("Input must be a DataFrame") + + column_names, columns = zip(*df.items()) + names = column_names if names is None else names + return cls.from_arrays(columns, sortorder=sortorder, names=names) + + # -------------------------------------------------------------------- + + @cache_readonly + def _values(self) -> np.ndarray: + # We override here, since our parent uses _data, which we don't use. + values = [] + + for i in range(self.nlevels): + index = self.levels[i] + codes = self.codes[i] + + vals = index + if isinstance(vals.dtype, CategoricalDtype): + vals = cast("CategoricalIndex", vals) + vals = vals._data._internal_get_values() + + if isinstance(vals.dtype, ExtensionDtype) or lib.is_np_dtype( + vals.dtype, "mM" + ): + vals = vals.astype(object) + + vals = np.asarray(vals) + vals = algos.take_nd(vals, codes, fill_value=index._na_value) + values.append(vals) + + arr = lib.fast_zip(values) + return arr + + @property + def values(self) -> np.ndarray: + return self._values + + @property + def array(self): + """ + Raises a ValueError for `MultiIndex` because there's no single + array backing a MultiIndex. + + Raises + ------ + ValueError + """ + raise ValueError( + "MultiIndex has no single backing array. Use " + "'MultiIndex.to_numpy()' to get a NumPy array of tuples." + ) + + @cache_readonly + def dtypes(self) -> Series: + """ + Return the dtypes as a Series for the underlying MultiIndex. + + Examples + -------- + >>> idx = pd.MultiIndex.from_product([(0, 1, 2), ('green', 'purple')], + ... names=['number', 'color']) + >>> idx + MultiIndex([(0, 'green'), + (0, 'purple'), + (1, 'green'), + (1, 'purple'), + (2, 'green'), + (2, 'purple')], + names=['number', 'color']) + >>> idx.dtypes + number int64 + color object + dtype: object + """ + from pandas import Series + + names = com.fill_missing_names([level.name for level in self.levels]) + return Series([level.dtype for level in self.levels], index=Index(names)) + + def __len__(self) -> int: + return len(self.codes[0]) + + @property + def size(self) -> int: + """ + Return the number of elements in the underlying data. + """ + # override Index.size to avoid materializing _values + return len(self) + + # -------------------------------------------------------------------- + # Levels Methods + + @cache_readonly + def levels(self) -> FrozenList: + """ + Levels of the MultiIndex. + + Levels refer to the different hierarchical levels or layers in a MultiIndex. + In a MultiIndex, each level represents a distinct dimension or category of + the index. + + To access the levels, you can use the levels attribute of the MultiIndex, + which returns a tuple of Index objects. Each Index object represents a + level in the MultiIndex and contains the unique values found in that + specific level. + + If a MultiIndex is created with levels A, B, C, and the DataFrame using + it filters out all rows of the level C, MultiIndex.levels will still + return A, B, C. + + Examples + -------- + >>> index = pd.MultiIndex.from_product([['mammal'], + ... ('goat', 'human', 'cat', 'dog')], + ... names=['Category', 'Animals']) + >>> leg_num = pd.DataFrame(data=(4, 2, 4, 4), index=index, columns=['Legs']) + >>> leg_num + Legs + Category Animals + mammal goat 4 + human 2 + cat 4 + dog 4 + + >>> leg_num.index.levels + FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']]) + + MultiIndex levels will not change even if the DataFrame using the MultiIndex + does not contain all them anymore. + See how "human" is not in the DataFrame, but it is still in levels: + + >>> large_leg_num = leg_num[leg_num.Legs > 2] + >>> large_leg_num + Legs + Category Animals + mammal goat 4 + cat 4 + dog 4 + + >>> large_leg_num.index.levels + FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']]) + """ + # Use cache_readonly to ensure that self.get_locs doesn't repeatedly + # create new IndexEngine + # https://github.com/pandas-dev/pandas/issues/31648 + result = [x._rename(name=name) for x, name in zip(self._levels, self._names)] + for level in result: + # disallow midx.levels[0].name = "foo" + level._no_setting_name = True + return FrozenList(result) + + def _set_levels( + self, + levels, + *, + level=None, + copy: bool = False, + validate: bool = True, + verify_integrity: bool = False, + ) -> None: + # This is NOT part of the levels property because it should be + # externally not allowed to set levels. User beware if you change + # _levels directly + if validate: + if len(levels) == 0: + raise ValueError("Must set non-zero number of levels.") + if level is None and len(levels) != self.nlevels: + raise ValueError("Length of levels must match number of levels.") + if level is not None and len(levels) != len(level): + raise ValueError("Length of levels must match length of level.") + + if level is None: + new_levels = FrozenList( + ensure_index(lev, copy=copy)._view() for lev in levels + ) + level_numbers = list(range(len(new_levels))) + else: + level_numbers = [self._get_level_number(lev) for lev in level] + new_levels_list = list(self._levels) + for lev_num, lev in zip(level_numbers, levels): + new_levels_list[lev_num] = ensure_index(lev, copy=copy)._view() + new_levels = FrozenList(new_levels_list) + + if verify_integrity: + new_codes = self._verify_integrity( + levels=new_levels, levels_to_verify=level_numbers + ) + self._codes = new_codes + + names = self.names + self._levels = new_levels + if any(names): + self._set_names(names) + + self._reset_cache() + + def set_levels( + self, levels, *, level=None, verify_integrity: bool = True + ) -> MultiIndex: + """ + Set new levels on MultiIndex. Defaults to returning new index. + + Parameters + ---------- + levels : sequence or list of sequence + New level(s) to apply. + level : int, level name, or sequence of int/level names (default None) + Level(s) to set (None for all levels). + verify_integrity : bool, default True + If True, checks that levels and codes are compatible. + + Returns + ------- + MultiIndex + + Examples + -------- + >>> idx = pd.MultiIndex.from_tuples( + ... [ + ... (1, "one"), + ... (1, "two"), + ... (2, "one"), + ... (2, "two"), + ... (3, "one"), + ... (3, "two") + ... ], + ... names=["foo", "bar"] + ... ) + >>> idx + MultiIndex([(1, 'one'), + (1, 'two'), + (2, 'one'), + (2, 'two'), + (3, 'one'), + (3, 'two')], + names=['foo', 'bar']) + + >>> idx.set_levels([['a', 'b', 'c'], [1, 2]]) + MultiIndex([('a', 1), + ('a', 2), + ('b', 1), + ('b', 2), + ('c', 1), + ('c', 2)], + names=['foo', 'bar']) + >>> idx.set_levels(['a', 'b', 'c'], level=0) + MultiIndex([('a', 'one'), + ('a', 'two'), + ('b', 'one'), + ('b', 'two'), + ('c', 'one'), + ('c', 'two')], + names=['foo', 'bar']) + >>> idx.set_levels(['a', 'b'], level='bar') + MultiIndex([(1, 'a'), + (1, 'b'), + (2, 'a'), + (2, 'b'), + (3, 'a'), + (3, 'b')], + names=['foo', 'bar']) + + If any of the levels passed to ``set_levels()`` exceeds the + existing length, all of the values from that argument will + be stored in the MultiIndex levels, though the values will + be truncated in the MultiIndex output. + + >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]) + MultiIndex([('a', 1), + ('a', 2), + ('b', 1), + ('b', 2), + ('c', 1), + ('c', 2)], + names=['foo', 'bar']) + >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]).levels + FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]]) + """ + + if isinstance(levels, Index): + pass + elif is_array_like(levels): + levels = Index(levels) + elif is_list_like(levels): + levels = list(levels) + + level, levels = _require_listlike(level, levels, "Levels") + idx = self._view() + idx._reset_identity() + idx._set_levels( + levels, level=level, validate=True, verify_integrity=verify_integrity + ) + return idx + + @property + def nlevels(self) -> int: + """ + Integer number of levels in this MultiIndex. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']]) + >>> mi + MultiIndex([('a', 'b', 'c')], + ) + >>> mi.nlevels + 3 + """ + return len(self._levels) + + @property + def levshape(self) -> Shape: + """ + A tuple with the length of each level. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']]) + >>> mi + MultiIndex([('a', 'b', 'c')], + ) + >>> mi.levshape + (1, 1, 1) + """ + return tuple(len(x) for x in self.levels) + + # -------------------------------------------------------------------- + # Codes Methods + + @property + def codes(self) -> FrozenList: + return self._codes + + def _set_codes( + self, + codes, + *, + level=None, + copy: bool = False, + validate: bool = True, + verify_integrity: bool = False, + ) -> None: + if validate: + if level is None and len(codes) != self.nlevels: + raise ValueError("Length of codes must match number of levels") + if level is not None and len(codes) != len(level): + raise ValueError("Length of codes must match length of levels.") + + level_numbers: list[int] | range + if level is None: + new_codes = FrozenList( + _coerce_indexer_frozen(level_codes, lev, copy=copy).view() + for lev, level_codes in zip(self._levels, codes) + ) + level_numbers = range(len(new_codes)) + else: + level_numbers = [self._get_level_number(lev) for lev in level] + new_codes_list = list(self._codes) + for lev_num, level_codes in zip(level_numbers, codes): + lev = self.levels[lev_num] + new_codes_list[lev_num] = _coerce_indexer_frozen( + level_codes, lev, copy=copy + ) + new_codes = FrozenList(new_codes_list) + + if verify_integrity: + new_codes = self._verify_integrity( + codes=new_codes, levels_to_verify=level_numbers + ) + + self._codes = new_codes + + self._reset_cache() + + def set_codes( + self, codes, *, level=None, verify_integrity: bool = True + ) -> MultiIndex: + """ + Set new codes on MultiIndex. Defaults to returning new index. + + Parameters + ---------- + codes : sequence or list of sequence + New codes to apply. + level : int, level name, or sequence of int/level names (default None) + Level(s) to set (None for all levels). + verify_integrity : bool, default True + If True, checks that levels and codes are compatible. + + Returns + ------- + new index (of same type and class...etc) or None + The same type as the caller or None if ``inplace=True``. + + Examples + -------- + >>> idx = pd.MultiIndex.from_tuples( + ... [(1, "one"), (1, "two"), (2, "one"), (2, "two")], names=["foo", "bar"] + ... ) + >>> idx + MultiIndex([(1, 'one'), + (1, 'two'), + (2, 'one'), + (2, 'two')], + names=['foo', 'bar']) + + >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]]) + MultiIndex([(2, 'one'), + (1, 'one'), + (2, 'two'), + (1, 'two')], + names=['foo', 'bar']) + >>> idx.set_codes([1, 0, 1, 0], level=0) + MultiIndex([(2, 'one'), + (1, 'two'), + (2, 'one'), + (1, 'two')], + names=['foo', 'bar']) + >>> idx.set_codes([0, 0, 1, 1], level='bar') + MultiIndex([(1, 'one'), + (1, 'one'), + (2, 'two'), + (2, 'two')], + names=['foo', 'bar']) + >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]], level=[0, 1]) + MultiIndex([(2, 'one'), + (1, 'one'), + (2, 'two'), + (1, 'two')], + names=['foo', 'bar']) + """ + + level, codes = _require_listlike(level, codes, "Codes") + idx = self._view() + idx._reset_identity() + idx._set_codes(codes, level=level, verify_integrity=verify_integrity) + return idx + + # -------------------------------------------------------------------- + # Index Internals + + @cache_readonly + def _engine(self): + # Calculate the number of bits needed to represent labels in each + # level, as log2 of their sizes: + # NaN values are shifted to 1 and missing values in other while + # calculating the indexer are shifted to 0 + sizes = np.ceil( + np.log2( + [len(level) + libindex.multiindex_nulls_shift for level in self.levels] + ) + ) + + # Sum bit counts, starting from the _right_.... + lev_bits = np.cumsum(sizes[::-1])[::-1] + + # ... in order to obtain offsets such that sorting the combination of + # shifted codes (one for each level, resulting in a unique integer) is + # equivalent to sorting lexicographically the codes themselves. Notice + # that each level needs to be shifted by the number of bits needed to + # represent the _previous_ ones: + offsets = np.concatenate([lev_bits[1:], [0]]).astype("uint64") + + # Check the total number of bits needed for our representation: + if lev_bits[0] > 64: + # The levels would overflow a 64 bit uint - use Python integers: + return MultiIndexPyIntEngine(self.levels, self.codes, offsets) + return MultiIndexUIntEngine(self.levels, self.codes, offsets) + + # Return type "Callable[..., MultiIndex]" of "_constructor" incompatible with return + # type "Type[MultiIndex]" in supertype "Index" + @property + def _constructor(self) -> Callable[..., MultiIndex]: # type: ignore[override] + return type(self).from_tuples + + @doc(Index._shallow_copy) + def _shallow_copy(self, values: np.ndarray, name=lib.no_default) -> MultiIndex: + names = name if name is not lib.no_default else self.names + + return type(self).from_tuples(values, sortorder=None, names=names) + + def _view(self) -> MultiIndex: + result = type(self)( + levels=self.levels, + codes=self.codes, + sortorder=self.sortorder, + names=self.names, + verify_integrity=False, + ) + result._cache = self._cache.copy() + result._cache.pop("levels", None) # GH32669 + return result + + # -------------------------------------------------------------------- + + # error: Signature of "copy" incompatible with supertype "Index" + def copy( # type: ignore[override] + self, + names=None, + deep: bool = False, + name=None, + ) -> Self: + """ + Make a copy of this object. + + Names, dtype, levels and codes can be passed and will be set on new copy. + + Parameters + ---------- + names : sequence, optional + deep : bool, default False + name : Label + Kept for compatibility with 1-dimensional Index. Should not be used. + + Returns + ------- + MultiIndex + + Notes + ----- + In most cases, there should be no functional difference from using + ``deep``, but if ``deep`` is passed it will attempt to deepcopy. + This could be potentially expensive on large MultiIndex objects. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']]) + >>> mi + MultiIndex([('a', 'b', 'c')], + ) + >>> mi.copy() + MultiIndex([('a', 'b', 'c')], + ) + """ + names = self._validate_names(name=name, names=names, deep=deep) + keep_id = not deep + levels, codes = None, None + + if deep: + from copy import deepcopy + + levels = deepcopy(self.levels) + codes = deepcopy(self.codes) + + levels = levels if levels is not None else self.levels + codes = codes if codes is not None else self.codes + + new_index = type(self)( + levels=levels, + codes=codes, + sortorder=self.sortorder, + names=names, + verify_integrity=False, + ) + new_index._cache = self._cache.copy() + new_index._cache.pop("levels", None) # GH32669 + if keep_id: + new_index._id = self._id + return new_index + + def __array__(self, dtype=None, copy=None) -> np.ndarray: + """the array interface, return my values""" + return self.values + + def view(self, cls=None) -> Self: + """this is defined as a copy with the same identity""" + result = self.copy() + result._id = self._id + return result + + @doc(Index.__contains__) + def __contains__(self, key: Any) -> bool: + hash(key) + try: + self.get_loc(key) + return True + except (LookupError, TypeError, ValueError): + return False + + @cache_readonly + def dtype(self) -> np.dtype: + return np.dtype("O") + + def _is_memory_usage_qualified(self) -> bool: + """return a boolean if we need a qualified .info display""" + + def f(level) -> bool: + return "mixed" in level or "string" in level or "unicode" in level + + return any(f(level) for level in self._inferred_type_levels) + + # Cannot determine type of "memory_usage" + @doc(Index.memory_usage) # type: ignore[has-type] + def memory_usage(self, deep: bool = False) -> int: + # we are overwriting our base class to avoid + # computing .values here which could materialize + # a tuple representation unnecessarily + return self._nbytes(deep) + + @cache_readonly + def nbytes(self) -> int: + """return the number of bytes in the underlying data""" + return self._nbytes(False) + + def _nbytes(self, deep: bool = False) -> int: + """ + return the number of bytes in the underlying data + deeply introspect the level data if deep=True + + include the engine hashtable + + *this is in internal routine* + + """ + # for implementations with no useful getsizeof (PyPy) + objsize = 24 + + level_nbytes = sum(i.memory_usage(deep=deep) for i in self.levels) + label_nbytes = sum(i.nbytes for i in self.codes) + names_nbytes = sum(getsizeof(i, objsize) for i in self.names) + result = level_nbytes + label_nbytes + names_nbytes + + # include our engine hashtable + result += self._engine.sizeof(deep=deep) + return result + + # -------------------------------------------------------------------- + # Rendering Methods + + def _formatter_func(self, tup): + """ + Formats each item in tup according to its level's formatter function. + """ + formatter_funcs = [level._formatter_func for level in self.levels] + return tuple(func(val) for func, val in zip(formatter_funcs, tup)) + + def _get_values_for_csv( + self, *, na_rep: str = "nan", **kwargs + ) -> npt.NDArray[np.object_]: + new_levels = [] + new_codes = [] + + # go through the levels and format them + for level, level_codes in zip(self.levels, self.codes): + level_strs = level._get_values_for_csv(na_rep=na_rep, **kwargs) + # add nan values, if there are any + mask = level_codes == -1 + if mask.any(): + nan_index = len(level_strs) + # numpy 1.21 deprecated implicit string casting + level_strs = level_strs.astype(str) + level_strs = np.append(level_strs, na_rep) + assert not level_codes.flags.writeable # i.e. copy is needed + level_codes = level_codes.copy() # make writeable + level_codes[mask] = nan_index + new_levels.append(level_strs) + new_codes.append(level_codes) + + if len(new_levels) == 1: + # a single-level multi-index + return Index(new_levels[0].take(new_codes[0]))._get_values_for_csv() + else: + # reconstruct the multi-index + mi = MultiIndex( + levels=new_levels, + codes=new_codes, + names=self.names, + sortorder=self.sortorder, + verify_integrity=False, + ) + return mi._values + + def format( + self, + name: bool | None = None, + formatter: Callable | None = None, + na_rep: str | None = None, + names: bool = False, + space: int = 2, + sparsify=None, + adjoin: bool = True, + ) -> list: + warnings.warn( + # GH#55413 + f"{type(self).__name__}.format is deprecated and will be removed " + "in a future version. Convert using index.astype(str) or " + "index.map(formatter) instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + if name is not None: + names = name + + if len(self) == 0: + return [] + + stringified_levels = [] + for lev, level_codes in zip(self.levels, self.codes): + na = na_rep if na_rep is not None else _get_na_rep(lev.dtype) + + if len(lev) > 0: + formatted = lev.take(level_codes).format(formatter=formatter) + + # we have some NA + mask = level_codes == -1 + if mask.any(): + formatted = np.array(formatted, dtype=object) + formatted[mask] = na + formatted = formatted.tolist() + + else: + # weird all NA case + formatted = [ + pprint_thing(na if isna(x) else x, escape_chars=("\t", "\r", "\n")) + for x in algos.take_nd(lev._values, level_codes) + ] + stringified_levels.append(formatted) + + result_levels = [] + for lev, lev_name in zip(stringified_levels, self.names): + level = [] + + if names: + level.append( + pprint_thing(lev_name, escape_chars=("\t", "\r", "\n")) + if lev_name is not None + else "" + ) + + level.extend(np.array(lev, dtype=object)) + result_levels.append(level) + + if sparsify is None: + sparsify = get_option("display.multi_sparse") + + if sparsify: + sentinel: Literal[""] | bool | lib.NoDefault = "" + # GH3547 use value of sparsify as sentinel if it's "Falsey" + assert isinstance(sparsify, bool) or sparsify is lib.no_default + if sparsify in [False, lib.no_default]: + sentinel = sparsify + # little bit of a kludge job for #1217 + result_levels = sparsify_labels( + result_levels, start=int(names), sentinel=sentinel + ) + + if adjoin: + adj = get_adjustment() + return adj.adjoin(space, *result_levels).split("\n") + else: + return result_levels + + def _format_multi( + self, + *, + include_names: bool, + sparsify: bool | None | lib.NoDefault, + formatter: Callable | None = None, + ) -> list: + if len(self) == 0: + return [] + + stringified_levels = [] + for lev, level_codes in zip(self.levels, self.codes): + na = _get_na_rep(lev.dtype) + + if len(lev) > 0: + taken = formatted = lev.take(level_codes) + formatted = taken._format_flat(include_name=False, formatter=formatter) + + # we have some NA + mask = level_codes == -1 + if mask.any(): + formatted = np.array(formatted, dtype=object) + formatted[mask] = na + formatted = formatted.tolist() + + else: + # weird all NA case + formatted = [ + pprint_thing(na if isna(x) else x, escape_chars=("\t", "\r", "\n")) + for x in algos.take_nd(lev._values, level_codes) + ] + stringified_levels.append(formatted) + + result_levels = [] + for lev, lev_name in zip(stringified_levels, self.names): + level = [] + + if include_names: + level.append( + pprint_thing(lev_name, escape_chars=("\t", "\r", "\n")) + if lev_name is not None + else "" + ) + + level.extend(np.array(lev, dtype=object)) + result_levels.append(level) + + if sparsify is None: + sparsify = get_option("display.multi_sparse") + + if sparsify: + sentinel: Literal[""] | bool | lib.NoDefault = "" + # GH3547 use value of sparsify as sentinel if it's "Falsey" + assert isinstance(sparsify, bool) or sparsify is lib.no_default + if sparsify is lib.no_default: + sentinel = sparsify + # little bit of a kludge job for #1217 + result_levels = sparsify_labels( + result_levels, start=int(include_names), sentinel=sentinel + ) + + return result_levels + + # -------------------------------------------------------------------- + # Names Methods + + def _get_names(self) -> FrozenList: + return FrozenList(self._names) + + def _set_names(self, names, *, level=None, validate: bool = True): + """ + Set new names on index. Each name has to be a hashable type. + + Parameters + ---------- + values : str or sequence + name(s) to set + level : int, level name, or sequence of int/level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None + for all levels). Otherwise level must be None + validate : bool, default True + validate that the names match level lengths + + Raises + ------ + TypeError if each name is not hashable. + + Notes + ----- + sets names on levels. WARNING: mutates! + + Note that you generally want to set this *after* changing levels, so + that it only acts on copies + """ + # GH 15110 + # Don't allow a single string for names in a MultiIndex + if names is not None and not is_list_like(names): + raise ValueError("Names should be list-like for a MultiIndex") + names = list(names) + + if validate: + if level is not None and len(names) != len(level): + raise ValueError("Length of names must match length of level.") + if level is None and len(names) != self.nlevels: + raise ValueError( + "Length of names must match number of levels in MultiIndex." + ) + + if level is None: + level = range(self.nlevels) + else: + level = [self._get_level_number(lev) for lev in level] + + # set the name + for lev, name in zip(level, names): + if name is not None: + # GH 20527 + # All items in 'names' need to be hashable: + if not is_hashable(name): + raise TypeError( + f"{type(self).__name__}.name must be a hashable type" + ) + self._names[lev] = name + + # If .levels has been accessed, the names in our cache will be stale. + self._reset_cache() + + names = property( + fset=_set_names, + fget=_get_names, + doc=""" + Names of levels in MultiIndex. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays( + ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z']) + >>> mi + MultiIndex([(1, 3, 5), + (2, 4, 6)], + names=['x', 'y', 'z']) + >>> mi.names + FrozenList(['x', 'y', 'z']) + """, + ) + + # -------------------------------------------------------------------- + + @cache_readonly + def inferred_type(self) -> str: + return "mixed" + + def _get_level_number(self, level) -> int: + count = self.names.count(level) + if (count > 1) and not is_integer(level): + raise ValueError( + f"The name {level} occurs multiple times, use a level number" + ) + try: + level = self.names.index(level) + except ValueError as err: + if not is_integer(level): + raise KeyError(f"Level {level} not found") from err + if level < 0: + level += self.nlevels + if level < 0: + orig_level = level - self.nlevels + raise IndexError( + f"Too many levels: Index has only {self.nlevels} levels, " + f"{orig_level} is not a valid level number" + ) from err + # Note: levels are zero-based + elif level >= self.nlevels: + raise IndexError( + f"Too many levels: Index has only {self.nlevels} levels, " + f"not {level + 1}" + ) from err + return level + + @cache_readonly + def is_monotonic_increasing(self) -> bool: + """ + Return a boolean if the values are equal or increasing. + """ + if any(-1 in code for code in self.codes): + return False + + if all(level.is_monotonic_increasing for level in self.levels): + # If each level is sorted, we can operate on the codes directly. GH27495 + return libalgos.is_lexsorted( + [x.astype("int64", copy=False) for x in self.codes] + ) + + # reversed() because lexsort() wants the most significant key last. + values = [ + self._get_level_values(i)._values for i in reversed(range(len(self.levels))) + ] + try: + # error: Argument 1 to "lexsort" has incompatible type + # "List[Union[ExtensionArray, ndarray[Any, Any]]]"; + # expected "Union[_SupportsArray[dtype[Any]], + # _NestedSequence[_SupportsArray[dtype[Any]]], bool, + # int, float, complex, str, bytes, _NestedSequence[Union + # [bool, int, float, complex, str, bytes]]]" + sort_order = np.lexsort(values) # type: ignore[arg-type] + return Index(sort_order).is_monotonic_increasing + except TypeError: + # we have mixed types and np.lexsort is not happy + return Index(self._values).is_monotonic_increasing + + @cache_readonly + def is_monotonic_decreasing(self) -> bool: + """ + Return a boolean if the values are equal or decreasing. + """ + # monotonic decreasing if and only if reverse is monotonic increasing + return self[::-1].is_monotonic_increasing + + @cache_readonly + def _inferred_type_levels(self) -> list[str]: + """return a list of the inferred types, one for each level""" + return [i.inferred_type for i in self.levels] + + @doc(Index.duplicated) + def duplicated(self, keep: DropKeep = "first") -> npt.NDArray[np.bool_]: + shape = tuple(len(lev) for lev in self.levels) + ids = get_group_index(self.codes, shape, sort=False, xnull=False) + + return duplicated(ids, keep) + + # error: Cannot override final attribute "_duplicated" + # (previously declared in base class "IndexOpsMixin") + _duplicated = duplicated # type: ignore[misc] + + def fillna(self, value=None, downcast=None): + """ + fillna is not implemented for MultiIndex + """ + raise NotImplementedError("isna is not defined for MultiIndex") + + @doc(Index.dropna) + def dropna(self, how: AnyAll = "any") -> MultiIndex: + nans = [level_codes == -1 for level_codes in self.codes] + if how == "any": + indexer = np.any(nans, axis=0) + elif how == "all": + indexer = np.all(nans, axis=0) + else: + raise ValueError(f"invalid how option: {how}") + + new_codes = [level_codes[~indexer] for level_codes in self.codes] + return self.set_codes(codes=new_codes) + + def _get_level_values(self, level: int, unique: bool = False) -> Index: + """ + Return vector of label values for requested level, + equal to the length of the index + + **this is an internal method** + + Parameters + ---------- + level : int + unique : bool, default False + if True, drop duplicated values + + Returns + ------- + Index + """ + lev = self.levels[level] + level_codes = self.codes[level] + name = self._names[level] + if unique: + level_codes = algos.unique(level_codes) + filled = algos.take_nd(lev._values, level_codes, fill_value=lev._na_value) + return lev._shallow_copy(filled, name=name) + + # error: Signature of "get_level_values" incompatible with supertype "Index" + def get_level_values(self, level) -> Index: # type: ignore[override] + """ + Return vector of label values for requested level. + + Length of returned vector is equal to the length of the index. + + Parameters + ---------- + level : int or str + ``level`` is either the integer position of the level in the + MultiIndex, or the name of the level. + + Returns + ------- + Index + Values is a level of this MultiIndex converted to + a single :class:`Index` (or subclass thereof). + + Notes + ----- + If the level contains missing values, the result may be casted to + ``float`` with missing values specified as ``NaN``. This is because + the level is converted to a regular ``Index``. + + Examples + -------- + Create a MultiIndex: + + >>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def'))) + >>> mi.names = ['level_1', 'level_2'] + + Get level values by supplying level as either integer or name: + + >>> mi.get_level_values(0) + Index(['a', 'b', 'c'], dtype='object', name='level_1') + >>> mi.get_level_values('level_2') + Index(['d', 'e', 'f'], dtype='object', name='level_2') + + If a level contains missing values, the return type of the level + may be cast to ``float``. + + >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).dtypes + level_0 int64 + level_1 int64 + dtype: object + >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).get_level_values(0) + Index([1.0, nan, 2.0], dtype='float64') + """ + level = self._get_level_number(level) + values = self._get_level_values(level) + return values + + @doc(Index.unique) + def unique(self, level=None): + if level is None: + return self.drop_duplicates() + else: + level = self._get_level_number(level) + return self._get_level_values(level=level, unique=True) + + def to_frame( + self, + index: bool = True, + name=lib.no_default, + allow_duplicates: bool = False, + ) -> DataFrame: + """ + Create a DataFrame with the levels of the MultiIndex as columns. + + Column ordering is determined by the DataFrame constructor with data as + a dict. + + Parameters + ---------- + index : bool, default True + Set the index of the returned DataFrame as the original MultiIndex. + + name : list / sequence of str, optional + The passed names should substitute index level names. + + allow_duplicates : bool, optional default False + Allow duplicate column labels to be created. + + .. versionadded:: 1.5.0 + + Returns + ------- + DataFrame + + See Also + -------- + DataFrame : Two-dimensional, size-mutable, potentially heterogeneous + tabular data. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']]) + >>> mi + MultiIndex([('a', 'c'), + ('b', 'd')], + ) + + >>> df = mi.to_frame() + >>> df + 0 1 + a c a c + b d b d + + >>> df = mi.to_frame(index=False) + >>> df + 0 1 + 0 a c + 1 b d + + >>> df = mi.to_frame(name=['x', 'y']) + >>> df + x y + a c a c + b d b d + """ + from pandas import DataFrame + + if name is not lib.no_default: + if not is_list_like(name): + raise TypeError("'name' must be a list / sequence of column names.") + + if len(name) != len(self.levels): + raise ValueError( + "'name' should have same length as number of levels on index." + ) + idx_names = name + else: + idx_names = self._get_level_names() + + if not allow_duplicates and len(set(idx_names)) != len(idx_names): + raise ValueError( + "Cannot create duplicate column labels if allow_duplicates is False" + ) + + # Guarantee resulting column order - PY36+ dict maintains insertion order + result = DataFrame( + {level: self._get_level_values(level) for level in range(len(self.levels))}, + copy=False, + ) + result.columns = idx_names + + if index: + result.index = self + return result + + # error: Return type "Index" of "to_flat_index" incompatible with return type + # "MultiIndex" in supertype "Index" + def to_flat_index(self) -> Index: # type: ignore[override] + """ + Convert a MultiIndex to an Index of Tuples containing the level values. + + Returns + ------- + pd.Index + Index with the MultiIndex data represented in Tuples. + + See Also + -------- + MultiIndex.from_tuples : Convert flat index back to MultiIndex. + + Notes + ----- + This method will simply return the caller if called by anything other + than a MultiIndex. + + Examples + -------- + >>> index = pd.MultiIndex.from_product( + ... [['foo', 'bar'], ['baz', 'qux']], + ... names=['a', 'b']) + >>> index.to_flat_index() + Index([('foo', 'baz'), ('foo', 'qux'), + ('bar', 'baz'), ('bar', 'qux')], + dtype='object') + """ + return Index(self._values, tupleize_cols=False) + + def _is_lexsorted(self) -> bool: + """ + Return True if the codes are lexicographically sorted. + + Returns + ------- + bool + + Examples + -------- + In the below examples, the first level of the MultiIndex is sorted because + a>> pd.MultiIndex.from_arrays([['a', 'b', 'c'], + ... ['d', 'e', 'f']])._is_lexsorted() + True + >>> pd.MultiIndex.from_arrays([['a', 'b', 'c'], + ... ['d', 'f', 'e']])._is_lexsorted() + True + + In case there is a tie, the lexicographical sorting looks + at the next level of the MultiIndex. + + >>> pd.MultiIndex.from_arrays([[0, 1, 1], ['a', 'b', 'c']])._is_lexsorted() + True + >>> pd.MultiIndex.from_arrays([[0, 1, 1], ['a', 'c', 'b']])._is_lexsorted() + False + >>> pd.MultiIndex.from_arrays([['a', 'a', 'b', 'b'], + ... ['aa', 'bb', 'aa', 'bb']])._is_lexsorted() + True + >>> pd.MultiIndex.from_arrays([['a', 'a', 'b', 'b'], + ... ['bb', 'aa', 'aa', 'bb']])._is_lexsorted() + False + """ + return self._lexsort_depth == self.nlevels + + @cache_readonly + def _lexsort_depth(self) -> int: + """ + Compute and return the lexsort_depth, the number of levels of the + MultiIndex that are sorted lexically + + Returns + ------- + int + """ + if self.sortorder is not None: + return self.sortorder + return _lexsort_depth(self.codes, self.nlevels) + + def _sort_levels_monotonic(self, raise_if_incomparable: bool = False) -> MultiIndex: + """ + This is an *internal* function. + + Create a new MultiIndex from the current to monotonically sorted + items IN the levels. This does not actually make the entire MultiIndex + monotonic, JUST the levels. + + The resulting MultiIndex will have the same outward + appearance, meaning the same .values and ordering. It will also + be .equals() to the original. + + Returns + ------- + MultiIndex + + Examples + -------- + >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + >>> mi + MultiIndex([('a', 'bb'), + ('a', 'aa'), + ('b', 'bb'), + ('b', 'aa')], + ) + + >>> mi.sort_values() + MultiIndex([('a', 'aa'), + ('a', 'bb'), + ('b', 'aa'), + ('b', 'bb')], + ) + """ + if self._is_lexsorted() and self.is_monotonic_increasing: + return self + + new_levels = [] + new_codes = [] + + for lev, level_codes in zip(self.levels, self.codes): + if not lev.is_monotonic_increasing: + try: + # indexer to reorder the levels + indexer = lev.argsort() + except TypeError: + if raise_if_incomparable: + raise + else: + lev = lev.take(indexer) + + # indexer to reorder the level codes + indexer = ensure_platform_int(indexer) + ri = lib.get_reverse_indexer(indexer, len(indexer)) + level_codes = algos.take_nd(ri, level_codes, fill_value=-1) + + new_levels.append(lev) + new_codes.append(level_codes) + + return MultiIndex( + new_levels, + new_codes, + names=self.names, + sortorder=self.sortorder, + verify_integrity=False, + ) + + def remove_unused_levels(self) -> MultiIndex: + """ + Create new MultiIndex from current that removes unused levels. + + Unused level(s) means levels that are not expressed in the + labels. The resulting MultiIndex will have the same outward + appearance, meaning the same .values and ordering. It will + also be .equals() to the original. + + Returns + ------- + MultiIndex + + Examples + -------- + >>> mi = pd.MultiIndex.from_product([range(2), list('ab')]) + >>> mi + MultiIndex([(0, 'a'), + (0, 'b'), + (1, 'a'), + (1, 'b')], + ) + + >>> mi[2:] + MultiIndex([(1, 'a'), + (1, 'b')], + ) + + The 0 from the first level is not represented + and can be removed + + >>> mi2 = mi[2:].remove_unused_levels() + >>> mi2.levels + FrozenList([[1], ['a', 'b']]) + """ + new_levels = [] + new_codes = [] + + changed = False + for lev, level_codes in zip(self.levels, self.codes): + # Since few levels are typically unused, bincount() is more + # efficient than unique() - however it only accepts positive values + # (and drops order): + uniques = np.where(np.bincount(level_codes + 1) > 0)[0] - 1 + has_na = int(len(uniques) and (uniques[0] == -1)) + + if len(uniques) != len(lev) + has_na: + if lev.isna().any() and len(uniques) == len(lev): + break + # We have unused levels + changed = True + + # Recalculate uniques, now preserving order. + # Can easily be cythonized by exploiting the already existing + # "uniques" and stop parsing "level_codes" when all items + # are found: + uniques = algos.unique(level_codes) + if has_na: + na_idx = np.where(uniques == -1)[0] + # Just ensure that -1 is in first position: + uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]] + + # codes get mapped from uniques to 0:len(uniques) + # -1 (if present) is mapped to last position + code_mapping = np.zeros(len(lev) + has_na) + # ... and reassigned value -1: + code_mapping[uniques] = np.arange(len(uniques)) - has_na + + level_codes = code_mapping[level_codes] + + # new levels are simple + lev = lev.take(uniques[has_na:]) + + new_levels.append(lev) + new_codes.append(level_codes) + + result = self.view() + + if changed: + result._reset_identity() + result._set_levels(new_levels, validate=False) + result._set_codes(new_codes, validate=False) + + return result + + # -------------------------------------------------------------------- + # Pickling Methods + + def __reduce__(self): + """Necessary for making this object picklable""" + d = { + "levels": list(self.levels), + "codes": list(self.codes), + "sortorder": self.sortorder, + "names": list(self.names), + } + return ibase._new_Index, (type(self), d), None + + # -------------------------------------------------------------------- + + def __getitem__(self, key): + if is_scalar(key): + key = com.cast_scalar_indexer(key) + + retval = [] + for lev, level_codes in zip(self.levels, self.codes): + if level_codes[key] == -1: + retval.append(np.nan) + else: + retval.append(lev[level_codes[key]]) + + return tuple(retval) + else: + # in general cannot be sure whether the result will be sorted + sortorder = None + if com.is_bool_indexer(key): + key = np.asarray(key, dtype=bool) + sortorder = self.sortorder + elif isinstance(key, slice): + if key.step is None or key.step > 0: + sortorder = self.sortorder + elif isinstance(key, Index): + key = np.asarray(key) + + new_codes = [level_codes[key] for level_codes in self.codes] + + return MultiIndex( + levels=self.levels, + codes=new_codes, + names=self.names, + sortorder=sortorder, + verify_integrity=False, + ) + + def _getitem_slice(self: MultiIndex, slobj: slice) -> MultiIndex: + """ + Fastpath for __getitem__ when we know we have a slice. + """ + sortorder = None + if slobj.step is None or slobj.step > 0: + sortorder = self.sortorder + + new_codes = [level_codes[slobj] for level_codes in self.codes] + + return type(self)( + levels=self.levels, + codes=new_codes, + names=self._names, + sortorder=sortorder, + verify_integrity=False, + ) + + @Appender(_index_shared_docs["take"] % _index_doc_kwargs) + def take( + self: MultiIndex, + indices, + axis: Axis = 0, + allow_fill: bool = True, + fill_value=None, + **kwargs, + ) -> MultiIndex: + nv.validate_take((), kwargs) + indices = ensure_platform_int(indices) + + # only fill if we are passing a non-None fill_value + allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices) + + na_value = -1 + + taken = [lab.take(indices) for lab in self.codes] + if allow_fill: + mask = indices == -1 + if mask.any(): + masked = [] + for new_label in taken: + label_values = new_label + label_values[mask] = na_value + masked.append(np.asarray(label_values)) + taken = masked + + return MultiIndex( + levels=self.levels, codes=taken, names=self.names, verify_integrity=False + ) + + def append(self, other): + """ + Append a collection of Index options together. + + Parameters + ---------- + other : Index or list/tuple of indices + + Returns + ------- + Index + The combined index. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a'], ['b']]) + >>> mi + MultiIndex([('a', 'b')], + ) + >>> mi.append(mi) + MultiIndex([('a', 'b'), ('a', 'b')], + ) + """ + if not isinstance(other, (list, tuple)): + other = [other] + + if all( + (isinstance(o, MultiIndex) and o.nlevels >= self.nlevels) for o in other + ): + codes = [] + levels = [] + names = [] + for i in range(self.nlevels): + level_values = self.levels[i] + for mi in other: + level_values = level_values.union(mi.levels[i]) + level_codes = [ + recode_for_categories( + mi.codes[i], mi.levels[i], level_values, copy=False + ) + for mi in ([self, *other]) + ] + level_name = self.names[i] + if any(mi.names[i] != level_name for mi in other): + level_name = None + codes.append(np.concatenate(level_codes)) + levels.append(level_values) + names.append(level_name) + return MultiIndex( + codes=codes, levels=levels, names=names, verify_integrity=False + ) + + to_concat = (self._values,) + tuple(k._values for k in other) + new_tuples = np.concatenate(to_concat) + + # if all(isinstance(x, MultiIndex) for x in other): + try: + # We only get here if other contains at least one index with tuples, + # setting names to None automatically + return MultiIndex.from_tuples(new_tuples) + except (TypeError, IndexError): + return Index(new_tuples) + + def argsort( + self, *args, na_position: str = "last", **kwargs + ) -> npt.NDArray[np.intp]: + target = self._sort_levels_monotonic(raise_if_incomparable=True) + keys = [lev.codes for lev in target._get_codes_for_sorting()] + return lexsort_indexer(keys, na_position=na_position, codes_given=True) + + @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) + def repeat(self, repeats: int, axis=None) -> MultiIndex: + nv.validate_repeat((), {"axis": axis}) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "int") + repeats = ensure_platform_int(repeats) # type: ignore[assignment] + return MultiIndex( + levels=self.levels, + codes=[ + level_codes.view(np.ndarray).astype(np.intp, copy=False).repeat(repeats) + for level_codes in self.codes + ], + names=self.names, + sortorder=self.sortorder, + verify_integrity=False, + ) + + # error: Signature of "drop" incompatible with supertype "Index" + def drop( # type: ignore[override] + self, + codes, + level: Index | np.ndarray | Iterable[Hashable] | None = None, + errors: IgnoreRaise = "raise", + ) -> MultiIndex: + """ + Make a new :class:`pandas.MultiIndex` with the passed list of codes deleted. + + Parameters + ---------- + codes : array-like + Must be a list of tuples when ``level`` is not specified. + level : int or level name, default None + errors : str, default 'raise' + + Returns + ------- + MultiIndex + + Examples + -------- + >>> idx = pd.MultiIndex.from_product([(0, 1, 2), ('green', 'purple')], + ... names=["number", "color"]) + >>> idx + MultiIndex([(0, 'green'), + (0, 'purple'), + (1, 'green'), + (1, 'purple'), + (2, 'green'), + (2, 'purple')], + names=['number', 'color']) + >>> idx.drop([(1, 'green'), (2, 'purple')]) + MultiIndex([(0, 'green'), + (0, 'purple'), + (1, 'purple'), + (2, 'green')], + names=['number', 'color']) + + We can also drop from a specific level. + + >>> idx.drop('green', level='color') + MultiIndex([(0, 'purple'), + (1, 'purple'), + (2, 'purple')], + names=['number', 'color']) + + >>> idx.drop([1, 2], level=0) + MultiIndex([(0, 'green'), + (0, 'purple')], + names=['number', 'color']) + """ + if level is not None: + return self._drop_from_level(codes, level, errors) + + if not isinstance(codes, (np.ndarray, Index)): + try: + codes = com.index_labels_to_array(codes, dtype=np.dtype("object")) + except ValueError: + pass + + inds = [] + for level_codes in codes: + try: + loc = self.get_loc(level_codes) + # get_loc returns either an integer, a slice, or a boolean + # mask + if isinstance(loc, int): + inds.append(loc) + elif isinstance(loc, slice): + step = loc.step if loc.step is not None else 1 + inds.extend(range(loc.start, loc.stop, step)) + elif com.is_bool_indexer(loc): + if self._lexsort_depth == 0: + warnings.warn( + "dropping on a non-lexsorted multi-index " + "without a level parameter may impact performance.", + PerformanceWarning, + stacklevel=find_stack_level(), + ) + loc = loc.nonzero()[0] + inds.extend(loc) + else: + msg = f"unsupported indexer of type {type(loc)}" + raise AssertionError(msg) + except KeyError: + if errors != "ignore": + raise + + return self.delete(inds) + + def _drop_from_level( + self, codes, level, errors: IgnoreRaise = "raise" + ) -> MultiIndex: + codes = com.index_labels_to_array(codes) + i = self._get_level_number(level) + index = self.levels[i] + values = index.get_indexer(codes) + # If nan should be dropped it will equal -1 here. We have to check which values + # are not nan and equal -1, this means they are missing in the index + nan_codes = isna(codes) + values[(np.equal(nan_codes, False)) & (values == -1)] = -2 + if index.shape[0] == self.shape[0]: + values[np.equal(nan_codes, True)] = -2 + + not_found = codes[values == -2] + if len(not_found) != 0 and errors != "ignore": + raise KeyError(f"labels {not_found} not found in level") + mask = ~algos.isin(self.codes[i], values) + + return self[mask] + + def swaplevel(self, i=-2, j=-1) -> MultiIndex: + """ + Swap level i with level j. + + Calling this method does not change the ordering of the values. + + Parameters + ---------- + i : int, str, default -2 + First level of index to be swapped. Can pass level name as string. + Type of parameters can be mixed. + j : int, str, default -1 + Second level of index to be swapped. Can pass level name as string. + Type of parameters can be mixed. + + Returns + ------- + MultiIndex + A new MultiIndex. + + See Also + -------- + Series.swaplevel : Swap levels i and j in a MultiIndex. + DataFrame.swaplevel : Swap levels i and j in a MultiIndex on a + particular axis. + + Examples + -------- + >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + >>> mi + MultiIndex([('a', 'bb'), + ('a', 'aa'), + ('b', 'bb'), + ('b', 'aa')], + ) + >>> mi.swaplevel(0, 1) + MultiIndex([('bb', 'a'), + ('aa', 'a'), + ('bb', 'b'), + ('aa', 'b')], + ) + """ + new_levels = list(self.levels) + new_codes = list(self.codes) + new_names = list(self.names) + + i = self._get_level_number(i) + j = self._get_level_number(j) + + new_levels[i], new_levels[j] = new_levels[j], new_levels[i] + new_codes[i], new_codes[j] = new_codes[j], new_codes[i] + new_names[i], new_names[j] = new_names[j], new_names[i] + + return MultiIndex( + levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False + ) + + def reorder_levels(self, order) -> MultiIndex: + """ + Rearrange levels using input order. May not drop or duplicate levels. + + Parameters + ---------- + order : list of int or list of str + List representing new level order. Reference level by number + (position) or by key (label). + + Returns + ------- + MultiIndex + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=['x', 'y']) + >>> mi + MultiIndex([(1, 3), + (2, 4)], + names=['x', 'y']) + + >>> mi.reorder_levels(order=[1, 0]) + MultiIndex([(3, 1), + (4, 2)], + names=['y', 'x']) + + >>> mi.reorder_levels(order=['y', 'x']) + MultiIndex([(3, 1), + (4, 2)], + names=['y', 'x']) + """ + order = [self._get_level_number(i) for i in order] + result = self._reorder_ilevels(order) + return result + + def _reorder_ilevels(self, order) -> MultiIndex: + if len(order) != self.nlevels: + raise AssertionError( + f"Length of order must be same as number of levels ({self.nlevels}), " + f"got {len(order)}" + ) + new_levels = [self.levels[i] for i in order] + new_codes = [self.codes[i] for i in order] + new_names = [self.names[i] for i in order] + + return MultiIndex( + levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False + ) + + def _recode_for_new_levels( + self, new_levels, copy: bool = True + ) -> Generator[np.ndarray, None, None]: + if len(new_levels) > self.nlevels: + raise AssertionError( + f"Length of new_levels ({len(new_levels)}) " + f"must be <= self.nlevels ({self.nlevels})" + ) + for i in range(len(new_levels)): + yield recode_for_categories( + self.codes[i], self.levels[i], new_levels[i], copy=copy + ) + + def _get_codes_for_sorting(self) -> list[Categorical]: + """ + we are categorizing our codes by using the + available categories (all, not just observed) + excluding any missing ones (-1); this is in preparation + for sorting, where we need to disambiguate that -1 is not + a valid valid + """ + + def cats(level_codes): + return np.arange( + np.array(level_codes).max() + 1 if len(level_codes) else 0, + dtype=level_codes.dtype, + ) + + return [ + Categorical.from_codes(level_codes, cats(level_codes), True, validate=False) + for level_codes in self.codes + ] + + def sortlevel( + self, + level: IndexLabel = 0, + ascending: bool | list[bool] = True, + sort_remaining: bool = True, + na_position: str = "first", + ) -> tuple[MultiIndex, npt.NDArray[np.intp]]: + """ + Sort MultiIndex at the requested level. + + The result will respect the original ordering of the associated + factor at that level. + + Parameters + ---------- + level : list-like, int or str, default 0 + If a string is given, must be a name of the level. + If list-like must be names or ints of levels. + ascending : bool, default True + False to sort in descending order. + Can also be a list to specify a directed ordering. + sort_remaining : sort by the remaining levels after level + na_position : {'first' or 'last'}, default 'first' + Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at + the end. + + .. versionadded:: 2.1.0 + + Returns + ------- + sorted_index : pd.MultiIndex + Resulting index. + indexer : np.ndarray[np.intp] + Indices of output values in original index. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([[0, 0], [2, 1]]) + >>> mi + MultiIndex([(0, 2), + (0, 1)], + ) + + >>> mi.sortlevel() + (MultiIndex([(0, 1), + (0, 2)], + ), array([1, 0])) + + >>> mi.sortlevel(sort_remaining=False) + (MultiIndex([(0, 2), + (0, 1)], + ), array([0, 1])) + + >>> mi.sortlevel(1) + (MultiIndex([(0, 1), + (0, 2)], + ), array([1, 0])) + + >>> mi.sortlevel(1, ascending=False) + (MultiIndex([(0, 2), + (0, 1)], + ), array([0, 1])) + """ + if not is_list_like(level): + level = [level] + # error: Item "Hashable" of "Union[Hashable, Sequence[Hashable]]" has + # no attribute "__iter__" (not iterable) + level = [ + self._get_level_number(lev) for lev in level # type: ignore[union-attr] + ] + sortorder = None + + codes = [self.codes[lev] for lev in level] + # we have a directed ordering via ascending + if isinstance(ascending, list): + if not len(level) == len(ascending): + raise ValueError("level must have same length as ascending") + elif sort_remaining: + codes.extend( + [self.codes[lev] for lev in range(len(self.levels)) if lev not in level] + ) + else: + sortorder = level[0] + + indexer = lexsort_indexer( + codes, orders=ascending, na_position=na_position, codes_given=True + ) + + indexer = ensure_platform_int(indexer) + new_codes = [level_codes.take(indexer) for level_codes in self.codes] + + new_index = MultiIndex( + codes=new_codes, + levels=self.levels, + names=self.names, + sortorder=sortorder, + verify_integrity=False, + ) + + return new_index, indexer + + def _wrap_reindex_result(self, target, indexer, preserve_names: bool): + if not isinstance(target, MultiIndex): + if indexer is None: + target = self + elif (indexer >= 0).all(): + target = self.take(indexer) + else: + try: + target = MultiIndex.from_tuples(target) + except TypeError: + # not all tuples, see test_constructor_dict_multiindex_reindex_flat + return target + + target = self._maybe_preserve_names(target, preserve_names) + return target + + def _maybe_preserve_names(self, target: Index, preserve_names: bool) -> Index: + if ( + preserve_names + and target.nlevels == self.nlevels + and target.names != self.names + ): + target = target.copy(deep=False) + target.names = self.names + return target + + # -------------------------------------------------------------------- + # Indexing Methods + + def _check_indexing_error(self, key) -> None: + if not is_hashable(key) or is_iterator(key): + # We allow tuples if they are hashable, whereas other Index + # subclasses require scalar. + # We have to explicitly exclude generators, as these are hashable. + raise InvalidIndexError(key) + + @cache_readonly + def _should_fallback_to_positional(self) -> bool: + """ + Should integer key(s) be treated as positional? + """ + # GH#33355 + return self.levels[0]._should_fallback_to_positional + + def _get_indexer_strict( + self, key, axis_name: str + ) -> tuple[Index, npt.NDArray[np.intp]]: + keyarr = key + if not isinstance(keyarr, Index): + keyarr = com.asarray_tuplesafe(keyarr) + + if len(keyarr) and not isinstance(keyarr[0], tuple): + indexer = self._get_indexer_level_0(keyarr) + + self._raise_if_missing(key, indexer, axis_name) + return self[indexer], indexer + + return super()._get_indexer_strict(key, axis_name) + + def _raise_if_missing(self, key, indexer, axis_name: str) -> None: + keyarr = key + if not isinstance(key, Index): + keyarr = com.asarray_tuplesafe(key) + + if len(keyarr) and not isinstance(keyarr[0], tuple): + # i.e. same condition for special case in MultiIndex._get_indexer_strict + + mask = indexer == -1 + if mask.any(): + check = self.levels[0].get_indexer(keyarr) + cmask = check == -1 + if cmask.any(): + raise KeyError(f"{keyarr[cmask]} not in index") + # We get here when levels still contain values which are not + # actually in Index anymore + raise KeyError(f"{keyarr} not in index") + else: + return super()._raise_if_missing(key, indexer, axis_name) + + def _get_indexer_level_0(self, target) -> npt.NDArray[np.intp]: + """ + Optimized equivalent to `self.get_level_values(0).get_indexer_for(target)`. + """ + lev = self.levels[0] + codes = self._codes[0] + cat = Categorical.from_codes(codes=codes, categories=lev, validate=False) + ci = Index(cat) + return ci.get_indexer_for(target) + + def get_slice_bound( + self, + label: Hashable | Sequence[Hashable], + side: Literal["left", "right"], + ) -> int: + """ + For an ordered MultiIndex, compute slice bound + that corresponds to given label. + + Returns leftmost (one-past-the-rightmost if `side=='right') position + of given label. + + Parameters + ---------- + label : object or tuple of objects + side : {'left', 'right'} + + Returns + ------- + int + Index of label. + + Notes + ----- + This method only works if level 0 index of the MultiIndex is lexsorted. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abbc'), list('gefd')]) + + Get the locations from the leftmost 'b' in the first level + until the end of the multiindex: + + >>> mi.get_slice_bound('b', side="left") + 1 + + Like above, but if you get the locations from the rightmost + 'b' in the first level and 'f' in the second level: + + >>> mi.get_slice_bound(('b','f'), side="right") + 3 + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ + if not isinstance(label, tuple): + label = (label,) + return self._partial_tup_index(label, side=side) + + # pylint: disable-next=useless-parent-delegation + def slice_locs(self, start=None, end=None, step=None) -> tuple[int, int]: + """ + For an ordered MultiIndex, compute the slice locations for input + labels. + + The input labels can be tuples representing partial levels, e.g. for a + MultiIndex with 3 levels, you can pass a single value (corresponding to + the first level), or a 1-, 2-, or 3-tuple. + + Parameters + ---------- + start : label or tuple, default None + If None, defaults to the beginning + end : label or tuple + If None, defaults to the end + step : int or None + Slice step + + Returns + ------- + (start, end) : (int, int) + + Notes + ----- + This method only works if the MultiIndex is properly lexsorted. So, + if only the first 2 levels of a 3-level MultiIndex are lexsorted, + you can only pass two levels to ``.slice_locs``. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abbd'), list('deff')], + ... names=['A', 'B']) + + Get the slice locations from the beginning of 'b' in the first level + until the end of the multiindex: + + >>> mi.slice_locs(start='b') + (1, 4) + + Like above, but stop at the end of 'b' in the first level and 'f' in + the second level: + + >>> mi.slice_locs(start='b', end=('b', 'f')) + (1, 3) + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ + # This function adds nothing to its parent implementation (the magic + # happens in get_slice_bound method), but it adds meaningful doc. + return super().slice_locs(start, end, step) + + def _partial_tup_index(self, tup: tuple, side: Literal["left", "right"] = "left"): + if len(tup) > self._lexsort_depth: + raise UnsortedIndexError( + f"Key length ({len(tup)}) was greater than MultiIndex lexsort depth " + f"({self._lexsort_depth})" + ) + + n = len(tup) + start, end = 0, len(self) + zipped = zip(tup, self.levels, self.codes) + for k, (lab, lev, level_codes) in enumerate(zipped): + section = level_codes[start:end] + + loc: npt.NDArray[np.intp] | np.intp | int + if lab not in lev and not isna(lab): + # short circuit + try: + loc = algos.searchsorted(lev, lab, side=side) + except TypeError as err: + # non-comparable e.g. test_slice_locs_with_type_mismatch + raise TypeError(f"Level type mismatch: {lab}") from err + if not is_integer(loc): + # non-comparable level, e.g. test_groupby_example + raise TypeError(f"Level type mismatch: {lab}") + if side == "right" and loc >= 0: + loc -= 1 + return start + algos.searchsorted(section, loc, side=side) + + idx = self._get_loc_single_level_index(lev, lab) + if isinstance(idx, slice) and k < n - 1: + # Get start and end value from slice, necessary when a non-integer + # interval is given as input GH#37707 + start = idx.start + end = idx.stop + elif k < n - 1: + # error: Incompatible types in assignment (expression has type + # "Union[ndarray[Any, dtype[signedinteger[Any]]] + end = start + algos.searchsorted( # type: ignore[assignment] + section, idx, side="right" + ) + # error: Incompatible types in assignment (expression has type + # "Union[ndarray[Any, dtype[signedinteger[Any]]] + start = start + algos.searchsorted( # type: ignore[assignment] + section, idx, side="left" + ) + elif isinstance(idx, slice): + idx = idx.start + return start + algos.searchsorted(section, idx, side=side) + else: + return start + algos.searchsorted(section, idx, side=side) + + def _get_loc_single_level_index(self, level_index: Index, key: Hashable) -> int: + """ + If key is NA value, location of index unify as -1. + + Parameters + ---------- + level_index: Index + key : label + + Returns + ------- + loc : int + If key is NA value, loc is -1 + Else, location of key in index. + + See Also + -------- + Index.get_loc : The get_loc method for (single-level) index. + """ + if is_scalar(key) and isna(key): + # TODO: need is_valid_na_for_dtype(key, level_index.dtype) + return -1 + else: + return level_index.get_loc(key) + + def get_loc(self, key): + """ + Get location for a label or a tuple of labels. + + The location is returned as an integer/slice or boolean + mask. + + Parameters + ---------- + key : label or tuple of labels (one for each level) + + Returns + ------- + int, slice object or boolean mask + If the key is past the lexsort depth, the return may be a + boolean mask array, otherwise it is always a slice or int. + + See Also + -------- + Index.get_loc : The get_loc method for (single-level) index. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + + Notes + ----- + The key cannot be a slice, list of same-level labels, a boolean mask, + or a sequence of such. If you want to use those, use + :meth:`MultiIndex.get_locs` instead. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) + + >>> mi.get_loc('b') + slice(1, 3, None) + + >>> mi.get_loc(('b', 'e')) + 1 + """ + self._check_indexing_error(key) + + def _maybe_to_slice(loc): + """convert integer indexer to boolean mask or slice if possible""" + if not isinstance(loc, np.ndarray) or loc.dtype != np.intp: + return loc + + loc = lib.maybe_indices_to_slice(loc, len(self)) + if isinstance(loc, slice): + return loc + + mask = np.empty(len(self), dtype="bool") + mask.fill(False) + mask[loc] = True + return mask + + if not isinstance(key, tuple): + loc = self._get_level_indexer(key, level=0) + return _maybe_to_slice(loc) + + keylen = len(key) + if self.nlevels < keylen: + raise KeyError( + f"Key length ({keylen}) exceeds index depth ({self.nlevels})" + ) + + if keylen == self.nlevels and self.is_unique: + # TODO: what if we have an IntervalIndex level? + # i.e. do we need _index_as_unique on that level? + try: + return self._engine.get_loc(key) + except KeyError as err: + raise KeyError(key) from err + except TypeError: + # e.g. test_partial_slicing_with_multiindex partial string slicing + loc, _ = self.get_loc_level(key, list(range(self.nlevels))) + return loc + + # -- partial selection or non-unique index + # break the key into 2 parts based on the lexsort_depth of the index; + # the first part returns a continuous slice of the index; the 2nd part + # needs linear search within the slice + i = self._lexsort_depth + lead_key, follow_key = key[:i], key[i:] + + if not lead_key: + start = 0 + stop = len(self) + else: + try: + start, stop = self.slice_locs(lead_key, lead_key) + except TypeError as err: + # e.g. test_groupby_example key = ((0, 0, 1, 2), "new_col") + # when self has 5 integer levels + raise KeyError(key) from err + + if start == stop: + raise KeyError(key) + + if not follow_key: + return slice(start, stop) + + warnings.warn( + "indexing past lexsort depth may impact performance.", + PerformanceWarning, + stacklevel=find_stack_level(), + ) + + loc = np.arange(start, stop, dtype=np.intp) + + for i, k in enumerate(follow_key, len(lead_key)): + mask = self.codes[i][loc] == self._get_loc_single_level_index( + self.levels[i], k + ) + if not mask.all(): + loc = loc[mask] + if not len(loc): + raise KeyError(key) + + return _maybe_to_slice(loc) if len(loc) != stop - start else slice(start, stop) + + def get_loc_level(self, key, level: IndexLabel = 0, drop_level: bool = True): + """ + Get location and sliced index for requested label(s)/level(s). + + Parameters + ---------- + key : label or sequence of labels + level : int/level name or list thereof, optional + drop_level : bool, default True + If ``False``, the resulting index will not drop any level. + + Returns + ------- + tuple + A 2-tuple where the elements : + + Element 0: int, slice object or boolean array. + + Element 1: The resulting sliced multiindex/index. If the key + contains all levels, this will be ``None``. + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')], + ... names=['A', 'B']) + + >>> mi.get_loc_level('b') + (slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B')) + + >>> mi.get_loc_level('e', level='B') + (array([False, True, False]), Index(['b'], dtype='object', name='A')) + + >>> mi.get_loc_level(['b', 'e']) + (1, None) + """ + if not isinstance(level, (list, tuple)): + level = self._get_level_number(level) + else: + level = [self._get_level_number(lev) for lev in level] + + loc, mi = self._get_loc_level(key, level=level) + if not drop_level: + if lib.is_integer(loc): + # Slice index must be an integer or None + mi = self[loc : loc + 1] + else: + mi = self[loc] + return loc, mi + + def _get_loc_level(self, key, level: int | list[int] = 0): + """ + get_loc_level but with `level` known to be positional, not name-based. + """ + + # different name to distinguish from maybe_droplevels + def maybe_mi_droplevels(indexer, levels): + """ + If level does not exist or all levels were dropped, the exception + has to be handled outside. + """ + new_index = self[indexer] + + for i in sorted(levels, reverse=True): + new_index = new_index._drop_level_numbers([i]) + + return new_index + + if isinstance(level, (tuple, list)): + if len(key) != len(level): + raise AssertionError( + "Key for location must have same length as number of levels" + ) + result = None + for lev, k in zip(level, key): + loc, new_index = self._get_loc_level(k, level=lev) + if isinstance(loc, slice): + mask = np.zeros(len(self), dtype=bool) + mask[loc] = True + loc = mask + result = loc if result is None else result & loc + + try: + # FIXME: we should be only dropping levels on which we are + # scalar-indexing + mi = maybe_mi_droplevels(result, level) + except ValueError: + # droplevel failed because we tried to drop all levels, + # i.e. len(level) == self.nlevels + mi = self[result] + + return result, mi + + # kludge for #1796 + if isinstance(key, list): + key = tuple(key) + + if isinstance(key, tuple) and level == 0: + try: + # Check if this tuple is a single key in our first level + if key in self.levels[0]: + indexer = self._get_level_indexer(key, level=level) + new_index = maybe_mi_droplevels(indexer, [0]) + return indexer, new_index + except (TypeError, InvalidIndexError): + pass + + if not any(isinstance(k, slice) for k in key): + if len(key) == self.nlevels and self.is_unique: + # Complete key in unique index -> standard get_loc + try: + return (self._engine.get_loc(key), None) + except KeyError as err: + raise KeyError(key) from err + except TypeError: + # e.g. partial string indexing + # test_partial_string_timestamp_multiindex + pass + + # partial selection + indexer = self.get_loc(key) + ilevels = [i for i in range(len(key)) if key[i] != slice(None, None)] + if len(ilevels) == self.nlevels: + if is_integer(indexer): + # we are dropping all levels + return indexer, None + + # TODO: in some cases we still need to drop some levels, + # e.g. test_multiindex_perf_warn + # test_partial_string_timestamp_multiindex + ilevels = [ + i + for i in range(len(key)) + if ( + not isinstance(key[i], str) + or not self.levels[i]._supports_partial_string_indexing + ) + and key[i] != slice(None, None) + ] + if len(ilevels) == self.nlevels: + # TODO: why? + ilevels = [] + return indexer, maybe_mi_droplevels(indexer, ilevels) + + else: + indexer = None + for i, k in enumerate(key): + if not isinstance(k, slice): + loc_level = self._get_level_indexer(k, level=i) + if isinstance(loc_level, slice): + if com.is_null_slice(loc_level) or com.is_full_slice( + loc_level, len(self) + ): + # everything + continue + + # e.g. test_xs_IndexSlice_argument_not_implemented + k_index = np.zeros(len(self), dtype=bool) + k_index[loc_level] = True + + else: + k_index = loc_level + + elif com.is_null_slice(k): + # taking everything, does not affect `indexer` below + continue + + else: + # FIXME: this message can be inaccurate, e.g. + # test_series_varied_multiindex_alignment + raise TypeError(f"Expected label or tuple of labels, got {key}") + + if indexer is None: + indexer = k_index + else: + indexer &= k_index + if indexer is None: + indexer = slice(None, None) + ilevels = [i for i in range(len(key)) if key[i] != slice(None, None)] + return indexer, maybe_mi_droplevels(indexer, ilevels) + else: + indexer = self._get_level_indexer(key, level=level) + if ( + isinstance(key, str) + and self.levels[level]._supports_partial_string_indexing + ): + # check to see if we did an exact lookup vs sliced + check = self.levels[level].get_loc(key) + if not is_integer(check): + # e.g. test_partial_string_timestamp_multiindex + return indexer, self[indexer] + + try: + result_index = maybe_mi_droplevels(indexer, [level]) + except ValueError: + result_index = self[indexer] + + return indexer, result_index + + def _get_level_indexer( + self, key, level: int = 0, indexer: npt.NDArray[np.bool_] | None = None + ): + # `level` kwarg is _always_ positional, never name + # return a boolean array or slice showing where the key is + # in the totality of values + # if the indexer is provided, then use this + + level_index = self.levels[level] + level_codes = self.codes[level] + + def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): + # Compute a bool indexer to identify the positions to take. + # If we have an existing indexer, we only need to examine the + # subset of positions where the existing indexer is True. + if indexer is not None: + # we only need to look at the subset of codes where the + # existing indexer equals True + codes = codes[indexer] + + if step is None or step == 1: + new_indexer = (codes >= start) & (codes < stop) + else: + r = np.arange(start, stop, step, dtype=codes.dtype) + new_indexer = algos.isin(codes, r) + + if indexer is None: + return new_indexer + + indexer = indexer.copy() + indexer[indexer] = new_indexer + return indexer + + if isinstance(key, slice): + # handle a slice, returning a slice if we can + # otherwise a boolean indexer + step = key.step + is_negative_step = step is not None and step < 0 + + try: + if key.start is not None: + start = level_index.get_loc(key.start) + elif is_negative_step: + start = len(level_index) - 1 + else: + start = 0 + + if key.stop is not None: + stop = level_index.get_loc(key.stop) + elif is_negative_step: + stop = 0 + elif isinstance(start, slice): + stop = len(level_index) + else: + stop = len(level_index) - 1 + except KeyError: + # we have a partial slice (like looking up a partial date + # string) + start = stop = level_index.slice_indexer(key.start, key.stop, key.step) + step = start.step + + if isinstance(start, slice) or isinstance(stop, slice): + # we have a slice for start and/or stop + # a partial date slicer on a DatetimeIndex generates a slice + # note that the stop ALREADY includes the stopped point (if + # it was a string sliced) + start = getattr(start, "start", start) + stop = getattr(stop, "stop", stop) + return convert_indexer(start, stop, step) + + elif level > 0 or self._lexsort_depth == 0 or step is not None: + # need to have like semantics here to right + # searching as when we are using a slice + # so adjust the stop by 1 (so we include stop) + stop = (stop - 1) if is_negative_step else (stop + 1) + return convert_indexer(start, stop, step) + else: + # sorted, so can return slice object -> view + i = algos.searchsorted(level_codes, start, side="left") + j = algos.searchsorted(level_codes, stop, side="right") + return slice(i, j, step) + + else: + idx = self._get_loc_single_level_index(level_index, key) + + if level > 0 or self._lexsort_depth == 0: + # Desired level is not sorted + if isinstance(idx, slice): + # test_get_loc_partial_timestamp_multiindex + locs = (level_codes >= idx.start) & (level_codes < idx.stop) + return locs + + locs = np.asarray(level_codes == idx, dtype=bool) + + if not locs.any(): + # The label is present in self.levels[level] but unused: + raise KeyError(key) + return locs + + if isinstance(idx, slice): + # e.g. test_partial_string_timestamp_multiindex + start = algos.searchsorted(level_codes, idx.start, side="left") + # NB: "left" here bc of slice semantics + end = algos.searchsorted(level_codes, idx.stop, side="left") + else: + start = algos.searchsorted(level_codes, idx, side="left") + end = algos.searchsorted(level_codes, idx, side="right") + + if start == end: + # The label is present in self.levels[level] but unused: + raise KeyError(key) + return slice(start, end) + + def get_locs(self, seq) -> npt.NDArray[np.intp]: + """ + Get location for a sequence of labels. + + Parameters + ---------- + seq : label, slice, list, mask or a sequence of such + You should use one of the above for each level. + If a level should not be used, set it to ``slice(None)``. + + Returns + ------- + numpy.ndarray + NumPy array of integers suitable for passing to iloc. + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) + + >>> mi.get_locs('b') # doctest: +SKIP + array([1, 2], dtype=int64) + + >>> mi.get_locs([slice(None), ['e', 'f']]) # doctest: +SKIP + array([1, 2], dtype=int64) + + >>> mi.get_locs([[True, False, True], slice('e', 'f')]) # doctest: +SKIP + array([2], dtype=int64) + """ + + # must be lexsorted to at least as many levels + true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s] + if true_slices and true_slices[-1] >= self._lexsort_depth: + raise UnsortedIndexError( + "MultiIndex slicing requires the index to be lexsorted: slicing " + f"on levels {true_slices}, lexsort depth {self._lexsort_depth}" + ) + + if any(x is Ellipsis for x in seq): + raise NotImplementedError( + "MultiIndex does not support indexing with Ellipsis" + ) + + n = len(self) + + def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]: + if isinstance(indexer, slice): + new_indexer = np.zeros(n, dtype=np.bool_) + new_indexer[indexer] = True + return new_indexer + return indexer + + # a bool indexer for the positions we want to take + indexer: npt.NDArray[np.bool_] | None = None + + for i, k in enumerate(seq): + lvl_indexer: npt.NDArray[np.bool_] | slice | None = None + + if com.is_bool_indexer(k): + if len(k) != n: + raise ValueError( + "cannot index with a boolean indexer that " + "is not the same length as the index" + ) + lvl_indexer = np.asarray(k) + if indexer is None: + lvl_indexer = lvl_indexer.copy() + + elif is_list_like(k): + # a collection of labels to include from this level (these are or'd) + + # GH#27591 check if this is a single tuple key in the level + try: + lvl_indexer = self._get_level_indexer(k, level=i, indexer=indexer) + except (InvalidIndexError, TypeError, KeyError) as err: + # InvalidIndexError e.g. non-hashable, fall back to treating + # this as a sequence of labels + # KeyError it can be ambiguous if this is a label or sequence + # of labels + # github.com/pandas-dev/pandas/issues/39424#issuecomment-871626708 + for x in k: + if not is_hashable(x): + # e.g. slice + raise err + # GH 39424: Ignore not founds + # GH 42351: No longer ignore not founds & enforced in 2.0 + # TODO: how to handle IntervalIndex level? (no test cases) + item_indexer = self._get_level_indexer( + x, level=i, indexer=indexer + ) + if lvl_indexer is None: + lvl_indexer = _to_bool_indexer(item_indexer) + elif isinstance(item_indexer, slice): + lvl_indexer[item_indexer] = True # type: ignore[index] + else: + lvl_indexer |= item_indexer + + if lvl_indexer is None: + # no matches we are done + # test_loc_getitem_duplicates_multiindex_empty_indexer + return np.array([], dtype=np.intp) + + elif com.is_null_slice(k): + # empty slice + if indexer is None and i == len(seq) - 1: + return np.arange(n, dtype=np.intp) + continue + + else: + # a slice or a single label + lvl_indexer = self._get_level_indexer(k, level=i, indexer=indexer) + + # update indexer + lvl_indexer = _to_bool_indexer(lvl_indexer) + if indexer is None: + indexer = lvl_indexer + else: + indexer &= lvl_indexer + if not np.any(indexer) and np.any(lvl_indexer): + raise KeyError(seq) + + # empty indexer + if indexer is None: + return np.array([], dtype=np.intp) + + pos_indexer = indexer.nonzero()[0] + return self._reorder_indexer(seq, pos_indexer) + + # -------------------------------------------------------------------- + + def _reorder_indexer( + self, + seq: tuple[Scalar | Iterable | AnyArrayLike, ...], + indexer: npt.NDArray[np.intp], + ) -> npt.NDArray[np.intp]: + """ + Reorder an indexer of a MultiIndex (self) so that the labels are in the + same order as given in seq + + Parameters + ---------- + seq : label/slice/list/mask or a sequence of such + indexer: a position indexer of self + + Returns + ------- + indexer : a sorted position indexer of self ordered as seq + """ + + # check if sorting is necessary + need_sort = False + for i, k in enumerate(seq): + if com.is_null_slice(k) or com.is_bool_indexer(k) or is_scalar(k): + pass + elif is_list_like(k): + if len(k) <= 1: # type: ignore[arg-type] + pass + elif self._is_lexsorted(): + # If the index is lexsorted and the list_like label + # in seq are sorted then we do not need to sort + k_codes = self.levels[i].get_indexer(k) + k_codes = k_codes[k_codes >= 0] # Filter absent keys + # True if the given codes are not ordered + need_sort = (k_codes[:-1] > k_codes[1:]).any() + else: + need_sort = True + elif isinstance(k, slice): + if self._is_lexsorted(): + need_sort = k.step is not None and k.step < 0 + else: + need_sort = True + else: + need_sort = True + if need_sort: + break + if not need_sort: + return indexer + + n = len(self) + keys: tuple[np.ndarray, ...] = () + # For each level of the sequence in seq, map the level codes with the + # order they appears in a list-like sequence + # This mapping is then use to reorder the indexer + for i, k in enumerate(seq): + if is_scalar(k): + # GH#34603 we want to treat a scalar the same as an all equal list + k = [k] + if com.is_bool_indexer(k): + new_order = np.arange(n)[indexer] + elif is_list_like(k): + # Generate a map with all level codes as sorted initially + if not isinstance(k, (np.ndarray, ExtensionArray, Index, ABCSeries)): + k = sanitize_array(k, None) + k = algos.unique(k) + key_order_map = np.ones(len(self.levels[i]), dtype=np.uint64) * len( + self.levels[i] + ) + # Set order as given in the indexer list + level_indexer = self.levels[i].get_indexer(k) + level_indexer = level_indexer[level_indexer >= 0] # Filter absent keys + key_order_map[level_indexer] = np.arange(len(level_indexer)) + + new_order = key_order_map[self.codes[i][indexer]] + elif isinstance(k, slice) and k.step is not None and k.step < 0: + # flip order for negative step + new_order = np.arange(n)[::-1][indexer] + elif isinstance(k, slice) and k.start is None and k.stop is None: + # slice(None) should not determine order GH#31330 + new_order = np.ones((n,), dtype=np.intp)[indexer] + else: + # For all other case, use the same order as the level + new_order = np.arange(n)[indexer] + keys = (new_order,) + keys + + # Find the reordering using lexsort on the keys mapping + ind = np.lexsort(keys) + return indexer[ind] + + def truncate(self, before=None, after=None) -> MultiIndex: + """ + Slice index between two labels / tuples, return new MultiIndex. + + Parameters + ---------- + before : label or tuple, can be partial. Default None + None defaults to start. + after : label or tuple, can be partial. Default None + None defaults to end. + + Returns + ------- + MultiIndex + The truncated MultiIndex. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([['a', 'b', 'c'], ['x', 'y', 'z']]) + >>> mi + MultiIndex([('a', 'x'), ('b', 'y'), ('c', 'z')], + ) + >>> mi.truncate(before='a', after='b') + MultiIndex([('a', 'x'), ('b', 'y')], + ) + """ + if after and before and after < before: + raise ValueError("after < before") + + i, j = self.levels[0].slice_locs(before, after) + left, right = self.slice_locs(before, after) + + new_levels = list(self.levels) + new_levels[0] = new_levels[0][i:j] + + new_codes = [level_codes[left:right] for level_codes in self.codes] + new_codes[0] = new_codes[0] - i + + return MultiIndex( + levels=new_levels, + codes=new_codes, + names=self._names, + verify_integrity=False, + ) + + def equals(self, other: object) -> bool: + """ + Determines if two MultiIndex objects have the same labeling information + (the levels themselves do not necessarily have to be the same) + + See Also + -------- + equal_levels + """ + if self.is_(other): + return True + + if not isinstance(other, Index): + return False + + if len(self) != len(other): + return False + + if not isinstance(other, MultiIndex): + # d-level MultiIndex can equal d-tuple Index + if not self._should_compare(other): + # object Index or Categorical[object] may contain tuples + return False + return array_equivalent(self._values, other._values) + + if self.nlevels != other.nlevels: + return False + + for i in range(self.nlevels): + self_codes = self.codes[i] + other_codes = other.codes[i] + self_mask = self_codes == -1 + other_mask = other_codes == -1 + if not np.array_equal(self_mask, other_mask): + return False + self_codes = self_codes[~self_mask] + self_values = self.levels[i]._values.take(self_codes) + + other_codes = other_codes[~other_mask] + other_values = other.levels[i]._values.take(other_codes) + + # since we use NaT both datetime64 and timedelta64 we can have a + # situation where a level is typed say timedelta64 in self (IOW it + # has other values than NaT) but types datetime64 in other (where + # its all NaT) but these are equivalent + if len(self_values) == 0 and len(other_values) == 0: + continue + + if not isinstance(self_values, np.ndarray): + # i.e. ExtensionArray + if not self_values.equals(other_values): + return False + elif not isinstance(other_values, np.ndarray): + # i.e. other is ExtensionArray + if not other_values.equals(self_values): + return False + else: + if not array_equivalent(self_values, other_values): + return False + + return True + + def equal_levels(self, other: MultiIndex) -> bool: + """ + Return True if the levels of both MultiIndex objects are the same + + """ + if self.nlevels != other.nlevels: + return False + + for i in range(self.nlevels): + if not self.levels[i].equals(other.levels[i]): + return False + return True + + # -------------------------------------------------------------------- + # Set Methods + + def _union(self, other, sort) -> MultiIndex: + other, result_names = self._convert_can_do_setop(other) + if other.has_duplicates: + # This is only necessary if other has dupes, + # otherwise difference is faster + result = super()._union(other, sort) + + if isinstance(result, MultiIndex): + return result + return MultiIndex.from_arrays( + zip(*result), sortorder=None, names=result_names + ) + + else: + right_missing = other.difference(self, sort=False) + if len(right_missing): + result = self.append(right_missing) + else: + result = self._get_reconciled_name_object(other) + + if sort is not False: + try: + result = result.sort_values() + except TypeError: + if sort is True: + raise + warnings.warn( + "The values in the array are unorderable. " + "Pass `sort=False` to suppress this warning.", + RuntimeWarning, + stacklevel=find_stack_level(), + ) + return result + + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + return is_object_dtype(dtype) + + def _get_reconciled_name_object(self, other) -> MultiIndex: + """ + If the result of a set operation will be self, + return self, unless the names change, in which + case make a shallow copy of self. + """ + names = self._maybe_match_names(other) + if self.names != names: + # error: Cannot determine type of "rename" + return self.rename(names) # type: ignore[has-type] + return self + + def _maybe_match_names(self, other): + """ + Try to find common names to attach to the result of an operation between + a and b. Return a consensus list of names if they match at least partly + or list of None if they have completely different names. + """ + if len(self.names) != len(other.names): + return [None] * len(self.names) + names = [] + for a_name, b_name in zip(self.names, other.names): + if a_name == b_name: + names.append(a_name) + else: + # TODO: what if they both have np.nan for their names? + names.append(None) + return names + + def _wrap_intersection_result(self, other, result) -> MultiIndex: + _, result_names = self._convert_can_do_setop(other) + return result.set_names(result_names) + + def _wrap_difference_result(self, other, result: MultiIndex) -> MultiIndex: + _, result_names = self._convert_can_do_setop(other) + + if len(result) == 0: + return result.remove_unused_levels().set_names(result_names) + else: + return result.set_names(result_names) + + def _convert_can_do_setop(self, other): + result_names = self.names + + if not isinstance(other, Index): + if len(other) == 0: + return self[:0], self.names + else: + msg = "other must be a MultiIndex or a list of tuples" + try: + other = MultiIndex.from_tuples(other, names=self.names) + except (ValueError, TypeError) as err: + # ValueError raised by tuples_to_object_array if we + # have non-object dtype + raise TypeError(msg) from err + else: + result_names = get_unanimous_names(self, other) + + return other, result_names + + # -------------------------------------------------------------------- + + @doc(Index.astype) + def astype(self, dtype, copy: bool = True): + dtype = pandas_dtype(dtype) + if isinstance(dtype, CategoricalDtype): + msg = "> 1 ndim Categorical are not supported at this time" + raise NotImplementedError(msg) + if not is_object_dtype(dtype): + raise TypeError( + "Setting a MultiIndex dtype to anything other than object " + "is not supported" + ) + if copy is True: + return self._view() + return self + + def _validate_fill_value(self, item): + if isinstance(item, MultiIndex): + # GH#43212 + if item.nlevels != self.nlevels: + raise ValueError("Item must have length equal to number of levels.") + return item._values + elif not isinstance(item, tuple): + # Pad the key with empty strings if lower levels of the key + # aren't specified: + item = (item,) + ("",) * (self.nlevels - 1) + elif len(item) != self.nlevels: + raise ValueError("Item must have length equal to number of levels.") + return item + + def putmask(self, mask, value: MultiIndex) -> MultiIndex: + """ + Return a new MultiIndex of the values set with the mask. + + Parameters + ---------- + mask : array like + value : MultiIndex + Must either be the same length as self or length one + + Returns + ------- + MultiIndex + """ + mask, noop = validate_putmask(self, mask) + if noop: + return self.copy() + + if len(mask) == len(value): + subset = value[mask].remove_unused_levels() + else: + subset = value.remove_unused_levels() + + new_levels = [] + new_codes = [] + + for i, (value_level, level, level_codes) in enumerate( + zip(subset.levels, self.levels, self.codes) + ): + new_level = level.union(value_level, sort=False) + value_codes = new_level.get_indexer_for(subset.get_level_values(i)) + new_code = ensure_int64(level_codes) + new_code[mask] = value_codes + new_levels.append(new_level) + new_codes.append(new_code) + + return MultiIndex( + levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False + ) + + def insert(self, loc: int, item) -> MultiIndex: + """ + Make new MultiIndex inserting new item at location + + Parameters + ---------- + loc : int + item : tuple + Must be same length as number of levels in the MultiIndex + + Returns + ------- + new_index : Index + """ + item = self._validate_fill_value(item) + + new_levels = [] + new_codes = [] + for k, level, level_codes in zip(item, self.levels, self.codes): + if k not in level: + # have to insert into level + # must insert at end otherwise you have to recompute all the + # other codes + lev_loc = len(level) + level = level.insert(lev_loc, k) + else: + lev_loc = level.get_loc(k) + + new_levels.append(level) + new_codes.append(np.insert(ensure_int64(level_codes), loc, lev_loc)) + + return MultiIndex( + levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False + ) + + def delete(self, loc) -> MultiIndex: + """ + Make new index with passed location deleted + + Returns + ------- + new_index : MultiIndex + """ + new_codes = [np.delete(level_codes, loc) for level_codes in self.codes] + return MultiIndex( + levels=self.levels, + codes=new_codes, + names=self.names, + verify_integrity=False, + ) + + @doc(Index.isin) + def isin(self, values, level=None) -> npt.NDArray[np.bool_]: + if isinstance(values, Generator): + values = list(values) + + if level is None: + if len(values) == 0: + return np.zeros((len(self),), dtype=np.bool_) + if not isinstance(values, MultiIndex): + values = MultiIndex.from_tuples(values) + return values.unique().get_indexer_for(self) != -1 + else: + num = self._get_level_number(level) + levs = self.get_level_values(num) + + if levs.size == 0: + return np.zeros(len(levs), dtype=np.bool_) + return levs.isin(values) + + # error: Incompatible types in assignment (expression has type overloaded function, + # base class "Index" defined the type as "Callable[[Index, Any, bool], Any]") + rename = Index.set_names # type: ignore[assignment] + + # --------------------------------------------------------------- + # Arithmetic/Numeric Methods - Disabled + + __add__ = make_invalid_op("__add__") + __radd__ = make_invalid_op("__radd__") + __iadd__ = make_invalid_op("__iadd__") + __sub__ = make_invalid_op("__sub__") + __rsub__ = make_invalid_op("__rsub__") + __isub__ = make_invalid_op("__isub__") + __pow__ = make_invalid_op("__pow__") + __rpow__ = make_invalid_op("__rpow__") + __mul__ = make_invalid_op("__mul__") + __rmul__ = make_invalid_op("__rmul__") + __floordiv__ = make_invalid_op("__floordiv__") + __rfloordiv__ = make_invalid_op("__rfloordiv__") + __truediv__ = make_invalid_op("__truediv__") + __rtruediv__ = make_invalid_op("__rtruediv__") + __mod__ = make_invalid_op("__mod__") + __rmod__ = make_invalid_op("__rmod__") + __divmod__ = make_invalid_op("__divmod__") + __rdivmod__ = make_invalid_op("__rdivmod__") + # Unary methods disabled + __neg__ = make_invalid_op("__neg__") + __pos__ = make_invalid_op("__pos__") + __abs__ = make_invalid_op("__abs__") + __invert__ = make_invalid_op("__invert__") + + +def _lexsort_depth(codes: list[np.ndarray], nlevels: int) -> int: + """Count depth (up to a maximum of `nlevels`) with which codes are lexsorted.""" + int64_codes = [ensure_int64(level_codes) for level_codes in codes] + for k in range(nlevels, 0, -1): + if libalgos.is_lexsorted(int64_codes[:k]): + return k + return 0 + + +def sparsify_labels(label_list, start: int = 0, sentinel: object = ""): + pivoted = list(zip(*label_list)) + k = len(label_list) + + result = pivoted[: start + 1] + prev = pivoted[start] + + for cur in pivoted[start + 1 :]: + sparse_cur = [] + + for i, (p, t) in enumerate(zip(prev, cur)): + if i == k - 1: + sparse_cur.append(t) + # error: Argument 1 to "append" of "list" has incompatible + # type "list[Any]"; expected "tuple[Any, ...]" + result.append(sparse_cur) # type: ignore[arg-type] + break + + if p == t: + sparse_cur.append(sentinel) + else: + sparse_cur.extend(cur[i:]) + # error: Argument 1 to "append" of "list" has incompatible + # type "list[Any]"; expected "tuple[Any, ...]" + result.append(sparse_cur) # type: ignore[arg-type] + break + + prev = cur + + return list(zip(*result)) + + +def _get_na_rep(dtype: DtypeObj) -> str: + if isinstance(dtype, ExtensionDtype): + return f"{dtype.na_value}" + else: + dtype_type = dtype.type + + return {np.datetime64: "NaT", np.timedelta64: "NaT"}.get(dtype_type, "NaN") + + +def maybe_droplevels(index: Index, key) -> Index: + """ + Attempt to drop level or levels from the given index. + + Parameters + ---------- + index: Index + key : scalar or tuple + + Returns + ------- + Index + """ + # drop levels + original_index = index + if isinstance(key, tuple): + # Caller is responsible for ensuring the key is not an entry in the first + # level of the MultiIndex. + for _ in key: + try: + index = index._drop_level_numbers([0]) + except ValueError: + # we have dropped too much, so back out + return original_index + else: + try: + index = index._drop_level_numbers([0]) + except ValueError: + pass + + return index + + +def _coerce_indexer_frozen(array_like, categories, copy: bool = False) -> np.ndarray: + """ + Coerce the array-like indexer to the smallest integer dtype that can encode all + of the given categories. + + Parameters + ---------- + array_like : array-like + categories : array-like + copy : bool + + Returns + ------- + np.ndarray + Non-writeable. + """ + array_like = coerce_indexer_dtype(array_like, categories) + if copy: + array_like = array_like.copy() + array_like.flags.writeable = False + return array_like + + +def _require_listlike(level, arr, arrname: str): + """ + Ensure that level is either None or listlike, and arr is list-of-listlike. + """ + if level is not None and not is_list_like(level): + if not is_list_like(arr): + raise TypeError(f"{arrname} must be list-like") + if len(arr) > 0 and is_list_like(arr[0]): + raise TypeError(f"{arrname} must be list-like") + level = [level] + arr = [arr] + elif level is None or is_list_like(level): + if not is_list_like(arr) or not is_list_like(arr[0]): + raise TypeError(f"{arrname} must be list of lists-like") + return level, arr diff --git a/shared/package-files/26/26cdc61aecf1403670e53af92a07b40c2631f608b77b26b80d9c5fc226fa7b76/runtests.py b/shared/package-files/26/26cdc61aecf1403670e53af92a07b40c2631f608b77b26b80d9c5fc226fa7b76/runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9f760f070be528e8cd51ab38e00bc944dda9ac --- /dev/null +++ b/shared/package-files/26/26cdc61aecf1403670e53af92a07b40c2631f608b77b26b80d9c5fc226fa7b76/runtests.py @@ -0,0 +1,13 @@ +""" +.. deprecated:: 1.6 + + sympy.utilities.runtests has been renamed to sympy.testing.runtests. +""" + +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.utilities.runtests submodule is deprecated. Use sympy.testing.runtests instead.", + deprecated_since_version="1.6", + active_deprecations_target="deprecated-sympy-utilities-submodules") + +from sympy.testing.runtests import * # noqa: F401,F403 diff --git a/shared/package-files/26/26cedfcbb8c94aa6adc3ce82ce0eafe930dc70232515a13b0abf0ac72de14feb/_multiformat_message_string.cpython-311.pyc b/shared/package-files/26/26cedfcbb8c94aa6adc3ce82ce0eafe930dc70232515a13b0abf0ac72de14feb/_multiformat_message_string.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8db9f402e97edae777d4b02e4b8849d56c22581 Binary files /dev/null and b/shared/package-files/26/26cedfcbb8c94aa6adc3ce82ce0eafe930dc70232515a13b0abf0ac72de14feb/_multiformat_message_string.cpython-311.pyc differ diff --git a/shared/package-files/26/26d1505bdc05162e8d62606b86460e44e194269a5c37245e805f686f750ca362/_sample_dirichlet_cpu_dispatch.h b/shared/package-files/26/26d1505bdc05162e8d62606b86460e44e194269a5c37245e805f686f750ca362/_sample_dirichlet_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b5a9bdf468d3a47c1b9f961c011d96df65918e01 --- /dev/null +++ b/shared/package-files/26/26d1505bdc05162e8d62606b86460e44e194269a5c37245e805f686f750ca362/_sample_dirichlet_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _sample_dirichlet(const at::Tensor & self, ::std::optional generator=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/26/26d2dc1efbb5bf27574ec83b9fb373e47e6f6496a8e4a4ca08ff78d2fa861704/gelu_backward_ops.h b/shared/package-files/26/26d2dc1efbb5bf27574ec83b9fb373e47e6f6496a8e4a4ca08ff78d2fa861704/gelu_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..786eb7b0815553520fe7bb11c0a499ee4cb3fbe2 --- /dev/null +++ b/shared/package-files/26/26d2dc1efbb5bf27574ec83b9fb373e47e6f6496a8e4a4ca08ff78d2fa861704/gelu_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API gelu_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::string_view, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::gelu_backward"; + static constexpr const char* overload_name = "grad_input"; + static constexpr const char* schema_str = "gelu_backward.grad_input(Tensor grad_output, Tensor self, *, str approximate='none', Tensor(a!) grad_input) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate, at::Tensor & grad_input); +}; + +struct TORCH_API gelu_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::string_view); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::gelu_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/26d39fefb16f155d2a7fe3429574dd3fd68d5d08dc168d6a9d4092cd1d3b3e28/clip_grad.h b/shared/package-files/26/26d39fefb16f155d2a7fe3429574dd3fd68d5d08dc168d6a9d4092cd1d3b3e28/clip_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..a5fbbcbd854cdd8ec9f9358ef9c6328d49cf132f --- /dev/null +++ b/shared/package-files/26/26d39fefb16f155d2a7fe3429574dd3fd68d5d08dc168d6a9d4092cd1d3b3e28/clip_grad.h @@ -0,0 +1,144 @@ +#pragma once + +#include + +#include +#include +#include + +namespace torch::nn::utils { + +// Clips gradient norm of a vector of Tensors. +// See +// https://pytorch.org/docs/stable/nn.html?highlight=clip_grad_norm#torch.nn.utils.clip_grad_norm_ +// for more details about this module. +// +// Difference with the python version: unlike the python version, even when +// skipping the finiteness checks (error_if_nonfinite = false), this function +// will introduce a device <=> CPU synchronization (for devices where that makes +// sense!) in order to return a CPU-side `double`. This C++ version therefore +// cannot be run fully asynchronously w.r.t. the device of the gradients. +inline double clip_grad_norm_( + const std::vector& parameters, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + std::vector params_with_grad; + + for (const auto& param : parameters) { + auto& grad = param.grad(); + if (grad.defined()) { + params_with_grad.push_back(param); + } + } + + if (params_with_grad.empty()) { + return 0.0; + } + + Tensor total_norm_tensor; + if (norm_type == std::numeric_limits::infinity()) { + std::vector norms; + norms.reserve(params_with_grad.size()); + + for (const auto& param : params_with_grad) { + norms.emplace_back(param.grad().data().abs().max()); + } + total_norm_tensor = + (norms.size() == 1) ? norms[0] : torch::max(torch::stack(norms)); + } else if (norm_type == 0) { + total_norm_tensor = + torch::full({}, static_cast(params_with_grad.size())); + } else { + std::vector norms; + norms.reserve(params_with_grad.size()); + + for (const auto& param : params_with_grad) { + norms.emplace_back(param.grad().data().norm(norm_type)); + } + total_norm_tensor = + (norms.size() == 1) ? norms[0] : torch::stack(norms).norm(norm_type); + } + + // When possible (ie when skipping the finiteness check), we avoid + // synchronizing the CPU and the gradients' device until the very end to + // preserve async execution on the device. When checking for finite-ness, this + // optional ensures we only sync once. + std::optional total_norm = std::nullopt; + if (error_if_nonfinite) { + total_norm = total_norm_tensor.item().toDouble(); + TORCH_CHECK( + std::isfinite(*total_norm), + "The total norm of order ", + norm_type, + " for gradients from `parameters` ", + "is non-finite, so it cannot be clipped. To disable this error and scale ", + "the gradients with the non-finite norm anyway, set ", + "`error_if_nonfinite=false`"); + } + + auto clip_coef = max_norm / (total_norm_tensor + 1e-6); + auto clip_coef_clamped = + torch::clamp(clip_coef, std::nullopt /* min */, 1.0 /* max */); + for (auto& param : params_with_grad) { + param.grad().data().mul_(clip_coef_clamped); + } + + if (!total_norm.has_value()) { + total_norm = total_norm_tensor.item().toDouble(); + } + return *total_norm; +} + +// A wrapper around clip_grad_norm_ that allows us to call the function with a +// braced-init-list of Tensors. +inline double clip_grad_norm_( + std::initializer_list parameters, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + return clip_grad_norm_( + std::vector(parameters), max_norm, norm_type, error_if_nonfinite); +} + +// A wrapper around clip_grad_norm_ that allows us to call the function with a +// single Tensor. +inline double clip_grad_norm_( + Tensor parameter, + double max_norm, + double norm_type = 2.0, + bool error_if_nonfinite = false) { + std::vector params = {std::move(parameter)}; + return clip_grad_norm_(params, max_norm, norm_type, error_if_nonfinite); +} + +// Clips gradient of an iterable of parameters at specified value. +// Gradients are modified in-place. +// See https://pytorch.org/docs/stable/nn.html#clip-grad-value +// for more details about this module. +inline void clip_grad_value_( + const std::vector& parameters, + double clip_value) { + for (const auto& param : parameters) { + if (param.grad().defined()) { + param.grad().data().clamp_(-clip_value, clip_value); + } + } +} + +// A wrapper around clip_grad_value_ that allows us to call the function with a +// braced-init-list of Tensors. +inline void clip_grad_value_( + std::initializer_list parameters, + double clip_value) { + clip_grad_value_(std::vector(parameters), clip_value); +} + +// A wrapper around clip_grad_value_ that allows us to call the function with a +// single Tensor. +inline void clip_grad_value_(Tensor parameter, double clip_value) { + std::vector params = {std::move(parameter)}; + clip_grad_value_(params, clip_value); +} + +} // namespace torch::nn::utils diff --git a/shared/package-files/26/26d57b7c66d3491a9a2a58c58fc94e96b5955e51915232d38483ae0501eb2787/mkldnn_linear_ops.h b/shared/package-files/26/26d57b7c66d3491a9a2a58c58fc94e96b5955e51915232d38483ae0501eb2787/mkldnn_linear_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..dd8eeb9743aaf74eab93b8d74997b374713cdd36 --- /dev/null +++ b/shared/package-files/26/26d57b7c66d3491a9a2a58c58fc94e96b5955e51915232d38483ae0501eb2787/mkldnn_linear_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mkldnn_linear { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const ::std::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_linear"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias); +}; + +struct TORCH_API mkldnn_linear_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const ::std::optional &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_linear"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "mkldnn_linear.out(Tensor self, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/26e3c1fae0c8dda3df57d1aa1891d278eb4c7149d66aadfe8f9ba3461821c013/Stream.h b/shared/package-files/26/26e3c1fae0c8dda3df57d1aa1891d278eb4c7149d66aadfe8f9ba3461821c013/Stream.h new file mode 100644 index 0000000000000000000000000000000000000000..43b2b3ea43ec190de4cb614f734d2f4c179367fe --- /dev/null +++ b/shared/package-files/26/26e3c1fae0c8dda3df57d1aa1891d278eb4c7149d66aadfe8f9ba3461821c013/Stream.h @@ -0,0 +1,27 @@ +#ifndef THP_STREAM_INC +#define THP_STREAM_INC + +#include +#include +#include +#include + +struct THPStream { + PyObject_HEAD + int64_t stream_id; + int64_t device_type; + int64_t device_index; + // Used to switch stream context management, initialized lazily. + PyObject* context; +}; +extern TORCH_API PyTypeObject* THPStreamClass; + +void THPStream_init(PyObject* module); + +inline bool THPStream_Check(PyObject* obj) { + return THPStreamClass && PyObject_IsInstance(obj, (PyObject*)THPStreamClass); +} + +TORCH_PYTHON_API PyObject* THPStream_Wrap(const c10::Stream& stream); + +#endif // THP_STREAM_INC diff --git a/shared/package-files/26/26e410aa2a756fbbe7047fb371719a692d35c0a64f92f87ee256947d56a1f967/__init__.cpython-311.pyc b/shared/package-files/26/26e410aa2a756fbbe7047fb371719a692d35c0a64f92f87ee256947d56a1f967/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f4667e805a263428822c49d9e094189a9a3c71 Binary files /dev/null and b/shared/package-files/26/26e410aa2a756fbbe7047fb371719a692d35c0a64f92f87ee256947d56a1f967/__init__.cpython-311.pyc differ diff --git a/shared/package-files/26/26e5c9ff43dbeb81075e0d890d12779fb5c0bad23efa367f2290c881e98e40ff/hp_roman8.cpython-311.pyc b/shared/package-files/26/26e5c9ff43dbeb81075e0d890d12779fb5c0bad23efa367f2290c881e98e40ff/hp_roman8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5889bbe7e22a209eb44349545c1c17c65bc26fe1 Binary files /dev/null and b/shared/package-files/26/26e5c9ff43dbeb81075e0d890d12779fb5c0bad23efa367f2290c881e98e40ff/hp_roman8.cpython-311.pyc differ diff --git a/shared/package-files/26/26e79ce1da81568cc7d1959e082665f34c0ddcb43f78e7f2521cbca705833a73/lcm_ops.h b/shared/package-files/26/26e79ce1da81568cc7d1959e082665f34c0ddcb43f78e7f2521cbca705833a73/lcm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c75e18b225c4936257561dd12a0fa55121d664f7 --- /dev/null +++ b/shared/package-files/26/26e79ce1da81568cc7d1959e082665f34c0ddcb43f78e7f2521cbca705833a73/lcm_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API lcm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::lcm"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API lcm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::lcm"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "lcm(Tensor self, Tensor other) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API lcm_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::lcm_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/26/26eac6c09bcfb638abc72a93c5341bf16ea84809ac2567338be65c5e2013c64c/reinplace.py b/shared/package-files/26/26eac6c09bcfb638abc72a93c5341bf16ea84809ac2567338be65c5e2013c64c/reinplace.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcd72938367c5272edea4e6804f9d10582a0ba8 --- /dev/null +++ b/shared/package-files/26/26eac6c09bcfb638abc72a93c5341bf16ea84809ac2567338be65c5e2013c64c/reinplace.py @@ -0,0 +1,752 @@ +# mypy: allow-untyped-defs +import _operator +import itertools +from collections import defaultdict +from enum import Enum + +import torch +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.fx import Node +from torch.fx._compatibility import compatibility +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_map_only + + +__all__ = ["reinplace"] + + +class _ViewType(Enum): + NonView = 0 + SingleOutputView = 1 + MultiOutputView = 2 + + +def _is_view_op(tgt): + if tgt is not None and isinstance(tgt, torch._ops.OpOverload): + schema = tgt._schema + if len(schema.arguments) > 0: + first_arg = schema.arguments[0] + # check if op is a view + return ( + first_arg.alias_info is not None and not first_arg.alias_info.is_write + ) + + +def _get_view_type(tgt) -> _ViewType: + if tgt is not None and isinstance(tgt, torch._ops.OpOverload): + schema = tgt._schema + if len(schema.arguments) > 0: + first_arg = schema.arguments[0] + # check if op is a view + if first_arg.alias_info is not None and not first_arg.alias_info.is_write: + # check if op is a multi-output view + if "*" in first_arg.alias_info.after_set: + return _ViewType.MultiOutputView + else: + return _ViewType.SingleOutputView + return _ViewType.NonView + + +# Stores a bunch of metadata related to functionalization each node. +# Relevant metadata: +# n.meta['fake_result']: FakeTensor (same type as the output of the node, but with FakeTenors instead of Tensors) +# The fake tensor output from running the current node +# n.meta['view_of']: Node +# If the current node n is a view of some base tensor, the 'view_of' field tells us which +# view node was used to generate the current node (a view tensor). +# This information actually makes `fake_result` redundant, but we can use `fake_result` +# to sanity check that our aliasing information is correct. +@compatibility(is_backward_compatible=False) +class _FunctionalizationMetadataProp(torch.fx.Interpreter): + def run_node(self, node: Node): + self.node_counter += 1 + result = super().run_node(node) + node.meta["fake_result"] = result + node.meta["node_idx"] = self.node_counter + + # (1) Update metadata with the list of nodes that are used by this node + # copy_() doesn't read from its first argument; it writes to it, overwriting previous data. + # We don't want to treat it as "being used as an input". + node_args = node.args + if node.target is torch.ops.aten.copy_.default: + node_args = node_args[1:] + + # (2) Update metadata to track aliasing information about view tensor nodes. + if node.op == "call_function": + view_type = _get_view_type(node.target) + if view_type == _ViewType.SingleOutputView: + assert isinstance(node.args[0], Node) + node.meta["view_of"] = node.args[0] + elif view_type == _ViewType.MultiOutputView: + self.multi_output_view_nodes[node] = node.args[0] + + # Check if we returned a multi-output view, + # and we're now grabbing the individual views from the output. + # + # For multi-output views, we want to map each output view to the base, + # but this mapping involves two separate nodes in FX IR. + # e.g. "a, b = x_1.split(...)" becomes: + # %split_tensor : [num_users=2] = call_function[target=torch.ops.aten.split.Tensor](args = (%x_1, 2), kwargs = {}) + # %getitem : [num_users=1] = call_function[target=operator.getitem](args = (%split_tensor, 0), kwargs = {}) + # %getitem_1 : [num_users=1] = call_function[target=operator.getitem](args = (%split_tensor, 1), kwargs = {}) + # And we'd like to set: + # getitem1.meta['view_of'] = x_1 + elif node.target is _operator.getitem: + list_arg = node.args[0] + maybe_base_of_view = self.multi_output_view_nodes.get(list_arg, None) + if maybe_base_of_view is not None: + # Note: we could also track indexing info here for multi-output views. + # I don't think this metadata is strictly needed for de-functionalization. + assert isinstance(maybe_base_of_view, Node) + node.meta["view_of"] = maybe_base_of_view + + if "view_of" in node.meta: + # We're linking the current node with its first argument as views. + # Assert here that this is actually the case, and their storages are the same. + assert isinstance(node.meta["fake_result"], FakeTensor) + assert isinstance(node.meta["view_of"].meta["fake_result"], FakeTensor) + view_storage = StorageWeakRef(node.meta["fake_result"]._typed_storage()) + base_storage = StorageWeakRef( + node.meta["view_of"].meta["fake_result"]._typed_storage() + ) + assert view_storage == base_storage + return result + + def propagate(self, *args): + self.multi_output_view_nodes = {} + self.node_counter = -1 + + with FakeTensorMode() as mode: + fake_args = [ + mode.from_tensor(a) if isinstance(a, torch.Tensor) else a for a in args + ] + return super().run(*fake_args) + + +def _schemas_match(functional_schema, inplace_schema): + names_match = ( + inplace_schema.name.endswith("_") + and inplace_schema.name[:-1] == functional_schema.name + ) + arg_types_match = len(functional_schema.arguments) == len( + inplace_schema.arguments + ) and all( + a1.type == a2.type + for a1, a2 in zip(functional_schema.arguments, inplace_schema.arguments) + ) + # for the inplace op, its first argument should be mutable + assert ( + inplace_schema.arguments[0].alias_info is not None + and inplace_schema.arguments[0].alias_info.is_write + ) + # and its remaining arguments shouldn't be. + assert all(a.alias_info is None for a in inplace_schema.arguments[1:]) + return names_match and arg_types_match + + +# TODO: this should be beefed up to be able to properly re-inplace with: +# - mutating ops (e.g. _fused_moving_avg_obs_fq_helper) +# - out= ops (e.g. angle -> angle.out) +# TODO: we should also figure this info out using torchgen. +def _maybe_get_inplace_op(op): + # __module__ seems broken; it returns torch._ops.aten which doesn't exist + if not isinstance(op, torch._ops.OpOverload): + return None + # Some view ops have inplace variants (as_strided_, etc), + # but we do NOT want the reinplacing pass to directly add these into the program. + # (they'll require extra special handling, aren't aren't really useful for perf anyway) + if _is_view_op(op): + return None + op_namespace = op.__module__.split(".")[-1] + op_base_name = op.overloadpacket.__name__ + maybe_namespace_module = getattr(torch.ops, op_namespace) + maybe_inplace_op = ( + None + if maybe_namespace_module is None + else getattr(maybe_namespace_module, f"{op_base_name}_", None) + ) + if maybe_inplace_op is None: + return None + + inplace_overloads = [ + getattr(maybe_inplace_op, overload_name) + for overload_name in maybe_inplace_op.overloads() + ] + inplace_overloads_with_matching_schemas = [ + f for f in inplace_overloads if _schemas_match(op._schema, f._schema) + ] + # Just because foo() and foo_() are both existing operators, + # They aren't guaranteed to have compatible schemas. + # For example, pow.Scalar(Scalar self, Tensor exponent) has no valid inplace variant, + # Even though several overloads of pow_ exist. + if len(inplace_overloads_with_matching_schemas) == 0: + return None + assert len(inplace_overloads_with_matching_schemas) == 1 + inplace_op = inplace_overloads_with_matching_schemas[0] + return inplace_op + + +_VIEW_INVERSE_MAP = { + torch.ops.aten.diagonal_scatter.default: torch.ops.aten.diagonal.default, + torch.ops.aten.select_scatter.default: torch.ops.aten.select.int, + torch.ops.aten.slice_scatter.default: torch.ops.aten.slice.Tensor, + torch.ops.aten.as_strided_scatter.default: torch.ops.aten.as_strided.default, +} + + +# This function, given a set of set of (aliased) tensor nodes, +# Returns any nodes in the graph that *use* any of the aliases, that occur *after* op_index +# in the node ordering. +def _get_all_later_node_usages(tensor_aliases: set[Node], op_index: int): + def _add_if_tensor(x, set_): + if isinstance(x, FakeTensor): + set_.add(StorageWeakRef(x._typed_storage())) + + nodes_used_after = set() + for t in tensor_aliases: + # get all nodes that use the current alias + usage_nodes = t.users + for n in usage_nodes: + # We only care about usages after the current node + if "node_idx" not in n.meta or n.meta["node_idx"] <= op_index: + continue + # We also don't care about intermediate view ops. + # They only matter if their output is then used elsewhere + # (either in an out-of-place op, or as an output to the function). + if n in tensor_aliases: + if ( + isinstance(n.target, torch._ops.OpOverload) + or n.target == _operator.getitem + ): + continue + nodes_used_after.add(n) + return nodes_used_after + + +# Given an op that we're trying to re-inplace, "b = foo(a)", +# And given a {view}_scatter op that shows up later in the graph, "y = {view}_scatter(base, x, args...)" +# Then re-inplacing `foo()` would allow us to remove the `{view}_scatter` op entirely, IF: +# If there are any aliases in the alias_set(a) that satisfy: +# (1) The base of "alias", "alias_base", has the same size/stride/offset metadata as "base" +# (2) The output of running {view}(alias, args...) gives you the same size/stride/offset metadata +# as "alias" +def _get_view_inverse_node_usages( + later_node_usages: set[Node], self_aliases: set[Node] +) -> set[Node]: + def matching_view_metadata(a, b): + return ( + a.size() == b.size() + and a.stride() == b.stride() + and a.storage_offset() == b.storage_offset() + ) + + view_inverse_nodes = set() + # Go through them in node order, so we can see chains of view_scatter ops. + for n in sorted(later_node_usages, key=lambda x: x.meta["node_idx"]): + if n.target not in _VIEW_INVERSE_MAP: + continue + base = n.args[0] + mutated_view = n.args[1] + assert isinstance(base, Node) + assert isinstance(base.meta["fake_result"], FakeTensor) + assert isinstance(mutated_view, Node) + assert isinstance(mutated_view.meta["fake_result"], FakeTensor) + # Check that this view_inverse op actually corresponds to taking doing the inverse + # of one of our existing self_alias nodes. + original_view = _VIEW_INVERSE_MAP[n.target] + for self_alias in self_aliases: + # We're looking for some alias of the self arg, "alias", + # that was created from some op `alias = foo(base, args...)` + # such that the current _scatter op "inverts" that foo call. + # We can check that by running the original op again, and checking that the strides match. + if "view_of" not in self_alias.meta: + continue + self_alias_base = self_alias.meta["view_of"] + try: + # The we're trying to re-use the args from the view_scatter call inside of the corresponding + # view op, which might throw. This just indicates that view_scatter op isn't a valid inverse + # of the current alias we're looking at. + view_replay_metadata = original_view( + self_alias_base.meta["fake_result"], *n.args[2:], **n.kwargs + ) + expected_metadata = self_alias.meta["fake_result"] + # If the alias and its base both have matching metadata, then this view_scatter op is valid to re-inplace. + if matching_view_metadata( + self_alias_base.meta["fake_result"], base.meta["fake_result"] + ) and matching_view_metadata(view_replay_metadata, expected_metadata): + view_inverse_nodes.add(n) + except Exception: + continue + + return view_inverse_nodes + + +@compatibility(is_backward_compatible=True) +def reinplace(gm, *sample_args): + """ + Given an fx.GraphModule, modifies it to perform "reinplacing", + mutating the nodes of the graph. + We look for out-of-place op call sites like `b = a.add(...)`, + and convert them to be inplace (`b = a.add_(...)`), + as long as the input to the current operator ("a") isn't re-used + anywhere later in the graph. + + This pass currently expects to operate on a **functional, ATen** graph. + This can be obtained by running `make_fx(functionalize(f))`. + + Sample inputs are needed to determine aliasing relationships of the inputs. + In general, we can't reinplace node `b = a.add(...)` if "a" aliases any of the + inputs to the program. + + Given a node "b = foo(a, args...) the algorithm for re-inplacing is as follows: + + (1) Perform some initial checks on the metadata of "a" and "args..." + that can disqualify them from being reinplaced. + + (1a) Check that the self argument we're attempting to reinplace + has acceptable dtype/size metadata to reinplace with. + + For example, if we have: + a = torch.ones(1) + b = torch.ones(10) + out = torch.add(a, b) + We can't turn that into + a.add_(b) + Because that would require resizing "a". + + Similarly, we can't convert torch.ge(a, b) into a.ge_(b), + because that would require changing a's dtype (from e.g. float32 to bool). + Note that in this specific example, we could technically do better.. + + If we see the pattern: + a_1 = a.ge(b) + a_2 = aten._to_copy(a_1, a.dtype) + Then we this should be valid to completely re-inplace + (this is exactly what functionalization will emit when it sees a.ge_(b)). + + This optimization is only really important for user programs + that directly use inplace comparison ops though. + + We also cannot re-inplace on tensors that have overlapping memory, + e.g. torch.ones(1).expand(4, 4).add_(1) + + (1b) Check if "a" is an alias of any of the program inputs. + + If it is, skip and move to the next node. + Inplace'ing an op that would cause it to mutate a program is not sound, + because that would be a side effect visible to the user. + + NOTE: there's a future optimization that we should make: + if "a" is a (alias of a) program input, but later in the program + there is a node that looks like "a.copy_(...)", + Then re-inplacing is ok to do - we are temporarily re-using a's buffer, + which will later be overwritten by the copy_() call. + + This will be an important optimization to have for programs that mutate + their inputs. It currently isn't implemented though. + + (1c) Check if "a" and "args..." alias + + For example, re-inplacing to create code like the below + isn't guaranteed to be sound: + + aten.mul_(a, a) + + (2) Check that "a" and all of its outstanding aliases are not used anywhere + later in the graph. If this is the case, then it's safe to re-inplace + to "b = foo_(a)". + + There are a few caveats to this, explained in more detail below: + (a) If "a" is used later as an argument to a view op, that is okay. + It's only a problem if "a" (or that view) is later passed + into a normal operator, or if it is returned as the program output. + (b) If "a" is a repeat argument in `foo()`, then don't reinplace. + Most ATen kernels don't make any guarantees that this is sound, + e.g. if you do aten.mul_(a, a). + So we'll just ban re-inplacing in this case. + It's only a problem if "a" (or that view) is later passed + (c) If "a" is used as an input into a view "inverse" / "scatter" + operator, it is potentially fine to re-inplace + (and remove that scatter operator from the graph). + See below for a more detailed example. + + NOTE: there is an optimization in this step that is crucial + to fully recovering performance from functionalization. + + Given this program: + def f(x): + a = torch.ops.aten.add(x, x) + b = torch.ops.aten.diagonal(a) + torch.ops.aten.fill_(b, 0) + return d + + Functionalization will emit the following: + def f(x): + a = torch.ops.aten.add(x, x) + b = torch.ops.aten.diagonal(a, 0, 1) + b_updated = torch.ops.aten.fill(b, 0) + a_updated = torch.ops.aten.diagonal_scatter(a, b_updated, 0, 1) + return a_updated + + Ordinarily, we would not be able to reinplace the fill, + because "b" aliases with "a" which is used by the diagonal_scatter call. + + "re-inplacing" is on the hook for figuring out that it is ok to + completely, the expensive diagonal_scatter call, if we re-inplace the add(). + + So, for every `alias in alias_set(a)`, instead of checking + that "alias" is not used anywhere later in the graph, + we check that + EITHER: + (a) alias is not used anywhere later in the graph + OR: + (b) alias is used exactly once later on in the graph, + in the following op: + + out = foo_scatter(alias, x, args...) + + where the following must hold: + (i) "foo_scatter" is the "inverse" operator for foo. + This only applies to "foo" ops that are view operators, + which view into a subset of the original tensor's memory. + In practice, there are ~4 operators where this applies: + diagonal -> diagonal_scatter + slice -> slice_scatter + select -> select_scatter + as_strided -> as_strided_scatter + (ii) "args..." are the same between the foo() and foo_scatter() calls. + + (3) Perform the actual re-inplacing on foo! + + (3b) is the common case, but special care is needed for {view}_scatter (3a) + + (3a) {view}_scatter ops. + + Consider this program: + a = torch.zeros(2, 2) + b = torch.ones(2) + a[0] = b + + Post functionalization, that will look like: + a = torch.zeros(2) + b = torch.ones(1) + a_updated = torch.select_scatter(a, b, 0, 0) + + In this case though, there is no "functional" op to re-inplace! + Instead, we'd like to directly remove toe select_scatter call. + We already know from (3) that this is valid, + because "a" has no later usages in the graph. + + We perform the re-inplacing on the {view}_scatter op like so + Before: + a_updated = torch.select_scatter(a, b, args...) + After: + a_slice = a.select(a, args...) + a_slice.copy_(b) + + (3b) Otherwise, replace the functional op with its inplace variant. + Before: + b = foo(a, args...) + After: + a.foo_(args...) + + (4) Finally, after converting either: + Before: + b = foo(a) + After: + foo_(a) + or + Before: + b = {slice}_scatter(a, mutated_slice, args...) + After: + slice = {slice}(a, args...) + slice.copy_(mutated_slice) + + We now need to find all later nodes that use "b" as an argument + and update them to take in "a" instead. + + Note that for the majority of inplace ops, this isn't actually necessary + (because most inplace ops return "self" as their output). + This isn't generally true for all mutable ops though, which is why + we need to actually replace all of the arguments. + + We also need to update our metadata of Dict[StorageWeakRef, Set[Node]], + That maps a given tensor storage to the set of all nodes that take in that storage + as an input. + Specifically, re-inplacing `b = foo(a)` causes "a" and "b"'s sets to get fused + together. + + (5) Any "view_inverse/scatter" nodes that were identified as "it's ok to ignore them" + during step (3) get manually deleted from the graph. + Their outputs are no longer used, so technically standard DCE would be able + to do this, but we can no longer run FX's DCE pass now that we have mutable + ops in the graph. + """ + _FunctionalizationMetadataProp(gm).propagate(*sample_args) + + # Useful debug printing + # def _print(x): + # if isinstance(x, FakeTensor): + # print(f'fake_result: {StorageWeakRef(x._typed_storage()).cdata}') + + # for n in gm.graph.nodes: + # print(n.format_node()) + # if hasattr(n, 'meta'): + # print(f'node_idx: {n.meta["node_idx"]}') + # if 'fake_result' in n.meta: + # tree_map(_print, n.meta['fake_result']) + # if 'view_of' in n.meta: + # print(f'view_of: {str(n.meta["view_of"])}') + # print() + + # We need to know which nodes correspond to inputs (or their aliases) + # so we know not to re-inplace them. + # NOTE: later, we'll need to add an optimization for fully recovering performance + # on programs that mutate inputs. + input_storages = { + StorageWeakRef(node.meta["fake_result"]._typed_storage()) + for node in gm.graph.nodes + if ( + node.op == "placeholder" + and isinstance(node.meta["fake_result"], torch.Tensor) + ) + } + + # We also need to know for a given node, what are all of its aliasing nodes. + storage_to_nodes: dict[StorageWeakRef, set[Node]] = defaultdict(set) + for n in gm.graph.nodes: + if "fake_result" in n.meta: + # Tree-mapping because some ops can return lists of tensors. + def _add_to_map(x): + if isinstance(x, FakeTensor): + storage_to_nodes[StorageWeakRef(x._typed_storage())].add(n) + + pytree.tree_map_(_add_to_map, n.meta["fake_result"]) + + # inplace-ify functional ops, subject to the constraints written below. + all_later_view_inverse_nodes_to_delete = set() + for node in gm.graph.nodes: + if node.op == "call_function": + # Today, the re-inplace pass on directly acts on: + # - functional ops with an inplace variant + # - {view}_scatter ops that can be potentially removed from the graph. + # Both of these ops take in tensor first args, so filtering on this condition + # makes the later code simpler. + # We should revisit this at some point though, particularly when we also want + # the reinplacer to be able to handle out= and mutable operators + # and tensorlist first args (like `_foreach_` ops). + if not isinstance(node.target, torch._ops.OpOverload): + continue + if len(node.target._schema.arguments) < 1: + continue + if type(node.target._schema.arguments[0].type) != torch.TensorType: + continue + + # Step 1a: Check that the self argument we're attempting to reinplace + # has the same size/stride as the output. + # For example, we shouldn't try to reinplace torch.add(scalar_tensor, larger_tensor) + # As it would require resizing scalar_tensor. + # (We could potentially swizzle this into larger_tensor.add_(scalar_tensor), + # this is probably an optimization to revisit later). + self_arg = node.args[0] + self_flattened = pytree.tree_leaves(self_arg.meta["fake_result"]) + node_flattened = pytree.tree_leaves(node.meta["fake_result"]) + self_has_wrong_metadata = False + if len(self_flattened) == len(node_flattened): + for self_meta, node_meta in zip(self_flattened, node_flattened): + if self_meta.numel() != node_meta.numel(): + self_has_wrong_metadata = True + if self_meta.dtype != node_meta.dtype: + self_has_wrong_metadata = True + # We also cannot re-inplace on tensors that have internal memory overlap. + # e.g. torch.ones(1).expand(4, 4).add_(1) + if torch._debug_has_internal_overlap(self_meta) == 1: + self_has_wrong_metadata = True + # Here, we (optimistically) assume that a.resize(b) is valid to re-inplace, + # Since users should never really be calling the functional "torch.ops.aten.resize" + # op directly in their programs. + if self_has_wrong_metadata and node.target != torch.ops.aten.resize.default: + continue + + # Step 1b: ensure that the op we're trying to re-inplace isn't a program input + self_arg_storage = StorageWeakRef( + self_arg.meta["fake_result"]._typed_storage() + ) + if self_arg_storage in input_storages: + # TODO: later, add the optimization for handling `copy_()` calls in the graph. + continue + if len([x for x in node.args if x is self_arg]) > 1: + # Step 1c: + # Calling stuff like aten.mul_(a, a) isn't guaranteed to be sound, + # so we prevent re-inplacing in this case. + continue + + self_arg_storage = StorageWeakRef( + self_arg.meta["fake_result"]._typed_storage() + ) + self_aliases = storage_to_nodes[self_arg_storage] + + # First, we find all later usages of any of the aliases of self_arg. + later_node_usages = _get_all_later_node_usages( + self_aliases, node.meta["node_idx"] + ) + # Then, we check if any of those later usages are actually view_scatter ops + # that are safe to fully remove. + later_view_inverse_node_usages = _get_view_inverse_node_usages( + later_node_usages, self_aliases + ) + + # Step 2: Check to see if the input to the op is re-used later in the graph. + # If not (same goes for its aliases), then this op is safe to re-in place. + # This is a slightly roundabout way to check that there are no later usages of the current self argument. + # (later_view_inverse_node_usages corresponds to "view_scatter" nodes that we are allowed to delete) + can_reinplace = len(later_node_usages - later_view_inverse_node_usages) == 0 + if not can_reinplace: + continue + + # Step 3a: Special handling for when we see *_scatter operators. + # When we see an operator like `b = torch.slice_scatter(a, ...)`, + # instead of trying to "inplace" it into a.slice_scatter_(..._), + # we would prefer to remove it from the graph entirely, + # and instead copy_() the slice directly into the larger tensor. + # See the description of the algorithm for a full example. + if ( + node.target in _VIEW_INVERSE_MAP + and node not in all_later_view_inverse_nodes_to_delete + ): + view_op = _VIEW_INVERSE_MAP[node.target] + # Before: + # base_updated = torch.ops.aten.slice_scatter.default(base, mutated_slice, args...) + # After: + # slice = torch.ops.aten.slice.default(base, args...) + # slice.copy_(mutated_slice) + with gm.graph.inserting_before(node): + mutated_slice_node = node.args[1] + remaining_slice_args = node.args[2:] + slice_node = gm.graph.create_node( + "call_function", + view_op, + (self_arg,) + tuple(remaining_slice_args), + node.kwargs, + ) + gm.graph.create_node( + "call_function", + torch.ops.aten.copy_.default, + ( + slice_node, + mutated_slice_node, + ), + {}, + ) + # Add the slice_scatter node to our "nodes to delete" list. + all_later_view_inverse_nodes_to_delete.add(node) + + else: + # Step 3b: Check to see if this operator has an inplace variant. + maybe_inplace_op = _maybe_get_inplace_op(node.target) + if maybe_inplace_op is None: + continue + # And if so, replace it with its inplace variant. + node.target = maybe_inplace_op + + # At this point, 'storage_to_nodes' will be stale. + # Now that we're inplacing `b = foo(a)`, we need to effectively + # union together the dict values for b and a's storage. + # Hmm... morally I think we also want to keep the `fake_result` metadata + # up to date here, but I'm not sure how easy it is to do. + # Maybe it's fine to wait until the end of the pass to update it. + curr_node_storage = StorageWeakRef( + node.meta["fake_result"]._typed_storage() + ) + storage_to_nodes[self_arg_storage].update( + storage_to_nodes[curr_node_storage] + ) + storage_to_nodes[curr_node_storage].update( + storage_to_nodes[self_arg_storage] + ) + + # Need to remember the view_scatter view nodes we found so we can remove them alter. + all_later_view_inverse_nodes_to_delete.update( + later_view_inverse_node_usages + ) + + # Step 4: + # Now that we've replaced b = a.foo() with a.foo_(), + # We need to replace any later usages of "b" with "a" + for old in itertools.chain([node], later_view_inverse_node_usages): + new = old.args[0] + nodes_to_update = [ + n for n in old.users if n.meta["node_idx"] > node.meta["node_idx"] + ] + for node_to_update in nodes_to_update: + + def replace_arg(a): + if a == old: + return new + return a + + # First, replace usages of "b" with "a" + node_to_update.args = tree_map_only( + Node, replace_arg, node_to_update.args + ) + node_to_update.kwargs = tree_map_only( + Node, replace_arg, node_to_update.kwargs + ) + + # Second, update our storage_to_nodes data structure. + old_flattened_res = pytree.tree_leaves(old.meta["fake_result"]) + node_flattened_res = pytree.tree_leaves( + node_to_update.meta["fake_result"] + ) + + old_res_storage = { + StorageWeakRef(x._typed_storage()) + for x in old_flattened_res + if isinstance(x, FakeTensor) + } + node_res_storage = { + StorageWeakRef(x._typed_storage()) + for x in node_flattened_res + if isinstance(x, FakeTensor) + } + + # This will happen if we're updating a view op, e.g. + # e.g. replacing + # x = view(old) + # x = view(new) + # When that happens, we need to make sure to keep our + # storage mapping up to date. + # + # We're checking for len(...) == 1 here because all view ops are guaranteed to return either a single tensor, + # or multiple tensors that all share the same storage. + # We can't just check equality because we might encounter FX nodes that return zero tensor outputs. + if ( + len(old_res_storage) == 1 + and len(node_res_storage) == 1 + and old_res_storage == node_res_storage + ): + new_flattened_res = pytree.tree_leaves(new.meta["fake_result"]) + new_res_storage = { + StorageWeakRef(x._typed_storage()) + for x in new_flattened_res + if isinstance(x, FakeTensor) + } + assert len(new_res_storage) == 1 + (new_ref,) = new_res_storage + (node_ref,) = node_res_storage + # Technically, "old_ref" and all its aliases will remain + # in our mapping. + # That should be fine though, since we deleted "old" + # from the graph at this point. + storage_to_nodes[node_ref].update(storage_to_nodes[new_ref]) + storage_to_nodes[new_ref].update(storage_to_nodes[node_ref]) + + # Step 4: delete any _scatter nodes that we de-functionalized + # Need to take care not to delete any of these nodes until after *all* modifications + # to the graph are finished. + for to_delete in all_later_view_inverse_nodes_to_delete: + gm.graph.erase_node(to_delete) + + gm.recompile() + return gm diff --git a/shared/package-files/26/26eb7be57a5925ca6b6deab0197e321b1ca39dc23998b9f0ace2527b94722865/vec128_convert.h b/shared/package-files/26/26eb7be57a5925ca6b6deab0197e321b1ca39dc23998b9f0ace2527b94722865/vec128_convert.h new file mode 100644 index 0000000000000000000000000000000000000000..4131802c9923d44e168a69aa192f8f4a5b62406f --- /dev/null +++ b/shared/package-files/26/26eb7be57a5925ca6b6deab0197e321b1ca39dc23998b9f0ace2527b94722865/vec128_convert.h @@ -0,0 +1,64 @@ +#pragma once +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { +#if (defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256)) +template +struct VecConvert< + float, + 1, + src_t, + 1, + typename std::enable_if_t, + void>> { + static inline VectorizedN apply(const VectorizedN& src) { + return convert_int8_half_register_to_float(src[0]); + } +}; +template +struct VecConvert< + float, + 2, + src_t, + 1, + typename std::enable_if_t, + void>> { + static inline VectorizedN apply(const VectorizedN& src) { + const auto [v0, v1] = convert_int8_to_float(src[0]); + return VectorizedN(v0, v1); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + uint16x8_t u16_8 = vld1q_u16(reinterpret_cast(&src[0])); + auto u16_low1 = vget_low_u16(u16_8); + auto u16_high1 = vget_high_u16(u16_8); + float32x4_t f32x4_0 = vreinterpretq_f32_u32(vshlq_n_u32(vmovl_u16(u16_low1), 16)); + float32x4_t f32x4_1 = vreinterpretq_f32_u32(vshlq_n_u32(vmovl_u16(u16_high1), 16)); + result[0] = f32x4_0; + result[1] = f32x4_1; + return result; + } +}; +// Half register to full register. +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + uint16x4_t u16_8 = vld1_u16(reinterpret_cast(&src[0])); + float32x4_t f32x4_0 = vreinterpretq_f32_u32(vshlq_n_u32(vmovl_u16(u16_8), 16)); + result[0] = f32x4_0; + return result; + } +}; + +#endif // defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/shared/package-files/26/26ec7c0fb84ece4df8c39c0feecbc3ab96ab30df313b3e00fccd9997a1385492/refine_tuple_types.h b/shared/package-files/26/26ec7c0fb84ece4df8c39c0feecbc3ab96ab30df313b3e00fccd9997a1385492/refine_tuple_types.h new file mode 100644 index 0000000000000000000000000000000000000000..49b8750b72ce8591deca5617654c91ab61d30cb3 --- /dev/null +++ b/shared/package-files/26/26ec7c0fb84ece4df8c39c0feecbc3ab96ab30df313b3e00fccd9997a1385492/refine_tuple_types.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace torch::jit { + +// updates the types of tuples according to the type of their current inputs. +TORCH_API void RefineTupleTypes(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/shared/package-files/26/26f2af5ae14e65075abecbbad2c7aebb3ca4eecc023b9efd4dbd430640f1b6e1/test_version.cpython-311.pyc b/shared/package-files/26/26f2af5ae14e65075abecbbad2c7aebb3ca4eecc023b9efd4dbd430640f1b6e1/test_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..122c49fa0da3f62a7669555331171a84b4a8871e Binary files /dev/null and b/shared/package-files/26/26f2af5ae14e65075abecbbad2c7aebb3ca4eecc023b9efd4dbd430640f1b6e1/test_version.cpython-311.pyc differ diff --git a/shared/package-files/26/26f3e7f80007ce7e7739d01a939ed0457ca43290e52d2126f47c6086058fc641/test_append.cpython-311.pyc b/shared/package-files/26/26f3e7f80007ce7e7739d01a939ed0457ca43290e52d2126f47c6086058fc641/test_append.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd6b26cb710e88658c4a9a90c20d6a003858c0fb Binary files /dev/null and b/shared/package-files/26/26f3e7f80007ce7e7739d01a939ed0457ca43290e52d2126f47c6086058fc641/test_append.cpython-311.pyc differ diff --git a/shared/package-files/26/26f5aff48a363c0b98c04130d9f056e1073962f75b92c729297d6498bceca079/PKG-INFO b/shared/package-files/26/26f5aff48a363c0b98c04130d9f056e1073962f75b92c729297d6498bceca079/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..7328e3f7d18d31422d13b4fd63a7ef746956b7db --- /dev/null +++ b/shared/package-files/26/26f5aff48a363c0b98c04130d9f056e1073962f75b92c729297d6498bceca079/PKG-INFO @@ -0,0 +1,10 @@ +Metadata-Version: 1.0 +Name: my-test-package +Version: 1.0 +Summary: UNKNOWN +Home-page: UNKNOWN +Author: UNKNOWN +Author-email: UNKNOWN +License: UNKNOWN +Description: UNKNOWN +Platform: UNKNOWN diff --git a/shared/package-files/26/26f75982260d24d784eb22d5c9114ea068d56dfae5e1cfa402510fcc122218cf/conftest.py b/shared/package-files/26/26f75982260d24d784eb22d5c9114ea068d56dfae5e1cfa402510fcc122218cf/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..53b54bb494da6274b72bc32ce360ea0e56bd34b9 --- /dev/null +++ b/shared/package-files/26/26f75982260d24d784eb22d5c9114ea068d56dfae5e1cfa402510fcc122218cf/conftest.py @@ -0,0 +1,331 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import functools +import os +import pathlib +import subprocess +import sys +import time +import urllib.request + +import pytest +import hypothesis as h + +from ..conftest import groups, defaults + +from pyarrow import set_timezone_db_path +from pyarrow.util import find_free_port + + +# setup hypothesis profiles +h.settings.register_profile('ci', max_examples=1000) +h.settings.register_profile('dev', max_examples=50) +h.settings.register_profile('debug', max_examples=10, + verbosity=h.Verbosity.verbose) + +# load default hypothesis profile, either set HYPOTHESIS_PROFILE environment +# variable or pass --hypothesis-profile option to pytest, to see the generated +# examples try: +# pytest pyarrow -sv --enable-hypothesis --hypothesis-profile=debug +h.settings.load_profile(os.environ.get('HYPOTHESIS_PROFILE', 'dev')) + +# Set this at the beginning before the AWS SDK was loaded to avoid reading in +# user configuration values. +os.environ['AWS_CONFIG_FILE'] = "/dev/null" + + +if sys.platform == 'win32': + tzdata_set_path = os.environ.get('PYARROW_TZDATA_PATH', None) + if tzdata_set_path: + set_timezone_db_path(tzdata_set_path) + + +# GH-45295: For ORC, try to populate TZDIR env var from tzdata package resource +# path. +# +# Note this is a different kind of database than what we allow to be set by +# `PYARROW_TZDATA_PATH` and passed to set_timezone_db_path. +if sys.platform == 'win32': + if os.environ.get('TZDIR', None) is None: + from importlib import resources + try: + os.environ['TZDIR'] = os.path.join(resources.files('tzdata'), 'zoneinfo') + except ModuleNotFoundError: + print( + 'Package "tzdata" not found. Not setting TZDIR environment variable.' + ) + + +def pytest_addoption(parser): + # Create options to selectively enable test groups + def bool_env(name, default=None): + value = os.environ.get(name.upper()) + if not value: # missing or empty + return default + value = value.lower() + if value in {'1', 'true', 'on', 'yes', 'y'}: + return True + elif value in {'0', 'false', 'off', 'no', 'n'}: + return False + else: + raise ValueError('{}={} is not parsable as boolean' + .format(name.upper(), value)) + + for group in groups: + default = bool_env('PYARROW_TEST_{}'.format(group), defaults[group]) + parser.addoption('--enable-{}'.format(group), + action='store_true', default=default, + help=('Enable the {} test group'.format(group))) + parser.addoption('--disable-{}'.format(group), + action='store_true', default=False, + help=('Disable the {} test group'.format(group))) + + +class PyArrowConfig: + def __init__(self): + self.is_enabled = {} + + def apply_mark(self, mark): + group = mark.name + if group in groups: + self.requires(group) + + def requires(self, group): + if not self.is_enabled[group]: + pytest.skip('{} NOT enabled'.format(group)) + + +def pytest_configure(config): + # Apply command-line options to initialize PyArrow-specific config object + config.pyarrow = PyArrowConfig() + + for mark in groups: + config.addinivalue_line( + "markers", mark, + ) + + enable_flag = '--enable-{}'.format(mark) + disable_flag = '--disable-{}'.format(mark) + + is_enabled = (config.getoption(enable_flag) and not + config.getoption(disable_flag)) + config.pyarrow.is_enabled[mark] = is_enabled + + +def pytest_runtest_setup(item): + # Apply test markers to skip tests selectively + for mark in item.iter_markers(): + item.config.pyarrow.apply_mark(mark) + + +@pytest.fixture +def tempdir(tmpdir): + # convert pytest's LocalPath to pathlib.Path + return pathlib.Path(tmpdir.strpath) + + +@pytest.fixture(scope='session') +def base_datadir(): + return pathlib.Path(__file__).parent / 'data' + + +@pytest.fixture(autouse=True) +def disable_aws_metadata(monkeypatch): + """Stop the AWS SDK from trying to contact the EC2 metadata server. + + Otherwise, this causes a 5 second delay in tests that exercise the + S3 filesystem. + """ + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + + +# TODO(kszucs): move the following fixtures to test_fs.py once the previous +# parquet dataset implementation and hdfs implementation are removed. + +@pytest.fixture(scope='session') +def hdfs_connection(): + host = os.environ.get('ARROW_HDFS_TEST_HOST', 'default') + port = int(os.environ.get('ARROW_HDFS_TEST_PORT', 0)) + user = os.environ.get('ARROW_HDFS_TEST_USER', 'hdfs') + return host, port, user + + +@pytest.fixture(scope='session') +def s3_connection(): + host, port = '127.0.0.1', find_free_port() + access_key, secret_key = 'arrow', 'apachearrow' + return host, port, access_key, secret_key + + +def retry(attempts=3, delay=1.0, max_delay=None, backoff=1): + """ + Retry decorator + + Parameters + ---------- + attempts : int, default 3 + The number of attempts. + delay : float, default 1 + Initial delay in seconds. + max_delay : float, optional + The max delay between attempts. + backoff : float, default 1 + The multiplier to delay after each attempt. + """ + def decorate(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + remaining_attempts = attempts + curr_delay = delay + while remaining_attempts > 0: + try: + return func(*args, **kwargs) + except Exception as err: + remaining_attempts -= 1 + last_exception = err + curr_delay *= backoff + if max_delay: + curr_delay = min(curr_delay, max_delay) + time.sleep(curr_delay) + raise last_exception + return wrapper + return decorate + + +@pytest.fixture(scope='session') +def s3_server(s3_connection, tmpdir_factory): + @retry(attempts=5, delay=1, backoff=2) + def minio_server_health_check(address): + resp = urllib.request.urlopen(f"http://{address}/minio/health/live") + assert resp.getcode() == 200 + + tmpdir = tmpdir_factory.getbasetemp() + host, port, access_key, secret_key = s3_connection + + address = '{}:{}'.format(host, port) + env = os.environ.copy() + env.update({ + 'MINIO_ACCESS_KEY': access_key, + 'MINIO_SECRET_KEY': secret_key + }) + + args = ['minio', '--compat', 'server', '--quiet', '--address', + address, tmpdir] + proc = None + try: + proc = subprocess.Popen(args, env=env) + except OSError: + pytest.skip('`minio` command cannot be located') + else: + # Wait for the server to startup before yielding + minio_server_health_check(address) + + yield { + 'connection': s3_connection, + 'process': proc, + 'tempdir': tmpdir + } + finally: + if proc is not None: + proc.kill() + proc.wait() + + +@pytest.fixture(scope='session') +def gcs_server(): + port = find_free_port() + env = os.environ.copy() + exe = 'storage-testbench' + args = [exe, '--port', str(port)] + proc = None + try: + # start server + proc = subprocess.Popen(args, env=env) + # Make sure the server is alive. + if proc.poll() is not None: + pytest.skip(f"Command {args} did not start server successfully!") + except OSError as e: + pytest.skip(f"Command {args} failed to execute: {e}") + else: + yield { + 'connection': ('localhost', port), + 'process': proc, + } + finally: + if proc is not None: + proc.kill() + proc.wait() + + +@pytest.fixture(scope='session') +def azure_server(tmpdir_factory): + port = find_free_port() + env = os.environ.copy() + tmpdir = tmpdir_factory.getbasetemp() + # We only need blob service emulator, not queue or table. + args = ['azurite-blob', "--location", tmpdir, "--blobPort", str(port)] + # For old Azurite. We can't install the latest Azurite with old + # Node.js on old Ubuntu. + args += ["--skipApiVersionCheck"] + proc = None + try: + proc = subprocess.Popen(args, env=env) + # Make sure the server is alive. + if proc.poll() is not None: + pytest.skip(f"Command {args} did not start server successfully!") + except (ModuleNotFoundError, OSError) as e: + pytest.skip(f"Command {args} failed to execute: {e}") + else: + yield { + # Use the standard azurite account_name and account_key. + # https://learn.microsoft.com/en-us/azure/storage/common/storage-use-emulator#authorize-with-shared-key-credentials + 'connection': ('127.0.0.1', port, 'devstoreaccount1', + 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2' + 'UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=='), + 'process': proc, + 'tempdir': tmpdir, + } + finally: + if proc is not None: + proc.kill() + proc.wait() + + +@pytest.fixture( + params=[ + 'builtin_pickle', + 'cloudpickle' + ], + scope='session' +) +def pickle_module(request): + return request.getfixturevalue(request.param) + + +@pytest.fixture(scope='session') +def builtin_pickle(): + import pickle + return pickle + + +@pytest.fixture(scope='session') +def cloudpickle(): + cp = pytest.importorskip('cloudpickle') + if 'HIGHEST_PROTOCOL' not in cp.__dict__: + cp.HIGHEST_PROTOCOL = cp.DEFAULT_PROTOCOL + return cp diff --git a/shared/package-files/26/26f76d3aeae01cfee24b080f7a386233bd3f8be5eae9fbb982b8bae1a659f61b/version.py b/shared/package-files/26/26f76d3aeae01cfee24b080f7a386233bd3f8be5eae9fbb982b8bae1a659f61b/version.py new file mode 100644 index 0000000000000000000000000000000000000000..11a922533cf6579650e4f3e8accad7a800678fea --- /dev/null +++ b/shared/package-files/26/26f76d3aeae01cfee24b080f7a386233bd3f8be5eae9fbb982b8bae1a659f61b/version.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2014 Yahoo! Inc. All Rights Reserved. +# Copyright 2011 OpenStack Foundation. +# +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +_VERSION = "0.20" + + +def version_string(): + return _VERSION diff --git a/shared/package-files/26/26feb7f230b1c9550d8cad9916b25dfb2d1b04d31421ec524a3064afd6811df6/conv.cpython-311.pyc b/shared/package-files/26/26feb7f230b1c9550d8cad9916b25dfb2d1b04d31421ec524a3064afd6811df6/conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e0ee80229529e757b4d4fda13175d2b281e94d0 Binary files /dev/null and b/shared/package-files/26/26feb7f230b1c9550d8cad9916b25dfb2d1b04d31421ec524a3064afd6811df6/conv.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c003874bfc09c0d1c3ff89222654e78c8d0d631e61f897e456a97a8bea9bdfb/__init__.cpython-311.pyc b/shared/package-files/2c/2c003874bfc09c0d1c3ff89222654e78c8d0d631e61f897e456a97a8bea9bdfb/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..827d75759822a7eeb67afbf11eeafe9355b69ae7 Binary files /dev/null and b/shared/package-files/2c/2c003874bfc09c0d1c3ff89222654e78c8d0d631e61f897e456a97a8bea9bdfb/__init__.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c08b8ecf6e924652fa12dd339b340cc0de6ce429b442b3c980d175ae4cf2413/ScalarOps.h b/shared/package-files/2c/2c08b8ecf6e924652fa12dd339b340cc0de6ce429b442b3c980d175ae4cf2413/ScalarOps.h new file mode 100644 index 0000000000000000000000000000000000000000..ed591955dd876bd147218e706eb16ec17c34dd90 --- /dev/null +++ b/shared/package-files/2c/2c08b8ecf6e924652fa12dd339b340cc0de6ce429b442b3c980d175ae4cf2413/ScalarOps.h @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::detail { +// When filling a number to 1-element CPU tensor, we want to skip +// everything but manipulate data ptr directly. +// Ideally this fast pass should be implemented in TensorIterator, +// but we also want to skip compute_types which in not avoidable +// in TensorIterator for now. +Tensor& scalar_fill(Tensor& self, const Scalar& value); +TORCH_API Tensor scalar_tensor_static( + const Scalar& s, + std::optional dtype_opt, + std::optional device_opt); +} // namespace at::detail + +// This is in the c10 namespace because we use ADL to find the functions in it. +namespace c10 { + +// FIXME: this should be (and was) Scalar::toTensor, but there is currently no +// way to implement this without going through Derived Types (which are not part +// of core). +inline at::Tensor scalar_to_tensor( + const Scalar& s, + const Device device = at::kCPU) { + // This is the fast track we have for CPU scalar tensors. + if (device == at::kCPU) { + return at::detail::scalar_tensor_static(s, s.type(), at::kCPU); + } + return at::scalar_tensor(s, at::device(device).dtype(s.type())); +} + +} // namespace c10 + +namespace at::native { + +inline Tensor wrapped_scalar_tensor( + const Scalar& scalar, + const Device device = at::kCPU) { + auto tensor = scalar_to_tensor(scalar, device); + tensor.unsafeGetTensorImpl()->set_wrapped_number(true); + return tensor; +} + +} // namespace at::native diff --git a/shared/package-files/2c/2c0b929bfb631d0969ff4a1e90d735e0d09b8f681e8b8451f63a308dbfeeeb9a/test_other.py b/shared/package-files/2c/2c0b929bfb631d0969ff4a1e90d735e0d09b8f681e8b8451f63a308dbfeeeb9a/test_other.py new file mode 100644 index 0000000000000000000000000000000000000000..00136e572288e9858412fd9d84e3ee48dc52a09c --- /dev/null +++ b/shared/package-files/2c/2c0b929bfb631d0969ff4a1e90d735e0d09b8f681e8b8451f63a308dbfeeeb9a/test_other.py @@ -0,0 +1,675 @@ +""" +test all other .agg behavior +""" + +import datetime as dt +from functools import partial + +import numpy as np +import pytest + +from pandas.errors import SpecificationError + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + PeriodIndex, + Series, + date_range, + period_range, +) +import pandas._testing as tm + +from pandas.io.formats.printing import pprint_thing + + +def test_agg_partial_failure_raises(): + # GH#43741 + + df = DataFrame( + { + "data1": np.random.default_rng(2).standard_normal(5), + "data2": np.random.default_rng(2).standard_normal(5), + "key1": ["a", "a", "b", "b", "a"], + "key2": ["one", "two", "one", "two", "one"], + } + ) + grouped = df.groupby("key1") + + def peak_to_peak(arr): + return arr.max() - arr.min() + + with pytest.raises(TypeError, match="unsupported operand type"): + grouped.agg([peak_to_peak]) + + with pytest.raises(TypeError, match="unsupported operand type"): + grouped.agg(peak_to_peak) + + +def test_agg_datetimes_mixed(): + data = [[1, "2012-01-01", 1.0], [2, "2012-01-02", 2.0], [3, None, 3.0]] + + df1 = DataFrame( + { + "key": [x[0] for x in data], + "date": [x[1] for x in data], + "value": [x[2] for x in data], + } + ) + + data = [ + [ + row[0], + (dt.datetime.strptime(row[1], "%Y-%m-%d").date() if row[1] else None), + row[2], + ] + for row in data + ] + + df2 = DataFrame( + { + "key": [x[0] for x in data], + "date": [x[1] for x in data], + "value": [x[2] for x in data], + } + ) + + df1["weights"] = df1["value"] / df1["value"].sum() + gb1 = df1.groupby("date").aggregate("sum") + + df2["weights"] = df1["value"] / df1["value"].sum() + gb2 = df2.groupby("date").aggregate("sum") + + assert len(gb1) == len(gb2) + + +def test_agg_period_index(): + prng = period_range("2012-1-1", freq="M", periods=3) + df = DataFrame(np.random.default_rng(2).standard_normal((3, 2)), index=prng) + rs = df.groupby(level=0).sum() + assert isinstance(rs.index, PeriodIndex) + + # GH 3579 + index = period_range(start="1999-01", periods=5, freq="M") + s1 = Series(np.random.default_rng(2).random(len(index)), index=index) + s2 = Series(np.random.default_rng(2).random(len(index)), index=index) + df = DataFrame.from_dict({"s1": s1, "s2": s2}) + grouped = df.groupby(df.index.month) + list(grouped) + + +def test_agg_dict_parameter_cast_result_dtypes(): + # GH 12821 + + df = DataFrame( + { + "class": ["A", "A", "B", "B", "C", "C", "D", "D"], + "time": date_range("1/1/2011", periods=8, freq="h"), + } + ) + df.loc[[0, 1, 2, 5], "time"] = None + + # test for `first` function + exp = df.loc[[0, 3, 4, 6]].set_index("class") + grouped = df.groupby("class") + tm.assert_frame_equal(grouped.first(), exp) + tm.assert_frame_equal(grouped.agg("first"), exp) + tm.assert_frame_equal(grouped.agg({"time": "first"}), exp) + tm.assert_series_equal(grouped.time.first(), exp["time"]) + tm.assert_series_equal(grouped.time.agg("first"), exp["time"]) + + # test for `last` function + exp = df.loc[[0, 3, 4, 7]].set_index("class") + grouped = df.groupby("class") + tm.assert_frame_equal(grouped.last(), exp) + tm.assert_frame_equal(grouped.agg("last"), exp) + tm.assert_frame_equal(grouped.agg({"time": "last"}), exp) + tm.assert_series_equal(grouped.time.last(), exp["time"]) + tm.assert_series_equal(grouped.time.agg("last"), exp["time"]) + + # count + exp = Series([2, 2, 2, 2], index=Index(list("ABCD"), name="class"), name="time") + tm.assert_series_equal(grouped.time.agg(len), exp) + tm.assert_series_equal(grouped.time.size(), exp) + + exp = Series([0, 1, 1, 2], index=Index(list("ABCD"), name="class"), name="time") + tm.assert_series_equal(grouped.time.count(), exp) + + +def test_agg_cast_results_dtypes(): + # similar to GH12821 + # xref #11444 + u = [dt.datetime(2015, x + 1, 1) for x in range(12)] + v = list("aaabbbbbbccd") + df = DataFrame({"X": v, "Y": u}) + + result = df.groupby("X")["Y"].agg(len) + expected = df.groupby("X")["Y"].count() + tm.assert_series_equal(result, expected) + + +def test_aggregate_float64_no_int64(): + # see gh-11199 + df = DataFrame({"a": [1, 2, 3, 4, 5], "b": [1, 2, 2, 4, 5], "c": [1, 2, 3, 4, 5]}) + + expected = DataFrame({"a": [1, 2.5, 4, 5]}, index=[1, 2, 4, 5]) + expected.index.name = "b" + + result = df.groupby("b")[["a"]].mean() + tm.assert_frame_equal(result, expected) + + expected = DataFrame({"a": [1, 2.5, 4, 5], "c": [1, 2.5, 4, 5]}, index=[1, 2, 4, 5]) + expected.index.name = "b" + + result = df.groupby("b")[["a", "c"]].mean() + tm.assert_frame_equal(result, expected) + + +def test_aggregate_api_consistency(): + # GH 9052 + # make sure that the aggregates via dict + # are consistent + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": np.random.default_rng(2).standard_normal(8) + 1.0, + "D": np.arange(8), + } + ) + + grouped = df.groupby(["A", "B"]) + c_mean = grouped["C"].mean() + c_sum = grouped["C"].sum() + d_mean = grouped["D"].mean() + d_sum = grouped["D"].sum() + + result = grouped["D"].agg(["sum", "mean"]) + expected = pd.concat([d_sum, d_mean], axis=1) + expected.columns = ["sum", "mean"] + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg(["sum", "mean"]) + expected = pd.concat([c_sum, c_mean, d_sum, d_mean], axis=1) + expected.columns = MultiIndex.from_product([["C", "D"], ["sum", "mean"]]) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped[["D", "C"]].agg(["sum", "mean"]) + expected = pd.concat([d_sum, d_mean, c_sum, c_mean], axis=1) + expected.columns = MultiIndex.from_product([["D", "C"], ["sum", "mean"]]) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg({"C": "mean", "D": "sum"}) + expected = pd.concat([d_sum, c_mean], axis=1) + tm.assert_frame_equal(result, expected, check_like=True) + + result = grouped.agg({"C": ["mean", "sum"], "D": ["mean", "sum"]}) + expected = pd.concat([c_mean, c_sum, d_mean, d_sum], axis=1) + expected.columns = MultiIndex.from_product([["C", "D"], ["mean", "sum"]]) + + msg = r"Column\(s\) \['r', 'r2'\] do not exist" + with pytest.raises(KeyError, match=msg): + grouped[["D", "C"]].agg({"r": "sum", "r2": "mean"}) + + +def test_agg_dict_renaming_deprecation(): + # 15931 + df = DataFrame({"A": [1, 1, 1, 2, 2], "B": range(5), "C": range(5)}) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").agg( + {"B": {"foo": ["sum", "max"]}, "C": {"bar": ["count", "min"]}} + ) + + msg = r"Column\(s\) \['ma'\] do not exist" + with pytest.raises(KeyError, match=msg): + df.groupby("A")[["B", "C"]].agg({"ma": "max"}) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").B.agg({"foo": "count"}) + + +def test_agg_compat(): + # GH 12334 + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": np.random.default_rng(2).standard_normal(8) + 1.0, + "D": np.arange(8), + } + ) + + g = df.groupby(["A", "B"]) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"C": ["sum", "std"]}) + + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"C": "sum", "D": "std"}) + + +def test_agg_nested_dicts(): + # API change for disallowing these types of nested dicts + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": np.random.default_rng(2).standard_normal(8) + 1.0, + "D": np.arange(8), + } + ) + + g = df.groupby(["A", "B"]) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + g.aggregate({"r1": {"C": ["mean", "sum"]}, "r2": {"D": ["mean", "sum"]}}) + + with pytest.raises(SpecificationError, match=msg): + g.agg({"C": {"ra": ["mean", "std"]}, "D": {"rb": ["mean", "std"]}}) + + # same name as the original column + # GH9052 + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"result1": np.sum, "result2": np.mean}) + + with pytest.raises(SpecificationError, match=msg): + g["D"].agg({"D": np.sum, "result2": np.mean}) + + +def test_agg_item_by_item_raise_typeerror(): + df = DataFrame(np.random.default_rng(2).integers(10, size=(20, 10))) + + def raiseException(df): + pprint_thing("----------------------------------------") + pprint_thing(df.to_string()) + raise TypeError("test") + + with pytest.raises(TypeError, match="test"): + df.groupby(0).agg(raiseException) + + +def test_series_agg_multikey(): + ts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) + + result = grouped.agg("sum") + expected = grouped.sum() + tm.assert_series_equal(result, expected) + + +def test_series_agg_multi_pure_python(): + data = DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "C": [ + "dull", + "dull", + "shiny", + "dull", + "dull", + "shiny", + "shiny", + "dull", + "shiny", + "shiny", + "shiny", + ], + "D": np.random.default_rng(2).standard_normal(11), + "E": np.random.default_rng(2).standard_normal(11), + "F": np.random.default_rng(2).standard_normal(11), + } + ) + + def bad(x): + assert len(x.values.base) > 0 + return "foo" + + result = data.groupby(["A", "B"]).agg(bad) + expected = data.groupby(["A", "B"]).agg(lambda x: "foo") + tm.assert_frame_equal(result, expected) + + +def test_agg_consistency(): + # agg with ([]) and () not consistent + # GH 6715 + def P1(a): + return np.percentile(a.dropna(), q=1) + + df = DataFrame( + { + "col1": [1, 2, 3, 4], + "col2": [10, 25, 26, 31], + "date": [ + dt.date(2013, 2, 10), + dt.date(2013, 2, 10), + dt.date(2013, 2, 11), + dt.date(2013, 2, 11), + ], + } + ) + + g = df.groupby("date") + + expected = g.agg([P1]) + expected.columns = expected.columns.levels[0] + + result = g.agg(P1) + tm.assert_frame_equal(result, expected) + + +def test_agg_callables(): + # GH 7929 + df = DataFrame({"foo": [1, 2], "bar": [3, 4]}).astype(np.int64) + + class fn_class: + def __call__(self, x): + return sum(x) + + equiv_callables = [ + sum, + np.sum, + lambda x: sum(x), + lambda x: x.sum(), + partial(sum), + fn_class(), + ] + + expected = df.groupby("foo").agg("sum") + for ecall in equiv_callables: + warn = FutureWarning if ecall is sum or ecall is np.sum else None + msg = "using DataFrameGroupBy.sum" + with tm.assert_produces_warning(warn, match=msg): + result = df.groupby("foo").agg(ecall) + tm.assert_frame_equal(result, expected) + + +def test_agg_over_numpy_arrays(): + # GH 3788 + df = DataFrame( + [ + [1, np.array([10, 20, 30])], + [1, np.array([40, 50, 60])], + [2, np.array([20, 30, 40])], + ], + columns=["category", "arraydata"], + ) + gb = df.groupby("category") + + expected_data = [[np.array([50, 70, 90])], [np.array([20, 30, 40])]] + expected_index = Index([1, 2], name="category") + expected_column = ["arraydata"] + expected = DataFrame(expected_data, index=expected_index, columns=expected_column) + + alt = gb.sum(numeric_only=False) + tm.assert_frame_equal(alt, expected) + + result = gb.agg("sum", numeric_only=False) + tm.assert_frame_equal(result, expected) + + # FIXME: the original version of this test called `gb.agg(sum)` + # and that raises TypeError if `numeric_only=False` is passed + + +@pytest.mark.parametrize("as_period", [True, False]) +def test_agg_tzaware_non_datetime_result(as_period): + # discussed in GH#29589, fixed in GH#29641, operating on tzaware values + # with function that is not dtype-preserving + dti = date_range("2012-01-01", periods=4, tz="UTC") + if as_period: + dti = dti.tz_localize(None).to_period("D") + + df = DataFrame({"a": [0, 0, 1, 1], "b": dti}) + gb = df.groupby("a") + + # Case that _does_ preserve the dtype + result = gb["b"].agg(lambda x: x.iloc[0]) + expected = Series(dti[::2], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + # Cases that do _not_ preserve the dtype + result = gb["b"].agg(lambda x: x.iloc[0].year) + expected = Series([2012, 2012], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + result = gb["b"].agg(lambda x: x.iloc[-1] - x.iloc[0]) + expected = Series([pd.Timedelta(days=1), pd.Timedelta(days=1)], name="b") + expected.index.name = "a" + if as_period: + expected = Series([pd.offsets.Day(1), pd.offsets.Day(1)], name="b") + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + +def test_agg_timezone_round_trip(): + # GH 15426 + ts = pd.Timestamp("2016-01-01 12:00:00", tz="US/Pacific") + df = DataFrame({"a": 1, "b": [ts + dt.timedelta(minutes=nn) for nn in range(10)]}) + + result1 = df.groupby("a")["b"].agg("min").iloc[0] + result2 = df.groupby("a")["b"].agg(lambda x: np.min(x)).iloc[0] + result3 = df.groupby("a")["b"].min().iloc[0] + + assert result1 == ts + assert result2 == ts + assert result3 == ts + + dates = [ + pd.Timestamp(f"2016-01-0{i:d} 12:00:00", tz="US/Pacific") for i in range(1, 5) + ] + df = DataFrame({"A": ["a", "b"] * 2, "B": dates}) + grouped = df.groupby("A") + + ts = df["B"].iloc[0] + assert ts == grouped.nth(0)["B"].iloc[0] + assert ts == grouped.head(1)["B"].iloc[0] + assert ts == grouped.first()["B"].iloc[0] + + # GH#27110 applying iloc should return a DataFrame + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert ts == grouped.apply(lambda x: x.iloc[0]).iloc[0, 1] + + ts = df["B"].iloc[2] + assert ts == grouped.last()["B"].iloc[0] + + # GH#27110 applying iloc should return a DataFrame + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert ts == grouped.apply(lambda x: x.iloc[-1]).iloc[0, 1] + + +def test_sum_uint64_overflow(): + # see gh-14758 + # Convert to uint64 and don't overflow + df = DataFrame([[1, 2], [3, 4], [5, 6]], dtype=object) + df = df + 9223372036854775807 + + index = Index( + [9223372036854775808, 9223372036854775810, 9223372036854775812], dtype=np.uint64 + ) + expected = DataFrame( + {1: [9223372036854775809, 9223372036854775811, 9223372036854775813]}, + index=index, + dtype=object, + ) + + expected.index.name = 0 + result = df.groupby(0).sum(numeric_only=False) + tm.assert_frame_equal(result, expected) + + # out column is non-numeric, so with numeric_only=True it is dropped + result2 = df.groupby(0).sum(numeric_only=True) + expected2 = expected[[]] + tm.assert_frame_equal(result2, expected2) + + +@pytest.mark.parametrize( + "structure, expected", + [ + (tuple, DataFrame({"C": {(1, 1): (1, 1, 1), (3, 4): (3, 4, 4)}})), + (list, DataFrame({"C": {(1, 1): [1, 1, 1], (3, 4): [3, 4, 4]}})), + ( + lambda x: tuple(x), + DataFrame({"C": {(1, 1): (1, 1, 1), (3, 4): (3, 4, 4)}}), + ), + ( + lambda x: list(x), + DataFrame({"C": {(1, 1): [1, 1, 1], (3, 4): [3, 4, 4]}}), + ), + ], +) +def test_agg_structs_dataframe(structure, expected): + df = DataFrame( + {"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]} + ) + + result = df.groupby(["A", "B"]).aggregate(structure) + expected.index.names = ["A", "B"] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "structure, expected", + [ + (tuple, Series([(1, 1, 1), (3, 4, 4)], index=[1, 3], name="C")), + (list, Series([[1, 1, 1], [3, 4, 4]], index=[1, 3], name="C")), + (lambda x: tuple(x), Series([(1, 1, 1), (3, 4, 4)], index=[1, 3], name="C")), + (lambda x: list(x), Series([[1, 1, 1], [3, 4, 4]], index=[1, 3], name="C")), + ], +) +def test_agg_structs_series(structure, expected): + # Issue #18079 + df = DataFrame( + {"A": [1, 1, 1, 3, 3, 3], "B": [1, 1, 1, 4, 4, 4], "C": [1, 1, 1, 3, 4, 4]} + ) + + result = df.groupby("A")["C"].aggregate(structure) + expected.index.name = "A" + tm.assert_series_equal(result, expected) + + +def test_agg_category_nansum(observed): + categories = ["a", "b", "c"] + df = DataFrame( + {"A": pd.Categorical(["a", "a", "b"], categories=categories), "B": [1, 2, 3]} + ) + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A", observed=observed).B.agg(np.nansum) + expected = Series( + [3, 3, 0], + index=pd.CategoricalIndex(["a", "b", "c"], categories=categories, name="A"), + name="B", + ) + if observed: + expected = expected[expected != 0] + tm.assert_series_equal(result, expected) + + +def test_agg_list_like_func(): + # GH 18473 + df = DataFrame({"A": [str(x) for x in range(3)], "B": [str(x) for x in range(3)]}) + grouped = df.groupby("A", as_index=False, sort=False) + result = grouped.agg({"B": lambda x: list(x)}) + expected = DataFrame( + {"A": [str(x) for x in range(3)], "B": [[str(x)] for x in range(3)]} + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_lambda_with_timezone(): + # GH 23683 + df = DataFrame( + { + "tag": [1, 1], + "date": [ + pd.Timestamp("2018-01-01", tz="UTC"), + pd.Timestamp("2018-01-02", tz="UTC"), + ], + } + ) + result = df.groupby("tag").agg({"date": lambda e: e.head(1)}) + expected = DataFrame( + [pd.Timestamp("2018-01-01", tz="UTC")], + index=Index([1], name="tag"), + columns=["date"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "err_cls", + [ + NotImplementedError, + RuntimeError, + KeyError, + IndexError, + OSError, + ValueError, + ArithmeticError, + AttributeError, + ], +) +def test_groupby_agg_err_catching(err_cls): + # make sure we suppress anything other than TypeError or AssertionError + # in _python_agg_general + + # Use a non-standard EA to make sure we don't go down ndarray paths + from pandas.tests.extension.decimal.array import ( + DecimalArray, + make_data, + to_decimal, + ) + + data = make_data()[:5] + df = DataFrame( + {"id1": [0, 0, 0, 1, 1], "id2": [0, 1, 0, 1, 1], "decimals": DecimalArray(data)} + ) + + expected = Series(to_decimal([data[0], data[3]])) + + def weird_func(x): + # weird function that raise something other than TypeError or IndexError + # in _python_agg_general + if len(x) == 0: + raise err_cls + return x.iloc[0] + + result = df["decimals"].groupby(df["id1"]).agg(weird_func) + tm.assert_series_equal(result, expected, check_names=False) diff --git a/shared/package-files/2c/2c158a191815b8704fd5df591b632e3422dfee5db9c8e875c9c47070f169e6d3/_sfdp_pattern_10.cpython-311.pyc b/shared/package-files/2c/2c158a191815b8704fd5df591b632e3422dfee5db9c8e875c9c47070f169e6d3/_sfdp_pattern_10.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5173357e6251a1b1cb937d2c2fed3666c9f94b56 Binary files /dev/null and b/shared/package-files/2c/2c158a191815b8704fd5df591b632e3422dfee5db9c8e875c9c47070f169e6d3/_sfdp_pattern_10.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c18d3973b8acb9217efca46cb0b757ae7f2add02dbc9bfd4a85943f6dea4701/supported_ops.py b/shared/package-files/2c/2c18d3973b8acb9217efca46cb0b757ae7f2add02dbc9bfd4a85943f6dea4701/supported_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..791a11a9b3aa7dcac62cc3a2c129985abaf85bc1 --- /dev/null +++ b/shared/package-files/2c/2c18d3973b8acb9217efca46cb0b757ae7f2add02dbc9bfd4a85943f6dea4701/supported_ops.py @@ -0,0 +1,344 @@ +# mypy: allow-untyped-defs +import inspect +import textwrap + +import torch.jit +from torch.jit._builtins import _find_builtin + + +# this file is for generating documentation using sphinx autodoc +# > help(torch.jit.supported_ops) will also give a nice listed of the +# supported ops programmatically + + +def _hidden(name): + return name.startswith("_") and not name.startswith("__") + + +def _emit_type(type): + return str(type) + + +def _emit_arg(indent, i, arg): + v = f"{arg.name} : {_emit_type(arg.type)}" + default = arg.default_value + if default is not None: + v = f"{v}={str(default)}" + if i > 0: + v = f"\n{' ' * indent}{v}" + return v + + +def _emit_args(indent, arguments): + return ",".join(_emit_arg(indent, i, arg) for i, arg in enumerate(arguments)) + + +def _emit_ret(ret): + return _emit_type(ret.type) + + +def _emit_rets(returns): + if len(returns) == 1: + return _emit_ret(returns[0]) + return f"Tuple[{', '.join(_emit_ret(r) for r in returns)}]" + + +def _emit_schema(mod, name, schema, arg_start=0, padding=4): + if mod is None: + qualified_name = name + else: + qualified_name = f"{mod}.{name}" + schema_str = ( + f"{qualified_name}" + f"({_emit_args(len(qualified_name) + 1 + padding, schema.arguments[arg_start:])}) " + f"-> {_emit_rets(schema.returns)}" + ) + return schema_str + + +def _get_tensor_ops(): + def is_tensor_method(schema): + if len(schema.arguments) == 0: + return False + self = schema.arguments[0] + if self.name != "self": + return False + if not self.type.isSubtypeOf(torch._C.TensorType.get()): + return False + return True + + methods = [] + # discover methods + for elem in dir(torch.Tensor): + if not _hidden(elem): + schemas = torch._C._jit_get_schemas_for_operator("aten::" + elem) + for schema in schemas: + if is_tensor_method(schema): + methods.append(_emit_schema("Tensor", elem, schema, arg_start=1)) + + return "Supported Tensor Methods", methods + + +def _get_nn_functional_ops(): + functions = [] + + # Iterate over torch.nn.functional + mod = torch.nn.functional + name = mod.__name__ + for elem in dir(torch.nn.functional): + attr = getattr(mod, elem) + if not inspect.isfunction(attr) or _hidden(elem[0]): + # Ignore non-functions and internal methods + continue + + attr_module = inspect.getmodule(attr) + if not attr_module: + raise RuntimeError(f"Module for {attr} not found") + + if "torch.nn.functional" not in attr_module.__name__: + # Ignore functions from outside torch.nn.functional + continue + + try: + # compile fn, get schema + scripted = torch.jit.script(attr) + scripted_schema = scripted.schema + functions.append(_emit_schema(name, elem, scripted_schema)) + except: # noqa: B001,E722 + # Skip interpolate / boolean dispatched things + pass + + # Iterate over modules that we know contain a lot of builtins + for mod in torch.jit._builtins._modules_containing_builtins: + name = mod.__name__ + for elem in dir(mod): + builtin = _find_builtin(getattr(mod, elem)) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + # remove _tan but not __and__ + if not _hidden(elem): + functions.append(_emit_schema(name, elem, schema)) + return "Supported PyTorch Functions", functions + + +def _get_builtins_helper(): + builtins = [] + for fn, _builtin_name in torch.jit._builtins._builtin_ops: + mod = inspect.getmodule(fn) + + if not hasattr(fn, "__name__"): + # typing classes + continue + if not mod: + continue + if _hidden(fn.__name__) or _hidden(fn.__qualname__) or _hidden(mod.__name__): + # skip internal-only methods + continue + + if "torch._C" in mod.__name__: + continue + + builtins.append((fn, _builtin_name)) + + return builtins + + +def _is_math_fn(fn): + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + + return mod.__name__ == "math" + + +def _get_torchscript_builtins(): + functions = [] + builtins = filter(lambda fn: not _is_math_fn(fn[0]), _get_builtins_helper()) + builtins_list = list(builtins) + # Iterate over the specially added builtins + for fn, _builtin_name in builtins_list: + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + builtin = _find_builtin(fn) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + functions.append(_emit_schema(mod.__name__, fn.__name__, schema)) + + return "TorchScript Builtin Functions", functions + + +def _get_math_builtins(): + functions = [] + builtins = filter(lambda fn: _is_math_fn(fn[0]), _get_builtins_helper()) + builtins_list = list(builtins) + # Iterate over the specially added builtins + for fn, _builtin_name in builtins_list: + mod = inspect.getmodule(fn) + if not mod: + raise RuntimeError(f"Module for {fn} not found") + builtin = _find_builtin(fn) + if builtin is not None: + schemas = torch._C._jit_get_schemas_for_operator(builtin) + for schema in schemas: + schema_str = _emit_schema(mod.__name__, fn.__name__, schema) + if "Tensor" in schema_str: + # Skip Tensor ops that have the same name as math functions + # (they will show up in the tensor methods section) + continue + functions.append(schema) + + return "``math`` Module", functions + + +def _get_global_builtins(): + # Taken from the 'globals' map in torch/csrc/jit/frontend/ir_emitter.cpp + supported_builtins = [ + "print", + "tuple", + "float", + "complex", + "int", + "bool", + "str", + "getattr", + "hasattr", + "isinstance", + "len", + "hex", + "oct", + "round", + "hash", + "min", + "max", + "abs", + "all", + "divmod", + "list", + "ord", + "chr", + "bin", + "range", + "zip", + "enumerate", + "sorted", + ] + + op_renames = { + "bool": "aten::Bool", + "int": "aten::Int", + "float": "aten::Float", + "complex": "aten::Complex", + "abs": "prim::abs", + "max": "prim::max", + "min": "prim::min", + "range": "fake::does_not_exist", + } + + schemaless_op_explanations = { + "print": "Print any value", + "tuple": "Lists cannot be converted to tuples with this method since their size is not statically known", + "getattr": "Attribute name must be a literal string", + "hasattr": "Attribute name must be a literal string", + "isinstance": "Result is static", + "zip": "Arguments must be iterable. See :ref:`Iterables ` for details.", + "enumerate": "Arguments must be iterable. See :ref:`Iterables ` for details.", + "range": "Can only be used as an iterator in a for loop", + } + + magic_methods = [ + ("complex", "__complex__"), + ("float", "__float__"), + ("int", "__int__"), + ("bool", "__bool__"), + ("str", "__str__"), + ("len", "__len__"), + ("hex", "__hex__"), + ("oct", "__oct__"), + ] + + magic_methods_rows = [] + for fn, magic_method in magic_methods: + magic_methods_rows.append(f'"{fn}", "``{magic_method}``"') + + schematized_ops = [] + schemaless_ops = [] + + for fn in supported_builtins: + op_name = f"aten::{fn}" + if fn in op_renames: + op_name = op_renames[fn] + schemas = torch._C._jit_get_schemas_for_operator(op_name) + for s in schemas: + schematized_ops.append(_emit_schema(None, fn, s, padding=0)) + if len(schemas) > 0: + schematized_ops.append("") + else: + table_row = ( + f'":external+python:py:obj:`{fn}`", "{schemaless_op_explanations[fn]}"' + ) + schemaless_ops.append(table_row) + + schematized_ops_str = "\n".join(schematized_ops) + schemaless_ops_str = "\n".join(schemaless_ops) + magic_methods_rows_str = "\n".join(magic_methods_rows) + schematized_ops_str = textwrap.indent(schematized_ops_str, "\t") + schemaless_ops_str = textwrap.indent(schemaless_ops_str, "\t") + magic_methods_rows_str = textwrap.indent(magic_methods_rows_str, "\t") + section = f""" +The functions in the following table are supported but do not have a static schema + +.. csv-table:: + :header: "Function", "Note" + +{schemaless_ops_str} + +The following functions will use the corresponding magic method on :any:`TorchScript classes` + +.. csv-table:: + :header: "Function", "Magic Method" + +{magic_methods_rows_str} + +These built-in functions use the schema + +.. rst-class:: codeblock-height-limiter + +:: + +{schematized_ops_str} + """ + + return "Python Built-in Functions", section + + +def _list_supported_ops(): + def emit_block(decls): + return "\n.. rst-class:: codeblock-height-limiter\n\n::\n\n{}\n".format( + "".join(f" {d}\n\n" for d in decls) + ) + + body = "" + op_gathering_fns = ( + _get_tensor_ops, + _get_nn_functional_ops, + _get_torchscript_builtins, + _get_global_builtins, + _get_math_builtins, + ) + for fn in op_gathering_fns: + header, items = fn() + link_target = header.replace("`", "").replace("-", "").lower().replace(" ", "-") + if isinstance(items, str): + section = f"{header}\n{'~' * len(header)}\n{items}\n" + else: + section = f"{header}\n{'~' * len(header)}\n{emit_block(items)}" + section = f".. _{link_target}:" + "\n\n" + section + body += section + + return body + + +__doc__ = _list_supported_ops() diff --git a/shared/package-files/2c/2c28454293ed6f4d29164c0852c2ae176173f29560edddadca73df7de919c43c/evalf.cpython-311.pyc b/shared/package-files/2c/2c28454293ed6f4d29164c0852c2ae176173f29560edddadca73df7de919c43c/evalf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d43118423902b99fd0faaaa20a49b5465a99b66 Binary files /dev/null and b/shared/package-files/2c/2c28454293ed6f4d29164c0852c2ae176173f29560edddadca73df7de919c43c/evalf.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c2c77bc0635e8b039cdde9b65e49f8769159cec6f8a5b18c1c46bbd28161109/_version_meson.py b/shared/package-files/2c/2c2c77bc0635e8b039cdde9b65e49f8769159cec6f8a5b18c1c46bbd28161109/_version_meson.py new file mode 100644 index 0000000000000000000000000000000000000000..973a8d3fdc4a7233dcfb068268a80e4484253212 --- /dev/null +++ b/shared/package-files/2c/2c2c77bc0635e8b039cdde9b65e49f8769159cec6f8a5b18c1c46bbd28161109/_version_meson.py @@ -0,0 +1,2 @@ +__version__="2.2.3" +__git_version__="0691c5cf90477d3503834d983f69350f250a6ff7" diff --git a/shared/package-files/2c/2c2dce3af29d5d8f2772d5aa881ac3bd5a3164a745a6786bf019c9e69701be57/_embedding_bag_dense_backward.h b/shared/package-files/2c/2c2dce3af29d5d8f2772d5aa881ac3bd5a3164a745a6786bf019c9e69701be57/_embedding_bag_dense_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..ded38e22e30e40a058e3fbb6fcc7494eb0192759 --- /dev/null +++ b/shared/package-files/2c/2c2dce3af29d5d8f2772d5aa881ac3bd5a3164a745a6786bf019c9e69701be57/_embedding_bag_dense_backward.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor +inline at::Tensor _embedding_bag_dense_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx); +} +namespace symint { + template >> + at::Tensor _embedding_bag_dense_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx); + } +} + +// aten::_embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor +inline at::Tensor _embedding_bag_dense_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx); +} +namespace symint { + template >> + at::Tensor _embedding_bag_dense_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx); + } +} + +// aten::_embedding_bag_dense_backward.out(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _embedding_bag_dense_backward_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); +} +namespace symint { + template >> + at::Tensor & _embedding_bag_dense_backward_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); + } +} + +// aten::_embedding_bag_dense_backward.out(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _embedding_bag_dense_backward_outf(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx, at::Tensor & out) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); +} +namespace symint { + template >> + at::Tensor & _embedding_bag_dense_backward_outf(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx, at::Tensor & out) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); + } +} + +// aten::_embedding_bag_dense_backward.out(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _embedding_bag_dense_backward_symint_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); +} +namespace symint { + template >> + at::Tensor & _embedding_bag_dense_backward_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); + } +} + +// aten::_embedding_bag_dense_backward.out(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _embedding_bag_dense_backward_symint_outf(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx, at::Tensor & out) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); +} +namespace symint { + template >> + at::Tensor & _embedding_bag_dense_backward_outf(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx, at::Tensor & out) { + return at::_ops::_embedding_bag_dense_backward_out::call(grad, indices, offset2bag, bag_size, maximum_indices, num_weights, scale_grad_by_freq, mode, per_sample_weights, padding_idx, out); + } +} + +} diff --git a/shared/package-files/2c/2c39a5f5a1c8afcd4a25e5d3d2c42f296179d5063789d0d2bec4d0a3a82e017f/autocast.h b/shared/package-files/2c/2c39a5f5a1c8afcd4a25e5d3d2c42f296179d5063789d0d2bec4d0a3a82e017f/autocast.h new file mode 100644 index 0000000000000000000000000000000000000000..ea3de368404c9c620ee032c2bd77e968ec917dbd --- /dev/null +++ b/shared/package-files/2c/2c39a5f5a1c8afcd4a25e5d3d2c42f296179d5063789d0d2bec4d0a3a82e017f/autocast.h @@ -0,0 +1,13 @@ + +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void Autocast(const std::shared_ptr& graph); + +TORCH_API bool setAutocastMode(bool value); +TORCH_API bool autocastEnabled(); + +} // namespace torch::jit diff --git a/shared/package-files/2c/2c46df823fc5a8dfdcffef04a79ae27cbaf1d8ef9d500ce2f0e7d905a0e21ab9/probaln.c b/shared/package-files/2c/2c46df823fc5a8dfdcffef04a79ae27cbaf1d8ef9d500ce2f0e7d905a0e21ab9/probaln.c new file mode 100644 index 0000000000000000000000000000000000000000..b42f85685aa16e0aa6548dd622c7efc55a1fd7a6 --- /dev/null +++ b/shared/package-files/2c/2c46df823fc5a8dfdcffef04a79ae27cbaf1d8ef9d500ce2f0e7d905a0e21ab9/probaln.c @@ -0,0 +1,468 @@ +/* The MIT License + + Copyright (C) 2003-2006, 2008-2010 by Heng Li + Copyright (C) 2016-2017, 2020, 2023 Genome Research Ltd. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h +#include + +#include +#include +#include +#include +#include +#include +#include +#include "htslib/hts.h" + +/***************************************** + * Probabilistic banded glocal alignment * + *****************************************/ + +#define EI .25 +#define EM .33333333333 + +static float g_qual2prob[256]; + +#define set_u(u, b, i, k) { int x=(i)-(b); x=x>0?x:0; (u)=((k)-x+1)*3; } + +/* + The topology of the profile HMM: + + /\ /\ /\ /\ + I[1] I[k-1] I[k] I[L] + ^ \ \ ^ \ ^ \ \ ^ + | \ \ | \ | \ \ | + M[0] M[1] -> ... -> M[k-1] -> M[k] -> ... -> M[L] M[L+1] + \ \/ \/ \/ / + \ /\ /\ /\ / + -> D[k-1] -> D[k] -> + + M[0] points to every {M,I}[k] and every {M,I}[k] points to M[L+1]. + + On input, ref is the reference sequence and query is the query + sequence. Both are sequences of 0/1/2/3/4 where 4 stands for an + ambiguous residue. iqual is the base quality. c sets the gap open + probability, gap extension probability and band width. + + On output, state and q are arrays of length l_query. The higher 30 + bits give the reference position the query base is matched to and the + lower two bits can be 0 (an alignment match) or 1 (an + insertion). q[i] gives the phred scaled posterior probability of + state[i] being wrong. + + Returns phred-scaled likelihood score, or INT_MIN on failure. + */ +int probaln_glocal(const uint8_t *ref, int l_ref, const uint8_t *query, + int l_query, const uint8_t *iqual, const probaln_par_t *c, + int *state, uint8_t *q) +{ + double *f = NULL, *b = NULL, *s = NULL, m[9], sI, sM, bI, bM; + float *qual = NULL; + int bw, bw2, i, k, is_backward = 1, Pr; + + if ( l_ref<0 || l_query<0 || l_query >= INT_MAX - 2) { + errno = EINVAL; + return INT_MIN; + } + if (l_ref==0 || l_query==0) + return 0; // Is this actually invalid?? + + /*** initialization ***/ + is_backward = state && q? 1 : 0; + bw = l_ref > l_query? l_ref : l_query; + if (bw > c->bw) bw = c->bw; + if (bw < abs(l_ref - l_query)) bw = abs(l_ref - l_query); + bw2 = bw * 2 + 1; + size_t i_dim = bw2 < l_ref ? (size_t) bw2*3+6 : (size_t) l_ref*3+6; + + // allocate the forward and backward matrices f[][] and b[][] + // and the scaling array s[] + // Ideally these callocs would be mallocs + initialisation of + // the few bits needed. + if (SIZE_MAX / (l_query+1) / i_dim < sizeof(double)) { + errno = ENOMEM; // Allocation would fail + return INT_MIN; + } + f = calloc((l_query+1)*i_dim, sizeof(double)); + if (!f) goto fail; + if (is_backward) { + b = calloc((l_query+1)*i_dim, sizeof(double)); + if (!b) goto fail; + } + + // s[] is the scaling factor to avoid underflow + s = malloc((l_query+2) * sizeof(double)); + if (!s) goto fail; + + // initialize qual + qual = malloc(l_query * sizeof(float)); + if (!qual) goto fail; + if (g_qual2prob[0] == 0) + for (i = 0; i < 256; ++i) + g_qual2prob[i] = pow(10, -i/10.); + qual[0] = 0.0; // Should be unused + for (i = 0; i < l_query; ++i) + qual[i] = g_qual2prob[iqual? iqual[i] : 30]; + + // initialize transition probability + // the value here seems not to affect results; FIXME: need proof + sM = sI = 1. / (2 * l_query + 2); + m[0*3+0] = (1 - c->d - c->d) * (1 - sM); + m[0*3+1] = m[0*3+2] = c->d * (1 - sM); + m[1*3+0] = (1 - c->e) * (1 - sI); + m[1*3+1] = c->e * (1 - sI); + m[1*3+2] = 0.; + m[2*3+0] = 1 - c->e; + m[2*3+1] = 0.; + m[2*3+2] = c->e; + bM = (1 - c->d) / l_ref; // (bM+bI)*l_ref==1 + bI = c->d / l_ref; + + // f[] and b[] are 2-d arrays of three scores, with rows along the + // query and columns across the band. The first query base and + // first band position appear at index 1 allowing edge conditions + // to be stored in index 0. Hence the loops below appear to use + // 1-based indexing instead of 0-based as you'd normally expect in C, + // and the sequences are accessed using query[i - 1] and ref[k - 1]. + + /*** forward ***/ + // f[0] + set_u(k, bw, 0, 0); + f[0*i_dim+k] = s[0] = 1.; + { // f[1] + double *fi = &f[1*i_dim], sum; + int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1; + for (k = beg, sum = 0.; k <= end; ++k) { + int u; + double e = (ref[k - 1] > 3 || query[0] > 3)? 1. : ref[k - 1] == query[0]? 1. - qual[0] : qual[0] * EM; + set_u(u, bw, 1, k); + fi[u+0] = e * bM; fi[u+1] = EI * bI; + sum += fi[u] + fi[u+1]; + } + s[1] = sum; + } + // f[2..l_query] + for (i = 2; i <= l_query; ++i) { + double *fi = &f[i*i_dim], *fi1 = &f[(i-1)*i_dim], sum, qli = qual[i-1]; + int beg = 1, end = l_ref, x; + uint8_t qyi = query[i - 1]; + x = i - bw; beg = beg > x? beg : x; // band start + x = i + bw; end = end < x? end : x; // band end + + // NB end-beg is almost always 14 (99.9% of the time) + // Hence not a large volume to parallelise. + // + // Maybe stripe in diagonal doing 14 lines together? + // + // Consider rotation? 150x14 vs 14x150 so inner loop + // takes longer. + + double E[] = { + qli * EM, // 00 + 1. - qli, // 01 + 1., // 10 + 1., // 11 + }; + double M = 1./s[i-1]; + + // Note this code has the original version listed here (albeit + // with improved formatting), but we do not compile using + // -DPROBALN_ORIG. The purpose of this code is to act as an + // easier(?) to understand version of the heavily optimised + // version following it and as an easy validation path in case + // of any differences in results. +#ifdef PROBALN_ORIG + for (k = beg, sum = 0.; k <= end; ++k) { + int u, v11, v01, v10; + double e; + e = E[(ref[k - 1] > 3 || qyi > 3)*2 + (ref[k - 1] == qyi)]; + set_u(u, bw, i, k); + set_u(v11, bw, i-1, k-1); + set_u(v10, bw, i-1, k); + set_u(v01, bw, i, k-1); + fi[u+0] = e * (m[0] * M*fi1[v11+0] + m[3] * M*fi1[v11+1] + m[6] * M*fi1[v11+2]); + fi[u+1] = EI * (m[1] * M*fi1[v10+0] + m[4] * M*fi1[v10+1]); + fi[u+2] = m[2] * fi[v01+0] + m[8] * fi[v01+2]; + sum += fi[u] + fi[u+1] + fi[u+2]; + } +#else + // We use EI*(M*m[1]*? + M*m[4]*?) a lot. So factor it out here. + double xm[5]; + xm[0] = M*m[0]; + xm[1] = M*m[3]; + xm[2] = M*m[6]; + xm[3] = EI*M*m[1]; + xm[4] = EI*M*m[4]; + + { + int u, v11; + set_u(u, bw, i, beg); + set_u(v11, bw, i-1, beg-1); + // Rather than recompute k->{u,v01,v10,v11} each loop + // we just increment the pointers. + double *xi = &fi[u]; + double *yi = &fi1[v11]; + // Derived from xi[0,2] in previous loop iter. + double l_x0 = m[2]*xi[0]; + double l_x2 = m[8]*xi[2]; + for (k = beg, sum = 0.; k <= end; ++k, xi+=3, yi+=3) { + int cond = (ref[k-1] > 3 || qyi > 3)*2 + (ref[k-1] == qyi); + + double z0 = xm[0]*yi[0]; + double z1 = xm[1]*yi[1]; + double z2 = xm[2]*yi[2]; + double z3 = xm[3]*yi[3]; + double z4 = xm[4]*yi[4]; + + xi[0] = E[cond] * (z0+z1+z2); + xi[1] = z3 + z4; + xi[2] = l_x0 + l_x2; + sum += xi[0] + xi[1] + xi[2]; + + l_x0 = m[2]*xi[0]; + l_x2 = m[8]*xi[2]; + } + } +#endif + s[i] = sum; + } + + { // f[l_query+1] + double sum; + double M = 1./s[l_query]; + // Note that this goes from 1 to l_ref inclusive, but as the + // alignment is banded not all of the values will have been + // calculated (the rest are taken as 0), so the summation + // actually goes over the values set in the last iteration of + // the previous loop (when i = l_query). For some reason lost to + // time this is done by looking for valid values of 'u' instead of + // working out 'beg' and 'end'. + + // From HTSlib 1.8 to 1.17, the endpoint was incorrectly set + // to i_dim - 3. When l_query <= bandwidth, this caused the last + // column to be missed, and if l_ref == l_query then a match at the end + // could incorrectly be reported as an insertion. See #1605. + + for (k = 1, sum = 0.; k <= l_ref; ++k) { + int u; + set_u(u, bw, l_query, k); + if (u < 3 || u >= i_dim) continue; + sum += M*f[l_query*i_dim + u+0] * sM + M*f[l_query*i_dim + u+1] * sI; + } + s[l_query+1] = sum; // the last scaling factor + } + { // compute likelihood + double p = 1., Pr1 = 0.; + for (i = 0; i <= l_query + 1; ++i) { + p *= s[i]; + if (p < 1e-100) Pr1 += -4.343 * log(p), p = 1.; + } + Pr1 += -4.343 * log(p * l_ref * l_query); + Pr = (int)(Pr1 + .499); + if (!is_backward) { // skip backward and MAP + free(f); free(s); free(qual); + return Pr; + } + } + /*** backward ***/ + // b[l_query] (b[l_query+1][0]=1 and thus \tilde{b}[][]=1/s[l_query+1]; this is where s[l_query+1] comes from) + for (k = 1; k <= l_ref; ++k) { + int u; + double *bi = &b[l_query*i_dim]; + set_u(u, bw, l_query, k); + if (u < 3 || u >= i_dim) continue; + bi[u+0] = sM / s[l_query] / s[l_query+1]; bi[u+1] = sI / s[l_query] / s[l_query+1]; + } + // b[l_query-1..1] + for (i = l_query - 1; i >= 1; --i) { + int beg = 1, end = l_ref, x; + double *bi = &b[i*i_dim], *bi1 = &b[(i+1)*i_dim], y = (i > 1), qli1 = qual[i]; + uint8_t qyi1 = query[i]; + x = i - bw; beg = beg > x? beg : x; + x = i + bw; end = end < x? end : x; + double E[] = { + qli1 * EM, //000 + 1. - qli1, //001 + 1., //010 + 1., //011 + //0,0,0,0 //1xx + }; + +#ifdef PROBALN_ORIG + for (k = end; k >= beg; --k) { + int u, v11, v01, v10; + double e; + set_u(u, bw, i, k); + set_u(v11, bw, i+1, k+1); + set_u(v10, bw, i+1, k); + set_u(v01, bw, i, k+1); + e = (k>=l_ref)?0 :E[(ref[k] > 3 || qyi1 > 3)*2 + (ref[k] == qyi1)] * bi1[v11]; + bi[u+0] = e * m[0] + EI * m[1] * bi1[v10+1] + m[2] * bi[v01+2]; // bi1[v11] has been foled into e. + bi[u+1] = e * m[3] + EI * m[4] * bi1[v10+1]; + bi[u+2] = (e * m[6] + m[8] * bi[v01+2]) * y; +// fprintf(stderr, "B (%d,%d;%d): %lg,%lg,%lg\n", i, k, u, bi[u], bi[u+1], bi[u+2]); // DEBUG + } + // rescale + int _beg, _end; + set_u(_beg, bw, i, beg); set_u(_end, bw, i, end); _end += 2; + for (k = _beg, y = 1./s[i]; k <= _end; ++k) bi[k] *= y; +#else + { + int u, v10; + set_u(u, bw, i, end); + set_u(v10, bw, i+1, end); + // Rather than recompute k->{u,v01,v10,v11} each loop + // we just increment the pointers. + double *xi = &bi[u]; + double *yi = &bi1[v10]; + // NB xi[5] is equiv to v01+2. + double xi_5 = xi[5]; + // Manual loop invariant removal + double e1 = EI*m[1]; + double e4 = EI*m[4]; + // Do renorm too in the same pass. + double n = 1./s[i]; + for (k = end; k >= beg; --k, xi -= 3, yi -= 3) { + double e = (k>=l_ref) + ? 0 + : E[(ref[k]>3 || qyi1>3)*2 + (ref[k] == qyi1)] * yi[3]; + + xi[1] = e * m[3] + e4 * yi[1]; + xi[0] = e * m[0] + e1 * yi[1] + m[2] * xi_5; + xi[2] = (e * m[6] + m[8] * xi_5) * y; + // bi[u+2] from this iter becomes bi[v01+2] in next iter + xi_5 = xi[2]; + + // rescale + xi[1] *= n; + xi[0] *= n; + xi[2] *= n; + } + } +#endif + } + { // b[0] + int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1; + double sum = 0.; + for (k = end; k >= beg; --k) { + int u; + double e = (ref[k - 1] > 3 || query[0] > 3)? 1. : ref[k - 1] == query[0]? 1. - qual[0] : qual[0] * EM; + set_u(u, bw, 1, k); + if (u < 3 || u >= i_dim) continue; + sum += e * b[1*i_dim + u+0] * bM + EI * b[1*i_dim + u+1] * bI; + } + set_u(k, bw, 0, 0); + b[0*i_dim + k] = sum / s[0]; // if everything works as is expected, b[0][k] == 1.0 + } + /*** MAP ***/ + for (i = 1; i <= l_query; ++i) { + double sum = 0., *fi = &f[i*i_dim], *bi = &b[i*i_dim], max = 0.; + int beg = 1, end = l_ref, x, max_k = -1; + x = i - bw; beg = beg > x? beg : x; + x = i + bw; end = end < x? end : x; + double M = 1./s[i]; +#ifdef PROBALN_ORIG + for (k = beg; k <= end; ++k) { + int u; + double z; + set_u(u, bw, i, k); + z = M*fi[u+0] * bi[u+0]; + if (z > max) max = z, max_k = (k-1)<<2 | 0; + sum += z; + z = M*fi[u+1] * bi[u+1]; + if (z > max) max = z, max_k = (k-1)<<2 | 1; + sum += z; + } +#else + { + int u; + set_u(u, bw, i, beg); + for (k = beg; k <= end; ++k, u+=3) { + double z1, z2; + z1 = M*fi[u+0] * bi[u+0]; + z2 = M*fi[u+1] * bi[u+1]; + int which = z2 > z1; // strictly z2 >= z1 matches old code + double zm = which ? z2 : z1; + if (zm > max) { + max = zm; + max_k = (k-1)<<2 | which; + } + sum += z1 + z2; + } + } +#endif + max /= sum; sum *= s[i]; // if everything works as is expected, sum == 1.0 + if (state) state[i-1] = max_k; + if (q) k = (int)(-4.343 * log(1. - max) + .499), q[i-1] = k > 100? 99 : k; +#ifdef PROBALN_MAIN + k = 0; + set_u(k, bw, 0, 0); + fprintf(stderr, "(%.10lg,%.10lg) (%d,%d:%c,%c:%d) %lg\n", b[0][k], sum, i-1, max_k>>2, + "ACGT"[query[i - 1]], "ACGT"[ref[(max_k>>2)]], max_k&3, max); // DEBUG +#endif + } + + /*** free ***/ + free(f); free(b); free(s); free(qual); + return Pr; + + fail: + free(f); free(b); free(s); free(qual); + return INT_MIN; +} + +#ifdef PROBALN_MAIN +#include +int main(int argc, char *argv[]) +{ + uint8_t conv[256], *iqual, *ref, *query; + probaln_par_t par = { 0.001, 0.1, 10 }; + int c, l_ref, l_query, i, q = 30, b = 10, P; + while ((c = getopt(argc, argv, "b:q:")) >= 0) { + switch (c) { + case 'b': b = atoi(optarg); break; + case 'q': q = atoi(optarg); break; + } + } + if (optind + 2 > argc) { + fprintf(stderr, "Usage: %s [-q %d] [-b %d] \n", argv[0], q, b); // example: acttc attc + return 1; + } + memset(conv, 4, 256); + conv['a'] = conv['A'] = 0; conv['c'] = conv['C'] = 1; + conv['g'] = conv['G'] = 2; conv['t'] = conv['T'] = 3; + ref = (uint8_t*)argv[optind]; query = (uint8_t*)argv[optind+1]; + l_ref = strlen((char*)ref); l_query = strlen((char*)query); + for (i = 0; i < l_ref; ++i) ref[i] = conv[ref[i]]; + for (i = 0; i < l_query; ++i) query[i] = conv[query[i]]; + iqual = malloc(l_query); + memset(iqual, q, l_query); + par.bw = b; + P = probaln_glocal(ref, l_ref, query, l_query, iqual, &par, 0, 0); + fprintf(stderr, "%d\n", P); + free(iqual); + return 0; +} +#endif diff --git a/shared/package-files/2c/2c47fd448ec09a2226f2d3778bcc273d47afcdba035c08869d30b5477b988b8c/__init__.cpython-311.pyc b/shared/package-files/2c/2c47fd448ec09a2226f2d3778bcc273d47afcdba035c08869d30b5477b988b8c/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f07fc64730e8e6efcf873ed3bbc3d8faa4f5d6a Binary files /dev/null and b/shared/package-files/2c/2c47fd448ec09a2226f2d3778bcc273d47afcdba035c08869d30b5477b988b8c/__init__.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c4b0405a40af9ed9837fe094522c7e45c786426b2d9e590b120e94e78070c67/_sfdp_pattern_7.cpython-311.pyc b/shared/package-files/2c/2c4b0405a40af9ed9837fe094522c7e45c786426b2d9e590b120e94e78070c67/_sfdp_pattern_7.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc64bb440ae2eaab4c24f82e15d77642f6db0068 Binary files /dev/null and b/shared/package-files/2c/2c4b0405a40af9ed9837fe094522c7e45c786426b2d9e590b120e94e78070c67/_sfdp_pattern_7.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c4dda8c76cf2219d870cc566825d98ef0049f45916bd029c7ace63a02f73119/__init__.py b/shared/package-files/2c/2c4dda8c76cf2219d870cc566825d98ef0049f45916bd029c7ace63a02f73119/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18a88220c4173be40838ce1ea4f66be4a4c68bee --- /dev/null +++ b/shared/package-files/2c/2c4dda8c76cf2219d870cc566825d98ef0049f45916bd029c7ace63a02f73119/__init__.py @@ -0,0 +1,556 @@ +# mypy: allow-untyped-defs +r""" +This package introduces support for the XPU backend, specifically tailored for +Intel GPU optimization. + +This package is lazily initialized, so you can always import it, and use +:func:`is_available()` to determine if your system supports XPU. +""" +import threading +import traceback +from functools import lru_cache +from typing import Any, Callable, Optional, Union + +import torch +import torch._C +from torch import device as _device +from torch._utils import _dummy_type, _LazySeedTracker + +from ._utils import _get_device_index +from .streams import Event, Stream + + +_initialized = False +_tls = threading.local() +_initialization_lock = threading.Lock() +_queued_calls: list[ + tuple[Callable[[], None], list[str]] +] = [] # don't invoke these until initialization occurs +_is_in_bad_fork = getattr(torch._C, "_xpu_isInBadFork", lambda: False) +_device_t = Union[_device, str, int, None] +_lazy_seed_tracker = _LazySeedTracker() +default_generators: tuple[torch._C.Generator] = () # type: ignore[assignment] + + +def _is_compiled() -> bool: + r"""Return true if compile with XPU support.""" + return torch._C._has_xpu + + +if _is_compiled(): + _XpuDeviceProperties = torch._C._XpuDeviceProperties + _exchange_device = torch._C._xpu_exchangeDevice + _maybe_exchange_device = torch._C._xpu_maybeExchangeDevice +else: + # Define dummy if PyTorch was compiled without XPU + _XpuDeviceProperties = _dummy_type("_XpuDeviceProperties") # type: ignore[assignment, misc] + + def _exchange_device(device: int) -> int: + raise NotImplementedError("PyTorch was compiled without XPU support") + + def _maybe_exchange_device(device: int) -> int: + raise NotImplementedError("PyTorch was compiled without XPU support") + + +@lru_cache(maxsize=1) +def device_count() -> int: + r"""Return the number of XPU device available.""" + if not _is_compiled(): + return 0 + return torch._C._xpu_getDeviceCount() + + +def is_available() -> bool: + r"""Return a bool indicating if XPU is currently available.""" + # This function nerver throws. + return device_count() > 0 + + +def is_bf16_supported(): + r"""Return a bool indicating if the current XPU device supports dtype bfloat16.""" + return True + + +def is_initialized(): + r"""Return whether PyTorch's XPU state has been initialized.""" + return _initialized and not _is_in_bad_fork() + + +def _lazy_call(callable, **kwargs): + if is_initialized(): + callable() + else: + global _lazy_seed_tracker + if kwargs.get("seed_all", False): + _lazy_seed_tracker.queue_seed_all(callable, traceback.format_stack()) + elif kwargs.get("seed", False): + _lazy_seed_tracker.queue_seed(callable, traceback.format_stack()) + else: + # Don't store the actual traceback to avoid memory cycle + _queued_calls.append((callable, traceback.format_stack())) + + +def init(): + r"""Initialize PyTorch's XPU state. + This is a Python API about lazy initialization that avoids initializing + XPU until the first time it is accessed. Does nothing if the XPU state is + already initialized. + """ + _lazy_init() + + +def _lazy_init(): + global _initialized, _queued_calls + if is_initialized() or hasattr(_tls, "is_initializing"): + return + with _initialization_lock: + # This test was was protected via GIL. Double-check whether XPU has + # already been initialized. + if is_initialized(): + return + # Stop promptly upon encountering a bad fork error. + if _is_in_bad_fork(): + raise RuntimeError( + "Cannot re-initialize XPU in forked subprocess. To use XPU with " + "multiprocessing, you must use the 'spawn' start method" + ) + if not _is_compiled(): + raise AssertionError("Torch not compiled with XPU enabled") + # This function inits XPU backend and detects bad fork processing. + torch._C._xpu_init() + # Some of the queued calls may reentrantly call _lazy_init(); We need to + # just return without initializing in that case. + _tls.is_initializing = True + + _queued_calls.extend(calls for calls in _lazy_seed_tracker.get_calls() if calls) + + try: + for queued_call, orig_traceback in _queued_calls: + try: + queued_call() + except Exception as e: + msg = ( + f"XPU call failed lazily at initialization with error: {str(e)}\n\n" + f"XPU call was originally invoked at:\n\n{''.join(orig_traceback)}" + ) + raise Exception(msg) from e # noqa: TRY002 + finally: + delattr(_tls, "is_initializing") + _initialized = True + + +class _DeviceGuard: + def __init__(self, index: int): + self.idx = index + self.prev_idx = -1 + + def __enter__(self): + self.prev_idx = torch.xpu._exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any): + self.idx = torch.xpu._maybe_exchange_device(self.prev_idx) + return False + + +class device: + r"""Context-manager that changes the selected device. + + Args: + device (torch.device or int or str): device index to select. It's a no-op if + this argument is a negative integer or ``None``. + """ + + def __init__(self, device: Any): + self.idx = _get_device_index(device, optional=True) + self.prev_idx = -1 + + def __enter__(self): + self.prev_idx = torch.xpu._exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any): + self.idx = torch.xpu._maybe_exchange_device(self.prev_idx) + return False + + +class device_of(device): + r"""Context-manager that changes the current device to that of given object. + + You can use both tensors and storages as arguments. If a given object is + not allocated on a XPU, this is a no-op. + + Args: + obj (Tensor or Storage): object allocated on the selected device. + """ + + def __init__(self, obj): + idx = obj.get_device() if obj.is_xpu else -1 + super().__init__(idx) + + +def set_device(device: _device_t) -> None: + r"""Set the current device. + + Args: + device (torch.device or int or str): selected device. This function is a + no-op if this argument is negative. + """ + _lazy_init() + device = _get_device_index(device) + if device >= 0: + torch._C._xpu_setDevice(device) + + +def get_device_name(device: Optional[_device_t] = None) -> str: + r"""Get the name of a device. + + Args: + device (torch.device or int or str, optional): device for which to + return the name. This function is a no-op if this argument is a + negative integer. It uses the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + + Returns: + str: the name of the device + """ + return get_device_properties(device).name + + +@lru_cache(None) +def get_device_capability(device: Optional[_device_t] = None) -> dict[str, Any]: + r"""Get the xpu capability of a device. + + Args: + device (torch.device or int or str, optional): device for which to + return the device capability. This function is a no-op if this + argument is a negative integer. It uses the current device, given by + :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` + (default). + + Returns: + Dict[str, Any]: the xpu capability dictionary of the device + """ + props = get_device_properties(device) + # pybind service attributes are no longer needed and their presence breaks + # the further logic related to the serialization of the created dictionary. + # In particular it filters out `` + # to fix Triton tests. + # This field appears after updating pybind to 2.13.6. + return { + prop: getattr(props, prop) + for prop in dir(props) + if not prop.startswith(("__", "_pybind11_")) + } + + +def get_device_properties(device: Optional[_device_t] = None) -> _XpuDeviceProperties: + r"""Get the properties of a device. + + Args: + device (torch.device or int or str): device for which to return the + properties of the device. + + Returns: + _XpuDeviceProperties: the properties of the device + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return _get_device_properties(device) # type: ignore[name-defined] # noqa: F821 + + +def current_device() -> int: + r"""Return the index of a currently selected device.""" + _lazy_init() + return torch._C._xpu_getDevice() + + +def _get_device(device: Union[int, str, torch.device]) -> torch.device: + r"""Return the torch.device type object from the passed in device. + + Args: + device (torch.device or int or str): selected device. + """ + if isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device("xpu", device) + return device + + +class StreamContext: + r"""Context-manager that selects a given stream. + + All XPU kernels queued within its context will be enqueued on a selected + stream. + + Args: + Stream (Stream): selected stream. This manager is a no-op if it's + ``None``. + .. note:: Streams are per-device. + """ + cur_stream: Optional["torch.xpu.Stream"] + + def __init__(self, stream: Optional["torch.xpu.Stream"]): + self.stream = stream + self.idx = _get_device_index(None, True) + if self.idx is None: + self.idx = -1 + + def __enter__(self): + cur_stream = self.stream + if cur_stream is None or self.idx == -1: + return + self.src_prev_stream = torch.xpu.current_stream(None) + + # If the stream is not on the current device, then set the current stream on the device + if self.src_prev_stream.device != cur_stream.device: + with device(cur_stream.device): + self.dst_prev_stream = torch.xpu.current_stream(cur_stream.device) + torch.xpu.set_stream(cur_stream) + + def __exit__(self, type: Any, value: Any, traceback: Any): + cur_stream = self.stream + if cur_stream is None or self.idx == -1: + return + + # Reset the stream on the original device and destination device + if self.src_prev_stream.device != cur_stream.device: + torch.xpu.set_stream(self.dst_prev_stream) + torch.xpu.set_stream(self.src_prev_stream) + + +def stream(stream: Optional["torch.xpu.Stream"]) -> StreamContext: + r"""Wrap around the Context-manager StreamContext that selects a given stream. + + Arguments: + stream (Stream): selected stream. This manager is a no-op if it's ``None``. + """ + return StreamContext(stream) + + +def _set_stream_by_id(stream_id, device_index, device_type): + r"""set stream specified by the stream id, device index and device type + + Args: stream_id (int): not visible to the user, used to assigned to the specific stream. + device_index (int): selected device index. + device_type (int): selected device type. + """ + torch._C._xpu_setStream( + stream_id=stream_id, + device_index=device_index, + device_type=device_type, + ) + + +def set_stream(stream: Stream): + r"""Set the current stream.This is a wrapper API to set the stream. + Usage of this function is discouraged in favor of the ``stream`` + context manager. + + Args: + stream (Stream): selected stream. This function is a no-op + if this argument is ``None``. + """ + if stream is None: + return + _lazy_init() + _set_stream_by_id( + stream_id=stream.stream_id, + device_index=stream.device_index, + device_type=stream.device_type, + ) + + +def current_stream(device: Optional[_device_t] = None) -> Stream: + r"""Return the currently selected :class:`Stream` for a given device. + + Args: + device (torch.device or int, optional): selected device. Returns + the currently selected :class:`Stream` for the current device, given + by :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` + (default). + """ + _lazy_init() + streamdata = torch._C._xpu_getCurrentStream( + _get_device_index(device, optional=True) + ) + return Stream( + stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2] + ) + + +def get_stream_from_external( + data_ptr: int, device: Optional[_device_t] = None +) -> Stream: + r"""Return a :class:`Stream` from an external SYCL queue. + + This function is used to wrap SYCL queue created in other libraries in order + to facilitate data exchange and multi-library interactions. + + .. note:: This function doesn't manage the queue life-cycle, it is the user + responsibility to keep the referenced queue alive while this returned stream is + being used. The different SYCL queue pointers will result in distinct + :class:`Stream` objects, even if the SYCL queues they dereference are equivalent. + + Args: + data_ptr(int): Integer representation of the `sycl::queue*` value passed externally. + device(torch.device or int, optional): the device where the queue was originally created. + It is the user responsibility to ensure the device is specified correctly. + """ + _lazy_init() + streamdata = torch._C._xpu_getStreamFromExternal( + data_ptr, _get_device_index(device, optional=True) + ) + return Stream( + stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2] + ) + + +def synchronize(device: _device_t = None) -> None: + r"""Wait for all kernels in all streams on a XPU device to complete. + + Args: + device (torch.device or int, optional): device for which to synchronize. + It uses the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return torch._C._xpu_synchronize(device) + + +def get_arch_list() -> list[str]: + r"""Return list XPU architectures this library was compiled for.""" + if not _is_compiled(): + return [] + arch_flags = torch._C._xpu_getArchFlags() + if arch_flags is None: + return [] + return arch_flags.split() + + +def get_gencode_flags() -> str: + r"""Return XPU AOT(ahead-of-time) build flags this library was compiled with.""" + arch_list = get_arch_list() + if len(arch_list) == 0: + return "" + return f'-device {",".join(arch for arch in arch_list)}' + + +def _get_generator(device: torch.device) -> torch._C.Generator: + r"""Return the XPU Generator object for the given device. + + Args: + device (torch.device): selected device. + """ + idx = device.index + if idx is None: + idx = current_device() + return torch.xpu.default_generators[idx] + + +def _set_rng_state_offset( + offset: int, device: Union[int, str, torch.device] = "xpu" +) -> None: + r"""Set the random number generator state offset of the specified GPU. + + Args: + offset (int): The desired offset + device (torch.device or int, optional): The device to set the RNG state. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + """ + final_device = _get_device(device) + + def cb(): + default_generator = _get_generator(final_device) + default_generator.set_offset(offset) + + _lazy_call(cb) + + +def _get_rng_state_offset(device: Union[int, str, torch.device] = "xpu") -> int: + r"""Return the random number generator state offset of the specified GPU. + + Args: + device (torch.device or int, optional): The device to return the RNG state offset of. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + + .. warning:: + This function eagerly initializes XPU. + """ + _lazy_init() + final_device = _get_device(device) + default_generator = _get_generator(final_device) + return default_generator.get_offset() + + +# import here to avoid circular import +from .memory import ( + empty_cache, + max_memory_allocated, + max_memory_reserved, + mem_get_info, + memory_allocated, + memory_reserved, + memory_stats, + memory_stats_as_nested_dict, + reset_accumulated_memory_stats, + reset_peak_memory_stats, +) +from .random import ( + get_rng_state, + get_rng_state_all, + initial_seed, + manual_seed, + manual_seed_all, + seed, + seed_all, + set_rng_state, + set_rng_state_all, +) + + +__all__ = [ + "Event", + "Stream", + "StreamContext", + "current_device", + "current_stream", + "default_generators", + "device", + "device_of", + "device_count", + "empty_cache", + "get_arch_list", + "get_device_capability", + "get_device_name", + "get_device_properties", + "get_gencode_flags", + "get_rng_state", + "get_rng_state_all", + "get_stream_from_external", + "init", + "initial_seed", + "is_available", + "is_bf16_supported", + "is_initialized", + "manual_seed", + "manual_seed_all", + "max_memory_allocated", + "max_memory_reserved", + "mem_get_info", + "memory_allocated", + "memory_reserved", + "memory_stats", + "memory_stats_as_nested_dict", + "reset_accumulated_memory_stats", + "reset_peak_memory_stats", + "seed", + "seed_all", + "set_device", + "set_rng_state", + "set_rng_state_all", + "set_stream", + "stream", + "streams", + "synchronize", +] diff --git a/shared/package-files/2c/2c531b667b396f1ad6ef0a6fb18e3d40221348ba2fdb80c0f3007655b199f66e/graph.py b/shared/package-files/2c/2c531b667b396f1ad6ef0a6fb18e3d40221348ba2fdb80c0f3007655b199f66e/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..ff475a14b7409dd83ea8a5e3c1714514ea547855 --- /dev/null +++ b/shared/package-files/2c/2c531b667b396f1ad6ef0a6fb18e3d40221348ba2fdb80c0f3007655b199f66e/graph.py @@ -0,0 +1,2011 @@ +# mypy: allow-untyped-defs +import builtins +import contextlib +import copy +import enum +import functools +import inspect +import keyword +import math +import os +import re +import typing +import warnings +from collections import defaultdict +from collections.abc import Iterable +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, Callable, Literal, NamedTuple, Optional, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._C import _fx_map_arg as map_arg, _NodeIter + +from . import _pytree as fx_pytree +from ._compatibility import compatibility +from .immutable_collections import immutable_dict +from .node import _get_qualified_name, _type_repr, Argument, Node, Target + + +__all__ = ["PythonCode", "CodeGen", "Graph"] + +if TYPE_CHECKING: + from ._symbolic_trace import Tracer # noqa: F401 + from .graph_module import GraphModule # noqa: F401 + + +# Mapping of builtins to their `typing` equivalent. +# (PEP585: See D68459095 test plan) +_origin_type_map = { + list: typing.List, # noqa: UP006 + dict: typing.Dict, # noqa: UP006 + set: typing.Set, # noqa: UP006 + frozenset: typing.FrozenSet, # noqa: UP006 + tuple: typing.Tuple, # noqa: UP006 +} + +_legal_ops = dict.fromkeys( + ["call_function", "call_method", "get_attr", "call_module", "placeholder", "output"] +) + + +# Signature for functions thattransforms the body (`list[str]`) of the +# generated code +TransformCodeFunc = Callable[[list[str]], list[str]] + + +class _CustomBuiltin(NamedTuple): + """Additional objs that we add to every graph's globals. + + The repr() for some standard library objects is not valid Python code without + an import. For common objects of this sort, we bundle them in the globals of + every FX graph. + """ + + # How to import this object from the standard library. + import_str: str + # The actual object, produced from that import string. + obj: Any + + +# Combined dict of disallowed variable names so we can check with one lookup +_illegal_names = {k: object() for k in keyword.kwlist} +_illegal_names.update(builtins.__dict__) # can't shadow a builtin name + +_custom_builtins: dict[str, _CustomBuiltin] = {} + + +def _register_custom_builtin(name: str, import_str: str, obj: Any): + _custom_builtins[name] = _CustomBuiltin(import_str, obj) + _illegal_names[name] = obj + + +_register_custom_builtin("inf", "from math import inf", math.inf) +_register_custom_builtin("nan", "from math import nan", math.nan) +_register_custom_builtin("NoneType", "NoneType = type(None)", type(None)) +_register_custom_builtin("torch", "import torch", torch) +_register_custom_builtin("device", "from torch import device", torch.device) +_register_custom_builtin("fx_pytree", "import torch.fx._pytree as fx_pytree", fx_pytree) +_register_custom_builtin("pytree", "import torch.utils._pytree as pytree", pytree) + + +def _is_magic(x: str) -> bool: + return x.startswith("__") and x.endswith("__") + + +def _snake_case(s: str) -> str: + """ + Transforms the given string ``s`` to a Python-style variable name + + Examples: + ``mod.snake_case`` -> ``mod.snake_case`` + ``mod.pascalCase``-> ``mod.pascal_case`` + ``mod.ALL_CAPS`` -> ``mod.all_caps`` + """ + return _snake_case_sub(s).lower() + + +# Replace occurrences where a lowercase letter is followed by an uppercase letter +_snake_case_sub = functools.partial(re.compile(r"(?<=[a-z])([A-Z])").sub, r"_\1") + +# Find chars that can't be in a Python identifier +_illegal_char_regex = re.compile("[^0-9a-zA-Z_]+") + +# Combined check for variable names: +# 1) Checks name is not empty +# 2) Checks first character is not a digit +# 3) Checks name has no illegal characters (_illegal_char_regex) +# 3) Splits off the number suffix (if present) +_name_regex = re.compile(r"^([a-zA-Z_][0-9a-zA-Z_]*?)(?:_(\d+))?$") + +# starts with torch but does not start with torch._dynamo. or torch._inductor. +_torch_but_not_dynamo = re.compile( + r"^torch(?:\.(?!_dynamo\.|_inductor\.)[^.]+)*$" +).fullmatch + + +def _is_from_torch(obj: Any) -> bool: + module_name = getattr(obj, "__module__", None) + if module_name is not None: + return _torch_but_not_dynamo(module_name) is not None + + name = getattr(obj, "__name__", None) + # exclude torch because torch.torch.torch.torch works. idk mang + if name is not None and name != "torch": + for guess in [torch, torch.nn.functional]: + if getattr(guess, name, None) is obj: + return True + + return False + + +class _Namespace: + """A context for associating names uniquely with objects. + + The following invariants are enforced: + - Each object gets a single name. + - Each name is unique within a given namespace. + - Names generated do not shadow builtins, unless the object is indeed that builtin. + """ + + def __init__(self): + self._obj_to_name: dict[Any, str] = {} + self._used_names: set[str] = set() + self._base_count: dict[str, int] = {} + + def create_name(self, candidate: str, obj: Optional[Any]) -> str: + """Create a unique name. + + Arguments: + candidate: used as the basis for the unique name, relevant to the user. + obj: If not None, an object that will be associated with the unique name. + """ + if obj is not None and obj in self._obj_to_name: + return self._obj_to_name[obj] + + # optimistically check if candidate is already a valid name + match = _name_regex.match(candidate) + if match is None: + # delete all characters that are illegal in a Python identifier + candidate = _illegal_char_regex.sub("_", candidate) + + if not candidate: + candidate = "_unnamed" + + if candidate[0].isdigit(): + candidate = f"_{candidate}" + + match = _name_regex.match(candidate) + assert match is not None + + base, num = match.group(1, 2) + if num is None or candidate in self._used_names: + num = self._base_count.get(candidate, 0) + if _illegal_names.get(candidate, obj) is not obj: + num += 1 + candidate = f"{base}_{num}" + # assume illegal names don't end in _\d so no need to check again + else: + num = int(num) + + while candidate in self._used_names: + num += 1 + candidate = f"{base}_{num}" + + self._used_names.add(candidate) + self._base_count[base] = num + if obj is not None: + self._obj_to_name[obj] = candidate + return candidate + + def associate_name_with_obj(self, name: str, obj: Any): + """Associate a unique name with an object. + + Neither `name` nor `obj` should be associated already. + """ + maybe_existing = self._obj_to_name.setdefault(obj, name) + assert maybe_existing is name, "obj is already associated" + + def _rename_object(self, obj: Any, name: str): + assert obj in self._obj_to_name + self._obj_to_name[obj] = name + self._used_names.add(name) + + +dtype_abbrs = { + torch.bfloat16: "bf16", + torch.float64: "f64", + torch.float32: "f32", + torch.float16: "f16", + torch.float8_e4m3fn: "f8e4m3fn", + torch.float8_e5m2: "f8e5m2", + torch.float8_e4m3fnuz: "f8e4m3fnuz", + torch.float8_e5m2fnuz: "f8e5m2fnuz", + torch.float8_e8m0fnu: "f8e8m0fnu", + torch.complex32: "c32", + torch.complex64: "c64", + torch.complex128: "c128", + torch.int8: "i8", + torch.int16: "i16", + torch.int32: "i32", + torch.int64: "i64", + torch.bool: "b8", + torch.uint8: "u8", + torch.uint16: "u16", + torch.uint32: "u32", + torch.uint64: "u64", + torch.bits16: "b16", + torch.bits1x8: "b1x8", +} + + +@compatibility(is_backward_compatible=True) +@dataclass +class PythonCode: + """ + Represents all the information necessary to exec or save a graph as Python code. + """ + + # Python source code for the forward function definition. + src: str + # Values in global scope during execution of `src_def`. + globals: dict[str, Any] + # Optional mapping from the forward function's line number to + # node index. + _lineno_map: Optional[dict[int, Optional[int]]] + + +def _format_target(base: str, target: str) -> str: + elems = target.split(".") + r = base + for e in elems: + if not e.isidentifier(): + r = f'getattr({r}, "{e}")' + else: + r = f"{r}.{e}" + return r + + +class _InsertPoint: + def __init__(self, graph, new_insert): + self.graph = graph + self.orig_insert, graph._insert = graph._insert, new_insert + + def __enter__(self): + pass + + def __exit__(self, type, value, tb): + self.graph._insert = self.orig_insert + + +class _node_list: + def __init__(self, graph: "Graph", direction: Literal["_prev", "_next"] = "_next"): + assert direction in ("_next", "_prev") + self.graph = graph + self.direction = direction + + def __len__(self): + return self.graph._len + + def __iter__(self): + return _NodeIter(self.graph._root, self.direction == "_prev") + + def __reversed__(self): + return _node_list(self.graph, "_next" if self.direction == "_prev" else "_prev") + + +class _PyTreeInfo(NamedTuple): + """ + Contains extra info stored when we're using Pytrees + """ + + orig_args: list[str] + in_spec: pytree.TreeSpec + out_spec: Optional[pytree.TreeSpec] + + +@dataclass(frozen=True) +class _ParsedStackTrace: + """ + Represents the top-most frame of a parsed stack trace + """ + + file: str + lineno: str + name: str + code: str + + def get_summary_str(self): + return f"File: {self.file}:{self.lineno} in {self.name}, code: {self.code}" + + +# get File:lineno code from stack_trace +def _parse_stack_trace(stack_trace: str): + if stack_trace is None: + return None + pattern = re.compile(r"^File \"(.+)\", line (\d+), in (.+)$") + lines = stack_trace.strip().split("\n") + # stacktrace should have innermost frame last, so we + # iterate backwards to find the first line that starts + # with 'File ' + for idx in range(len(lines) - 2, -1, -1): + line = lines[idx].strip() + matches = pattern.match(line) + if matches: + file = matches.group(1) + lineno = matches.group(2) + name = matches.group(3) + # next line should be the code + code = lines[idx + 1].strip() + return _ParsedStackTrace(file, lineno, name, code) + return None + + +@compatibility(is_backward_compatible=False) +class CodeGen: + def __init__(self): + self._body_transformer: Optional[TransformCodeFunc] = None + self._func_name: str = "forward" + + def gen_fn_def(self, free_vars: list[str], maybe_return_annotation: str) -> str: + """ + Given the free variables and a return annotation, generates the beginning of the FX function. + By default, `gen_fn_def(['a', 'b'], '') == 'def {self._func_name}(a, b):'` + """ + # If the original function didn't have self as its first argument, we + # would have added it. + if len(free_vars) == 0 or free_vars[0] != "self": + free_vars.insert(0, "self") + return ( + f"def {self._func_name}({', '.join(free_vars)}){maybe_return_annotation}:" + ) + + def generate_output(self, output_args: Argument) -> str: + """ + Given the output arguments, generates the return statement of the FX function. + Note: The returned statement should not be indented. + """ + return f"return {repr(output_args)}" + + def process_inputs(self, *args: Any) -> Any: + """ + Transforms the inputs so that the graph can take them as arguments, as + non-default codegen may result in the inputs to the function being + different from the inputs to the graph. + + If the graph was directly runnable, this invariant should hold true + `f.graph.process_outputs(f.graph(*f.graph.process_inputs(*inputs))) == f(*inputs)` + """ + return args + + def process_outputs(self, outputs: Any) -> Any: + """ + Transforms the outputs of the graph to be identical to the codegen. + + See ``process_inputs`` for more details. + """ + return outputs + + def additional_globals(self) -> list[tuple[str, Any]]: + """ + If your codegen uses extra global values, add tuples of (identifier,reference to the value) here. + For example, return ['List', typing.List] if you need ``List`` in the global context. + """ + return [] + + def _gen_python_code( + self, + nodes, + root_module: str, + namespace: _Namespace, + *, + verbose: bool = False, + include_stride: bool = False, + include_device: bool = False, + colored: bool = False, + ) -> PythonCode: + free_vars: list[str] = [] + body: list[str] = [] + globals_: dict[str, Any] = {} + wrapped_fns: dict[str, None] = {} + + # Wrap string in list to pass by reference + maybe_return_annotation: list[str] = [""] + include_stride = include_stride or ( + os.environ.get("FX_GRAPH_SHOW_STRIDE", "0") == "1" + ) + include_device = include_device or ( + os.environ.get("FX_GRAPH_SHOW_DEVICE", "0") == "1" + ) + + def add_global(name_hint: str, obj: Any): + """Add an obj to be tracked as a global. + + We call this for names that reference objects external to the + Graph, like functions or types. + + Returns: the global name that should be used to reference 'obj' in generated source. + """ + if ( + _is_from_torch(obj) and obj != torch.device + ): # to support registering torch.device + # HACK: workaround for how torch custom ops are registered. We + # can't import them like normal modules so they must retain their + # fully qualified name. + return _get_qualified_name(obj) + + # normalize the name hint to get a proper identifier + global_name = namespace.create_name(name_hint, obj) + + if global_name in globals_: + assert globals_[global_name] is obj + return global_name + globals_[global_name] = obj + return global_name + + # Pre-fill the globals table with registered builtins. + for name, (_, obj) in _custom_builtins.items(): + add_global(name, obj) + + def type_repr(o: Any): + if o == (): + # Empty tuple is used for empty tuple type annotation Tuple[()] + return "()" + + typename = _type_repr(o) + + if origin_type := getattr(o, "__origin__", None): + # list[...], typing.List[...], TensorType[...] + + if isinstance(o, typing._GenericAlias): # type: ignore[attr-defined] + # This is a generic pre-PEP585 type, e.g. typing.List[torch.Tensor] + origin_type = _origin_type_map.get(origin_type, origin_type) + + origin_typename = add_global(_type_repr(origin_type), origin_type) + + if hasattr(o, "__args__"): + # Assign global names for each of the inner type variables. + args = [type_repr(arg) for arg in o.__args__] + + if len(args) == 0: + # Bare type, such as `typing.Tuple` with no subscript + # This code-path used in Python < 3.9 + return origin_typename + + return f'{origin_typename}[{",".join(args)}]' + else: + # Bare type, such as `typing.Tuple` with no subscript + # This code-path used in Python 3.9+ + return origin_typename + + # Common case: this is a regular module name like 'foo.bar.baz' + return add_global(typename, o) + + if colored: + red = _color_fns["red"] + dim_green = _color_fns["dim_green"] + dim = _color_fns["dim"] + dim_blue = _color_fns["dim_blue"] + blue = _color_fns["blue"] + else: + red = _identity + dim_green = _identity + dim = _identity + dim_blue = _identity + blue = _identity + + def _get_repr(arg: Any) -> str: + if isinstance(arg, Node): # first because common + return repr(arg) + elif isinstance(arg, tuple) and hasattr(arg, "_fields"): + # Handle NamedTuples (if it has `_fields`) via add_global. + qualified_name = _get_qualified_name(type(arg)) + global_name = add_global(qualified_name, type(arg)) + return f"{global_name}{repr(tuple(arg))}" + elif isinstance( + arg, (torch._ops.OpOverload, torch._ops.HigherOrderOperator) + ): + qualified_name = _get_qualified_name(arg) + global_name = add_global(qualified_name, arg) + return f"{global_name}" + elif isinstance(arg, enum.Enum): + cls = arg.__class__ + clsname = add_global(cls.__name__, cls) + return f"{clsname}.{arg.name}" + elif isinstance(arg, torch.Tensor): + size = list(arg.size()) + dtype = str(arg.dtype).split(".")[-1] + return f"torch.Tensor(size={size}, dtype={dtype})" + elif isinstance(arg, tuple): + if len(arg) == 1: + return f"({_get_repr(arg[0])},)" + else: + return "(" + ", ".join(_get_repr(a) for a in arg) + ")" + elif isinstance(arg, list): + return "[" + ", ".join(_get_repr(a) for a in arg) + "]" + elif isinstance(arg, slice): + return f"slice({_get_repr(arg.start)}, {_get_repr(arg.stop)}, {_get_repr(arg.step)})" + else: + return blue(repr(arg)) + + def _format_args( + args: tuple[Argument, ...], kwargs: dict[str, Argument] + ) -> str: + res = [_get_repr(a) for a in args] + res.extend([f"{k} = {_get_repr(v)}" for k, v in kwargs.items()]) + return ", ".join(res) + + # Run through reverse nodes and record the first instance of a use + # of a given node. This represents the *last* use of the node in the + # execution order of the program, which we will use to free unused + # values + node_to_last_use: dict[Node, Node] = {} + user_to_last_uses: dict[Node, list[Node]] = {} + + def register_last_uses(n: Node, user: Node): + if n not in node_to_last_use: + node_to_last_use[n] = user + user_to_last_uses.setdefault(user, []).append(n) + + for node in reversed(nodes): + for input_node in node._input_nodes: + register_last_uses(input_node, node) + + def delete_unused_values(user: Node): + """ + Delete values after their last use. This ensures that values that are + not used in the remainder of the code are freed and the memory usage + of the code is optimal. + """ + if user.op == "placeholder": + return + if user.op == "output": + body.append("\n") + return + nodes_to_delete = user_to_last_uses.get(user, []) + + if len(user.users.keys()) == 0: + # This node is not used by any others. however it's also not + # removed by DCE since side-effect. We want to free it's outputs + # right after its execution done to save memory. + nodes_to_delete.append(user) + + if len(nodes_to_delete): + to_delete_str = " = ".join( + [repr(n) for n in nodes_to_delete] + ["None"] + ) + body.append(f"; {dim(to_delete_str)}\n") + else: + body.append("\n") + + prev_stacktrace = None + + def append_stacktrace_summary(node: Node): + """ + Append a summary of the stacktrace to the generated code. This is + useful for debugging. + """ + nonlocal prev_stacktrace + + if node.op not in {"placeholder", "output"}: + stack_trace = node.stack_trace + if stack_trace: + if stack_trace != prev_stacktrace: + prev_stacktrace = stack_trace + if parsed_stack_trace := _parse_stack_trace(stack_trace): + summary_str = parsed_stack_trace.get_summary_str() + else: + summary_str = "" + body.append(f'\n {dim(f"# {summary_str}")}\n') + elif prev_stacktrace != "": + prev_stacktrace = "" + no_stacktrace_msg = "# No stacktrace found for following nodes" + body.append(f"\n{dim(no_stacktrace_msg)}\n") + + def stringify_shape(shape: Iterable) -> str: + return f"[{', '.join([str(x) for x in shape])}]" + + def emit_node(node: Node): + maybe_type_annotation = ( + "" if node.type is None else f" : {type_repr(node.type)}" + ) + + if verbose: + # override annotation with more detailed information + from torch.fx.experimental.proxy_tensor import py_sym_types + from torch.fx.passes.shape_prop import TensorMetadata + + meta_val = node.meta.get( + "val", + node.meta.get("tensor_meta", node.meta.get("example_value", None)), + ) + # use string as annotation, to make it valid python code + if isinstance(meta_val, torch.Tensor) and meta_val.layout not in ( + torch.sparse_csc, + torch.sparse_csr, + ): + stride_annotation = ( + f"{stringify_shape(meta_val.stride())}" + if include_stride + else "" + ) + device_annotation = f"{meta_val.device}" if include_device else "" + maybe_type_annotation = ( + f': "{red(dtype_abbrs[meta_val.dtype])}{blue(stringify_shape(meta_val.shape))}' + f'{dim_blue(stride_annotation)}{dim_green(device_annotation)}"' + ) + elif isinstance(meta_val, py_sym_types): + maybe_type_annotation = f': "Sym({meta_val})"' + elif isinstance(meta_val, TensorMetadata): + maybe_type_annotation = f': "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}"' + + if node.op == "placeholder": + assert isinstance(node.target, str) + maybe_default_arg = ( + "" if not node.args else f" = {_get_repr(node.args[0])}" + ) + free_vars.append( + f"{node.target}{maybe_type_annotation}{maybe_default_arg}" + ) + raw_name = node.target.replace("*", "") + if raw_name != repr(node): + body.append(f"{repr(node)} = {raw_name}\n") + return + elif node.op == "call_method": + assert isinstance(node.target, str) + body.append( + f"{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.target)}" + f"({_format_args(node.args[1:], node.kwargs)})" + ) + return + elif node.op == "call_function": + assert callable(node.target) + # pretty print operators + if ( + getattr(node.target, "__module__", "") == "_operator" + and node.target.__name__ in magic_methods + ): + assert isinstance(node.args, tuple) + body.append( + f"{repr(node)}{maybe_type_annotation} = " + f"{magic_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}" + ) + return + + # pretty print inplace operators; required for jit.script to work properly + # not currently supported in normal FX graphs, but generated by torchdynamo + if ( + getattr(node.target, "__module__", "") == "_operator" + and node.target.__name__ in inplace_methods + ): + body.append( + f"{inplace_methods[node.target.__name__].format(*(_get_repr(a) for a in node.args))}; " + f"{repr(node)}{maybe_type_annotation} = {_get_repr(node.args[0])}" + ) + return + + qualified_name = _get_qualified_name(node.target) + global_name = add_global(qualified_name, node.target) + # special case for getattr: node.args could be 2-argument or 3-argument + # 2-argument: attribute access; 3-argument: fall through to attrib function call with default value + if ( + global_name == "getattr" + and isinstance(node.args, tuple) + and isinstance(node.args[1], str) + and node.args[1].isidentifier() + and len(node.args) == 2 + ): + body.append( + f"{repr(node)}{maybe_type_annotation} = {_format_target(_get_repr(node.args[0]), node.args[1])}" + ) + return + body.append( + f"{repr(node)}{maybe_type_annotation} = {global_name}({_format_args(node.args, node.kwargs)})" + ) + if node.meta.get("is_wrapped", False): + wrapped_fns.setdefault(global_name) + return + elif node.op == "call_module": + assert isinstance(node.target, str) + body.append( + f"{repr(node)}{maybe_type_annotation} = " + f"{_format_target(root_module, node.target)}({_format_args(node.args, node.kwargs)})" + ) + return + elif node.op == "get_attr": + assert isinstance(node.target, str) + body.append( + f"{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}" + ) + return + elif node.op == "output": + if node.type is not None: + maybe_return_annotation[0] = f" -> {type_repr(node.type)}" + body.append(self.generate_output(node.args[0])) + return + raise NotImplementedError(f"node: {node.op} {node.target}") + + for i, node in enumerate(nodes): + # NOTE: emit_node does not emit a string with newline. It depends + # on delete_unused_values to append one + if verbose: + append_stacktrace_summary(node) + # emit a counter comment to keep track of + # node index, which will be deleted later + # after going through _body_transformer + body.append(f"# COUNTER: {i}\n") + emit_node(node) + delete_unused_values(node) + + if len(body) == 0: + # If the Graph has no non-placeholder nodes, no lines for the body + # have been emitted. To continue to have valid Python code, emit a + # single pass statement + body.append("pass\n") + + if len(wrapped_fns) > 0: + wrap_name = add_global("wrap", torch.fx.wrap) + wrap_stmts = "\n".join([f'{wrap_name}("{name}")' for name in wrapped_fns]) + else: + wrap_stmts = "" + + if self._body_transformer: + body = self._body_transformer(body) + + for name, value in self.additional_globals(): + add_global(name, value) + + prologue = self.gen_fn_def(free_vars, maybe_return_annotation[0]) + + # remove counter and generate lineno to node index mapping + lineno_map: dict[int, Optional[int]] = {} + prologue_len = prologue.count("\n") + 1 + new_lines: list[str] = [] + cur_idx = None + for line in "".join(body).split("\n"): + counter = _counter_regexp.search(line) + if counter is not None: + cur_idx = int(counter.group(1)) + else: + lineno_map[len(new_lines) + prologue_len] = cur_idx + new_lines.append(line) + + code = "\n".join(new_lines).lstrip("\n") + code = "\n".join(" " + line for line in code.split("\n")) + + fn_code = f""" +{wrap_stmts} + +{prologue} +{code}""" + return PythonCode(fn_code, globals_, _lineno_map=lineno_map) + + +# Ideally, we'd like to refactor all of the pytree logic into this codegen +# class. Unfortunately, there are 3 areas we currently need extra logic in FX. +# 1. In the initial symbolic trace, the pytree logic is tied up with `concrete_args`. +# 2. In the FX graph, we need to access 2 attributes - in_spec and out_spec. +# Since we can't access .graph within the FX forward, we need to copy the attribute to the module. +# 3. We currently can't register the pytree imports with `add_global` - not sure why. +class _PyTreeCodeGen(CodeGen): + def __init__(self, pytree_info: _PyTreeInfo): + super().__init__() + self.pytree_info: _PyTreeInfo = pytree_info + + def process_inputs(self, *inputs: Any) -> Any: + flat_args = pytree.arg_tree_leaves(*inputs) + return flat_args + + def process_outputs(self, out: Any) -> Any: + if self.pytree_info is None or self.pytree_info.out_spec is None: + return out + if not isinstance(out, (list, tuple)): + out = [out] + assert self.pytree_info.out_spec is not None + return pytree.tree_unflatten(out, self.pytree_info.out_spec) + + def gen_fn_def(self, free_vars, maybe_return_annotation): + # Given a user function/model: + # myargs = [myargs0, myargs1] + # mykwargs = {'mykwargs0': ..., 'mykwargs1': ...} + # def forward(self, mypos, *myargs, mykey=None, **mykwargs): + # + # The generated code flattens all keywords into positional arguments for `forward()` + # e.g forward(self, mypos, myargs0, myargs1, mykey, mykwargs0, mykwargs1): + # + # Within `forward`, `tree_flatten_spec``still parses args and kwargs separately + # e.g. tree_flatten_spec(([mypos, myargs0, myargs1], + # {'mykey':mykey, 'mykwargs0':mykwargs0, 'mykwargs1':mykwargs1}), + # self._in_spec) + # + # If the user function/model does not have keywords, the dict is suppressed from tree_flatten_spec + # e.g. tree_flatten_spec([mypos, myargs0, myargs1]), self._in_spec) + if self.pytree_info is None: + return super().gen_fn_def(free_vars, maybe_return_annotation) + + fn_args = self.pytree_info.orig_args + has_orig_self = (fn_args[0] == "self") if len(fn_args) > 0 else False + if has_orig_self: + free_vars.insert(0, "self") + fn_definition = super().gen_fn_def(fn_args[:], maybe_return_annotation) + + if len(free_vars) > 0: # pytree has placeholders in it + # when kwargs is present, in_spec is tuple(args, kwargs) + has_args_kwargs_tuple = ( + self.pytree_info.in_spec.type == tuple + and self.pytree_info.in_spec.num_children == 2 + and self.pytree_info.in_spec.children_specs[0].type == tuple + and self.pytree_info.in_spec.children_specs[1].type == dict + ) + fn_kwargs = "{}" + fn_signature = f"[{', '.join(fn_args)}], self._in_spec" + if has_args_kwargs_tuple: + count_args = self.pytree_info.in_spec.children_specs[0].num_children + fn_args = self.pytree_info.orig_args[:count_args] + fn_kwargs = ( + "{" + + ", ".join( + f"'{k}':{v}" + for k, v in zip( + self.pytree_info.in_spec.children_specs[1].context, + self.pytree_info.orig_args[count_args:], + ) + ) + + "}" + ) + fn_signature = f"([{', '.join(fn_args)}], {fn_kwargs}), self._in_spec" + + # in Python, `var1: annotation1, var2: annotation2 = function_call()` is invalid. + # we need to split it to two lines: + # one for annotation: `var1: annotation1; var2: annotation2;` (note the semicolon) + # one for code: `var1, var2, = function_call()` + without_annotation = [x.split(":")[0] for x in free_vars] + has_annotation = [x + "; " for x in free_vars if ":" in x] + if len(has_annotation) > 0: + fn_definition += "\n " + "".join(has_annotation) + "\n" + fn_definition += f""" + {', '.join(without_annotation)}, = fx_pytree.tree_flatten_spec({fn_signature})""" + return fn_definition + + def generate_output(self, output_args): + if self.pytree_info and self.pytree_info.out_spec: + return f"return pytree.tree_unflatten({repr(output_args)}, self._out_spec)" + else: + return super().generate_output(output_args) + + +class _FindNodesLookupTable: + """ + Side table for the graph for the purpose of doing fast queries + """ + + def __init__(self): + self.table: dict[tuple[str, Optional[Target]], dict[Node, None]] = defaultdict( + dict + ) + + def _key(self, node) -> tuple[str, Optional[Target]]: + return (node.op, node.target if node.op == "call_function" else None) + + def __contains__(self, node) -> bool: + return node in self.table[self._key(node)] + + def insert(self, node: Node) -> None: + self.table[self._key(node)][node] = None + + def remove(self, node: Node) -> None: + self.table[self._key(node)].pop(node) + + def find_nodes(self, *, op: str, target: Optional["Target"] = None): + if op == "call_function": + assert target is not None + return [*self.table[(op, target)].keys()] + + if target is None: + return [*self.table[(op, None)].keys()] + + # op is call_method, get_attr, call_module + return [node for node in self.table[(op, None)].keys() if node.target == target] + + +@compatibility(is_backward_compatible=True) +class Graph: + """ + ``Graph`` is the main data structure used in the FX Intermediate Representation. + It consists of a series of ``Node`` s, each representing callsites (or other + syntactic constructs). The list of ``Node`` s, taken together, constitute a + valid Python function. + + For example, the following code + + .. code-block:: python + + import torch + import torch.fx + + + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.param = torch.nn.Parameter(torch.rand(3, 4)) + self.linear = torch.nn.Linear(4, 5) + + def forward(self, x): + return torch.topk( + torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3 + ) + + + m = MyModule() + gm = torch.fx.symbolic_trace(m) + + Will produce the following Graph:: + + print(gm.graph) + + .. code-block:: text + + graph(x): + %linear_weight : [num_users=1] = self.linear.weight + %add_1 : [num_users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {}) + %linear_1 : [num_users=1] = call_module[target=linear](args = (%add_1,), kwargs = {}) + %relu_1 : [num_users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {}) + %sum_1 : [num_users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1}) + %topk_1 : [num_users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {}) + return topk_1 + + For the semantics of operations represented in the ``Graph``, please see :class:`Node`. + """ + + @compatibility(is_backward_compatible=True) + def __init__( + self, + owning_module: Optional["GraphModule"] = None, + tracer_cls: Optional[type["Tracer"]] = None, + tracer_extras: Optional[dict[str, Any]] = None, + ): + """ + Construct an empty Graph. + """ + self._root: Node = Node(self, "", "root", "", (), {}) + self._used_names: dict[str, int] = {} # base name -> number + self._insert = self._root.prepend + self._len = 0 + self._graph_namespace = _Namespace() + self._owning_module = owning_module + self._tracer_cls = tracer_cls + self._tracer_extras = tracer_extras + self._codegen = CodeGen() + self._co_fields: dict[str, Any] = {} + self._find_nodes_lookup_table = _FindNodesLookupTable() + + @property + def owning_module(self): + return self._owning_module + + @owning_module.setter + def owning_module(self, mod: Optional["GraphModule"]): + self._owning_module = mod + + @property + def nodes(self) -> _node_list: + """ + Get the list of Nodes that constitute this Graph. + + Note that this ``Node`` list representation is a doubly-linked list. Mutations + during iteration (e.g. delete a Node, add a Node) are safe. + + Returns: + + A doubly-linked list of Nodes. Note that ``reversed`` can be called on + this list to switch iteration order. + """ + return _node_list(self) + + @compatibility(is_backward_compatible=False) + def output_node(self) -> Node: + output_node = next(iter(reversed(self.nodes))) + assert output_node.op == "output" + return output_node + + @compatibility(is_backward_compatible=False) + def find_nodes( + self, *, op: str, target: Optional["Target"] = None, sort: bool = True + ): + """ + Allows for fast query of nodes + + Args: + + op (str): the name of the operation + + target (Optional[Target]): the target of the node. For call_function, + the target is required. For other ops, the target is optional. + + sort (bool): whether to return nodes in the order they appear on + on the graph. + + Returns: + + Iteratable of nodes with the requested op and target. + """ + node_list = self._find_nodes_lookup_table.find_nodes(op=op, target=target) + if sort: + return sorted(node_list) + return node_list + + @compatibility(is_backward_compatible=True) + def graph_copy( + self, g: "Graph", val_map: dict[Node, Node], return_output_node=False + ) -> "Optional[Argument]": + """ + Copy all nodes from a given graph into ``self``. + + Args: + + g (Graph): The source graph from which to copy Nodes. + + val_map (Dict[Node, Node]): a dictionary that will be populated with a mapping + from nodes in ``g`` to nodes in ``self``. Note that ``val_map`` can be passed + in with values in it already to override copying of certain values. + + Returns: + + The value in ``self`` that is now equivalent to the output value in ``g``, + if ``g`` had an ``output`` node. ``None`` otherwise. + """ + for node in g.nodes: + if node in val_map: + continue + if node.op == "output": + rv = map_arg(node.args[0], lambda n: val_map[n]) + return rv if not return_output_node else (rv, node) + val_map[node] = self.node_copy(node, lambda n: val_map[n]) + return None + + def __deepcopy__(self, memo=None) -> "Graph": + """ + Explicitly implement __deepcopy__ to prevent excessive recursion depth + from the default implementation. This uses graph_copy to copy the nodes + in an iterative way, rather than recursive. It also populates the + memoization table to prevent unnecessary copies (e.g. references to + nodes or other parts of the Graph from a custom GraphModule implementation. + """ + memo = memo if memo else {} + g = Graph(tracer_cls=self._tracer_cls) + output_vals = g.graph_copy(self, val_map=memo, return_output_node=True) + g._codegen = copy.deepcopy(self._codegen) + if output_vals is not None: + assert isinstance(output_vals, tuple) + output_val, old_output_node = output_vals + new_output_node = g.output( + output_val, type_expr=getattr(old_output_node, "type", None) + ) + new_output_node.meta = copy.copy(old_output_node.meta) + return g + + @compatibility(is_backward_compatible=True) + def create_node( + self, + op: str, + target: "Target", + args: Optional[tuple["Argument", ...]] = None, + kwargs: Optional[dict[str, "Argument"]] = None, + name: Optional[str] = None, + type_expr: Optional[Any] = None, + ) -> Node: + """ + Create a ``Node`` and add it to the ``Graph`` at the current insert-point. + Note that the current insert-point can be set via :meth:`Graph.inserting_before` + and :meth:`Graph.inserting_after`. + + Args: + op (str): the opcode for this Node. One of 'call_function', 'call_method', 'get_attr', + 'call_module', 'placeholder', or 'output'. The semantics of these opcodes are + described in the ``Graph`` docstring. + + args (Optional[Tuple[Argument, ...]]): is a tuple of arguments to this node. + + kwargs (Optional[Dict[str, Argument]]): the kwargs of this Node + + name (Optional[str]): an optional string name for the ``Node``. + This will influence the name of the value assigned to in the + Python generated code. + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + Returns: + + The newly-created and inserted node. + """ + # `target in _legal_ops` is checked in Node.__init__ + if not args: + args = () + else: + assert isinstance(args, tuple), "args must be a tuple" + if not kwargs: + kwargs = immutable_dict() + else: + assert isinstance(kwargs, dict), "kwargs must be a dict" + + candidate = name if name is not None else self._target_to_str(target) + name = self._graph_namespace.create_name(candidate, None) + n = Node(self, name, op, target, args, kwargs, type_expr) + + if ( + self.owning_module is not None + and getattr(self.owning_module, "_create_node_hooks", None) is not None + ): + for f in self.owning_module._create_node_hooks: + f(n) + + self._graph_namespace.associate_name_with_obj(name, n) + + self._insert(n) + self._find_nodes_lookup_table.insert(n) + self._len += 1 + return n + + @compatibility(is_backward_compatible=False) + def process_inputs(self, *args): + """ + Processes args so that they can be passed to the FX graph. + """ + return self._codegen.process_inputs(*args) + + @compatibility(is_backward_compatible=False) + def process_outputs(self, out): + return self._codegen.process_outputs(out) + + @compatibility(is_backward_compatible=True) + def erase_node(self, to_erase: Node) -> None: + """ + Erases a ``Node`` from the ``Graph``. Throws an exception if + there are still users of that node in the ``Graph``. + + Args: + + to_erase (Node): The ``Node`` to erase from the ``Graph``. + """ + if len(to_erase.users) > 0: + raise RuntimeError( + f"Tried to erase Node {to_erase} but it still had {len(to_erase.users)} " + f"users in the graph: {to_erase.users}!" + ) + if to_erase.graph != self: + raise RuntimeError(f"Attempting to remove {to_erase} from wrong graph!") + if to_erase._erased: + warnings.warn(f"erase_node({to_erase}) on an already erased node") + return + + if ( + self.owning_module is not None + and getattr(self.owning_module, "_erase_node_hooks", None) is not None + ): + for f in self.owning_module._erase_node_hooks: + f(to_erase) + + self._find_nodes_lookup_table.remove(to_erase) + to_erase._remove_from_list() + to_erase._erased = True # iterators may retain handles to erased nodes + self._len -= 1 + + # Null out this Node's argument nodes so that the Nodes referred to + # can update their ``users`` accordingly + to_erase._update_args_kwargs( + map_arg(to_erase._args, lambda n: None), + map_arg(to_erase._kwargs, lambda n: None), + ) + + @compatibility(is_backward_compatible=True) + def inserting_before(self, n: Optional[Node] = None): + """Set the point at which create_node and companion methods will insert into the graph. + When used within a 'with' statement, this will temporary set the insert point and + then restore it when the with statement exits:: + + with g.inserting_before(n): + ... # inserting before node n + ... # insert point restored to what it was previously + g.inserting_before(n) # set the insert point permanently + + Args: + + n (Optional[Node]): The node before which to insert. If None this will insert before + the beginning of the entire graph. + + Returns: + A resource manager that will restore the insert point on ``__exit__``. + """ + if n is None: + return self.inserting_after(self._root) + assert n.graph == self, "Node to insert before is not in graph." + return _InsertPoint(self, n.prepend) + + @compatibility(is_backward_compatible=True) + def inserting_after(self, n: Optional[Node] = None): + """Set the point at which create_node and companion methods will insert into the graph. + When used within a 'with' statement, this will temporary set the insert point and + then restore it when the with statement exits:: + + with g.inserting_after(n): + ... # inserting after node n + ... # insert point restored to what it was previously + g.inserting_after(n) # set the insert point permanently + + Args: + + n (Optional[Node]): The node before which to insert. If None this will insert after + the beginning of the entire graph. + + Returns: + A resource manager that will restore the insert point on ``__exit__``. + """ + if n is None: + return self.inserting_before(self._root) + assert n.graph == self, "Node to insert after is not in graph." + return _InsertPoint(self, n.append) + + @compatibility(is_backward_compatible=True) + def placeholder( + self, + name: str, + type_expr: Optional[Any] = None, + default_value: Any = inspect.Signature.empty, + ) -> Node: + """ + Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents + a function input. + + Args: + + name (str): A name for the input value. This corresponds to the name + of the positional argument to the function this ``Graph`` represents. + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. This is needed in some + cases for proper code generation (e.g. when the function is used + subsequently in TorchScript compilation). + + default_value (Any): The default value this function argument should take + on. NOTE: to allow for `None` as a default value, `inspect.Signature.empty` + should be passed as this argument to specify that the parameter does _not_ + have a default value. + + .. note:: + The same insertion point and type expression rules apply for this method + as ``Graph.create_node``. + """ + args = () if default_value is inspect.Signature.empty else (default_value,) + return self.create_node("placeholder", name, args=args, type_expr=type_expr) + + @compatibility(is_backward_compatible=True) + def get_attr(self, qualified_name: str, type_expr: Optional[Any] = None) -> Node: + """ + Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the + fetch of an attribute from the ``Module`` hierarchy. + + Args: + + qualified_name (str): the fully-qualified name of the attribute to be retrieved. + For example, if the traced Module has a submodule named ``foo``, which has a + submodule named ``bar``, which has an attribute named ``baz``, the qualified + name ``foo.bar.baz`` should be passed as ``qualified_name``. + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + + Returns: + + The newly-created and inserted ``get_attr`` node. + + .. note:: + The same insertion point and type expression rules apply for this method + as ``Graph.create_node``. + """ + + def _get_attr_reference_exists( + mod: torch.nn.Module, qualified_name: str + ) -> bool: + module_path, _, name = qualified_name.rpartition(".") + + try: + submod: torch.nn.Module = mod.get_submodule(module_path) + except AttributeError: + warnings.warn(f"Failed to fetch module {module_path}!") + return False + + if not hasattr(submod, name): + return False + + res = getattr(submod, name) + + if ( + not isinstance(res, torch.nn.Module) + and not isinstance(res, torch.nn.Parameter) + and name not in submod._buffers + ): + return False + + return True + + if self.owning_module and not _get_attr_reference_exists( + self.owning_module, qualified_name + ): + warnings.warn( + "Attempted to insert a get_attr Node with no " + "underlying reference in the owning " + "GraphModule! Call " + "GraphModule.add_submodule to add the " + "necessary submodule, " + "GraphModule.add_parameter to add the " + "necessary Parameter, or " + "nn.Module.register_buffer to add the " + "necessary buffer", + stacklevel=2, + ) + return self.create_node("get_attr", qualified_name, type_expr=type_expr) + + @compatibility(is_backward_compatible=True) + def call_module( + self, + module_name: str, + args: Optional[tuple["Argument", ...]] = None, + kwargs: Optional[dict[str, "Argument"]] = None, + type_expr: Optional[Any] = None, + ) -> Node: + """ + Insert a ``call_module`` ``Node`` into the ``Graph``. A ``call_module`` node + represents a call to the forward() function of a ``Module`` in the ``Module`` + hierarchy. + + Args: + + module_name (str): The qualified name of the ``Module`` in the ``Module`` + hierarchy to be called. For example, if the traced ``Module`` has a + submodule named ``foo``, which has a submodule named ``bar``, the + qualified name ``foo.bar`` should be passed as ``module_name`` to + call that module. + + args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed + to the called method. Note that this should *not* include a ``self`` argument. + + kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed + to the called method + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + Returns: + + The newly-created and inserted ``call_module`` node. + + .. note:: + The same insertion point and type expression rules apply for this method + as :meth:`Graph.create_node`. + """ + if self.owning_module and self.owning_module.get_submodule(module_name) is None: + warnings.warn( + "Attempted to insert a call_module Node with " + "no underlying reference in the owning " + "GraphModule! Call " + "GraphModule.add_submodule to add the " + "necessary submodule" + ) + return self.create_node( + "call_module", module_name, args, kwargs, type_expr=type_expr + ) + + @compatibility(is_backward_compatible=True) + def call_method( + self, + method_name: str, + args: Optional[tuple["Argument", ...]] = None, + kwargs: Optional[dict[str, "Argument"]] = None, + type_expr: Optional[Any] = None, + ) -> Node: + """ + Insert a ``call_method`` ``Node`` into the ``Graph``. A ``call_method`` node + represents a call to a given method on the 0th element of ``args``. + + Args: + + method_name (str): The name of the method to apply to the self argument. + For example, if args[0] is a ``Node`` representing a ``Tensor``, + then to call ``relu()`` on that ``Tensor``, pass ``relu`` to ``method_name``. + + args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed + to the called method. Note that this *should* include a ``self`` argument. + + kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed + to the called method + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + Returns: + + The newly created and inserted ``call_method`` node. + + .. note:: + The same insertion point and type expression rules apply for this method + as :meth:`Graph.create_node`. + """ + return self.create_node( + "call_method", method_name, args, kwargs, type_expr=type_expr + ) + + @compatibility(is_backward_compatible=True) + def call_function( + self, + the_function: Callable[..., Any], + args: Optional[tuple["Argument", ...]] = None, + kwargs: Optional[dict[str, "Argument"]] = None, + type_expr: Optional[Any] = None, + ) -> Node: + """ + Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node + represents a call to a Python callable, specified by ``the_function``. + + Args: + + the_function (Callable[..., Any]): The function to be called. Can be any PyTorch + operator, Python function, or member of the ``builtins`` or ``operator`` + namespaces. + + args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed + to the called function. + + kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed + to the called function + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + Returns: + + The newly created and inserted ``call_function`` node. + + .. note:: + The same insertion point and type expression rules apply for this method + as :meth:`Graph.create_node`. + """ + return self.create_node( + "call_function", the_function, args, kwargs, type_expr=type_expr + ) + + @compatibility(is_backward_compatible=True) + def node_copy( + self, node: Node, arg_transform: Callable[[Node], "Argument"] = lambda x: x + ) -> Node: + """ + Copy a node from one graph into another. ``arg_transform`` needs to transform arguments from + the graph of node to the graph of self. Example:: + + # Copying all the nodes in `g` into `new_graph` + g: torch.fx.Graph = ... + new_graph = torch.fx.graph() + value_remap = {} + for node in g.nodes: + value_remap[node] = new_graph.node_copy(node, lambda n: value_remap[n]) + + Args: + + node (Node): The node to copy into ``self``. + + arg_transform (Callable[[Node], Argument]): A function that transforms + ``Node`` arguments in node's ``args`` and ``kwargs`` into the + equivalent argument in ``self``. In the simplest case, this should + retrieve a value out of a table mapping Nodes in the original + graph to ``self``. + """ + args = map_arg(node.args, arg_transform) + kwargs = map_arg(node.kwargs, arg_transform) + assert isinstance(args, tuple) + assert isinstance(kwargs, dict) + result_node = self.create_node( + node.op, node.target, args, kwargs, node.name, node.type + ) + result_node.meta = copy.copy(node.meta) + return result_node + + @compatibility(is_backward_compatible=True) + def output(self, result: "Argument", type_expr: Optional[Any] = None): + """ + Insert an ``output`` ``Node`` into the ``Graph``. An ``output`` node represents + a ``return`` statement in Python code. ``result`` is the value that should + be returned. + + Args: + + result (Argument): The value to be returned. + + type_expr (Optional[Any]): an optional type annotation representing the + Python type the output of this node will have. + + .. note:: + + The same insertion point and type expression rules apply for this method + as ``Graph.create_node``. + """ + return self.create_node( + op="output", target="output", args=(result,), type_expr=type_expr + ) + + def _target_to_str(self, target: Target) -> str: + if callable(target): + op = target.__name__ + else: + assert isinstance(target, str) + op = target + if _is_magic(op): + op = op[2:-2] + op = _snake_case(op) + return op + + @compatibility(is_backward_compatible=True) + def python_code( + self, + root_module: str, + *, + verbose: bool = False, + include_stride: bool = False, + include_device: bool = False, + colored: bool = False, + ) -> PythonCode: + """ + Turn this ``Graph`` into valid Python code. + + Args: + + root_module (str): The name of the root module on which to look-up + qualified name targets. This is usually 'self'. + + Returns: + + A PythonCode object, consisting of two fields: + src: the Python source code representing the object + globals: a dictionary of global names in `src` -> the objects that they reference. + """ + # NOTE: [Graph Namespaces] + # + # There are two types of symbols in generated Python source code: + # locals and globals. + # Locals are locally defined by the output of a node in the Graph. + # Globals are references to external objects, like functions or types. + # + # When generating Python code, we need to make sure to name things + # appropriately. In particular: + # - All names should be unique, to avoid weird shadowing bugs. + # - These names need to be consistent, e.g. a object should always be + # referenced by the same name. + # + # To do this, we create a new namespace just for this source. All names + # that get printed must come from this namespace. + # + # Why can't we re-use node.name? Because it was generated within the + # namespace `self._graph_namespace`. In order to provide uniqueness + # over both locals (node.name) *and* globals, we create a completely + # new namespace to put all identifiers in. + namespace = _Namespace() + + # Override Node's repr to generate a valid name within our namespace. + # Since repr() is designed to produce a valid Python expression, it + # makes sense to re-use it. This way, it's easy to print something like + # Tuple[Node, Node] by simply calling repr() on it. Node's __repr__ is + # implemented cooperatively to allow this. + def node_repr(n: Node): + return namespace.create_name(n.name, n) + + @contextmanager + def override_node_repr(graph: Graph): + orig_repr_fns = {} + for node in graph.nodes: + orig_repr_fns[node] = node._repr_fn + node._repr_fn = node_repr + try: + yield None + finally: + # restore the original repr functions + for node in graph.nodes: + node._repr_fn = orig_repr_fns[node] + + with override_node_repr(self): + return self._python_code( + root_module, + namespace, + verbose=verbose, + include_stride=include_stride, + include_device=include_device, + colored=colored, + ) + + def _python_code( + self, + root_module: str, + namespace: _Namespace, + *, + verbose: bool = False, + include_stride: bool = False, + include_device: bool = False, + colored: bool = False, + ) -> PythonCode: + return self._codegen._gen_python_code( + self.nodes, + root_module, + namespace, + verbose=verbose, + include_stride=include_stride, + include_device=include_device, + colored=colored, + ) + + def __str__(self) -> str: + """ + Return a human-readable (not machine-readable) string representation + of this Graph + """ + placeholder_names: list[str] = [] + # This is a one-element array just so ``format_node`` can modify the closed + # over value + maybe_return_typename: list[str] = [""] + + node_strs = [node.format_node(placeholder_names) for node in self.nodes] + param_str = ", ".join(placeholder_names) + s = f"graph({param_str}){maybe_return_typename[0]}:" + for node_str in node_strs: + if node_str: + s += "\n " + node_str + return s + + @compatibility(is_backward_compatible=True) + def print_tabular(self): + """ + Prints the intermediate representation of the graph in tabular + format. Note that this API requires the ``tabulate`` module to be + installed. + """ + try: + from tabulate import tabulate + except ImportError: + print( + "`print_tabular` relies on the library `tabulate`, " + "which could not be found on this machine. Run `pip " + "install tabulate` to install the library." + ) + raise + + node_specs = [[n.op, n.name, n.target, n.args, n.kwargs] for n in self.nodes] + print( + tabulate(node_specs, headers=["opcode", "name", "target", "args", "kwargs"]) + ) + + @compatibility(is_backward_compatible=True) + def lint(self): + """ + Runs various checks on this Graph to make sure it is well-formed. In + particular: + - Checks Nodes have correct ownership (owned by this graph) + - Checks Nodes appear in topological order + - If this Graph has an owning GraphModule, checks that targets + exist in that GraphModule + """ + + # Check topo order + def check_arg(arg: Node, n: Optional[Node] = None) -> None: + context_str = f" of Node '{n}' " if n else " " + if arg.graph is not self: + raise RuntimeError( + f"Argument '{arg}'{context_str}does not belong to this Graph, " + f"but was used as an argument! If you are copying nodes from another graph, make " + f"sure to use ``arg_transform`` on node_copy() to remap values\n{self}" + ) + if arg not in seen_values: + raise RuntimeError( + f"Argument '{arg}'{context_str}was used before it has been " + f"defined! Please check that Nodes in the graph are topologically ordered\n{self}" + ) + + seen_names: set[str] = set() + seen_values: set[Node] = set() + for node in self.nodes: + if node.op not in _legal_ops: + raise RuntimeError(f"Node {node} had unknown opcode {node.op}!") + if node.graph is not self: + raise RuntimeError(f"Node '{node}' does not belong to this Graph!") + if node not in self._find_nodes_lookup_table: + raise RuntimeError(f"Node '{node}' is not added to the side table") + for arg in node._input_nodes: + check_arg(arg, node) + seen_values.add(node) + + if node.name in seen_names: + raise RuntimeError(f"Node redefined name {node.name}!") + seen_names.add(node.name) + + # Check targets are legit + if self.owning_module: + num_warnings = 0 + MAX_WARNINGS = 5 + for node in self.nodes: + if node.op == "call_function": + if not callable(node.target): + raise ValueError( + f"Node {node} target {node.target} has type {torch.typename(node.target)} but " + "a Callable is expected" + ) + else: + if not isinstance(node.target, str): + raise ValueError( + f"Node {node} target {node.target} has type {torch.typename(node.target)} but " + "a str is expected" + ) + if node.op in ["get_attr", "call_module"]: + target_atoms = node.target.split(".") + m_itr = self.owning_module + for i, atom in enumerate(target_atoms): + new_m_itr = getattr(m_itr, atom, None) + seen_qualname = ".".join(target_atoms[:i]) + if new_m_itr is None: + raise RuntimeError( + f"Node {node} target {node.target} references nonexistent attribute " + f"{atom} of {seen_qualname}" + ) + if node.op == "call_module" and not isinstance( + new_m_itr, torch.nn.Module + ): + raise RuntimeError( + f"Node {node} target {node.target} {atom} of {seen_qualname} does " + "not reference an nn.Module" + ) + elif ( + node.op == "get_attr" + and not isinstance(new_m_itr, torch.nn.Module) + and not isinstance(new_m_itr, torch.nn.Parameter) + and atom not in m_itr._buffers + ): + if num_warnings < MAX_WARNINGS: + # Don't emit this warning too frequently, + # for very large graphs this can become very expensive + # from a performance perspective. + warnings.warn( + f"Node {node} target {node.target} {atom} of {seen_qualname} does " + "not reference an nn.Module, nn.Parameter, or buffer, which is " + "what 'get_attr' Nodes typically target" + ) + num_warnings += 1 + else: + m_itr = new_m_itr + if num_warnings > MAX_WARNINGS: + warnings.warn( + f"Additional {num_warnings - MAX_WARNINGS} warnings " + "suppressed about get_attr references" + ) + + @compatibility(is_backward_compatible=True) + def eliminate_dead_code( + self, is_impure_node: Optional[Callable[[Node], bool]] = None + ) -> bool: + """ + Remove all dead code from the graph, based on each node's number of + users, and whether the nodes have any side effects. The graph must be + topologically sorted before calling. + + Args: + is_impure_node (Optional[Callable[[Node], bool]]): A function that returns + whether a node is impure. If this is None, then the default behavior is to + use Node.is_impure. + + Returns: + bool: Whether the graph was changed as a result of the pass. + + Example: + + Before dead code is eliminated, `a` from `a = x + 1` below has no users + and thus can be eliminated from the graph without having an effect. + + .. code-block:: python + + def forward(self, x): + a = x + 1 + return x + self.attr_1 + + After dead code is eliminated, `a = x + 1` has been removed, and the rest + of `forward` remains. + + .. code-block:: python + + def forward(self, x): + return x + self.attr_1 + + .. warning:: + + Dead code elimination has some heuristics to avoid removing + side-effectful nodes (see Node.is_impure) but in general coverage + is very bad, so you should assume that this method is not sound + to call unless you know that your FX graph consists entirely + of functional operations or you supply your own custom + function for detecting side-effectful nodes. + """ + # Lint the graph first to make sure its topologically sorted, otherwise + # DCE below will not behave as expected. + self.lint() + + def has_side_effect(node): + if is_impure_node is not None: + return is_impure_node(node) + return node.is_impure() + + # Reverse iterate so that when we remove a node, any nodes used as an + # input to that node have an updated user count that no longer reflects + # the removed node. + changed = False + for node in reversed(self.nodes): + if not has_side_effect(node) and len(node.users) == 0: + self.erase_node(node) + changed = True + + return changed + + @compatibility(is_backward_compatible=False) + def set_codegen(self, codegen: CodeGen): + self._codegen = codegen + + @compatibility(is_backward_compatible=False) + def on_generate_code( + self, + make_transformer: Callable[[Optional[TransformCodeFunc]], TransformCodeFunc], + ): + """Register a transformer function when python code is generated + + Args: + make_transformer (Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]): + a function that returns a code transformer to be registered. + This function is called by `on_generate_code` to obtain the + code transformer. + + This function is also given as its input the currently + registered code transformer (or None if nothing is registered), + in case it is not desirable to overwrite it. This is useful to + chain code transformers together. + + Returns: + a context manager that when used in a `with` statement, to automatically + restore the previously registered code transformer. + + Example: + + .. code-block:: python + + + gm: fx.GraphModule = ... + + + # This is a code transformer we want to register. This code + # transformer prepends a pdb import and trace statement at the very + # beginning of the generated torch.fx code to allow for manual + # debugging with the PDB library. + def insert_pdb(body): + return ["import pdb; pdb.set_trace()\\n", *body] + + + # Registers `insert_pdb`, and overwrites the current registered + # code transformer (given by `_` to the lambda): + gm.graph.on_generate_code(lambda _: insert_pdb) + + # Or alternatively, registers a code transformer which first + # runs `body` through existing registered transformer, then + # through `insert_pdb`: + gm.graph.on_generate_code( + lambda current_trans: ( + lambda body: insert_pdb(current_trans(body) if current_trans else body) + ) + ) + + gm.recompile() + gm(*inputs) # drops into pdb + + + This function can also be used as a context manager, with the benefit to + automatically restores the previously registered code transformer: + + .. code-block:: python + + # ... continue from previous example + + with gm.graph.on_generate_code(lambda _: insert_pdb): + # do more stuff with `gm`... + gm.recompile() + gm(*inputs) # drops into pdb + + # now previous code transformer is restored (but `gm`'s code with pdb + # remains - that means you can run `gm` with pdb here too, until you + # run next `recompile()`). + """ + on_gen_code_old = self._codegen._body_transformer + self._codegen._body_transformer = make_transformer(on_gen_code_old) + + @contextlib.contextmanager + def on_generate_code_context_manager(): + try: + yield + finally: + self._codegen._body_transformer = on_gen_code_old + + return on_generate_code_context_manager() + + +def _identity(x): + return x + + +def _make_color_fn(code): + def f(s): + reset = "\033[0m" + return f"{code}{s}{reset}" + + return f + + +_color_codes = { + "yellow": "\033[33m", + "cyan": "\033[36m", + "green": "\033[32m", + "blue": "\033[34m", + "red": "\033[31m", + "dim": "\033[2m", + "dim_blue": "\033[2m\033[34m", + "dim_green": "\033[2m\033[32m", +} +_color_fns = {k: _make_color_fn(v) for k, v in _color_codes.items()} +_counter_regexp = re.compile(r"# COUNTER: (\d+)") + + +reflectable_magic_methods = { + "add": "{} + {}", + "sub": "{} - {}", + "mul": "{} * {}", + "floordiv": "{} // {}", + "truediv": "{} / {}", + "div": "{} / {}", + "mod": "{} % {}", + "pow": "{} ** {}", + "lshift": "{} << {}", + "rshift": "{} >> {}", + "and_": "{} & {}", + "or_": "{} | {}", + "xor": "{} ^ {}", + "getitem": "{}[{}]", + "matmul": "{} @ {}", +} + +magic_methods = { + "eq": "{} == {}", + "ne": "{} != {}", + "lt": "{} < {}", + "gt": "{} > {}", + "le": "{} <= {}", + "ge": "{} >= {}", + "pos": "+{}", + "neg": "-{}", + "invert": "~{}", + **reflectable_magic_methods, +} + +inplace_methods = { + "iadd": "{} += {}", + "iand": "{} &= {}", + "ifloordiv": "{} //= {}", + "ilshift": "{} <<= {}", + "imod": "{} %= {}", + "imul": "{} *= {}", + "imatmul": "{} @= {}", + "ior": "{} |= {}", + "ipow": "{} **= {}", + "irshift": "{} >>= {}", + "isub": "{} -= {}", + "itruediv": "{} /= {}", + "ixor": "{} ^= {}", + "setitem": "{}[{}] = {}", +} diff --git a/shared/package-files/2c/2c5bb5fa40357ef5487512ef7acd3b18e13ebaec8cf33d72c1068f086f2387a9/series.cpython-311.pyc b/shared/package-files/2c/2c5bb5fa40357ef5487512ef7acd3b18e13ebaec8cf33d72c1068f086f2387a9/series.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8d3c3115ff77f54305127be1ed7fc7aff5aac75 Binary files /dev/null and b/shared/package-files/2c/2c5bb5fa40357ef5487512ef7acd3b18e13ebaec8cf33d72c1068f086f2387a9/series.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c5cc8acb081e462d77fdaf314a26613c01d1bb2d0fe1e1b268ef4afc14b3ea3/pipe.py b/shared/package-files/2c/2c5cc8acb081e462d77fdaf314a26613c01d1bb2d0fe1e1b268ef4afc14b3ea3/pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..8ecca96e9d23ff268a253c48269d5cca451ea270 --- /dev/null +++ b/shared/package-files/2c/2c5cc8acb081e462d77fdaf314a26613c01d1bb2d0fe1e1b268ef4afc14b3ea3/pipe.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractPipeTests: + def test_pipe_exclusive(self, fs, fs_target): + fs.pipe_file(fs_target, b"data") + assert fs.cat_file(fs_target) == b"data" + with pytest.raises(FileExistsError): + fs.pipe_file(fs_target, b"data", mode="create") + fs.pipe_file(fs_target, b"new data", mode="overwrite") + assert fs.cat_file(fs_target) == b"new data" diff --git a/shared/package-files/2c/2c65e75924dbf16edfed86dcd18df1b0faaccdd5de361a74c57ac42bdb91d2ba/packbits.cpython-311.pyc b/shared/package-files/2c/2c65e75924dbf16edfed86dcd18df1b0faaccdd5de361a74c57ac42bdb91d2ba/packbits.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb6d5997b0b07b5290d0301effe39efc99a29a7a Binary files /dev/null and b/shared/package-files/2c/2c65e75924dbf16edfed86dcd18df1b0faaccdd5de361a74c57ac42bdb91d2ba/packbits.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c71dd8b3dbfb812da5d897ad7b50fbb558aa5e6b911a2e4129edca06d73a74d/fix_execfile.cpython-311.pyc b/shared/package-files/2c/2c71dd8b3dbfb812da5d897ad7b50fbb558aa5e6b911a2e4129edca06d73a74d/fix_execfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..004d2af7ea4dfd7660a5bf9729c88e9958261075 Binary files /dev/null and b/shared/package-files/2c/2c71dd8b3dbfb812da5d897ad7b50fbb558aa5e6b911a2e4129edca06d73a74d/fix_execfile.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c77d10808c769cf00308b445e213023e77e1845abb66bbb9ac24c715db0f713/fix_last.cpython-311.pyc b/shared/package-files/2c/2c77d10808c769cf00308b445e213023e77e1845abb66bbb9ac24c715db0f713/fix_last.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..814e67cd270441d19394b6d83f89c9eba9bf229b Binary files /dev/null and b/shared/package-files/2c/2c77d10808c769cf00308b445e213023e77e1845abb66bbb9ac24c715db0f713/fix_last.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c7f67c2fa3cc95412e60313d3211c59d06da73e5221d0bac35ebd509b0d463a/test_dst.cpython-311.pyc b/shared/package-files/2c/2c7f67c2fa3cc95412e60313d3211c59d06da73e5221d0bac35ebd509b0d463a/test_dst.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4aeac51be3935007529c9d6e733b6dedb0df52fa Binary files /dev/null and b/shared/package-files/2c/2c7f67c2fa3cc95412e60313d3211c59d06da73e5221d0bac35ebd509b0d463a/test_dst.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c839d0c051d42bd3e1f4d74e19098a0700c355afbdccdcd3786cfc71c36af95/_multiarray_umath.cpython-311.pyc b/shared/package-files/2c/2c839d0c051d42bd3e1f4d74e19098a0700c355afbdccdcd3786cfc71c36af95/_multiarray_umath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e2a76b36dfabf2d952c26128ce70de7c2c58e0e Binary files /dev/null and b/shared/package-files/2c/2c839d0c051d42bd3e1f4d74e19098a0700c355afbdccdcd3786cfc71c36af95/_multiarray_umath.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c8ba32431640f5cfb554f622d8ea0480862aab64a23bac9da94aa8abe6a4731/_transform_bias_rescale_qkv.h b/shared/package-files/2c/2c8ba32431640f5cfb554f622d8ea0480862aab64a23bac9da94aa8abe6a4731/_transform_bias_rescale_qkv.h new file mode 100644 index 0000000000000000000000000000000000000000..51424d7498a189c2af31f791c8d564f3506d9d33 --- /dev/null +++ b/shared/package-files/2c/2c8ba32431640f5cfb554f622d8ea0480862aab64a23bac9da94aa8abe6a4731/_transform_bias_rescale_qkv.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_transform_bias_rescale_qkv(Tensor qkv, Tensor qkv_bias, int num_heads) -> (Tensor, Tensor, Tensor) +inline ::std::tuple _transform_bias_rescale_qkv(const at::Tensor & qkv, const at::Tensor & qkv_bias, int64_t num_heads) { + return at::_ops::_transform_bias_rescale_qkv::call(qkv, qkv_bias, num_heads); +} + +// aten::_transform_bias_rescale_qkv.out(Tensor qkv, Tensor qkv_bias, int num_heads, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _transform_bias_rescale_qkv_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & qkv, const at::Tensor & qkv_bias, int64_t num_heads) { + return at::_ops::_transform_bias_rescale_qkv_out::call(qkv, qkv_bias, num_heads, out0, out1, out2); +} +// aten::_transform_bias_rescale_qkv.out(Tensor qkv, Tensor qkv_bias, int num_heads, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _transform_bias_rescale_qkv_outf(const at::Tensor & qkv, const at::Tensor & qkv_bias, int64_t num_heads, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::_transform_bias_rescale_qkv_out::call(qkv, qkv_bias, num_heads, out0, out1, out2); +} + +} diff --git a/shared/package-files/2c/2c8dd340f77c493cc50bce126e4d9de58350484a52a630fc9b8282f05bf3b73e/test_summation.cpython-311.pyc b/shared/package-files/2c/2c8dd340f77c493cc50bce126e4d9de58350484a52a630fc9b8282f05bf3b73e/test_summation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3a84abde4c68391c8a5db2459c1a0bec39b6656 Binary files /dev/null and b/shared/package-files/2c/2c8dd340f77c493cc50bce126e4d9de58350484a52a630fc9b8282f05bf3b73e/test_summation.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c92367c5f06b7a5b0810656ebe0d4d80aa7fcc50afefc807d5d3b4ae81d4aaf/hardswish_backward_ops.h b/shared/package-files/2c/2c92367c5f06b7a5b0810656ebe0d4d80aa7fcc50afefc807d5d3b4ae81d4aaf/hardswish_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6c531fa54fb6788ac8cb2dbfd5628005dc7978ad --- /dev/null +++ b/shared/package-files/2c/2c92367c5f06b7a5b0810656ebe0d4d80aa7fcc50afefc807d5d3b4ae81d4aaf/hardswish_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API hardswish_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::hardswish_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "hardswish_backward(Tensor grad_output, Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self); +}; + +struct TORCH_API hardswish_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::hardswish_backward"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "hardswish_backward.out(Tensor grad_output, Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2c9610d21a6f8c9bab62d97ef65c901f5d747101614db744cea29488909184c1/CUDAStream.h b/shared/package-files/2c/2c9610d21a6f8c9bab62d97ef65c901f5d747101614db744cea29488909184c1/CUDAStream.h new file mode 100644 index 0000000000000000000000000000000000000000..05c314469f87c067e64e18b6b3448569fad27582 --- /dev/null +++ b/shared/package-files/2c/2c9610d21a6f8c9bab62d97ef65c901f5d747101614db744cea29488909184c1/CUDAStream.h @@ -0,0 +1,268 @@ +#pragma once + +#include + +#include +#include +#include +#include + +/* + * Stream pool note. + * + * A CUDAStream is an abstraction of an actual cuStream on the GPU. CUDAStreams + * are backed by cuStreams, but they use several pools to minimize the costs + * associated with creating, retaining, and destroying cuStreams. + * + * There are three pools per device, and a device's pools are lazily created. + * + * The first pool contains only the default stream. When the default stream + * is requested it's returned. + * + * The second pool is the "low priority" or "default priority" streams. In + * HIP builds there is no distinction between streams in this pool and streams + * in the third pool (below). There are 32 of these streams per device, and + * when a stream is requested one of these streams is returned round-robin. + * That is, the first stream requested is at index 0, the second at index 1... + * to index 31, then index 0 again. + * + * This means that if 33 low priority streams are requested, the first and + * last streams requested are actually the same stream (under the covers) + * and kernels enqueued on them cannot run concurrently. + * + * The third pool is the "high priority" streams. The third pool acts like + * the second pool except the streams are created with a higher priority. + * + * These pools suggest that stream users should prefer many short-lived streams, + * as the cost of acquiring and releasing streams is effectively zero. If + * many longer-lived streams are required in performance critical scenarios + * then the functionality here may need to be extended to allow, for example, + * "reserving" a subset of the pool so that other streams do not accidentally + * overlap the performance critical streams. + * + * Note: although the notion of "current stream for device" is thread local + * (every OS thread has a separate current stream, as one might expect), + * the stream pool is global across all threads; stream 0 is always stream 0 + * no matter which thread you use it on. Multiple threads can synchronize + * on the same stream. Although the CUDA documentation is not very clear + * on the matter, streams are thread safe; e.g., it is safe to enqueue + * a kernel on the same stream from two different threads. + */ + +namespace c10::cuda { + +static constexpr int max_compile_time_stream_priorities = 4; + +// Value object representing a CUDA stream. This is just a wrapper +// around c10::Stream, but it comes with a little extra CUDA-specific +// functionality (conversion to cudaStream_t), and a guarantee that +// the wrapped c10::Stream really is a CUDA stream. +class C10_CUDA_API CUDAStream { + public: + enum Unchecked { UNCHECKED }; + + /// Construct a CUDAStream from a Stream. This construction is checked, + /// and will raise an error if the Stream is not, in fact, a CUDA stream. + explicit CUDAStream(Stream stream) : stream_(stream) { + TORCH_CHECK(stream_.device_type() == DeviceType::CUDA); + } + + /// Construct a CUDAStream from a Stream with no error checking. + /// This constructor uses the "named" constructor idiom, and can + /// be invoked as: CUDAStream(CUDAStream::UNCHECKED, stream) + explicit CUDAStream(Unchecked, Stream stream) : stream_(stream) {} + + bool operator==(const CUDAStream& other) const noexcept { + return unwrap() == other.unwrap(); + } + + bool operator!=(const CUDAStream& other) const noexcept { + return unwrap() != other.unwrap(); + } + + /// Implicit conversion to cudaStream_t. + operator cudaStream_t() const { + return stream(); + } + + /// Implicit conversion to Stream (a.k.a., forget that the stream is a + /// CUDA stream). + operator Stream() const { + return unwrap(); + } + + /// Used to avoid baking in device type explicitly to Python-side API. + DeviceType device_type() const { + return DeviceType::CUDA; + } + + /// Get the CUDA device index that this stream is associated with. + DeviceIndex device_index() const { + return stream_.device_index(); + } + + /// Get the full Device that this stream is associated with. The Device + /// is guaranteed to be a CUDA device. + Device device() const { + return Device(DeviceType::CUDA, device_index()); + } + + /// Return the stream ID corresponding to this particular stream. + StreamId id() const { + return stream_.id(); + } + + bool query() const { + DeviceGuard guard{stream_.device()}; + cudaError_t err = C10_CUDA_ERROR_HANDLED(cudaStreamQuery(stream())); + + if (err == cudaSuccess) { + return true; + } else if (err != cudaErrorNotReady) { + C10_CUDA_CHECK(err); + } else { + // ignore and clear the error if not ready + (void)cudaGetLastError(); + } + + return false; + } + + void synchronize() const { + DeviceGuard guard{stream_.device()}; + c10::cuda::stream_synchronize(stream()); + } + + int priority() const { + DeviceGuard guard{stream_.device()}; + int priority = 0; + C10_CUDA_CHECK(cudaStreamGetPriority(stream(), &priority)); + return priority; + } + + /// Explicit conversion to cudaStream_t. + cudaStream_t stream() const; + + /// Explicit conversion to Stream. + Stream unwrap() const { + return stream_; + } + + /// Reversibly pack a CUDAStream into a struct representation. + /// Previously the stream's data was packed into a single int64_t, + /// as it was assumed the fields would not require more than + /// 64 bits of storage in total. + /// See https://github.com/pytorch/pytorch/issues/75854 + /// for more information regarding newer platforms that may violate + /// this assumption. + /// + /// The CUDAStream can be unpacked using unpack(). + struct c10::StreamData3 pack3() const { + return stream_.pack3(); + } + + // Unpack a CUDAStream from the 3 fields generated by pack(). + static CUDAStream unpack3( + StreamId stream_id, + DeviceIndex device_index, + DeviceType device_type) { + return CUDAStream(Stream::unpack3(stream_id, device_index, device_type)); + } + + static std::tuple priority_range() { + // Note: this returns the range of priority **supported by PyTorch**, not + // the range of priority **supported by CUDA**. The former is a subset of + // the latter. + int least_priority = 0, greatest_priority = 0; + C10_CUDA_CHECK( + cudaDeviceGetStreamPriorityRange(&least_priority, &greatest_priority)); +#ifdef USE_ROCM + // See Note [HIP stream priorities] + TORCH_INTERNAL_ASSERT( + least_priority == 1, "Unexpected HIP stream priority range"); + least_priority = 0; +#else + TORCH_INTERNAL_ASSERT( + least_priority == 0, "Unexpected CUDA stream priority range"); +#endif + TORCH_INTERNAL_ASSERT( + greatest_priority <= -1, "Unexpected CUDA stream priority range"); + greatest_priority = std::max( + -c10::cuda::max_compile_time_stream_priorities + 1, greatest_priority); + return std::make_tuple(least_priority, greatest_priority); + } + + // Deleted for now; use CUDAEvent::block instead + // void synchronize_with(const CUDAEvent& event) const; + + private: + Stream stream_; +}; + +/** + * Get a new stream from the CUDA stream pool. You can think of this + * as "creating" a new stream, but no such creation actually happens; + * instead, streams are preallocated from the pool and returned in a + * round-robin fashion. + * + * You can request a stream from the high priority pool by setting + * isHighPriority to true, or a stream for a specific device by setting device + * (defaulting to the current CUDA stream.) + */ +C10_API CUDAStream +getStreamFromPool(const bool isHighPriority = false, DeviceIndex device = -1); +// no default priority to disambiguate overloads +C10_API CUDAStream +getStreamFromPool(const int priority, DeviceIndex device = -1); + +/** + * Get a CUDAStream from a externally allocated one. + * + * This is mainly for interoperability with different libraries where we + * want to operate on a non-torch allocated stream for data exchange or similar + * purposes + */ +C10_API CUDAStream +getStreamFromExternal(cudaStream_t ext_stream, DeviceIndex device_index); + +/** + * Get the default CUDA stream, for the passed CUDA device, or for the + * current device if no device index is passed. The default stream is + * where most computation occurs when you aren't explicitly using + * streams. + */ +C10_API CUDAStream getDefaultCUDAStream(DeviceIndex device_index = -1); + +/** + * Get the current CUDA stream, for the passed CUDA device, or for the + * current device if no device index is passed. The current CUDA stream + * will usually be the default CUDA stream for the device, but it may + * be different if someone called 'setCurrentCUDAStream' or used 'StreamGuard' + * or 'CUDAStreamGuard'. + */ +C10_API CUDAStream getCurrentCUDAStream(DeviceIndex device_index = -1); + +/** + * Set the current stream on the device of the passed in stream to be + * the passed in stream. Yes, you read that right: this function + * has *nothing* to do with the current device: it toggles the current + * stream of the device of the passed stream. + * + * Confused? Avoid using this function; prefer using 'CUDAStreamGuard' instead + * (which will switch both your current device and current stream in the way you + * expect, and reset it back to its original state afterwards). + */ +C10_API void setCurrentCUDAStream(CUDAStream stream); + +C10_API std::ostream& operator<<(std::ostream& stream, const CUDAStream& s); + +} // namespace c10::cuda + +namespace std { +template <> +struct hash { + size_t operator()(c10::cuda::CUDAStream s) const noexcept { + return std::hash{}(s.unwrap()); + } +}; +} // namespace std diff --git a/shared/package-files/2c/2c968fcc4f3db741cf1ceb5322746afbf48c496dffb39ef2e4c1ed4f479630f5/_numeric_suite.cpython-311.pyc b/shared/package-files/2c/2c968fcc4f3db741cf1ceb5322746afbf48c496dffb39ef2e4c1ed4f479630f5/_numeric_suite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ade162c2ed5827143ea1709109be9ab9b253918 Binary files /dev/null and b/shared/package-files/2c/2c968fcc4f3db741cf1ceb5322746afbf48c496dffb39ef2e4c1ed4f479630f5/_numeric_suite.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c9d02990583dda71865e6ee3884011d40a4a7fe3bb6a1ab375e06865dc7be71/_native_batch_norm_legit.h b/shared/package-files/2c/2c9d02990583dda71865e6ee3884011d40a4a7fe3bb6a1ab375e06865dc7be71/_native_batch_norm_legit.h new file mode 100644 index 0000000000000000000000000000000000000000..9e9c5805ef5d6c7710b39d4b3187637eeee52b0f --- /dev/null +++ b/shared/package-files/2c/2c9d02990583dda71865e6ee3884011d40a4a7fe3bb6a1ab375e06865dc7be71/_native_batch_norm_legit.h @@ -0,0 +1,59 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) +inline ::std::tuple _native_batch_norm_legit(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps) { + return at::_ops::_native_batch_norm_legit::call(input, weight, bias, running_mean, running_var, training, momentum, eps); +} + +// aten::_native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!)) +inline ::std::tuple _native_batch_norm_legit_out(at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps) { + return at::_ops::_native_batch_norm_legit_out::call(input, weight, bias, running_mean, running_var, training, momentum, eps, out, save_mean, save_invstd); +} +// aten::_native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!)) +inline ::std::tuple _native_batch_norm_legit_outf(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd) { + return at::_ops::_native_batch_norm_legit_out::call(input, weight, bias, running_mean, running_var, training, momentum, eps, out, save_mean, save_invstd); +} + +// aten::_native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) +inline ::std::tuple _native_batch_norm_legit(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps) { + return at::_ops::_native_batch_norm_legit_no_stats::call(input, weight, bias, training, momentum, eps); +} + +// aten::_native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _native_batch_norm_legit_out(at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps) { + return at::_ops::_native_batch_norm_legit_no_stats_out::call(input, weight, bias, training, momentum, eps, out, save_mean, save_invstd); +} +// aten::_native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _native_batch_norm_legit_outf(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd) { + return at::_ops::_native_batch_norm_legit_no_stats_out::call(input, weight, bias, training, momentum, eps, out, save_mean, save_invstd); +} + +// aten::_native_batch_norm_legit_functional(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor running_mean_out, Tensor running_var_out) +inline ::std::tuple _native_batch_norm_legit_functional(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, bool training, double momentum, double eps) { + return at::_ops::_native_batch_norm_legit_functional::call(input, weight, bias, running_mean, running_var, training, momentum, eps); +} + +} diff --git a/shared/package-files/2c/2ca00605e14d13f6c827bfc29c9a19b5e8f9df4270b9d9beb6f315298c1fe6f2/_values_ops.h b/shared/package-files/2c/2ca00605e14d13f6c827bfc29c9a19b5e8f9df4270b9d9beb6f315298c1fe6f2/_values_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..89ef737b88c8f8e22546fec5711f9843d394faca --- /dev/null +++ b/shared/package-files/2c/2ca00605e14d13f6c827bfc29c9a19b5e8f9df4270b9d9beb6f315298c1fe6f2/_values_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _values { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_values"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_values(Tensor(a) self) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2ca2eb10ba08c361d3936fc510156ab980bbadfa85ce332669648551010d6b45/build_ext.py b/shared/package-files/2c/2ca2eb10ba08c361d3936fc510156ab980bbadfa85ce332669648551010d6b45/build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..cf60bd0ad82f64d253370388338ebdc6dea442ac --- /dev/null +++ b/shared/package-files/2c/2ca2eb10ba08c361d3936fc510156ab980bbadfa85ce332669648551010d6b45/build_ext.py @@ -0,0 +1,800 @@ +"""distutils.command.build_ext + +Implements the Distutils 'build_ext' command, for building extension +modules (currently limited to C extensions, should accommodate C++ +extensions ASAP).""" + +import contextlib +import os +import re +import sys +from distutils._log import log +from site import USER_BASE + +from .._modified import newer_group +from ..core import Command +from ..errors import ( + CCompilerError, + CompileError, + DistutilsError, + DistutilsOptionError, + DistutilsPlatformError, + DistutilsSetupError, +) +from ..extension import Extension +from ..sysconfig import customize_compiler, get_config_h_filename, get_python_version +from ..util import get_platform, is_freethreaded, is_mingw + +# An extension name is just a dot-separated list of Python NAMEs (ie. +# the same as a fully-qualified module name). +extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$') + + +def show_compilers(): + from ..ccompiler import show_compilers + + show_compilers() + + +class build_ext(Command): + description = "build C/C++ extensions (compile/link to build directory)" + + # XXX thoughts on how to deal with complex command-line options like + # these, i.e. how to make it so fancy_getopt can suck them off the + # command line and make it look like setup.py defined the appropriate + # lists of tuples of what-have-you. + # - each command needs a callback to process its command-line options + # - Command.__init__() needs access to its share of the whole + # command line (must ultimately come from + # Distribution.parse_command_line()) + # - it then calls the current command class' option-parsing + # callback to deal with weird options like -D, which have to + # parse the option text and churn out some custom data + # structure + # - that data structure (in this case, a list of 2-tuples) + # will then be present in the command object by the time + # we get to finalize_options() (i.e. the constructor + # takes care of both command-line and client options + # in between initialize_options() and finalize_options()) + + sep_by = f" (separated by '{os.pathsep}')" + user_options = [ + ('build-lib=', 'b', "directory for compiled extension modules"), + ('build-temp=', 't', "directory for temporary files (build by-products)"), + ( + 'plat-name=', + 'p', + "platform name to cross-compile for, if supported " + f"[default: {get_platform()}]", + ), + ( + 'inplace', + 'i', + "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules", + ), + ( + 'include-dirs=', + 'I', + "list of directories to search for header files" + sep_by, + ), + ('define=', 'D', "C preprocessor macros to define"), + ('undef=', 'U', "C preprocessor macros to undefine"), + ('libraries=', 'l', "external C libraries to link with"), + ( + 'library-dirs=', + 'L', + "directories to search for external C libraries" + sep_by, + ), + ('rpath=', 'R', "directories to search for shared C libraries at runtime"), + ('link-objects=', 'O', "extra explicit link objects to include in the link"), + ('debug', 'g', "compile/link with debugging information"), + ('force', 'f', "forcibly build everything (ignore file timestamps)"), + ('compiler=', 'c', "specify the compiler type"), + ('parallel=', 'j', "number of parallel build jobs"), + ('swig-cpp', None, "make SWIG create C++ files (default is C)"), + ('swig-opts=', None, "list of SWIG command line options"), + ('swig=', None, "path to the SWIG executable"), + ('user', None, "add user include, library and rpath"), + ] + + boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user'] + + help_options = [ + ('help-compiler', None, "list available compilers", show_compilers), + ] + + def initialize_options(self): + self.extensions = None + self.build_lib = None + self.plat_name = None + self.build_temp = None + self.inplace = False + self.package = None + + self.include_dirs = None + self.define = None + self.undef = None + self.libraries = None + self.library_dirs = None + self.rpath = None + self.link_objects = None + self.debug = None + self.force = None + self.compiler = None + self.swig = None + self.swig_cpp = None + self.swig_opts = None + self.user = None + self.parallel = None + + @staticmethod + def _python_lib_dir(sysconfig): + """ + Resolve Python's library directory for building extensions + that rely on a shared Python library. + + See python/cpython#44264 and python/cpython#48686 + """ + if not sysconfig.get_config_var('Py_ENABLE_SHARED'): + return + + if sysconfig.python_build: + yield '.' + return + + if sys.platform == 'zos': + # On z/OS, a user is not required to install Python to + # a predetermined path, but can use Python portably + installed_dir = sysconfig.get_config_var('base') + lib_dir = sysconfig.get_config_var('platlibdir') + yield os.path.join(installed_dir, lib_dir) + else: + # building third party extensions + yield sysconfig.get_config_var('LIBDIR') + + def finalize_options(self): # noqa: C901 + from distutils import sysconfig + + self.set_undefined_options( + 'build', + ('build_lib', 'build_lib'), + ('build_temp', 'build_temp'), + ('compiler', 'compiler'), + ('debug', 'debug'), + ('force', 'force'), + ('parallel', 'parallel'), + ('plat_name', 'plat_name'), + ) + + if self.package is None: + self.package = self.distribution.ext_package + + self.extensions = self.distribution.ext_modules + + # Make sure Python's include directories (for Python.h, pyconfig.h, + # etc.) are in the include search path. + py_include = sysconfig.get_python_inc() + plat_py_include = sysconfig.get_python_inc(plat_specific=True) + if self.include_dirs is None: + self.include_dirs = self.distribution.include_dirs or [] + if isinstance(self.include_dirs, str): + self.include_dirs = self.include_dirs.split(os.pathsep) + + # If in a virtualenv, add its include directory + # Issue 16116 + if sys.exec_prefix != sys.base_exec_prefix: + self.include_dirs.append(os.path.join(sys.exec_prefix, 'include')) + + # Put the Python "system" include dir at the end, so that + # any local include dirs take precedence. + self.include_dirs.extend(py_include.split(os.path.pathsep)) + if plat_py_include != py_include: + self.include_dirs.extend(plat_py_include.split(os.path.pathsep)) + + self.ensure_string_list('libraries') + self.ensure_string_list('link_objects') + + # Life is easier if we're not forever checking for None, so + # simplify these options to empty lists if unset + if self.libraries is None: + self.libraries = [] + if self.library_dirs is None: + self.library_dirs = [] + elif isinstance(self.library_dirs, str): + self.library_dirs = self.library_dirs.split(os.pathsep) + + if self.rpath is None: + self.rpath = [] + elif isinstance(self.rpath, str): + self.rpath = self.rpath.split(os.pathsep) + + # for extensions under windows use different directories + # for Release and Debug builds. + # also Python's library directory must be appended to library_dirs + if os.name == 'nt' and not is_mingw(): + # the 'libs' directory is for binary installs - we assume that + # must be the *native* platform. But we don't really support + # cross-compiling via a binary install anyway, so we let it go. + self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs')) + if sys.base_exec_prefix != sys.prefix: # Issue 16116 + self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs')) + if self.debug: + self.build_temp = os.path.join(self.build_temp, "Debug") + else: + self.build_temp = os.path.join(self.build_temp, "Release") + + # Append the source distribution include and library directories, + # this allows distutils on windows to work in the source tree + self.include_dirs.append(os.path.dirname(get_config_h_filename())) + self.library_dirs.append(sys.base_exec_prefix) + + # Use the .lib files for the correct architecture + if self.plat_name == 'win32': + suffix = 'win32' + else: + # win-amd64 + suffix = self.plat_name[4:] + new_lib = os.path.join(sys.exec_prefix, 'PCbuild') + if suffix: + new_lib = os.path.join(new_lib, suffix) + self.library_dirs.append(new_lib) + + # For extensions under Cygwin, Python's library directory must be + # appended to library_dirs + if sys.platform[:6] == 'cygwin': + if not sysconfig.python_build: + # building third party extensions + self.library_dirs.append( + os.path.join( + sys.prefix, "lib", "python" + get_python_version(), "config" + ) + ) + else: + # building python standard extensions + self.library_dirs.append('.') + + self.library_dirs.extend(self._python_lib_dir(sysconfig)) + + # The argument parsing will result in self.define being a string, but + # it has to be a list of 2-tuples. All the preprocessor symbols + # specified by the 'define' option will be set to '1'. Multiple + # symbols can be separated with commas. + + if self.define: + defines = self.define.split(',') + self.define = [(symbol, '1') for symbol in defines] + + # The option for macros to undefine is also a string from the + # option parsing, but has to be a list. Multiple symbols can also + # be separated with commas here. + if self.undef: + self.undef = self.undef.split(',') + + if self.swig_opts is None: + self.swig_opts = [] + else: + self.swig_opts = self.swig_opts.split(' ') + + # Finally add the user include and library directories if requested + if self.user: + user_include = os.path.join(USER_BASE, "include") + user_lib = os.path.join(USER_BASE, "lib") + if os.path.isdir(user_include): + self.include_dirs.append(user_include) + if os.path.isdir(user_lib): + self.library_dirs.append(user_lib) + self.rpath.append(user_lib) + + if isinstance(self.parallel, str): + try: + self.parallel = int(self.parallel) + except ValueError: + raise DistutilsOptionError("parallel should be an integer") + + def run(self): # noqa: C901 + from ..ccompiler import new_compiler + + # 'self.extensions', as supplied by setup.py, is a list of + # Extension instances. See the documentation for Extension (in + # distutils.extension) for details. + # + # For backwards compatibility with Distutils 0.8.2 and earlier, we + # also allow the 'extensions' list to be a list of tuples: + # (ext_name, build_info) + # where build_info is a dictionary containing everything that + # Extension instances do except the name, with a few things being + # differently named. We convert these 2-tuples to Extension + # instances as needed. + + if not self.extensions: + return + + # If we were asked to build any C/C++ libraries, make sure that the + # directory where we put them is in the library search path for + # linking extensions. + if self.distribution.has_c_libraries(): + build_clib = self.get_finalized_command('build_clib') + self.libraries.extend(build_clib.get_library_names() or []) + self.library_dirs.append(build_clib.build_clib) + + # Setup the CCompiler object that we'll use to do all the + # compiling and linking + self.compiler = new_compiler( + compiler=self.compiler, + verbose=self.verbose, + dry_run=self.dry_run, + force=self.force, + ) + customize_compiler(self.compiler) + # If we are cross-compiling, init the compiler now (if we are not + # cross-compiling, init would not hurt, but people may rely on + # late initialization of compiler even if they shouldn't...) + if os.name == 'nt' and self.plat_name != get_platform(): + self.compiler.initialize(self.plat_name) + + # The official Windows free threaded Python installer doesn't set + # Py_GIL_DISABLED because its pyconfig.h is shared with the + # default build, so define it here (pypa/setuptools#4662). + if os.name == 'nt' and is_freethreaded(): + self.compiler.define_macro('Py_GIL_DISABLED', '1') + + # And make sure that any compile/link-related options (which might + # come from the command-line or from the setup script) are set in + # that CCompiler object -- that way, they automatically apply to + # all compiling and linking done here. + if self.include_dirs is not None: + self.compiler.set_include_dirs(self.include_dirs) + if self.define is not None: + # 'define' option is a list of (name,value) tuples + for name, value in self.define: + self.compiler.define_macro(name, value) + if self.undef is not None: + for macro in self.undef: + self.compiler.undefine_macro(macro) + if self.libraries is not None: + self.compiler.set_libraries(self.libraries) + if self.library_dirs is not None: + self.compiler.set_library_dirs(self.library_dirs) + if self.rpath is not None: + self.compiler.set_runtime_library_dirs(self.rpath) + if self.link_objects is not None: + self.compiler.set_link_objects(self.link_objects) + + # Now actually compile and link everything. + self.build_extensions() + + def check_extensions_list(self, extensions): # noqa: C901 + """Ensure that the list of extensions (presumably provided as a + command option 'extensions') is valid, i.e. it is a list of + Extension objects. We also support the old-style list of 2-tuples, + where the tuples are (ext_name, build_info), which are converted to + Extension instances here. + + Raise DistutilsSetupError if the structure is invalid anywhere; + just returns otherwise. + """ + if not isinstance(extensions, list): + raise DistutilsSetupError( + "'ext_modules' option must be a list of Extension instances" + ) + + for i, ext in enumerate(extensions): + if isinstance(ext, Extension): + continue # OK! (assume type-checking done + # by Extension constructor) + + if not isinstance(ext, tuple) or len(ext) != 2: + raise DistutilsSetupError( + "each element of 'ext_modules' option must be an " + "Extension instance or 2-tuple" + ) + + ext_name, build_info = ext + + log.warning( + "old-style (ext_name, build_info) tuple found in " + "ext_modules for extension '%s' " + "-- please convert to Extension instance", + ext_name, + ) + + if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)): + raise DistutilsSetupError( + "first element of each tuple in 'ext_modules' " + "must be the extension name (a string)" + ) + + if not isinstance(build_info, dict): + raise DistutilsSetupError( + "second element of each tuple in 'ext_modules' " + "must be a dictionary (build info)" + ) + + # OK, the (ext_name, build_info) dict is type-safe: convert it + # to an Extension instance. + ext = Extension(ext_name, build_info['sources']) + + # Easy stuff: one-to-one mapping from dict elements to + # instance attributes. + for key in ( + 'include_dirs', + 'library_dirs', + 'libraries', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + ): + val = build_info.get(key) + if val is not None: + setattr(ext, key, val) + + # Medium-easy stuff: same syntax/semantics, different names. + ext.runtime_library_dirs = build_info.get('rpath') + if 'def_file' in build_info: + log.warning("'def_file' element of build info dict no longer supported") + + # Non-trivial stuff: 'macros' split into 'define_macros' + # and 'undef_macros'. + macros = build_info.get('macros') + if macros: + ext.define_macros = [] + ext.undef_macros = [] + for macro in macros: + if not (isinstance(macro, tuple) and len(macro) in (1, 2)): + raise DistutilsSetupError( + "'macros' element of build info dict must be 1- or 2-tuple" + ) + if len(macro) == 1: + ext.undef_macros.append(macro[0]) + elif len(macro) == 2: + ext.define_macros.append(macro) + + extensions[i] = ext + + def get_source_files(self): + self.check_extensions_list(self.extensions) + filenames = [] + + # Wouldn't it be neat if we knew the names of header files too... + for ext in self.extensions: + filenames.extend(ext.sources) + return filenames + + def get_outputs(self): + # Sanity check the 'extensions' list -- can't assume this is being + # done in the same run as a 'build_extensions()' call (in fact, we + # can probably assume that it *isn't*!). + self.check_extensions_list(self.extensions) + + # And build the list of output (built) filenames. Note that this + # ignores the 'inplace' flag, and assumes everything goes in the + # "build" tree. + return [self.get_ext_fullpath(ext.name) for ext in self.extensions] + + def build_extensions(self): + # First, sanity-check the 'extensions' list + self.check_extensions_list(self.extensions) + if self.parallel: + self._build_extensions_parallel() + else: + self._build_extensions_serial() + + def _build_extensions_parallel(self): + workers = self.parallel + if self.parallel is True: + workers = os.cpu_count() # may return None + try: + from concurrent.futures import ThreadPoolExecutor + except ImportError: + workers = None + + if workers is None: + self._build_extensions_serial() + return + + with ThreadPoolExecutor(max_workers=workers) as executor: + futures = [ + executor.submit(self.build_extension, ext) for ext in self.extensions + ] + for ext, fut in zip(self.extensions, futures): + with self._filter_build_errors(ext): + fut.result() + + def _build_extensions_serial(self): + for ext in self.extensions: + with self._filter_build_errors(ext): + self.build_extension(ext) + + @contextlib.contextmanager + def _filter_build_errors(self, ext): + try: + yield + except (CCompilerError, DistutilsError, CompileError) as e: + if not ext.optional: + raise + self.warn(f'building extension "{ext.name}" failed: {e}') + + def build_extension(self, ext): + sources = ext.sources + if sources is None or not isinstance(sources, (list, tuple)): + raise DistutilsSetupError( + f"in 'ext_modules' option (extension '{ext.name}'), " + "'sources' must be present and must be " + "a list of source filenames" + ) + # sort to make the resulting .so file build reproducible + sources = sorted(sources) + + ext_path = self.get_ext_fullpath(ext.name) + depends = sources + ext.depends + if not (self.force or newer_group(depends, ext_path, 'newer')): + log.debug("skipping '%s' extension (up-to-date)", ext.name) + return + else: + log.info("building '%s' extension", ext.name) + + # First, scan the sources for SWIG definition files (.i), run + # SWIG on 'em to create .c files, and modify the sources list + # accordingly. + sources = self.swig_sources(sources, ext) + + # Next, compile the source code to object files. + + # XXX not honouring 'define_macros' or 'undef_macros' -- the + # CCompiler API needs to change to accommodate this, and I + # want to do one thing at a time! + + # Two possible sources for extra compiler arguments: + # - 'extra_compile_args' in Extension object + # - CFLAGS environment variable (not particularly + # elegant, but people seem to expect it and I + # guess it's useful) + # The environment variable should take precedence, and + # any sensible compiler will give precedence to later + # command line args. Hence we combine them in order: + extra_args = ext.extra_compile_args or [] + + macros = ext.define_macros[:] + for undef in ext.undef_macros: + macros.append((undef,)) + + objects = self.compiler.compile( + sources, + output_dir=self.build_temp, + macros=macros, + include_dirs=ext.include_dirs, + debug=self.debug, + extra_postargs=extra_args, + depends=ext.depends, + ) + + # XXX outdated variable, kept here in case third-part code + # needs it. + self._built_objects = objects[:] + + # Now link the object files together into a "shared object" -- + # of course, first we have to figure out all the other things + # that go into the mix. + if ext.extra_objects: + objects.extend(ext.extra_objects) + extra_args = ext.extra_link_args or [] + + # Detect target language, if not provided + language = ext.language or self.compiler.detect_language(sources) + + self.compiler.link_shared_object( + objects, + ext_path, + libraries=self.get_libraries(ext), + library_dirs=ext.library_dirs, + runtime_library_dirs=ext.runtime_library_dirs, + extra_postargs=extra_args, + export_symbols=self.get_export_symbols(ext), + debug=self.debug, + build_temp=self.build_temp, + target_lang=language, + ) + + def swig_sources(self, sources, extension): + """Walk the list of source files in 'sources', looking for SWIG + interface (.i) files. Run SWIG on all that are found, and + return a modified 'sources' list with SWIG source files replaced + by the generated C (or C++) files. + """ + new_sources = [] + swig_sources = [] + swig_targets = {} + + # XXX this drops generated C/C++ files into the source tree, which + # is fine for developers who want to distribute the generated + # source -- but there should be an option to put SWIG output in + # the temp dir. + + if self.swig_cpp: + log.warning("--swig-cpp is deprecated - use --swig-opts=-c++") + + if ( + self.swig_cpp + or ('-c++' in self.swig_opts) + or ('-c++' in extension.swig_opts) + ): + target_ext = '.cpp' + else: + target_ext = '.c' + + for source in sources: + (base, ext) = os.path.splitext(source) + if ext == ".i": # SWIG interface file + new_sources.append(base + '_wrap' + target_ext) + swig_sources.append(source) + swig_targets[source] = new_sources[-1] + else: + new_sources.append(source) + + if not swig_sources: + return new_sources + + swig = self.swig or self.find_swig() + swig_cmd = [swig, "-python"] + swig_cmd.extend(self.swig_opts) + if self.swig_cpp: + swig_cmd.append("-c++") + + # Do not override commandline arguments + if not self.swig_opts: + swig_cmd.extend(extension.swig_opts) + + for source in swig_sources: + target = swig_targets[source] + log.info("swigging %s to %s", source, target) + self.spawn(swig_cmd + ["-o", target, source]) + + return new_sources + + def find_swig(self): + """Return the name of the SWIG executable. On Unix, this is + just "swig" -- it should be in the PATH. Tries a bit harder on + Windows. + """ + if os.name == "posix": + return "swig" + elif os.name == "nt": + # Look for SWIG in its standard installation directory on + # Windows (or so I presume!). If we find it there, great; + # if not, act like Unix and assume it's in the PATH. + for vers in ("1.3", "1.2", "1.1"): + fn = os.path.join(f"c:\\swig{vers}", "swig.exe") + if os.path.isfile(fn): + return fn + else: + return "swig.exe" + else: + raise DistutilsPlatformError( + f"I don't know how to find (much less run) SWIG on platform '{os.name}'" + ) + + # -- Name generators ----------------------------------------------- + # (extension names, filenames, whatever) + def get_ext_fullpath(self, ext_name): + """Returns the path of the filename for a given extension. + + The file is located in `build_lib` or directly in the package + (inplace option). + """ + fullname = self.get_ext_fullname(ext_name) + modpath = fullname.split('.') + filename = self.get_ext_filename(modpath[-1]) + + if not self.inplace: + # no further work needed + # returning : + # build_dir/package/path/filename + filename = os.path.join(*modpath[:-1] + [filename]) + return os.path.join(self.build_lib, filename) + + # the inplace option requires to find the package directory + # using the build_py command for that + package = '.'.join(modpath[0:-1]) + build_py = self.get_finalized_command('build_py') + package_dir = os.path.abspath(build_py.get_package_dir(package)) + + # returning + # package_dir/filename + return os.path.join(package_dir, filename) + + def get_ext_fullname(self, ext_name): + """Returns the fullname of a given extension name. + + Adds the `package.` prefix""" + if self.package is None: + return ext_name + else: + return self.package + '.' + ext_name + + def get_ext_filename(self, ext_name): + r"""Convert the name of an extension (eg. "foo.bar") into the name + of the file from which it will be loaded (eg. "foo/bar.so", or + "foo\bar.pyd"). + """ + from ..sysconfig import get_config_var + + ext_path = ext_name.split('.') + ext_suffix = get_config_var('EXT_SUFFIX') + return os.path.join(*ext_path) + ext_suffix + + def get_export_symbols(self, ext): + """Return the list of symbols that a shared extension has to + export. This either uses 'ext.export_symbols' or, if it's not + provided, "PyInit_" + module_name. Only relevant on Windows, where + the .pyd file (DLL) must export the module "PyInit_" function. + """ + name = ext.name.split('.')[-1] + try: + # Unicode module name support as defined in PEP-489 + # https://peps.python.org/pep-0489/#export-hook-name + name.encode('ascii') + except UnicodeEncodeError: + suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii') + else: + suffix = "_" + name + + initfunc_name = "PyInit" + suffix + if initfunc_name not in ext.export_symbols: + ext.export_symbols.append(initfunc_name) + return ext.export_symbols + + def get_libraries(self, ext): # noqa: C901 + """Return the list of libraries to link against when building a + shared extension. On most platforms, this is just 'ext.libraries'; + on Windows, we add the Python library (eg. python20.dll). + """ + # The python library is always needed on Windows. For MSVC, this + # is redundant, since the library is mentioned in a pragma in + # pyconfig.h that MSVC groks. The other Windows compilers all seem + # to need it mentioned explicitly, though, so that's what we do. + # Append '_d' to the python import library on debug builds. + if sys.platform == "win32" and not is_mingw(): + from .._msvccompiler import MSVCCompiler + + if not isinstance(self.compiler, MSVCCompiler): + template = "python%d%d" + if self.debug: + template = template + '_d' + pythonlib = template % ( + sys.hexversion >> 24, + (sys.hexversion >> 16) & 0xFF, + ) + # don't extend ext.libraries, it may be shared with other + # extensions, it is a reference to the original list + return ext.libraries + [pythonlib] + else: + # On Android only the main executable and LD_PRELOADs are considered + # to be RTLD_GLOBAL, all the dependencies of the main executable + # remain RTLD_LOCAL and so the shared libraries must be linked with + # libpython when python is built with a shared python library (issue + # bpo-21536). + # On Cygwin (and if required, other POSIX-like platforms based on + # Windows like MinGW) it is simply necessary that all symbols in + # shared libraries are resolved at link time. + from ..sysconfig import get_config_var + + link_libpython = False + if get_config_var('Py_ENABLE_SHARED'): + # A native build on an Android device or on Cygwin + if hasattr(sys, 'getandroidapilevel'): + link_libpython = True + elif sys.platform == 'cygwin' or is_mingw(): + link_libpython = True + elif '_PYTHON_HOST_PLATFORM' in os.environ: + # We are cross-compiling for one of the relevant platforms + if get_config_var('ANDROID_API_LEVEL') != 0: + link_libpython = True + elif get_config_var('MACHDEP') == 'cygwin': + link_libpython = True + + if link_libpython: + ldversion = get_config_var('LDVERSION') + return ext.libraries + ['python' + ldversion] + + return ext.libraries diff --git a/shared/package-files/2c/2caeff458d4a89d26691e67eebd2d9989c79bc56a2056cbc3c5f6e33ca3a3e35/arccosh_ops.h b/shared/package-files/2c/2caeff458d4a89d26691e67eebd2d9989c79bc56a2056cbc3c5f6e33ca3a3e35/arccosh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..85977aaa00a1a7ae60d2dea51b978a50f0511f98 --- /dev/null +++ b/shared/package-files/2c/2caeff458d4a89d26691e67eebd2d9989c79bc56a2056cbc3c5f6e33ca3a3e35/arccosh_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API arccosh { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::arccosh"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "arccosh(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API arccosh_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::arccosh_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "arccosh_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API arccosh_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::arccosh"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "arccosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2cc7cfd9296904246b8e79eb190eede5338b6754309c145ba0a22af09356bf5b/_thread_safe_fork.cpython-311.pyc b/shared/package-files/2c/2cc7cfd9296904246b8e79eb190eede5338b6754309c145ba0a22af09356bf5b/_thread_safe_fork.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1adfe2eda39a259c0ffa030576447547faad6bd8 Binary files /dev/null and b/shared/package-files/2c/2cc7cfd9296904246b8e79eb190eede5338b6754309c145ba0a22af09356bf5b/_thread_safe_fork.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cc82a73ee2ec8978ef03560915dec84f569eecce1866c0fce140c7ec2178c2e/test_qubit.cpython-311.pyc b/shared/package-files/2c/2cc82a73ee2ec8978ef03560915dec84f569eecce1866c0fce140c7ec2178c2e/test_qubit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f268d32574200a4755e44bc2ce7474c62d9d224 Binary files /dev/null and b/shared/package-files/2c/2cc82a73ee2ec8978ef03560915dec84f569eecce1866c0fce140c7ec2178c2e/test_qubit.cpython-311.pyc differ diff --git a/shared/package-files/2c/2ccc9e61ec77b4531dafc4a74a86b6f0dfe603b658d00e4b3fa1d9a0cf71077d/convert.h b/shared/package-files/2c/2ccc9e61ec77b4531dafc4a74a86b6f0dfe603b658d00e4b3fa1d9a0cf71077d/convert.h new file mode 100644 index 0000000000000000000000000000000000000000..150751481c197934de154db66e2d613b823f8ce6 --- /dev/null +++ b/shared/package-files/2c/2ccc9e61ec77b4531dafc4a74a86b6f0dfe603b658d00e4b3fa1d9a0cf71077d/convert.h @@ -0,0 +1,51 @@ +/* convert.h -- functions for converting between VCF/BCF and related formats. + + Copyright (C) 2014-2024 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#ifndef __CONVERT_H__ +#define __CONVERT_H__ + +#include + +typedef struct _convert_t convert_t; +enum convert_option +{ + allow_undef_tags, // see `bcftools query --allow-undef-tags`, throws an error if tag is not defined otherwise + subset_samples, // in bracketed expressions (e.g. [ %GT]) consider only marked samples + header_samples, // include sample name in bracketed tags (e.g. SAMPLE1:GT SAMPLE2:GT for [ %GT]) + force_newline, // automatically insert a newline when not part of the formatting expression + print_filtered, // print the provided string instead of discarding samples not included in subset_samples + no_hdr_indices, // drop column indices when printing header, i.e. "#CHROM", not "#[1]CHROM" +}; + +convert_t *convert_init(bcf_hdr_t *hdr, int *samples, int nsamples, const char *str); +void convert_destroy(convert_t *convert); +int convert_set_option(convert_t *convert, enum convert_option opt, ...); +int convert_header(convert_t *convert, kstring_t *str); +int convert_line(convert_t *convert, bcf1_t *rec, kstring_t *str); +int convert_max_unpack(convert_t *convert); +int convert_is_tag_used(convert_t *convert, char *tag); +const char **convert_list_used_tags(convert_t *convert, int *ntags); + +#endif + diff --git a/shared/package-files/2c/2cce5af033bcc74034c9a03464084e5726dc4487291f2d9fc421f4628a87ff63/null_context_manager.py b/shared/package-files/2c/2cce5af033bcc74034c9a03464084e5726dc4487291f2d9fc421f4628a87ff63/null_context_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..80d09f68097edbe676077be183711dabe5cbc664 --- /dev/null +++ b/shared/package-files/2c/2cce5af033bcc74034c9a03464084e5726dc4487291f2d9fc421f4628a87ff63/null_context_manager.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs +import contextlib + +import torch + +class NullContextManager(torch.nn.Module): + """ + Null context manager in Python will be traced out. + """ + + def forward(self, x): + """ + Null context manager in Python will be traced out. + """ + ctx = contextlib.nullcontext() + with ctx: + return x.sin() + x.cos() + +example_args = (torch.randn(3, 2),) +tags = {"python.context-manager"} +model = NullContextManager() diff --git a/shared/package-files/2c/2cd1cf39d482052e06c3081465a39258f49bdadf47ea3d4c3991114ce3647c5c/special_xlogy_ops.h b/shared/package-files/2c/2cd1cf39d482052e06c3081465a39258f49bdadf47ea3d4c3991114ce3647c5c/special_xlogy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9dab42907be49c7736223b00de808da59607008d --- /dev/null +++ b/shared/package-files/2c/2cd1cf39d482052e06c3081465a39258f49bdadf47ea3d4c3991114ce3647c5c/special_xlogy_ops.h @@ -0,0 +1,84 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_xlogy { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "special_xlogy(Tensor self, Tensor other) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API special_xlogy_self_scalar { + using schema = at::Tensor (const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = "self_scalar"; + static constexpr const char* schema_str = "special_xlogy.self_scalar(Scalar self, Tensor other) -> Tensor"; + static at::Tensor call(const at::Scalar & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other); +}; + +struct TORCH_API special_xlogy_other_scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = "other_scalar"; + static constexpr const char* schema_str = "special_xlogy.other_scalar(Tensor self, Scalar other) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API special_xlogy_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "special_xlogy.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API special_xlogy_self_scalar_out { + using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = "self_scalar_out"; + static constexpr const char* schema_str = "special_xlogy.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API special_xlogy_other_scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_xlogy"; + static constexpr const char* overload_name = "other_scalar_out"; + static constexpr const char* schema_str = "special_xlogy.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2cd31a04fc9c284c7941da611171bd2b185014aa315735c5b3119733fcce12e9/test_at.cpython-311.pyc b/shared/package-files/2c/2cd31a04fc9c284c7941da611171bd2b185014aa315735c5b3119733fcce12e9/test_at.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57afde8cd801cbf36263c56837a33d5bd5b0fe54 Binary files /dev/null and b/shared/package-files/2c/2cd31a04fc9c284c7941da611171bd2b185014aa315735c5b3119733fcce12e9/test_at.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cd4fa6db1a96b27d385bfd9d3d2d8e0f84f0e6454203be7ec426931886f9dd9/prod_ops.h b/shared/package-files/2c/2cd4fa6db1a96b27d385bfd9d3d2d8e0f84f0e6454203be7ec426931886f9dd9/prod_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9e348c2617a2bd1535bb2038d8752ebdfd302fdc --- /dev/null +++ b/shared/package-files/2c/2cd4fa6db1a96b27d385bfd9d3d2d8e0f84f0e6454203be7ec426931886f9dd9/prod_ops.h @@ -0,0 +1,84 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API prod { + using schema = at::Tensor (const at::Tensor &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "prod(Tensor self, *, ScalarType? dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, ::std::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dtype); +}; + +struct TORCH_API prod_dim_int { + using schema = at::Tensor (const at::Tensor &, int64_t, bool, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = "dim_int"; + static constexpr const char* schema_str = "prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t dim, bool keepdim, ::std::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim, ::std::optional dtype); +}; + +struct TORCH_API prod_int_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, bool, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = "int_out"; + static constexpr const char* schema_str = "prod.int_out(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, int64_t dim, bool keepdim, ::std::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim, ::std::optional dtype, at::Tensor & out); +}; + +struct TORCH_API prod_dim_Dimname { + using schema = at::Tensor (const at::Tensor &, at::Dimname, bool, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = "dim_Dimname"; + static constexpr const char* schema_str = "prod.dim_Dimname(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::Dimname dim, bool keepdim, ::std::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim, ::std::optional dtype); +}; + +struct TORCH_API prod_Dimname_out { + using schema = at::Tensor & (const at::Tensor &, at::Dimname, bool, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = "Dimname_out"; + static constexpr const char* schema_str = "prod.Dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Dimname dim, bool keepdim, ::std::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim, ::std::optional dtype, at::Tensor & out); +}; + +struct TORCH_API prod_out { + using schema = at::Tensor & (const at::Tensor &, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::prod"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "prod.out(Tensor self, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, ::std::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dtype, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/2c/2cd761dc5c6d918a6688fbb459db2ad1386a6c467a062b9e01914e1a50672680/test_elliptic_integrals.cpython-311.pyc b/shared/package-files/2c/2cd761dc5c6d918a6688fbb459db2ad1386a6c467a062b9e01914e1a50672680/test_elliptic_integrals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16b5fc9e3a87550a6c7e644de46ad6e0a8dffcfb Binary files /dev/null and b/shared/package-files/2c/2cd761dc5c6d918a6688fbb459db2ad1386a6c467a062b9e01914e1a50672680/test_elliptic_integrals.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cd79965f0f6e08904eedf18e2045f344c5ce087083dbe59abb258be5ba351dc/_zoneinfo.cpython-311.pyc b/shared/package-files/2c/2cd79965f0f6e08904eedf18e2045f344c5ce087083dbe59abb258be5ba351dc/_zoneinfo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ed0347cd03f8926c9526c040241b3633830c1ee Binary files /dev/null and b/shared/package-files/2c/2cd79965f0f6e08904eedf18e2045f344c5ce087083dbe59abb258be5ba351dc/_zoneinfo.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cdc9b651073c5b0ef6e546e2369414be26a8c015f81b24ae0ed5407ce3e734c/_index_put_impl_meta_dispatch.h b/shared/package-files/2c/2cdc9b651073c5b0ef6e546e2369414be26a8c015f81b24ae0ed5407ce3e734c/_index_put_impl_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2380c013237b940b8103f9bfe4cfa5c0875e74fa --- /dev/null +++ b/shared/package-files/2c/2cdc9b651073c5b0ef6e546e2369414be26a8c015f81b24ae0ed5407ce3e734c/_index_put_impl_meta_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor & _index_put_impl_(at::Tensor & self, const c10::List<::std::optional> & indices, const at::Tensor & values, bool accumulate=false, bool unsafe=false); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/2c/2ce67289577d685835c58894c2af85280d63331b860f253429c4e9a2bf35af5b/debug.py b/shared/package-files/2c/2ce67289577d685835c58894c2af85280d63331b860f253429c4e9a2bf35af5b/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..84534fb232509f0c9bbe722820bd1ae649d53e07 --- /dev/null +++ b/shared/package-files/2c/2ce67289577d685835c58894c2af85280d63331b860f253429c4e9a2bf35af5b/debug.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch._C._lazy + + +def render_ir_graph(tensors): + """Return a text dump of the LTC IR graph in dot format for the tensors. + The text can be processed by tools like dot to be rendered in pdf,png etc.""" + return torch._C._lazy._get_tensors_dot(tensors) + + +def dump_ir(tensors, ir_format): + """Return a dump of the tensors in the specified format. + Valid format are + - text: for LTC IR + - backend: for the activate backend IR + """ + if ir_format == "text": + return torch._C._lazy._get_tensors_text(tensors) + elif ir_format == "backend": + return torch._C._lazy._get_tensors_backend(tensors) + else: + raise RuntimeError(f"Unrecognized IR format: {ir_format}") diff --git a/shared/package-files/2c/2cf92d2073e1b68577bace65716dcffac8ddf5a6893e95427c841d40fee9000b/_linalg_solve_ex_meta.h b/shared/package-files/2c/2cf92d2073e1b68577bace65716dcffac8ddf5a6893e95427c841d40fee9000b/_linalg_solve_ex_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..042b5e2ad5c4e447a3eaf939c16da4a86e48bf78 --- /dev/null +++ b/shared/package-files/2c/2cf92d2073e1b68577bace65716dcffac8ddf5a6893e95427c841d40fee9000b/_linalg_solve_ex_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured__linalg_solve_ex : public at::impl::MetaBase { + + + void meta(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2cfaea98401b2ca7a3d61657c277504f2d2133e6c8ce4f4b0afb1e147a107bb8/qconfig_mapping.py b/shared/package-files/2c/2cfaea98401b2ca7a3d61657c277504f2d2133e6c8ce4f4b0afb1e147a107bb8/qconfig_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..a43b69e4fa8f42e507df053a777df73f26fc9d20 --- /dev/null +++ b/shared/package-files/2c/2cfaea98401b2ca7a3d61657c277504f2d2133e6c8ce4f4b0afb1e147a107bb8/qconfig_mapping.py @@ -0,0 +1,381 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from collections import OrderedDict +from typing import Any, Callable, Union + +import torch + +from .fake_quantize import default_weight_fake_quant, FixedQParamsFakeQuantize +from .observer import ( + _PartialWrapper, + default_fixed_qparams_range_0to1_observer, + default_fixed_qparams_range_neg1to1_observer, + default_placeholder_observer, + default_weight_observer, +) +from .qconfig import ( + default_quint8_weight_qconfig, + default_reuse_input_qconfig, + default_symmetric_qnnpack_qat_qconfig, + default_symmetric_qnnpack_qconfig, + get_default_qat_qconfig, + get_default_qconfig, + QConfig, + QConfigAny, +) + + +__all__ = [ + "get_default_qconfig_mapping", + "get_default_qat_qconfig_mapping", + "QConfigMapping", +] + + +# TODO: replace all usages with these constants +_GLOBAL_DICT_KEY = "" +_OBJECT_TYPE_DICT_KEY = "object_type" +_MODULE_NAME_REGEX_DICT_KEY = "module_name_regex" +_MODULE_NAME_DICT_KEY = "module_name" +_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY = "module_name_object_type_order" + +# TODO: derive this map from the BackendConfig +_FIXED_QPARAMS_OP_TO_OBSERVER: dict[Union[Callable, str], _PartialWrapper] = { + torch.nn.Hardsigmoid: default_fixed_qparams_range_0to1_observer, + torch.nn.functional.hardsigmoid: default_fixed_qparams_range_0to1_observer, + "hardsigmoid": default_fixed_qparams_range_0to1_observer, + "hardsigmoid_": default_fixed_qparams_range_0to1_observer, + torch.nn.Sigmoid: default_fixed_qparams_range_0to1_observer, + torch.sigmoid: default_fixed_qparams_range_0to1_observer, + "sigmoid": default_fixed_qparams_range_0to1_observer, + "sigmoid_": default_fixed_qparams_range_0to1_observer, + torch.nn.Softmax: default_fixed_qparams_range_0to1_observer, + torch.nn.Tanh: default_fixed_qparams_range_neg1to1_observer, + torch.tanh: default_fixed_qparams_range_neg1to1_observer, + "tanh": default_fixed_qparams_range_neg1to1_observer, + "tanh_": default_fixed_qparams_range_neg1to1_observer, +} + + +def _get_default_qconfig_mapping( + is_qat: bool, backend: str, version: int +) -> QConfigMapping: + """ + Return the default QConfigMapping for the given quantization type and backend. + """ + if is_qat: + qconfig = get_default_qat_qconfig(backend, version) + else: + qconfig = get_default_qconfig(backend, version) + default_weight = default_weight_fake_quant if is_qat else default_weight_observer + + # default_per_channel_weight_observer is not currently compatible with fbgemm backend + # so we have to modify the weight observer to default_weight_observer or another + # per tensor supported observer. + # see https://github.com/pytorch/pytorch/issues/47535 + if backend in ("fbgemm", "x86"): + qconfig_transpose = QConfig( + activation=qconfig.activation, weight=default_weight + ) + else: + qconfig_transpose = qconfig + + # currently layernorm only supports float weights + # we have to add this because otherwise there will be a extra quantize-dequantize pair + qconfig_layernorm = QConfig( + activation=qconfig.activation, weight=default_placeholder_observer + ) + + qconfig_mapping = ( + QConfigMapping() + .set_global(qconfig) + .set_object_type("reshape", default_reuse_input_qconfig) + .set_object_type(torch.nn.ConvTranspose1d, qconfig_transpose) + .set_object_type(torch.nn.ConvTranspose2d, qconfig_transpose) + .set_object_type(torch.nn.ConvTranspose3d, qconfig_transpose) + .set_object_type(torch.nn.functional.conv_transpose1d, qconfig_transpose) + .set_object_type(torch.nn.functional.conv_transpose2d, qconfig_transpose) + .set_object_type(torch.nn.functional.conv_transpose3d, qconfig_transpose) + .set_object_type(torch.nn.functional.layer_norm, qconfig_layernorm) + .set_object_type(torch.nn.LayerNorm, qconfig_layernorm) + .set_object_type(torch.nn.PReLU, default_quint8_weight_qconfig) + ) + # Use special observers for ops with fixed qparams + fixed_qparams_observer_to_qconfig: dict[Any, QConfigAny] = {} + for fixed_qparams_op, observer in _FIXED_QPARAMS_OP_TO_OBSERVER.items(): + if observer in fixed_qparams_observer_to_qconfig: + fixed_qparams_qconfig = fixed_qparams_observer_to_qconfig[observer] + else: + if is_qat: + activation = FixedQParamsFakeQuantize.with_args(observer=observer) + else: + activation = observer + fixed_qparams_qconfig = QConfig( + activation=activation, weight=default_weight + ) + fixed_qparams_observer_to_qconfig[observer] = fixed_qparams_qconfig + qconfig_mapping.set_object_type(fixed_qparams_op, fixed_qparams_qconfig) + + # TODO Currently it's required that separate ops in a fused op/module have the same qconfig. + # Need to be able to support fusion of ops with different qconfigs + + return qconfig_mapping + + +def get_default_qconfig_mapping(backend="x86", version=0) -> QConfigMapping: + """ + Return the default QConfigMapping for post training quantization. + + Args: + * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be + one of ["x86" (default), "fbgemm", "qnnpack", "onednn"] + * ``version`` (int) : the version for the default qconfig mapping + """ + # TODO: add assert for backend choices + return _get_default_qconfig_mapping(False, backend, version) + + +def get_default_qat_qconfig_mapping(backend="x86", version=1) -> QConfigMapping: + """ + Return the default QConfigMapping for quantization aware training. + + Args: + * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be + one of ["x86" (default), "fbgemm", "qnnpack", "onednn"] + * ``version`` (int) : the version for the default qconfig mapping + """ + return _get_default_qconfig_mapping(True, backend, version) + + +def _get_symmetric_qnnpack_qconfig_mapping() -> QConfigMapping: + """ + Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qconfig` + as the default QConfig. + """ + default_qconfig = default_symmetric_qnnpack_qconfig + return _get_default_qconfig_mapping_with_default_qconfig( + False, "qnnpack", default_qconfig + ) + + +def _get_symmetric_qnnpack_qat_qconfig_mapping() -> QConfigMapping: + """ + Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qat_qconfig` + as the default QConfig. + """ + default_qconfig = default_symmetric_qnnpack_qat_qconfig + return _get_default_qconfig_mapping_with_default_qconfig( + True, "qnnpack", default_qconfig + ) + + +def _get_default_qconfig_mapping_with_default_qconfig( + is_qat: bool, + backend: str, + default_qconfig: QConfig, +) -> QConfigMapping: + """ + Return a QConfigMapping that uses the provided qconfig as the default QConfig. + """ + if is_qat: + qconfig_mapping = get_default_qat_qconfig_mapping(backend) + else: + qconfig_mapping = get_default_qconfig_mapping(backend) + qconfig_mapping.set_global(default_qconfig) + for pattern in qconfig_mapping.object_type_qconfigs.keys(): + if pattern not in _FIXED_QPARAMS_OP_TO_OBSERVER: + qconfig_mapping.set_object_type(pattern, default_qconfig) + return qconfig_mapping + + +_QCONFIG_STYLE_ORDER: list[str] = [ + "global_qconfig", + "object_type_qconfigs", + "module_name_regex_qconfigs", + "module_name_qconfigs", + "module_name_object_type_order_qconfigs", +] + + +class QConfigMapping: + """ + Mapping from model ops to :class:`torch.ao.quantization.QConfig` s. + + The user can specify QConfigs using the following methods (in increasing match priority): + + ``set_global`` : sets the global (default) QConfig + + ``set_object_type`` : sets the QConfig for a given module type, function, or method name + + ``set_module_name_regex`` : sets the QConfig for modules matching the given regex string + + ``set_module_name`` : sets the QConfig for modules matching the given module name + + ``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination + of the given module name, object type, and the index at which the module appears + + Example usage:: + + qconfig_mapping = QConfigMapping() + .set_global(global_qconfig) + .set_object_type(torch.nn.Linear, qconfig1) + .set_object_type(torch.nn.ReLU, qconfig1) + .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1) + .set_module_name_regex("foo.*", qconfig2) + .set_module_name("module1", qconfig1) + .set_module_name("module2", qconfig2) + .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3) + + """ + + def __init__(self) -> None: + # In increasing match priority: + self.global_qconfig: QConfigAny = None + self.object_type_qconfigs: OrderedDict[ + Union[Callable, str], QConfigAny + ] = OrderedDict() + self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict() + self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict() + self.module_name_object_type_order_qconfigs: OrderedDict[ + tuple[str, Callable, int], QConfigAny + ] = OrderedDict() + + def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping: + """ + Set the global (default) QConfig. + """ + self.global_qconfig = global_qconfig + return self + + def set_object_type( + self, object_type: Union[Callable, str], qconfig: QConfigAny + ) -> QConfigMapping: + """ + Set the QConfig for a given module type, function, or method name. + If the QConfig for an existing object type was already set, the new QConfig will override the old one. + """ + self.object_type_qconfigs[object_type] = qconfig + return self + + def set_module_name_regex( + self, module_name_regex: str, qconfig: QConfigAny + ) -> QConfigMapping: + """ + Set the QConfig for modules matching the given regex string. + + Regexes will be matched in the order in which they are registered through this method. + Thus, the caller should register more specific patterns first, e.g.:: + + qconfig_mapping = QConfigMapping() + .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1) + .set_module_name_regex("foo.*bar.*", qconfig2) + .set_module_name_regex("foo.*", qconfig3) + + In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2, + and "foo.baz.relu" would match qconfig3. + + If the QConfig for an existing module name regex was already set, the new QConfig will override the + old one while preserving the order in which the regexes were originally registered. + """ + self.module_name_regex_qconfigs[module_name_regex] = qconfig + return self + + def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping: + """ + Set the QConfig for modules matching the given module name. + If the QConfig for an existing module name was already set, the new QConfig will override the old one. + """ + self.module_name_qconfigs[module_name] = qconfig + return self + + def set_module_name_object_type_order( + self, module_name: str, object_type: Callable, index: int, qconfig: QConfigAny + ) -> QConfigMapping: + """ + Set the QConfig for modules matching a combination of the given module name, object type, + and the index at which the module appears. + + If the QConfig for an existing (module name, object type, index) was already set, the new QConfig + will override the old one. + """ + self.module_name_object_type_order_qconfigs[ + (module_name, object_type, index) + ] = qconfig + return self + + def __repr__(self) -> str: + output = self.__class__.__name__ + " (" + for style_name in _QCONFIG_STYLE_ORDER: + output += f"\n {style_name}" + qconfigs = getattr(self, style_name) + if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0: + for key, qconfig in qconfigs.items(): + output += f"\n {key}: {qconfig}" + else: + output += f"\n {qconfigs}" + return output + "\n)" + + # TODO: remove this + def to_dict(self) -> dict[str, Any]: + """ + Convert this ``QConfigMapping`` to a dictionary with the following keys: + + "" (for global QConfig) + + "object_type" + + "module_name_regex" + + "module_name" + + "module_name_object_type_order" + + The values of this dictionary are lists of tuples. + """ + return { + _GLOBAL_DICT_KEY: self.global_qconfig, + _OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()), + _MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()), + _MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()), + _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [ + (*k, v) for k, v in self.module_name_object_type_order_qconfigs.items() + ], + } + + # TODO: remove this + @classmethod + def from_dict(cls, qconfig_dict: dict[str, Any]) -> QConfigMapping: + """ + Create a ``QConfigMapping`` from a dictionary with the following keys (all optional): + + "" (for global QConfig) + + "object_type" + + "module_name_regex" + + "module_name" + + "module_name_object_type_order" + + The values of this dictionary are expected to be lists of tuples. + """ + conf = cls() + if _GLOBAL_DICT_KEY in qconfig_dict: + conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY]) + for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []): + conf.set_object_type(object_type, qconfig) + for module_name_regex, qconfig in qconfig_dict.get( + _MODULE_NAME_REGEX_DICT_KEY, [] + ): + conf.set_module_name_regex(module_name_regex, qconfig) + for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []): + conf.set_module_name(module_name, qconfig) + for module_name, object_type, index, qconfig in qconfig_dict.get( + _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, [] + ): + conf.set_module_name_object_type_order( + module_name, object_type, index, qconfig + ) + return conf diff --git a/shared/package-files/2c/2cfb59f358a593a940bd5b839d671df6856694a69d823b6261ac8ac2a5a4461f/_foreach_log.h b/shared/package-files/2c/2cfb59f358a593a940bd5b839d671df6856694a69d823b6261ac8ac2a5a4461f/_foreach_log.h new file mode 100644 index 0000000000000000000000000000000000000000..8c3c90ec597e80286c5ec7adfe192e8f1e8ef339 --- /dev/null +++ b/shared/package-files/2c/2cfb59f358a593a940bd5b839d671df6856694a69d823b6261ac8ac2a5a4461f/_foreach_log.h @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_log(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_log(at::TensorList self) { + return at::_ops::_foreach_log::call(self); +} + +// aten::_foreach_log_(Tensor(a!)[] self) -> () +inline void _foreach_log_(at::TensorList self) { + return at::_ops::_foreach_log_::call(self); +} + +// aten::_foreach_log.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_log_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_log_out::call(self, out); +} +// aten::_foreach_log.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_log_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_log_out::call(self, out); +} + +} diff --git a/shared/package-files/2c/2cfbdd04760ca794f2215aa9dcb37fe81d4d09e6254d8d8b1403867ef4888807/_manylinux.cpython-311.pyc b/shared/package-files/2c/2cfbdd04760ca794f2215aa9dcb37fe81d4d09e6254d8d8b1403867ef4888807/_manylinux.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc555ad25084dfdeb68a97db2fff2b1a07a454b2 Binary files /dev/null and b/shared/package-files/2c/2cfbdd04760ca794f2215aa9dcb37fe81d4d09e6254d8d8b1403867ef4888807/_manylinux.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cfc2f8dc7db2015749c50943ea24e468fa7258f8929b7407aae69e6ade2fdc3/_scaled_dot_product_cudnn_attention_cuda_dispatch.h b/shared/package-files/2c/2cfc2f8dc7db2015749c50943ea24e468fa7258f8929b7407aae69e6ade2fdc3/_scaled_dot_product_cudnn_attention_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0c4f59a5c39125b7832c94f078e16ee471356511 --- /dev/null +++ b/shared/package-files/2c/2cfc2f8dc7db2015749c50943ea24e468fa7258f8929b7407aae69e6ade2fdc3/_scaled_dot_product_cudnn_attention_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _scaled_dot_product_cudnn_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & attn_bias, bool compute_log_sumexp, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, ::std::optional scale=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/2c/2cfc651d49b4ea489958e5ed95dab667068cbc9d61003ad7b6f42d0115d4c30a/_globals.cpython-311.pyc b/shared/package-files/2c/2cfc651d49b4ea489958e5ed95dab667068cbc9d61003ad7b6f42d0115d4c30a/_globals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7043b7ba4bd1f149b66a68629c58b5f1b9cc3c77 Binary files /dev/null and b/shared/package-files/2c/2cfc651d49b4ea489958e5ed95dab667068cbc9d61003ad7b6f42d0115d4c30a/_globals.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cfe759389547d08297eeeed8de22fbf168582ffb1ffa55aa430f1f48fb2d342/test_constructors.py b/shared/package-files/2c/2cfe759389547d08297eeeed8de22fbf168582ffb1ffa55aa430f1f48fb2d342/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..8456e6a7acba5a160556f6f3192fa795ce678786 --- /dev/null +++ b/shared/package-files/2c/2cfe759389547d08297eeeed8de22fbf168582ffb1ffa55aa430f1f48fb2d342/test_constructors.py @@ -0,0 +1,860 @@ +from datetime import ( + date, + datetime, +) +import itertools + +import numpy as np +import pytest + +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike + +import pandas as pd +from pandas import ( + Index, + MultiIndex, + Series, + Timestamp, + date_range, +) +import pandas._testing as tm + + +def test_constructor_single_level(): + result = MultiIndex( + levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] + ) + assert isinstance(result, MultiIndex) + expected = Index(["foo", "bar", "baz", "qux"], name="first") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["first"] + + +def test_constructor_no_levels(): + msg = "non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + MultiIndex(levels=[], codes=[]) + + msg = "Must pass both levels and codes" + with pytest.raises(TypeError, match=msg): + MultiIndex(levels=[]) + with pytest.raises(TypeError, match=msg): + MultiIndex(codes=[]) + + +def test_constructor_nonhashable_names(): + # GH 20527 + levels = [[1, 2], ["one", "two"]] + codes = [[0, 0, 1, 1], [0, 1, 0, 1]] + names = (["foo"], ["bar"]) + msg = r"MultiIndex\.name must be a hashable type" + with pytest.raises(TypeError, match=msg): + MultiIndex(levels=levels, codes=codes, names=names) + + # With .rename() + mi = MultiIndex( + levels=[[1, 2], ["one", "two"]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=("foo", "bar"), + ) + renamed = [["fooo"], ["barr"]] + with pytest.raises(TypeError, match=msg): + mi.rename(names=renamed) + + # With .set_names() + with pytest.raises(TypeError, match=msg): + mi.set_names(names=renamed) + + +def test_constructor_mismatched_codes_levels(idx): + codes = [np.array([1]), np.array([2]), np.array([3])] + levels = ["a"] + + msg = "Length of levels and codes must be the same" + with pytest.raises(ValueError, match=msg): + MultiIndex(levels=levels, codes=codes) + + length_error = ( + r"On level 0, code max \(3\) >= length of level \(1\)\. " + "NOTE: this index is in an inconsistent state" + ) + label_error = r"Unequal code lengths: \[4, 2\]" + code_value_error = r"On level 0, code value \(-2\) < -1" + + # important to check that it's looking at the right thing. + with pytest.raises(ValueError, match=length_error): + MultiIndex(levels=[["a"], ["b"]], codes=[[0, 1, 2, 3], [0, 3, 4, 1]]) + + with pytest.raises(ValueError, match=label_error): + MultiIndex(levels=[["a"], ["b"]], codes=[[0, 0, 0, 0], [0, 0]]) + + # external API + with pytest.raises(ValueError, match=length_error): + idx.copy().set_levels([["a"], ["b"]]) + + with pytest.raises(ValueError, match=label_error): + idx.copy().set_codes([[0, 0, 0, 0], [0, 0]]) + + # test set_codes with verify_integrity=False + # the setting should not raise any value error + idx.copy().set_codes(codes=[[0, 0, 0, 0], [0, 0]], verify_integrity=False) + + # code value smaller than -1 + with pytest.raises(ValueError, match=code_value_error): + MultiIndex(levels=[["a"], ["b"]], codes=[[0, -2], [0, 0]]) + + +def test_na_levels(): + # GH26408 + # test if codes are re-assigned value -1 for levels + # with missing values (NaN, NaT, None) + result = MultiIndex( + levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[0, -1, 1, 2, 3, 4]] + ) + expected = MultiIndex( + levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[-1, -1, -1, -1, 3, 4]] + ) + tm.assert_index_equal(result, expected) + + result = MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[0, -1, 1, 2, 3, 4]] + ) + expected = MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[-1, -1, 1, -1, 3, -1]] + ) + tm.assert_index_equal(result, expected) + + # verify set_levels and set_codes + result = MultiIndex( + levels=[[1, 2, 3, 4, 5]], codes=[[0, -1, 1, 2, 3, 4]] + ).set_levels([[np.nan, "s", pd.NaT, 128, None]]) + tm.assert_index_equal(result, expected) + + result = MultiIndex( + levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[1, 2, 2, 2, 2, 2]] + ).set_codes([[0, -1, 1, 2, 3, 4]]) + tm.assert_index_equal(result, expected) + + +def test_copy_in_constructor(): + levels = np.array(["a", "b", "c"]) + codes = np.array([1, 1, 2, 0, 0, 1, 1]) + val = codes[0] + mi = MultiIndex(levels=[levels, levels], codes=[codes, codes], copy=True) + assert mi.codes[0][0] == val + codes[0] = 15 + assert mi.codes[0][0] == val + val = levels[0] + levels[0] = "PANDA" + assert mi.levels[0][0] == val + + +# ---------------------------------------------------------------------------- +# from_arrays +# ---------------------------------------------------------------------------- +def test_from_arrays(idx): + arrays = [ + np.asarray(lev).take(level_codes) + for lev, level_codes in zip(idx.levels, idx.codes) + ] + + # list of arrays as input + result = MultiIndex.from_arrays(arrays, names=idx.names) + tm.assert_index_equal(result, idx) + + # infer correctly + result = MultiIndex.from_arrays([[pd.NaT, Timestamp("20130101")], ["a", "b"]]) + assert result.levels[0].equals(Index([Timestamp("20130101")])) + assert result.levels[1].equals(Index(["a", "b"])) + + +def test_from_arrays_iterator(idx): + # GH 18434 + arrays = [ + np.asarray(lev).take(level_codes) + for lev, level_codes in zip(idx.levels, idx.codes) + ] + + # iterator as input + result = MultiIndex.from_arrays(iter(arrays), names=idx.names) + tm.assert_index_equal(result, idx) + + # invalid iterator input + msg = "Input must be a list / sequence of array-likes." + with pytest.raises(TypeError, match=msg): + MultiIndex.from_arrays(0) + + +def test_from_arrays_tuples(idx): + arrays = tuple( + tuple(np.asarray(lev).take(level_codes)) + for lev, level_codes in zip(idx.levels, idx.codes) + ) + + # tuple of tuples as input + result = MultiIndex.from_arrays(arrays, names=idx.names) + tm.assert_index_equal(result, idx) + + +@pytest.mark.parametrize( + ("idx1", "idx2"), + [ + ( + pd.period_range("2011-01-01", freq="D", periods=3), + pd.period_range("2015-01-01", freq="h", periods=3), + ), + ( + date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"), + date_range("2015-01-01 10:00", freq="h", periods=3, tz="Asia/Tokyo"), + ), + ( + pd.timedelta_range("1 days", freq="D", periods=3), + pd.timedelta_range("2 hours", freq="h", periods=3), + ), + ], +) +def test_from_arrays_index_series_period_datetimetz_and_timedelta(idx1, idx2): + result = MultiIndex.from_arrays([idx1, idx2]) + tm.assert_index_equal(result.get_level_values(0), idx1) + tm.assert_index_equal(result.get_level_values(1), idx2) + + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + tm.assert_index_equal(result2.get_level_values(0), idx1) + tm.assert_index_equal(result2.get_level_values(1), idx2) + + tm.assert_index_equal(result, result2) + + +def test_from_arrays_index_datetimelike_mixed(): + idx1 = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern") + idx2 = date_range("2015-01-01 10:00", freq="h", periods=3) + idx3 = pd.timedelta_range("1 days", freq="D", periods=3) + idx4 = pd.period_range("2011-01-01", freq="D", periods=3) + + result = MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) + tm.assert_index_equal(result.get_level_values(0), idx1) + tm.assert_index_equal(result.get_level_values(1), idx2) + tm.assert_index_equal(result.get_level_values(2), idx3) + tm.assert_index_equal(result.get_level_values(3), idx4) + + result2 = MultiIndex.from_arrays( + [Series(idx1), Series(idx2), Series(idx3), Series(idx4)] + ) + tm.assert_index_equal(result2.get_level_values(0), idx1) + tm.assert_index_equal(result2.get_level_values(1), idx2) + tm.assert_index_equal(result2.get_level_values(2), idx3) + tm.assert_index_equal(result2.get_level_values(3), idx4) + + tm.assert_index_equal(result, result2) + + +def test_from_arrays_index_series_categorical(): + # GH13743 + idx1 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=False) + idx2 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=True) + + result = MultiIndex.from_arrays([idx1, idx2]) + tm.assert_index_equal(result.get_level_values(0), idx1) + tm.assert_index_equal(result.get_level_values(1), idx2) + + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + tm.assert_index_equal(result2.get_level_values(0), idx1) + tm.assert_index_equal(result2.get_level_values(1), idx2) + + result3 = MultiIndex.from_arrays([idx1.values, idx2.values]) + tm.assert_index_equal(result3.get_level_values(0), idx1) + tm.assert_index_equal(result3.get_level_values(1), idx2) + + +def test_from_arrays_empty(): + # 0 levels + msg = "Must pass non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + MultiIndex.from_arrays(arrays=[]) + + # 1 level + result = MultiIndex.from_arrays(arrays=[[]], names=["A"]) + assert isinstance(result, MultiIndex) + expected = Index([], name="A") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["A"] + + # N levels + for N in [2, 3]: + arrays = [[]] * N + names = list("ABC")[:N] + result = MultiIndex.from_arrays(arrays=arrays, names=names) + expected = MultiIndex(levels=[[]] * N, codes=[[]] * N, names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "invalid_sequence_of_arrays", + [ + 1, + [1], + [1, 2], + [[1], 2], + [1, [2]], + "a", + ["a"], + ["a", "b"], + [["a"], "b"], + (1,), + (1, 2), + ([1], 2), + (1, [2]), + "a", + ("a",), + ("a", "b"), + (["a"], "b"), + [(1,), 2], + [1, (2,)], + [("a",), "b"], + ((1,), 2), + (1, (2,)), + (("a",), "b"), + ], +) +def test_from_arrays_invalid_input(invalid_sequence_of_arrays): + msg = "Input must be a list / sequence of array-likes" + with pytest.raises(TypeError, match=msg): + MultiIndex.from_arrays(arrays=invalid_sequence_of_arrays) + + +@pytest.mark.parametrize( + "idx1, idx2", [([1, 2, 3], ["a", "b"]), ([], ["a", "b"]), ([1, 2, 3], [])] +) +def test_from_arrays_different_lengths(idx1, idx2): + # see gh-13599 + msg = "^all arrays must be same length$" + with pytest.raises(ValueError, match=msg): + MultiIndex.from_arrays([idx1, idx2]) + + +def test_from_arrays_respects_none_names(): + # GH27292 + a = Series([1, 2, 3], name="foo") + b = Series(["a", "b", "c"], name="bar") + + result = MultiIndex.from_arrays([a, b], names=None) + expected = MultiIndex( + levels=[[1, 2, 3], ["a", "b", "c"]], codes=[[0, 1, 2], [0, 1, 2]], names=None + ) + + tm.assert_index_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# from_tuples +# ---------------------------------------------------------------------------- +def test_from_tuples(): + msg = "Cannot infer number of levels from empty list" + with pytest.raises(TypeError, match=msg): + MultiIndex.from_tuples([]) + + expected = MultiIndex( + levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + + # input tuples + result = MultiIndex.from_tuples(((1, 2), (3, 4)), names=["a", "b"]) + tm.assert_index_equal(result, expected) + + +def test_from_tuples_iterator(): + # GH 18434 + # input iterator for tuples + expected = MultiIndex( + levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + + result = MultiIndex.from_tuples(zip([1, 3], [2, 4]), names=["a", "b"]) + tm.assert_index_equal(result, expected) + + # input non-iterables + msg = "Input must be a list / sequence of tuple-likes." + with pytest.raises(TypeError, match=msg): + MultiIndex.from_tuples(0) + + +def test_from_tuples_empty(): + # GH 16777 + result = MultiIndex.from_tuples([], names=["a", "b"]) + expected = MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"]) + tm.assert_index_equal(result, expected) + + +def test_from_tuples_index_values(idx): + result = MultiIndex.from_tuples(idx) + assert (result.values == idx.values).all() + + +def test_tuples_with_name_string(): + # GH 15110 and GH 14848 + + li = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] + msg = "Names should be list-like for a MultiIndex" + with pytest.raises(ValueError, match=msg): + Index(li, name="abc") + with pytest.raises(ValueError, match=msg): + Index(li, name="a") + + +def test_from_tuples_with_tuple_label(): + # GH 15457 + expected = pd.DataFrame( + [[2, 1, 2], [4, (1, 2), 3]], columns=["a", "b", "c"] + ).set_index(["a", "b"]) + idx = MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=("a", "b")) + result = pd.DataFrame([2, 3], columns=["c"], index=idx) + tm.assert_frame_equal(expected, result) + + +# ---------------------------------------------------------------------------- +# from_product +# ---------------------------------------------------------------------------- +def test_from_product_empty_zero_levels(): + # 0 levels + msg = "Must pass non-zero number of levels/codes" + with pytest.raises(ValueError, match=msg): + MultiIndex.from_product([]) + + +def test_from_product_empty_one_level(): + result = MultiIndex.from_product([[]], names=["A"]) + expected = Index([], name="A") + tm.assert_index_equal(result.levels[0], expected) + assert result.names == ["A"] + + +@pytest.mark.parametrize( + "first, second", [([], []), (["foo", "bar", "baz"], []), ([], ["a", "b", "c"])] +) +def test_from_product_empty_two_levels(first, second): + names = ["A", "B"] + result = MultiIndex.from_product([first, second], names=names) + expected = MultiIndex(levels=[first, second], codes=[[], []], names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("N", list(range(4))) +def test_from_product_empty_three_levels(N): + # GH12258 + names = ["A", "B", "C"] + lvl2 = list(range(N)) + result = MultiIndex.from_product([[], lvl2, []], names=names) + expected = MultiIndex(levels=[[], lvl2, []], codes=[[], [], []], names=names) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "invalid_input", [1, [1], [1, 2], [[1], 2], "a", ["a"], ["a", "b"], [["a"], "b"]] +) +def test_from_product_invalid_input(invalid_input): + msg = r"Input must be a list / sequence of iterables|Input must be list-like" + with pytest.raises(TypeError, match=msg): + MultiIndex.from_product(iterables=invalid_input) + + +def test_from_product_datetimeindex(): + dt_index = date_range("2000-01-01", periods=2) + mi = MultiIndex.from_product([[1, 2], dt_index]) + etalon = construct_1d_object_array_from_listlike( + [ + (1, Timestamp("2000-01-01")), + (1, Timestamp("2000-01-02")), + (2, Timestamp("2000-01-01")), + (2, Timestamp("2000-01-02")), + ] + ) + tm.assert_numpy_array_equal(mi.values, etalon) + + +def test_from_product_rangeindex(): + # RangeIndex is preserved by factorize, so preserved in levels + rng = Index(range(5)) + other = ["a", "b"] + mi = MultiIndex.from_product([rng, other]) + tm.assert_index_equal(mi._levels[0], rng, exact=True) + + +@pytest.mark.parametrize("ordered", [False, True]) +@pytest.mark.parametrize("f", [lambda x: x, lambda x: Series(x), lambda x: x.values]) +def test_from_product_index_series_categorical(ordered, f): + # GH13743 + first = ["foo", "bar"] + + idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=ordered) + expected = pd.CategoricalIndex( + list("abcaab") + list("abcaab"), categories=list("bac"), ordered=ordered + ) + + result = MultiIndex.from_product([first, f(idx)]) + tm.assert_index_equal(result.get_level_values(1), expected) + + +def test_from_product(): + first = ["foo", "bar", "buz"] + second = ["a", "b", "c"] + names = ["first", "second"] + result = MultiIndex.from_product([first, second], names=names) + + tuples = [ + ("foo", "a"), + ("foo", "b"), + ("foo", "c"), + ("bar", "a"), + ("bar", "b"), + ("bar", "c"), + ("buz", "a"), + ("buz", "b"), + ("buz", "c"), + ] + expected = MultiIndex.from_tuples(tuples, names=names) + + tm.assert_index_equal(result, expected) + + +def test_from_product_iterator(): + # GH 18434 + first = ["foo", "bar", "buz"] + second = ["a", "b", "c"] + names = ["first", "second"] + tuples = [ + ("foo", "a"), + ("foo", "b"), + ("foo", "c"), + ("bar", "a"), + ("bar", "b"), + ("bar", "c"), + ("buz", "a"), + ("buz", "b"), + ("buz", "c"), + ] + expected = MultiIndex.from_tuples(tuples, names=names) + + # iterator as input + result = MultiIndex.from_product(iter([first, second]), names=names) + tm.assert_index_equal(result, expected) + + # Invalid non-iterable input + msg = "Input must be a list / sequence of iterables." + with pytest.raises(TypeError, match=msg): + MultiIndex.from_product(0) + + +@pytest.mark.parametrize( + "a, b, expected_names", + [ + ( + Series([1, 2, 3], name="foo"), + Series(["a", "b"], name="bar"), + ["foo", "bar"], + ), + (Series([1, 2, 3], name="foo"), ["a", "b"], ["foo", None]), + ([1, 2, 3], ["a", "b"], None), + ], +) +def test_from_product_infer_names(a, b, expected_names): + # GH27292 + result = MultiIndex.from_product([a, b]) + expected = MultiIndex( + levels=[[1, 2, 3], ["a", "b"]], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=expected_names, + ) + tm.assert_index_equal(result, expected) + + +def test_from_product_respects_none_names(): + # GH27292 + a = Series([1, 2, 3], name="foo") + b = Series(["a", "b"], name="bar") + + result = MultiIndex.from_product([a, b], names=None) + expected = MultiIndex( + levels=[[1, 2, 3], ["a", "b"]], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=None, + ) + tm.assert_index_equal(result, expected) + + +def test_from_product_readonly(): + # GH#15286 passing read-only array to from_product + a = np.array(range(3)) + b = ["a", "b"] + expected = MultiIndex.from_product([a, b]) + + a.setflags(write=False) + result = MultiIndex.from_product([a, b]) + tm.assert_index_equal(result, expected) + + +def test_create_index_existing_name(idx): + # GH11193, when an existing index is passed, and a new name is not + # specified, the new index should inherit the previous object name + index = idx + index.names = ["foo", "bar"] + result = Index(index) + expected = Index( + Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ) + ) + tm.assert_index_equal(result, expected) + + result = Index(index, name="A") + expected = Index( + Index( + [ + ("foo", "one"), + ("foo", "two"), + ("bar", "one"), + ("baz", "two"), + ("qux", "one"), + ("qux", "two"), + ], + dtype="object", + ), + name="A", + ) + tm.assert_index_equal(result, expected) + + +# ---------------------------------------------------------------------------- +# from_frame +# ---------------------------------------------------------------------------- +def test_from_frame(): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], columns=["L1", "L2"] + ) + expected = MultiIndex.from_tuples( + [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")], names=["L1", "L2"] + ) + result = MultiIndex.from_frame(df) + tm.assert_index_equal(expected, result) + + +def test_from_frame_missing_values_multiIndex(): + # GH 39984 + pa = pytest.importorskip("pyarrow") + + df = pd.DataFrame( + { + "a": Series([1, 2, None], dtype="Int64"), + "b": pd.Float64Dtype().__from_arrow__(pa.array([0.2, np.nan, None])), + } + ) + multi_indexed = MultiIndex.from_frame(df) + expected = MultiIndex.from_arrays( + [ + Series([1, 2, None]).astype("Int64"), + pd.Float64Dtype().__from_arrow__(pa.array([0.2, np.nan, None])), + ], + names=["a", "b"], + ) + tm.assert_index_equal(multi_indexed, expected) + + +@pytest.mark.parametrize( + "non_frame", + [ + Series([1, 2, 3, 4]), + [1, 2, 3, 4], + [[1, 2], [3, 4], [5, 6]], + Index([1, 2, 3, 4]), + np.array([[1, 2], [3, 4], [5, 6]]), + 27, + ], +) +def test_from_frame_error(non_frame): + # GH 22420 + with pytest.raises(TypeError, match="Input must be a DataFrame"): + MultiIndex.from_frame(non_frame) + + +def test_from_frame_dtype_fidelity(): + # GH 22420 + df = pd.DataFrame( + { + "dates": date_range("19910905", periods=6, tz="US/Eastern"), + "a": [1, 1, 1, 2, 2, 2], + "b": pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + "c": ["x", "x", "y", "z", "x", "y"], + } + ) + original_dtypes = df.dtypes.to_dict() + + expected_mi = MultiIndex.from_arrays( + [ + date_range("19910905", periods=6, tz="US/Eastern"), + [1, 1, 1, 2, 2, 2], + pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True), + ["x", "x", "y", "z", "x", "y"], + ], + names=["dates", "a", "b", "c"], + ) + mi = MultiIndex.from_frame(df) + mi_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)} + + tm.assert_index_equal(expected_mi, mi) + assert original_dtypes == mi_dtypes + + +@pytest.mark.parametrize( + "names_in,names_out", [(None, [("L1", "x"), ("L2", "y")]), (["x", "y"], ["x", "y"])] +) +def test_from_frame_valid_names(names_in, names_out): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], + columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + ) + mi = MultiIndex.from_frame(df, names=names_in) + assert mi.names == names_out + + +@pytest.mark.parametrize( + "names,expected_error_msg", + [ + ("bad_input", "Names should be list-like for a MultiIndex"), + (["a", "b", "c"], "Length of names must match number of levels in MultiIndex"), + ], +) +def test_from_frame_invalid_names(names, expected_error_msg): + # GH 22420 + df = pd.DataFrame( + [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], + columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + ) + with pytest.raises(ValueError, match=expected_error_msg): + MultiIndex.from_frame(df, names=names) + + +def test_index_equal_empty_iterable(): + # #16844 + a = MultiIndex(levels=[[], []], codes=[[], []], names=["a", "b"]) + b = MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"]) + tm.assert_index_equal(a, b) + + +def test_raise_invalid_sortorder(): + # Test that the MultiIndex constructor raise when a incorrect sortorder is given + # GH#28518 + + levels = [[0, 1], [0, 1, 2]] + + # Correct sortorder + MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2 + ) + + with pytest.raises(ValueError, match=r".* sortorder 2 with lexsort_depth 1.*"): + MultiIndex( + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=2 + ) + + with pytest.raises(ValueError, match=r".* sortorder 1 with lexsort_depth 0.*"): + MultiIndex( + levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=1 + ) + + +def test_datetimeindex(): + idx1 = pd.DatetimeIndex( + ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"] * 2, tz="Asia/Tokyo" + ) + idx2 = date_range("2010/01/01", periods=6, freq="ME", tz="US/Eastern") + idx = MultiIndex.from_arrays([idx1, idx2]) + + expected1 = pd.DatetimeIndex( + ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"], tz="Asia/Tokyo" + ) + + tm.assert_index_equal(idx.levels[0], expected1) + tm.assert_index_equal(idx.levels[1], idx2) + + # from datetime combos + # GH 7888 + date1 = np.datetime64("today") + date2 = datetime.today() + date3 = Timestamp.today() + + for d1, d2 in itertools.product([date1, date2, date3], [date1, date2, date3]): + index = MultiIndex.from_product([[d1], [d2]]) + assert isinstance(index.levels[0], pd.DatetimeIndex) + assert isinstance(index.levels[1], pd.DatetimeIndex) + + # but NOT date objects, matching Index behavior + date4 = date.today() + index = MultiIndex.from_product([[date4], [date2]]) + assert not isinstance(index.levels[0], pd.DatetimeIndex) + assert isinstance(index.levels[1], pd.DatetimeIndex) + + +def test_constructor_with_tz(): + index = pd.DatetimeIndex( + ["2013/01/01 09:00", "2013/01/02 09:00"], name="dt1", tz="US/Pacific" + ) + columns = pd.DatetimeIndex( + ["2014/01/01 09:00", "2014/01/02 09:00"], name="dt2", tz="Asia/Tokyo" + ) + + result = MultiIndex.from_arrays([index, columns]) + + assert result.names == ["dt1", "dt2"] + tm.assert_index_equal(result.levels[0], index) + tm.assert_index_equal(result.levels[1], columns) + + result = MultiIndex.from_arrays([Series(index), Series(columns)]) + + assert result.names == ["dt1", "dt2"] + tm.assert_index_equal(result.levels[0], index) + tm.assert_index_equal(result.levels[1], columns) + + +def test_multiindex_inference_consistency(): + # check that inference behavior matches the base class + + v = date.today() + + arr = [v, v] + + idx = Index(arr) + assert idx.dtype == object + + mi = MultiIndex.from_arrays([arr]) + lev = mi.levels[0] + assert lev.dtype == object + + mi = MultiIndex.from_product([arr]) + lev = mi.levels[0] + assert lev.dtype == object + + mi = MultiIndex.from_tuples([(x,) for x in arr]) + lev = mi.levels[0] + assert lev.dtype == object + + +def test_dtype_representation(using_infer_string): + # GH#46900 + pmidx = MultiIndex.from_arrays([[1], ["a"]], names=[("a", "b"), ("c", "d")]) + result = pmidx.dtypes + exp = "object" if not using_infer_string else "string" + expected = Series( + ["int64", exp], + index=MultiIndex.from_tuples([("a", "b"), ("c", "d")]), + dtype=object, + ) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/38/3800d9b91dceea2065a6ed6279383362e97ac38b8e56b9343f404ee531860099/METADATA b/shared/package-files/38/3800d9b91dceea2065a6ed6279383362e97ac38b8e56b9343f404ee531860099/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..32214fb4400035788bfe5c0de42dad106a4f54f1 --- /dev/null +++ b/shared/package-files/38/3800d9b91dceea2065a6ed6279383362e97ac38b8e56b9343f404ee531860099/METADATA @@ -0,0 +1,420 @@ +Metadata-Version: 2.1 +Name: autocommand +Version: 2.2.2 +Summary: A library to create a command-line program from a function +Home-page: https://github.com/Lucretiel/autocommand +Author: Nathan West +License: LGPLv3 +Project-URL: Homepage, https://github.com/Lucretiel/autocommand +Project-URL: Bug Tracker, https://github.com/Lucretiel/autocommand/issues +Platform: any +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE + +[![PyPI version](https://badge.fury.io/py/autocommand.svg)](https://badge.fury.io/py/autocommand) + +# autocommand + +A library to automatically generate and run simple argparse parsers from function signatures. + +## Installation + +Autocommand is installed via pip: + +``` +$ pip install autocommand +``` + +## Usage + +Autocommand turns a function into a command-line program. It converts the function's parameter signature into command-line arguments, and automatically runs the function if the module was called as `__main__`. In effect, it lets your create a smart main function. + +```python +from autocommand import autocommand + +# This program takes exactly one argument and echos it. +@autocommand(__name__) +def echo(thing): + print(thing) +``` + +``` +$ python echo.py hello +hello +$ python echo.py -h +usage: echo [-h] thing + +positional arguments: + thing + +optional arguments: + -h, --help show this help message and exit +$ python echo.py hello world # too many arguments +usage: echo.py [-h] thing +echo.py: error: unrecognized arguments: world +``` + +As you can see, autocommand converts the signature of the function into an argument spec. When you run the file as a program, autocommand collects the command-line arguments and turns them into function arguments. The function is executed with these arguments, and then the program exits with the return value of the function, via `sys.exit`. Autocommand also automatically creates a usage message, which can be invoked with `-h` or `--help`, and automatically prints an error message when provided with invalid arguments. + +### Types + +You can use a type annotation to give an argument a type. Any type (or in fact any callable) that returns an object when given a string argument can be used, though there are a few special cases that are described later. + +```python +@autocommand(__name__) +def net_client(host, port: int): + ... +``` + +Autocommand will catch `TypeErrors` raised by the type during argument parsing, so you can supply a callable and do some basic argument validation as well. + +### Trailing Arguments + +You can add a `*args` parameter to your function to give it trailing arguments. The command will collect 0 or more trailing arguments and supply them to `args` as a tuple. If a type annotation is supplied, the type is applied to each argument. + +```python +# Write the contents of each file, one by one +@autocommand(__name__) +def cat(*files): + for filename in files: + with open(filename) as file: + for line in file: + print(line.rstrip()) +``` + +``` +$ python cat.py -h +usage: ipython [-h] [file [file ...]] + +positional arguments: + file + +optional arguments: + -h, --help show this help message and exit +``` + +### Options + +To create `--option` switches, just assign a default. Autocommand will automatically create `--long` and `-s`hort switches. + +```python +@autocommand(__name__) +def do_with_config(argument, config='~/foo.conf'): + pass +``` + +``` +$ python example.py -h +usage: example.py [-h] [-c CONFIG] argument + +positional arguments: + argument + +optional arguments: + -h, --help show this help message and exit + -c CONFIG, --config CONFIG +``` + +The option's type is automatically deduced from the default, unless one is explicitly given in an annotation: + +```python +@autocommand(__name__) +def http_connect(host, port=80): + print('{}:{}'.format(host, port)) +``` + +``` +$ python http.py -h +usage: http.py [-h] [-p PORT] host + +positional arguments: + host + +optional arguments: + -h, --help show this help message and exit + -p PORT, --port PORT +$ python http.py localhost +localhost:80 +$ python http.py localhost -p 8080 +localhost:8080 +$ python http.py localhost -p blah +usage: http.py [-h] [-p PORT] host +http.py: error: argument -p/--port: invalid int value: 'blah' +``` + +#### None + +If an option is given a default value of `None`, it reads in a value as normal, but supplies `None` if the option isn't provided. + +#### Switches + +If an argument is given a default value of `True` or `False`, or +given an explicit `bool` type, it becomes an option switch. + +```python + @autocommand(__name__) + def example(verbose=False, quiet=False): + pass +``` + +``` +$ python example.py -h +usage: example.py [-h] [-v] [-q] + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet +``` + +Autocommand attempts to do the "correct thing" in these cases- if the default is `True`, then supplying the switch makes the argument `False`; if the type is `bool` and the default is some other `True` value, then supplying the switch makes the argument `False`, while not supplying the switch makes the argument the default value. + +Autocommand also supports the creation of switch inverters. Pass `add_nos=True` to `autocommand` to enable this. + +``` + @autocommand(__name__, add_nos=True) + def example(verbose=False): + pass +``` + +``` +$ python example.py -h +usage: ipython [-h] [-v] [--no-verbose] + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + --no-verbose +``` + +Using the `--no-` version of a switch will pass the opposite value in as a function argument. If multiple switches are present, the last one takes precedence. + +#### Files + +If the default value is a file object, such as `sys.stdout`, then autocommand just looks for a string, for a file path. It doesn't do any special checking on the string, though (such as checking if the file exists); it's better to let the client decide how to handle errors in this case. Instead, it provides a special context manager called `smart_open`, which behaves exactly like `open` if a filename or other openable type is provided, but also lets you use already open files: + +```python +from autocommand import autocommand, smart_open +import sys + +# Write the contents of stdin, or a file, to stdout +@autocommand(__name__) +def write_out(infile=sys.stdin): + with smart_open(infile) as f: + for line in f: + print(line.rstrip()) + # If a file was opened, it is closed here. If it was just stdin, it is untouched. +``` + +``` +$ echo "Hello World!" | python write_out.py | tee hello.txt +Hello World! +$ python write_out.py --infile hello.txt +Hello World! +``` + +### Descriptions and docstrings + +The `autocommand` decorator accepts `description` and `epilog` kwargs, corresponding to the `description `_ and `epilog `_ of the `ArgumentParser`. If no description is given, but the decorated function has a docstring, then it is taken as the `description` for the `ArgumentParser`. You can also provide both the description and epilog in the docstring by splitting it into two sections with 4 or more - characters. + +```python +@autocommand(__name__) +def copy(infile=sys.stdin, outfile=sys.stdout): + ''' + Copy an the contents of a file (or stdin) to another file (or stdout) + ---------- + Some extra documentation in the epilog + ''' + with smart_open(infile) as istr: + with smart_open(outfile, 'w') as ostr: + for line in istr: + ostr.write(line) +``` + +``` +$ python copy.py -h +usage: copy.py [-h] [-i INFILE] [-o OUTFILE] + +Copy an the contents of a file (or stdin) to another file (or stdout) + +optional arguments: + -h, --help show this help message and exit + -i INFILE, --infile INFILE + -o OUTFILE, --outfile OUTFILE + +Some extra documentation in the epilog +$ echo "Hello World" | python copy.py --outfile hello.txt +$ python copy.py --infile hello.txt --outfile hello2.txt +$ python copy.py --infile hello2.txt +Hello World +``` + +### Parameter descriptions + +You can also attach description text to individual parameters in the annotation. To attach both a type and a description, supply them both in any order in a tuple + +```python +@autocommand(__name__) +def copy_net( + infile: 'The name of the file to send', + host: 'The host to send the file to', + port: (int, 'The port to connect to')): + + ''' + Copy a file over raw TCP to a remote destination. + ''' + # Left as an exercise to the reader +``` + +### Decorators and wrappers + +Autocommand automatically follows wrapper chains created by `@functools.wraps`. This means that you can apply other wrapping decorators to your main function, and autocommand will still correctly detect the signature. + +```python +from functools import wraps +from autocommand import autocommand + +def print_yielded(func): + ''' + Convert a generator into a function that prints all yielded elements + ''' + @wraps(func) + def wrapper(*args, **kwargs): + for thing in func(*args, **kwargs): + print(thing) + return wrapper + +@autocommand(__name__, + description= 'Print all the values from START to STOP, inclusive, in steps of STEP', + epilog= 'STOP and STEP default to 1') +@print_yielded +def seq(stop, start=1, step=1): + for i in range(start, stop + 1, step): + yield i +``` + +``` +$ seq.py -h +usage: seq.py [-h] [-s START] [-S STEP] stop + +Print all the values from START to STOP, inclusive, in steps of STEP + +positional arguments: + stop + +optional arguments: + -h, --help show this help message and exit + -s START, --start START + -S STEP, --step STEP + +STOP and STEP default to 1 +``` + +Even though autocommand is being applied to the `wrapper` returned by `print_yielded`, it still retreives the signature of the underlying `seq` function to create the argument parsing. + +### Custom Parser + +While autocommand's automatic parser generator is a powerful convenience, it doesn't cover all of the different features that argparse provides. If you need these features, you can provide your own parser as a kwarg to `autocommand`: + +```python +from argparse import ArgumentParser +from autocommand import autocommand + +parser = ArgumentParser() +# autocommand can't do optional positonal parameters +parser.add_argument('arg', nargs='?') +# or mutually exclusive options +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') + +@autocommand(__name__, parser=parser) +def main(arg, verbose, quiet): + print(arg, verbose, quiet) +``` + +``` +$ python parser.py -h +usage: write_file.py [-h] [-v | -q] [arg] + +positional arguments: + arg + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet +$ python parser.py +None False False +$ python parser.py hello +hello False False +$ python parser.py -v +None True False +$ python parser.py -q +None False True +$ python parser.py -vq +usage: parser.py [-h] [-v | -q] [arg] +parser.py: error: argument -q/--quiet: not allowed with argument -v/--verbose +``` + +Any parser should work fine, so long as each of the parser's arguments has a corresponding parameter in the decorated main function. The order of parameters doesn't matter, as long as they are all present. Note that when using a custom parser, autocommand doesn't modify the parser or the retrieved arguments. This means that no description/epilog will be added, and the function's type annotations and defaults (if present) will be ignored. + +## Testing and Library use + +The decorated function is only called and exited from if the first argument to `autocommand` is `'__main__'` or `True`. If it is neither of these values, or no argument is given, then a new main function is created by the decorator. This function has the signature `main(argv=None)`, and is intended to be called with arguments as if via `main(sys.argv[1:])`. The function has the attributes `parser` and `main`, which are the generated `ArgumentParser` and the original main function that was decorated. This is to facilitate testing and library use of your main. Calling the function triggers a `parse_args()` with the supplied arguments, and returns the result of the main function. Note that, while it returns instead of calling `sys.exit`, the `parse_args()` function will raise a `SystemExit` in the event of a parsing error or `-h/--help` argument. + +```python + @autocommand() + def test_prog(arg1, arg2: int, quiet=False, verbose=False): + if not quiet: + print(arg1, arg2) + if verbose: + print("LOUD NOISES") + + return 0 + + print(test_prog(['-v', 'hello', '80'])) +``` + +``` +$ python test_prog.py +hello 80 +LOUD NOISES +0 +``` + +If the function is called with no arguments, `sys.argv[1:]` is used. This is to allow the autocommand function to be used as a setuptools entry point. + +## Exceptions and limitations + +- There are a few possible exceptions that `autocommand` can raise. All of them derive from `autocommand.AutocommandError`. + + - If an invalid annotation is given (that is, it isn't a `type`, `str`, `(type, str)`, or `(str, type)`, an `AnnotationError` is raised. The `type` may be any callable, as described in the `Types`_ section. + - If the function has a `**kwargs` parameter, a `KWargError` is raised. + - If, somehow, the function has a positional-only parameter, a `PositionalArgError` is raised. This means that the argument doesn't have a name, which is currently not possible with a plain `def` or `lambda`, though many built-in functions have this kind of parameter. + +- There are a few argparse features that are not supported by autocommand. + + - It isn't possible to have an optional positional argument (as opposed to a `--option`). POSIX thinks this is bad form anyway. + - It isn't possible to have mutually exclusive arguments or options + - It isn't possible to have subcommands or subparsers, though I'm working on a few solutions involving classes or nested function definitions to allow this. + +## Development + +Autocommand cannot be important from the project root; this is to enforce separation of concerns and prevent accidental importing of `setup.py` or tests. To develop, install the project in editable mode: + +``` +$ python setup.py develop +``` + +This will create a link to the source files in the deployment directory, so that any source changes are reflected when it is imported. diff --git a/shared/package-files/38/38065c7656f511b0582e0ed291c692adbad8c3f88a532add62364a884612ef03/mean_meta.h b/shared/package-files/38/38065c7656f511b0582e0ed291c692adbad8c3f88a532add62364a884612ef03/mean_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..51730be508d5d6aa5fee74d67ee9486ab57a7a78 --- /dev/null +++ b/shared/package-files/38/38065c7656f511b0582e0ed291c692adbad8c3f88a532add62364a884612ef03/mean_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_mean_dim : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional dtype); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/38/380727b3daa9c74ea27e086f072eff5c0e56b001a8c6f4ea6b5f7b9170c2339b/test_scalarprint.cpython-311.pyc b/shared/package-files/38/380727b3daa9c74ea27e086f072eff5c0e56b001a8c6f4ea6b5f7b9170c2339b/test_scalarprint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c21837a7f22375b9d6f25a6c9442173d9b82a68c Binary files /dev/null and b/shared/package-files/38/380727b3daa9c74ea27e086f072eff5c0e56b001a8c6f4ea6b5f7b9170c2339b/test_scalarprint.cpython-311.pyc differ diff --git a/shared/package-files/38/380a1ffb254249cb699a29f43c00cd652f6d557fe212132b006c8d0ac6d72117/inner_ops.h b/shared/package-files/38/380a1ffb254249cb699a29f43c00cd652f6d557fe212132b006c8d0ac6d72117/inner_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..694cdefc506b2dd35a6f54b27be2e4c2f8e4e027 --- /dev/null +++ b/shared/package-files/38/380a1ffb254249cb699a29f43c00cd652f6d557fe212132b006c8d0ac6d72117/inner_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API inner { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::inner"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "inner(Tensor self, Tensor other) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API inner_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::inner"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "inner.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/380accfbf5f06df608ac52401230f6908c62d17c91def56570e1a2bbfe2b9612/common.cpython-311.pyc b/shared/package-files/38/380accfbf5f06df608ac52401230f6908c62d17c91def56570e1a2bbfe2b9612/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37eb8452c79aa8a90cd55763c27a75771fe5a260 Binary files /dev/null and b/shared/package-files/38/380accfbf5f06df608ac52401230f6908c62d17c91def56570e1a2bbfe2b9612/common.cpython-311.pyc differ diff --git a/shared/package-files/38/380e2dd57417ed0aa6de91a14d960a9e8e1cff36c872fa525acb4efcb5c8551a/dispatch_interface.py b/shared/package-files/38/380e2dd57417ed0aa6de91a14d960a9e8e1cff36c872fa525acb4efcb5c8551a/dispatch_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc908d707c8efa30ce1e334313e1f946bdb5348 --- /dev/null +++ b/shared/package-files/38/380e2dd57417ed0aa6de91a14d960a9e8e1cff36c872fa525acb4efcb5c8551a/dispatch_interface.py @@ -0,0 +1,185 @@ +# This file contains utilities for testing the dispatching feature + +# A full test of all dispatchable algorithms is performed by +# modifying the pytest invocation and setting an environment variable +# NETWORKX_TEST_BACKEND=nx_loopback pytest +# This is comprehensive, but only tests the `test_override_dispatch` +# function in networkx.classes.backends. + +# To test the `_dispatchable` function directly, several tests scattered throughout +# NetworkX have been augmented to test normal and dispatch mode. +# Searching for `dispatch_interface` should locate the specific tests. + +import networkx as nx +from networkx import DiGraph, Graph, MultiDiGraph, MultiGraph, PlanarEmbedding +from networkx.classes.reportviews import NodeView + + +class LoopbackGraph(Graph): + __networkx_backend__ = "nx_loopback" + + +class LoopbackDiGraph(DiGraph): + __networkx_backend__ = "nx_loopback" + + +class LoopbackMultiGraph(MultiGraph): + __networkx_backend__ = "nx_loopback" + + +class LoopbackMultiDiGraph(MultiDiGraph): + __networkx_backend__ = "nx_loopback" + + +class LoopbackPlanarEmbedding(PlanarEmbedding): + __networkx_backend__ = "nx_loopback" + + +def convert(graph): + if isinstance(graph, PlanarEmbedding): + return LoopbackPlanarEmbedding(graph) + if isinstance(graph, MultiDiGraph): + return LoopbackMultiDiGraph(graph) + if isinstance(graph, MultiGraph): + return LoopbackMultiGraph(graph) + if isinstance(graph, DiGraph): + return LoopbackDiGraph(graph) + if isinstance(graph, Graph): + return LoopbackGraph(graph) + raise TypeError(f"Unsupported type of graph: {type(graph)}") + + +class LoopbackBackendInterface: + def __getattr__(self, item): + try: + return nx.utils.backends._registered_algorithms[item].orig_func + except KeyError: + raise AttributeError(item) from None + + @staticmethod + def convert_from_nx( + graph, + *, + edge_attrs=None, + node_attrs=None, + preserve_edge_attrs=None, + preserve_node_attrs=None, + preserve_graph_attrs=None, + name=None, + graph_name=None, + ): + if name in { + # Raise if input graph changes. See test_dag.py::test_topological_sort6 + "lexicographical_topological_sort", + "topological_generations", + "topological_sort", + # Would be nice to some day avoid these cutoffs of full testing + }: + return graph + if isinstance(graph, NodeView): + # Convert to a Graph with only nodes (no edges) + new_graph = Graph() + new_graph.add_nodes_from(graph.items()) + graph = new_graph + G = LoopbackGraph() + elif not isinstance(graph, Graph): + raise TypeError( + f"Bad type for graph argument {graph_name} in {name}: {type(graph)}" + ) + elif graph.__class__ in {Graph, LoopbackGraph}: + G = LoopbackGraph() + elif graph.__class__ in {DiGraph, LoopbackDiGraph}: + G = LoopbackDiGraph() + elif graph.__class__ in {MultiGraph, LoopbackMultiGraph}: + G = LoopbackMultiGraph() + elif graph.__class__ in {MultiDiGraph, LoopbackMultiDiGraph}: + G = LoopbackMultiDiGraph() + elif graph.__class__ in {PlanarEmbedding, LoopbackPlanarEmbedding}: + G = LoopbackDiGraph() # or LoopbackPlanarEmbedding + else: + # Would be nice to handle these better some day + # nx.algorithms.approximation.kcomponents._AntiGraph + # nx.classes.tests.test_multidigraph.MultiDiGraphSubClass + # nx.classes.tests.test_multigraph.MultiGraphSubClass + G = graph.__class__() + + if preserve_graph_attrs: + G.graph.update(graph.graph) + + # add nodes + G.add_nodes_from(graph) + if preserve_node_attrs: + for n, dd in G._node.items(): + dd.update(graph.nodes[n]) + elif node_attrs: + for n, dd in G._node.items(): + dd.update( + (attr, graph._node[n].get(attr, default)) + for attr, default in node_attrs.items() + if default is not None or attr in graph._node[n] + ) + + # tools to build datadict and keydict + if preserve_edge_attrs: + + def G_new_datadict(old_dd): + return G.edge_attr_dict_factory(old_dd) + elif edge_attrs: + + def G_new_datadict(old_dd): + return G.edge_attr_dict_factory( + (attr, old_dd.get(attr, default)) + for attr, default in edge_attrs.items() + if default is not None or attr in old_dd + ) + else: + + def G_new_datadict(old_dd): + return G.edge_attr_dict_factory() + + if G.is_multigraph(): + + def G_new_inner(keydict): + kd = G.adjlist_inner_dict_factory( + (k, G_new_datadict(dd)) for k, dd in keydict.items() + ) + return kd + else: + G_new_inner = G_new_datadict + + # add edges keeping the same order in _adj and _pred + G_adj = G._adj + if G.is_directed(): + for n, nbrs in graph._adj.items(): + G_adj[n].update((nbr, G_new_inner(dd)) for nbr, dd in nbrs.items()) + # ensure same datadict for pred and adj; and pred order of graph._pred + G_pred = G._pred + for n, nbrs in graph._pred.items(): + G_pred[n].update((nbr, G_adj[nbr][n]) for nbr in nbrs) + else: # undirected + for n, nbrs in graph._adj.items(): + # ensure same datadict for both ways; and adj order of graph._adj + G_adj[n].update( + (nbr, G_adj[nbr][n] if n in G_adj[nbr] else G_new_inner(dd)) + for nbr, dd in nbrs.items() + ) + + return G + + @staticmethod + def convert_to_nx(obj, *, name=None): + return obj + + @staticmethod + def on_start_tests(items): + # Verify that items can be xfailed + for item in items: + assert hasattr(item, "add_marker") + + def can_run(self, name, args, kwargs): + # It is unnecessary to define this function if algorithms are fully supported. + # We include it for illustration purposes. + return hasattr(self, name) + + +backend_interface = LoopbackBackendInterface() diff --git a/shared/package-files/38/381609a210e54a6f58b96674adb9cc7a72db63edbf5b5c9211490f24f0fd5e47/python_tracer.h b/shared/package-files/38/381609a210e54a6f58b96674adb9cc7a72db63edbf5b5c9211490f24f0fd5e47/python_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..55c36f7a88ab05d58ccedaf26f8cd2958647f765 --- /dev/null +++ b/shared/package-files/38/381609a210e54a6f58b96674adb9cc7a72db63edbf5b5c9211490f24f0fd5e47/python_tracer.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +struct Module; + +namespace tracer { +void initPythonTracerBindings(PyObject* module); + +SourceRange getPythonInterpreterSourceRange(); + +Node* preRecordPythonTrace( + THPObjectPtr pyobj, + const std::string& arg_types, + at::ArrayRef inputs, + std::vector scalar_args); + +std::pair, Stack> createGraphByTracingWithDict( + const py::function& func, + const py::dict& inputs_dict, + const Stack& inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); + +std::pair, Stack> createGraphByTracing( + const py::function& func, + Stack inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); +} // namespace tracer +} // namespace torch::jit diff --git a/shared/package-files/38/381636f21ba211622da86822ba4819cc72cb6926d2f328fd91d867feee7ad988/_internal_testing.py b/shared/package-files/38/381636f21ba211622da86822ba4819cc72cb6926d2f328fd91d867feee7ad988/_internal_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc2d017930b812ba4d6883e971d53a643a97bce --- /dev/null +++ b/shared/package-files/38/381636f21ba211622da86822ba4819cc72cb6926d2f328fd91d867feee7ad988/_internal_testing.py @@ -0,0 +1,178 @@ +import os +import re +import numpy as np +import torch +import triton +import triton.language as tl +from triton.backends.nvidia.compiler import _path_to_binary +import pytest + +from numpy.random import RandomState +from typing import Optional, Union +from triton.runtime.jit import TensorWrapper, reinterpret, type_canonicalisation_dict + +int_dtypes = ['int8', 'int16', 'int32', 'int64'] +uint_dtypes = ['uint8', 'uint16', 'uint32', 'uint64'] +integral_dtypes = int_dtypes + uint_dtypes +float_dtypes = ['float16', 'float32', 'float64'] +float_dtypes_with_bfloat16 = float_dtypes + ['bfloat16'] +dtypes = integral_dtypes + float_dtypes +dtypes_with_bfloat16 = dtypes + ['bfloat16'] +torch_float8_dtypes = ['float8_e4m3fn', 'float8_e5m2'] +torch_dtypes = ['bool'] + int_dtypes + ['uint8'] + float_dtypes + ['bfloat16'] + + +def is_interpreter(): + return os.environ.get('TRITON_INTERPRET', '0') == '1' + + +def get_current_target(): + if is_interpreter(): + return None + return triton.runtime.driver.active.get_current_target() + + +def is_cuda(): + target = get_current_target() + return False if target is None else target.backend == "cuda" + + +def is_hopper(): + return is_cuda() and torch.cuda.get_device_capability()[0] >= 9 + + +def is_hip(): + target = get_current_target() + return False if target is None else target.backend == "hip" + + +def is_hip_mi200(): + target = get_current_target() + if target is None or target.backend != 'hip': + return False + return target.arch == 'gfx90a' + + +def is_hip_mi300(): + target = get_current_target() + if target is None or target.backend != 'hip': + return False + return target.arch in ('gfx940', 'gfx941', 'gfx942') + + +def is_hip_mi350(): + target = get_current_target() + if target is None or target.backend != 'hip': + return False + return target.arch in ('gfx950') + + +def is_hip_cdna(): + return is_hip_mi200() or is_hip_mi300() or is_hip_mi350() + + +def is_xpu(): + target = get_current_target() + return False if target is None else target.backend == "xpu" + + +def get_arch(): + target = get_current_target() + return "" if target is None else str(target.arch) + + +def numpy_random(shape, dtype_str, rs: Optional[RandomState] = None, low=None, high=None): + """ + Override `rs` if you're calling this function twice and don't want the same + result for both calls. + """ + if isinstance(shape, int): + shape = (shape, ) + if rs is None: + rs = RandomState(seed=17) + if dtype_str in int_dtypes + uint_dtypes: + iinfo = np.iinfo(getattr(np, dtype_str)) + low = iinfo.min if low is None else max(low, iinfo.min) + high = iinfo.max if high is None else min(high, iinfo.max) + dtype = getattr(np, dtype_str) + x = rs.randint(low, high, shape, dtype=dtype) + x[x == 0] = 1 # Workaround. Never return zero so tests of division don't error out. + return x + elif dtype_str and 'float8' in dtype_str: + x = rs.randint(20, 40, shape, dtype=np.int8) + return x + elif dtype_str in float_dtypes: + return rs.normal(0, 1, shape).astype(dtype_str) + elif dtype_str == 'bfloat16': + return (rs.normal(0, 1, shape).astype('float32').view('uint32') & np.uint32(0xffff0000)).view('float32') + elif dtype_str in ['bool', 'int1', 'bool_']: + return rs.normal(0, 1, shape) > 0.0 + else: + raise RuntimeError(f'Unknown dtype {dtype_str}') + + +def to_triton(x: np.ndarray, device, dst_type=None) -> Union[TensorWrapper, torch.Tensor]: + ''' + Note: We need dst_type because the type of x can be different from dst_type. + For example: x is of type `float32`, dst_type is `bfloat16`. + If dst_type is None, we infer dst_type from x. + ''' + t = x.dtype.name + if t in uint_dtypes: + signed_type_name = t.lstrip('u') # e.g. "uint16" -> "int16" + x_signed = x.astype(getattr(np, signed_type_name)) + return reinterpret(torch.tensor(x_signed, device=device), getattr(tl, t)) + else: + if dst_type and 'float8' in dst_type: + return reinterpret(torch.tensor(x, device=device), getattr(tl, dst_type)) + if t == 'float32' and dst_type == 'bfloat16': + return torch.tensor(x, device=device).bfloat16() + return torch.tensor(x, device=device) + + +def str_to_triton_dtype(x: str) -> tl.dtype: + return tl.str_to_ty(type_canonicalisation_dict[x]) + + +def torch_dtype_name(dtype) -> str: + if isinstance(dtype, triton.language.dtype): + return dtype.name + elif isinstance(dtype, torch.dtype): + # 'torch.int64' -> 'int64' + m = re.match(r'^torch\.(\w+)$', str(dtype)) + return m.group(1) + else: + raise TypeError(f'not a triton or torch dtype: {type(dtype)}') + + +def to_numpy(x): + if isinstance(x, TensorWrapper): + return x.base.cpu().numpy().astype(getattr(np, torch_dtype_name(x.dtype))) + elif isinstance(x, torch.Tensor): + if x.dtype is torch.bfloat16: + return x.cpu().float().numpy() + return x.cpu().numpy() + else: + raise ValueError(f"Not a triton-compatible tensor: {x}") + + +def supports_tma(byval_only=False): + if is_interpreter(): + return True + if not is_cuda(): + return False + _, cuda_version = _path_to_binary("ptxas") + min_cuda_version = (12, 0) if byval_only else (12, 3) + cuda_version_tuple = tuple(map(int, cuda_version.split("."))) + assert len(cuda_version_tuple) == 2, cuda_version_tuple + return torch.cuda.get_device_capability()[0] >= 9 and cuda_version_tuple >= min_cuda_version + + +def tma_skip_msg(byval_only=False): + if byval_only: + return "Requires __grid_constant__ TMA support (NVIDIA Hopper or higher, CUDA 12.0 or higher)" + else: + return "Requires advanced TMA support (NVIDIA Hopper or higher, CUDA 12.3 or higher)" + + +requires_tma = pytest.mark.skipif(not supports_tma(), reason=tma_skip_msg()) diff --git a/shared/package-files/38/381788a9d0199102e5aa7675157a937d6de360d179ddd2f7d871eb35927ec106/saved_variable_hooks.h b/shared/package-files/38/381788a9d0199102e5aa7675157a937d6de360d179ddd2f7d871eb35927ec106/saved_variable_hooks.h new file mode 100644 index 0000000000000000000000000000000000000000..ed255d34a04303febc347740aa40a9913b1b3332 --- /dev/null +++ b/shared/package-files/38/381788a9d0199102e5aa7675157a937d6de360d179ddd2f7d871eb35927ec106/saved_variable_hooks.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace torch::autograd { + +struct TORCH_API SavedVariableHooks { + virtual void call_pack_hook(const at::Tensor& tensor) = 0; + virtual at::Tensor call_unpack_hook() = 0; + virtual ~SavedVariableHooks() = default; + virtual std::optional> + retrieve_unpack_hook_data() const { + throw std::runtime_error( + "Compiled Autograd only supports python saved tensor hooks "); + } +}; + +} // namespace torch::autograd diff --git a/shared/package-files/38/38180f853e0a58b01bbe681d40adcd245f9a2e7cd0578aeb3217e908382d634a/Store.hpp b/shared/package-files/38/38180f853e0a58b01bbe681d40adcd245f9a2e7cd0578aeb3217e908382d634a/Store.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0b6dfe48d0d0c27b048ccf6c779b45e98f651467 --- /dev/null +++ b/shared/package-files/38/38180f853e0a58b01bbe681d40adcd245f9a2e7cd0578aeb3217e908382d634a/Store.hpp @@ -0,0 +1,129 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace c10d { + +// callback function will be given arguments (std::optional oldValue, +// std::optional newValue) +using WatchKeyCallback = + std::function, std::optional)>; + +class TORCH_API Store : public torch::CustomClassHolder { + public: + static constexpr std::chrono::milliseconds kDefaultTimeout = + std::chrono::seconds(300); + static constexpr std::chrono::milliseconds kNoTimeout = + std::chrono::milliseconds::zero(); + + Store() : timeout_(kDefaultTimeout) {} + + explicit Store(const std::chrono::milliseconds& timeout) + : timeout_(timeout) {} + + Store(const Store&) = default; + Store(Store&&) noexcept = default; + + ~Store() override = default; + + void set(const std::string& key, const std::string& value); + + virtual void set( + const std::string& key, + const std::vector& value) = 0; + + std::string compareSet( + const std::string& key, + const std::string& currentValue, + const std::string& newValue); + + virtual std::vector compareSet( + const std::string& key, + const std::vector& currentValue, + const std::vector& newValue) { + TORCH_INTERNAL_ASSERT(false, "Not implemented."); + } + + std::string get_to_str(const std::string& key); + + virtual std::vector get(const std::string& key) = 0; + + virtual int64_t add(const std::string& key, int64_t value) = 0; + + virtual bool deleteKey(const std::string& key) = 0; + + virtual bool check(const std::vector& keys) = 0; + + virtual int64_t getNumKeys() = 0; + + virtual void wait(const std::vector& keys) = 0; + + virtual void wait( + const std::vector& keys, + const std::chrono::milliseconds& timeout) = 0; + + virtual const std::chrono::milliseconds& getTimeout() const noexcept; + + virtual void setTimeout(const std::chrono::milliseconds& timeout); + + // watchKey() is deprecated and no longer supported. + virtual void watchKey( + const std::string& /* unused */, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + WatchKeyCallback /* unused */) { + TORCH_CHECK(false, "watchKey is deprecated, no implementation support it."); + } + + virtual void append( + const std::string& key, + const std::vector& value); + + virtual std::vector> multiGet( + const std::vector& keys); + + virtual void multiSet( + const std::vector& keys, + const std::vector>& values); + + // Returns true if this store support append, multiGet and multiSet + virtual bool hasExtendedApi() const; + + protected: + std::chrono::milliseconds timeout_; +}; + +/* +StoreTimeoutGuard is a RAII guard that will set the store timeout and restore it +when it returns. +*/ +class StoreTimeoutGuard { + public: + explicit StoreTimeoutGuard( + Store& store, + const std::chrono::milliseconds& timeout) + : store_(store), oldTimeout_(store.getTimeout()) { + store.setTimeout(timeout); + } + + ~StoreTimeoutGuard() { + store_.setTimeout(oldTimeout_); + } + + /* Disabling copy and move semantics */ + StoreTimeoutGuard(const StoreTimeoutGuard&) = delete; + StoreTimeoutGuard& operator=(const StoreTimeoutGuard&) = delete; + StoreTimeoutGuard(StoreTimeoutGuard&&) = delete; + StoreTimeoutGuard& operator=(StoreTimeoutGuard&&) = delete; + + private: + Store& store_; + std::chrono::milliseconds oldTimeout_{}; +}; + +} // namespace c10d diff --git a/shared/package-files/38/3819c5cfe385b3810c437d17420d4f06c29ab100508deb37011cd4ccf09b5858/string_arrow.cpython-311.pyc b/shared/package-files/38/3819c5cfe385b3810c437d17420d4f06c29ab100508deb37011cd4ccf09b5858/string_arrow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..978cdb77a75e1bd300d59354ae3697f546ae1a63 Binary files /dev/null and b/shared/package-files/38/3819c5cfe385b3810c437d17420d4f06c29ab100508deb37011cd4ccf09b5858/string_arrow.cpython-311.pyc differ diff --git a/shared/package-files/38/381c4d7b001c1aeb0cea3ba6ad6db35039b2b4fe9e0403af934bad7d33a775f4/_coalesce.h b/shared/package-files/38/381c4d7b001c1aeb0cea3ba6ad6db35039b2b4fe9e0403af934bad7d33a775f4/_coalesce.h new file mode 100644 index 0000000000000000000000000000000000000000..d03342f2d592264836a3bd67cadaced773072a0c --- /dev/null +++ b/shared/package-files/38/381c4d7b001c1aeb0cea3ba6ad6db35039b2b4fe9e0403af934bad7d33a775f4/_coalesce.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_coalesce(Tensor self) -> Tensor +inline at::Tensor _coalesce(const at::Tensor & self) { + return at::_ops::_coalesce::call(self); +} + +// aten::_coalesce.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _coalesce_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::_coalesce_out::call(self, out); +} +// aten::_coalesce.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _coalesce_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::_coalesce_out::call(self, out); +} + +} diff --git a/shared/package-files/38/381d0d3d6bddd4777217102003939a401c5f2e5e6f884da0322bf94106d0c3a6/sizevars.py b/shared/package-files/38/381d0d3d6bddd4777217102003939a401c5f2e5e6f884da0322bf94106d0c3a6/sizevars.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7f24f96498165932815e7c26ecff352161d325 --- /dev/null +++ b/shared/package-files/38/381d0d3d6bddd4777217102003939a401c5f2e5e6f884da0322bf94106d0c3a6/sizevars.py @@ -0,0 +1,925 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections.abc import Iterable, Sequence +from typing import Any, Callable, cast, Optional, Union + +import sympy +from sympy import Expr + +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols, ShapeEnv +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import FloorDiv, ModularIndexing +from torch.utils._sympy.symbol import symbol_is_type, SymT +from torch.utils._sympy.value_ranges import bound_sympy, IntInfinity, ValueRanges + +from .runtime.runtime_utils import is_power_of_2 +from .utils import ( + has_free_symbols, + sympy_index_symbol, + sympy_index_symbol_with_prefix, + sympy_subs, + VarRanges, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + + +def evaluate_expr( + shape_env: ShapeEnv, + expr: Union[sympy.Basic, bool], + axioms: Optional[tuple[sympy.Expr]] = None, + var_to_range: Optional[tuple[tuple[sympy.Symbol, ValueRanges[Any]]]] = None, +) -> bool: + if expr in (True, False): + return bool(expr) + + try: + simplified = shape_env._maybe_evaluate_static( + expr, + axioms=axioms, + var_to_range=var_to_range, + ) + if simplified is not None: + return bool(simplified) + except Exception: + log.debug("Could not simplify %s", expr, exc_info=True) + + return False + + +# This class is a little awkward, because ShapeEnv is doing most of the heavy +# lifting and in some cases we should be directly passing through to ShapeEnv, +# but there is some extra inductor logic that needs to be handled here +class SizeVarAllocator: + def __init__(self, shape_env=None) -> None: + super().__init__() + if shape_env is None: + shape_env = ShapeEnv() + self.shape_env = shape_env + self.var_to_val = self.shape_env.var_to_val + self.replacements: dict[sympy.Symbol, Expr] = self.shape_env.replacements + # Maps of dynamic sizes that have to be precomputed on the host to the kernel args. + # The basic idea is if we have some complicated sympy expression + # f(s0), we may choose to precompute it on the host and then replace + # all occurrences of that sympy expression with ps0, so that when we + # codegen we simply reference ps0 directly without repeating + # f(s0). Unlike regular size variables, ps variables cannot be + # guarded upon; so if we are asked to guard on a Sympy expression + # which potentially could have already had a precomputed replacement + # on it, we are obligated to invert the precomputed replacements + # (inv_precomputed_replacements). + self.precomputed_replacements: dict[Expr, sympy.Symbol] = {} + self.inv_precomputed_replacements: dict[sympy.Symbol, Expr] = {} + self.stride_vars = self.make_stride_vars_cache() + self.simplify_with_ranges = self.make_simplify_with_ranges_cache() + self._simplify_loops = self.make_simplify_loops_cache() + + def simplify(self, expr: Expr): + return sympy.expand(expr).xreplace(self.replacements) + + def make_simplify_with_ranges_cache(self) -> Callable[[Expr, VarRanges], Expr]: + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: dict[tuple[Any, ...], Expr] = {} + replacement_count = len(self.replacements) + + def simplify_with_ranges(expr: Expr, var_ranges: VarRanges) -> Expr: + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (expr, *var_ranges.items()) + result = cache.get(key, None) + if result is None: + result = self._simplify_with_ranges(expr, var_ranges) + cache[key] = result + if result != expr: + cache[(result, *var_ranges.items())] = result + return result + + return simplify_with_ranges + + def make_simplify_loops_cache(self): + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: dict[tuple[Any, ...], Any] = {} + replacement_count = len(self.replacements) + + def simplify_loops(index_vars, sizes, index_formulas): + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (*index_vars, *sizes, *index_formulas) + result = cache.get(key, None) + if result is None: + result = self._simplify_loops_impl(index_vars, sizes, index_formulas) + cache[key] = result + return result + + return simplify_loops + + def _simplify_with_ranges(self, expr: Expr, var_ranges: VarRanges) -> Expr: + """ + Simplify indexing expression with knowledge of the ranges of + iteration variables. + """ + + expr = join_dimensions(self.simplify(expr)) + original_expr = expr + + var_to_range = dict(self.shape_env.var_to_range) + var_to_range.update( + { + k: ValueRanges( + 0, max(0, v - 1) if not has_free_symbols([v]) else IntInfinity() + ) + for k, v in var_ranges.items() + } + ) + for var in expr.free_symbols: + if var not in var_to_range: + var_to_range[var] = ValueRanges(0, IntInfinity()) + + var_to_range_tuple = cast( + tuple[tuple[sympy.Symbol, ValueRanges[sympy.Expr]]], + tuple(var_to_range.items()), + ) + + axioms = [] + for var, upper_bound in var_ranges.items(): + axioms.append(0 <= var) + axioms.append(var < upper_bound) + axioms = tuple(axioms) + self.shape_env.get_axioms() + + def statically_known(expr): + evaluated = self.shape_env._maybe_evaluate_static( + expr, + axioms=axioms, + var_to_range=var_to_range_tuple, + ) + return bool(evaluated) + + def remove_zero_terms(base, divisor): + """Symbols smaller than the divisor are zero""" + if not statically_known(base >= 0): + return base + + for v in base.free_symbols: + if v in var_ranges: + # var smaller than divisor can be removed + # if the rest is guaranteed to be multiple of divisor + rest = sympy.Wild("_rest", exclude=[v]) + m = base.match(v + rest) + if m and v not in m[rest].free_symbols: + gcd = sympy.gcd(m[rest], divisor) + if gcd == divisor: + if statically_known(v < divisor): + base = m[rest] + return base + + def visit_indexing_div(base, divisor): + return FloorDiv(remove_zero_terms(base, divisor), divisor) + + def visit_modular_indexing(base, divisor, modulus): + base = remove_zero_terms(base, divisor) + + can_remove_mod = statically_known(base >= 0) and statically_known( + base < modulus * divisor + ) + + if can_remove_mod: + return FloorDiv(base, divisor) + return ModularIndexing(base, divisor, modulus) + + if expr.has(ModularIndexing): + expr = expr.replace( + ModularIndexing( + sympy.Wild("base", integer=True), + sympy.Wild("divisor", integer=True), + sympy.Wild("modulus", integer=True), + ), + visit_modular_indexing, + ) + + if expr.has(FloorDiv): + expr = expr.replace( + FloorDiv( + sympy.Wild("base", integer=True), + sympy.Wild("divisor", integer=True), + ), + visit_indexing_div, + ) + + if expr != original_expr: + return self._simplify_with_ranges(expr, var_ranges) + return expr + + def _simplify_loops_impl( + self, index_vars: list[sympy.Symbol], sizes, index_formulas + ): + """ + Try to remove as many axis from loop iterations as possible, by: + 1) removing size==1 dimensions + 2) fuse contiguous dimensions into a single loop + If channel_last = True, we will prevent the last dim fused with other dims + """ + sizes = list(map(self.simplify, sizes)) + + strides = [ + # index_formulas may contain boolean expressions (e.g. s0 < 10), + # for which "strides" don't make sense so we ignore them here. + # NOTE: These expressions may still block merging dims in the sound + # substitution test performed in can_merge_dims. + ( + self.stride_vars(x, index_vars) + if isinstance(x, sympy.Expr) + else [0] * len(index_vars) + ) + for x in index_formulas + ] + assert len(sizes) == len(strides[0]), (len(sizes), len(strides[0])) + + for i in range(len(sizes)): + if sizes[i] == 1: + # remove dim + sizes[i] = None + + def can_merge_dims(a, b): + for k in range(len(strides)): + if self.simplify(strides[k][a] * sizes[a]) == self.simplify( + strides[k][b] + ): + # approximate test passed, try sound version + va = index_vars[a] + vb = index_vars[b] + m1 = sympy_index_symbol("_merge_tester1") + m2 = sympy_index_symbol("_merge_tester2") + # NOTE: can't sub vb=0 here in case va * vb appears in the expression, + # in which case both expr1 and expr2 would be zero! + expr1 = sympy_subs(index_formulas[k], {va: m1 * sizes[a], vb: m2}) + expr2 = sympy_subs(index_formulas[k], {va: 0, vb: (m1 + m2)}) + if self.simplify(expr1) == self.simplify(expr2): + continue + return False + return True + + changed = True + while changed: + changed = False + for i, j in itertools.product( + reversed(range(len(sizes))), reversed(range(len(sizes))) + ): + if i == j or sizes[i] is None or sizes[j] is None: + continue + if can_merge_dims(i, j): + changed = True + sizes[i] = sizes[i] * sizes[j] + sizes[j] = None + + def reindex(index): + it = list(reversed(index)) + new_index = [] + for size in sizes: + if size is None: + new_index.append(sympy.S.Zero) + else: + new_index.append(it.pop()) + assert not it + return new_index + + def prune(index): + assert len(index) == len(sizes) + return [i for i, s in zip(index, sizes) if s is not None] + + return [x for x in sizes if x is not None], reindex, prune + + # Note - [On Statically Known] + # + # The statically_known_* family of functions below replaces a prior system, called maybe_guard_*. The prior system + # operated by providing essentially a question, where the size hinted values were evaluated. If the condition was + # true, we add a guard and return True, otherwise, False. + # + # def maybe_guard_foo(args): + # if size_hinted_check(args): + # return False # No guard, no optim + # guard(args) # Make a guard + # return True # Safe to apply optimization + # + # The prior system incurred a guard, and green lit an optimization. + # + # The new system works in reverse - in the new system, if we know that the inputs are static, and evaluate the + # condition as true, we green light the optimization, and we do not incur a guard. If we cannot prove that, we + # return False. + # + # def maybe_guard_foo(args): + # if all_static(args): + # return True # Safe to apply optimization + # else: + # return False # No guard, no optim + + # See Note - [On Statically Known] + + def is_expr_static_and_true(self, expr: Union[sympy.Basic, bool]) -> bool: + return evaluate_expr(self.shape_env, expr) + + def statically_known_equals( + self, left: Union[Expr, int], right: Union[Expr, int] + ) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right are equal. + """ + return self.is_expr_static_and_true(sympy.Eq(left, right)) # type: ignore[arg-type] + + # See Note - [On Statically Known] + def statically_known_list_equals(self, left: list[Expr], right: list[Expr]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right lists are equal. + """ + return len(left) == len(right) and all( + self.statically_known_equals(l, r) for l, r in zip(left, right) + ) + + # See Note - [On Statically Known] + def statically_known_leq(self, left: Expr, right: Union[Expr, int]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than or equal to right. + """ + expr = left <= right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_geq(self, left: Expr, right: Union[Expr, int]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is greater than or equal to right. + """ + expr = left >= right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_lt(self, left: Expr, right: Union[Expr, int]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than right. + """ + expr = left < right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_gt(self, left: Expr, right: Union[Expr, int]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is greater than right. + """ + expr = left > right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_multiple_of( + self, numerator: Expr, denominator: Union[Expr, int] + ) -> bool: + """ + Return a bool indicating if it is sound to optimize for the numerator being a multiple of the denominator. + """ + if free_unbacked_symbols(numerator) or free_unbacked_symbols(denominator): + return False + expr = sympy.Eq(numerator % denominator, 0) + return self.is_expr_static_and_true(expr) # type: ignore[arg-type] + + # See Note - [On Statically Known] + def statically_known_power_of_2(self, expr: Expr) -> bool: + """ + Returns a bool indicating if x is known to be a power of 2. + """ + return isinstance(expr, sympy.Integer) and is_power_of_2(int(expr)) + + # The guard functions require you to ALREADY KNOW that a particular + # condition holds. If you don't know (you want to guard on an expression + # being a particular value, and then get access to that value), use + # the evaluate functions. + + def guard_equals(self, left: Expr, right: Expr) -> Expr: + if isinstance(left, Expr): + left = sympy_subs(left, self.inv_precomputed_replacements) # type: ignore[arg-type] + if isinstance(right, Expr): + right = sympy_subs(right, self.inv_precomputed_replacements) # type: ignore[arg-type] + + expr = sympy.Eq(left, right) + static_expr = self.shape_env._maybe_evaluate_static(expr) + + if static_expr is not None: + assert bool(static_expr) + return left + + assert self.shape_env.defer_runtime_assert(expr, "guard_equals") + return left + + def guard_leq(self, left: Expr, right: Expr) -> None: + return self.guard_lt(left, right + 1) + + def guard_lt(self, left: Expr, right: Expr) -> None: + expr = sympy.Lt(left, right) + static_expr = self.shape_env._maybe_evaluate_static(expr) + + if static_expr is not None: + assert bool(static_expr) + return + + assert self.shape_env.defer_runtime_assert(expr, "guard_lt") + + def guarded_order(self, seq): + """ + Return the order of a sequence as a permutation of range(len(seq)) and guard on that order not changing. + """ + seq = [*map(self.remove_precomputed_replacements, seq)] + seq = [(self.size_hint(var), orig_idx, var) for orig_idx, var in enumerate(seq)] + seq.sort() + order = [-1] * len(seq) + last_var = None + for new_index, (_, orig_index, var) in enumerate(seq): + order[orig_index] = new_index + if last_var is not None: + self.guard_leq(last_var, var) + last_var = var + return order + + # The evaluate functions evaluate some symbolic sympy expression + # (NB: not necessarily an Expr) and return what the concrete result + # is, guarding on the expression being that result + + # NB: write evaluate_expr(sympy.Lt(a, b)) rather than evaluate_expr(a < b) + # as this will ensure that you actually have a sympy'ified expression, + # and will prevent you from incorrectly writing evaluate_expr(a == b) + # which does the wrong thing if a or b is a sympy expression + def evaluate_expr( + self, + left: Union[Expr, sympy.logic.boolalg.Boolean], + size_oblivious: bool = False, + ) -> bool: + assert isinstance(left, (Expr, sympy.logic.boolalg.Boolean)), type(left) + return self.shape_env.evaluate_expr( + sympy.sympify(left), size_oblivious=size_oblivious + ) + + def evaluate_min(self, left: Expr, right: Expr) -> Expr: + """return the smaller of left and right, and guard on that choice""" + if isinstance(left, Expr): + left = sympy_subs(left, self.inv_precomputed_replacements) # type: ignore[arg-type] + if isinstance(right, Expr): + right = sympy_subs(right, self.inv_precomputed_replacements) # type: ignore[arg-type] + try: + lv = self.size_hint(left) + rv = self.size_hint(right) + except TypeError: # unbacked symints + if left == right or self.statically_known_leq(left, right): + return left + if self.statically_known_leq(right, left): + return right + gcd = sympy.gcd(left, right) + if left == gcd: # handle `min(10*u0, u0)` etc + return left + if right == gcd: + return right + raise TypeError( + f"evaluate_min({left}, {right}) with unbacked symints" + ) from None + if lv <= rv: + self.guard_leq(left, right) + return left + else: + self.guard_leq(right, left) + return right + + def evaluate_max(self, left: Expr, right: Expr) -> Expr: + """return the larger of left and right, and guard on that choice""" + # Always choose the opposite of eval min for consistency + # This means min(a, b) and max(a, b) produce the same guards + min_val = self.evaluate_min(left, right) + return right if min_val is left else left + + def evaluate_static_shape(self, left: Union[Expr, int]) -> int: + if isinstance(left, int): + return left + right = self.size_hint(left) + self.guard_equals(left, sympy.Integer(right)) + return int(right) + + def evaluate_static_shapes(self, left: Sequence[Union[Expr, int]]) -> list[int]: + return [self.evaluate_static_shape(x) for x in left] + + def remove_precomputed_replacements(self, expr: Expr) -> Expr: + if any(symbol_is_type(s, SymT.PRECOMPUTED_SIZE) for s in expr.free_symbols): # type: ignore[attr-defined] + return sympy_subs(expr, self.inv_precomputed_replacements) # type: ignore[arg-type] + return expr + + def symbolic_hint(self, expr: Union[Expr, int]) -> Union[Expr, int]: + if isinstance(expr, int): + return expr + # Substitute all hints into expr, but leave unbacked symints alone + expr = self.simplify(expr) + if not isinstance(expr, Expr): + assert isinstance(expr, int) + return expr + free_symbols = expr.free_symbols + if not free_symbols: + try: + return int(expr) # type: ignore[return-value] + except TypeError: + return expr # inf/nan/I + expr = self.remove_precomputed_replacements(expr) + return sympy_subs(expr, self.var_to_val) + + def size_hint( + self, expr: Union[Expr, int], *, fallback: Optional[int] = None + ) -> int: + out = self.symbolic_hint(expr) + if not isinstance(out, (int, sympy.Integer)) and fallback is not None: + # Use the provided heuristic fallback hint + unbacked_sym_vrs = { + s: self.shape_env.var_to_range.get(s, None) for s in out.free_symbols + } + if all(vr is not None for vr in unbacked_sym_vrs.values()): + hint_vr = bound_sympy(out, unbacked_sym_vrs) # type: ignore[arg-type] + if isinstance(hint_vr.lower, (int, sympy.Integer)): + fallback = max(fallback, int(hint_vr.lower)) + if isinstance(hint_vr.upper, (int, sympy.Integer)): + fallback = min(fallback, int(hint_vr.upper)) + return fallback + + try: + return int(out) + except Exception: + log.debug("failed on: %s", out) + raise + + def size_hints( + self, + exprs: Iterable[Expr], + *, + fallback: Optional[int] = None, + ) -> tuple[int, ...]: + return tuple(self.size_hint(x, fallback=fallback) for x in exprs) + + def _lru_cache(self, fn, maxsize=None): + """ + Wrapper around functools.lru_cache that clears when replacements + has been invalidated. + """ + fn_cache = functools.lru_cache(maxsize)(fn) + prior_len = len(self.replacements) + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + nonlocal prior_len + if prior_len != len(self.replacements): + prior_len = len(self.replacements) + fn_cache.cache_clear() + return fn_cache(*args, **kwargs) + + return wrapper + + def make_stride_vars_cache(self): + cache = self._lru_cache(self._stride_vars) + + def stride_vars( + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Optional[Sequence[sympy.Symbol]] = None, + ) -> list[Expr]: + if not support_vars: + support_vars = vars + return cache(index, tuple(vars), tuple(support_vars)) + + return stride_vars + + def _stride_vars( + self, + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol], + ) -> list[Expr]: + """Convert an indexing expression back into strides + + NOTE: This is only valid if the index is a standard strided offset + calculation. e.g. 10 * ModularIndexing(i0 + 1, 1, 2) would give a + stride of -10 because the index wraps around after the first element + + """ + strides = [] + index = self.simplify(index) + # remove any offset + index = index - sympy_subs( + index, {v: sympy.S.Zero for v in support_vars if v != 0} + ) + for i in range(len(vars)): + # drop all the other dims + index_dim = sympy_subs( + index, + { + support_vars[j]: sympy.S.Zero + for j in range(len(support_vars)) + if vars[i] != support_vars[j] and support_vars[j] != 0 + }, + ) + v = vars[i] + if v == 0: + strides.append(sympy.S.Zero) + else: + # TODO(jansel): should we use sympy.diff here? + strides.append( + sympy_subs(index_dim, {v: sympy.S.One}) + - sympy_subs(index_dim, {v: sympy.S.Zero}) + ) + return strides + + def atomically_apply_size_hint( + self, expr: Union[Expr, int], *, fallback: Optional[int] = None + ) -> Union[Expr, int]: + if isinstance(expr, int): + return int(expr) + + # For multiple expressions that depend on an unbacked symint, + # we want to compute them consistently for a size hint we have chosen. + # So, recursively compute expressions via size hints of contained symbols. + # For example: u1 * u2 - 10 ==> fallback * fallback - 10 + assert isinstance(expr, Expr), type(expr) + free_symbols = expr.free_symbols + size_dict = { + symbol: V.graph.sizevars.size_hint(symbol, fallback=fallback) + for symbol in free_symbols + } + return expr.subs(size_dict) + + def offset_var(self, index: Expr, vars: list[sympy.Symbol]) -> Expr: + """Extract offset part of an indexing expression""" + index = self.simplify(index) + return sympy_subs(index, {v: sympy.S.Zero for v in vars if v != 0}) + + def stride_hints( + self, + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Optional[Sequence[sympy.Symbol]] = None, + ) -> list[int]: + for v in index.free_symbols: + if symbol_is_type(v, SymT.INDIRECT): # type: ignore[attr-defined] + index = sympy_subs(index, {v: 0}) # type: ignore[dict-item] + result = [] + for s in self.stride_vars(index, vars, support_vars): + try: + result.append(self.size_hint(s)) + except TypeError: + result.append(0) + return result + + def stride_order(self, index: Expr, vars: list[sympy.Symbol]) -> list[int]: + strides = tuple(map(abs, self.stride_hints(index, vars))) + order = list(range(len(strides))) + order.sort(key=lambda x: (strides[x] == 0, strides[x])) + return order + + def lookup_precomputed_size(self, expr: Expr) -> Expr: + if ( + isinstance(expr, (int, sympy.Symbol, sympy.Number)) + or expr.is_number + or expr.is_symbol + ): + return expr + expr = self.remove_precomputed_replacements(expr) + if expr not in self.precomputed_replacements: + sym = sympy_index_symbol_with_prefix( + SymT.PRECOMPUTED_SIZE, len(self.precomputed_replacements) + ) + self.precomputed_replacements[expr] = sym + self.inv_precomputed_replacements[sym] = expr + return self.precomputed_replacements[expr] + + def free_symbols(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet(self.var_to_val.keys()) - OrderedSet(self.replacements.keys()) + + def combine_modular_indexing_pairs(self, index: sympy.Expr) -> sympy.Expr: + """ + A pair of special ModularIndexing can be combined. + + E.g. ModularIndexing(ModularIndexing(x, 1, a), 1, b) + We can simplify this to ModuleIndexing(x, 1, b), if + 1. x is non negative integer + 2. a and b are positive integers + 3. a is a multiple of b. + """ + + def _check_args(x, div, mod, is_first): + if not isinstance(div, sympy.Integer) or not isinstance(mod, sympy.Integer): + return False + if div != 1: + return False + if mod <= 0: + return False + + if is_first: + # first ModularIndexing should conatins a nested ModularIndex + if not isinstance(x, ModularIndexing): + return False + else: + # second ModularIndexing should constains a non-negative + # symbol + if not isinstance(x, sympy.Symbol) or not self.statically_known_geq( + x, 0 + ): + return False + return True + + if isinstance(index, ModularIndexing): + x, div, mod = index.args + + if not _check_args(x, div, mod, True): + return index + + x2, div2, mod2 = x.args + + if not _check_args(x2, div2, mod2, False): + return index + + if mod2 % mod != 0: + return index + + return ModularIndexing(x2, 1, mod) + + return index + + def expand_floor_div( + self, index: sympy.Expr + ) -> Union[bool, tuple[sympy.Expr, sympy.Expr]]: + """ + Expand the FloorDiv to the entire expression so that the expression may + be simplfied. + + E.g., for a 2D contiguous tensor with shape [a, 2 * b], and index variables + x1, x2, index expression 'x1 * 2b + x2' can be easily combined. + But index expression 'x1 * b + x2 // 2' can not. + By expanding the FloorDiv to the entire expression, we get + '(x1 * 2b + x2) // 2'. This transformation allows us to merge loops + for the numerator! + + Return false if this optimization can be applied; + Return the new expression and the denominator otherwise. + The original expression will be equivalent to 'new_expression // denominator' + """ + if not isinstance(index, sympy.Add): + return False + terms = index.args + + if len(terms) < 2: + return False + floor_div_index = -1 + varlist = [] + factorlist = [] + for idx, term in enumerate(terms): + if isinstance(term, sympy.Mul): + # For dynamic shape, term like '2*s1*x1' has 3 child nodes. + # - A integer for 2 + # - A symbol for s1 + # - A symbol for x1 + # Skip for now. + if len(term.args) != 2: + return False + factor, var = term.args + varlist.append(var) + factorlist.append(factor) + if not isinstance(factor, sympy.Integer) or not isinstance( + var, sympy.Symbol + ): + return False + # It's easier to reason about the correceness of the transformation + # for non-negative integers. + if not self.statically_known_geq(var, 0): + return False + elif isinstance(term, FloorDiv): + var, factor = term.args + if not isinstance(factor, sympy.Integer) or not isinstance( + var, sympy.Symbol + ): + return False + if not self.statically_known_geq(var, 0): + return False + if floor_div_index >= 0: + # can not handle multi FloorDiv yet + return False + + floor_div_index = idx + varlist.append(var) + # this factor is denominator + factorlist.append(factor) + else: + return False + + if floor_div_index < 0: + return False + + # Construct the new expression and remember the denominator + denominator = factorlist[floor_div_index] + new_index = sympy.S.Zero + + for var, factor, idx in zip(varlist, factorlist, itertools.count()): + if idx == floor_div_index: + new_index += var + else: + new_index += (factor * denominator) * var + + return new_index, denominator + + +def join_dimensions(expr: Expr) -> Expr: + if not isinstance(expr, sympy.Add) or not expr.has(ModularIndexing): + return expr # fast exit path + return _join_dimensions_cached(expr) + + +@functools.lru_cache(256) +def _join_dimensions_cached(expr: Expr) -> Expr: + """ + ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4) + becomes + ModularIndexing(i0, 1, 128) + ModularIndexing(i0, 1, 32) + 32 * FloorDiv(i0, 32) + becomes i0 + + + This type of pattern can come from view operations + """ + assert isinstance(expr, sympy.Add) + + scale = sympy.Wild("scale", exclude=[0], integer=True) + base = sympy.Wild("base", integer=True) + divisor = sympy.Wild("divisor", integer=True) + mod1 = sympy.Wild("modulus", integer=True) + mod2 = sympy.Wild("modulus2", integer=True) + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] + * m1[mod1] + * ModularIndexing(m1[base], m1[divisor] * m1[mod1], mod2) + ) + if m2 and term1 != term2: + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] + * ModularIndexing(m1[base], m1[divisor], m1[mod1] * m2[mod2]) + ) + return expr + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] * m1[mod1] * FloorDiv(m1[base], m1[divisor] * m1[mod1]) + ) + if m2 is not None: # in case of success we get an empty dict here + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] * FloorDiv(m1[base], m1[divisor]) + ) + return expr + return expr + + +class SimplifyIndexing(V.WrapperHandler): # type: ignore[name-defined] + """ + A wrapper around .virtualize.ops that uses var range information to + simplify ModularIndexing/FloorDiv. + """ + + def __init__(self, inner, var_ranges: VarRanges) -> None: + super().__init__(inner) + self.name = "SimplifyIndexing" + self._simplify: Callable[[Expr], Expr] = ( + lambda index: V.graph.sizevars.simplify_with_ranges(index, var_ranges) + ) + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(name, self._simplify(index)) + + def store(self, name, index, value, mode=None): + return self._inner.store(name, self._simplify(index), value, mode=mode) + + def store_reduction(self, name, index, value): + return self._inner.store_reduction(name, self._simplify(index), value) + + def index_expr(self, index, dtype): + return self._inner.index_expr(self._simplify(index), dtype) + + def check_bounds(self, index, size, lower, upper): + return self._inner.check_bounds(self._simplify(index), size, lower, upper) diff --git a/shared/package-files/38/382155eec7241726a6e16b6999a462d38b5ed5845c48ce6e9fe4983b7cb7f299/base_scheduler.cpython-311.pyc b/shared/package-files/38/382155eec7241726a6e16b6999a462d38b5ed5845c48ce6e9fe4983b7cb7f299/base_scheduler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91a5d4ee6ef00e45100406c188d7fbc62018e1e4 Binary files /dev/null and b/shared/package-files/38/382155eec7241726a6e16b6999a462d38b5ed5845c48ce6e9fe4983b7cb7f299/base_scheduler.cpython-311.pyc differ diff --git a/shared/package-files/38/3821fe78f876acc30ceb891ff15ae7c251d9657c5f2ab01094edc160f5b06d94/row_indices_copy.h b/shared/package-files/38/3821fe78f876acc30ceb891ff15ae7c251d9657c5f2ab01094edc160f5b06d94/row_indices_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..bebb568027acb9574083ee68aee4040e8fef7e41 --- /dev/null +++ b/shared/package-files/38/3821fe78f876acc30ceb891ff15ae7c251d9657c5f2ab01094edc160f5b06d94/row_indices_copy.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::row_indices_copy(Tensor self) -> Tensor +inline at::Tensor row_indices_copy(const at::Tensor & self) { + return at::_ops::row_indices_copy::call(self); +} + +// aten::row_indices_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & row_indices_copy_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::row_indices_copy_out::call(self, out); +} +// aten::row_indices_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & row_indices_copy_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::row_indices_copy_out::call(self, out); +} + +} diff --git a/shared/package-files/38/382253f5d126039eba2f8940ccb2418d2d1140251a5d623af3126ef6934d1737/_coalesce_ops.h b/shared/package-files/38/382253f5d126039eba2f8940ccb2418d2d1140251a5d623af3126ef6934d1737/_coalesce_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..825b727a526f2a6bad1c9f70ddb4e997a057c0f7 --- /dev/null +++ b/shared/package-files/38/382253f5d126039eba2f8940ccb2418d2d1140251a5d623af3126ef6934d1737/_coalesce_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _coalesce { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_coalesce"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_coalesce(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API _coalesce_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_coalesce"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_coalesce.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/3825b99b2f04e149fdd658cd6064dd9a5a9472191117584507f6a7847c8db871/test_constructors.cpython-311.pyc b/shared/package-files/38/3825b99b2f04e149fdd658cd6064dd9a5a9472191117584507f6a7847c8db871/test_constructors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44daca2b395a743353901ba0cd7f7d3809337eaa Binary files /dev/null and b/shared/package-files/38/3825b99b2f04e149fdd658cd6064dd9a5a9472191117584507f6a7847c8db871/test_constructors.cpython-311.pyc differ diff --git a/shared/package-files/38/382b240adb396c22a5fd12817bd33be3329222c56978f9f8e12fda269d6d1571/cuda_awbarrier_helpers.h b/shared/package-files/38/382b240adb396c22a5fd12817bd33be3329222c56978f9f8e12fda269d6d1571/cuda_awbarrier_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..7c58346fe78c59329aca138ebc92add9015c005c --- /dev/null +++ b/shared/package-files/38/382b240adb396c22a5fd12817bd33be3329222c56978f9f8e12fda269d6d1571/cuda_awbarrier_helpers.h @@ -0,0 +1,365 @@ +/* + * Copyright 1993-2019 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#ifndef _CUDA_AWBARRIER_HELPERS_H_ +#define _CUDA_AWBARRIER_HELPERS_H_ + +#define _CUDA_AWBARRIER_NAMESPACE nvcuda::experimental +#define _CUDA_AWBARRIER_BEGIN_NAMESPACE namespace nvcuda { namespace experimental { +#define _CUDA_AWBARRIER_END_NAMESPACE } } + +#define _CUDA_AWBARRIER_INTERNAL_NAMESPACE _CUDA_AWBARRIER_NAMESPACE::__awbarrier_internal +#define _CUDA_AWBARRIER_BEGIN_INTERNAL_NAMESPACE _CUDA_AWBARRIER_BEGIN_NAMESPACE namespace __awbarrier_internal { +#define _CUDA_AWBARRIER_END_INTERNAL_NAMESPACE } _CUDA_AWBARRIER_END_NAMESPACE + +# if !defined(_CUDA_AWBARRIER_QUALIFIER) +# define _CUDA_AWBARRIER_QUALIFIER inline __device__ +# endif +# if !defined(_CUDA_AWBARRIER_STATIC_QUALIFIER) +# define _CUDA_AWBARRIER_STATIC_QUALIFIER static inline __device__ +#endif + +#if defined(__CUDA_ARCH__) +#if (__CUDA_ARCH__ >= 900) +# define _CUDA_AWBARRIER_SM_TARGET _CUDA_AWBARRIER_SM_90 +#elif (__CUDA_ARCH__ >= 800) +# define _CUDA_AWBARRIER_SM_TARGET _CUDA_AWBARRIER_SM_80 +#elif (__CUDA_ARCH__ >= 700) +# define _CUDA_AWBARRIER_SM_TARGET _CUDA_AWBARRIER_SM_70 +#endif +#else +# define _CUDA_AWBARRIER_SM_TARGET _CUDA_AWBARRIER_SM_70 +#endif + +#define _CUDA_AWBARRIER_MAX_COUNT ((1 << 14) - 1) + +#if defined(__cplusplus) && ((__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1900))) +# define _CUDA_AWBARRIER_CPLUSPLUS_11_OR_LATER +#endif + +#if !defined(_CUDA_AWBARRIER_DEBUG) +# if defined(__CUDACC_DEBUG__) +# define _CUDA_AWBARRIER_DEBUG 1 +# else +# define _CUDA_AWBARRIER_DEBUG 0 +# endif +#endif + +#if defined(_CUDA_AWBARRIER_DEBUG) && (_CUDA_AWBARRIER_DEBUG == 1) && !defined(NDEBUG) +# if !defined(__CUDACC_RTC__) +# include +# endif +# define _CUDA_AWBARRIER_ASSERT(x) assert((x)); +# define _CUDA_AWBARRIER_ABORT() assert(0); +#else +# define _CUDA_AWBARRIER_ASSERT(x) +# define _CUDA_AWBARRIER_ABORT() __trap(); +#endif + +#if defined(__CUDACC_RTC__) +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +typedef uint64_t uintptr_t; +#else +# include +#endif + +// implicitly provided by NVRTC +#ifndef __CUDACC_RTC__ +#include +#endif /* !defined(__CUDACC_RTC__) */ + +typedef uint64_t __mbarrier_t; +typedef uint64_t __mbarrier_token_t; + +_CUDA_AWBARRIER_BEGIN_INTERNAL_NAMESPACE + +extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *); + +union AWBarrier { + struct { + uint32_t expected; + uint32_t pending; + } split; + uint64_t raw; +}; + +_CUDA_AWBARRIER_STATIC_QUALIFIER +void awbarrier_init(uint64_t* barrier, uint32_t expected_count) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + _CUDA_AWBARRIER_ASSERT(expected_count > 0 && expected_count < (1 << 29)); + + NV_IF_TARGET(NV_PROVIDES_SM_80, + asm volatile ("mbarrier.init.shared.b64 [%0], %1;" + : + : "r"(__nvvm_get_smem_pointer(barrier)), "r"(expected_count) + : "memory"); + return; + ) + NV_IF_TARGET(NV_PROVIDES_SM_70, + AWBarrier* awbarrier = reinterpret_cast(barrier); + + awbarrier->split.expected = 0x40000000 - expected_count; + awbarrier->split.pending = 0x80000000 - expected_count; + return; + ) +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +void awbarrier_inval(uint64_t* barrier) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_80, + asm volatile ("mbarrier.inval.shared.b64 [%0];" + : + : "r"(__nvvm_get_smem_pointer(barrier)) + : "memory"); + return; + ) + return; +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +uint32_t awbarrier_token_pending_count(uint64_t token) { + NV_IF_TARGET(NV_PROVIDES_SM_80, + uint32_t __pending_count; + + asm ("mbarrier.pending_count.b64 %0, %1;" + : "=r"(__pending_count) + : "l"(token)); + return __pending_count; + ) + NV_IF_TARGET(NV_PROVIDES_SM_70, + const uint32_t pending = token >> 32; + return 0x80000000 - (pending & 0x7fffffff); + ) +} + +template +_CUDA_AWBARRIER_STATIC_QUALIFIER +uint64_t awbarrier_arrive_drop(uint64_t* barrier) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_80, + uint64_t token; + + if (_Drop) { + asm volatile ("mbarrier.arrive_drop.shared.b64 %0, [%1];" + : "=l"(token) + : "r"(__nvvm_get_smem_pointer(barrier)) + : "memory"); + } else { + asm volatile ("mbarrier.arrive.shared.b64 %0, [%1];" + : "=l"(token) + : "r"(__nvvm_get_smem_pointer(barrier)) + : "memory"); + } + + return token; + ) + NV_IF_TARGET(NV_PROVIDES_SM_70, + AWBarrier* awbarrier = reinterpret_cast(barrier); + + while ((*reinterpret_cast(&awbarrier->split.pending) & 0x7fffffff) == 0); + + if (_Drop) { + (void)atomicAdd_block(&awbarrier->split.expected, 1); + } + + __threadfence_block(); + + const uint32_t old_pending = atomicAdd_block(&awbarrier->split.pending, 1); + const uint32_t new_pending = old_pending + 1; + const bool reset = (old_pending ^ new_pending) & 0x80000000; + + if (reset) { + __threadfence_block(); + + uint32_t new_expected = *reinterpret_cast(&awbarrier->split.expected); + new_expected &= ~0x40000000; + if (new_expected & 0x20000000) { + new_expected |= 0x40000000; + } + atomicAdd_block(&awbarrier->split.pending, new_expected); + } + + return static_cast(old_pending) << 32; + ) +} + +template +_CUDA_AWBARRIER_STATIC_QUALIFIER +uint64_t awbarrier_arrive_drop_no_complete(uint64_t* barrier, uint32_t count) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + _CUDA_AWBARRIER_ASSERT(count > 0 && count < (1 << 29)); + + NV_IF_TARGET(NV_PROVIDES_SM_80, + uint64_t token; + + if (_Drop) { + asm volatile ("mbarrier.arrive_drop.noComplete.shared.b64 %0, [%1], %2;" + : "=l"(token) + : "r"(__nvvm_get_smem_pointer(barrier)), "r"(count) + : "memory"); + } else { + asm volatile ("mbarrier.arrive.noComplete.shared.b64 %0, [%1], %2;" + : "=l"(token) + : "r"(__nvvm_get_smem_pointer(barrier)), "r"(count) + : "memory"); + } + + return token; + ) + NV_IF_TARGET(NV_PROVIDES_SM_70, + AWBarrier* awbarrier = reinterpret_cast(barrier); + + while ((*reinterpret_cast(&awbarrier->split.pending) & 0x7fffffff) == 0); + + if (_Drop) { + (void)atomicAdd_block(&awbarrier->split.expected, count); + } + + return static_cast(atomicAdd_block(&awbarrier->split.pending, count)) << 32; + ) +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +bool awbarrier_test_wait(uint64_t* barrier, uint64_t token) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_80, + uint32_t __wait_complete; + + asm volatile ("{" + " .reg .pred %%p;" + " mbarrier.test_wait.shared.b64 %%p, [%1], %2;" + " selp.b32 %0, 1, 0, %%p;" + "}" + : "=r"(__wait_complete) + : "r"(__nvvm_get_smem_pointer(barrier)), "l"(token) + : "memory"); + return bool(__wait_complete); + ) + NV_IF_TARGET(NV_PROVIDES_SM_70, + volatile AWBarrier* awbarrier = reinterpret_cast(barrier); + + return ((token >> 32) ^ awbarrier->split.pending) & 0x80000000; + ) +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +bool awbarrier_test_wait_parity(uint64_t* barrier, bool phase_parity) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_90, + uint32_t __wait_complete = 0; + + asm volatile ("{" + ".reg .pred %%p;" + "mbarrier.test_wait.parity.shared.b64 %%p, [%1], %2;" + "selp.b32 %0, 1, 0, %%p;" + "}" + : "=r"(__wait_complete) + : "r"(__nvvm_get_smem_pointer(barrier)), "r"(static_cast(phase_parity)) + : "memory"); + + return __wait_complete; + ) + _CUDA_AWBARRIER_ABORT() + return false; +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +bool awbarrier_try_wait(uint64_t* barrier, uint64_t token, uint32_t max_sleep_nanosec) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_90, + uint32_t __wait_complete = 0; + + asm volatile ("{\n\t" + ".reg .pred p;\n\t" + "mbarrier.try_wait.shared.b64 p, [%1], %2, %3;\n\t" + "selp.b32 %0, 1, 0, p;\n\t" + "}" + : "=r"(__wait_complete) + : "r"(__nvvm_get_smem_pointer(barrier)), "l"(token), "r"(max_sleep_nanosec) + : "memory"); + + return __wait_complete; + ) + _CUDA_AWBARRIER_ABORT() + return false; +} + +_CUDA_AWBARRIER_STATIC_QUALIFIER +bool awbarrier_try_wait_parity(uint64_t* barrier, bool phase_parity, uint32_t max_sleep_nanosec) { + _CUDA_AWBARRIER_ASSERT(__isShared(barrier)); + + NV_IF_TARGET(NV_PROVIDES_SM_90, + uint32_t __wait_complete = 0; + + asm volatile ("{\n\t" + ".reg .pred p;\n\t" + "mbarrier.try_wait.parity.shared.b64 p, [%1], %2, %3;\n\t" + "selp.b32 %0, 1, 0, p;\n\t" + "}" + : "=r"(__wait_complete) + : "r"(__nvvm_get_smem_pointer(barrier)), "r"(static_cast(phase_parity)), "r"(max_sleep_nanosec) + : "memory"); + + return __wait_complete; + ) + _CUDA_AWBARRIER_ABORT() + return false; +} + +_CUDA_AWBARRIER_END_INTERNAL_NAMESPACE + +#endif /* !_CUDA_AWBARRIER_HELPERS_H_ */ diff --git a/shared/package-files/38/3835b730b67ecaf129fdf356307312c3646cf92147ede4cc35987439b4e57f31/misc_patterns.py b/shared/package-files/38/3835b730b67ecaf129fdf356307312c3646cf92147ede4cc35987439b4e57f31/misc_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e0f1f35023dfe96b39e094845a9b5826bcb376 --- /dev/null +++ b/shared/package-files/38/3835b730b67ecaf129fdf356307312c3646cf92147ede4cc35987439b4e57f31/misc_patterns.py @@ -0,0 +1,131 @@ +# mypy: allow-untyped-defs +import functools + +import torch +from torch._dynamo.utils import counters +from torch._ops import OpOverload, OpOverloadPacket +from torch.utils._ordered_set import OrderedSet + +from ..pattern_matcher import fwd_only, register_replacement + + +aten = torch.ops.aten + + +@functools.lru_cache(None) +def _misc_patterns_init(): + from .joint_graph import patterns as joint_graph_patterns + from .post_grad import pass_patterns as post_grad_patterns_all + + post_grad_patterns = post_grad_patterns_all[1] # medium priority + + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + + # These patterns do 2 things + # 1. Since we know that index is completely unique, we can codegen it using + # stores instead of atomic adds, which is quite a bit faster. + # 2. Also, since we are guaranteed that they are completely within bounds, + # we can use unsafe indexing and skip debug asserts + def randperm_index_add_pattern(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return torch.index_add(x, dim=0, source=y, index=index), index + + def randperm_index_add_replacement(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return ( + torch.ops.aten._unsafe_index_put( + x, (index,), aten._unsafe_index(x, (index,)) + y, accumulate=False + ), + index, + ) + + register_replacement( + randperm_index_add_pattern, + randperm_index_add_replacement, + [torch.empty(4, 8, device=device), torch.empty(2, 8, device=device)], + fwd_only, + [post_grad_patterns, joint_graph_patterns], + ) + + def randperm_index_pattern(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten.index(x, (index,)), index + + def randperm_index_replacement(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten._unsafe_index(x, (index,)), index + + register_replacement( + randperm_index_pattern, + randperm_index_replacement, + [torch.empty(4, 8, device=device)], + fwd_only, + [post_grad_patterns, joint_graph_patterns], + scalar_workaround={"slice_shape": 42}, + ) + + +class NumpyCompatNormalization: + numpy_compat: dict[str, tuple[str, ...]] = { + "dim": ("axis",), + "keepdim": ("keepdims",), + "input": ("x", "a", "x1"), + "other": ("x2",), + } + inverse_mapping: dict[str, str] + cache: dict["torch.fx.graph.Target", OrderedSet[str]] + + def __init__(self) -> None: + self.cache = {} # callable -> tuple of replaceable args e.g. ["axis"] + self.inverse_mapping = {} + for actual_kwarg, numpy_kwargs in self.numpy_compat.items(): + for numpy_kwarg in numpy_kwargs: + assert numpy_kwarg not in self.inverse_mapping + self.inverse_mapping[numpy_kwarg] = actual_kwarg + + def __call__(self, graph: torch.fx.Graph): + for node in graph.nodes: + if node.op != "call_function": + continue + if isinstance(node.target, (OpOverload, OpOverloadPacket)): + # only applies to torch ops; e.g. torch.stack(axis=1) works, torch.ops.aten.stack(axis=1) doesn't. + continue + kwargs = node.kwargs + + if node.target in self.cache: + replaceable_kwargs = self.cache[node.target] + else: + signatures = torch.fx.operator_schemas.get_signature_for_torch_op( + node.target + ) + signatures = () if signatures is None else signatures + replaceable_kwargs = OrderedSet() + for sig in signatures: + for param_name in sig.parameters.keys(): + if param_name in self.numpy_compat: + replaceable_kwargs.update(self.numpy_compat[param_name]) + + self.cache[node.target] = replaceable_kwargs + + if not replaceable_kwargs: + continue + + new_kwargs = {} + kwargs_changed = False + for k, v in kwargs.items(): + if k in replaceable_kwargs: + kwargs_changed = True + new_kwargs[self.inverse_mapping[k]] = v + else: + new_kwargs[k] = v + + if kwargs_changed: + node.kwargs = torch.fx.immutable_collections.immutable_dict(new_kwargs) + counters["inductor"]["numpy_compat_normalization"] += 1 + + +numpy_compat_normalization = NumpyCompatNormalization() diff --git a/shared/package-files/38/383abab7dd5f9cd1704ced14d769dc01fc9932a82dd82d34600a9e106754f448/__init__.cpython-311.pyc b/shared/package-files/38/383abab7dd5f9cd1704ced14d769dc01fc9932a82dd82d34600a9e106754f448/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c3476416b16ccb61b6d6c1d145ed5ffe737554 Binary files /dev/null and b/shared/package-files/38/383abab7dd5f9cd1704ced14d769dc01fc9932a82dd82d34600a9e106754f448/__init__.cpython-311.pyc differ diff --git a/shared/package-files/38/383eb92322b75c6601c707cd489327bff7d331d47eb2e744f883eb2beebfd5da/ordinals.cpython-311.pyc b/shared/package-files/38/383eb92322b75c6601c707cd489327bff7d331d47eb2e744f883eb2beebfd5da/ordinals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32fdc099f20fda6070165f2d233e3087e96e4ebc Binary files /dev/null and b/shared/package-files/38/383eb92322b75c6601c707cd489327bff7d331d47eb2e744f883eb2beebfd5da/ordinals.cpython-311.pyc differ diff --git a/shared/package-files/38/384088cc5560cd0d1c843e5386444a46e86c6d92e45cb1fb2477ddebc38035c4/_cycles.cpython-311.pyc b/shared/package-files/38/384088cc5560cd0d1c843e5386444a46e86c6d92e45cb1fb2477ddebc38035c4/_cycles.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63739d7bf267bcde9f7ba09e4cffddfffb9ffb2 Binary files /dev/null and b/shared/package-files/38/384088cc5560cd0d1c843e5386444a46e86c6d92e45cb1fb2477ddebc38035c4/_cycles.cpython-311.pyc differ diff --git a/shared/package-files/38/384a68c8c5fbc5b0973304a93de0692e3fbf459901c78839da2e4a9ae7f4b619/conftest.cpython-311.pyc b/shared/package-files/38/384a68c8c5fbc5b0973304a93de0692e3fbf459901c78839da2e4a9ae7f4b619/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0b3e385b887b5cc7bb157f4ffb1babeef1272fb Binary files /dev/null and b/shared/package-files/38/384a68c8c5fbc5b0973304a93de0692e3fbf459901c78839da2e4a9ae7f4b619/conftest.cpython-311.pyc differ diff --git a/shared/package-files/38/385a1fd5e8688f1f79e0fdfea8c27d7ca6dd78a770f0bd9a438863628a7589fb/base_futures.py b/shared/package-files/38/385a1fd5e8688f1f79e0fdfea8c27d7ca6dd78a770f0bd9a438863628a7589fb/base_futures.py new file mode 100644 index 0000000000000000000000000000000000000000..cd811a788cb6df2601b35b5b5b1d069e6b39100f --- /dev/null +++ b/shared/package-files/38/385a1fd5e8688f1f79e0fdfea8c27d7ca6dd78a770f0bd9a438863628a7589fb/base_futures.py @@ -0,0 +1,68 @@ +__all__ = () + +import reprlib +from _thread import get_ident + +from . import format_helpers + +# States for Future. +_PENDING = 'PENDING' +_CANCELLED = 'CANCELLED' +_FINISHED = 'FINISHED' + + +def isfuture(obj): + """Check for a Future. + + This returns True when obj is a Future instance or is advertising + itself as duck-type compatible by setting _asyncio_future_blocking. + See comment in Future for more details. + """ + return (hasattr(obj.__class__, '_asyncio_future_blocking') and + obj._asyncio_future_blocking is not None) + + +def _format_callbacks(cb): + """helper function for Future.__repr__""" + size = len(cb) + if not size: + cb = '' + + def format_cb(callback): + return format_helpers._format_callback_source(callback, ()) + + if size == 1: + cb = format_cb(cb[0][0]) + elif size == 2: + cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0])) + elif size > 2: + cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]), + size - 2, + format_cb(cb[-1][0])) + return f'cb=[{cb}]' + + +def _future_repr_info(future): + # (Future) -> str + """helper function for Future.__repr__""" + info = [future._state.lower()] + if future._state == _FINISHED: + if future._exception is not None: + info.append(f'exception={future._exception!r}') + else: + # use reprlib to limit the length of the output, especially + # for very long strings + result = reprlib.repr(future._result) + info.append(f'result={result}') + if future._callbacks: + info.append(_format_callbacks(future._callbacks)) + if future._source_traceback: + frame = future._source_traceback[-1] + info.append(f'created at {frame[0]}:{frame[1]}') + return info + + +@reprlib.recursive_repr() +def _future_repr(future): + info = ' '.join(_future_repr_info(future)) + return f'<{future.__class__.__name__} {info}>' diff --git a/shared/package-files/38/385d11ac0bc3fac0c9b1533980bffdc659622ca6870ce1b72093a4eaa6f0d4bc/positive.h b/shared/package-files/38/385d11ac0bc3fac0c9b1533980bffdc659622ca6870ce1b72093a4eaa6f0d4bc/positive.h new file mode 100644 index 0000000000000000000000000000000000000000..4bd5cf2d143c7cb98a8c7ecf0b9aa50059613288 --- /dev/null +++ b/shared/package-files/38/385d11ac0bc3fac0c9b1533980bffdc659622ca6870ce1b72093a4eaa6f0d4bc/positive.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::positive(Tensor(a) self) -> Tensor(a) +inline at::Tensor positive(const at::Tensor & self) { + return at::_ops::positive::call(self); +} + +} diff --git a/shared/package-files/38/385ef814559b6aaf036b6d95186acc025f7c9ad1c4892cd4ddf9826cfd8ed76b/_native_multi_head_attention_cpu_dispatch.h b/shared/package-files/38/385ef814559b6aaf036b6d95186acc025f7c9ad1c4892cd4ddf9826cfd8ed76b/_native_multi_head_attention_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7995360ae249d850d4c5ec25b39b6f6edbff61b0 --- /dev/null +++ b/shared/package-files/38/385ef814559b6aaf036b6d95186acc025f7c9ad1c4892cd4ddf9826cfd8ed76b/_native_multi_head_attention_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple _native_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, ::std::optional mask_type=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/38/38610a2aea4699dec8da4a820410a2692fcdf68fe836366c22d209a43aa4c06f/_addmm_activation_ops.h b/shared/package-files/38/38610a2aea4699dec8da4a820410a2692fcdf68fe836366c22d209a43aa4c06f/_addmm_activation_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..21c7648b5cc90061ce27a6ea8aab32b533ab417b --- /dev/null +++ b/shared/package-files/38/38610a2aea4699dec8da4a820410a2692fcdf68fe836366c22d209a43aa4c06f/_addmm_activation_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _addmm_activation_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_addmm_activation"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu, at::Tensor & out); +}; + +struct TORCH_API _addmm_activation { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_addmm_activation"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/3861d99363ecd6c85ebdc253ef9e2bd4d0f54a870476136eea81276547cc1aa1/duplicate_dq_pass.cpython-311.pyc b/shared/package-files/38/3861d99363ecd6c85ebdc253ef9e2bd4d0f54a870476136eea81276547cc1aa1/duplicate_dq_pass.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d3c0d21ed475747b5a4d1ef32eed207c485563 Binary files /dev/null and b/shared/package-files/38/3861d99363ecd6c85ebdc253ef9e2bd4d0f54a870476136eea81276547cc1aa1/duplicate_dq_pass.cpython-311.pyc differ diff --git a/shared/package-files/38/3862ed1e5b38dbc4500343dfb69e5cb0b8c99e17762670ec4cef81c4cebac6f0/special_log_softmax_compositeimplicitautograd_dispatch.h b/shared/package-files/38/3862ed1e5b38dbc4500343dfb69e5cb0b8c99e17762670ec4cef81c4cebac6f0/special_log_softmax_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..489ce4cd366b6236c64dfe5ab961b68bb11789be --- /dev/null +++ b/shared/package-files/38/3862ed1e5b38dbc4500343dfb69e5cb0b8c99e17762670ec4cef81c4cebac6f0/special_log_softmax_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor special_log_softmax(const at::Tensor & self, int64_t dim, ::std::optional dtype=::std::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/38/38636a460003e33e44b7027dd04dd2c7bb37f6e80ff7cbb1e2fe3e7c9d531d02/test_modules.cpython-311.pyc b/shared/package-files/38/38636a460003e33e44b7027dd04dd2c7bb37f6e80ff7cbb1e2fe3e7c9d531d02/test_modules.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef4df6cd669a9f658f7a50d699614977609a2af5 Binary files /dev/null and b/shared/package-files/38/38636a460003e33e44b7027dd04dd2c7bb37f6e80ff7cbb1e2fe3e7c9d531d02/test_modules.cpython-311.pyc differ diff --git a/shared/package-files/38/386454857a12498d6e0143f65546f8e5e46578e0ae1d372ddf045755276fa51f/test_compression.py b/shared/package-files/38/386454857a12498d6e0143f65546f8e5e46578e0ae1d372ddf045755276fa51f/test_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58dda9e8dc47f2072e0175c120036523ed83f7 --- /dev/null +++ b/shared/package-files/38/386454857a12498d6e0143f65546f8e5e46578e0ae1d372ddf045755276fa51f/test_compression.py @@ -0,0 +1,378 @@ +import gzip +import io +import os +from pathlib import Path +import subprocess +import sys +import tarfile +import textwrap +import time +import zipfile + +import numpy as np +import pytest + +from pandas.compat import is_platform_windows + +import pandas as pd +import pandas._testing as tm + +import pandas.io.common as icom + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_compression_size(obj, method, compression_only): + if compression_only == "tar": + compression_only = {"method": "tar", "mode": "w:gz"} + + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression=compression_only) + compressed_size = os.path.getsize(path) + getattr(obj, method)(path, compression=None) + uncompressed_size = os.path.getsize(path) + assert uncompressed_size > compressed_size + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_csv", "to_json"]) +def test_compression_size_fh(obj, method, compression_only): + with tm.ensure_clean() as path: + with icom.get_handle( + path, + "w:gz" if compression_only == "tar" else "w", + compression=compression_only, + ) as handles: + getattr(obj, method)(handles.handle) + assert not handles.handle.closed + compressed_size = os.path.getsize(path) + with tm.ensure_clean() as path: + with icom.get_handle(path, "w", compression=None) as handles: + getattr(obj, method)(handles.handle) + assert not handles.handle.closed + uncompressed_size = os.path.getsize(path) + assert uncompressed_size > compressed_size + + +@pytest.mark.parametrize( + "write_method, write_kwargs, read_method", + [ + ("to_csv", {"index": False}, pd.read_csv), + ("to_json", {}, pd.read_json), + ("to_pickle", {}, pd.read_pickle), + ], +) +def test_dataframe_compression_defaults_to_infer( + write_method, write_kwargs, read_method, compression_only, compression_to_extension +): + # GH22004 + input = pd.DataFrame([[1.0, 0, -4], [3.4, 5, 2]], columns=["X", "Y", "Z"]) + extension = compression_to_extension[compression_only] + with tm.ensure_clean("compressed" + extension) as path: + getattr(input, write_method)(path, **write_kwargs) + output = read_method(path, compression=compression_only) + tm.assert_frame_equal(output, input) + + +@pytest.mark.parametrize( + "write_method,write_kwargs,read_method,read_kwargs", + [ + ("to_csv", {"index": False, "header": True}, pd.read_csv, {"squeeze": True}), + ("to_json", {}, pd.read_json, {"typ": "series"}), + ("to_pickle", {}, pd.read_pickle, {}), + ], +) +def test_series_compression_defaults_to_infer( + write_method, + write_kwargs, + read_method, + read_kwargs, + compression_only, + compression_to_extension, +): + # GH22004 + input = pd.Series([0, 5, -2, 10], name="X") + extension = compression_to_extension[compression_only] + with tm.ensure_clean("compressed" + extension) as path: + getattr(input, write_method)(path, **write_kwargs) + if "squeeze" in read_kwargs: + kwargs = read_kwargs.copy() + del kwargs["squeeze"] + output = read_method(path, compression=compression_only, **kwargs).squeeze( + "columns" + ) + else: + output = read_method(path, compression=compression_only, **read_kwargs) + tm.assert_series_equal(output, input, check_names=False) + + +def test_compression_warning(compression_only): + # Assert that passing a file object to to_csv while explicitly specifying a + # compression protocol triggers a RuntimeWarning, as per GH21227. + df = pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ) + with tm.ensure_clean() as path: + with icom.get_handle(path, "w", compression=compression_only) as handles: + with tm.assert_produces_warning(RuntimeWarning): + df.to_csv(handles.handle, compression=compression_only) + + +def test_compression_binary(compression_only): + """ + Binary file handles support compression. + + GH22555 + """ + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + # with a file + with tm.ensure_clean() as path: + with open(path, mode="wb") as file: + df.to_csv(file, mode="wb", compression=compression_only) + file.seek(0) # file shouldn't be closed + tm.assert_frame_equal( + df, pd.read_csv(path, index_col=0, compression=compression_only) + ) + + # with BytesIO + file = io.BytesIO() + df.to_csv(file, mode="wb", compression=compression_only) + file.seek(0) # file shouldn't be closed + tm.assert_frame_equal( + df, pd.read_csv(file, index_col=0, compression=compression_only) + ) + + +def test_gzip_reproducibility_file_name(): + """ + Gzip should create reproducible archives with mtime. + + Note: Archives created with different filenames will still be different! + + GH 28103 + """ + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) + compression_options = {"method": "gzip", "mtime": 1} + + # test for filename + with tm.ensure_clean() as path: + path = Path(path) + df.to_csv(path, compression=compression_options) + time.sleep(0.1) + output = path.read_bytes() + df.to_csv(path, compression=compression_options) + assert output == path.read_bytes() + + +def test_gzip_reproducibility_file_object(): + """ + Gzip should create reproducible archives with mtime. + + GH 28103 + """ + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) + compression_options = {"method": "gzip", "mtime": 1} + + # test for file object + buffer = io.BytesIO() + df.to_csv(buffer, compression=compression_options, mode="wb") + output = buffer.getvalue() + time.sleep(0.1) + buffer = io.BytesIO() + df.to_csv(buffer, compression=compression_options, mode="wb") + assert output == buffer.getvalue() + + +@pytest.mark.single_cpu +def test_with_missing_lzma(): + """Tests if import pandas works when lzma is not present.""" + # https://github.com/pandas-dev/pandas/issues/27575 + code = textwrap.dedent( + """\ + import sys + sys.modules['lzma'] = None + import pandas + """ + ) + subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE) + + +@pytest.mark.single_cpu +def test_with_missing_lzma_runtime(): + """Tests if RuntimeError is hit when calling lzma without + having the module available. + """ + code = textwrap.dedent( + """ + import sys + import pytest + sys.modules['lzma'] = None + import pandas as pd + df = pd.DataFrame() + with pytest.raises(RuntimeError, match='lzma module'): + df.to_csv('foo.csv', compression='xz') + """ + ) + subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE) + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_gzip_compression_level(obj, method): + # GH33196 + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression="gzip") + compressed_size_default = os.path.getsize(path) + getattr(obj, method)(path, compression={"method": "gzip", "compresslevel": 1}) + compressed_size_fast = os.path.getsize(path) + assert compressed_size_default < compressed_size_fast + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_xz_compression_level_read(obj, method): + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression="xz") + compressed_size_default = os.path.getsize(path) + getattr(obj, method)(path, compression={"method": "xz", "preset": 1}) + compressed_size_fast = os.path.getsize(path) + assert compressed_size_default < compressed_size_fast + if method == "to_csv": + pd.read_csv(path, compression="xz") + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_bzip_compression_level(obj, method): + """GH33196 bzip needs file size > 100k to show a size difference between + compression levels, so here we just check if the call works when + compression is passed as a dict. + """ + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression={"method": "bz2", "compresslevel": 1}) + + +@pytest.mark.parametrize( + "suffix,archive", + [ + (".zip", zipfile.ZipFile), + (".tar", tarfile.TarFile), + ], +) +def test_empty_archive_zip(suffix, archive): + with tm.ensure_clean(filename=suffix) as path: + with archive(path, "w"): + pass + with pytest.raises(ValueError, match="Zero files found"): + pd.read_csv(path) + + +def test_ambiguous_archive_zip(): + with tm.ensure_clean(filename=".zip") as path: + with zipfile.ZipFile(path, "w") as file: + file.writestr("a.csv", "foo,bar") + file.writestr("b.csv", "foo,bar") + with pytest.raises(ValueError, match="Multiple files found in ZIP file"): + pd.read_csv(path) + + +def test_ambiguous_archive_tar(tmp_path): + csvAPath = tmp_path / "a.csv" + with open(csvAPath, "w", encoding="utf-8") as a: + a.write("foo,bar\n") + csvBPath = tmp_path / "b.csv" + with open(csvBPath, "w", encoding="utf-8") as b: + b.write("foo,bar\n") + + tarpath = tmp_path / "archive.tar" + with tarfile.TarFile(tarpath, "w") as tar: + tar.add(csvAPath, "a.csv") + tar.add(csvBPath, "b.csv") + + with pytest.raises(ValueError, match="Multiple files found in TAR archive"): + pd.read_csv(tarpath) + + +def test_tar_gz_to_different_filename(): + with tm.ensure_clean(filename=".foo") as file: + pd.DataFrame( + [["1", "2"]], + columns=["foo", "bar"], + ).to_csv(file, compression={"method": "tar", "mode": "w:gz"}, index=False) + with gzip.open(file) as uncompressed: + with tarfile.TarFile(fileobj=uncompressed) as archive: + members = archive.getmembers() + assert len(members) == 1 + content = archive.extractfile(members[0]).read().decode("utf8") + + if is_platform_windows(): + expected = "foo,bar\r\n1,2\r\n" + else: + expected = "foo,bar\n1,2\n" + + assert content == expected + + +def test_tar_no_error_on_close(): + with io.BytesIO() as buffer: + with icom._BytesTarFile(fileobj=buffer, mode="w"): + pass diff --git a/shared/package-files/38/3868d42798cf32b98c30698c5cbf4c39972728524d9b94952c7c775b032a7ee1/fbgemm_linear_int8_weight.h b/shared/package-files/38/3868d42798cf32b98c30698c5cbf4c39972728524d9b94952c7c775b032a7ee1/fbgemm_linear_int8_weight.h new file mode 100644 index 0000000000000000000000000000000000000000..aff69fd09f64cfcc1a43acadf96fc2cf4cec0789 --- /dev/null +++ b/shared/package-files/38/3868d42798cf32b98c30698c5cbf4c39972728524d9b94952c7c775b032a7ee1/fbgemm_linear_int8_weight.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::fbgemm_linear_int8_weight(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor +inline at::Tensor fbgemm_linear_int8_weight(const at::Tensor & input, const at::Tensor & weight, const at::Tensor & packed, const at::Tensor & col_offsets, const at::Scalar & weight_scale, const at::Scalar & weight_zero_point, const at::Tensor & bias) { + return at::_ops::fbgemm_linear_int8_weight::call(input, weight, packed, col_offsets, weight_scale, weight_zero_point, bias); +} + +} diff --git a/shared/package-files/38/386a066ad512f69361076f84a6286f0f52a6c7ae28997fe4a54fd4aaaf68bd8d/log1p_ops.h b/shared/package-files/38/386a066ad512f69361076f84a6286f0f52a6c7ae28997fe4a54fd4aaaf68bd8d/log1p_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b05aaa10eb24cd19f4467d376705e7b90ddd9287 --- /dev/null +++ b/shared/package-files/38/386a066ad512f69361076f84a6286f0f52a6c7ae28997fe4a54fd4aaaf68bd8d/log1p_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API log1p { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log1p"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log1p(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API log1p_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log1p_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log1p_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API log1p_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log1p"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/386f2aa5b00fa4143d9a0b00a599805b284db7f5c9d328df9db6a72b8cb30997/base_hop.cpython-311.pyc b/shared/package-files/38/386f2aa5b00fa4143d9a0b00a599805b284db7f5c9d328df9db6a72b8cb30997/base_hop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..279361af253aa5e76f1a04317098bc271e5d67cb Binary files /dev/null and b/shared/package-files/38/386f2aa5b00fa4143d9a0b00a599805b284db7f5c9d328df9db6a72b8cb30997/base_hop.cpython-311.pyc differ diff --git a/shared/package-files/38/386f918fcb40a6e102fceadba1630ebbc53412b5237751e9efc4857c47f5add9/linalg_lu_factor.h b/shared/package-files/38/386f918fcb40a6e102fceadba1630ebbc53412b5237751e9efc4857c47f5add9/linalg_lu_factor.h new file mode 100644 index 0000000000000000000000000000000000000000..1b4ddfb56427e7b856f1abbd2d04eeeb683b3de8 --- /dev/null +++ b/shared/package-files/38/386f918fcb40a6e102fceadba1630ebbc53412b5237751e9efc4857c47f5add9/linalg_lu_factor.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots) +inline ::std::tuple linalg_lu_factor(const at::Tensor & A, bool pivot=true) { + return at::_ops::linalg_lu_factor::call(A, pivot); +} + +// aten::linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots) +inline ::std::tuple linalg_lu_factor_out(at::Tensor & LU, at::Tensor & pivots, const at::Tensor & A, bool pivot=true) { + return at::_ops::linalg_lu_factor_out::call(A, pivot, LU, pivots); +} +// aten::linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots) +inline ::std::tuple linalg_lu_factor_outf(const at::Tensor & A, bool pivot, at::Tensor & LU, at::Tensor & pivots) { + return at::_ops::linalg_lu_factor_out::call(A, pivot, LU, pivots); +} + +} diff --git a/shared/package-files/38/3873811f0c81638aaf6ba750b0ebac911f34bec3b0d0e741a2c884ed45968e74/conv2d.h b/shared/package-files/38/3873811f0c81638aaf6ba750b0ebac911f34bec3b0d0e741a2c884ed45968e74/conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..9aa328d98b6db8cc567fcb84c32a5d768e8befb0 --- /dev/null +++ b/shared/package-files/38/3873811f0c81638aaf6ba750b0ebac911f34bec3b0d0e741a2c884ed45968e74/conv2d.h @@ -0,0 +1,101 @@ +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +// An API to compute 2D depthwise convolutions with bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + int stride, + int pad, + int groups); + +// An API to compute 2D depthwise convolutions without bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + int stride, + int pad, + int groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +bool conv2dIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const TensorInfo& bias, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +bool mkldnnPrepackedConvIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +Tensor computeConv2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedConv2dClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedLinearClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeMkldnnPrepackedConvRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +} // namespace torch::jit::tensorexpr diff --git a/shared/package-files/38/3876d873aefca6a0316fdbb5d1ea815e4b0cca15ad3e235a3c373c100dc29cc7/bench_special.cpython-311.pyc b/shared/package-files/38/3876d873aefca6a0316fdbb5d1ea815e4b0cca15ad3e235a3c373c100dc29cc7/bench_special.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2480933eb6e36d7c0ffc80c41f35ed9ec1d68c25 Binary files /dev/null and b/shared/package-files/38/3876d873aefca6a0316fdbb5d1ea815e4b0cca15ad3e235a3c373c100dc29cc7/bench_special.cpython-311.pyc differ diff --git a/shared/package-files/38/387a1a95c12722eaa218dd144719da80f5e382e53afac4408de12e70dd9b6e80/test_put.py b/shared/package-files/38/387a1a95c12722eaa218dd144719da80f5e382e53afac4408de12e70dd9b6e80/test_put.py new file mode 100644 index 0000000000000000000000000000000000000000..bc5f046b7fa3308e30959953f8751056de941a32 --- /dev/null +++ b/shared/package-files/38/387a1a95c12722eaa218dd144719da80f5e382e53afac4408de12e70dd9b6e80/test_put.py @@ -0,0 +1,374 @@ +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +import pandas as pd +from pandas import ( + DataFrame, + HDFStore, + Index, + MultiIndex, + Series, + _testing as tm, + concat, + date_range, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_store, +) +from pandas.util import _test_decorators as td + +pytestmark = pytest.mark.single_cpu + + +def test_format_type(tmp_path, setup_path): + df = DataFrame({"A": [1, 2]}) + with HDFStore(tmp_path / setup_path) as store: + store.put("a", df, format="fixed") + store.put("b", df, format="table") + + assert store.get_storer("a").format_type == "fixed" + assert store.get_storer("b").format_type == "table" + + +def test_format_kwarg_in_constructor(tmp_path, setup_path): + # GH 13291 + + msg = "format is not a defined argument for HDFStore" + + with pytest.raises(ValueError, match=msg): + HDFStore(tmp_path / setup_path, format="table") + + +def test_api_default_format(tmp_path, setup_path): + # default_format option + with ensure_clean_store(setup_path) as store: + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + with pd.option_context("io.hdf.default_format", "fixed"): + _maybe_remove(store, "df") + store.put("df", df) + assert not store.get_storer("df").is_table + + msg = "Can only append to Tables" + with pytest.raises(ValueError, match=msg): + store.append("df2", df) + + with pd.option_context("io.hdf.default_format", "table"): + _maybe_remove(store, "df") + store.put("df", df) + assert store.get_storer("df").is_table + + _maybe_remove(store, "df2") + store.append("df2", df) + assert store.get_storer("df").is_table + + path = tmp_path / setup_path + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + with pd.option_context("io.hdf.default_format", "fixed"): + df.to_hdf(path, key="df") + with HDFStore(path) as store: + assert not store.get_storer("df").is_table + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, key="df2", append=True) + + with pd.option_context("io.hdf.default_format", "table"): + df.to_hdf(path, key="df3") + with HDFStore(path) as store: + assert store.get_storer("df3").is_table + df.to_hdf(path, key="df4", append=True) + with HDFStore(path) as store: + assert store.get_storer("df4").is_table + + +def test_put(setup_path): + with ensure_clean_store(setup_path) as store: + ts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + df = DataFrame( + np.random.default_rng(2).standard_normal((20, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=20, freq="B"), + ) + store["a"] = ts + store["b"] = df[:10] + store["foo/bar/bah"] = df[:10] + store["foo"] = df[:10] + store["/foo"] = df[:10] + store.put("c", df[:10], format="table") + + # not OK, not a table + msg = "Can only append to Tables" + with pytest.raises(ValueError, match=msg): + store.put("b", df[10:], append=True) + + # node does not currently exist, test _is_table_type returns False + # in this case + _maybe_remove(store, "f") + with pytest.raises(ValueError, match=msg): + store.put("f", df[10:], append=True) + + # can't put to a table (use append instead) + with pytest.raises(ValueError, match=msg): + store.put("c", df[10:], append=True) + + # overwrite table + store.put("c", df[:10], format="table", append=False) + tm.assert_frame_equal(df[:10], store["c"]) + + +def test_put_string_index(setup_path): + with ensure_clean_store(setup_path) as store: + index = Index([f"I am a very long string index: {i}" for i in range(20)]) + s = Series(np.arange(20), index=index) + df = DataFrame({"A": s, "B": s}) + + store["a"] = s + tm.assert_series_equal(store["a"], s) + + store["b"] = df + tm.assert_frame_equal(store["b"], df) + + # mixed length + index = Index( + ["abcdefghijklmnopqrstuvwxyz1234567890"] + + [f"I am a very long string index: {i}" for i in range(20)] + ) + s = Series(np.arange(21), index=index) + df = DataFrame({"A": s, "B": s}) + store["a"] = s + tm.assert_series_equal(store["a"], s) + + store["b"] = df + tm.assert_frame_equal(store["b"], df) + + +def test_put_compression(setup_path): + with ensure_clean_store(setup_path) as store: + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + + store.put("c", df, format="table", complib="zlib") + tm.assert_frame_equal(store["c"], df) + + # can't compress if format='fixed' + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): + store.put("b", df, format="fixed", complib="zlib") + + +@td.skip_if_windows +def test_put_compression_blosc(setup_path): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + + with ensure_clean_store(setup_path) as store: + # can't compress if format='fixed' + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): + store.put("b", df, format="fixed", complib="blosc") + + store.put("c", df, format="table", complib="blosc") + tm.assert_frame_equal(store["c"], df) + + +def test_put_mixed_type(setup_path): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df["obj1"] = "foo" + df["obj2"] = "bar" + df["bool1"] = df["A"] > 0 + df["bool2"] = df["B"] > 0 + df["bool3"] = True + df["int1"] = 1 + df["int2"] = 2 + df["timestamp1"] = Timestamp("20010102").as_unit("ns") + df["timestamp2"] = Timestamp("20010103").as_unit("ns") + df["datetime1"] = Timestamp("20010102").as_unit("ns") + df["datetime2"] = Timestamp("20010103").as_unit("ns") + df.loc[df.index[3:6], ["obj1"]] = np.nan + df = df._consolidate() + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "df") + + with tm.assert_produces_warning(pd.errors.PerformanceWarning): + store.put("df", df) + + expected = store.get("df") + tm.assert_frame_equal(expected, df) + + +@pytest.mark.parametrize("format", ["table", "fixed"]) +@pytest.mark.parametrize( + "index", + [ + Index([str(i) for i in range(10)]), + Index(np.arange(10, dtype=float)), + Index(np.arange(10)), + date_range("2020-01-01", periods=10), + pd.period_range("2020-01-01", periods=10), + ], +) +def test_store_index_types(setup_path, format, index): + # GH5386 + # test storing various index types + + with ensure_clean_store(setup_path) as store: + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 2)), + columns=list("AB"), + index=index, + ) + _maybe_remove(store, "df") + store.put("df", df, format=format) + tm.assert_frame_equal(df, store["df"]) + + +def test_column_multiindex(setup_path): + # GH 4710 + # recreate multi-indexes properly + + index = MultiIndex.from_tuples( + [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")], names=["first", "second"] + ) + df = DataFrame(np.arange(12).reshape(3, 4), columns=index) + expected = df.set_axis(df.index.to_numpy()) + + with ensure_clean_store(setup_path) as store: + store.put("df", df) + tm.assert_frame_equal( + store["df"], expected, check_index_type=True, check_column_type=True + ) + + store.put("df1", df, format="table") + tm.assert_frame_equal( + store["df1"], expected, check_index_type=True, check_column_type=True + ) + + msg = re.escape("cannot use a multi-index on axis [1] with data_columns ['A']") + with pytest.raises(ValueError, match=msg): + store.put("df2", df, format="table", data_columns=["A"]) + msg = re.escape("cannot use a multi-index on axis [1] with data_columns True") + with pytest.raises(ValueError, match=msg): + store.put("df3", df, format="table", data_columns=True) + + # appending multi-column on existing table (see GH 6167) + with ensure_clean_store(setup_path) as store: + store.append("df2", df) + store.append("df2", df) + + tm.assert_frame_equal(store["df2"], concat((df, df))) + + # non_index_axes name + df = DataFrame(np.arange(12).reshape(3, 4), columns=Index(list("ABCD"), name="foo")) + expected = df.set_axis(df.index.to_numpy()) + + with ensure_clean_store(setup_path) as store: + store.put("df1", df, format="table") + tm.assert_frame_equal( + store["df1"], expected, check_index_type=True, check_column_type=True + ) + + +def test_store_multiindex(setup_path): + # validate multi-index names + # GH 5527 + with ensure_clean_store(setup_path) as store: + + def make_index(names=None): + dti = date_range("2013-12-01", "2013-12-02") + mi = MultiIndex.from_product([dti, range(2), range(3)], names=names) + return mi + + # no names + _maybe_remove(store, "df") + df = DataFrame(np.zeros((12, 2)), columns=["a", "b"], index=make_index()) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + + # partial names + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", None, None]), + ) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + + # series + _maybe_remove(store, "ser") + ser = Series(np.zeros(12), index=make_index(["date", None, None])) + store.append("ser", ser) + xp = Series(np.zeros(12), index=make_index(["date", "level_1", "level_2"])) + tm.assert_series_equal(store.select("ser"), xp) + + # dup with column + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "a", "t"]), + ) + msg = "duplicate names/columns in the multi-index when storing as a table" + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # dup within level + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "date", "date"]), + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # fully names + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "s", "t"]), + ) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + + +@pytest.mark.parametrize("format", ["fixed", "table"]) +def test_store_periodindex(tmp_path, setup_path, format): + # GH 7796 + # test of PeriodIndex in HDFStore + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 1)), + index=pd.period_range("20220101", freq="M", periods=5), + ) + + path = tmp_path / setup_path + df.to_hdf(path, key="df", mode="w", format=format) + expected = pd.read_hdf(path, "df") + tm.assert_frame_equal(df, expected) diff --git a/shared/package-files/38/387ca853b648d506e3a827a8c74f60b0504e852c4e2bb3ea506be042e46e53e8/symbolic_opset11.cpython-311.pyc b/shared/package-files/38/387ca853b648d506e3a827a8c74f60b0504e852c4e2bb3ea506be042e46e53e8/symbolic_opset11.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e431add7f1e7998d8bcb79fd9452cb30d25a838 Binary files /dev/null and b/shared/package-files/38/387ca853b648d506e3a827a8c74f60b0504e852c4e2bb3ea506be042e46e53e8/symbolic_opset11.cpython-311.pyc differ diff --git a/shared/package-files/38/387ec6edda5154c656ae47f0a5c63b8e016b5d1c099800e07d1e134595f90975/version.sh b/shared/package-files/38/387ec6edda5154c656ae47f0a5c63b8e016b5d1c099800e07d1e134595f90975/version.sh new file mode 100644 index 0000000000000000000000000000000000000000..007c916a2db004f82333b00dbb7d6c0fc10e506a --- /dev/null +++ b/shared/package-files/38/387ec6edda5154c656ae47f0a5c63b8e016b5d1c099800e07d1e134595f90975/version.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# version.sh +# +# Author : Petr Danecek +# +# Copyright (C) 2018-2021 Genome Research Ltd. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +# Master version, for use in tarballs or non-git source copies +VERSION=1.21 + +# If we have a git clone, then check against the current tag +if [ -e .git ] +then + # If we ever get to 10.x this will need to be more liberal + VERSION=`git describe --match '[0-9].[0-9]*' --dirty --always` +fi + +echo $VERSION diff --git a/shared/package-files/38/3880c75b843832377f63f791d545832ee3ce544209389263e4c6db69045d2350/__init__.py b/shared/package-files/38/3880c75b843832377f63f791d545832ee3ce544209389263e4c6db69045d2350/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18534bbc588e7480ac6529c6648c5976eadaea3a --- /dev/null +++ b/shared/package-files/38/3880c75b843832377f63f791d545832ee3ce544209389263e4c6db69045d2350/__init__.py @@ -0,0 +1,32 @@ +from .conv_fused import ( + ConvBn1d, + ConvBn2d, + ConvBn3d, + ConvBnReLU1d, + ConvBnReLU2d, + ConvBnReLU3d, + ConvReLU1d, + ConvReLU2d, + ConvReLU3d, + freeze_bn_stats, + update_bn_stats, +) +from .linear_fused import LinearBn1d +from .linear_relu import LinearReLU + + +__all__ = [ + "LinearReLU", + "LinearBn1d", + "ConvReLU1d", + "ConvReLU2d", + "ConvReLU3d", + "ConvBn1d", + "ConvBn2d", + "ConvBn3d", + "ConvBnReLU1d", + "ConvBnReLU2d", + "ConvBnReLU3d", + "update_bn_stats", + "freeze_bn_stats", +] diff --git a/shared/package-files/38/38811062a5f9770357b10ec69ae79c17f319b6b332c12ac3c6997c87072a306b/special_scaled_modified_bessel_k1_meta.h b/shared/package-files/38/38811062a5f9770357b10ec69ae79c17f319b6b332c12ac3c6997c87072a306b/special_scaled_modified_bessel_k1_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..9c2b3c888900c60eef5e14396aa6cad9fd9a4c2b --- /dev/null +++ b/shared/package-files/38/38811062a5f9770357b10ec69ae79c17f319b6b332c12ac3c6997c87072a306b/special_scaled_modified_bessel_k1_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_scaled_modified_bessel_k1 : public TensorIteratorBase { + + + void meta(const at::Tensor & x); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/38/388304a64c8721c2721b8d9f8561ab29f07c59e255bd40d3538c891d7599217c/test_versionpredicate.py b/shared/package-files/38/388304a64c8721c2721b8d9f8561ab29f07c59e255bd40d3538c891d7599217c/test_versionpredicate.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e9ab2cf59b59523db8956e573953e32bd171cf --- /dev/null +++ b/shared/package-files/38/388304a64c8721c2721b8d9f8561ab29f07c59e255bd40d3538c891d7599217c/test_versionpredicate.py @@ -0,0 +1,13 @@ +"""Tests harness for distutils.versionpredicate. + +""" + +import distutils.versionpredicate +import doctest + +def load_tests(loader, tests, pattern): + tests.addTest(doctest.DocTestSuite(distutils.versionpredicate)) + return tests + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/38/38842f7e50557c754fb06b00ad6378ea15576592d447d27be8977978ddd8cf69/_native_batch_norm_legit_ops.h b/shared/package-files/38/38842f7e50557c754fb06b00ad6378ea15576592d447d27be8977978ddd8cf69/_native_batch_norm_legit_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b311c62b0811053846f676f2f002076e22fc68d3 --- /dev/null +++ b/shared/package-files/38/38842f7e50557c754fb06b00ad6378ea15576592d447d27be8977978ddd8cf69/_native_batch_norm_legit_ops.h @@ -0,0 +1,73 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _native_batch_norm_legit { + using schema = ::std::tuple (const at::Tensor &, const ::std::optional &, const ::std::optional &, at::Tensor &, at::Tensor &, bool, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_batch_norm_legit"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps); +}; + +struct TORCH_API _native_batch_norm_legit_out { + using schema = ::std::tuple (const at::Tensor &, const ::std::optional &, const ::std::optional &, at::Tensor &, at::Tensor &, bool, double, double, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_batch_norm_legit"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!))"; + static ::std::tuple call(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); +}; + +struct TORCH_API _native_batch_norm_legit_no_stats { + using schema = ::std::tuple (const at::Tensor &, const ::std::optional &, const ::std::optional &, bool, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_batch_norm_legit"; + static constexpr const char* overload_name = "no_stats"; + static constexpr const char* schema_str = "_native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps); +}; + +struct TORCH_API _native_batch_norm_legit_no_stats_out { + using schema = ::std::tuple (const at::Tensor &, const ::std::optional &, const ::std::optional &, bool, double, double, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_batch_norm_legit"; + static constexpr const char* overload_name = "no_stats_out"; + static constexpr const char* schema_str = "_native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))"; + static ::std::tuple call(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd); +}; + +struct TORCH_API _native_batch_norm_legit_functional { + using schema = ::std::tuple (const at::Tensor &, const ::std::optional &, const ::std::optional &, const at::Tensor &, const at::Tensor &, bool, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_batch_norm_legit_functional"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_native_batch_norm_legit_functional(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor running_mean_out, Tensor running_var_out)"; + static ::std::tuple call(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, bool training, double momentum, double eps); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, bool training, double momentum, double eps); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/38844e4d22e5df5fe448c11656aad8b8bd7972e453321417d98686eb32cdac35/_bz2.cpython-311-x86_64-linux-gnu.so b/shared/package-files/38/38844e4d22e5df5fe448c11656aad8b8bd7972e453321417d98686eb32cdac35/_bz2.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..cbd42a1980ac29269f14fb326d9fff997a69c630 Binary files /dev/null and b/shared/package-files/38/38844e4d22e5df5fe448c11656aad8b8bd7972e453321417d98686eb32cdac35/_bz2.cpython-311-x86_64-linux-gnu.so differ diff --git a/shared/package-files/38/388632e5f46389674b73c491aee834a4e8eb5e8b86d08f9fd86f10401d329eda/__init__.py b/shared/package-files/38/388632e5f46389674b73c491aee834a4e8eb5e8b86d08f9fd86f10401d329eda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac93de335b2d7379246de9cee658dd9eafe1d303 --- /dev/null +++ b/shared/package-files/38/388632e5f46389674b73c491aee834a4e8eb5e8b86d08f9fd86f10401d329eda/__init__.py @@ -0,0 +1 @@ +from torch.utils.data.datapipes import dataframe as dataframe, iter as iter, map as map diff --git a/shared/package-files/38/3886afe1565faa213dbf5fd8908555821dad567252aa9d46f8bc0315b4f4496b/__init__.cpython-311.pyc b/shared/package-files/38/3886afe1565faa213dbf5fd8908555821dad567252aa9d46f8bc0315b4f4496b/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8867a80be2b24e489ea454acf4a0ed3d8b0e324 Binary files /dev/null and b/shared/package-files/38/3886afe1565faa213dbf5fd8908555821dad567252aa9d46f8bc0315b4f4496b/__init__.cpython-311.pyc differ diff --git a/shared/package-files/38/388a42698a84cc793c127445a4580d7e220d90f0db73164b36c529ef13faea87/test_numeric_only.cpython-311.pyc b/shared/package-files/38/388a42698a84cc793c127445a4580d7e220d90f0db73164b36c529ef13faea87/test_numeric_only.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e6cc3051e2bd82786f1034ccedaa593fe980ab8 Binary files /dev/null and b/shared/package-files/38/388a42698a84cc793c127445a4580d7e220d90f0db73164b36c529ef13faea87/test_numeric_only.cpython-311.pyc differ diff --git a/shared/package-files/38/388c5a3a3be7132602a699e7b83755368b2ac89e51ff9634943768fc09eddbe7/__init__.cpython-311.pyc b/shared/package-files/38/388c5a3a3be7132602a699e7b83755368b2ac89e51ff9634943768fc09eddbe7/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee5ef4123ce1170e9f3abe91651fa2e39392d06 Binary files /dev/null and b/shared/package-files/38/388c5a3a3be7132602a699e7b83755368b2ac89e51ff9634943768fc09eddbe7/__init__.cpython-311.pyc differ diff --git a/shared/package-files/38/388c656067a297a08517075c52d935e56aa45ba079c42880376bad47a0e1154a/prefixes.cpython-311.pyc b/shared/package-files/38/388c656067a297a08517075c52d935e56aa45ba079c42880376bad47a0e1154a/prefixes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b3bfbfdb0ff73ba26eb979faf71953ad871f8ff Binary files /dev/null and b/shared/package-files/38/388c656067a297a08517075c52d935e56aa45ba079c42880376bad47a0e1154a/prefixes.cpython-311.pyc differ diff --git a/shared/package-files/38/389407b292f30c38a334599d2546ca1fea316b038a5252f985bbccfce6c8453b/__init__.py b/shared/package-files/38/389407b292f30c38a334599d2546ca1fea316b038a5252f985bbccfce6c8453b/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8055d3769f9dd00f4488c408d6dc502549e38f4c --- /dev/null +++ b/shared/package-files/38/389407b292f30c38a334599d2546ca1fea316b038a5252f985bbccfce6c8453b/__init__.py @@ -0,0 +1,190 @@ +"""Generic interface to all dbm clones. + +Use + + import dbm + d = dbm.open(file, 'w', 0o666) + +The returned object is a dbm.gnu, dbm.ndbm or dbm.dumb object, dependent on the +type of database being opened (determined by the whichdb function) in the case +of an existing dbm. If the dbm does not exist and the create or new flag ('c' +or 'n') was specified, the dbm type will be determined by the availability of +the modules (tested in the above order). + +It has the following interface (key and data are strings): + + d[key] = data # store data at key (may override data at + # existing key) + data = d[key] # retrieve data at key (raise KeyError if no + # such key) + del d[key] # delete data stored at key (raises KeyError + # if no such key) + flag = key in d # true if the key exists + list = d.keys() # return a list of all existing keys (slow!) + +Future versions may change the order in which implementations are +tested for existence, and add interfaces to other dbm-like +implementations. +""" + +__all__ = ['open', 'whichdb', 'error'] + +import io +import os +import struct +import sys + + +class error(Exception): + pass + +_names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb'] +_defaultmod = None +_modules = {} + +error = (error, OSError) + +try: + from dbm import ndbm +except ImportError: + ndbm = None + + +def open(file, flag='r', mode=0o666): + """Open or create database at path given by *file*. + + Optional argument *flag* can be 'r' (default) for read-only access, 'w' + for read-write access of an existing database, 'c' for read-write access + to a new or existing database, and 'n' for read-write access to a new + database. + + Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it + only if it doesn't exist; and 'n' always creates a new database. + """ + global _defaultmod + if _defaultmod is None: + for name in _names: + try: + mod = __import__(name, fromlist=['open']) + except ImportError: + continue + if not _defaultmod: + _defaultmod = mod + _modules[name] = mod + if not _defaultmod: + raise ImportError("no dbm clone found; tried %s" % _names) + + # guess the type of an existing database, if not creating a new one + result = whichdb(file) if 'n' not in flag else None + if result is None: + # db doesn't exist or 'n' flag was specified to create a new db + if 'c' in flag or 'n' in flag: + # file doesn't exist and the new flag was used so use default type + mod = _defaultmod + else: + raise error[0]("db file doesn't exist; " + "use 'c' or 'n' flag to create a new db") + elif result == "": + # db type cannot be determined + raise error[0]("db type could not be determined") + elif result not in _modules: + raise error[0]("db type is {0}, but the module is not " + "available".format(result)) + else: + mod = _modules[result] + return mod.open(file, flag, mode) + + +def whichdb(filename): + """Guess which db package to use to open a db file. + + Return values: + + - None if the database file can't be read; + - empty string if the file can be read but can't be recognized + - the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized. + + Importing the given module may still fail, and opening the + database using that module may still fail. + """ + + # Check for ndbm first -- this has a .pag and a .dir file + filename = os.fsencode(filename) + try: + f = io.open(filename + b".pag", "rb") + f.close() + f = io.open(filename + b".dir", "rb") + f.close() + return "dbm.ndbm" + except OSError: + # some dbm emulations based on Berkeley DB generate a .db file + # some do not, but they should be caught by the bsd checks + try: + f = io.open(filename + b".db", "rb") + f.close() + # guarantee we can actually open the file using dbm + # kind of overkill, but since we are dealing with emulations + # it seems like a prudent step + if ndbm is not None: + d = ndbm.open(filename) + d.close() + return "dbm.ndbm" + except OSError: + pass + + # Check for dumbdbm next -- this has a .dir and a .dat file + try: + # First check for presence of files + os.stat(filename + b".dat") + size = os.stat(filename + b".dir").st_size + # dumbdbm files with no keys are empty + if size == 0: + return "dbm.dumb" + f = io.open(filename + b".dir", "rb") + try: + if f.read(1) in (b"'", b'"'): + return "dbm.dumb" + finally: + f.close() + except OSError: + pass + + # See if the file exists, return None if not + try: + f = io.open(filename, "rb") + except OSError: + return None + + with f: + # Read the start of the file -- the magic number + s16 = f.read(16) + s = s16[0:4] + + # Return "" if not at least 4 bytes + if len(s) != 4: + return "" + + # Convert to 4-byte int in native byte order -- return "" if impossible + try: + (magic,) = struct.unpack("=l", s) + except struct.error: + return "" + + # Check for GNU dbm + if magic in (0x13579ace, 0x13579acd, 0x13579acf): + return "dbm.gnu" + + # Later versions of Berkeley db hash file have a 12-byte pad in + # front of the file type + try: + (magic,) = struct.unpack("=l", s16[-4:]) + except struct.error: + return "" + + # Unknown + return "" + + +if __name__ == "__main__": + for filename in sys.argv[1:]: + print(whichdb(filename) or "UNKNOWN", filename) diff --git a/shared/package-files/38/389b707e6f99cf4ddeb612e1acda38038770c7328472b30facd20900806b9af8/test_to_pydatetime.cpython-311.pyc b/shared/package-files/38/389b707e6f99cf4ddeb612e1acda38038770c7328472b30facd20900806b9af8/test_to_pydatetime.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd2094cb09c87b9c73d789363ce49be212d8e89e Binary files /dev/null and b/shared/package-files/38/389b707e6f99cf4ddeb612e1acda38038770c7328472b30facd20900806b9af8/test_to_pydatetime.cpython-311.pyc differ diff --git a/shared/package-files/38/389ccc7d9b5ebf760e289066d90c6713eabef7e7b1cb624b871a625616374ffd/test_gdb.py b/shared/package-files/38/389ccc7d9b5ebf760e289066d90c6713eabef7e7b1cb624b871a625616374ffd/test_gdb.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac2f55754fe549d11c1725221b9a77145b5adeb --- /dev/null +++ b/shared/package-files/38/389ccc7d9b5ebf760e289066d90c6713eabef7e7b1cb624b871a625616374ffd/test_gdb.py @@ -0,0 +1,1082 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from functools import lru_cache +import os +import re +import shutil +import subprocess +import sys + +import pytest + +import pyarrow as pa + + +pytestmark = pytest.mark.gdb + +here = os.path.dirname(os.path.abspath(__file__)) + +# The GDB script may be found in the source tree (if available) +# or in another location given by the ARROW_GDB_SCRIPT environment variable. +gdb_script = (os.environ.get('ARROW_GDB_SCRIPT') or + os.path.join(here, "../../../cpp/gdb_arrow.py")) + +gdb_command = ["gdb", "--nx"] + + +def environment_for_gdb(): + env = {} + for var in ['PATH', 'LD_LIBRARY_PATH']: + try: + env[var] = os.environ[var] + except KeyError: + pass + return env + + +@lru_cache() +def is_gdb_available(): + try: + # Try to use the same arguments as in GdbSession so that the + # same error return gets propagated. + proc = subprocess.run(gdb_command + ["--version"], + env=environment_for_gdb(), bufsize=0, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + except FileNotFoundError: + return False + return proc.returncode == 0 + + +@lru_cache() +def python_executable(): + path = shutil.which("python3") + assert path is not None, "Couldn't find python3 executable" + return path + + +def skip_if_gdb_unavailable(): + if not is_gdb_available(): + pytest.skip("gdb command unavailable") + + +def skip_if_gdb_script_unavailable(): + if not os.path.exists(gdb_script): + pytest.skip("gdb script not found") + + +class GdbSession: + proc = None + verbose = True + + def __init__(self, *args, **env): + # Let stderr through to let pytest display it separately on errors + gdb_env = environment_for_gdb() + gdb_env.update(env) + self.proc = subprocess.Popen(gdb_command + list(args), + env=gdb_env, bufsize=0, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) + self.last_stdout = [] + self.last_stdout_line = b"" + + def wait_until_ready(self): + """ + Record output until the gdb prompt displays. Return recorded output. + """ + # TODO: add timeout? + while (not self.last_stdout_line.startswith(b"(gdb) ") and + self.proc.poll() is None): + block = self.proc.stdout.read(4096) + if self.verbose: + sys.stdout.buffer.write(block) + sys.stdout.buffer.flush() + block, sep, last_line = block.rpartition(b"\n") + if sep: + self.last_stdout.append(self.last_stdout_line) + self.last_stdout.append(block + sep) + self.last_stdout_line = last_line + else: + assert block == b"" + self.last_stdout_line += last_line + + if self.proc.poll() is not None: + raise IOError("gdb session terminated unexpectedly") + + out = b"".join(self.last_stdout).decode('utf-8') + self.last_stdout = [] + self.last_stdout_line = b"" + return out + + def issue_command(self, line): + line = line.encode('utf-8') + b"\n" + if self.verbose: + sys.stdout.buffer.write(line) + sys.stdout.buffer.flush() + self.proc.stdin.write(line) + self.proc.stdin.flush() + + def run_command(self, line): + self.issue_command(line) + return self.wait_until_ready() + + def print_value(self, expr): + """ + Ask gdb to print the value of an expression and return the result. + """ + out = self.run_command(f"p {expr}") + out, n = re.subn(r"^\$\d+ = ", "", out) + assert n == 1, out + # gdb may add whitespace depending on result width, remove it + return out.strip() + + def select_frame(self, func_name): + """ + Select the innermost frame with the given function name. + """ + # Ideally, we would use the "frame function" command, + # but it's not available on old GDB versions (such as 8.1.1), + # so instead parse the stack trace for a matching frame number. + out = self.run_command("info stack") + pat = r"(?mi)^#(\d+)\s+.* in " + re.escape(func_name) + r"\b" + m = re.search(pat, out) + if m is None: + pytest.fail(f"Could not select frame for function {func_name}") + + frame_num = int(m[1]) + out = self.run_command(f"frame {frame_num}") + assert f"in {func_name}" in out + + def join(self): + if self.proc is not None: + self.proc.stdin.close() + self.proc.stdout.close() # avoid ResourceWarning + self.proc.kill() + self.proc.wait() + self.proc = None + + def __del__(self): + self.join() + + +@pytest.fixture(scope='session') +def gdb(): + skip_if_gdb_unavailable() + gdb = GdbSession("-q", python_executable()) + try: + gdb.wait_until_ready() + gdb.run_command("set confirm off") + gdb.run_command("set print array-indexes on") + # Make sure gdb formatting is not terminal-dependent + gdb.run_command("set width unlimited") + gdb.run_command("set charset UTF-8") + yield gdb + finally: + gdb.join() + + +@pytest.fixture(scope='session') +def gdb_arrow(gdb): + if 'deb' not in pa.cpp_build_info.build_type: + pytest.skip("Arrow C++ debug symbols not available") + + skip_if_gdb_script_unavailable() + gdb.run_command(f"source {gdb_script}") + + lib_path_var = 'PATH' if sys.platform == 'win32' else 'LD_LIBRARY_PATH' + lib_path = os.environ.get(lib_path_var) + if lib_path: + # GDB starts the inferior process in a pristine shell, need + # to propagate the library search path to find the Arrow DLL + gdb.run_command(f"set env {lib_path_var} {lib_path}") + + code = "from pyarrow.lib import _gdb_test_session; _gdb_test_session()" + out = gdb.run_command(f"run -c '{code}'") + assert ("Trace/breakpoint trap" in out or + "received signal" in out), out + gdb.select_frame("arrow::gdb::TestSession") + return gdb + + +def test_gdb_session(gdb): + out = gdb.run_command("show version") + assert out.startswith("GNU gdb ("), out + + +def test_gdb_arrow(gdb_arrow): + s = gdb_arrow.print_value("42 + 1") + assert s == "43" + + +def check_stack_repr(gdb, expr, expected): + """ + Check printing a stack-located value. + """ + s = gdb.print_value(expr) + if isinstance(expected, re.Pattern): + assert expected.match(s), s + else: + assert s == expected + + +def check_heap_repr(gdb, expr, expected): + """ + Check printing a heap-located value, given its address. + """ + s = gdb.print_value(f"*{expr}") + # GDB may prefix the value with an address or type specification + if s != expected: + assert s.endswith(f" {expected}") + + +def test_status(gdb_arrow): + check_stack_repr(gdb_arrow, "ok_status", "arrow::Status::OK()") + check_stack_repr(gdb_arrow, "error_status", + 'arrow::Status::IOError("This is an error")') + check_stack_repr( + gdb_arrow, "error_detail_status", + 'arrow::Status::IOError("This is an error", ' + 'detail=[custom-detail-id] "This is a detail")') + + check_stack_repr(gdb_arrow, "ok_result", "arrow::Result(42)") + check_stack_repr( + gdb_arrow, "error_result", + 'arrow::Result(arrow::Status::IOError("This is an error"))') + check_stack_repr( + gdb_arrow, "error_detail_result", + 'arrow::Result(arrow::Status::IOError("This is an error", ' + 'detail=[custom-detail-id] "This is a detail"))') + + +def test_buffer_stack(gdb_arrow): + check_stack_repr(gdb_arrow, "buffer_null", + "arrow::Buffer of size 0, read-only") + check_stack_repr(gdb_arrow, "buffer_abc", + 'arrow::Buffer of size 3, read-only, "abc"') + check_stack_repr( + gdb_arrow, "buffer_special_chars", + r'arrow::Buffer of size 12, read-only, "foo\"bar\000\r\n\t\037"') + check_stack_repr(gdb_arrow, "buffer_mutable", + 'arrow::MutableBuffer of size 3, mutable, "abc"') + + +def test_buffer_heap(gdb_arrow): + check_heap_repr(gdb_arrow, "heap_buffer", + 'arrow::Buffer of size 3, read-only, "abc"') + check_heap_repr(gdb_arrow, "heap_buffer_mutable.get()", + 'arrow::Buffer of size 3, mutable, "abc"') + + +def test_decimals(gdb_arrow): + v128 = "98765432109876543210987654321098765432" + check_stack_repr(gdb_arrow, "decimal128_zero", "arrow::Decimal128(0)") + check_stack_repr(gdb_arrow, "decimal128_pos", + f"arrow::Decimal128({v128})") + check_stack_repr(gdb_arrow, "decimal128_neg", + f"arrow::Decimal128(-{v128})") + check_stack_repr(gdb_arrow, "basic_decimal128_zero", + "arrow::BasicDecimal128(0)") + check_stack_repr(gdb_arrow, "basic_decimal128_pos", + f"arrow::BasicDecimal128({v128})") + check_stack_repr(gdb_arrow, "basic_decimal128_neg", + f"arrow::BasicDecimal128(-{v128})") + + v256 = ("9876543210987654321098765432109876543210" + "987654321098765432109876543210987654") + check_stack_repr(gdb_arrow, "decimal256_zero", "arrow::Decimal256(0)") + check_stack_repr(gdb_arrow, "decimal256_pos", + f"arrow::Decimal256({v256})") + check_stack_repr(gdb_arrow, "decimal256_neg", + f"arrow::Decimal256(-{v256})") + check_stack_repr(gdb_arrow, "basic_decimal256_zero", + "arrow::BasicDecimal256(0)") + check_stack_repr(gdb_arrow, "basic_decimal256_pos", + f"arrow::BasicDecimal256({v256})") + check_stack_repr(gdb_arrow, "basic_decimal256_neg", + f"arrow::BasicDecimal256(-{v256})") + + +def test_metadata(gdb_arrow): + check_heap_repr(gdb_arrow, "empty_metadata.get()", + "arrow::KeyValueMetadata of size 0") + check_heap_repr( + gdb_arrow, "metadata.get()", + ('arrow::KeyValueMetadata of size 2 = {' + '["key_text"] = "some value", ["key_binary"] = "z\\000\\037\\377"}')) + + +def test_types_stack(gdb_arrow): + check_stack_repr(gdb_arrow, "null_type", "arrow::null()") + check_stack_repr(gdb_arrow, "bool_type", "arrow::boolean()") + + check_stack_repr(gdb_arrow, "date32_type", "arrow::date32()") + check_stack_repr(gdb_arrow, "date64_type", "arrow::date64()") + check_stack_repr(gdb_arrow, "time_type_s", + "arrow::time32(arrow::TimeUnit::SECOND)") + check_stack_repr(gdb_arrow, "time_type_ms", + "arrow::time32(arrow::TimeUnit::MILLI)") + check_stack_repr(gdb_arrow, "time_type_us", + "arrow::time64(arrow::TimeUnit::MICRO)") + check_stack_repr(gdb_arrow, "time_type_ns", + "arrow::time64(arrow::TimeUnit::NANO)") + check_stack_repr(gdb_arrow, "timestamp_type_s", + "arrow::timestamp(arrow::TimeUnit::SECOND)") + check_stack_repr( + gdb_arrow, "timestamp_type_ms_timezone", + 'arrow::timestamp(arrow::TimeUnit::MILLI, "Europe/Paris")') + check_stack_repr(gdb_arrow, "timestamp_type_us", + "arrow::timestamp(arrow::TimeUnit::MICRO)") + check_stack_repr( + gdb_arrow, "timestamp_type_ns_timezone", + 'arrow::timestamp(arrow::TimeUnit::NANO, "Europe/Paris")') + + check_stack_repr(gdb_arrow, "day_time_interval_type", + "arrow::day_time_interval()") + check_stack_repr(gdb_arrow, "month_interval_type", + "arrow::month_interval()") + check_stack_repr(gdb_arrow, "month_day_nano_interval_type", + "arrow::month_day_nano_interval()") + check_stack_repr(gdb_arrow, "duration_type_s", + "arrow::duration(arrow::TimeUnit::SECOND)") + check_stack_repr(gdb_arrow, "duration_type_ns", + "arrow::duration(arrow::TimeUnit::NANO)") + + check_stack_repr(gdb_arrow, "decimal128_type", + "arrow::decimal128(16, 5)") + check_stack_repr(gdb_arrow, "decimal256_type", + "arrow::decimal256(42, 12)") + + check_stack_repr(gdb_arrow, "binary_type", "arrow::binary()") + check_stack_repr(gdb_arrow, "string_type", "arrow::utf8()") + check_stack_repr(gdb_arrow, "large_binary_type", "arrow::large_binary()") + check_stack_repr(gdb_arrow, "large_string_type", "arrow::large_utf8()") + check_stack_repr(gdb_arrow, "fixed_size_binary_type", + "arrow::fixed_size_binary(10)") + + check_stack_repr(gdb_arrow, "list_type", + "arrow::list(arrow::uint8())") + check_stack_repr(gdb_arrow, "large_list_type", + "arrow::large_list(arrow::large_utf8())") + check_stack_repr(gdb_arrow, "fixed_size_list_type", + "arrow::fixed_size_list(arrow::float64(), 3)") + check_stack_repr( + gdb_arrow, "map_type_unsorted", + "arrow::map(arrow::utf8(), arrow::binary(), keys_sorted=false)") + check_stack_repr( + gdb_arrow, "map_type_sorted", + "arrow::map(arrow::utf8(), arrow::binary(), keys_sorted=true)") + + check_stack_repr(gdb_arrow, "struct_type_empty", + "arrow::struct_({})") + check_stack_repr( + gdb_arrow, "struct_type", + ('arrow::struct_({arrow::field("ints", arrow::int8()), ' + 'arrow::field("strs", arrow::utf8(), nullable=false)})')) + + check_stack_repr( + gdb_arrow, "sparse_union_type", + ('arrow::sparse_union(fields={arrow::field("ints", arrow::int8()), ' + 'arrow::field("strs", arrow::utf8(), nullable=false)}, ' + 'type_codes={7, 42})')) + check_stack_repr( + gdb_arrow, "dense_union_type", + ('arrow::dense_union(fields={arrow::field("ints", arrow::int8()), ' + 'arrow::field("strs", arrow::utf8(), nullable=false)}, ' + 'type_codes={7, 42})')) + + check_stack_repr( + gdb_arrow, "dict_type_unordered", + "arrow::dictionary(arrow::int16(), arrow::utf8(), ordered=false)") + check_stack_repr( + gdb_arrow, "dict_type_ordered", + "arrow::dictionary(arrow::int16(), arrow::utf8(), ordered=true)") + + check_stack_repr( + gdb_arrow, "uuid_type", + ('arrow::ExtensionType "extension" ' + 'with storage type arrow::fixed_size_binary(16)')) + + +def test_types_heap(gdb_arrow): + check_heap_repr(gdb_arrow, "heap_null_type", "arrow::null()") + check_heap_repr(gdb_arrow, "heap_bool_type", "arrow::boolean()") + + check_heap_repr(gdb_arrow, "heap_time_type_ns", + "arrow::time64(arrow::TimeUnit::NANO)") + check_heap_repr( + gdb_arrow, "heap_timestamp_type_ns_timezone", + 'arrow::timestamp(arrow::TimeUnit::NANO, "Europe/Paris")') + + check_heap_repr(gdb_arrow, "heap_decimal128_type", + "arrow::decimal128(16, 5)") + + check_heap_repr(gdb_arrow, "heap_list_type", + "arrow::list(arrow::uint8())") + check_heap_repr(gdb_arrow, "heap_large_list_type", + "arrow::large_list(arrow::large_utf8())") + check_heap_repr(gdb_arrow, "heap_fixed_size_list_type", + "arrow::fixed_size_list(arrow::float64(), 3)") + check_heap_repr( + gdb_arrow, "heap_map_type", + "arrow::map(arrow::utf8(), arrow::binary(), keys_sorted=false)") + + check_heap_repr( + gdb_arrow, "heap_struct_type", + ('arrow::struct_({arrow::field("ints", arrow::int8()), ' + 'arrow::field("strs", arrow::utf8(), nullable=false)})')) + + check_heap_repr( + gdb_arrow, "heap_dict_type", + "arrow::dictionary(arrow::int16(), arrow::utf8(), ordered=false)") + + check_heap_repr( + gdb_arrow, "heap_uuid_type", + ('arrow::ExtensionType "extension" ' + 'with storage type arrow::fixed_size_binary(16)')) + + +def test_fields_stack(gdb_arrow): + check_stack_repr(gdb_arrow, "int_field", + 'arrow::field("ints", arrow::int64())') + check_stack_repr( + gdb_arrow, "float_field", + 'arrow::field("floats", arrow::float32(), nullable=false)') + + +def test_fields_heap(gdb_arrow): + check_heap_repr(gdb_arrow, "heap_int_field", + 'arrow::field("ints", arrow::int64())') + + +def test_scalars_stack(gdb_arrow): + check_stack_repr(gdb_arrow, "null_scalar", "arrow::NullScalar") + check_stack_repr(gdb_arrow, "bool_scalar", + "arrow::BooleanScalar of value true") + check_stack_repr(gdb_arrow, "bool_scalar_null", + "arrow::BooleanScalar of null value") + check_stack_repr(gdb_arrow, "int8_scalar", + "arrow::Int8Scalar of value -42") + check_stack_repr(gdb_arrow, "uint8_scalar", + "arrow::UInt8Scalar of value 234") + check_stack_repr(gdb_arrow, "int64_scalar", + "arrow::Int64Scalar of value -9223372036854775808") + check_stack_repr(gdb_arrow, "uint64_scalar", + "arrow::UInt64Scalar of value 18446744073709551615") + check_stack_repr(gdb_arrow, "half_float_scalar", + "arrow::HalfFloatScalar of value -1.5 [48640]") + check_stack_repr(gdb_arrow, "float_scalar", + "arrow::FloatScalar of value 1.25") + check_stack_repr(gdb_arrow, "double_scalar", + "arrow::DoubleScalar of value 2.5") + + check_stack_repr(gdb_arrow, "time_scalar_s", + "arrow::Time32Scalar of value 100s") + check_stack_repr(gdb_arrow, "time_scalar_ms", + "arrow::Time32Scalar of value 1000ms") + check_stack_repr(gdb_arrow, "time_scalar_us", + "arrow::Time64Scalar of value 10000us") + check_stack_repr(gdb_arrow, "time_scalar_ns", + "arrow::Time64Scalar of value 100000ns") + check_stack_repr(gdb_arrow, "time_scalar_null", + "arrow::Time64Scalar of null value [ns]") + + check_stack_repr(gdb_arrow, "duration_scalar_s", + "arrow::DurationScalar of value -100s") + check_stack_repr(gdb_arrow, "duration_scalar_ms", + "arrow::DurationScalar of value -1000ms") + check_stack_repr(gdb_arrow, "duration_scalar_us", + "arrow::DurationScalar of value -10000us") + check_stack_repr(gdb_arrow, "duration_scalar_ns", + "arrow::DurationScalar of value -100000ns") + check_stack_repr(gdb_arrow, "duration_scalar_null", + "arrow::DurationScalar of null value [ns]") + + check_stack_repr( + gdb_arrow, "timestamp_scalar_s", + "arrow::TimestampScalar of value 12345s [no timezone]") + check_stack_repr( + gdb_arrow, "timestamp_scalar_ms", + "arrow::TimestampScalar of value -123456ms [no timezone]") + check_stack_repr( + gdb_arrow, "timestamp_scalar_us", + "arrow::TimestampScalar of value 1234567us [no timezone]") + check_stack_repr( + gdb_arrow, "timestamp_scalar_ns", + "arrow::TimestampScalar of value -12345678ns [no timezone]") + check_stack_repr( + gdb_arrow, "timestamp_scalar_null", + "arrow::TimestampScalar of null value [ns, no timezone]") + + check_stack_repr( + gdb_arrow, "timestamp_scalar_s_tz", + 'arrow::TimestampScalar of value 12345s ["Europe/Paris"]') + check_stack_repr( + gdb_arrow, "timestamp_scalar_ms_tz", + 'arrow::TimestampScalar of value -123456ms ["Europe/Paris"]') + check_stack_repr( + gdb_arrow, "timestamp_scalar_us_tz", + 'arrow::TimestampScalar of value 1234567us ["Europe/Paris"]') + check_stack_repr( + gdb_arrow, "timestamp_scalar_ns_tz", + 'arrow::TimestampScalar of value -12345678ns ["Europe/Paris"]') + check_stack_repr( + gdb_arrow, "timestamp_scalar_null_tz", + 'arrow::TimestampScalar of null value [ns, "Europe/Paris"]') + + check_stack_repr(gdb_arrow, "month_interval_scalar", + "arrow::MonthIntervalScalar of value 23M") + check_stack_repr(gdb_arrow, "month_interval_scalar_null", + "arrow::MonthIntervalScalar of null value") + check_stack_repr(gdb_arrow, "day_time_interval_scalar", + "arrow::DayTimeIntervalScalar of value 23d-456ms") + check_stack_repr(gdb_arrow, "day_time_interval_scalar_null", + "arrow::DayTimeIntervalScalar of null value") + check_stack_repr( + gdb_arrow, "month_day_nano_interval_scalar", + "arrow::MonthDayNanoIntervalScalar of value 1M23d-456ns") + check_stack_repr( + gdb_arrow, "month_day_nano_interval_scalar_null", + "arrow::MonthDayNanoIntervalScalar of null value") + + check_stack_repr(gdb_arrow, "date32_scalar", + "arrow::Date32Scalar of value 23d [1970-01-24]") + check_stack_repr(gdb_arrow, "date32_scalar_null", + "arrow::Date32Scalar of null value") + check_stack_repr(gdb_arrow, "date64_scalar", + "arrow::Date64Scalar of value 3888000000ms [1970-02-15]") + check_stack_repr(gdb_arrow, "date64_scalar_null", + "arrow::Date64Scalar of null value") + + check_stack_repr( + gdb_arrow, "decimal128_scalar_null", + "arrow::Decimal128Scalar of null value [precision=10, scale=4]") + check_stack_repr( + gdb_arrow, "decimal128_scalar_pos_scale_pos", + "arrow::Decimal128Scalar of value 123.4567 [precision=10, scale=4]") + check_stack_repr( + gdb_arrow, "decimal128_scalar_pos_scale_neg", + "arrow::Decimal128Scalar of value -123.4567 [precision=10, scale=4]") + check_stack_repr( + gdb_arrow, "decimal128_scalar_neg_scale_pos", + ("arrow::Decimal128Scalar of value 1.234567e+10 " + "[precision=10, scale=-4]")) + check_stack_repr( + gdb_arrow, "decimal128_scalar_neg_scale_neg", + ("arrow::Decimal128Scalar of value -1.234567e+10 " + "[precision=10, scale=-4]")) + + check_stack_repr( + gdb_arrow, "decimal256_scalar_null", + "arrow::Decimal256Scalar of null value [precision=50, scale=4]") + check_stack_repr( + gdb_arrow, "decimal256_scalar_pos_scale_pos", + ("arrow::Decimal256Scalar of value " + "123456789012345678901234567890123456789012.3456 " + "[precision=50, scale=4]")) + check_stack_repr( + gdb_arrow, "decimal256_scalar_pos_scale_neg", + ("arrow::Decimal256Scalar of value " + "-123456789012345678901234567890123456789012.3456 " + "[precision=50, scale=4]")) + check_stack_repr( + gdb_arrow, "decimal256_scalar_neg_scale_pos", + ("arrow::Decimal256Scalar of value " + "1.234567890123456789012345678901234567890123456e+49 " + "[precision=50, scale=-4]")) + check_stack_repr( + gdb_arrow, "decimal256_scalar_neg_scale_neg", + ("arrow::Decimal256Scalar of value " + "-1.234567890123456789012345678901234567890123456e+49 " + "[precision=50, scale=-4]")) + + check_stack_repr( + gdb_arrow, "binary_scalar_null", + "arrow::BinaryScalar of null value") + check_stack_repr( + gdb_arrow, "binary_scalar_unallocated", + "arrow::BinaryScalar of value ") + check_stack_repr( + gdb_arrow, "binary_scalar_empty", + 'arrow::BinaryScalar of size 0, value ""') + check_stack_repr( + gdb_arrow, "binary_scalar_abc", + 'arrow::BinaryScalar of size 3, value "abc"') + check_stack_repr( + gdb_arrow, "binary_scalar_bytes", + r'arrow::BinaryScalar of size 3, value "\000\037\377"') + check_stack_repr( + gdb_arrow, "large_binary_scalar_abc", + 'arrow::LargeBinaryScalar of size 3, value "abc"') + + check_stack_repr( + gdb_arrow, "string_scalar_null", + "arrow::StringScalar of null value") + check_stack_repr( + gdb_arrow, "string_scalar_unallocated", + "arrow::StringScalar of value ") + check_stack_repr( + gdb_arrow, "string_scalar_empty", + 'arrow::StringScalar of size 0, value ""') + check_stack_repr( + gdb_arrow, "string_scalar_hehe", + 'arrow::StringScalar of size 6, value "héhé"') + # FIXME: excessive escaping ('\\xff' vs. '\x00') + check_stack_repr( + gdb_arrow, "string_scalar_invalid_chars", + r'arrow::StringScalar of size 11, value "abc\x00def\\xffghi"') + check_stack_repr( + gdb_arrow, "large_string_scalar_hehe", + 'arrow::LargeStringScalar of size 6, value "héhé"') + + check_stack_repr( + gdb_arrow, "fixed_size_binary_scalar", + 'arrow::FixedSizeBinaryScalar of size 3, value "abc"') + check_stack_repr( + gdb_arrow, "fixed_size_binary_scalar_null", + 'arrow::FixedSizeBinaryScalar of size 3, null with value " "') + + check_stack_repr( + gdb_arrow, "dict_scalar", + re.compile( + (r'^arrow::DictionaryScalar of index ' + r'arrow::Int8Scalar of value 42, ' + r'dictionary arrow::StringArray '))) + check_stack_repr( + gdb_arrow, "dict_scalar_null", + ('arrow::DictionaryScalar of type ' + 'arrow::dictionary(arrow::int8(), arrow::utf8(), ordered=false), ' + 'null value')) + + check_stack_repr( + gdb_arrow, "list_scalar", + ('arrow::ListScalar of value arrow::Int32Array of ' + 'length 3, offset 0, null count 0 = {[0] = 4, [1] = 5, [2] = 6}')) + check_stack_repr( + gdb_arrow, "list_scalar_null", + 'arrow::ListScalar of type arrow::list(arrow::int32()), null value') + check_stack_repr( + gdb_arrow, "large_list_scalar", + ('arrow::LargeListScalar of value arrow::Int32Array of ' + 'length 3, offset 0, null count 0 = {[0] = 4, [1] = 5, [2] = 6}')) + check_stack_repr( + gdb_arrow, "large_list_scalar_null", + ('arrow::LargeListScalar of type arrow::large_list(arrow::int32()), ' + 'null value')) + check_stack_repr( + gdb_arrow, "fixed_size_list_scalar", + ('arrow::FixedSizeListScalar of value arrow::Int32Array of ' + 'length 3, offset 0, null count 0 = {[0] = 4, [1] = 5, [2] = 6}')) + check_stack_repr( + gdb_arrow, "fixed_size_list_scalar_null", + ('arrow::FixedSizeListScalar of type ' + 'arrow::fixed_size_list(arrow::int32(), 3), null value')) + + check_stack_repr( + gdb_arrow, "struct_scalar", + ('arrow::StructScalar = {["ints"] = arrow::Int32Scalar of value 42, ' + '["strs"] = arrow::StringScalar of size 9, value "some text"}')) + check_stack_repr( + gdb_arrow, "struct_scalar_null", + ('arrow::StructScalar of type arrow::struct_(' + '{arrow::field("ints", arrow::int32()), ' + 'arrow::field("strs", arrow::utf8())}), null value')) + + check_stack_repr( + gdb_arrow, "sparse_union_scalar", + ('arrow::SparseUnionScalar of type code 7, ' + 'value arrow::Int32Scalar of value 43')) + check_stack_repr( + gdb_arrow, "sparse_union_scalar_null", re.compile( + r'^arrow::SparseUnionScalar of type arrow::sparse_union\(.*\), ' + r'type code 7, null value$')) + check_stack_repr( + gdb_arrow, "dense_union_scalar", + ('arrow::DenseUnionScalar of type code 7, ' + 'value arrow::Int32Scalar of value 43')) + check_stack_repr( + gdb_arrow, "dense_union_scalar_null", re.compile( + r'^arrow::DenseUnionScalar of type arrow::dense_union\(.*\), ' + r'type code 7, null value$')) + + check_stack_repr( + gdb_arrow, "extension_scalar", + ('arrow::ExtensionScalar of type "extension", ' + 'value arrow::FixedSizeBinaryScalar of size 16, ' + 'value "0123456789abcdef"')) + check_stack_repr( + gdb_arrow, "extension_scalar_null", + 'arrow::ExtensionScalar of type "extension", null value') + + +def test_scalars_heap(gdb_arrow): + check_heap_repr(gdb_arrow, "heap_null_scalar", "arrow::NullScalar") + check_heap_repr(gdb_arrow, "heap_bool_scalar", + "arrow::BooleanScalar of value true") + check_heap_repr( + gdb_arrow, "heap_decimal128_scalar", + "arrow::Decimal128Scalar of value 123.4567 [precision=10, scale=4]") + check_heap_repr( + gdb_arrow, "heap_decimal256_scalar", + ("arrow::Decimal256Scalar of value " + "123456789012345678901234567890123456789012.3456 " + "[precision=50, scale=4]")) + + check_heap_repr( + gdb_arrow, "heap_map_scalar", + ('arrow::MapScalar of type arrow::map(arrow::utf8(), arrow::int32(), ' + 'keys_sorted=false), value length 2, offset 0, null count 0')) + check_heap_repr( + gdb_arrow, "heap_map_scalar_null", + ('arrow::MapScalar of type arrow::map(arrow::utf8(), arrow::int32(), ' + 'keys_sorted=false), null value')) + + +def test_array_data(gdb_arrow): + check_stack_repr( + gdb_arrow, "int32_array_data", + ("arrow::ArrayData of type arrow::int32(), length 4, offset 0, " + "null count 1 = {[0] = -5, [1] = 6, [2] = null, [3] = 42}")) + + +def test_arrays_stack(gdb_arrow): + check_stack_repr( + gdb_arrow, "int32_array", + ("arrow::Int32Array of length 4, offset 0, null count 1 = " + "{[0] = -5, [1] = 6, [2] = null, [3] = 42}")) + check_stack_repr( + gdb_arrow, "list_array", + ("arrow::ListArray of type arrow::list(arrow::int64()), " + "length 3, offset 0, null count 1")) + + +def test_arrays_heap(gdb_arrow): + # Null + check_heap_repr( + gdb_arrow, "heap_null_array", + "arrow::NullArray of length 2, offset 0, null count 2") + + # Primitive + check_heap_repr( + gdb_arrow, "heap_int32_array", + ("arrow::Int32Array of length 4, offset 0, null count 1 = {" + "[0] = -5, [1] = 6, [2] = null, [3] = 42}")) + check_heap_repr( + gdb_arrow, "heap_int32_array_no_nulls", + ("arrow::Int32Array of length 4, offset 0, null count 0 = {" + "[0] = -5, [1] = 6, [2] = 3, [3] = 42}")) + check_heap_repr( + gdb_arrow, "heap_int32_array_sliced_1_9", + ("arrow::Int32Array of length 9, offset 1, unknown null count = {" + "[0] = 2, [1] = -3, [2] = 4, [3] = null, [4] = -5, [5] = 6, " + "[6] = -7, [7] = 8, [8] = null}")) + check_heap_repr( + gdb_arrow, "heap_int32_array_sliced_2_6", + ("arrow::Int32Array of length 6, offset 2, unknown null count = {" + "[0] = -3, [1] = 4, [2] = null, [3] = -5, [4] = 6, [5] = -7}")) + check_heap_repr( + gdb_arrow, "heap_int32_array_sliced_8_4", + ("arrow::Int32Array of length 4, offset 8, unknown null count = {" + "[0] = 8, [1] = null, [2] = -9, [3] = -10}")) + check_heap_repr( + gdb_arrow, "heap_int32_array_sliced_empty", + "arrow::Int32Array of length 0, offset 6, unknown null count") + + check_heap_repr( + gdb_arrow, "heap_double_array", + ("arrow::DoubleArray of length 2, offset 0, null count 1 = {" + "[0] = -1.5, [1] = null}")) + check_heap_repr( + gdb_arrow, "heap_float16_array", + ("arrow::HalfFloatArray of length 2, offset 0, null count 0 = {" + "[0] = 0.0, [1] = -1.5}")) + + # Boolean + check_heap_repr( + gdb_arrow, "heap_bool_array", + ("arrow::BooleanArray of length 18, offset 0, null count 6 = {" + "[0] = false, [1] = false, [2] = true, [3] = true, [4] = null, " + "[5] = null, [6] = false, [7] = false, [8] = true, [9] = true, " + "[10] = null, [11] = null, [12] = false, [13] = false, " + "[14] = true, [15] = true, [16] = null, [17] = null}")) + check_heap_repr( + gdb_arrow, "heap_bool_array_sliced_1_9", + ("arrow::BooleanArray of length 9, offset 1, unknown null count = {" + "[0] = false, [1] = true, [2] = true, [3] = null, [4] = null, " + "[5] = false, [6] = false, [7] = true, [8] = true}")) + check_heap_repr( + gdb_arrow, "heap_bool_array_sliced_2_6", + ("arrow::BooleanArray of length 6, offset 2, unknown null count = {" + "[0] = true, [1] = true, [2] = null, [3] = null, [4] = false, " + "[5] = false}")) + check_heap_repr( + gdb_arrow, "heap_bool_array_sliced_empty", + "arrow::BooleanArray of length 0, offset 6, unknown null count") + + # Temporal + check_heap_repr( + gdb_arrow, "heap_date32_array", + ("arrow::Date32Array of length 6, offset 0, null count 1 = {" + "[0] = 0d [1970-01-01], [1] = null, [2] = 18336d [2020-03-15], " + "[3] = -9004d [1945-05-08], [4] = -719162d [0001-01-01], " + "[5] = -719163d [year <= 0]}")) + check_heap_repr( + gdb_arrow, "heap_date64_array", + ("arrow::Date64Array of length 5, offset 0, null count 0 = {" + "[0] = 1584230400000ms [2020-03-15], " + "[1] = -777945600000ms [1945-05-08], " + "[2] = -62135596800000ms [0001-01-01], " + "[3] = -62135683200000ms [year <= 0], " + "[4] = 123ms [non-multiple of 86400000]}")) + check_heap_repr( + gdb_arrow, "heap_time32_array_s", + ("arrow::Time32Array of type arrow::time32(arrow::TimeUnit::SECOND), " + "length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -123s, [2] = 456s}")) + check_heap_repr( + gdb_arrow, "heap_time32_array_ms", + ("arrow::Time32Array of type arrow::time32(arrow::TimeUnit::MILLI), " + "length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -123ms, [2] = 456ms}")) + check_heap_repr( + gdb_arrow, "heap_time64_array_us", + ("arrow::Time64Array of type arrow::time64(arrow::TimeUnit::MICRO), " + "length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -123us, [2] = 456us}")) + check_heap_repr( + gdb_arrow, "heap_time64_array_ns", + ("arrow::Time64Array of type arrow::time64(arrow::TimeUnit::NANO), " + "length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -123ns, [2] = 456ns}")) + check_heap_repr( + gdb_arrow, "heap_month_interval_array", + ("arrow::MonthIntervalArray of length 3, offset 0, null count 1 = {" + "[0] = 123M, [1] = -456M, [2] = null}")) + check_heap_repr( + gdb_arrow, "heap_day_time_interval_array", + ("arrow::DayTimeIntervalArray of length 2, offset 0, null count 1 = {" + "[0] = 1d-600ms, [1] = null}")) + check_heap_repr( + gdb_arrow, "heap_month_day_nano_interval_array", + ("arrow::MonthDayNanoIntervalArray of length 2, offset 0, " + "null count 1 = {[0] = 1M-600d5000ns, [1] = null}")) + check_heap_repr( + gdb_arrow, "heap_duration_array_s", + ("arrow::DurationArray of type arrow::duration" + "(arrow::TimeUnit::SECOND), length 2, offset 0, null count 1 = {" + "[0] = null, [1] = -1234567890123456789s}")) + check_heap_repr( + gdb_arrow, "heap_duration_array_ns", + ("arrow::DurationArray of type arrow::duration" + "(arrow::TimeUnit::NANO), length 2, offset 0, null count 1 = {" + "[0] = null, [1] = -1234567890123456789ns}")) + if sys.maxsize > 2**32: + check_heap_repr( + gdb_arrow, "heap_timestamp_array_s", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::SECOND), length 4, offset 0, null count 1 = {" + "[0] = null, [1] = 0s [1970-01-01 00:00:00], " + "[2] = -2203932304s [1900-02-28 12:34:56], " + "[3] = 63730281600s [3989-07-14 00:00:00]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_ms", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::MILLI), length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -2203932303877ms [1900-02-28 12:34:56.123], " + "[2] = 63730281600789ms [3989-07-14 00:00:00.789]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_us", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::MICRO), length 3, offset 0, null count 1 = {" + "[0] = null, " + "[1] = -2203932303345679us [1900-02-28 12:34:56.654321], " + "[2] = 63730281600456789us [3989-07-14 00:00:00.456789]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_ns", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::NANO), length 2, offset 0, null count 1 = {" + "[0] = null, " + "[1] = -2203932303012345679ns [1900-02-28 12:34:56.987654321]}")) + else: + # Python's datetime is limited to smaller timestamps on 32-bit platforms + check_heap_repr( + gdb_arrow, "heap_timestamp_array_s", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::SECOND), length 4, offset 0, null count 1 = {" + "[0] = null, [1] = 0s [1970-01-01 00:00:00], " + "[2] = -2203932304s [too large to represent], " + "[3] = 63730281600s [too large to represent]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_ms", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::MILLI), length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -2203932303877ms [too large to represent], " + "[2] = 63730281600789ms [too large to represent]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_us", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::MICRO), length 3, offset 0, null count 1 = {" + "[0] = null, " + "[1] = -2203932303345679us [too large to represent], " + "[2] = 63730281600456789us [too large to represent]}")) + check_heap_repr( + gdb_arrow, "heap_timestamp_array_ns", + ("arrow::TimestampArray of type arrow::timestamp" + "(arrow::TimeUnit::NANO), length 2, offset 0, null count 1 = {" + "[0] = null, " + "[1] = -2203932303012345679ns [too large to represent]}")) + + # Decimal + check_heap_repr( + gdb_arrow, "heap_decimal128_array", + ("arrow::Decimal128Array of type arrow::decimal128(30, 6), " + "length 3, offset 0, null count 1 = {" + "[0] = null, [1] = -1234567890123456789.012345, " + "[2] = 1234567890123456789.012345}")) + check_heap_repr( + gdb_arrow, "heap_decimal256_array", + ("arrow::Decimal256Array of type arrow::decimal256(50, 6), " + "length 2, offset 0, null count 1 = {" + "[0] = null, " + "[1] = -123456789012345678901234567890123456789.012345}")) + check_heap_repr( + gdb_arrow, "heap_decimal128_array_sliced", + ("arrow::Decimal128Array of type arrow::decimal128(30, 6), " + "length 1, offset 1, unknown null count = {" + "[0] = -1234567890123456789.012345}")) + + # Binary-like + check_heap_repr( + gdb_arrow, "heap_fixed_size_binary_array", + (r'arrow::FixedSizeBinaryArray of type arrow::fixed_size_binary(3), ' + r'length 3, offset 0, null count 1 = {' + r'[0] = null, [1] = "abc", [2] = "\000\037\377"}')) + check_heap_repr( + gdb_arrow, "heap_fixed_size_binary_array_zero_width", + (r'arrow::FixedSizeBinaryArray of type arrow::fixed_size_binary(0), ' + r'length 2, offset 0, null count 1 = {[0] = null, [1] = ""}')) + check_heap_repr( + gdb_arrow, "heap_fixed_size_binary_array_sliced", + (r'arrow::FixedSizeBinaryArray of type arrow::fixed_size_binary(3), ' + r'length 1, offset 1, unknown null count = {[0] = "abc"}')) + check_heap_repr( + gdb_arrow, "heap_binary_array", + (r'arrow::BinaryArray of length 3, offset 0, null count 1 = {' + r'[0] = null, [1] = "abcd", [2] = "\000\037\377"}')) + check_heap_repr( + gdb_arrow, "heap_large_binary_array", + (r'arrow::LargeBinaryArray of length 3, offset 0, null count 1 = {' + r'[0] = null, [1] = "abcd", [2] = "\000\037\377"}')) + check_heap_repr( + gdb_arrow, "heap_string_array", + (r'arrow::StringArray of length 3, offset 0, null count 1 = {' + r'[0] = null, [1] = "héhé", [2] = "invalid \\xff char"}')) + check_heap_repr( + gdb_arrow, "heap_large_string_array", + (r'arrow::LargeStringArray of length 3, offset 0, null count 1 = {' + r'[0] = null, [1] = "héhé", [2] = "invalid \\xff char"}')) + check_heap_repr( + gdb_arrow, "heap_binary_array_sliced", + (r'arrow::BinaryArray of length 1, offset 1, unknown null count = ' + r'{[0] = "abcd"}')) + + # Nested + check_heap_repr( + gdb_arrow, "heap_list_array", + ("arrow::ListArray of type arrow::list(arrow::int64()), " + "length 3, offset 0, null count 1")) + + +def test_schema(gdb_arrow): + check_heap_repr(gdb_arrow, "schema_empty", + "arrow::Schema with 0 fields") + check_heap_repr( + gdb_arrow, "schema_non_empty", + ('arrow::Schema with 2 fields = {["ints"] = arrow::int8(), ' + '["strs"] = arrow::utf8()}')) + check_heap_repr( + gdb_arrow, "schema_with_metadata", + ('arrow::Schema with 2 fields and 2 metadata items = ' + '{["ints"] = arrow::int8(), ["strs"] = arrow::utf8()}')) + + +def test_chunked_array(gdb_arrow): + check_stack_repr( + gdb_arrow, "chunked_array", + ("arrow::ChunkedArray of type arrow::int32(), length 5, null count 1 " + "with 2 chunks = {[0] = length 2, offset 0, null count 0, " + "[1] = length 3, offset 0, null count 1}")) + + +def test_record_batch(gdb_arrow): + expected_prefix = 'arrow::RecordBatch with 2 columns, 3 rows' + expected_suffix = ( + '{["ints"] = arrow::ArrayData of type arrow::int32(), ' + 'length 3, offset 0, null count 0 = ' + '{[0] = 1, [1] = 2, [2] = 3}, ' + '["strs"] = arrow::ArrayData of type arrow::utf8(), ' + 'length 3, offset 0, null count 1 = ' + '{[0] = "abc", [1] = null, [2] = "def"}}') + + expected = f"{expected_prefix} = {expected_suffix}" + # Representations may differ between those two because of + # RecordBatch (base class) vs. SimpleRecordBatch (concrete class). + check_heap_repr(gdb_arrow, "batch", expected) + check_heap_repr(gdb_arrow, "batch.get()", expected) + + expected = f"{expected_prefix}, 3 metadata items = {expected_suffix}" + check_heap_repr(gdb_arrow, "batch_with_metadata", expected) + + +def test_table(gdb_arrow): + expected_table = ( + 'arrow::Table with 2 columns, 5 rows = {' + '["ints"] = arrow::ChunkedArray of type arrow::int32(), ' + 'length 5, null count 0 with 2 chunks = ' + '{[0] = length 3, offset 0, null count 0, ' + '[1] = length 2, offset 0, null count 0}, ' + '["strs"] = arrow::ChunkedArray of type arrow::utf8(), ' + 'length 5, null count 1 with 3 chunks = ' + '{[0] = length 2, offset 0, null count 1, ' + '[1] = length 1, offset 0, null count 0, ' + '[2] = length 2, offset 0, null count 0}}') + + # Same as RecordBatch above (Table vs. SimpleTable) + check_heap_repr(gdb_arrow, "table", expected_table) + check_heap_repr(gdb_arrow, "table.get()", expected_table) + + +def test_datum(gdb_arrow): + check_stack_repr(gdb_arrow, "empty_datum", "arrow::Datum (empty)") + check_stack_repr( + gdb_arrow, "scalar_datum", + "arrow::Datum of value arrow::BooleanScalar of null value") + check_stack_repr( + gdb_arrow, "array_datum", + re.compile(r"^arrow::Datum of value arrow::ArrayData of type ")) + check_stack_repr( + gdb_arrow, "chunked_array_datum", + re.compile(r"^arrow::Datum of value arrow::ChunkedArray of type ")) + check_stack_repr( + gdb_arrow, "batch_datum", + re.compile(r"^arrow::Datum of value arrow::RecordBatch " + r"with 2 columns, 3 rows ")) + check_stack_repr( + gdb_arrow, "table_datum", + re.compile(r"^arrow::Datum of value arrow::Table " + r"with 2 columns, 5 rows ")) diff --git a/shared/package-files/38/389d833ca9ffa860c1896ed3967f3fbcbb491af064cd66cec7295b1e7f799dee/hits_alg.py b/shared/package-files/38/389d833ca9ffa860c1896ed3967f3fbcbb491af064cd66cec7295b1e7f799dee/hits_alg.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e3069d86dcb0ad0149ce66c72161b5340e01e0 --- /dev/null +++ b/shared/package-files/38/389d833ca9ffa860c1896ed3967f3fbcbb491af064cd66cec7295b1e7f799dee/hits_alg.py @@ -0,0 +1,337 @@ +"""Hubs and authorities analysis of graph structure.""" + +import networkx as nx + +__all__ = ["hits"] + + +@nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}}) +def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): + """Returns HITS hubs and authorities values for nodes. + + The HITS algorithm computes two numbers for a node. + Authorities estimates the node value based on the incoming links. + Hubs estimates the node value based on outgoing links. + + Parameters + ---------- + G : graph + A NetworkX graph + + max_iter : integer, optional + Maximum number of iterations in power method. + + tol : float, optional + Error tolerance used to check convergence in power method iteration. + + nstart : dictionary, optional + Starting value of each node for power method iteration. + + normalized : bool (default=True) + Normalize results by the sum of all of the values. + + Returns + ------- + (hubs,authorities) : two-tuple of dictionaries + Two dictionaries keyed by node containing the hub and authority + values. + + Raises + ------ + PowerIterationFailedConvergence + If the algorithm fails to converge to the specified tolerance + within the specified number of iterations of the power iteration + method. + + Examples + -------- + >>> G = nx.path_graph(4) + >>> h, a = nx.hits(G) + + Notes + ----- + The eigenvector calculation is done by the power iteration method + and has no guarantee of convergence. The iteration will stop + after max_iter iterations or an error tolerance of + number_of_nodes(G)*tol has been reached. + + The HITS algorithm was designed for directed graphs but this + algorithm does not check if the input graph is directed and will + execute on undirected graphs. + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Jon Kleinberg, + Authoritative sources in a hyperlinked environment + Journal of the ACM 46 (5): 604-32, 1999. + doi:10.1145/324133.324140. + http://www.cs.cornell.edu/home/kleinber/auth.pdf. + """ + import numpy as np + import scipy as sp + + if len(G) == 0: + return {}, {} + A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float) + + if nstart is not None: + nstart = np.array(list(nstart.values())) + if max_iter <= 0: + raise nx.PowerIterationFailedConvergence(max_iter) + try: + _, _, vt = sp.sparse.linalg.svds(A, k=1, v0=nstart, maxiter=max_iter, tol=tol) + except sp.sparse.linalg.ArpackNoConvergence as exc: + raise nx.PowerIterationFailedConvergence(max_iter) from exc + + a = vt.flatten().real + h = A @ a + if normalized: + h /= h.sum() + a /= a.sum() + hubs = dict(zip(G, map(float, h))) + authorities = dict(zip(G, map(float, a))) + return hubs, authorities + + +def _hits_python(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): + if isinstance(G, nx.MultiGraph | nx.MultiDiGraph): + raise Exception("hits() not defined for graphs with multiedges.") + if len(G) == 0: + return {}, {} + # choose fixed starting vector if not given + if nstart is None: + h = dict.fromkeys(G, 1.0 / G.number_of_nodes()) + else: + h = nstart + # normalize starting vector + s = 1.0 / sum(h.values()) + for k in h: + h[k] *= s + for _ in range(max_iter): # power iteration: make up to max_iter iterations + hlast = h + h = dict.fromkeys(hlast.keys(), 0) + a = dict.fromkeys(hlast.keys(), 0) + # this "matrix multiply" looks odd because it is + # doing a left multiply a^T=hlast^T*G + for n in h: + for nbr in G[n]: + a[nbr] += hlast[n] * G[n][nbr].get("weight", 1) + # now multiply h=Ga + for n in h: + for nbr in G[n]: + h[n] += a[nbr] * G[n][nbr].get("weight", 1) + # normalize vector + s = 1.0 / max(h.values()) + for n in h: + h[n] *= s + # normalize vector + s = 1.0 / max(a.values()) + for n in a: + a[n] *= s + # check convergence, l1 norm + err = sum(abs(h[n] - hlast[n]) for n in h) + if err < tol: + break + else: + raise nx.PowerIterationFailedConvergence(max_iter) + if normalized: + s = 1.0 / sum(a.values()) + for n in a: + a[n] *= s + s = 1.0 / sum(h.values()) + for n in h: + h[n] *= s + return h, a + + +def _hits_numpy(G, normalized=True): + """Returns HITS hubs and authorities values for nodes. + + The HITS algorithm computes two numbers for a node. + Authorities estimates the node value based on the incoming links. + Hubs estimates the node value based on outgoing links. + + Parameters + ---------- + G : graph + A NetworkX graph + + normalized : bool (default=True) + Normalize results by the sum of all of the values. + + Returns + ------- + (hubs,authorities) : two-tuple of dictionaries + Two dictionaries keyed by node containing the hub and authority + values. + + Examples + -------- + >>> G = nx.path_graph(4) + + The `hubs` and `authorities` are given by the eigenvectors corresponding to the + maximum eigenvalues of the hubs_matrix and the authority_matrix, respectively. + + The ``hubs`` and ``authority`` matrices are computed from the adjacency + matrix: + + >>> adj_ary = nx.to_numpy_array(G) + >>> hubs_matrix = adj_ary @ adj_ary.T + >>> authority_matrix = adj_ary.T @ adj_ary + + `_hits_numpy` maps the eigenvector corresponding to the maximum eigenvalue + of the respective matrices to the nodes in `G`: + + >>> from networkx.algorithms.link_analysis.hits_alg import _hits_numpy + >>> hubs, authority = _hits_numpy(G) + + Notes + ----- + The eigenvector calculation uses NumPy's interface to LAPACK. + + The HITS algorithm was designed for directed graphs but this + algorithm does not check if the input graph is directed and will + execute on undirected graphs. + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Jon Kleinberg, + Authoritative sources in a hyperlinked environment + Journal of the ACM 46 (5): 604-32, 1999. + doi:10.1145/324133.324140. + http://www.cs.cornell.edu/home/kleinber/auth.pdf. + """ + import numpy as np + + if len(G) == 0: + return {}, {} + adj_ary = nx.to_numpy_array(G) + # Hub matrix + H = adj_ary @ adj_ary.T + e, ev = np.linalg.eig(H) + h = ev[:, np.argmax(e)] # eigenvector corresponding to the maximum eigenvalue + # Authority matrix + A = adj_ary.T @ adj_ary + e, ev = np.linalg.eig(A) + a = ev[:, np.argmax(e)] # eigenvector corresponding to the maximum eigenvalue + if normalized: + h /= h.sum() + a /= a.sum() + else: + h /= h.max() + a /= a.max() + hubs = dict(zip(G, map(float, h))) + authorities = dict(zip(G, map(float, a))) + return hubs, authorities + + +def _hits_scipy(G, max_iter=100, tol=1.0e-6, nstart=None, normalized=True): + """Returns HITS hubs and authorities values for nodes. + + + The HITS algorithm computes two numbers for a node. + Authorities estimates the node value based on the incoming links. + Hubs estimates the node value based on outgoing links. + + Parameters + ---------- + G : graph + A NetworkX graph + + max_iter : integer, optional + Maximum number of iterations in power method. + + tol : float, optional + Error tolerance used to check convergence in power method iteration. + + nstart : dictionary, optional + Starting value of each node for power method iteration. + + normalized : bool (default=True) + Normalize results by the sum of all of the values. + + Returns + ------- + (hubs,authorities) : two-tuple of dictionaries + Two dictionaries keyed by node containing the hub and authority + values. + + Examples + -------- + >>> from networkx.algorithms.link_analysis.hits_alg import _hits_scipy + >>> G = nx.path_graph(4) + >>> h, a = _hits_scipy(G) + + Notes + ----- + This implementation uses SciPy sparse matrices. + + The eigenvector calculation is done by the power iteration method + and has no guarantee of convergence. The iteration will stop + after max_iter iterations or an error tolerance of + number_of_nodes(G)*tol has been reached. + + The HITS algorithm was designed for directed graphs but this + algorithm does not check if the input graph is directed and will + execute on undirected graphs. + + Raises + ------ + PowerIterationFailedConvergence + If the algorithm fails to converge to the specified tolerance + within the specified number of iterations of the power iteration + method. + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Jon Kleinberg, + Authoritative sources in a hyperlinked environment + Journal of the ACM 46 (5): 604-632, 1999. + doi:10.1145/324133.324140. + http://www.cs.cornell.edu/home/kleinber/auth.pdf. + """ + import numpy as np + + if len(G) == 0: + return {}, {} + A = nx.to_scipy_sparse_array(G, nodelist=list(G)) + (n, _) = A.shape # should be square + ATA = A.T @ A # authority matrix + # choose fixed starting vector if not given + if nstart is None: + x = np.ones((n, 1)) / n + else: + x = np.array([nstart.get(n, 0) for n in list(G)], dtype=float) + x /= x.sum() + + # power iteration on authority matrix + i = 0 + while True: + xlast = x + x = ATA @ x + x /= x.max() + # check convergence, l1 norm + err = np.absolute(x - xlast).sum() + if err < tol: + break + if i > max_iter: + raise nx.PowerIterationFailedConvergence(max_iter) + i += 1 + + a = x.flatten() + h = A @ a + if normalized: + h /= h.sum() + a /= a.sum() + hubs = dict(zip(G, map(float, h))) + authorities = dict(zip(G, map(float, a))) + return hubs, authorities diff --git a/shared/package-files/38/38a272a7d13cdf5cc9af1a117e633d0203a30721b5081fa9cc5e645d016668a9/bdist_wheel.py b/shared/package-files/38/38a272a7d13cdf5cc9af1a117e633d0203a30721b5081fa9cc5e645d016668a9/bdist_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..6b811ee3dfeb4d082260350172f7f4f3221b3192 --- /dev/null +++ b/shared/package-files/38/38a272a7d13cdf5cc9af1a117e633d0203a30721b5081fa9cc5e645d016668a9/bdist_wheel.py @@ -0,0 +1,595 @@ +""" +Create a wheel (.whl) distribution. + +A wheel is a built archive format. +""" + +from __future__ import annotations + +import os +import re +import shutil +import stat +import struct +import sys +import sysconfig +import warnings +from email.generator import BytesGenerator, Generator +from email.policy import EmailPolicy +from glob import iglob +from shutil import rmtree +from zipfile import ZIP_DEFLATED, ZIP_STORED + +import setuptools +from setuptools import Command + +from . import __version__ as wheel_version +from .macosx_libfile import calculate_macosx_platform_tag +from .metadata import pkginfo_to_metadata +from .util import log +from .vendored.packaging import tags +from .vendored.packaging import version as _packaging_version +from .wheelfile import WheelFile + + +def safe_name(name): + """Convert an arbitrary string to a standard distribution name + Any runs of non-alphanumeric/. characters are replaced with a single '-'. + """ + return re.sub("[^A-Za-z0-9.]+", "-", name) + + +def safe_version(version): + """ + Convert an arbitrary string to a standard version string + """ + try: + # normalize the version + return str(_packaging_version.Version(version)) + except _packaging_version.InvalidVersion: + version = version.replace(" ", ".") + return re.sub("[^A-Za-z0-9.]+", "-", version) + + +setuptools_major_version = int(setuptools.__version__.split(".")[0]) + +PY_LIMITED_API_PATTERN = r"cp3\d" + + +def _is_32bit_interpreter(): + return struct.calcsize("P") == 4 + + +def python_tag(): + return f"py{sys.version_info[0]}" + + +def get_platform(archive_root): + """Return our platform name 'win32', 'linux_x86_64'""" + result = sysconfig.get_platform() + if result.startswith("macosx") and archive_root is not None: + result = calculate_macosx_platform_tag(archive_root, result) + elif _is_32bit_interpreter(): + if result == "linux-x86_64": + # pip pull request #3497 + result = "linux-i686" + elif result == "linux-aarch64": + # packaging pull request #234 + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + result = "linux-armv7l" + + return result.replace("-", "_") + + +def get_flag(var, fallback, expected=True, warn=True): + """Use a fallback value for determining SOABI flags if the needed config + var is unset or unavailable.""" + val = sysconfig.get_config_var(var) + if val is None: + if warn: + warnings.warn( + f"Config variable '{var}' is unset, Python ABI tag may " "be incorrect", + RuntimeWarning, + stacklevel=2, + ) + return fallback + return val == expected + + +def get_abi_tag(): + """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2).""" + soabi = sysconfig.get_config_var("SOABI") + impl = tags.interpreter_name() + if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"): + d = "" + m = "" + u = "" + if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")): + d = "d" + + if get_flag( + "WITH_PYMALLOC", + impl == "cp", + warn=(impl == "cp" and sys.version_info < (3, 8)), + ) and sys.version_info < (3, 8): + m = "m" + + abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}" + elif soabi and impl == "cp" and soabi.startswith("cpython"): + # non-Windows + abi = "cp" + soabi.split("-")[1] + elif soabi and impl == "cp" and soabi.startswith("cp"): + # Windows + abi = soabi.split("-")[0] + elif soabi and impl == "pp": + # we want something like pypy36-pp73 + abi = "-".join(soabi.split("-")[:2]) + abi = abi.replace(".", "_").replace("-", "_") + elif soabi and impl == "graalpy": + abi = "-".join(soabi.split("-")[:3]) + abi = abi.replace(".", "_").replace("-", "_") + elif soabi: + abi = soabi.replace(".", "_").replace("-", "_") + else: + abi = None + + return abi + + +def safer_name(name): + return safe_name(name).replace("-", "_") + + +def safer_version(version): + return safe_version(version).replace("-", "_") + + +def remove_readonly(func, path, excinfo): + remove_readonly_exc(func, path, excinfo[1]) + + +def remove_readonly_exc(func, path, exc): + os.chmod(path, stat.S_IWRITE) + func(path) + + +class bdist_wheel(Command): + description = "create a wheel distribution" + + supported_compressions = { + "stored": ZIP_STORED, + "deflated": ZIP_DEFLATED, + } + + user_options = [ + ("bdist-dir=", "b", "temporary directory for creating the distribution"), + ( + "plat-name=", + "p", + "platform name to embed in generated filenames " + "(default: %s)" % get_platform(None), + ), + ( + "keep-temp", + "k", + "keep the pseudo-installation tree around after " + "creating the distribution archive", + ), + ("dist-dir=", "d", "directory to put final built distributions in"), + ("skip-build", None, "skip rebuilding everything (for testing/debugging)"), + ( + "relative", + None, + "build the archive using relative paths " "(default: false)", + ), + ( + "owner=", + "u", + "Owner name used when creating a tar file" " [default: current user]", + ), + ( + "group=", + "g", + "Group name used when creating a tar file" " [default: current group]", + ), + ("universal", None, "make a universal wheel" " (default: false)"), + ( + "compression=", + None, + "zipfile compression (one of: {})" " (default: 'deflated')".format( + ", ".join(supported_compressions) + ), + ), + ( + "python-tag=", + None, + "Python implementation compatibility tag" + " (default: '%s')" % (python_tag()), + ), + ( + "build-number=", + None, + "Build number for this particular version. " + "As specified in PEP-0427, this must start with a digit. " + "[default: None]", + ), + ( + "py-limited-api=", + None, + "Python tag (cp32|cp33|cpNN) for abi3 wheel tag" " (default: false)", + ), + ] + + boolean_options = ["keep-temp", "skip-build", "relative", "universal"] + + def initialize_options(self): + self.bdist_dir = None + self.data_dir = None + self.plat_name = None + self.plat_tag = None + self.format = "zip" + self.keep_temp = False + self.dist_dir = None + self.egginfo_dir = None + self.root_is_pure = None + self.skip_build = None + self.relative = False + self.owner = None + self.group = None + self.universal = False + self.compression = "deflated" + self.python_tag = python_tag() + self.build_number = None + self.py_limited_api = False + self.plat_name_supplied = False + + def finalize_options(self): + if self.bdist_dir is None: + bdist_base = self.get_finalized_command("bdist").bdist_base + self.bdist_dir = os.path.join(bdist_base, "wheel") + + egg_info = self.distribution.get_command_obj("egg_info") + egg_info.ensure_finalized() # needed for correct `wheel_dist_name` + + self.data_dir = self.wheel_dist_name + ".data" + self.plat_name_supplied = self.plat_name is not None + + try: + self.compression = self.supported_compressions[self.compression] + except KeyError: + raise ValueError(f"Unsupported compression: {self.compression}") from None + + need_options = ("dist_dir", "plat_name", "skip_build") + + self.set_undefined_options("bdist", *zip(need_options, need_options)) + + self.root_is_pure = not ( + self.distribution.has_ext_modules() or self.distribution.has_c_libraries() + ) + + if self.py_limited_api and not re.match( + PY_LIMITED_API_PATTERN, self.py_limited_api + ): + raise ValueError("py-limited-api must match '%s'" % PY_LIMITED_API_PATTERN) + + # Support legacy [wheel] section for setting universal + wheel = self.distribution.get_option_dict("wheel") + if "universal" in wheel: + # please don't define this in your global configs + log.warning( + "The [wheel] section is deprecated. Use [bdist_wheel] instead.", + ) + val = wheel["universal"][1].strip() + if val.lower() in ("1", "true", "yes"): + self.universal = True + + if self.build_number is not None and not self.build_number[:1].isdigit(): + raise ValueError("Build tag (build-number) must start with a digit.") + + @property + def wheel_dist_name(self): + """Return distribution full name with - replaced with _""" + components = ( + safer_name(self.distribution.get_name()), + safer_version(self.distribution.get_version()), + ) + if self.build_number: + components += (self.build_number,) + return "-".join(components) + + def get_tag(self): + # bdist sets self.plat_name if unset, we should only use it for purepy + # wheels if the user supplied it. + if self.plat_name_supplied: + plat_name = self.plat_name + elif self.root_is_pure: + plat_name = "any" + else: + # macosx contains system version in platform name so need special handle + if self.plat_name and not self.plat_name.startswith("macosx"): + plat_name = self.plat_name + else: + # on macosx always limit the platform name to comply with any + # c-extension modules in bdist_dir, since the user can specify + # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake + + # on other platforms, and on macosx if there are no c-extension + # modules, use the default platform name. + plat_name = get_platform(self.bdist_dir) + + if _is_32bit_interpreter(): + if plat_name in ("linux-x86_64", "linux_x86_64"): + plat_name = "linux_i686" + if plat_name in ("linux-aarch64", "linux_aarch64"): + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + plat_name = "linux_armv7l" + + plat_name = ( + plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_") + ) + + if self.root_is_pure: + if self.universal: + impl = "py2.py3" + else: + impl = self.python_tag + tag = (impl, "none", plat_name) + else: + impl_name = tags.interpreter_name() + impl_ver = tags.interpreter_version() + impl = impl_name + impl_ver + # We don't work on CPython 3.1, 3.0. + if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"): + impl = self.py_limited_api + abi_tag = "abi3" + else: + abi_tag = str(get_abi_tag()).lower() + tag = (impl, abi_tag, plat_name) + # issue gh-374: allow overriding plat_name + supported_tags = [ + (t.interpreter, t.abi, plat_name) for t in tags.sys_tags() + ] + assert ( + tag in supported_tags + ), f"would build wheel with unsupported tag {tag}" + return tag + + def run(self): + build_scripts = self.reinitialize_command("build_scripts") + build_scripts.executable = "python" + build_scripts.force = True + + build_ext = self.reinitialize_command("build_ext") + build_ext.inplace = False + + if not self.skip_build: + self.run_command("build") + + install = self.reinitialize_command("install", reinit_subcommands=True) + install.root = self.bdist_dir + install.compile = False + install.skip_build = self.skip_build + install.warn_dir = False + + # A wheel without setuptools scripts is more cross-platform. + # Use the (undocumented) `no_ep` option to setuptools' + # install_scripts command to avoid creating entry point scripts. + install_scripts = self.reinitialize_command("install_scripts") + install_scripts.no_ep = True + + # Use a custom scheme for the archive, because we have to decide + # at installation time which scheme to use. + for key in ("headers", "scripts", "data", "purelib", "platlib"): + setattr(install, "install_" + key, os.path.join(self.data_dir, key)) + + basedir_observed = "" + + if os.name == "nt": + # win32 barfs if any of these are ''; could be '.'? + # (distutils.command.install:change_roots bug) + basedir_observed = os.path.normpath(os.path.join(self.data_dir, "..")) + self.install_libbase = self.install_lib = basedir_observed + + setattr( + install, + "install_purelib" if self.root_is_pure else "install_platlib", + basedir_observed, + ) + + log.info(f"installing to {self.bdist_dir}") + + self.run_command("install") + + impl_tag, abi_tag, plat_tag = self.get_tag() + archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}" + if not self.relative: + archive_root = self.bdist_dir + else: + archive_root = os.path.join( + self.bdist_dir, self._ensure_relative(install.install_base) + ) + + self.set_undefined_options("install_egg_info", ("target", "egginfo_dir")) + distinfo_dirname = ( + f"{safer_name(self.distribution.get_name())}-" + f"{safer_version(self.distribution.get_version())}.dist-info" + ) + distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname) + self.egg2dist(self.egginfo_dir, distinfo_dir) + + self.write_wheelfile(distinfo_dir) + + # Make the archive + if not os.path.exists(self.dist_dir): + os.makedirs(self.dist_dir) + + wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl") + with WheelFile(wheel_path, "w", self.compression) as wf: + wf.write_files(archive_root) + + # Add to 'Distribution.dist_files' so that the "upload" command works + getattr(self.distribution, "dist_files", []).append( + ( + "bdist_wheel", + "{}.{}".format(*sys.version_info[:2]), # like 3.7 + wheel_path, + ) + ) + + if not self.keep_temp: + log.info(f"removing {self.bdist_dir}") + if not self.dry_run: + if sys.version_info < (3, 12): + rmtree(self.bdist_dir, onerror=remove_readonly) + else: + rmtree(self.bdist_dir, onexc=remove_readonly_exc) + + def write_wheelfile( + self, wheelfile_base, generator="bdist_wheel (" + wheel_version + ")" + ): + from email.message import Message + + msg = Message() + msg["Wheel-Version"] = "1.0" # of the spec + msg["Generator"] = generator + msg["Root-Is-Purelib"] = str(self.root_is_pure).lower() + if self.build_number is not None: + msg["Build"] = self.build_number + + # Doesn't work for bdist_wininst + impl_tag, abi_tag, plat_tag = self.get_tag() + for impl in impl_tag.split("."): + for abi in abi_tag.split("."): + for plat in plat_tag.split("."): + msg["Tag"] = "-".join((impl, abi, plat)) + + wheelfile_path = os.path.join(wheelfile_base, "WHEEL") + log.info(f"creating {wheelfile_path}") + with open(wheelfile_path, "wb") as f: + BytesGenerator(f, maxheaderlen=0).flatten(msg) + + def _ensure_relative(self, path): + # copied from dir_util, deleted + drive, path = os.path.splitdrive(path) + if path[0:1] == os.sep: + path = drive + path[1:] + return path + + @property + def license_paths(self): + if setuptools_major_version >= 57: + # Setuptools has resolved any patterns to actual file names + return self.distribution.metadata.license_files or () + + files = set() + metadata = self.distribution.get_option_dict("metadata") + if setuptools_major_version >= 42: + # Setuptools recognizes the license_files option but does not do globbing + patterns = self.distribution.metadata.license_files + else: + # Prior to those, wheel is entirely responsible for handling license files + if "license_files" in metadata: + patterns = metadata["license_files"][1].split() + else: + patterns = () + + if "license_file" in metadata: + warnings.warn( + 'The "license_file" option is deprecated. Use "license_files" instead.', + DeprecationWarning, + stacklevel=2, + ) + files.add(metadata["license_file"][1]) + + if not files and not patterns and not isinstance(patterns, list): + patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*") + + for pattern in patterns: + for path in iglob(pattern): + if path.endswith("~"): + log.debug( + f'ignoring license file "{path}" as it looks like a backup' + ) + continue + + if path not in files and os.path.isfile(path): + log.info( + f'adding license file "{path}" (matched pattern "{pattern}")' + ) + files.add(path) + + return files + + def egg2dist(self, egginfo_path, distinfo_path): + """Convert an .egg-info directory into a .dist-info directory""" + + def adios(p): + """Appropriately delete directory, file or link.""" + if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): + shutil.rmtree(p) + elif os.path.exists(p): + os.unlink(p) + + adios(distinfo_path) + + if not os.path.exists(egginfo_path): + # There is no egg-info. This is probably because the egg-info + # file/directory is not named matching the distribution name used + # to name the archive file. Check for this case and report + # accordingly. + import glob + + pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info") + possible = glob.glob(pat) + err = f"Egg metadata expected at {egginfo_path} but not found" + if possible: + alt = os.path.basename(possible[0]) + err += f" ({alt} found - possible misnamed archive file?)" + + raise ValueError(err) + + if os.path.isfile(egginfo_path): + # .egg-info is a single file + pkginfo_path = egginfo_path + pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path) + os.mkdir(distinfo_path) + else: + # .egg-info is a directory + pkginfo_path = os.path.join(egginfo_path, "PKG-INFO") + pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path) + + # ignore common egg metadata that is useless to wheel + shutil.copytree( + egginfo_path, + distinfo_path, + ignore=lambda x, y: { + "PKG-INFO", + "requires.txt", + "SOURCES.txt", + "not-zip-safe", + }, + ) + + # delete dependency_links if it is only whitespace + dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt") + with open(dependency_links_path, encoding="utf-8") as dependency_links_file: + dependency_links = dependency_links_file.read().strip() + if not dependency_links: + adios(dependency_links_path) + + pkg_info_path = os.path.join(distinfo_path, "METADATA") + serialization_policy = EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with open(pkg_info_path, "w", encoding="utf-8") as out: + Generator(out, policy=serialization_policy).flatten(pkg_info) + + for license_path in self.license_paths: + filename = os.path.basename(license_path) + shutil.copy(license_path, os.path.join(distinfo_path, filename)) + + adios(egginfo_path) diff --git a/shared/package-files/38/38a298592e54662a399a160ba3c10666bb8d9559f0eddb5e466ff8169d77ab3f/test_core_functionalities.cpython-311.pyc b/shared/package-files/38/38a298592e54662a399a160ba3c10666bb8d9559f0eddb5e466ff8169d77ab3f/test_core_functionalities.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a5177a7f5d51ac312fa7f9e496e5ae51383c7bf Binary files /dev/null and b/shared/package-files/38/38a298592e54662a399a160ba3c10666bb8d9559f0eddb5e466ff8169d77ab3f/test_core_functionalities.cpython-311.pyc differ diff --git a/shared/package-files/38/38a3093276ef118d730ae4377da6c8ce4d43e055757808b6558ae4dc0bf934f1/test_gaussopt.cpython-311.pyc b/shared/package-files/38/38a3093276ef118d730ae4377da6c8ce4d43e055757808b6558ae4dc0bf934f1/test_gaussopt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50ef1c5fb8e68ae3957d6c24ffd33d6e6c62583d Binary files /dev/null and b/shared/package-files/38/38a3093276ef118d730ae4377da6c8ce4d43e055757808b6558ae4dc0bf934f1/test_gaussopt.cpython-311.pyc differ diff --git a/shared/package-files/38/38a38e72ced134f2719ed0888d92461f3a8930b2ba52be5fb80c3e6f5c8dc1e0/_embedding_bag_forward_only_ops.h b/shared/package-files/38/38a38e72ced134f2719ed0888d92461f3a8930b2ba52be5fb80c3e6f5c8dc1e0/_embedding_bag_forward_only_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..65da88f81c09618d7aa67f973978d451913463ea --- /dev/null +++ b/shared/package-files/38/38a38e72ced134f2719ed0888d92461f3a8930b2ba52be5fb80c3e6f5c8dc1e0/_embedding_bag_forward_only_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _embedding_bag_forward_only { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional &, bool, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_embedding_bag_forward_only"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx); +}; + +struct TORCH_API _embedding_bag_forward_only_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional &, bool, int64_t, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_embedding_bag_forward_only"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_embedding_bag_forward_only.out(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!))"; + static ::std::tuple call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/38/38a7aced12db92746929750f74566e4607c51473e5ca52276500fc79eeebece7/List.h b/shared/package-files/38/38a7aced12db92746929750f74566e4607c51473e5ca52276500fc79eeebece7/List.h new file mode 100644 index 0000000000000000000000000000000000000000..4cb22831947f41efc44db148d43a3395f2883843 --- /dev/null +++ b/shared/package-files/38/38a7aced12db92746929750f74566e4607c51473e5ca52276500fc79eeebece7/List.h @@ -0,0 +1,491 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +class Tensor; +} +namespace c10 { +struct IValue; +template class List; +struct Type; + +namespace detail { + +struct ListImpl final : public c10::intrusive_ptr_target { + using list_type = std::vector; + + explicit TORCH_API ListImpl(list_type list_, TypePtr elementType_); + + list_type list; + + TypePtr elementType; + + intrusive_ptr copy() const { + return make_intrusive(list, elementType); + } + friend TORCH_API bool operator==(const ListImpl& lhs, const ListImpl& rhs); +}; +} + +namespace impl { + +template class ListIterator; + +template class ListElementReference; + +template +void swap(ListElementReference&& lhs, ListElementReference&& rhs) noexcept; + +template +bool operator==(const ListElementReference& lhs, const T& rhs); + +template +bool operator==(const T& lhs, const ListElementReference& rhs); + +template +struct ListElementConstReferenceTraits { + // In the general case, we use IValue::to(). + using const_reference = typename c10::detail::ivalue_to_const_ref_overload_return::type; +}; + +// There is no to() overload for std::optional. +template<> +struct ListElementConstReferenceTraits> { + using const_reference = std::optional>; +}; + +template +class ListElementReference final { +public: + operator std::conditional_t< + std::is_reference_v::type>, + const T&, + T>() const; + + ListElementReference& operator=(T&& new_value) &&; + + ListElementReference& operator=(const T& new_value) &&; + + // assigning another ref to this assigns the underlying value + ListElementReference& operator=(ListElementReference&& rhs) && noexcept; + + const IValue& get() const& { + return *iterator_; + } + + friend void swap(ListElementReference&& lhs, ListElementReference&& rhs) noexcept; + + ListElementReference(const ListElementReference&) = delete; + ListElementReference& operator=(const ListElementReference&) = delete; + ~ListElementReference() = default; + +private: + ListElementReference(Iterator iter) + : iterator_(iter) {} + + // allow moving, but only our friends (i.e. the List class) can move us + ListElementReference(ListElementReference&&) noexcept = default; + ListElementReference& operator=(ListElementReference&& rhs) & noexcept { + iterator_ = std::move(rhs.iterator_); + return *this; + } + + friend class List; + friend class ListIterator; + + Iterator iterator_; +}; + +// this wraps vector::iterator to make sure user code can't rely +// on it being the type of the underlying vector. +template +class ListIterator final { + public: + // C++17 friendly std::iterator implementation + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = ListElementReference; + + explicit ListIterator() = default; + ~ListIterator() = default; + + ListIterator(const ListIterator&) = default; + ListIterator(ListIterator&&) noexcept = default; + ListIterator& operator=(const ListIterator&) = default; + ListIterator& operator=(ListIterator&&) noexcept = default; + + ListIterator& operator++() { + ++iterator_; + return *this; + } + + ListIterator operator++(int) { + ListIterator copy(*this); + ++*this; + return copy; + } + + ListIterator& operator--() { + --iterator_; + return *this; + } + + ListIterator operator--(int) { + ListIterator copy(*this); + --*this; + return copy; + } + + ListIterator& operator+=(typename List::size_type offset) { + iterator_ += offset; + return *this; + } + + ListIterator& operator-=(typename List::size_type offset) { + iterator_ -= offset; + return *this; + } + + ListIterator operator+(typename List::size_type offset) const { + return ListIterator{iterator_ + offset}; + } + + ListIterator operator-(typename List::size_type offset) const { + return ListIterator{iterator_ - offset}; + } + + friend difference_type operator-(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ - rhs.iterator_; + } + + ListElementReference operator*() const { + return {iterator_}; + } + + ListElementReference operator[](typename List::size_type offset) const { + return {iterator_ + offset}; + } + +private: + explicit ListIterator(Iterator iterator): iterator_(std::move(iterator)) {} + + Iterator iterator_; + + friend bool operator==(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ == rhs.iterator_; + } + + friend bool operator!=(const ListIterator& lhs, const ListIterator& rhs) { + return !(lhs == rhs); + } + + friend bool operator<(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ < rhs.iterator_; + } + + friend bool operator<=(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ <= rhs.iterator_; + } + + friend bool operator>(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ > rhs.iterator_; + } + + friend bool operator>=(const ListIterator& lhs, const ListIterator& rhs) { + return lhs.iterator_ >= rhs.iterator_; + } + + friend class ListIterator; + friend class List; +}; + +template List toTypedList(List list); +template List toList(List&& list); +template List toList(const List& list); +const IValue* ptr_to_first_element(const List& list); +} + +/** + * An object of this class stores a list of values of type T. + * + * This is a pointer type. After a copy, both Lists + * will share the same storage: + * + * > List a; + * > List b = a; + * > b.push_back("three"); + * > ASSERT("three" == a.get(0)); + * + * We use this class in the PyTorch kernel API instead of + * std::vector, because that allows us to do optimizations + * and switch out the underlying list implementation without + * breaking backwards compatibility for the kernel API. + */ +template +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +class List final { +private: + // This is an intrusive_ptr because List is a pointer type. + // Invariant: This will never be a nullptr, there will always be a valid + // ListImpl. + c10::intrusive_ptr impl_; + + using internal_reference_type = impl::ListElementReference; + using internal_const_reference_type = typename impl::ListElementConstReferenceTraits::const_reference; + +public: + using value_type = T; + using size_type = typename c10::detail::ListImpl::list_type::size_type; + using iterator = impl::ListIterator; + using const_iterator = impl::ListIterator; + using reverse_iterator = impl::ListIterator; + + /** + * Constructs an empty list. + */ + explicit List(); + + /** + * Constructs a list with some initial values. + * Example: + * List a({2, 3, 4}); + */ + List(std::initializer_list initial_values); + explicit List(ArrayRef initial_values); + + /** + * Create a generic list with runtime type information. + * This only works for c10::impl::GenericList and is not part of the public API + * but only supposed to be used internally by PyTorch. + */ + explicit List(TypePtr elementType); + + List(const List&) = default; + List& operator=(const List&) = default; + ~List() = default; + + /** + * Create a new List pointing to a deep copy of the same data. + * The List returned is a new list with separate storage. + * Changes in it are not reflected in the original list or vice versa. + */ + List copy() const; + + /** + * Returns the element at specified location pos, with bounds checking. + * If pos is not within the range of the container, an exception of type std::out_of_range is thrown. + */ + internal_const_reference_type get(size_type pos) const; + + /** + * Moves out the element at the specified location pos and returns it, with bounds checking. + * If pos is not within the range of the container, an exception of type std::out_of_range is thrown. + * The list contains an invalid element at position pos afterwards. Any operations + * on it before re-setting it are invalid. + */ + value_type extract(size_type pos) const; + + /** + * Returns a reference to the element at specified location pos, with bounds checking. + * If pos is not within the range of the container, an exception of type std::out_of_range is thrown. + * + * You cannot store the reference, but you can read it and assign new values to it: + * + * List list = ...; + * list[2] = 5; + * int64_t v = list[1]; + */ + internal_const_reference_type operator[](size_type pos) const; + + internal_reference_type operator[](size_type pos); + + /** + * Assigns a new value to the element at location pos. + */ + void set(size_type pos, const value_type& value) const; + + /** + * Assigns a new value to the element at location pos. + */ + void set(size_type pos, value_type&& value) const; + + /** + * Returns an iterator to the first element of the container. + * If the container is empty, the returned iterator will be equal to end(). + */ + iterator begin() const; + + /** + * Returns an iterator to the element following the last element of the container. + * This element acts as a placeholder; attempting to access it results in undefined behavior. + */ + iterator end() const; + + /** + * Checks if the container has no elements. + */ + bool empty() const; + + /** + * Returns the number of elements in the container + */ + size_type size() const; + + /** + * Increase the capacity of the vector to a value that's greater or equal to new_cap. + */ + void reserve(size_type new_cap) const; + + /** + * Erases all elements from the container. After this call, size() returns zero. + * Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated. + */ + void clear() const; + + /** + * Inserts value before pos. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + iterator insert(iterator pos, const T& value) const; + + /** + * Inserts value before pos. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + iterator insert(iterator pos, T&& value) const; + + /** + * Inserts a new element into the container directly before pos. + * The new element is constructed with the given arguments. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + template + iterator emplace(iterator pos, Args&&... value) const; + + /** + * Appends the given element value to the end of the container. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void push_back(const T& value) const; + + /** + * Appends the given element value to the end of the container. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void push_back(T&& value) const; + + /** + * Appends the given list to the end of the container. Uses at most one memory allocation. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void append(List lst) const; + + /** + * Appends the given element value to the end of the container. + * The new element is constructed with the given arguments. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + template + void emplace_back(Args&&... args) const; + + /** + * Removes the element at pos. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + iterator erase(iterator pos) const; + + /** + * Removes the elements in the range [first, last). + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + iterator erase(iterator first, iterator last) const; + + /** + * Removes the last element of the container. + * Calling pop_back on an empty container is undefined. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void pop_back() const; + + /** + * Resizes the container to contain count elements. + * If the current size is less than count, additional default-inserted elements are appended. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void resize(size_type count) const; + + /** + * Resizes the container to contain count elements. + * If the current size is less than count, additional copies of value are appended. + * May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated. + */ + void resize(size_type count, const T& value) const; + + /** + * Value equality comparison. This function implements Python-like semantics for + * equality: two lists with the same identity (e.g. same pointer) trivially + * compare equal, otherwise each element is compared for equality. + */ + template + friend bool operator==(const List& lhs, const List& rhs); + + template + friend bool operator!=(const List& lhs, const List& rhs); + + /** + * Identity comparison. Returns true if and only if `rhs` represents the same + * List object as `this`. + */ + bool is(const List& rhs) const; + + std::vector vec() const; + + /** + * Returns the number of Lists currently pointing to this same list. + * If this is the only instance pointing to this list, returns 1. + */ + // TODO Test use_count + size_t use_count() const; + + TypePtr elementType() const; + + // See [unsafe set type] for why this exists. + void unsafeSetElementType(TypePtr t); + +private: + explicit List(c10::intrusive_ptr&& elements); + explicit List(const c10::intrusive_ptr& elements); + friend struct IValue; + template friend List impl::toTypedList(List); + template friend List impl::toList(List&&); + template friend List impl::toList(const List&); + friend const IValue* impl::ptr_to_first_element(const List& list); +}; + +namespace impl { +// GenericList is how IValue stores lists. It is, however, not part of the +// public API. Kernels should use Lists with concrete types instead +// (maybe except for some internal prim ops). +using GenericList = List; + +} +} + +namespace torch { + template using List = c10::List; +} + +#include // IWYU pragma: keep diff --git a/shared/package-files/38/38a8d7aa0dcf47c0eca732f277241d9f8cde1b28b7ba71feeaa2b07768f98b2b/sinc_meta.h b/shared/package-files/38/38a8d7aa0dcf47c0eca732f277241d9f8cde1b28b7ba71feeaa2b07768f98b2b/sinc_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..5de51db4f4c52ee41381f16b96f8b53f9d28e1ca --- /dev/null +++ b/shared/package-files/38/38a8d7aa0dcf47c0eca732f277241d9f8cde1b28b7ba71feeaa2b07768f98b2b/sinc_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_sinc : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38abc4ba98b85be6c4f67d62c541d1dd0068da63811bbe143f0790007e8b978d/__init__.py b/shared/package-files/38/38abc4ba98b85be6c4f67d62c541d1dd0068da63811bbe143f0790007e8b978d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5af9ed93e92b98248a42fd30f1aa29385fa9f486 --- /dev/null +++ b/shared/package-files/38/38abc4ba98b85be6c4f67d62c541d1dd0068da63811bbe143f0790007e8b978d/__init__.py @@ -0,0 +1,47 @@ +from . import parametrizations, rnn, stateless +from .clip_grad import ( + _clip_grads_with_norm_ as clip_grads_with_norm_, + _get_total_norm as get_total_norm, + clip_grad_norm, + clip_grad_norm_, + clip_grad_value_, +) +from .convert_parameters import parameters_to_vector, vector_to_parameters +from .fusion import ( + fuse_conv_bn_eval, + fuse_conv_bn_weights, + fuse_linear_bn_eval, + fuse_linear_bn_weights, +) +from .init import skip_init +from .memory_format import ( + convert_conv2d_weight_memory_format, + convert_conv3d_weight_memory_format, +) +from .spectral_norm import remove_spectral_norm, spectral_norm +from .weight_norm import remove_weight_norm, weight_norm + + +__all__ = [ + "clip_grad_norm", + "clip_grad_norm_", + "clip_grads_with_norm_", + "clip_grad_value_", + "convert_conv2d_weight_memory_format", + "convert_conv3d_weight_memory_format", + "fuse_conv_bn_eval", + "fuse_conv_bn_weights", + "fuse_linear_bn_eval", + "fuse_linear_bn_weights", + "get_total_norm", + "parameters_to_vector", + "parametrizations", + "remove_spectral_norm", + "remove_weight_norm", + "rnn", + "skip_init", + "spectral_norm", + "stateless", + "vector_to_parameters", + "weight_norm", +] diff --git a/shared/package-files/38/38acf0316edfd394d15c0113b0a837e0f5757f7b116c69808f58f5eb9d0907e1/ccompiler.py b/shared/package-files/38/38acf0316edfd394d15c0113b0a837e0f5757f7b116c69808f58f5eb9d0907e1/ccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..714f13d8d30060542139ccf94c798e34134c0d98 --- /dev/null +++ b/shared/package-files/38/38acf0316edfd394d15c0113b0a837e0f5757f7b116c69808f58f5eb9d0907e1/ccompiler.py @@ -0,0 +1,1263 @@ +"""distutils.ccompiler + +Contains CCompiler, an abstract base class that defines the interface +for the Distutils compiler abstraction model.""" + +import os +import pathlib +import re +import sys +import types +import warnings + +from more_itertools import always_iterable + +from ._log import log +from ._modified import newer_group +from .dir_util import mkpath +from .errors import ( + CompileError, + DistutilsModuleError, + DistutilsPlatformError, + LinkError, + UnknownFileError, +) +from .file_util import move_file +from .spawn import spawn +from .util import execute, is_mingw, split_quoted + + +class CCompiler: + """Abstract base class to define the interface that must be implemented + by real compiler classes. Also has some utility methods used by + several compiler classes. + + The basic idea behind a compiler abstraction class is that each + instance can be used for all the compile/link steps in building a + single project. Thus, attributes common to all of those compile and + link steps -- include directories, macros to define, libraries to link + against, etc. -- are attributes of the compiler instance. To allow for + variability in how individual files are treated, most of those + attributes may be varied on a per-compilation or per-link basis. + """ + + # 'compiler_type' is a class attribute that identifies this class. It + # keeps code that wants to know what kind of compiler it's dealing with + # from having to import all possible compiler classes just to do an + # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type' + # should really, really be one of the keys of the 'compiler_class' + # dictionary (see below -- used by the 'new_compiler()' factory + # function) -- authors of new compiler interface classes are + # responsible for updating 'compiler_class'! + compiler_type = None + + # XXX things not handled by this compiler abstraction model: + # * client can't provide additional options for a compiler, + # e.g. warning, optimization, debugging flags. Perhaps this + # should be the domain of concrete compiler abstraction classes + # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base + # class should have methods for the common ones. + # * can't completely override the include or library searchg + # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2". + # I'm not sure how widely supported this is even by Unix + # compilers, much less on other platforms. And I'm even less + # sure how useful it is; maybe for cross-compiling, but + # support for that is a ways off. (And anyways, cross + # compilers probably have a dedicated binary with the + # right paths compiled in. I hope.) + # * can't do really freaky things with the library list/library + # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against + # different versions of libfoo.a in different locations. I + # think this is useless without the ability to null out the + # library search path anyways. + + # Subclasses that rely on the standard filename generation methods + # implemented below should override these; see the comment near + # those methods ('object_filenames()' et. al.) for details: + src_extensions = None # list of strings + obj_extension = None # string + static_lib_extension = None + shared_lib_extension = None # string + static_lib_format = None # format string + shared_lib_format = None # prob. same as static_lib_format + exe_extension = None # string + + # Default language settings. language_map is used to detect a source + # file or Extension target language, checking source filenames. + # language_order is used to detect the language precedence, when deciding + # what language to use when mixing source types. For example, if some + # extension has two files with ".c" extension, and one with ".cpp", it + # is still linked as c++. + language_map = { + ".c": "c", + ".cc": "c++", + ".cpp": "c++", + ".cxx": "c++", + ".m": "objc", + } + language_order = ["c++", "objc", "c"] + + include_dirs = [] + """ + include dirs specific to this compiler class + """ + + library_dirs = [] + """ + library dirs specific to this compiler class + """ + + def __init__(self, verbose=False, dry_run=False, force=False): + self.dry_run = dry_run + self.force = force + self.verbose = verbose + + # 'output_dir': a common output directory for object, library, + # shared object, and shared library files + self.output_dir = None + + # 'macros': a list of macro definitions (or undefinitions). A + # macro definition is a 2-tuple (name, value), where the value is + # either a string or None (no explicit value). A macro + # undefinition is a 1-tuple (name,). + self.macros = [] + + # 'include_dirs': a list of directories to search for include files + self.include_dirs = [] + + # 'libraries': a list of libraries to include in any link + # (library names, not filenames: eg. "foo" not "libfoo.a") + self.libraries = [] + + # 'library_dirs': a list of directories to search for libraries + self.library_dirs = [] + + # 'runtime_library_dirs': a list of directories to search for + # shared libraries/objects at runtime + self.runtime_library_dirs = [] + + # 'objects': a list of object files (or similar, such as explicitly + # named library files) to include on any link + self.objects = [] + + for key in self.executables.keys(): + self.set_executable(key, self.executables[key]) + + def set_executables(self, **kwargs): + """Define the executables (and options for them) that will be run + to perform the various stages of compilation. The exact set of + executables that may be specified here depends on the compiler + class (via the 'executables' class attribute), but most will have: + compiler the C/C++ compiler + linker_so linker used to create shared objects and libraries + linker_exe linker used to create binary executables + archiver static library creator + + On platforms with a command-line (Unix, DOS/Windows), each of these + is a string that will be split into executable name and (optional) + list of arguments. (Splitting the string is done similarly to how + Unix shells operate: words are delimited by spaces, but quotes and + backslashes can override this. See + 'distutils.util.split_quoted()'.) + """ + + # Note that some CCompiler implementation classes will define class + # attributes 'cpp', 'cc', etc. with hard-coded executable names; + # this is appropriate when a compiler class is for exactly one + # compiler/OS combination (eg. MSVCCompiler). Other compiler + # classes (UnixCCompiler, in particular) are driven by information + # discovered at run-time, since there are many different ways to do + # basically the same things with Unix C compilers. + + for key in kwargs: + if key not in self.executables: + raise ValueError( + f"unknown executable '{key}' for class {self.__class__.__name__}" + ) + self.set_executable(key, kwargs[key]) + + def set_executable(self, key, value): + if isinstance(value, str): + setattr(self, key, split_quoted(value)) + else: + setattr(self, key, value) + + def _find_macro(self, name): + i = 0 + for defn in self.macros: + if defn[0] == name: + return i + i += 1 + return None + + def _check_macro_definitions(self, definitions): + """Ensure that every element of 'definitions' is valid.""" + for defn in definitions: + self._check_macro_definition(*defn) + + def _check_macro_definition(self, defn): + """ + Raise a TypeError if defn is not valid. + + A valid definition is either a (name, value) 2-tuple or a (name,) tuple. + """ + if not isinstance(defn, tuple) or not self._is_valid_macro(*defn): + raise TypeError( + f"invalid macro definition '{defn}': " + "must be tuple (string,), (string, string), or (string, None)" + ) + + @staticmethod + def _is_valid_macro(name, value=None): + """ + A valid macro is a ``name : str`` and a ``value : str | None``. + """ + return isinstance(name, str) and isinstance(value, (str, types.NoneType)) + + # -- Bookkeeping methods ------------------------------------------- + + def define_macro(self, name, value=None): + """Define a preprocessor macro for all compilations driven by this + compiler object. The optional parameter 'value' should be a + string; if it is not supplied, then the macro will be defined + without an explicit value and the exact outcome depends on the + compiler used (XXX true? does ANSI say anything about this?) + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + self.macros.append((name, value)) + + def undefine_macro(self, name): + """Undefine a preprocessor macro for all compilations driven by + this compiler object. If the same macro is defined by + 'define_macro()' and undefined by 'undefine_macro()' the last call + takes precedence (including multiple redefinitions or + undefinitions). If the macro is redefined/undefined on a + per-compilation basis (ie. in the call to 'compile()'), then that + takes precedence. + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + undefn = (name,) + self.macros.append(undefn) + + def add_include_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + header files. The compiler is instructed to search directories in + the order in which they are supplied by successive calls to + 'add_include_dir()'. + """ + self.include_dirs.append(dir) + + def set_include_dirs(self, dirs): + """Set the list of directories that will be searched to 'dirs' (a + list of strings). Overrides any preceding calls to + 'add_include_dir()'; subsequence calls to 'add_include_dir()' add + to the list passed to 'set_include_dirs()'. This does not affect + any list of standard include directories that the compiler may + search by default. + """ + self.include_dirs = dirs[:] + + def add_library(self, libname): + """Add 'libname' to the list of libraries that will be included in + all links driven by this compiler object. Note that 'libname' + should *not* be the name of a file containing a library, but the + name of the library itself: the actual filename will be inferred by + the linker, the compiler, or the compiler class (depending on the + platform). + + The linker will be instructed to link against libraries in the + order they were supplied to 'add_library()' and/or + 'set_libraries()'. It is perfectly valid to duplicate library + names; the linker will be instructed to link against libraries as + many times as they are mentioned. + """ + self.libraries.append(libname) + + def set_libraries(self, libnames): + """Set the list of libraries to be included in all links driven by + this compiler object to 'libnames' (a list of strings). This does + not affect any standard system libraries that the linker may + include by default. + """ + self.libraries = libnames[:] + + def add_library_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + libraries specified to 'add_library()' and 'set_libraries()'. The + linker will be instructed to search for libraries in the order they + are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. + """ + self.library_dirs.append(dir) + + def set_library_dirs(self, dirs): + """Set the list of library search directories to 'dirs' (a list of + strings). This does not affect any standard library search path + that the linker may search by default. + """ + self.library_dirs = dirs[:] + + def add_runtime_library_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + shared libraries at runtime. + """ + self.runtime_library_dirs.append(dir) + + def set_runtime_library_dirs(self, dirs): + """Set the list of directories to search for shared libraries at + runtime to 'dirs' (a list of strings). This does not affect any + standard search path that the runtime linker may search by + default. + """ + self.runtime_library_dirs = dirs[:] + + def add_link_object(self, object): + """Add 'object' to the list of object files (or analogues, such as + explicitly named library files or the output of "resource + compilers") to be included in every link driven by this compiler + object. + """ + self.objects.append(object) + + def set_link_objects(self, objects): + """Set the list of object files (or analogues) to be included in + every link to 'objects'. This does not affect any standard object + files that the linker may include by default (such as system + libraries). + """ + self.objects = objects[:] + + # -- Private utility methods -------------------------------------- + # (here for the convenience of subclasses) + + # Helper method to prep compiler in subclass compile() methods + + def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): + """Process arguments and decide which source files to compile.""" + outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs) + + if extra is None: + extra = [] + + # Get the list of expected output (object) files + objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir) + assert len(objects) == len(sources) + + pp_opts = gen_preprocess_options(macros, incdirs) + + build = {} + for i in range(len(sources)): + src = sources[i] + obj = objects[i] + ext = os.path.splitext(src)[1] + self.mkpath(os.path.dirname(obj)) + build[obj] = (src, ext) + + return macros, objects, extra, pp_opts, build + + def _get_cc_args(self, pp_opts, debug, before): + # works for unixccompiler, cygwinccompiler + cc_args = pp_opts + ['-c'] + if debug: + cc_args[:0] = ['-g'] + if before: + cc_args[:0] = before + return cc_args + + def _fix_compile_args(self, output_dir, macros, include_dirs): + """Typecheck and fix-up some of the arguments to the 'compile()' + method, and return fixed-up values. Specifically: if 'output_dir' + is None, replaces it with 'self.output_dir'; ensures that 'macros' + is a list, and augments it with 'self.macros'; ensures that + 'include_dirs' is a list, and augments it with 'self.include_dirs'. + Guarantees that the returned values are of the correct type, + i.e. for 'output_dir' either string or None, and for 'macros' and + 'include_dirs' either list or None. + """ + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + if macros is None: + macros = list(self.macros) + elif isinstance(macros, list): + macros = macros + (self.macros or []) + else: + raise TypeError("'macros' (if supplied) must be a list of tuples") + + if include_dirs is None: + include_dirs = list(self.include_dirs) + elif isinstance(include_dirs, (list, tuple)): + include_dirs = list(include_dirs) + (self.include_dirs or []) + else: + raise TypeError("'include_dirs' (if supplied) must be a list of strings") + + # add include dirs for class + include_dirs += self.__class__.include_dirs + + return output_dir, macros, include_dirs + + def _prep_compile(self, sources, output_dir, depends=None): + """Decide which source files must be recompiled. + + Determine the list of object files corresponding to 'sources', + and figure out which ones really need to be recompiled. + Return a list of all object files and a dictionary telling + which source files can be skipped. + """ + # Get the list of expected output (object) files + objects = self.object_filenames(sources, output_dir=output_dir) + assert len(objects) == len(sources) + + # Return an empty dict for the "which source files can be skipped" + # return value to preserve API compatibility. + return objects, {} + + def _fix_object_args(self, objects, output_dir): + """Typecheck and fix up some arguments supplied to various methods. + Specifically: ensure that 'objects' is a list; if output_dir is + None, replace with self.output_dir. Return fixed versions of + 'objects' and 'output_dir'. + """ + if not isinstance(objects, (list, tuple)): + raise TypeError("'objects' must be a list or tuple of strings") + objects = list(objects) + + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + return (objects, output_dir) + + def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs): + """Typecheck and fix up some of the arguments supplied to the + 'link_*' methods. Specifically: ensure that all arguments are + lists, and augment them with their permanent versions + (eg. 'self.libraries' augments 'libraries'). Return a tuple with + fixed versions of all arguments. + """ + if libraries is None: + libraries = list(self.libraries) + elif isinstance(libraries, (list, tuple)): + libraries = list(libraries) + (self.libraries or []) + else: + raise TypeError("'libraries' (if supplied) must be a list of strings") + + if library_dirs is None: + library_dirs = list(self.library_dirs) + elif isinstance(library_dirs, (list, tuple)): + library_dirs = list(library_dirs) + (self.library_dirs or []) + else: + raise TypeError("'library_dirs' (if supplied) must be a list of strings") + + # add library dirs for class + library_dirs += self.__class__.library_dirs + + if runtime_library_dirs is None: + runtime_library_dirs = list(self.runtime_library_dirs) + elif isinstance(runtime_library_dirs, (list, tuple)): + runtime_library_dirs = list(runtime_library_dirs) + ( + self.runtime_library_dirs or [] + ) + else: + raise TypeError( + "'runtime_library_dirs' (if supplied) must be a list of strings" + ) + + return (libraries, library_dirs, runtime_library_dirs) + + def _need_link(self, objects, output_file): + """Return true if we need to relink the files listed in 'objects' + to recreate 'output_file'. + """ + if self.force: + return True + else: + if self.dry_run: + newer = newer_group(objects, output_file, missing='newer') + else: + newer = newer_group(objects, output_file) + return newer + + def detect_language(self, sources): + """Detect the language of a given file, or list of files. Uses + language_map, and language_order to do the job. + """ + if not isinstance(sources, list): + sources = [sources] + lang = None + index = len(self.language_order) + for source in sources: + base, ext = os.path.splitext(source) + extlang = self.language_map.get(ext) + try: + extindex = self.language_order.index(extlang) + if extindex < index: + lang = extlang + index = extindex + except ValueError: + pass + return lang + + # -- Worker methods ------------------------------------------------ + # (must be implemented by subclasses) + + def preprocess( + self, + source, + output_file=None, + macros=None, + include_dirs=None, + extra_preargs=None, + extra_postargs=None, + ): + """Preprocess a single C/C++ source file, named in 'source'. + Output will be written to file named 'output_file', or stdout if + 'output_file' not supplied. 'macros' is a list of macro + definitions as for 'compile()', which will augment the macros set + with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a + list of directory names that will be added to the default list. + + Raises PreprocessError on failure. + """ + pass + + def compile( + self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + """Compile one or more source files. + + 'sources' must be a list of filenames, most likely C/C++ + files, but in reality anything that can be handled by a + particular compiler and compiler class (eg. MSVCCompiler can + handle resource files in 'sources'). Return a list of object + filenames, one per source filename in 'sources'. Depending on + the implementation, not all source files will necessarily be + compiled, but all corresponding object filenames will be + returned. + + If 'output_dir' is given, object files will be put under it, while + retaining their original path component. That is, "foo/bar.c" + normally compiles to "foo/bar.o" (for a Unix implementation); if + 'output_dir' is "build", then it would compile to + "build/foo/bar.o". + + 'macros', if given, must be a list of macro definitions. A macro + definition is either a (name, value) 2-tuple or a (name,) 1-tuple. + The former defines a macro; if the value is None, the macro is + defined without an explicit value. The 1-tuple case undefines a + macro. Later definitions/redefinitions/ undefinitions take + precedence. + + 'include_dirs', if given, must be a list of strings, the + directories to add to the default include file search path for this + compilation only. + + 'debug' is a boolean; if true, the compiler will be instructed to + output debug symbols in (or alongside) the object file(s). + + 'extra_preargs' and 'extra_postargs' are implementation- dependent. + On platforms that have the notion of a command-line (e.g. Unix, + DOS/Windows), they are most likely lists of strings: extra + command-line arguments to prepend/append to the compiler command + line. On other platforms, consult the implementation class + documentation. In any event, they are intended as an escape hatch + for those occasions when the abstract compiler framework doesn't + cut the mustard. + + 'depends', if given, is a list of filenames that all targets + depend on. If a source file is older than any file in + depends, then the source file will be recompiled. This + supports dependency tracking, but only at a coarse + granularity. + + Raises CompileError on failure. + """ + # A concrete compiler class can either override this method + # entirely or implement _compile(). + macros, objects, extra_postargs, pp_opts, build = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) + + # Return *all* object filenames, not just the ones we just built. + return objects + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compile 'src' to product 'obj'.""" + # A concrete compiler class that does not override compile() + # should implement _compile(). + pass + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + """Link a bunch of stuff together to create a static library file. + The "bunch of stuff" consists of the list of object files supplied + as 'objects', the extra object files supplied to + 'add_link_object()' and/or 'set_link_objects()', the libraries + supplied to 'add_library()' and/or 'set_libraries()', and the + libraries supplied as 'libraries' (if any). + + 'output_libname' should be a library name, not a filename; the + filename will be inferred from the library name. 'output_dir' is + the directory where the library file will be put. + + 'debug' is a boolean; if true, debugging information will be + included in the library (note that on most platforms, it is the + compile step where this matters: the 'debug' flag is included here + just for consistency). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LibError on failure. + """ + pass + + # values for target_desc parameter in link() + SHARED_OBJECT = "shared_object" + SHARED_LIBRARY = "shared_library" + EXECUTABLE = "executable" + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + """Link a bunch of stuff together to create an executable or + shared library file. + + The "bunch of stuff" consists of the list of object files supplied + as 'objects'. 'output_filename' should be a filename. If + 'output_dir' is supplied, 'output_filename' is relative to it + (i.e. 'output_filename' can provide directory components if + needed). + + 'libraries' is a list of libraries to link against. These are + library names, not filenames, since they're translated into + filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" + on Unix and "foo.lib" on DOS/Windows). However, they can include a + directory component, which means the linker will look in that + specific directory rather than searching all the normal locations. + + 'library_dirs', if supplied, should be a list of directories to + search for libraries that were specified as bare library names + (ie. no directory component). These are on top of the system + default and those supplied to 'add_library_dir()' and/or + 'set_library_dirs()'. 'runtime_library_dirs' is a list of + directories that will be embedded into the shared library and used + to search for other shared libraries that *it* depends on at + run-time. (This may only be relevant on Unix.) + + 'export_symbols' is a list of symbols that the shared library will + export. (This appears to be relevant only on Windows.) + + 'debug' is as for 'compile()' and 'create_static_lib()', with the + slight distinction that it actually matters on most platforms (as + opposed to 'create_static_lib()', which includes a 'debug' flag + mostly for form's sake). + + 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except + of course that they supply command-line arguments for the + particular linker being used). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LinkError on failure. + """ + raise NotImplementedError + + # Old 'link_*()' methods, rewritten to use the new 'link()' method. + + def link_shared_lib( + self, + objects, + output_libname, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + self.link( + CCompiler.SHARED_LIBRARY, + objects, + self.library_filename(output_libname, lib_type='shared'), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_shared_object( + self, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + self.link( + CCompiler.SHARED_OBJECT, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_executable( + self, + objects, + output_progname, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + target_lang=None, + ): + self.link( + CCompiler.EXECUTABLE, + objects, + self.executable_filename(output_progname), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, + debug, + extra_preargs, + extra_postargs, + None, + target_lang, + ) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function; there is + # no appropriate default implementation so subclasses should + # implement all of these. + + def library_dir_option(self, dir): + """Return the compiler option to add 'dir' to the list of + directories searched for libraries. + """ + raise NotImplementedError + + def runtime_library_dir_option(self, dir): + """Return the compiler option to add 'dir' to the list of + directories searched for runtime libraries. + """ + raise NotImplementedError + + def library_option(self, lib): + """Return the compiler option to add 'lib' to the list of libraries + linked into the shared library or executable. + """ + raise NotImplementedError + + def has_function( # noqa: C901 + self, + funcname, + includes=None, + include_dirs=None, + libraries=None, + library_dirs=None, + ): + """Return a boolean indicating whether funcname is provided as + a symbol on the current platform. The optional arguments can + be used to augment the compilation environment. + + The libraries argument is a list of flags to be passed to the + linker to make additional symbol definitions available for + linking. + + The includes and include_dirs arguments are deprecated. + Usually, supplying include files with function declarations + will cause function detection to fail even in cases where the + symbol is available for linking. + + """ + # this can't be included at module scope because it tries to + # import math which might not be available at that point - maybe + # the necessary logic should just be inlined? + import tempfile + + if includes is None: + includes = [] + else: + warnings.warn("includes is deprecated", DeprecationWarning) + if include_dirs is None: + include_dirs = [] + else: + warnings.warn("include_dirs is deprecated", DeprecationWarning) + if libraries is None: + libraries = [] + if library_dirs is None: + library_dirs = [] + fd, fname = tempfile.mkstemp(".c", funcname, text=True) + with os.fdopen(fd, "w", encoding='utf-8') as f: + for incl in includes: + f.write(f"""#include "{incl}"\n""") + if not includes: + # Use "char func(void);" as the prototype to follow + # what autoconf does. This prototype does not match + # any well-known function the compiler might recognize + # as a builtin, so this ends up as a true link test. + # Without a fake prototype, the test would need to + # know the exact argument types, and the has_function + # interface does not provide that level of information. + f.write( + f"""\ +#ifdef __cplusplus +extern "C" +#endif +char {funcname}(void); +""" + ) + f.write( + f"""\ +int main (int argc, char **argv) {{ + {funcname}(); + return 0; +}} +""" + ) + + try: + objects = self.compile([fname], include_dirs=include_dirs) + except CompileError: + return False + finally: + os.remove(fname) + + try: + self.link_executable( + objects, "a.out", libraries=libraries, library_dirs=library_dirs + ) + except (LinkError, TypeError): + return False + else: + os.remove( + self.executable_filename("a.out", output_dir=self.output_dir or '') + ) + finally: + for fn in objects: + os.remove(fn) + return True + + def find_library_file(self, dirs, lib, debug=False): + """Search the specified list of directories for a static or shared + library file 'lib' and return the full path to that file. If + 'debug' true, look for a debugging version (if that makes sense on + the current platform). Return None if 'lib' wasn't found in any of + the specified directories. + """ + raise NotImplementedError + + # -- Filename generation methods ----------------------------------- + + # The default implementation of the filename generating methods are + # prejudiced towards the Unix/DOS/Windows view of the world: + # * object files are named by replacing the source file extension + # (eg. .c/.cpp -> .o/.obj) + # * library files (shared or static) are named by plugging the + # library name and extension into a format string, eg. + # "lib%s.%s" % (lib_name, ".a") for Unix static libraries + # * executables are named by appending an extension (possibly + # empty) to the program name: eg. progname + ".exe" for + # Windows + # + # To reduce redundant code, these methods expect to find + # several attributes in the current object (presumably defined + # as class attributes): + # * src_extensions - + # list of C/C++ source file extensions, eg. ['.c', '.cpp'] + # * obj_extension - + # object file extension, eg. '.o' or '.obj' + # * static_lib_extension - + # extension for static library files, eg. '.a' or '.lib' + # * shared_lib_extension - + # extension for shared library/object files, eg. '.so', '.dll' + # * static_lib_format - + # format string for generating static library filenames, + # eg. 'lib%s.%s' or '%s.%s' + # * shared_lib_format + # format string for generating shared library filenames + # (probably same as static_lib_format, since the extension + # is one of the intended parameters to the format string) + # * exe_extension - + # extension for executable files, eg. '' or '.exe' + + def object_filenames(self, source_filenames, strip_dir=False, output_dir=''): + if output_dir is None: + output_dir = '' + return list( + self._make_out_path(output_dir, strip_dir, src_name) + for src_name in source_filenames + ) + + @property + def out_extensions(self): + return dict.fromkeys(self.src_extensions, self.obj_extension) + + def _make_out_path(self, output_dir, strip_dir, src_name): + return self._make_out_path_exts( + output_dir, strip_dir, src_name, self.out_extensions + ) + + @classmethod + def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions): + r""" + >>> exts = {'.c': '.o'} + >>> CCompiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/') + './foo/bar.o' + >>> CCompiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/') + './bar.o' + """ + src = pathlib.PurePath(src_name) + # Ensure base is relative to honor output_dir (python/cpython#37775). + base = cls._make_relative(src) + try: + new_ext = extensions[src.suffix] + except LookupError: + raise UnknownFileError(f"unknown file type '{src.suffix}' (from '{src}')") + if strip_dir: + base = pathlib.PurePath(base.name) + return os.path.join(output_dir, base.with_suffix(new_ext)) + + @staticmethod + def _make_relative(base: pathlib.Path): + return base.relative_to(base.anchor) + + def shared_object_filename(self, basename, strip_dir=False, output_dir=''): + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + self.shared_lib_extension) + + def executable_filename(self, basename, strip_dir=False, output_dir=''): + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + (self.exe_extension or '')) + + def library_filename( + self, + libname, + lib_type='static', + strip_dir=False, + output_dir='', # or 'shared' + ): + assert output_dir is not None + expected = '"static", "shared", "dylib", "xcode_stub"' + if lib_type not in eval(expected): + raise ValueError(f"'lib_type' must be {expected}") + fmt = getattr(self, lib_type + "_lib_format") + ext = getattr(self, lib_type + "_lib_extension") + + dir, base = os.path.split(libname) + filename = fmt % (base, ext) + if strip_dir: + dir = '' + + return os.path.join(output_dir, dir, filename) + + # -- Utility methods ----------------------------------------------- + + def announce(self, msg, level=1): + log.debug(msg) + + def debug_print(self, msg): + from distutils.debug import DEBUG + + if DEBUG: + print(msg) + + def warn(self, msg): + sys.stderr.write(f"warning: {msg}\n") + + def execute(self, func, args, msg=None, level=1): + execute(func, args, msg, self.dry_run) + + def spawn(self, cmd, **kwargs): + spawn(cmd, dry_run=self.dry_run, **kwargs) + + def move_file(self, src, dst): + return move_file(src, dst, dry_run=self.dry_run) + + def mkpath(self, name, mode=0o777): + mkpath(name, mode, dry_run=self.dry_run) + + +# Map a sys.platform/os.name ('posix', 'nt') to the default compiler +# type for that platform. Keys are interpreted as re match +# patterns. Order is important; platform mappings are preferred over +# OS names. +_default_compilers = ( + # Platform string mappings + # on a cygwin built python we can use gcc like an ordinary UNIXish + # compiler + ('cygwin.*', 'unix'), + ('zos', 'zos'), + # OS name mappings + ('posix', 'unix'), + ('nt', 'msvc'), +) + + +def get_default_compiler(osname=None, platform=None): + """Determine the default compiler to use for the given platform. + + osname should be one of the standard Python OS names (i.e. the + ones returned by os.name) and platform the common value + returned by sys.platform for the platform in question. + + The default values are os.name and sys.platform in case the + parameters are not given. + """ + if osname is None: + osname = os.name + if platform is None: + platform = sys.platform + # Mingw is a special case where sys.platform is 'win32' but we + # want to use the 'mingw32' compiler, so check it first + if is_mingw(): + return 'mingw32' + for pattern, compiler in _default_compilers: + if ( + re.match(pattern, platform) is not None + or re.match(pattern, osname) is not None + ): + return compiler + # Default to Unix compiler + return 'unix' + + +# Map compiler types to (module_name, class_name) pairs -- ie. where to +# find the code that implements an interface to this compiler. (The module +# is assumed to be in the 'distutils' package.) +compiler_class = { + 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"), + 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"), + 'cygwin': ( + 'cygwinccompiler', + 'CygwinCCompiler', + "Cygwin port of GNU C Compiler for Win32", + ), + 'mingw32': ( + 'cygwinccompiler', + 'Mingw32CCompiler', + "Mingw32 port of GNU C Compiler for Win32", + ), + 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"), + 'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'), +} + + +def show_compilers(): + """Print list of available compilers (used by the "--help-compiler" + options to "build", "build_ext", "build_clib"). + """ + # XXX this "knows" that the compiler option it's describing is + # "--compiler", which just happens to be the case for the three + # commands that use it. + from distutils.fancy_getopt import FancyGetopt + + compilers = sorted( + ("compiler=" + compiler, None, compiler_class[compiler][2]) + for compiler in compiler_class.keys() + ) + pretty_printer = FancyGetopt(compilers) + pretty_printer.print_help("List of available compilers:") + + +def new_compiler(plat=None, compiler=None, verbose=False, dry_run=False, force=False): + """Generate an instance of some CCompiler subclass for the supplied + platform/compiler combination. 'plat' defaults to 'os.name' + (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler + for that platform. Currently only 'posix' and 'nt' are supported, and + the default compilers are "traditional Unix interface" (UnixCCompiler + class) and Visual C++ (MSVCCompiler class). Note that it's perfectly + possible to ask for a Unix compiler object under Windows, and a + Microsoft compiler object under Unix -- if you supply a value for + 'compiler', 'plat' is ignored. + """ + if plat is None: + plat = os.name + + try: + if compiler is None: + compiler = get_default_compiler(plat) + + (module_name, class_name, long_description) = compiler_class[compiler] + except KeyError: + msg = f"don't know how to compile C/C++ code on platform '{plat}'" + if compiler is not None: + msg = msg + f" with '{compiler}' compiler" + raise DistutilsPlatformError(msg) + + try: + module_name = "distutils." + module_name + __import__(module_name) + module = sys.modules[module_name] + klass = vars(module)[class_name] + except ImportError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to load module '{module_name}'" + ) + except KeyError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to find class '{class_name}' " + f"in module '{module_name}'" + ) + + # XXX The None is necessary to preserve backwards compatibility + # with classes that expect verbose to be the first positional + # argument. + return klass(None, dry_run, force) + + +def gen_preprocess_options(macros, include_dirs): + """Generate C pre-processor options (-D, -U, -I) as used by at least + two types of compilers: the typical Unix compiler and Visual C++. + 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) + means undefine (-U) macro 'name', and (name,value) means define (-D) + macro 'name' to 'value'. 'include_dirs' is just a list of directory + names to be added to the header file search path (-I). Returns a list + of command-line options suitable for either Unix compilers or Visual + C++. + """ + # XXX it would be nice (mainly aesthetic, and so we don't generate + # stupid-looking command lines) to go over 'macros' and eliminate + # redundant definitions/undefinitions (ie. ensure that only the + # latest mention of a particular macro winds up on the command + # line). I don't think it's essential, though, since most (all?) + # Unix C compilers only pay attention to the latest -D or -U + # mention of a macro on their command line. Similar situation for + # 'include_dirs'. I'm punting on both for now. Anyways, weeding out + # redundancies like this should probably be the province of + # CCompiler, since the data structures used are inherited from it + # and therefore common to all CCompiler classes. + pp_opts = [] + for macro in macros: + if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2): + raise TypeError( + f"bad macro definition '{macro}': " + "each element of 'macros' list must be a 1- or 2-tuple" + ) + + if len(macro) == 1: # undefine this macro + pp_opts.append(f"-U{macro[0]}") + elif len(macro) == 2: + if macro[1] is None: # define with no explicit value + pp_opts.append(f"-D{macro[0]}") + else: + # XXX *don't* need to be clever about quoting the + # macro value here, because we're going to avoid the + # shell at all costs when we spawn the command! + pp_opts.append("-D{}={}".format(*macro)) + + pp_opts.extend(f"-I{dir}" for dir in include_dirs) + return pp_opts + + +def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): + """Generate linker options for searching library directories and + linking with specific libraries. 'libraries' and 'library_dirs' are, + respectively, lists of library names (not filenames!) and search + directories. Returns a list of command-line options suitable for use + with some compiler (depending on the two format strings passed in). + """ + lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs] + + for dir in runtime_library_dirs: + lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir))) + + # XXX it's important that we *not* remove redundant library mentions! + # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to + # resolve all symbols. I just hope we never have to say "-lfoo obj.o + # -lbar" to get things to work -- that's certainly a possibility, but a + # pretty nasty way to arrange your C code. + + for lib in libraries: + (lib_dir, lib_name) = os.path.split(lib) + if lib_dir: + lib_file = compiler.find_library_file([lib_dir], lib_name) + if lib_file: + lib_opts.append(lib_file) + else: + compiler.warn( + f"no library file corresponding to '{lib}' found (skipping)" + ) + else: + lib_opts.append(compiler.library_option(lib)) + return lib_opts diff --git a/shared/package-files/38/38ad2b19fa36ada31ceb40f7ae59f79efa4ba949e2bc0a4e087990566b8c4a98/abs_native.h b/shared/package-files/38/38ad2b19fa36ada31ceb40f7ae59f79efa4ba949e2bc0a4e087990566b8c4a98/abs_native.h new file mode 100644 index 0000000000000000000000000000000000000000..08804986275fef5bb746d57d2d8d2b2986699f9b --- /dev/null +++ b/shared/package-files/38/38ad2b19fa36ada31ceb40f7ae59f79efa4ba949e2bc0a4e087990566b8c4a98/abs_native.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor abs(const at::Tensor & self); +TORCH_API at::Tensor & abs_(at::Tensor & self); +TORCH_API at::Tensor & abs_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor NestedTensor_abs(const at::Tensor & self); +TORCH_API at::Tensor & NestedTensor_abs_(at::Tensor & self); +TORCH_API at::Tensor abs_sparse(const at::Tensor & self); +TORCH_API at::Tensor & abs_sparse_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & abs_sparse_(at::Tensor & self); +TORCH_API at::Tensor abs_sparse_csr(const at::Tensor & self); +TORCH_API at::Tensor & abs_sparse_csr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & abs_sparse_csr_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38b1d9542f140260ac0ed55c9e3be488e22c088689bbd865b96a82f665be81b1/activation.py b/shared/package-files/38/38b1d9542f140260ac0ed55c9e3be488e22c088689bbd865b96a82f665be81b1/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e37fd80baaa752d8721204e6df40599ca9021d --- /dev/null +++ b/shared/package-files/38/38b1d9542f140260ac0ed55c9e3be488e22c088689bbd865b96a82f665be81b1/activation.py @@ -0,0 +1,343 @@ +# mypy: allow-untyped-defs +from warnings import warn + +import torch + + +__all__ = [ + "ReLU6", + "Hardswish", + "ELU", + "LeakyReLU", + "Sigmoid", + "Softmax", + "MultiheadAttention", + "PReLU", +] + + +class ReLU6(torch.nn.ReLU): + r"""Applies the element-wise function: + + :math:`\text{ReLU6}(x) = \min(\max(x_0, x), q(6))`, where :math:`x_0` is the + zero_point, and :math:`q(6)` is the quantized representation of number 6. + + Args: + inplace: can optionally do the operation in-place. Default: ``False`` + + Shape: + - Input: :math:`(N, *)` where `*` means, any number of additional + dimensions + - Output: :math:`(N, *)`, same shape as the input + + .. image:: ../scripts/activation_images/ReLU6.png + + Examples:: + + >>> m = nn.quantized.ReLU6() + >>> input = torch.randn(2) + >>> # xdoctest: +SKIP + >>> input = torch.quantize_per_tensor(input, 1.0, 0, dtype=torch.qint32) + >>> output = m(input) + """ + + def __init__(self, inplace=False): + super().__init__(inplace) + self.inplace = inplace + + def forward(self, input): + return torch.ops.quantized.relu6(input, self.inplace) + + def _get_name(self): + return "QuantizedReLU6" + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + return ReLU6(mod.inplace) + + +class Hardswish(torch.nn.Hardswish): + r"""This is the quantized version of :class:`~torch.nn.Hardswish`. + + Args: + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + """ + + def __init__(self, scale, zero_point, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.hardswish(input, self.scale, self.zero_point) + + def _get_name(self): + return "QuantizedHardswish" + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + return Hardswish(float(scale), int(zero_point)) + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls(float(scale), int(zero_point)) + + +class ELU(torch.nn.ELU): + r"""This is the quantized equivalent of :class:`~torch.nn.ELU`. + + Args: + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + alpha: the alpha constant + """ + + def __init__(self, scale, zero_point, alpha=1.0): + super().__init__(alpha) + self.scale = scale + self.zero_point = zero_point + + def forward(self, input): + return torch.ao.nn.quantized.functional.elu( + input, self.scale, self.zero_point, self.alpha + ) + + def _get_name(self): + return "QuantizedELU" + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + return ELU(float(scale), int(zero_point), mod.alpha) + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls(float(scale), int(zero_point), mod.alpha) + + +class LeakyReLU(torch.nn.LeakyReLU): + r"""This is the quantized equivalent of :class:`~torch.nn.LeakyReLU`. + + Args: + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + negative_slope: Controls the angle of the negative slope. Default: 1e-2 + """ + + def __init__( + self, + scale: float, + zero_point: int, + negative_slope: float = 1e-2, + inplace: bool = False, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__(negative_slope, inplace) + self.register_buffer("scale", torch.tensor(scale, **factory_kwargs)) + self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.leaky_relu( + input, self.negative_slope, self.inplace, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedLeakyReLU" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace) + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace) + + +class Sigmoid(torch.nn.Sigmoid): + r"""This is the quantized equivalent of :class:`~torch.nn.Sigmoid`. + + Args: + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + """ + + def __init__(self, output_scale: float, output_zero_point: int): + super().__init__() + self.output_scale = output_scale + self.output_zero_point = output_zero_point + + def forward(self, input): + return torch.ops.quantized.sigmoid( + input, self.output_scale, self.output_zero_point + ) + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + ( + output_scale, + output_zero_point, + ) = mod.activation_post_process.calculate_qparams() + return cls(float(output_scale), int(output_zero_point)) + + +class Softmax(torch.nn.Softmax): + r"""This is the quantized version of :class:`~torch.nn.Softmax`. + + Args: + dim: A dimension along which Softmax will be computed (so every slice along dim will sum to 1). + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + """ + + def __init__(self, dim=None, scale=1.0, zero_point=0): + super().__init__() + self.dim = dim + self.scale = scale + self.zero_point = zero_point + + def forward(self, input): + dim = self.dim + if dim is None: + stacklevel = 3 + # Note: adding the mypy ignore on _get_softmax_dim seems less bad + # than making `_get_softmax_dim` an official API. + dim = torch.nn.functional._get_softmax_dim( # type: ignore[attr-defined] + "softmax", input.dim(), stacklevel + ) + return torch.ops.quantized.softmax(input, dim, self.scale, self.zero_point) + + def _get_name(self): + return "QuantizedSoftmax" + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + return Softmax(mod.dim, float(scale), int(zero_point)) + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls(mod.dim, float(scale), int(zero_point)) + + +class MultiheadAttention(torch.ao.nn.quantizable.MultiheadAttention): + _FLOAT_MODULE = torch.ao.nn.quantizable.MultiheadAttention + + def _get_name(self): + return "QuantizedMultiheadAttention" + + @classmethod + def from_float(cls, other): + # The whole flow is float -> observed -> quantized + # This class does observed -> quantized only + raise NotImplementedError( + "It looks like you are trying to convert a " + "non-observed MHA module. Please, see " + "the examples on quantizable MHAs." + ) + + @classmethod + def from_observed(cls, other): + converted = torch.ao.quantization.convert( + other, + mapping=None, + inplace=False, + remove_qconfig=True, + convert_custom_config_dict=None, + ) + converted.__class__ = cls + # Remove the parameters for the bias_k and bias_v to quantize them + # TODO: This is a potential source of accuracy drop. + # quantized cat takes the scale and zp of the first + # element, which might lose the precision in the bias_k + # and the bias_v (which are cat'ed with k/v being first). + if converted.bias_k is not None: + bias_k = converted._parameters.pop("bias_k") + sc, zp = torch._choose_qparams_per_tensor(bias_k, reduce_range=False) + bias_k = torch.quantize_per_tensor(bias_k, sc, zp, torch.quint8) + setattr(converted, "bias_k", bias_k) # noqa: B010 + + if converted.bias_v is not None: + bias_v = converted._parameters.pop("bias_v") + sc, zp = torch._choose_qparams_per_tensor( + bias_k, reduce_range=False # type: ignore[possibly-undefined] + ) + bias_v = torch.quantize_per_tensor(bias_v, sc, zp, torch.quint8) + setattr(converted, "bias_v", bias_v) # noqa: B010 + + del converted.in_proj_weight + del converted.in_proj_bias + + return converted + + +class PReLU(torch.nn.Module): + r"""This is the quantized equivalent of :class:`~torch.nn.PReLU`. + + Args: + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + num_parameters: number of parameters: 1, or the number of channels at input. Default: 1 + """ + + def __init__( + self, output_scale: float, output_zero_point: int, num_parameters: int = 1 + ) -> None: + super().__init__() + self.num_parameters = num_parameters + self.scale = output_scale + self.zero_point = output_zero_point + w = torch.randn(num_parameters, dtype=torch.float) + qw = torch.quantize_per_tensor(w, scale=1.0, zero_point=0, dtype=torch.quint8) + self.set_weight(qw) + + def set_weight(self, w: torch.Tensor) -> None: + self.weight = w + + def forward(self, input: torch.Tensor) -> torch.Tensor: + return torch.ops.quantized.prelu( + input, self.weight, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedPReLU" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + scale, zero_point = mod.activation_post_process.calculate_qparams() + qprelu = cls(float(scale), int(zero_point), mod.num_parameters) + float_wt = mod.weight.float() + observer = mod.qconfig.weight() + observer(float_wt) + if observer.dtype != torch.quint8: + warn( + f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}" + ) + wt_scale, wt_zp = observer.calculate_qparams() + qweight = torch.quantize_per_tensor( + float_wt, float(wt_scale), int(wt_zp), torch.quint8 + ) + qprelu.set_weight(qweight) + return qprelu + + @classmethod + def from_reference(cls, mod, scale, zero_point): + qprelu = cls(float(scale), int(zero_point), mod.num_parameters) + float_wt = mod.weight.float() + observer = mod.qconfig.weight() + observer(float_wt) + if observer.dtype != torch.quint8: + warn( + f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}" + ) + wt_scale, wt_zp = observer.calculate_qparams() + qweight = torch.quantize_per_tensor( + float_wt, float(wt_scale), int(wt_zp), torch.quint8 + ) + qprelu.set_weight(qweight) + return qprelu diff --git a/shared/package-files/38/38b3dcc24cab6e4b79a4d677e36a37662bfd4c2ae5a54de1d7cb3d47e731a972/polynomialring.py b/shared/package-files/38/38b3dcc24cab6e4b79a4d677e36a37662bfd4c2ae5a54de1d7cb3d47e731a972/polynomialring.py new file mode 100644 index 0000000000000000000000000000000000000000..daccdcdede4d409e995a79540b0c3f9e8017d2d9 --- /dev/null +++ b/shared/package-files/38/38b3dcc24cab6e4b79a4d677e36a37662bfd4c2ae5a54de1d7cb3d47e731a972/polynomialring.py @@ -0,0 +1,203 @@ +"""Implementation of :class:`PolynomialRing` class. """ + + +from sympy.polys.domains.ring import Ring +from sympy.polys.domains.compositedomain import CompositeDomain + +from sympy.polys.polyerrors import CoercionFailed, GeneratorsError +from sympy.utilities import public + +@public +class PolynomialRing(Ring, CompositeDomain): + """A class for representing multivariate polynomial rings. """ + + is_PolynomialRing = is_Poly = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self, domain_or_ring, symbols=None, order=None): + from sympy.polys.rings import PolyRing + + if isinstance(domain_or_ring, PolyRing) and symbols is None and order is None: + ring = domain_or_ring + else: + ring = PolyRing(symbols, domain_or_ring, order) + + self.ring = ring + self.dtype = ring.dtype + + self.gens = ring.gens + self.ngens = ring.ngens + self.symbols = ring.symbols + self.domain = ring.domain + + + if symbols: + if ring.domain.is_Field and ring.domain.is_Exact and len(symbols)==1: + self.is_PID = True + + # TODO: remove this + self.dom = self.domain + + def new(self, element): + return self.ring.ring_new(element) + + def of_type(self, element): + """Check if ``a`` is of type ``dtype``. """ + return self.ring.is_element(element) + + @property + def zero(self): + return self.ring.zero + + @property + def one(self): + return self.ring.one + + @property + def order(self): + return self.ring.order + + def __str__(self): + return str(self.domain) + '[' + ','.join(map(str, self.symbols)) + ']' + + def __hash__(self): + return hash((self.__class__.__name__, self.ring, self.domain, self.symbols)) + + def __eq__(self, other): + """Returns `True` if two domains are equivalent. """ + if not isinstance(other, PolynomialRing): + return NotImplemented + return self.ring == other.ring + + def is_unit(self, a): + """Returns ``True`` if ``a`` is a unit of ``self``""" + if not a.is_ground: + return False + K = self.domain + return K.is_unit(K.convert_from(a, self)) + + def canonical_unit(self, a): + u = self.domain.canonical_unit(a.LC) + return self.ring.ground_new(u) + + def to_sympy(self, a): + """Convert `a` to a SymPy object. """ + return a.as_expr() + + def from_sympy(self, a): + """Convert SymPy's expression to `dtype`. """ + return self.ring.from_expr(a) + + def from_ZZ(K1, a, K0): + """Convert a Python `int` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python `int` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python `Fraction` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python `Fraction` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY `mpz` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY `mpq` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a `GaussianInteger` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a `GaussianRational` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath `mpf` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ComplexField(K1, a, K0): + """Convert a mpmath `mpf` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_AlgebraicField(K1, a, K0): + """Convert an algebraic number to ``dtype``. """ + if K1.domain != K0: + a = K1.domain.convert_from(a, K0) + if a is not None: + return K1.new(a) + + def from_PolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + try: + return a.set_ring(K1.ring) + except (CoercionFailed, GeneratorsError): + return None + + def from_FractionField(K1, a, K0): + """Convert a rational function to ``dtype``. """ + if K1.domain == K0: + return K1.ring.from_list([a]) + + q, r = K0.numer(a).div(K0.denom(a)) + + if r.is_zero: + return K1.from_PolynomialRing(q, K0.field.ring.to_domain()) + else: + return None + + def from_GlobalPolynomialRing(K1, a, K0): + """Convert from old poly ring to ``dtype``. """ + if K1.symbols == K0.gens: + ad = a.to_dict() + if K1.domain != K0.domain: + ad = {m: K1.domain.convert(c) for m, c in ad.items()} + return K1(ad) + elif a.is_ground and K0.domain == K1: + return K1.convert_from(a.to_list()[0], K0.domain) + + def get_field(self): + """Returns a field associated with `self`. """ + return self.ring.to_field().to_domain() + + def is_positive(self, a): + """Returns True if `LC(a)` is positive. """ + return self.domain.is_positive(a.LC) + + def is_negative(self, a): + """Returns True if `LC(a)` is negative. """ + return self.domain.is_negative(a.LC) + + def is_nonpositive(self, a): + """Returns True if `LC(a)` is non-positive. """ + return self.domain.is_nonpositive(a.LC) + + def is_nonnegative(self, a): + """Returns True if `LC(a)` is non-negative. """ + return self.domain.is_nonnegative(a.LC) + + def gcdex(self, a, b): + """Extended GCD of `a` and `b`. """ + return a.gcdex(b) + + def gcd(self, a, b): + """Returns GCD of `a` and `b`. """ + return a.gcd(b) + + def lcm(self, a, b): + """Returns LCM of `a` and `b`. """ + return a.lcm(b) + + def factorial(self, a): + """Returns factorial of `a`. """ + return self.dtype(self.domain.factorial(a)) diff --git a/shared/package-files/38/38ba3f42d9c96b884848d469094a798b38df339e7e5b51a6e09f7c19ca7f2c8f/index_tricks.cpython-311.pyc b/shared/package-files/38/38ba3f42d9c96b884848d469094a798b38df339e7e5b51a6e09f7c19ca7f2c8f/index_tricks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e91a3e15d3d512e24cafcf84dc324262fecb3d Binary files /dev/null and b/shared/package-files/38/38ba3f42d9c96b884848d469094a798b38df339e7e5b51a6e09f7c19ca7f2c8f/index_tricks.cpython-311.pyc differ diff --git a/shared/package-files/38/38bcb36504e4fd4d8a793ef2019e5478329bac78d23f645bfba091a6412fa101/clamp_min.h b/shared/package-files/38/38bcb36504e4fd4d8a793ef2019e5478329bac78d23f645bfba091a6412fa101/clamp_min.h new file mode 100644 index 0000000000000000000000000000000000000000..ec7b2ebfbe2b88ff05547ead99cd1a9099e6f9fb --- /dev/null +++ b/shared/package-files/38/38bcb36504e4fd4d8a793ef2019e5478329bac78d23f645bfba091a6412fa101/clamp_min.h @@ -0,0 +1,64 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::clamp_min(Tensor self, Scalar min) -> Tensor +inline at::Tensor clamp_min(const at::Tensor & self, const at::Scalar & min) { + return at::_ops::clamp_min::call(self, min); +} + +// aten::clamp_min.Tensor(Tensor self, Tensor min) -> Tensor +inline at::Tensor clamp_min(const at::Tensor & self, const at::Tensor & min) { + return at::_ops::clamp_min_Tensor::call(self, min); +} + +// aten::clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!) +inline at::Tensor & clamp_min_(at::Tensor & self, const at::Scalar & min) { + return at::_ops::clamp_min_::call(self, min); +} + +// aten::clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!) +inline at::Tensor & clamp_min_(at::Tensor & self, const at::Tensor & min) { + return at::_ops::clamp_min__Tensor::call(self, min); +} + +// aten::clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_min_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & min) { + return at::_ops::clamp_min_out::call(self, min, out); +} +// aten::clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_min_outf(const at::Tensor & self, const at::Scalar & min, at::Tensor & out) { + return at::_ops::clamp_min_out::call(self, min, out); +} + +// aten::clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_min_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & min) { + return at::_ops::clamp_min_Tensor_out::call(self, min, out); +} +// aten::clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_min_outf(const at::Tensor & self, const at::Tensor & min, at::Tensor & out) { + return at::_ops::clamp_min_Tensor_out::call(self, min, out); +} + +} diff --git a/shared/package-files/38/38bd9594dc0732f43faaf94bca2e85bef1a7bdb0344b6973a09a30f3a57c8e71/decomposition_table.py b/shared/package-files/38/38bd9594dc0732f43faaf94bca2e85bef1a7bdb0344b6973a09a30f3a57c8e71/decomposition_table.py new file mode 100644 index 0000000000000000000000000000000000000000..1b830f91a9fdebf16062977955e0f804be854ed6 --- /dev/null +++ b/shared/package-files/38/38bd9594dc0732f43faaf94bca2e85bef1a7bdb0344b6973a09a30f3a57c8e71/decomposition_table.py @@ -0,0 +1,116 @@ +# mypy: allow-untyped-defs +"""Dispatcher for AtenLib functions from onnx-script.""" + +from __future__ import annotations + +from typing import Callable + +import torch +import torch._ops +import torch.fx +from torch.onnx._internal.fx import registration + + +def _create_onnx_supports_op_overload_table( + registry, +) -> set[torch._ops.OperatorBase | Callable]: + """ + Creates a set of OperatorBase and Callable objects that represent ONNX-supported PyTorch operations. + + Args: + registry (OnnxRegistry): The ONNX registry for PyTorch. + + Returns: + A collection of OperatorBase and Callable objects representing ONNX-supported PyTorch operations. + """ + table: set[torch._ops.OperatorBase | Callable] = set() + + # Some ops in `torch.ops.aten` are not discoverable through `dir(torch.ops.aten)`, + # but retrievable via explicit lookup. + # https://github.com/pytorch/pytorch/issues/99681 + # This is a workaround to make sure we register ONNX symbolic functions for these. + onnx_supported_aten_lookup_table = [ + k.split("::")[1].split(".")[0] + for k in registry._all_registered_ops() + if k.startswith("aten::") + ] + + for op_namespace in (torch.ops.aten, torch.ops.prims): + attr_names = dir(op_namespace) + if op_namespace is torch.ops.aten: + attr_names += onnx_supported_aten_lookup_table + for attr_name in attr_names: + if not hasattr(op_namespace, attr_name): + # torchlib owns some attributes that are not aten ops. + continue + op_overload_packet = getattr(op_namespace, attr_name) + if not isinstance(op_overload_packet, torch._ops.OpOverloadPacket): + continue + + for overload_name in op_overload_packet.overloads(): + op_overload = getattr(op_overload_packet, overload_name) + internal_op_name = registration.OpName.from_qualified_name( + qualified_name=op_overload.name() + ) + # NOTE: If the overload is supported in registry or it's default overload is supported in registry, + # we add it to the table. + if registry.is_registered_op( + namespace=internal_op_name.namespace, + op_name=internal_op_name.op_name, + overload=internal_op_name.overload, + ) or registry.is_registered_op( + namespace=internal_op_name.namespace, + op_name=internal_op_name.op_name, + overload=None, + ): + # This line maps torch.ops.aten.add.Tensor, torch.ops.aten.add.Scalar, torch.ops.aten.add.out, etc + # to "aten::add". This means the exporter for "aten::add" is used for all overloads of "aten::add". + # This is applied to all ops under torch.ops.aten. + table.add(op_overload) + return table + + +def create_onnx_friendly_decomposition_table( + registry, +) -> dict[torch._ops.OperatorBase, Callable]: + """ + This function creates a dictionary of op overloads and their decomposition functions + for ops that do not have ONNX symbolic functions. If an op already has an ONNX symbolic function, + its decomposition function is excluded from the table. The decomposition table is a subset of PyTorch's + built-in aten-to-aten decomposition. + + Args: + registry (torch.onnx.OnnxRegistry): The ONNX registry for PyTorch. + + Returns: + Dict[torch._ops.OperatorBase, Callable]: A dictionary that maps op overloads to their corresponding + decomposition functions. + """ + decomposition_table: dict[torch._ops.OperatorBase, Callable] = {} + # Dictionary that maps torch.ops.aten.* to exporter look up key; e.g., + # _OP_OVERLOAD_TO_EXPORTER_KEY_TABLE[torch.add.Tensor] is "aten::add". + _ONNX_SUPPORT_OP_OVERLOADS = _create_onnx_supports_op_overload_table(registry) + + # NOTE: If we import torch._decomp, we will get RuntimeError: Only a single + # TORCH_LIBRARY can be used to register the namespace nvprims; please put all of your + # definitions in a single TORCH_LIBRARY block. + for op_overload, decomp_fn in torch._decomp.decomposition_table.items(): + # Skip decomposition into "prim::*" ops (defined in 'torch._refs'), because they + # are not generally supported by ONNX. + # Skip decomposition for op_overload as long as that op_overload has a corresponding ONNX + # symbolic function. + if ( + "torch._refs" in decomp_fn.__module__ + or op_overload in _ONNX_SUPPORT_OP_OVERLOADS + ): + continue + decomposition_table[op_overload] = decomp_fn + + # NOTE: There are ops in core ATen and under torch._refs, + # that are not decomposed to prim::ops. We need to pick them + # back + for op_overload, decomp_fn in torch._decomp.core_aten_decompositions().items(): + if op_overload in _ONNX_SUPPORT_OP_OVERLOADS: + continue + decomposition_table[op_overload] = decomp_fn + return decomposition_table diff --git a/shared/package-files/38/38bdeef86eac0b0bd9b81bae6103b44292fec16c6d8f115a06355086d890fd9f/galois_resolvents.py b/shared/package-files/38/38bdeef86eac0b0bd9b81bae6103b44292fec16c6d8f115a06355086d890fd9f/galois_resolvents.py new file mode 100644 index 0000000000000000000000000000000000000000..5d73b56870a498f09102787da3517e7520edb3db --- /dev/null +++ b/shared/package-files/38/38bdeef86eac0b0bd9b81bae6103b44292fec16c6d8f115a06355086d890fd9f/galois_resolvents.py @@ -0,0 +1,676 @@ +r""" +Galois resolvents + +Each of the functions in ``sympy.polys.numberfields.galoisgroups`` that +computes Galois groups for a particular degree $n$ uses resolvents. Given the +polynomial $T$ whose Galois group is to be computed, a resolvent is a +polynomial $R$ whose roots are defined as functions of the roots of $T$. + +One way to compute the coefficients of $R$ is by approximating the roots of $T$ +to sufficient precision. This module defines a :py:class:`~.Resolvent` class +that handles this job, determining the necessary precision, and computing $R$. + +In some cases, the coefficients of $R$ are symmetric in the roots of $T$, +meaning they are equal to fixed functions of the coefficients of $T$. Therefore +another approach is to compute these functions once and for all, and record +them in a lookup table. This module defines code that can compute such tables. +The tables for polynomials $T$ of degrees 4 through 6, produced by this code, +are recorded in the resolvent_lookup.py module. + +""" + +from sympy.core.evalf import ( + evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath, +) +from sympy.core.symbol import symbols, Dummy +from sympy.polys.densetools import dup_eval +from sympy.polys.domains import ZZ +from sympy.polys.orderings import lex +from sympy.polys.polyroots import preprocess_roots +from sympy.polys.polytools import Poly +from sympy.polys.rings import xring +from sympy.polys.specialpolys import symmetric_poly +from sympy.utilities.lambdify import lambdify + +from mpmath import MPContext +from mpmath.libmp.libmpf import prec_to_dps + + +class GaloisGroupException(Exception): + ... + + +class ResolventException(GaloisGroupException): + ... + + +class Resolvent: + r""" + If $G$ is a subgroup of the symmetric group $S_n$, + $F$ a multivariate polynomial in $\mathbb{Z}[X_1, \ldots, X_n]$, + $H$ the stabilizer of $F$ in $G$ (i.e. the permutations $\sigma$ such that + $F(X_{\sigma(1)}, \ldots, X_{\sigma(n)}) = F(X_1, \ldots, X_n)$), and $s$ + a set of left coset representatives of $H$ in $G$, then the resolvent + polynomial $R(Y)$ is the product over $\sigma \in s$ of + $Y - F(X_{\sigma(1)}, \ldots, X_{\sigma(n)})$. + + For example, consider the resolvent for the form + $$F = X_0 X_2 + X_1 X_3$$ + and the group $G = S_4$. In this case, the stabilizer $H$ is the dihedral + group $D4 = < (0123), (02) >$, and a set of representatives of $G/H$ is + $\{I, (01), (03)\}$. The resolvent can be constructed as follows: + + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.core.symbol import symbols + >>> from sympy.polys.numberfields.galoisgroups import Resolvent + >>> X = symbols('X0 X1 X2 X3') + >>> F = X[0]*X[2] + X[1]*X[3] + >>> s = [Permutation([0, 1, 2, 3]), Permutation([1, 0, 2, 3]), + ... Permutation([3, 1, 2, 0])] + >>> R = Resolvent(F, X, s) + + This resolvent has three roots, which are the conjugates of ``F`` under the + three permutations in ``s``: + + >>> R.root_lambdas[0](*X) + X0*X2 + X1*X3 + >>> R.root_lambdas[1](*X) + X0*X3 + X1*X2 + >>> R.root_lambdas[2](*X) + X0*X1 + X2*X3 + + Resolvents are useful for computing Galois groups. Given a polynomial $T$ + of degree $n$, we will use a resolvent $R$ where $Gal(T) \leq G \leq S_n$. + We will then want to substitute the roots of $T$ for the variables $X_i$ + in $R$, and study things like the discriminant of $R$, and the way $R$ + factors over $\mathbb{Q}$. + + From the symmetry in $R$'s construction, and since $Gal(T) \leq G$, we know + from Galois theory that the coefficients of $R$ must lie in $\mathbb{Z}$. + This allows us to compute the coefficients of $R$ by approximating the + roots of $T$ to sufficient precision, plugging these values in for the + variables $X_i$ in the coefficient expressions of $R$, and then simply + rounding to the nearest integer. + + In order to determine a sufficient precision for the roots of $T$, this + ``Resolvent`` class imposes certain requirements on the form ``F``. It + could be possible to design a different ``Resolvent`` class, that made + different precision estimates, and different assumptions about ``F``. + + ``F`` must be homogeneous, and all terms must have unit coefficient. + Furthermore, if $r$ is the number of terms in ``F``, and $t$ the total + degree, and if $m$ is the number of conjugates of ``F``, i.e. the number + of permutations in ``s``, then we require that $m < r 2^t$. Again, it is + not impossible to work with forms ``F`` that violate these assumptions, but + this ``Resolvent`` class requires them. + + Since determining the integer coefficients of the resolvent for a given + polynomial $T$ is one of the main problems this class solves, we take some + time to explain the precision bounds it uses. + + The general problem is: + Given a multivariate polynomial $P \in \mathbb{Z}[X_1, \ldots, X_n]$, and a + bound $M \in \mathbb{R}_+$, compute an $\varepsilon > 0$ such that for any + complex numbers $a_1, \ldots, a_n$ with $|a_i| < M$, if the $a_i$ are + approximated to within an accuracy of $\varepsilon$ by $b_i$, that is, + $|a_i - b_i| < \varepsilon$ for $i = 1, \ldots, n$, then + $|P(a_1, \ldots, a_n) - P(b_1, \ldots, b_n)| < 1/2$. In other words, if it + is known that $P(a_1, \ldots, a_n) = c$ for some $c \in \mathbb{Z}$, then + $P(b_1, \ldots, b_n)$ can be rounded to the nearest integer in order to + determine $c$. + + To derive our error bound, consider the monomial $xyz$. Defining + $d_i = b_i - a_i$, our error is + $|(a_1 + d_1)(a_2 + d_2)(a_3 + d_3) - a_1 a_2 a_3|$, which is bounded + above by $|(M + \varepsilon)^3 - M^3|$. Passing to a general monomial of + total degree $t$, this expression is bounded by + $M^{t-1}\varepsilon(t + 2^t\varepsilon/M)$ provided $\varepsilon < M$, + and by $(t+1)M^{t-1}\varepsilon$ provided $\varepsilon < M/2^t$. + But since our goal is to make the error less than $1/2$, we will choose + $\varepsilon < 1/(2(t+1)M^{t-1})$, which implies the condition that + $\varepsilon < M/2^t$, as long as $M \geq 2$. + + Passing from the general monomial to the general polynomial is easy, by + scaling and summing error bounds. + + In our specific case, we are given a homogeneous polynomial $F$ of + $r$ terms and total degree $t$, all of whose coefficients are $\pm 1$. We + are given the $m$ permutations that make the conjugates of $F$, and + we want to bound the error in the coefficients of the monic polynomial + $R(Y)$ having $F$ and its conjugates as roots (i.e. the resolvent). + + For $j$ from $1$ to $m$, the coefficient of $Y^{m-j}$ in $R(Y)$ is the + $j$th elementary symmetric polynomial in the conjugates of $F$. This sums + the products of these conjugates, taken $j$ at a time, in all possible + combinations. There are $\binom{m}{j}$ such combinations, and each product + of $j$ conjugates of $F$ expands to a sum of $r^j$ terms, each of unit + coefficient, and total degree $jt$. An error bound for the $j$th coeff of + $R$ is therefore + $$\binom{m}{j} r^j (jt + 1) M^{jt - 1} \varepsilon$$ + When our goal is to evaluate all the coefficients of $R$, we will want to + use the maximum of these error bounds. It is clear that this bound is + strictly increasing for $j$ up to the ceiling of $m/2$. After that point, + the first factor $\binom{m}{j}$ begins to decrease, while the others + continue to increase. However, the binomial coefficient never falls by more + than a factor of $1/m$ at a time, so our assumptions that $M \geq 2$ and + $m < r 2^t$ are enough to tell us that the constant coefficient of $R$, + i.e. that where $j = m$, has the largest error bound. Therefore we can use + $$r^m (mt + 1) M^{mt - 1} \varepsilon$$ + as our error bound for all the coefficients. + + Note that this bound is also (more than) adequate to determine whether any + of the roots of $R$ is an integer. Each of these roots is a single + conjugate of $F$, which contains less error than the trace, i.e. the + coefficient of $Y^{m - 1}$. By rounding the roots of $R$ to the nearest + integers, we therefore get all the candidates for integer roots of $R$. By + plugging these candidates into $R$, we can check whether any of them + actually is a root. + + Note: We take the definition of resolvent from Cohen, but the error bound + is ours. + + References + ========== + + .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*. + (Def 6.3.2) + + """ + + def __init__(self, F, X, s): + r""" + Parameters + ========== + + F : :py:class:`~.Expr` + polynomial in the symbols in *X* + X : list of :py:class:`~.Symbol` + s : list of :py:class:`~.Permutation` + representing the cosets of the stabilizer of *F* in + some subgroup $G$ of $S_n$, where $n$ is the length of *X*. + """ + self.F = F + self.X = X + self.s = s + + # Number of conjugates: + self.m = len(s) + # Total degree of F (computed below): + self.t = None + # Number of terms in F (computed below): + self.r = 0 + + for monom, coeff in Poly(F).terms(): + if abs(coeff) != 1: + raise ResolventException('Resolvent class expects forms with unit coeffs') + t = sum(monom) + if t != self.t and self.t is not None: + raise ResolventException('Resolvent class expects homogeneous forms') + self.t = t + self.r += 1 + + m, t, r = self.m, self.t, self.r + if not m < r * 2**t: + raise ResolventException('Resolvent class expects m < r*2^t') + M = symbols('M') + # Precision sufficient for computing the coeffs of the resolvent: + self.coeff_prec_func = Poly(r**m*(m*t + 1)*M**(m*t - 1)) + # Precision sufficient for checking whether any of the roots of the + # resolvent are integers: + self.root_prec_func = Poly(r*(t + 1)*M**(t - 1)) + + # The conjugates of F are the roots of the resolvent. + # For evaluating these to required numerical precisions, we need + # lambdified versions. + # Note: for a given permutation sigma, the conjugate (sigma F) is + # equivalent to lambda [sigma^(-1) X]: F. + self.root_lambdas = [ + lambdify((~s[j])(X), F) + for j in range(self.m) + ] + + # For evaluating the coeffs, we'll also need lambdified versions of + # the elementary symmetric functions for degree m. + Y = symbols('Y') + R = symbols(' '.join(f'R{i}' for i in range(m))) + f = 1 + for r in R: + f *= (Y - r) + C = Poly(f, Y).coeffs() + self.esf_lambdas = [lambdify(R, c) for c in C] + + def get_prec(self, M, target='coeffs'): + r""" + For a given upper bound *M* on the magnitude of the complex numbers to + be plugged in for this resolvent's symbols, compute a sufficient + precision for evaluating those complex numbers, such that the + coefficients, or the integer roots, of the resolvent can be determined. + + Parameters + ========== + + M : real number + Upper bound on magnitude of the complex numbers to be plugged in. + + target : str, 'coeffs' or 'roots', default='coeffs' + Name the task for which a sufficient precision is desired. + This is either determining the coefficients of the resolvent + ('coeffs') or determining its possible integer roots ('roots'). + The latter may require significantly lower precision. + + Returns + ======= + + int $m$ + such that $2^{-m}$ is a sufficient upper bound on the + error in approximating the complex numbers to be plugged in. + + """ + # As explained in the docstring for this class, our precision estimates + # require that M be at least 2. + M = max(M, 2) + f = self.coeff_prec_func if target == 'coeffs' else self.root_prec_func + r, _, _, _ = evalf(2*f(M), 1, {}) + return fastlog(r) + 1 + + def approximate_roots_of_poly(self, T, target='coeffs'): + """ + Approximate the roots of a given polynomial *T* to sufficient precision + in order to evaluate this resolvent's coefficients, or determine + whether the resolvent has an integer root. + + Parameters + ========== + + T : :py:class:`~.Poly` + + target : str, 'coeffs' or 'roots', default='coeffs' + Set the approximation precision to be sufficient for the desired + task, which is either determining the coefficients of the resolvent + ('coeffs') or determining its possible integer roots ('roots'). + The latter may require significantly lower precision. + + Returns + ======= + + list of elements of :ref:`CC` + + """ + ctx = MPContext() + # Because sympy.polys.polyroots._integer_basis() is called when a CRootOf + # is formed, we proactively extract the integer basis now. This means that + # when we call T.all_roots(), every root will be a CRootOf, not a Mul + # of Integer*CRootOf. + coeff, T = preprocess_roots(T) + coeff = ctx.mpf(str(coeff)) + + scaled_roots = T.all_roots(radicals=False) + + # Since we're going to be approximating the roots of T anyway, we can + # get a good upper bound on the magnitude of the roots by starting with + # a very low precision approx. + approx0 = [coeff * quad_to_mpmath(_evalf_with_bounded_error(r, m=0)) for r in scaled_roots] + # Here we add 1 to account for the possible error in our initial approximation. + M = max(abs(b) for b in approx0) + 1 + m = self.get_prec(M, target=target) + n = fastlog(M._mpf_) + 1 + p = m + n + 1 + ctx.prec = p + d = prec_to_dps(p) + + approx1 = [r.eval_approx(d, return_mpmath=True) for r in scaled_roots] + approx1 = [coeff*ctx.mpc(r) for r in approx1] + + return approx1 + + @staticmethod + def round_mpf(a): + if isinstance(a, int): + return a + # If we use python's built-in `round()`, we lose precision. + # If we use `ZZ` directly, we may add or subtract 1. + # + # XXX: We have to convert to int before converting to ZZ because + # flint.fmpz cannot convert a mpmath mpf. + return ZZ(int(a.context.nint(a))) + + def round_roots_to_integers_for_poly(self, T): + """ + For a given polynomial *T*, round the roots of this resolvent to the + nearest integers. + + Explanation + =========== + + None of the integers returned by this method is guaranteed to be a + root of the resolvent; however, if the resolvent has any integer roots + (for the given polynomial *T*), then they must be among these. + + If the coefficients of the resolvent are also desired, then this method + should not be used. Instead, use the ``eval_for_poly`` method. This + method may be significantly faster than ``eval_for_poly``. + + Parameters + ========== + + T : :py:class:`~.Poly` + + Returns + ======= + + dict + Keys are the indices of those permutations in ``self.s`` such that + the corresponding root did round to a rational integer. + + Values are :ref:`ZZ`. + + + """ + approx_roots_of_T = self.approximate_roots_of_poly(T, target='roots') + approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas] + return { + i: self.round_mpf(r.real) + for i, r in enumerate(approx_roots_of_self) + if self.round_mpf(r.imag) == 0 + } + + def eval_for_poly(self, T, find_integer_root=False): + r""" + Compute the integer values of the coefficients of this resolvent, when + plugging in the roots of a given polynomial. + + Parameters + ========== + + T : :py:class:`~.Poly` + + find_integer_root : ``bool``, default ``False`` + If ``True``, then also determine whether the resolvent has an + integer root, and return the first one found, along with its + index, i.e. the index of the permutation ``self.s[i]`` it + corresponds to. + + Returns + ======= + + Tuple ``(R, a, i)`` + + ``R`` is this resolvent as a dense univariate polynomial over + :ref:`ZZ`, i.e. a list of :ref:`ZZ`. + + If *find_integer_root* was ``True``, then ``a`` and ``i`` are the + first integer root found, and its index, if one exists. + Otherwise ``a`` and ``i`` are both ``None``. + + """ + approx_roots_of_T = self.approximate_roots_of_poly(T, target='coeffs') + approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas] + approx_coeffs_of_self = [c(*approx_roots_of_self) for c in self.esf_lambdas] + + R = [] + for c in approx_coeffs_of_self: + if self.round_mpf(c.imag) != 0: + # If precision was enough, this should never happen. + raise ResolventException(f"Got non-integer coeff for resolvent: {c}") + R.append(self.round_mpf(c.real)) + + a0, i0 = None, None + + if find_integer_root: + for i, r in enumerate(approx_roots_of_self): + if self.round_mpf(r.imag) != 0: + continue + if not dup_eval(R, (a := self.round_mpf(r.real)), ZZ): + a0, i0 = a, i + break + + return R, a0, i0 + + +def wrap(text, width=80): + """Line wrap a polynomial expression. """ + out = '' + col = 0 + for c in text: + if c == ' ' and col > width: + c, col = '\n', 0 + else: + col += 1 + out += c + return out + + +def s_vars(n): + """Form the symbols s1, s2, ..., sn to stand for elem. symm. polys. """ + return symbols([f's{i + 1}' for i in range(n)]) + + +def sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=False): + """ + Compute the coefficients of a resolvent as functions of the coefficients of + the associated polynomial. + + F must be a sparse polynomial. + """ + import time, sys + # Roots of resolvent as multivariate forms over vars X: + root_forms = [ + F.compose(list(zip(X, sigma(X)))) + for sigma in s + ] + + # Coeffs of resolvent (besides lead coeff of 1) as symmetric forms over vars X: + Y = [Dummy(f'Y{i}') for i in range(len(s))] + coeff_forms = [] + for i in range(1, len(s) + 1): + if verbose: + print('----') + print(f'Computing symmetric poly of degree {i}...') + sys.stdout.flush() + t0 = time.time() + G = symmetric_poly(i, *Y) + t1 = time.time() + if verbose: + print(f'took {t1 - t0} seconds') + print('lambdifying...') + sys.stdout.flush() + t0 = time.time() + C = lambdify(Y, (-1)**i*G) + t1 = time.time() + if verbose: + print(f'took {t1 - t0} seconds') + sys.stdout.flush() + coeff_forms.append(C) + + coeffs = [] + for i, f in enumerate(coeff_forms): + if verbose: + print('----') + print(f'Plugging root forms into elem symm poly {i+1}...') + sys.stdout.flush() + t0 = time.time() + g = f(*root_forms) + t1 = time.time() + coeffs.append(g) + if verbose: + print(f'took {t1 - t0} seconds') + sys.stdout.flush() + + # Now symmetrize these coeffs. This means recasting them as polynomials in + # the elementary symmetric polys over X. + symmetrized = [] + symmetrization_times = [] + ss = s_vars(len(X)) + for i, A in list(enumerate(coeffs)): + if verbose: + print('-----') + print(f'Coeff {i+1}...') + sys.stdout.flush() + t0 = time.time() + B, rem, _ = A.symmetrize() + t1 = time.time() + if rem != 0: + msg = f"Got nonzero remainder {rem} for resolvent (F, X, s) = ({F}, {X}, {s})" + raise ResolventException(msg) + B_str = str(B.as_expr(*ss)) + symmetrized.append(B_str) + symmetrization_times.append(t1 - t0) + if verbose: + print(wrap(B_str)) + print(f'took {t1 - t0} seconds') + sys.stdout.flush() + + return symmetrized, symmetrization_times + + +def define_resolvents(): + """Define all the resolvents for polys T of degree 4 through 6. """ + from sympy.combinatorics.galois import PGL2F5 + from sympy.combinatorics.permutations import Permutation + + R4, X4 = xring("X0,X1,X2,X3", ZZ, lex) + X = X4 + + # The one resolvent used in `_galois_group_degree_4_lookup()`: + F40 = X[0]*X[1]**2 + X[1]*X[2]**2 + X[2]*X[3]**2 + X[3]*X[0]**2 + s40 = [ + Permutation(3), + Permutation(3)(0, 1), + Permutation(3)(0, 2), + Permutation(3)(0, 3), + Permutation(3)(1, 2), + Permutation(3)(2, 3), + ] + + # First resolvent used in `_galois_group_degree_4_root_approx()`: + F41 = X[0]*X[2] + X[1]*X[3] + s41 = [ + Permutation(3), + Permutation(3)(0, 1), + Permutation(3)(0, 3) + ] + + R5, X5 = xring("X0,X1,X2,X3,X4", ZZ, lex) + X = X5 + + # First resolvent used in `_galois_group_degree_5_hybrid()`, + # and only one used in `_galois_group_degree_5_lookup_ext_factor()`: + F51 = ( X[0]**2*(X[1]*X[4] + X[2]*X[3]) + + X[1]**2*(X[2]*X[0] + X[3]*X[4]) + + X[2]**2*(X[3]*X[1] + X[4]*X[0]) + + X[3]**2*(X[4]*X[2] + X[0]*X[1]) + + X[4]**2*(X[0]*X[3] + X[1]*X[2])) + s51 = [ + Permutation(4), + Permutation(4)(0, 1), + Permutation(4)(0, 2), + Permutation(4)(0, 3), + Permutation(4)(0, 4), + Permutation(4)(1, 4) + ] + + R6, X6 = xring("X0,X1,X2,X3,X4,X5", ZZ, lex) + X = X6 + + # First resolvent used in `_galois_group_degree_6_lookup()`: + H = PGL2F5() + term0 = X[0]**2*X[5]**2*(X[1]*X[4] + X[2]*X[3]) + terms = {term0.compose(list(zip(X, s(X)))) for s in H.elements} + F61 = sum(terms) + s61 = [Permutation(5)] + [Permutation(5)(0, n) for n in range(1, 6)] + + # Second resolvent used in `_galois_group_degree_6_lookup()`: + F62 = X[0]*X[1]*X[2] + X[3]*X[4]*X[5] + s62 = [Permutation(5)] + [ + Permutation(5)(i, j + 3) for i in range(3) for j in range(3) + ] + + return { + (4, 0): (F40, X4, s40), + (4, 1): (F41, X4, s41), + (5, 1): (F51, X5, s51), + (6, 1): (F61, X6, s61), + (6, 2): (F62, X6, s62), + } + + +def generate_lambda_lookup(verbose=False, trial_run=False): + """ + Generate the whole lookup table of coeff lambdas, for all resolvents. + """ + jobs = define_resolvents() + lambda_lists = {} + total_time = 0 + time_for_61 = 0 + time_for_61_last = 0 + for k, (F, X, s) in jobs.items(): + symmetrized, times = sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=verbose) + + total_time += sum(times) + if k == (6, 1): + time_for_61 = sum(times) + time_for_61_last = times[-1] + + sv = s_vars(len(X)) + head = f'lambda {", ".join(str(v) for v in sv)}:' + lambda_lists[k] = ',\n '.join([ + f'{head} ({wrap(f)})' + for f in symmetrized + ]) + + if trial_run: + break + + table = ( + "# This table was generated by a call to\n" + "# `sympy.polys.numberfields.galois_resolvents.generate_lambda_lookup()`.\n" + f"# The entire job took {total_time:.2f}s.\n" + f"# Of this, Case (6, 1) took {time_for_61:.2f}s.\n" + f"# The final polynomial of Case (6, 1) alone took {time_for_61_last:.2f}s.\n" + "resolvent_coeff_lambdas = {\n") + + for k, L in lambda_lists.items(): + table += f" {k}: [\n" + table += " " + L + '\n' + table += " ],\n" + table += "}\n" + return table + + +def get_resolvent_by_lookup(T, number): + """ + Use the lookup table, to return a resolvent (as dup) for a given + polynomial *T*. + + Parameters + ========== + + T : Poly + The polynomial whose resolvent is needed + + number : int + For some degrees, there are multiple resolvents. + Use this to indicate which one you want. + + Returns + ======= + + dup + + """ + from sympy.polys.numberfields.resolvent_lookup import resolvent_coeff_lambdas + degree = T.degree() + L = resolvent_coeff_lambdas[(degree, number)] + T_coeffs = T.rep.to_list()[1:] + return [ZZ(1)] + [c(*T_coeffs) for c in L] + + +# Use +# (.venv) $ python -m sympy.polys.numberfields.galois_resolvents +# to reproduce the table found in resolvent_lookup.py +if __name__ == "__main__": + import sys + verbose = '-v' in sys.argv[1:] + trial_run = '-t' in sys.argv[1:] + table = generate_lambda_lookup(verbose=verbose, trial_run=trial_run) + print(table) diff --git a/shared/package-files/38/38bf39818535783f1cb8f9629227c59e05e97818dac65eab209f0a902ff7afe2/entry_points.txt b/shared/package-files/38/38bf39818535783f1cb8f9629227c59e05e97818dac65eab209f0a902ff7afe2/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..abc3eae3b3bc573957cf7401711948799b3465c0 --- /dev/null +++ b/shared/package-files/38/38bf39818535783f1cb8f9629227c59e05e97818dac65eab209f0a902ff7afe2/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/shared/package-files/38/38cc2c0e21e82ae24f242e7ae8b9066ae50cc231c0a2b779164f917089d73b52/test_legendre.cpython-311.pyc b/shared/package-files/38/38cc2c0e21e82ae24f242e7ae8b9066ae50cc231c0a2b779164f917089d73b52/test_legendre.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad9797a3ffd0c6286f4be41d25ae2c1949a5fb71 Binary files /dev/null and b/shared/package-files/38/38cc2c0e21e82ae24f242e7ae8b9066ae50cc231c0a2b779164f917089d73b52/test_legendre.cpython-311.pyc differ diff --git a/shared/package-files/38/38cde045764c798cf6cb2d2b183718cc78794d8fde1cb212f5f2c12b55881018/test_bitwise.cpython-311.pyc b/shared/package-files/38/38cde045764c798cf6cb2d2b183718cc78794d8fde1cb212f5f2c12b55881018/test_bitwise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b12ca5b91e448cad40a379b73f2039fac49e66a3 Binary files /dev/null and b/shared/package-files/38/38cde045764c798cf6cb2d2b183718cc78794d8fde1cb212f5f2c12b55881018/test_bitwise.cpython-311.pyc differ diff --git a/shared/package-files/38/38cf9581ed6c6ad1fe3006305a1ada797728ae7d4a1adbaa04af8f0dd75a3ab9/simple_mmlctop.xsl b/shared/package-files/38/38cf9581ed6c6ad1fe3006305a1ada797728ae7d4a1adbaa04af8f0dd75a3ab9/simple_mmlctop.xsl new file mode 100644 index 0000000000000000000000000000000000000000..0cd73bccc24c963ed9c6c4121cc410997b94261c --- /dev/null +++ b/shared/package-files/38/38cf9581ed6c6ad1fe3006305a1ada797728ae7d4a1adbaa04af8f0dd75a3ab9/simple_mmlctop.xsl @@ -0,0 +1,3166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + e + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [ + + + ] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + id + + + id + + + + + + + + + + + + + + domain + + + codomain + + + image + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + { + + + + + + + + if + + + + + + + + + + + otherwise + + + + + + + + + + + + + + + + + + + + + + + &#x230A; + + + + + + + + + + + + + + + + + + + &#x230B; + + + + + + + + + + + + e + + + + + + + + + + + + + + + + + ! + + + + + + + + + + + + + + + + max + + + min + + + + + + + max + + + min + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + gcd + + + lcm + + + + + + gcd + + + lcm + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2227; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2228; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x22BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + + + + + &#x2200; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + &#x2203; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00AF; + + + + + + + + + + + + + + + + + &#x211C; + + + &#x2111; + + + &#x2061; + + + + + + + + + + + + + + + + + &#x230A; + + + &#x2308; + + + + + + &#x230B; + + + &#x2309; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2260; + + + &#x2248; + + + &#x2223; + + + + + &#x2198; + + + &#x2197; + + + &#x2192; + + + + + &#x21D2; + + + &#x2208; + + + &#x2209; + + + &#x2284; + + + &#x2288; + + + + + + + + + + &#x2286; + + + &#x2282; + + + + + + + + + + + + &#x2265; + + + &#x2264; + + + &#x2261; + + + + + + + + + + + + + + + + + + + + + + ln + + + + + ln + + + + + + + + + + + + + + + + + + + + + + log + + + + + + log + + + + + + + + log + + + + log + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + d + + d + + + + + + + + d + + + + d + + + + + + + + + + + + + + + + + + &#x2032; + + + + + + + + + + + + + + + + + &#x2145; + + + + + + + + &#x2202; + + + + + &#x2202; + + + + + + + + + + + + + + + + + + + &#x2202; + + + + &#x2202; + + + + + + + + + + &#x2202; + + &#x2202; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2207; + 2 + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x222A; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2229; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + = + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + + + + + + + + + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + + + + + + + &#x222B; + + + + + + + + + &#x222B; + + + + + + + + + d + + + + + + + + + + + + + + + + lim + + + + &#x2192; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + 2 + + + + + + + + + + + + + median + + + + + + + + + + + + + + + + + mode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + det + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + &#x22C5; + + + &#x2297; + + + + + + + + + + + + &#x2124; + + + + &#x211D; + + + + &#x211A; + + + + &#x2115; + + + + &#x2102; + + + + &#x2119; + + + + e + + + + &#x2148; + + + + NaN + + + + true + + + + false + + + + &#x2205; + + + + &#x03C0; + + + + &#x213D; + + + + &#x221E; + + + diff --git a/shared/package-files/38/38d23cc7e79df8872a385e0ada5d0b554bc450ddbf747cedbcbe1ab91b22ebb5/singularityfunctions.py b/shared/package-files/38/38d23cc7e79df8872a385e0ada5d0b554bc450ddbf747cedbcbe1ab91b22ebb5/singularityfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..3e33d0542c45b67b193f17e00c25837f3a82109a --- /dev/null +++ b/shared/package-files/38/38d23cc7e79df8872a385e0ada5d0b554bc450ddbf747cedbcbe1ab91b22ebb5/singularityfunctions.py @@ -0,0 +1,63 @@ +from sympy.functions import SingularityFunction, DiracDelta +from sympy.integrals import integrate + + +def singularityintegrate(f, x): + """ + This function handles the indefinite integrations of Singularity functions. + The ``integrate`` function calls this function internally whenever an + instance of SingularityFunction is passed as argument. + + Explanation + =========== + + The idea for integration is the following: + + - If we are dealing with a SingularityFunction expression, + i.e. ``SingularityFunction(x, a, n)``, we just return + ``SingularityFunction(x, a, n + 1)/(n + 1)`` if ``n >= 0`` and + ``SingularityFunction(x, a, n + 1)`` if ``n < 0``. + + - If the node is a multiplication or power node having a + SingularityFunction term we rewrite the whole expression in terms of + Heaviside and DiracDelta and then integrate the output. Lastly, we + rewrite the output of integration back in terms of SingularityFunction. + + - If none of the above case arises, we return None. + + Examples + ======== + + >>> from sympy.integrals.singularityfunctions import singularityintegrate + >>> from sympy import SingularityFunction, symbols, Function + >>> x, a, n, y = symbols('x a n y') + >>> f = Function('f') + >>> singularityintegrate(SingularityFunction(x, a, 3), x) + SingularityFunction(x, a, 4)/4 + >>> singularityintegrate(5*SingularityFunction(x, 5, -2), x) + 5*SingularityFunction(x, 5, -1) + >>> singularityintegrate(6*SingularityFunction(x, 5, -1), x) + 6*SingularityFunction(x, 5, 0) + >>> singularityintegrate(x*SingularityFunction(x, 0, -1), x) + 0 + >>> singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x) + f(1)*SingularityFunction(x, 1, 0) + + """ + + if not f.has(SingularityFunction): + return None + + if isinstance(f, SingularityFunction): + x, a, n = f.args + if n.is_positive or n.is_zero: + return SingularityFunction(x, a, n + 1)/(n + 1) + elif n in (-1, -2, -3, -4): + return SingularityFunction(x, a, n + 1) + + if f.is_Mul or f.is_Pow: + + expr = f.rewrite(DiracDelta) + expr = integrate(expr, x) + return expr.rewrite(SingularityFunction) + return None diff --git a/shared/package-files/38/38db671b68f969d61380f9fea3309768add835ed23f919bf03c9f5b40f5e3b31/__init__.cpython-311.pyc b/shared/package-files/38/38db671b68f969d61380f9fea3309768add835ed23f919bf03c9f5b40f5e3b31/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ddfa390ebcbc696678c3fcc53be67247fb60252 Binary files /dev/null and b/shared/package-files/38/38db671b68f969d61380f9fea3309768add835ed23f919bf03c9f5b40f5e3b31/__init__.cpython-311.pyc differ diff --git a/shared/package-files/38/38dc998ee2d180a64d4fe561b79287b19850df405f48fe72dede7a65d71de844/_endian.py b/shared/package-files/38/38dc998ee2d180a64d4fe561b79287b19850df405f48fe72dede7a65d71de844/_endian.py new file mode 100644 index 0000000000000000000000000000000000000000..6f674b21371c4047e7649814bb71020e523b9986 --- /dev/null +++ b/shared/package-files/38/38dc998ee2d180a64d4fe561b79287b19850df405f48fe72dede7a65d71de844/_endian.py @@ -0,0 +1,78 @@ +import sys +from ctypes import * + +_array_type = type(Array) + +def _other_endian(typ): + """Return the type with the 'other' byte order. Simple types like + c_int and so on already have __ctype_be__ and __ctype_le__ + attributes which contain the types, for more complicated types + arrays and structures are supported. + """ + # check _OTHER_ENDIAN attribute (present if typ is primitive type) + if hasattr(typ, _OTHER_ENDIAN): + return getattr(typ, _OTHER_ENDIAN) + # if typ is array + if isinstance(typ, _array_type): + return _other_endian(typ._type_) * typ._length_ + # if typ is structure or union + if issubclass(typ, (Structure, Union)): + return typ + raise TypeError("This type does not support other endian: %s" % typ) + +class _swapped_meta: + def __setattr__(self, attrname, value): + if attrname == "_fields_": + fields = [] + for desc in value: + name = desc[0] + typ = desc[1] + rest = desc[2:] + fields.append((name, _other_endian(typ)) + rest) + value = fields + super().__setattr__(attrname, value) +class _swapped_struct_meta(_swapped_meta, type(Structure)): pass +class _swapped_union_meta(_swapped_meta, type(Union)): pass + +################################################################ + +# Note: The Structure metaclass checks for the *presence* (not the +# value!) of a _swapped_bytes_ attribute to determine the bit order in +# structures containing bit fields. + +if sys.byteorder == "little": + _OTHER_ENDIAN = "__ctype_be__" + + LittleEndianStructure = Structure + + class BigEndianStructure(Structure, metaclass=_swapped_struct_meta): + """Structure with big endian byte order""" + __slots__ = () + _swappedbytes_ = None + + LittleEndianUnion = Union + + class BigEndianUnion(Union, metaclass=_swapped_union_meta): + """Union with big endian byte order""" + __slots__ = () + _swappedbytes_ = None + +elif sys.byteorder == "big": + _OTHER_ENDIAN = "__ctype_le__" + + BigEndianStructure = Structure + + class LittleEndianStructure(Structure, metaclass=_swapped_struct_meta): + """Structure with little endian byte order""" + __slots__ = () + _swappedbytes_ = None + + BigEndianUnion = Union + + class LittleEndianUnion(Union, metaclass=_swapped_union_meta): + """Union with little endian byte order""" + __slots__ = () + _swappedbytes_ = None + +else: + raise RuntimeError("Invalid byteorder") diff --git a/shared/package-files/38/38de78597cab8f71dca65810e1132acba5bd17fe41ca931a2ce3339c292cdd06/_validate_sparse_coo_tensor_args_native.h b/shared/package-files/38/38de78597cab8f71dca65810e1132acba5bd17fe41ca931a2ce3339c292cdd06/_validate_sparse_coo_tensor_args_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9ddf2ef7e5c43757c23b89de8d6350467f4f3c6d --- /dev/null +++ b/shared/package-files/38/38de78597cab8f71dca65810e1132acba5bd17fe41ca931a2ce3339c292cdd06/_validate_sparse_coo_tensor_args_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _validate_sparse_coo_tensor_args(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional is_coalesced=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38e0e4b7a0f7da244855d1dc447d1895b76b42ecd39e89c85ede027017ebf2df/_content_store.py b/shared/package-files/38/38e0e4b7a0f7da244855d1dc447d1895b76b42ecd39e89c85ede027017ebf2df/_content_store.py new file mode 100644 index 0000000000000000000000000000000000000000..fab3730a43c87b77094f513a140bbbaae5ff725f --- /dev/null +++ b/shared/package-files/38/38e0e4b7a0f7da244855d1dc447d1895b76b42ecd39e89c85ede027017ebf2df/_content_store.py @@ -0,0 +1,239 @@ +# mypy: allow-untyped-defs +# This module provides a FAST (on GPU) content addressable store for storages +# (and tensors on top of them) with VERY WEAK portability guarantees (e.g., +# don't expect CPU/CUDA to address to the same hash, don't expect it to be +# portable across devices) that is NOT cryptographically secure. In return, +# we are able to hash 40G of tensor data on GPU in less than a second, +# compared to running SHA-1 in CPU which would a minute or so. The primary +# use case is for efficiently snapshotting intermediate tensor data for +# offline debugging, but it's been put in this module in case you think of +# another use case for it. The hash function could be replaced with a +# straight reimplementation of SHA-1, which would give us much stronger +# portability guarantees. +# +# WARNING: THERE IS NO BC/FC GUARANTEE FOR THIS FORMAT! If you need to format +# shift the result, consider packing it into a single torch.save object +# with traditional view sharing. +# +# Because of the weak portability guarantees, you can only write to the +# content store from a single process; we don't provide any capability +# of "reopening" a content store to add more things to it. But we don't +# assume that you can keep all of the tensors you want to add to the store +# in memory at once, because you probably can't! Nor do we assume that +# you know a priori whether or not two storages can be deduplicated or not. +# +# Note: only storages are content-addressed; tensors are name addressed +# +# Note: our padding strategy means that [1, 0] and [1] int16 tensors would +# map to the same (padded) storage. We think this will be immaterial for most +# users. + +import ctypes +import functools +import hashlib +import os.path +import struct +from collections import defaultdict +from typing import Optional + +import torch +import torch._prims as prims +import torch._utils +import torch.nn.functional as F +from torch.multiprocessing.reductions import StorageWeakRef + + +def lazy_compile(**compile_kwargs): + """Lazily wrap a function with torch.compile on the first call + + This avoids eagerly importing dynamo. + """ + + def decorate_fn(fn): + @functools.wraps(fn) + def compile_hook(*args, **kwargs): + compiled_fn = torch.compile(fn, **compile_kwargs) + globals()[fn.__name__] = functools.wraps(fn)(compiled_fn) + return compiled_fn(*args, **kwargs) + + return compile_hook + + return decorate_fn + + +# Use of torch.compile is mandatory for (1) good memory usage +# and (2) xor_sum implementation. This is our first instance of +# using PT2 to implement a kernel in PyTorch; if we get AOT capabilities +# it would be good to apply it here. +@lazy_compile(dynamic=True) +def hash_storage_kernel(x): + # The randint calls are carefully written to hit things we + # have lowerings for in inductor. Lack of unsigned 32-bit integer + # is a pain. + a = torch.randint( + -(2**31), 2**31, x.shape, device=x.device, dtype=torch.int32 + ).abs() + a = ((a % (2**31 - 1)) + 1).long() + b = ( + torch.randint(-(2**31), 2**31, x.shape, device=x.device, dtype=torch.int32) + .abs() + .long() + ) + # This is a standard shift-multiply universal hash family + # plus xor sum hash, using Philox to generate random numbers. + # Our Philox RNG is not deterministic across devices so + # don't use this for stable hashing. + # + # This assumes fixed length so you're also obligated to bucket + # by the length of tensor as well + return prims.xor_sum((a * x + b).int(), [0]) + + +# Returns a hex digest of the data in the storage. Guaranteed to be +# SHA-1 if stable_hash=True, otherwise it will consistent for a single +# process run but not necessarily across processes. +def hash_storage(storage: torch.UntypedStorage, *, stable_hash: bool = False) -> str: + import torch._dynamo + from torch._dynamo.utils import is_compile_supported + + device_type = storage.device.type + if stable_hash or not is_compile_supported(device_type): + cpu_storage = storage.cpu() + # TODO: make storage support buffer protocol so this isn't + # necessary + buf = (ctypes.c_byte * cpu_storage.nbytes()).from_address( + cpu_storage.data_ptr() + ) + sha1 = hashlib.sha1(usedforsecurity=False) + sha1.update(buf) + return sha1.hexdigest() + + # TODO: factor this into a random utility + if device_type == "cpu": + generator = torch._C.default_generator + elif device_type == "cuda": + generator = torch.cuda.default_generators[storage.device.index] + elif device_type == "mps": + generator = torch.mps._get_default_mps_generator() + elif device_type == "xpu": + generator = torch.xpu.default_generators[storage.device.index] + else: + raise AssertionError(f"unhandled device type {device_type}") + state = generator.get_state() + try: + generator.manual_seed(0) + x = torch.empty(0, dtype=torch.uint8, device=storage.device).set_(storage) # type: ignore[call-overload] + # The dtype-casting view cannot be compiled, and so the + # padding/reshaping also needs to be done externally even + # though it could be profitably fused + pad = -x.numel() % 4 + if pad > 0: + x = F.pad(x, (0, pad), "constant", 0) + x = x.view(torch.int32) + # We run the 32-bit hash five times with differing parameters to + # reduce chance of collision + ITER = 5 + cs = [hash_storage_kernel(x).item() for _ in range(ITER)] + return struct.pack(">" + "i" * ITER, *cs).hex() + finally: + generator.set_state(state) + + +class ContentStoreWriter: + # Structure: + # storages/ + # 00/ + # 0000..00 + # tensors/ + # name + def __init__(self, loc: str, stable_hash: bool = False) -> None: + self.loc: str = loc + self.seen_storage_hashes: set[str] = set() + self.stable_hash = stable_hash + + # TODO: offer some sort of non-blocking API to speed things up + def write_storage(self, storage: torch.UntypedStorage) -> str: + h = hash_storage(storage, stable_hash=self.stable_hash) + if h in self.seen_storage_hashes: + return h + # TODO: consider not using torch.save for this; we don't actually + # need any metadata for the storage + subfolder = os.path.join(self.loc, "storages") + os.makedirs(subfolder, exist_ok=True) + target = os.path.join(subfolder, h) + if os.path.exists(target): + return h + torch.save(storage, target) + self.seen_storage_hashes.add(h) + return h + + def compute_tensor_metadata(self, t: torch.Tensor, h=None): + if h is None: + h = hash_storage(t.untyped_storage(), stable_hash=self.stable_hash) + return ( + t.dtype, + h, + t.storage_offset(), + tuple(t.shape), + t.stride(), + torch._utils.get_tensor_metadata(t), + ) + + def write_tensor(self, name: str, t: torch.Tensor) -> None: + storage = t.untyped_storage() + h = self.write_storage(storage) + # TODO: Support more advanced snapshotting of requires_grad/grad/etc + d, f = os.path.split(name) + payload = self.compute_tensor_metadata(t, h=h) + subfolder = os.path.join(self.loc, "tensors", d) + os.makedirs(subfolder, exist_ok=True) + torch.save(payload, os.path.join(subfolder, f)) + + +class ContentStoreReader: + def __init__(self, loc: str, *, cache=True) -> None: + self.loc = loc + self.storage_cache: Optional[ + dict[Optional[torch.device], dict[str, StorageWeakRef]] + ] = None + if cache: + self.storage_cache = defaultdict(dict) + + def read_storage(self, h: str, *, device=None) -> torch.UntypedStorage: + if device is not None: + device = torch.device(device) + ws = ( + self.storage_cache[device].get(h) + if self.storage_cache is not None + else None + ) + s: Optional[torch.UntypedStorage] + if ws is not None: + s = torch.UntypedStorage._new_with_weak_ptr(ws.cdata) + if s is not None: + return s + s = torch.load( + os.path.join(self.loc, "storages", h), + weights_only=True, + map_location=device, + )._untyped_storage + assert s is not None + if self.storage_cache is not None: + self.storage_cache[device][h] = StorageWeakRef(s) + return s + + def read_tensor_metadata(self, name: str): + fn = os.path.join(self.loc, "tensors", name) + if not os.path.exists(fn): + raise FileNotFoundError(fn) + return torch.load(fn, weights_only=True) + + def read_tensor(self, name: str, *, device=None) -> torch.Tensor: + dtype, h, storage_offset, size, stride, metadata = self.read_tensor_metadata( + name + ) + storage = self.read_storage(h, device=device) + t = torch.tensor([], dtype=dtype, device=storage.device) + t.set_(storage, storage_offset, size, stride) + torch._utils.set_tensor_metadata(t, metadata) + return t diff --git a/shared/package-files/38/38eeaf6a551c99f4ec93f5b6b13dc2fb9049665147561eb5731fcb0a19ca87e6/test_attracting.cpython-311.pyc b/shared/package-files/38/38eeaf6a551c99f4ec93f5b6b13dc2fb9049665147561eb5731fcb0a19ca87e6/test_attracting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55116a58351d0e46a0525c7398d695e033dad71c Binary files /dev/null and b/shared/package-files/38/38eeaf6a551c99f4ec93f5b6b13dc2fb9049665147561eb5731fcb0a19ca87e6/test_attracting.cpython-311.pyc differ diff --git a/shared/package-files/38/38f679fbb442ac86ac89ce4650588a8c4d028e9eeff21e625d2d851ea4c17a80/greater_equal_native.h b/shared/package-files/38/38f679fbb442ac86ac89ce4650588a8c4d028e9eeff21e625d2d851ea4c17a80/greater_equal_native.h new file mode 100644 index 0000000000000000000000000000000000000000..001198a67530a3506e4f6cc2295c03abc598cd62 --- /dev/null +++ b/shared/package-files/38/38f679fbb442ac86ac89ce4650588a8c4d028e9eeff21e625d2d851ea4c17a80/greater_equal_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor greater_equal(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & greater_equal_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & greater_equal_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor greater_equal(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & greater_equal_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & greater_equal_(at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/38/38faf4c992334a9ef05ce546208b291bdd4b8d1a56c5365ce58571075a34d57c/reflection_pad3d_backward_native.h b/shared/package-files/38/38faf4c992334a9ef05ce546208b291bdd4b8d1a56c5365ce58571075a34d57c/reflection_pad3d_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2d31ec6f98f33698262661ec79d2260792c7300a --- /dev/null +++ b/shared/package-files/38/38faf4c992334a9ef05ce546208b291bdd4b8d1a56c5365ce58571075a34d57c/reflection_pad3d_backward_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_reflection_pad3d_backward_out_cpu : public at::meta::structured_reflection_pad3d_backward { +void impl(const at::Tensor & grad_output, const at::Tensor & self, at::ArrayRef padding, const at::Tensor & grad_input); +}; +struct TORCH_API structured_reflection_pad3d_backward_out_cuda : public at::meta::structured_reflection_pad3d_backward { +void impl(const at::Tensor & grad_output, const at::Tensor & self, at::ArrayRef padding, const at::Tensor & grad_input); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a00a691ad4eee915627ec9f389e4fc4599f2b82597313dfedb9422524559642/fft_fftshift_ops.h b/shared/package-files/3a/3a00a691ad4eee915627ec9f389e4fc4599f2b82597313dfedb9422524559642/fft_fftshift_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7f8b343dfea2991c5e3be54451e948c7c200878c --- /dev/null +++ b/shared/package-files/3a/3a00a691ad4eee915627ec9f389e4fc4599f2b82597313dfedb9422524559642/fft_fftshift_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fft_fftshift { + using schema = at::Tensor (const at::Tensor &, at::OptionalIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fft_fftshift"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "fft_fftshift(Tensor self, int[1]? dim=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::OptionalIntArrayRef dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalIntArrayRef dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3a065186293aaeb04922c29d1c02125249752c8d67637e713d0eda6495fd74bf/conv.py b/shared/package-files/3a/3a065186293aaeb04922c29d1c02125249752c8d67637e713d0eda6495fd74bf/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..9743f40e80749df0ccbff7630ff28b7b160ed7e3 --- /dev/null +++ b/shared/package-files/3a/3a065186293aaeb04922c29d1c02125249752c8d67637e713d0eda6495fd74bf/conv.py @@ -0,0 +1,1241 @@ +# mypy: allow-untyped-defs +r"""Quantized convolution modules.""" + +from typing import ClassVar, Optional + +import torch +import torch.ao.nn.intrinsic as nni +import torch.ao.nn.intrinsic.qat as nniqat +import torch.nn as nn +import torch.nn.functional as F +from torch._ops import ops +from torch.nn.common_types import _size_1_t +from torch.nn.modules.utils import _pair, _single, _triple +from torch.nn.utils import fuse_conv_bn_weights + +from .utils import _quantize_weight, WeightedQuantizedModule + + +__all__ = [ + "Conv1d", + "Conv2d", + "Conv3d", + "ConvTranspose1d", + "ConvTranspose2d", + "ConvTranspose3d", +] + +_SUPPORTED_PADDING = {"zeros", "reflect"} + + +def _reverse_repeat_padding(padding: list[int]) -> list[int]: + _reversed_padding_repeated_twice: list[int] = [] + N = len(padding) + for idx in range(N): + _reversed_padding_repeated_twice.extend(padding[N - idx - 1] for _ in range(2)) + return _reversed_padding_repeated_twice + + +class _ConvNd(WeightedQuantizedModule): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + # All subclasses have this signature - See PR #49702s + raise NotImplementedError + + def _init( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + bias, + padding_mode="zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups") + if out_channels % groups != 0: + raise ValueError("out_channels must be divisible by groups") + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.dilation = dilation + self.transposed = transposed + self.output_padding = output_padding + self.groups = groups + if padding_mode not in _SUPPORTED_PADDING: + raise ValueError( + f"'padding_mode' {padding_mode} is not supported by quantized convolution" + ) + self.padding_mode = padding_mode + # Initialize as NCHW. set_weight will internally transpose to NHWC. + if self.transposed: + weight_shape = [in_channels, out_channels // self.groups] + else: + weight_shape = [out_channels, in_channels // self.groups] + qweight = torch._empty_affine_quantized( + weight_shape + list(kernel_size), + scale=1, + zero_point=0, + dtype=torch.qint8, + **{k: v for k, v in factory_kwargs.items() if k != "dtype"}, + ) + bias_float = ( + torch.zeros( + out_channels, + dtype=torch.float, + **{k: v for k, v in factory_kwargs.items() if k != "dtype"}, + ) + if bias + else None + ) + + self.set_weight_bias(qweight, bias_float) + self.scale = 1.0 + self.zero_point = 0 + + def set_weight_bias(self, qweight, bias_float): + raise NotImplementedError + + def bias(self): + raise NotImplementedError + + def _weight_bias(self): + raise NotImplementedError + + def extra_repr(self): + s = ( + "{in_channels}, {out_channels}, kernel_size={kernel_size}" + ", stride={stride}, scale={scale}, zero_point={zero_point}" + ) + if self.padding != (0,) * len(self.padding): + s += ", padding={padding}" + if self.dilation != (1,) * len(self.dilation): + s += ", dilation={dilation}" + if self.output_padding != (0,) * len(self.output_padding): + s += ", output_padding={output_padding}" + if self.groups != 1: + s += ", groups={groups}" + if self.bias() is None: + s += ", bias=False" + return s.format(**self.__dict__) + + # ===== Serialization methods ===== + # The special consideration here is that we have to unpack the weights into + # their regular QTensor form for serialization. Packed weights should not + # live outside the process in which they were created, rather they should be + # derived from the QTensor weight. + # self + # |--- weight : Tensor + # |--- bias : Tensor + # + # TODO: maybe change to this when https://github.com/pytorch/pytorch/pull/32958 is landed + # self + # |--- _packed_params : Conv2dPackedParamsBase or Conv3dPackedParamsBase + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + (w, b) = self._weight_bias() + destination[prefix + "weight"] = w + destination[prefix + "bias"] = b + destination[prefix + "scale"] = torch.tensor(self.scale) + destination[prefix + "zero_point"] = torch.tensor(self.zero_point) + + @torch.jit.export + def __getstate__(self): + (w, b) = self._weight_bias() + return ( + self.in_channels, + self.out_channels, + self.kernel_size, + self.stride, + self.padding, + self.dilation, + self.transposed, + self.output_padding, + self.groups, + self.padding_mode, + w, + b, + self.scale, + self.zero_point, + self.training, + ) + + # ===== Deserialization methods ===== + # Counterpart to the serialization methods, we must pack the serialized + # QTensor weight into its packed format for use by the FBGEMM ops. + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + self.set_weight_bias(state_dict[prefix + "weight"], state_dict[prefix + "bias"]) + state_dict.pop(prefix + "weight") + state_dict.pop(prefix + "bias") + self.scale = float(state_dict[prefix + "scale"]) + state_dict.pop(prefix + "scale") + self.zero_point = int(state_dict[prefix + "zero_point"]) + state_dict.pop(prefix + "zero_point") + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + False, + missing_keys, + unexpected_keys, + error_msgs, + ) + + @torch.jit.export + def __setstate__(self, state): + self.in_channels = state[0] + self.out_channels = state[1] + self.kernel_size = state[2] + self.stride = state[3] + self.padding = state[4] + self.dilation = state[5] + self.transposed = state[6] + self.output_padding = state[7] + self.groups = state[8] + self.padding_mode = state[9] + self.set_weight_bias(state[10], state[11]) + self.scale = state[12] + self.zero_point = state[13] + self.training = state[14] + + def __deepcopy__(self, memo): + new_instance = type(self).__new__(type(self)) + torch.nn.Module.__init__(new_instance) + state = self.__getstate__() + new_instance.__setstate__(state) + return new_instance + + def __copy__(self): + return self.__deepcopy__({}) + + @classmethod + def get_qconv(cls, mod, activation_post_process, weight_post_process=None): + r"""Creates a qconv object and returns it.""" + if weight_post_process is None: + weight_post_process = mod.qconfig.weight() + weight_post_process(mod.weight) + assert ( + weight_post_process.dtype == torch.qint8 + ), "Weight observer must have a dtype of qint8" + qweight = _quantize_weight(mod.weight.float(), weight_post_process) + # the __init__ call used is the one from derived classes and not the one from _ConvNd + qconv = cls( + mod.in_channels, + mod.out_channels, + mod.kernel_size, + mod.stride, + mod.padding, + mod.dilation, + mod.groups, + mod.bias is not None, + mod.padding_mode, + ) + qconv.set_weight_bias(qweight, mod.bias) + if ( + activation_post_process is None + or activation_post_process.dtype == torch.float + ): + return qconv # dynamic quantization doesn't need scale/zero_point + else: + act_scale, act_zp = activation_post_process.calculate_qparams() + qconv.scale = float(act_scale) + qconv.zero_point = int(act_zp) + return qconv + + @staticmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + if hasattr(mod, "weight_fake_quant"): + # assert type(mod) == cls.__QAT_MODULE, " nnq." + cls.__name__ + \ + # ".from_float only works for " + cls.__QAT_MODULE.__name__ + if type(mod) == cls._NNIQAT_CONV_BN_MODULE: + mod.weight, mod.bias = fuse_conv_bn_weights( + mod.weight, + mod.bias, + mod.bn.running_mean, + mod.bn.running_var, + mod.bn.eps, + mod.bn.weight, + mod.bn.bias, + ) + assert hasattr( + mod, "activation_post_process" + ), "Input QAT module must have observer attached" + weight_post_process = mod.weight_fake_quant + activation_post_process = mod.activation_post_process + else: + assert type(mod) == cls._FLOAT_MODULE, ( + " nnq." + + cls.__name__ + + ".from_float only works for " + + cls._FLOAT_MODULE.__name__ + + " but got:" + + str(type(mod)) + ) + assert hasattr( + mod, "qconfig" + ), "Input float module must have qconfig defined." + activation_post_process = ( + None + if not hasattr(mod, "activation_post_process") + else mod.activation_post_process + ) + if type(mod) in [ + cls._NNI_CONV_RELU_MODULE, + cls._NNI_CONV_ADD_MODULE, + cls._NNI_CONV_ADD_RELU_MODULE, + ]: + mod = mod[0] + weight_post_process = mod.qconfig.weight() + return cls.get_qconv(mod, activation_post_process, weight_post_process) + + @classmethod + def from_reference(cls, ref_qconv, output_scale, output_zero_point): + r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module + Args: + ref_qconv (Module): a reference quantized module, either produced by torch.ao.quantization + utilities or provided by the user + output_scale (float): scale for output Tensor + output_zero_point (int): zero point for output Tensor + """ + qconv = cls( + ref_qconv.in_channels, + ref_qconv.out_channels, + ref_qconv.kernel_size, # type: ignore[arg-type] + ref_qconv.stride, # type: ignore[arg-type] + ref_qconv.padding, # type: ignore[arg-type] + ref_qconv.dilation, # type: ignore[arg-type] + ref_qconv.groups, + ref_qconv.bias is not None, # type: ignore[arg-type] + ref_qconv.padding_mode, + device=ref_qconv.weight.device, + dtype=ref_qconv.weight.dtype, + ) + qweight = ref_qconv.get_quantized_weight() + qconv.set_weight_bias(qweight, ref_qconv.bias) + qconv.scale = float(output_scale) + qconv.zero_point = int(output_zero_point) + return qconv + + +class Conv1d(_ConvNd): + r"""Applies a 1D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv1d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv1d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> m = nn.quantized.Conv1d(16, 33, 3, stride=2) + >>> input = torch.randn(20, 16, 100) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, + ... dtype=torch.quint8) + >>> output = m(q_input) + + """ + + _FLOAT_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d + _NNIQAT_CONV_BN_MODULE: ClassVar[Optional[type[nn.Module]]] = nniqat.ConvBn1d + _NNI_CONV_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = nni.ConvReLU1d + _NNI_CONV_ADD_MODULE: ClassVar[Optional[type[nn.Module]]] = None + _NNI_CONV_ADD_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = None + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: _size_1_t = 0, + dilation: _size_1_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _single(kernel_size) + stride = _single(stride) + padding = padding if isinstance(padding, str) else _single(padding) + dilation = _single(dilation) + + # Subclasses of _ConvNd needs to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + False, + _single(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConv1d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == "zeros": + self._packed_params = torch.ops.quantized.conv1d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups + ) + else: + self._packed_params = torch.ops.quantized.conv1d_prepack( + w, b, self.stride, _pair(0), self.dilation, self.groups + ) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv1d_unpack(self._packed_params) + return w, b + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + if self.padding_mode != "zeros": + # Padding in Conv1d is stored as (p, p), need to get (p,) + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1]) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return ops.quantized.conv1d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float( + cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant + ) + + +class Conv2d(_ConvNd): + r"""Applies a 2D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv2d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # With square kernels and equal stride + >>> m = nn.quantized.Conv2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> # non-square kernels and unequal stride and with padding and dilation + >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)) + >>> input = torch.randn(20, 16, 50, 100) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + + """ + _FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d + _NNIQAT_CONV_BN_MODULE: ClassVar[Optional[type[nn.Module]]] = nniqat.ConvBn2d + _NNI_CONV_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = nni.ConvReLU2d + _NNI_CONV_ADD_MODULE: ClassVar[type[nni.ConvAdd2d]] = nni.ConvAdd2d + _NNI_CONV_ADD_RELU_MODULE: ClassVar[type[nni.ConvAddReLU2d]] = nni.ConvAddReLU2d + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _pair(kernel_size) + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + False, + _pair(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConv2d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == "zeros": + self._packed_params = torch.ops.quantized.conv2d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups + ) + else: + self._packed_params = torch.ops.quantized.conv2d_prepack( + w, b, self.stride, _pair(0), self.dilation, self.groups + ) + + def _weight_bias(self): + return self._packed_params.unpack() + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + if self.padding_mode != "zeros": + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return ops.quantized.conv2d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float( + cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant + ) + + +class Conv3d(_ConvNd): + r"""Applies a 3D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv3d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv3d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # With square kernels and equal stride + >>> m = nn.quantized.Conv3d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2)) + >>> # non-square kernels and unequal stride and with padding and dilation + >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2)) + >>> input = torch.randn(20, 16, 56, 56, 56) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + + """ + _FLOAT_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d + _NNIQAT_CONV_BN_MODULE: ClassVar[Optional[type[nn.Module]]] = nniqat.ConvBn3d + _NNI_CONV_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = nni.ConvReLU3d + _NNI_CONV_ADD_MODULE: ClassVar[Optional[type[nn.Module]]] = None + _NNI_CONV_ADD_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = None + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + assert padding_mode != "reflect", "Conv3d does not support reflection padding" + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _triple(kernel_size) + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + False, + _triple(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConv3d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == "zeros": + self._packed_params = torch.ops.quantized.conv3d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups + ) + else: + self._packed_params = torch.ops.quantized.conv3d_prepack( + w, b, self.stride, _triple(0), self.dilation, self.groups + ) + + def _weight_bias(self): + return self._packed_params.unpack() + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, D, H, W)`!") + if self.padding_mode != "zeros": + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return ops.quantized.conv3d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float( + cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant + ) + + +# === Transposed Convolutions === + + +class _ConvTransposeNd(_ConvNd): + _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]] + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + bias, + padding_mode, + device=None, + dtype=None, + ): + if padding_mode != "zeros": + raise ValueError( + f'Only "zeros" padding mode is supported for {self.__class__.__name__}' + ) + factory_kwargs = {"device": device, "dtype": dtype} + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _input_padding( + self, kernel_size: list[int], dilation: list[int], padding: list[int] + ) -> list[int]: + res = torch.jit.annotate(list[int], []) + for kdx in range(len(kernel_size)): + pad = dilation[kdx] * (kernel_size[kdx] - 1) - padding[kdx] + res.append(pad) + return res + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + r"""Creates a quantized module from a float module or qparams_dict. + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + # derived classes override cls._FLOAT_MODULE attribute + msg = ( + " nnq." + + cls.__name__ + + ".from_float only works for " + + cls._FLOAT_MODULE.__name__ # type: ignore[attr-defined] + ) + assert type(mod) == cls._FLOAT_MODULE, msg + assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined." + weight_post_process = mod.qconfig.weight() # type: ignore[operator, union-attr] + weight_post_process(mod.weight) + assert ( + weight_post_process.dtype == torch.qint8 + ), "Weight observer must have a dtype of qint8" + qweight = _quantize_weight(mod.weight.float(), weight_post_process) + # the __init__ call used is the one from derived classes and not the one from _ConvTransposeNd + qconv = cls( + mod.in_channels, + mod.out_channels, + mod.kernel_size, # type: ignore[call-arg] + mod.stride, + mod.padding, + mod.output_padding, + mod.groups, + mod.bias is not None, + mod.dilation, + mod.padding_mode, + ) + qconv.set_weight_bias(qweight, mod.bias) + if ( + not hasattr(mod, "activation_post_process") + or mod.activation_post_process.dtype == torch.float + ): + return qconv # dynamic quantization doesn't need scale/zero_point + else: + act_scale, act_zp = mod.activation_post_process.calculate_qparams() # type: ignore[operator, union-attr] + qconv.scale = float(act_scale) + qconv.zero_point = int(act_zp) + return qconv + + @staticmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module + Args: + ref_qconvt (Module): a reference quantized module, either produced by torch.ao.quantization + utilities or provided by the user + output_scale (float): scale for output Tensor + output_zero_point (int): zero point for output Tensor + """ + qconv = cls( + ref_qconvt.in_channels, + ref_qconvt.out_channels, + ref_qconvt.kernel_size, # type: ignore[arg-type] + ref_qconvt.stride, # type: ignore[arg-type] + ref_qconvt.padding, # type: ignore[arg-type] + ref_qconvt.output_padding, # type: ignore[arg-type] + ref_qconvt.groups, + ref_qconvt.bias is not None, # type: ignore[arg-type] + ref_qconvt.dilation, # type: ignore[arg-type] + ref_qconvt.padding_mode, + device=ref_qconvt.weight.device, + dtype=ref_qconvt.weight.dtype, + ) + qweight = ref_qconvt.get_quantized_weight() + qconv.set_weight_bias(qweight, ref_qconvt.bias) + qconv.scale = float(output_scale) + qconv.zero_point = int(output_zero_point) + return qconv + + +class ConvTranspose1d(_ConvTransposeNd): + r"""Applies a 1D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose1d`. + + .. note:: Currently only the QNNPACK engine is implemented. + Please, set the `torch.backends.quantized.engine = 'qnnpack'` + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv1d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> torch.backends.quantized.engine = 'qnnpack' + >>> from torch.ao.nn import quantized as nnq + >>> # With square kernels and equal stride + >>> m = nnq.ConvTranspose1d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose1d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> input = torch.randn(20, 16, 50) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv1d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose1d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12]) + """ + + _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose1d]] = nn.ConvTranspose1d + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + groups=1, + bias=True, + dilation=1, + padding_mode="zeros", + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _single(kernel_size) + stride = _single(stride) + padding = _single(padding) + dilation = _single(dilation) + output_padding = _single(output_padding) + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConvTranspose1d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose1d_prepack( + w, + b, + self.stride, + self.padding, + self.output_padding, + self.dilation, + self.groups, + ) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv_transpose1d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + return torch.ops.quantized.conv_transpose1d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference( + cls, ref_qconvt, output_scale, output_zero_point + ) + + +class ConvTranspose2d(_ConvTransposeNd): + r"""Applies a 2D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose2d`. + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv2d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # QNNPACK or FBGEMM as backend + >>> torch.backends.quantized.engine = 'qnnpack' + >>> # With square kernels and equal stride + >>> import torch.ao.nn.quantized as nnq + >>> m = nnq.ConvTranspose2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> input = torch.randn(20, 16, 50, 100) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv2d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose2d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12, 12]) + """ + + _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose2d]] = nn.ConvTranspose2d + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + groups=1, + bias=True, + dilation=1, + padding_mode="zeros", + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _pair(kernel_size) + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + output_padding = _pair(output_padding) + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConvTranspose2d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose2d_prepack( + w, + b, + self.stride, + self.padding, + self.output_padding, + self.dilation, + self.groups, + ) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv2d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + return ops.quantized.conv_transpose2d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference( + cls, ref_qconvt, output_scale, output_zero_point + ) + + +class ConvTranspose3d(_ConvTransposeNd): + r"""Applies a 3D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose3d`. + + .. note:: Currently only the FBGEMM engine is implemented. + Please, set the `torch.backends.quantized.engine = 'fbgemm'` + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv3d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose3d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> torch.backends.quantized.engine = 'fbgemm' + >>> from torch.ao.nn import quantized as nnq + >>> # With cubic kernels and equal stride + >>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2) + >>> # non-cubic kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2)) + >>> input = torch.randn(20, 16, 50, 100, 100) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12, 12, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6, 6, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12, 12, 12]) + """ + + _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose3d]] = nn.ConvTranspose3d + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + groups=1, + bias=True, + dilation=1, + padding_mode="zeros", + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _triple(kernel_size) + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + output_padding = _triple(output_padding) + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _get_name(self): + return "QuantizedConvTranspose3d" + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose3d_prepack( + w, + b, + self.stride, + self.padding, + self.output_padding, + self.dilation, + self.groups, + ) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv3d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, T, H, W)`!") + return ops.quantized.conv_transpose3d( + input, self._packed_params, self.scale, self.zero_point + ) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference( + cls, ref_qconvt, output_scale, output_zero_point + ) diff --git a/shared/package-files/3a/3a0b8196cbd7be888e484ad9c069bcbd1141216f63a10cb4926c1a82cf92f272/_test_ambiguous_defaults.h b/shared/package-files/3a/3a0b8196cbd7be888e484ad9c069bcbd1141216f63a10cb4926c1a82cf92f272/_test_ambiguous_defaults.h new file mode 100644 index 0000000000000000000000000000000000000000..87b55158d11e82827543a443f034d81a7ee7ffa7 --- /dev/null +++ b/shared/package-files/3a/3a0b8196cbd7be888e484ad9c069bcbd1141216f63a10cb4926c1a82cf92f272/_test_ambiguous_defaults.h @@ -0,0 +1,36 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_test_ambiguous_defaults.a(Tensor dummy, int a=1, int b=1) -> Tensor +inline at::Tensor _test_ambiguous_defaults(const at::Tensor & dummy, int64_t a=1, int64_t b=1) { + return at::_ops::_test_ambiguous_defaults_a::call(dummy, a, b); +} + +// aten::_test_ambiguous_defaults.b(Tensor dummy, int a=2, str b="2") -> Tensor +inline at::Tensor _test_ambiguous_defaults(const at::Tensor & dummy, int64_t a, c10::string_view b) { + return at::_ops::_test_ambiguous_defaults_b::call(dummy, a, b); +} + +} diff --git a/shared/package-files/3a/3a0dc89fef13309373b4f7a3fefcd82a0cfa7f88484f76ee1b17f5aa4656c35b/_sfdp_pattern_6.cpython-311.pyc b/shared/package-files/3a/3a0dc89fef13309373b4f7a3fefcd82a0cfa7f88484f76ee1b17f5aa4656c35b/_sfdp_pattern_6.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d3f58fddc7755b241cb719fb852eacae71690d0 Binary files /dev/null and b/shared/package-files/3a/3a0dc89fef13309373b4f7a3fefcd82a0cfa7f88484f76ee1b17f5aa4656c35b/_sfdp_pattern_6.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a120d9886df9deac8d4643dc27fd1b6581d18c8541e486fce4133a185152c6b/util.cpython-311.pyc b/shared/package-files/3a/3a120d9886df9deac8d4643dc27fd1b6581d18c8541e486fce4133a185152c6b/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9da0f20a3cb0ccd82d455edcc93bb104f09d901 Binary files /dev/null and b/shared/package-files/3a/3a120d9886df9deac8d4643dc27fd1b6581d18c8541e486fce4133a185152c6b/util.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a13a31644344899fac930410a7773919dc34af39e1453e6b16a2f849e9fd864/_foreach_max_cuda_dispatch.h b/shared/package-files/3a/3a13a31644344899fac930410a7773919dc34af39e1453e6b16a2f849e9fd864/_foreach_max_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b81aed856bca4b094cf09afd1307faf7d3e3bb0f --- /dev/null +++ b/shared/package-files/3a/3a13a31644344899fac930410a7773919dc34af39e1453e6b16a2f849e9fd864/_foreach_max_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_max(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/3a/3a1b717bb68dccec1d11e06c12e62c60bd5815c4d6121edff8e3a43b9c83eccf/_framework_compat.cpython-311.pyc b/shared/package-files/3a/3a1b717bb68dccec1d11e06c12e62c60bd5815c4d6121edff8e3a43b9c83eccf/_framework_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a308670807941b079688254ae06f37ba3641d1ff Binary files /dev/null and b/shared/package-files/3a/3a1b717bb68dccec1d11e06c12e62c60bd5815c4d6121edff8e3a43b9c83eccf/_framework_compat.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a23dceee9cfc43c5578f5557fa7be275ea6304ce53cd16eecac7ca3454538a0/special_i1e_meta.h b/shared/package-files/3a/3a23dceee9cfc43c5578f5557fa7be275ea6304ce53cd16eecac7ca3454538a0/special_i1e_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..045b0a2377bc492ba1f95602afae88b003ad7aba --- /dev/null +++ b/shared/package-files/3a/3a23dceee9cfc43c5578f5557fa7be275ea6304ce53cd16eecac7ca3454538a0/special_i1e_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_i1e : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a24fabf51b6faf964627a434198e2193d4ef931c3ca4d60c36d36d6a311bd03/nvToolsExt.h b/shared/package-files/3a/3a24fabf51b6faf964627a434198e2193d4ef931c3ca4d60c36d36d6a311bd03/nvToolsExt.h new file mode 100644 index 0000000000000000000000000000000000000000..61e60aadaad018b0d7f1430eef0c735a2f15429a --- /dev/null +++ b/shared/package-files/3a/3a24fabf51b6faf964627a434198e2193d4ef931c3ca4d60c36d36d6a311bd03/nvToolsExt.h @@ -0,0 +1,1561 @@ +/* +* Copyright 2009-2017 NVIDIA Corporation. All rights reserved. +* +* NOTICE TO USER: +* +* This source code is subject to NVIDIA ownership rights under U.S. and +* international Copyright laws. +* +* This software and the information contained herein is PROPRIETARY and +* CONFIDENTIAL to NVIDIA and is being provided under the terms and conditions +* of a form of NVIDIA software license agreement. +* +* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE +* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR +* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH +* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF +* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. +* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, +* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +* OR PERFORMANCE OF THIS SOURCE CODE. +* +* U.S. Government End Users. This source code is a "commercial item" as +* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of +* "commercial computer software" and "commercial computer software +* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) +* and is provided to the U.S. Government only as a commercial end item. +* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through +* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the +* source code with only those rights set forth herein. +* +* Any use of this source code in individual and commercial software must +* include, in the user documentation and internal comments to the code, +* the above Disclaimer and U.S. Government End Users Notice. +*/ + +/** \file nvToolsExt.h + */ + +/* ========================================================================= */ +/** \mainpage + * \tableofcontents + * \section INTRODUCTION Introduction + * + * The NVIDIA Tools Extension library is a set of functions that a + * developer can use to provide additional information to tools. + * The additional information is used by the tool to improve + * analysis and visualization of data. + * + * The library introduces close to zero overhead if no tool is + * attached to the application. The overhead when a tool is + * attached is specific to the tool. + * + * \section INITIALIZATION_SECTION Initialization + * + * Typically the tool's library that plugs into NVTX is indirectly + * loaded via enviromental properties that are platform specific. + * For some platform or special cases, the user may be required + * to instead explicity initialize instead though. This can also + * be helpful to control when the API loads a tool's library instead + * of what would typically be the first function call to emit info. + * For these rare case, see \ref INITIALIZATION for additional information. + * + * \section MARKERS_AND_RANGES Markers and Ranges + * + * Markers and ranges are used to describe events at a specific time (markers) + * or over a time span (ranges) during the execution of the application + * respectively. + * + * \subsection MARKERS Markers + * + * Markers denote specific moments in time. + * + * + * See \ref DOMAINS and \ref EVENT_ATTRIBUTES for additional information on + * how to specify the domain. + * + * \subsection THREAD_RANGES Thread Ranges + * + * Thread ranges denote nested time ranges. Nesting is maintained per thread + * per domain and does not require any additional correlation mechanism. The + * duration of a thread range is defined by the corresponding pair of + * nvtxRangePush* to nvtxRangePop API calls. + * + * See \ref DOMAINS and \ref EVENT_ATTRIBUTES for additional information on + * how to specify the domain. + * + * \subsection PROCESS_RANGES Process Ranges + * + * Process ranges denote a time span that can expose arbitrary concurrency, as + * opposed to thread ranges that only support nesting. In addition the range + * start event can happen on a different thread than the end marker. For the + * correlation of a start/end pair an unique correlation ID is used that is + * returned from the start API call and needs to be passed into the end API + * call. + * + * \subsection EVENT_ATTRIBUTES Event Attributes + * + * \ref MARKERS_AND_RANGES can be annotated with various attributes to provide + * additional information for an event or to guide the tool's visualization of + * the data. Each of the attributes is optional and if left unused the + * attributes fall back to a default value. The attributes include: + * - color + * - category + * + * To specify any attribute other than the text message, the \ref + * EVENT_ATTRIBUTE_STRUCTURE "Event Attribute Structure" must be used. + * + * \section DOMAINS Domains + * + * Domains enable developers to scope annotations. By default all events and + * annotations are in the default domain. Additional domains can be registered. + * This allows developers to scope markers, ranges, and resources names to + * avoid conflicts. + * + * The function ::nvtxDomainCreateA or ::nvtxDomainCreateW is used to create + * a named domain. + * + * Each domain maintains its own + * - categories + * - thread range stacks + * - registered strings + * + * The function ::nvtxDomainDestroy marks the end of the domain. Destroying + * a domain unregisters and destroys all objects associated with it such as + * registered strings, resource objects, named categories, and started ranges. + * + * \section RESOURCE_NAMING Resource Naming + * + * This section covers calls that allow to annotate objects with user-provided + * names in order to allow for a better analysis of complex trace data. All of + * the functions take the handle or the ID of the object to name and the name. + * The functions can be called multiple times during the execution of an + * application, however, in that case it is implementation dependent which + * name will be reported by the tool. + * + * \subsection CATEGORY_NAMING Category Naming + * + * Some function in this library support associating an integer category + * to enable filtering and sorting. The category naming functions allow + * the application to associate a user friendly name with the integer + * category. Support for domains have been added in NVTX_VERSION_2 to + * avoid collisions when domains are developed independantly. + * + * \subsection RESOURCE_OBJECTS Resource Objects + * + * Resource objects are a generic mechanism for attaching data to an application + * resource. The identifier field makes the association to a pointer or handle, + * while the type field helps provide deeper understanding of the identifier as + * well as enabling differentiation in cases where handles generated by different + * APIs may collide. The resource object may also have an associated message to + * associate with the application resource, enabling further annotation of this + * object and how it is used. + * + * The resource object was introduced in NVTX_VERSION_2 to supersede existing naming + * functions and allow the application resource identified by those functions to be + * associated to a domain. The other naming functions are still supported for backward + * compatibility but will be associated only to the default domain. + * + * \subsection RESOURCE_NAMING_OS Resource Naming + * + * Some operating system resources creation APIs do not support providing a user friendly + * name, such as some OS thread creation APIs. This API support resource naming though + * both through resource objects and functions following the pattern + * nvtxName[RESOURCE_TYPE][A|W](identifier, name). Resource objects introduced in NVTX_VERSION 2 + * supersede the other functions with a a more general method of assigning names to OS resources, + * along with associating them to domains too. The older nvtxName* functions are only associated + * with the default domain. + * \section EXTENSIONS Optional Extensions + * Optional extensions will either appear within the existing sections the extend or appear + * in the "Related Pages" when they introduce new concepts. + */ + +#ifndef NVTOOLSEXT_H_ +#define NVTOOLSEXT_H_ + +#if defined(_MSC_VER) + #ifdef NVTX_EXPORTS + #define NVTX_DECLSPEC + #else + #define NVTX_DECLSPEC __declspec(dllimport) + #endif /* NVTX_EXPORTS */ + #define NVTX_API __stdcall + #define NVTX_INLINE_STATIC __inline static +#else /*defined(__GNUC__)*/ + #define NVTX_DECLSPEC + #define NVTX_API + #define NVTX_INLINE_STATIC inline static +#endif /* Platform */ + +/** + * The nvToolsExt library depends on stdint.h. If the build tool chain in use + * does not include stdint.h then define NVTX_STDINT_TYPES_ALREADY_DEFINED + * and define the following types: + *
    + *
  • uint8_t + *
  • int8_t + *
  • uint16_t + *
  • int16_t + *
  • uint32_t + *
  • int32_t + *
  • uint64_t + *
  • int64_t + *
  • uintptr_t + *
  • intptr_t + *
+ #define NVTX_STDINT_TYPES_ALREADY_DEFINED if you are using your own header file. + */ +#ifndef NVTX_STDINT_TYPES_ALREADY_DEFINED +#include +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * Tools Extension API version + */ +#define NVTX_VERSION 2 + +/** + * Size of the nvtxEventAttributes_t structure. + */ +#define NVTX_EVENT_ATTRIB_STRUCT_SIZE ( (uint16_t)( sizeof(nvtxEventAttributes_t) ) ) + +/** + * Size of the nvtxInitializationAttributes_t structure. + */ +#define NVTX_INITIALIZATION_ATTRIB_STRUCT_SIZE ( (uint16_t)( sizeof(nvtxInitializationAttributes_t) ) ) + +#define NVTX_NO_PUSH_POP_TRACKING ((int)-2) + +typedef uint64_t nvtxRangeId_t; + + +/* \brief String Handle Structure. +* \anchor STRING_HANDLE_STRUCTURE +* +* This structure is opaque to the user and is used as a handle to reference +* a string. The tools will return a pointer through the API for the application +* to hold on it's behalf to reference the string in the future. +* +*/ +typedef struct nvtxStringHandle* nvtxStringHandle_t; + +/* \brief Domain Handle Structure. +* \anchor DOMAIN_HANDLE_STRUCTURE +* +* This structure is opaque to the user and is used as a handle to reference +* a domain. The tools will return a pointer through the API for the application +* to hold on its behalf to reference the domain in the future. +* +*/ +typedef struct nvtxDomainHandle* nvtxDomainHandle_t; + + + + + + +/* ========================================================================= */ +/** \defgroup GENERAL General + * @{ + */ + +/** --------------------------------------------------------------------------- + * Color Types + * ------------------------------------------------------------------------- */ +typedef enum nvtxColorType_t +{ + NVTX_COLOR_UNKNOWN = 0, /**< Color attribute is unused. */ + NVTX_COLOR_ARGB = 1 /**< An ARGB color is provided. */ +} nvtxColorType_t; + +/** --------------------------------------------------------------------------- + * Message Types + * ------------------------------------------------------------------------- */ +typedef enum nvtxMessageType_t +{ + NVTX_MESSAGE_UNKNOWN = 0, /**< Message payload is unused. */ + NVTX_MESSAGE_TYPE_ASCII = 1, /**< A character sequence is used as payload. */ + NVTX_MESSAGE_TYPE_UNICODE = 2, /**< A wide character sequence is used as payload. */ + /* NVTX_VERSION_2 */ + NVTX_MESSAGE_TYPE_REGISTERED = 3 /**< A unique string handle that was registered + with \ref nvtxDomainRegisterStringA() or + \ref nvtxDomainRegisterStringW(). */ +} nvtxMessageType_t; + +typedef union nvtxMessageValue_t +{ + const char* ascii; + const wchar_t* unicode; + /* NVTX_VERSION_2 */ + nvtxStringHandle_t registered; +} nvtxMessageValue_t; + + +/** @} */ /*END defgroup*/ + +/* ========================================================================= */ +/** \defgroup INITIALIZATION Initialization +* @{ +* Typically the tool's library that plugs into NVTX is indirectly +* loaded via enviromental properties that are platform specific. +* For some platform or special cases, the user may be required +* to instead explicity initialize instead though. This can also +* be helpful to control when the API loads a tool's library instead +* of what would typically be the first function call to emit info. +*/ + +/** --------------------------------------------------------------------------- +* Initialization Modes +* ------------------------------------------------------------------------- */ +typedef enum nvtxInitializationMode_t +{ + NVTX_INITIALIZATION_MODE_UNKNOWN = 0, /**< A platform that supports indirect initialization will attempt this style, otherwise expect failure. */ + NVTX_INITIALIZATION_MODE_CALLBACK_V1 = 1, /**< A function pointer conforming to NVTX_VERSION=1 will be used. */ + NVTX_INITIALIZATION_MODE_CALLBACK_V2 = 2, /**< A function pointer conforming to NVTX_VERSION=2 will be used. */ + NVTX_INITIALIZATION_MODE_SIZE +} nvtxInitializationMode_t; + + +/** \brief Initialization Attribute Structure. +* \anchor INITIALIZATION_ATTRIBUTE_STRUCTURE +* +* This structure is used to describe the attributes used for initialization +* of the NVTX API. +* +* \par Initializing the Attributes +* +* The caller should always perform the following three tasks when using +* attributes: +*
    +*
  • Zero the structure +*
  • Set the version field +*
  • Set the size field +*
+* +* Zeroing the structure sets all the event attributes types and values +* to the default value. +* +* The version and size field are used by the Tools Extension +* implementation to handle multiple versions of the attributes structure. +* NVTX_INITIALIZATION_ATTRIB_STRUCT_SIZE may be used for the size. +* +* It is recommended that the caller use one of the following to methods +* to initialize the event attributes structure: +* +* \par Method 1: Initializing nvtxInitializationAttributes_t for future compatibility +* \code +* nvtxInitializationAttributes_t initAttribs = {0}; +* initAttribs.version = NVTX_VERSION; +* initAttribs.size = NVTX_INITIALIZATION_ATTRIB_STRUCT_SIZE; +* \endcode +* +* \par Method 2: Initializing nvtxInitializationAttributes_t for a specific version +* \code +* nvtxInitializationAttributes_t initAttribs = {0}; +* initAttribs.version =2; +* initAttribs.size = (uint16_t)(sizeof(nvtxInitializationAttributes_v2)); +* \endcode +* +* If the caller uses Method 1 it is critical that the entire binary +* layout of the structure be configured to 0 so that all fields +* are initialized to the default value. +* +* The caller should either use both NVTX_VERSION and +* NVTX_INITIALIZATION_ATTRIB_STRUCT_SIZE (Method 1) or use explicit values +* and a versioned type (Method 2). Using a mix of the two methods +* will likely cause either source level incompatibility or binary +* incompatibility in the future. +* +* \par Settings Attribute Types and Values +* +* +* \par Example: +* \code +* // Initialize +* nvtxInitializationAttributes_t initAttribs = {0}; +* initAttribs.version = NVTX_VERSION; +* initAttribs.size = NVTX_INITIALIZATION_ATTRIB_STRUCT_SIZE; +* +* // Configure the Attributes +* initAttribs.mode = NVTX_INITIALIZATION_MODE_CALLBACK_V2; +* initAttribs.fnptr = InitializeInjectionNvtx2; +* \endcode + +* \sa +* ::nvtxInitializationMode_t +* ::nvtxInitialize +*/ +typedef struct nvtxInitializationAttributes_v2 +{ + /** + * \brief Version flag of the structure. + * + * Needs to be set to NVTX_VERSION to indicate the version of NVTX APIs + * supported in this header file. This can optionally be overridden to + * another version of the tools extension library. + */ + uint16_t version; + + /** + * \brief Size of the structure. + * + * Needs to be set to the size in bytes of the event attribute + * structure used to specify the event. + */ + uint16_t size; + + /** + * \brief Mode of initialization. + * + * The mode of initialization dictates the overall behavior and which + * attributes in this struct will be used. + * + * Default Value is NVTX_INITIALIZATION_MODE_UNKNOWN = 0 + * \sa + * ::nvtxInitializationMode_t + */ + uint32_t mode; + + /** + * \brief Function pointer used for initialization if the mode requires + * + * The user has retrieved this function pointer from the tool library + * and would like to use it to initialize. The mode must be set to a + * NVTX_INITIALIZATION_MODE_CALLBACK_V# for this to be used. The mode + * will dictate the expectations for this member. The function signature + * will be cast from void(*)() to the appropriate signature for the mode. + * the expected behavior of the function will also depend on the mode + * beyond the simple function signature. + * + * Default Value is NVTX_INITIALIZATION_MODE_UNKNOWN which will either + * initialize based on external properties or fail if not supported on + * the given platform. + + * \sa + * ::nvtxInitializationMode_t + */ + void(*fnptr)(void); + +} nvtxInitializationAttributes_v2; + +typedef struct nvtxInitializationAttributes_v2 nvtxInitializationAttributes_t; + + +/* ------------------------------------------------------------------------- */ +/** \brief Force initialization (optional on most platforms) +* +* Force NVTX library to initialize. On some platform NVTX will implicit initialize +* upon the first function call into an NVTX API. +* +* \return Result codes are simplest to assume NVTX_SUCCESS or !NVTX_SUCCESS +* +* \param initAttrib - The initialization attribute structure +* +* \sa +* ::nvtxInitializationAttributes_t +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC int NVTX_API nvtxInitialize(const nvtxInitializationAttributes_t* initAttrib); +/** @} */ + + +/** @} */ /*END defgroup*/ + +/* ========================================================================= */ +/** \defgroup EVENT_ATTRIBUTES Event Attributes +* @{ +*/ + +/** --------------------------------------------------------------------------- +* Payload Types +* ------------------------------------------------------------------------- */ +typedef enum nvtxPayloadType_t +{ + NVTX_PAYLOAD_UNKNOWN = 0, /**< Color payload is unused. */ + NVTX_PAYLOAD_TYPE_UNSIGNED_INT64 = 1, /**< A 64 bit unsigned integer value is used as payload. */ + NVTX_PAYLOAD_TYPE_INT64 = 2, /**< A 64 bit signed integer value is used as payload. */ + NVTX_PAYLOAD_TYPE_DOUBLE = 3, /**< A 64 bit floating point value is used as payload. */ + /* NVTX_VERSION_2 */ + NVTX_PAYLOAD_TYPE_UNSIGNED_INT32 = 4, /**< A 32 bit floating point value is used as payload. */ + NVTX_PAYLOAD_TYPE_INT32 = 5, /**< A 32 bit floating point value is used as payload. */ + NVTX_PAYLOAD_TYPE_FLOAT = 6 /**< A 32 bit floating point value is used as payload. */ +} nvtxPayloadType_t; + +/** \brief Event Attribute Structure. + * \anchor EVENT_ATTRIBUTE_STRUCTURE + * + * This structure is used to describe the attributes of an event. The layout of + * the structure is defined by a specific version of the tools extension + * library and can change between different versions of the Tools Extension + * library. + * + * \par Initializing the Attributes + * + * The caller should always perform the following three tasks when using + * attributes: + *
    + *
  • Zero the structure + *
  • Set the version field + *
  • Set the size field + *
+ * + * Zeroing the structure sets all the event attributes types and values + * to the default value. + * + * The version and size field are used by the Tools Extension + * implementation to handle multiple versions of the attributes structure. + * + * It is recommended that the caller use one of the following to methods + * to initialize the event attributes structure: + * + * \par Method 1: Initializing nvtxEventAttributes for future compatibility + * \code + * nvtxEventAttributes_t eventAttrib = {0}; + * eventAttrib.version = NVTX_VERSION; + * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; + * \endcode + * + * \par Method 2: Initializing nvtxEventAttributes for a specific version + * \code + * nvtxEventAttributes_t eventAttrib = {0}; + * eventAttrib.version = 1; + * eventAttrib.size = (uint16_t)(sizeof(nvtxEventAttributes_v1)); + * \endcode + * + * If the caller uses Method 1 it is critical that the entire binary + * layout of the structure be configured to 0 so that all fields + * are initialized to the default value. + * + * The caller should either use both NVTX_VERSION and + * NVTX_EVENT_ATTRIB_STRUCT_SIZE (Method 1) or use explicit values + * and a versioned type (Method 2). Using a mix of the two methods + * will likely cause either source level incompatibility or binary + * incompatibility in the future. + * + * \par Settings Attribute Types and Values + * + * + * \par Example: + * \code + * // Initialize + * nvtxEventAttributes_t eventAttrib = {0}; + * eventAttrib.version = NVTX_VERSION; + * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; + * + * // Configure the Attributes + * eventAttrib.colorType = NVTX_COLOR_ARGB; + * eventAttrib.color = 0xFF880000; + * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; + * eventAttrib.message.ascii = "Example"; + * \endcode + * + * In the example the caller does not have to set the value of + * \ref ::nvtxEventAttributes_v2::category or + * \ref ::nvtxEventAttributes_v2::payload as these fields were set to + * the default value by {0}. + * \sa + * ::nvtxDomainMarkEx + * ::nvtxDomainRangeStartEx + * ::nvtxDomainRangePushEx + */ +typedef struct nvtxEventAttributes_v2 +{ + /** + * \brief Version flag of the structure. + * + * Needs to be set to NVTX_VERSION to indicate the version of NVTX APIs + * supported in this header file. This can optionally be overridden to + * another version of the tools extension library. + */ + uint16_t version; + + /** + * \brief Size of the structure. + * + * Needs to be set to the size in bytes of the event attribute + * structure used to specify the event. + */ + uint16_t size; + + /** + * \brief ID of the category the event is assigned to. + * + * A category is a user-controlled ID that can be used to group + * events. The tool may use category IDs to improve filtering or + * enable grouping of events in the same category. The functions + * \ref ::nvtxNameCategoryA or \ref ::nvtxNameCategoryW can be used + * to name a category. + * + * Default Value is 0 + */ + uint32_t category; + + /** \brief Color type specified in this attribute structure. + * + * Defines the color format of the attribute structure's \ref COLOR_FIELD + * "color" field. + * + * Default Value is NVTX_COLOR_UNKNOWN + */ + int32_t colorType; /* nvtxColorType_t */ + + /** \brief Color assigned to this event. \anchor COLOR_FIELD + * + * The color that the tool should use to visualize the event. + */ + uint32_t color; + + /** + * \brief Payload type specified in this attribute structure. + * + * Defines the payload format of the attribute structure's \ref PAYLOAD_FIELD + * "payload" field. + * + * Default Value is NVTX_PAYLOAD_UNKNOWN + */ + int32_t payloadType; /* nvtxPayloadType_t */ + + int32_t reserved0; + + /** + * \brief Payload assigned to this event. \anchor PAYLOAD_FIELD + * + * A numerical value that can be used to annotate an event. The tool could + * use the payload data to reconstruct graphs and diagrams. + */ + union payload_t + { + uint64_t ullValue; + int64_t llValue; + double dValue; + /* NVTX_VERSION_2 */ + uint32_t uiValue; + int32_t iValue; + float fValue; + } payload; + + /** \brief Message type specified in this attribute structure. + * + * Defines the message format of the attribute structure's \ref MESSAGE_FIELD + * "message" field. + * + * Default Value is NVTX_MESSAGE_UNKNOWN + */ + int32_t messageType; /* nvtxMessageType_t */ + + /** \brief Message assigned to this attribute structure. \anchor MESSAGE_FIELD + * + * The text message that is attached to an event. + */ + nvtxMessageValue_t message; + +} nvtxEventAttributes_v2; + +typedef struct nvtxEventAttributes_v2 nvtxEventAttributes_t; + +/** @} */ /*END defgroup*/ +/* ========================================================================= */ +/** \defgroup MARKERS_AND_RANGES Markers and Ranges + * + * See \ref MARKERS_AND_RANGES for more details + * + * @{ + */ + +/** \name Marker */ + +/* ------------------------------------------------------------------------- */ +/** \brief Marks an instantaneous event in the application. +* +* A marker can contain a text message or specify additional information +* using the event attributes structure. These attributes include a text +* message, color, category, and a payload. Each of the attributes is optional +* and can only be sent out using the \ref nvtxDomainMarkEx function. +* +* nvtxDomainMarkEx(NULL, event) is equivalent to calling +* nvtxMarkEx(event). +* +* \param domain - The domain of scoping the category. +* \param eventAttrib - The event attribute structure defining the marker's +* attribute types and attribute values. +* +* \sa +* ::nvtxMarkEx +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC void NVTX_API nvtxDomainMarkEx(nvtxDomainHandle_t domain, const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Marks an instantaneous event in the application. + * + * A marker can contain a text message or specify additional information + * using the event attributes structure. These attributes include a text + * message, color, category, and a payload. Each of the attributes is optional + * and can only be sent out using the \ref nvtxMarkEx function. + * If \ref nvtxMarkA or \ref nvtxMarkW are used to specify the marker + * or if an attribute is unspecified then a default value will be used. + * + * \param eventAttrib - The event attribute structure defining the marker's + * attribute types and attribute values. + * + * \par Example: + * \code + * // zero the structure + * nvtxEventAttributes_t eventAttrib = {0}; + * // set the version and the size information + * eventAttrib.version = NVTX_VERSION; + * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; + * // configure the attributes. 0 is the default for all attributes. + * eventAttrib.colorType = NVTX_COLOR_ARGB; + * eventAttrib.color = 0xFF880000; + * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; + * eventAttrib.message.ascii = "Example nvtxMarkEx"; + * nvtxMarkEx(&eventAttrib); + * \endcode + * + * \sa + * ::nvtxDomainMarkEx + * + * \version \NVTX_VERSION_1 + * @{ */ +NVTX_DECLSPEC void NVTX_API nvtxMarkEx(const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Marks an instantaneous event in the application. + * + * A marker created using \ref nvtxMarkA or \ref nvtxMarkW contains only a + * text message. + * + * \param message - The message associated to this marker event. + * + * \par Example: + * \code + * nvtxMarkA("Example nvtxMarkA"); + * nvtxMarkW(L"Example nvtxMarkW"); + * \endcode + * + * \sa + * ::nvtxDomainMarkEx + * ::nvtxMarkEx + * + * \version \NVTX_VERSION_0 + * @{ */ +NVTX_DECLSPEC void NVTX_API nvtxMarkA(const char* message); +NVTX_DECLSPEC void NVTX_API nvtxMarkW(const wchar_t* message); +/** @} */ + + +/** \name Process Ranges */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a process range in a domain. +* +* \param domain - The domain of scoping the category. +* \param eventAttrib - The event attribute structure defining the range's +* attribute types and attribute values. +* +* \return The unique ID used to correlate a pair of Start and End events. +* +* \remarks Ranges defined by Start/End can overlap. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("my domain"); +* nvtxEventAttributes_t eventAttrib = {0}; +* eventAttrib.version = NVTX_VERSION; +* eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; +* eventAttrib.message.ascii = "my range"; +* nvtxRangeId_t rangeId = nvtxDomainRangeStartEx(&eventAttrib); +* // ... +* nvtxDomainRangeEnd(rangeId); +* \endcode +* +* \sa +* ::nvtxDomainRangeEnd +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxDomainRangeStartEx(nvtxDomainHandle_t domain, const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a process range. + * + * \param eventAttrib - The event attribute structure defining the range's + * attribute types and attribute values. + * + * \return The unique ID used to correlate a pair of Start and End events. + * + * \remarks Ranges defined by Start/End can overlap. + * + * \par Example: + * \code + * nvtxEventAttributes_t eventAttrib = {0}; + * eventAttrib.version = NVTX_VERSION; + * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; + * eventAttrib.category = 3; + * eventAttrib.colorType = NVTX_COLOR_ARGB; + * eventAttrib.color = 0xFF0088FF; + * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; + * eventAttrib.message.ascii = "Example Range"; + * nvtxRangeId_t rangeId = nvtxRangeStartEx(&eventAttrib); + * // ... + * nvtxRangeEnd(rangeId); + * \endcode + * + * \sa + * ::nvtxRangeEnd + * ::nvtxDomainRangeStartEx + * + * \version \NVTX_VERSION_1 + * @{ */ +NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartEx(const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a process range. + * + * \param message - The event message associated to this range event. + * + * \return The unique ID used to correlate a pair of Start and End events. + * + * \remarks Ranges defined by Start/End can overlap. + * + * \par Example: + * \code + * nvtxRangeId_t r1 = nvtxRangeStartA("Range 1"); + * nvtxRangeId_t r2 = nvtxRangeStartW(L"Range 2"); + * nvtxRangeEnd(r1); + * nvtxRangeEnd(r2); + * \endcode + * + * \sa + * ::nvtxRangeEnd + * ::nvtxRangeStartEx + * ::nvtxDomainRangeStartEx + * + * \version \NVTX_VERSION_0 + * @{ */ +NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartA(const char* message); +NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartW(const wchar_t* message); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Ends a process range. +* +* \param domain - The domain +* \param id - The correlation ID returned from a nvtxRangeStart call. +* +* \remarks This function is offered completeness but is an alias for ::nvtxRangeEnd. +* It does not need a domain param since that is associated iwth the range ID at ::nvtxDomainRangeStartEx +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("my domain"); +* nvtxEventAttributes_t eventAttrib = {0}; +* eventAttrib.version = NVTX_VERSION; +* eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; +* eventAttrib.message.ascii = "my range"; +* nvtxRangeId_t rangeId = nvtxDomainRangeStartEx(&eventAttrib); +* // ... +* nvtxDomainRangeEnd(rangeId); +* \endcode +* +* \sa +* ::nvtxDomainRangeStartEx +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC void NVTX_API nvtxDomainRangeEnd(nvtxDomainHandle_t domain, nvtxRangeId_t id); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Ends a process range. + * + * \param id - The correlation ID returned from an nvtxRangeStart call. + * + * \sa + * ::nvtxDomainRangeStartEx + * ::nvtxRangeStartEx + * ::nvtxRangeStartA + * ::nvtxRangeStartW + * + * \version \NVTX_VERSION_0 + * @{ */ +NVTX_DECLSPEC void NVTX_API nvtxRangeEnd(nvtxRangeId_t id); +/** @} */ + +/** \name Thread Ranges */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a nested thread range. +* +* \param domain - The domain of scoping. +* \param eventAttrib - The event attribute structure defining the range's +* attribute types and attribute values. +* +* \return The 0 based level of range being started. This value is scoped to the domain. +* If an error occurs, a negative value is returned. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("example domain"); +* nvtxEventAttributes_t eventAttrib = {0}; +* eventAttrib.version = NVTX_VERSION; +* eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib.colorType = NVTX_COLOR_ARGB; +* eventAttrib.color = 0xFFFF0000; +* eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; +* eventAttrib.message.ascii = "Level 0"; +* nvtxDomainRangePushEx(domain, &eventAttrib); +* +* // Re-use eventAttrib +* eventAttrib.messageType = NVTX_MESSAGE_TYPE_UNICODE; +* eventAttrib.message.unicode = L"Level 1"; +* nvtxDomainRangePushEx(domain, &eventAttrib); +* +* nvtxDomainRangePop(domain); //level 1 +* nvtxDomainRangePop(domain); //level 0 +* \endcode +* +* \sa +* ::nvtxDomainRangePop +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC int NVTX_API nvtxDomainRangePushEx(nvtxDomainHandle_t domain, const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a nested thread range. + * + * \param eventAttrib - The event attribute structure defining the range's + * attribute types and attribute values. + * + * \return The 0 based level of range being started. This level is per domain. + * If an error occurs a negative value is returned. + * + * \par Example: + * \code + * nvtxEventAttributes_t eventAttrib = {0}; + * eventAttrib.version = NVTX_VERSION; + * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; + * eventAttrib.colorType = NVTX_COLOR_ARGB; + * eventAttrib.color = 0xFFFF0000; + * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; + * eventAttrib.message.ascii = "Level 0"; + * nvtxRangePushEx(&eventAttrib); + * + * // Re-use eventAttrib + * eventAttrib.messageType = NVTX_MESSAGE_TYPE_UNICODE; + * eventAttrib.message.unicode = L"Level 1"; + * nvtxRangePushEx(&eventAttrib); + * + * nvtxRangePop(); + * nvtxRangePop(); + * \endcode + * + * \sa + * ::nvtxDomainRangePushEx + * ::nvtxRangePop + * + * \version \NVTX_VERSION_1 + * @{ */ +NVTX_DECLSPEC int NVTX_API nvtxRangePushEx(const nvtxEventAttributes_t* eventAttrib); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Starts a nested thread range. + * + * \param message - The event message associated to this range event. + * + * \return The 0 based level of range being started. If an error occurs a + * negative value is returned. + * + * \par Example: + * \code + * nvtxRangePushA("Level 0"); + * nvtxRangePushW(L"Level 1"); + * nvtxRangePop(); + * nvtxRangePop(); + * \endcode + * + * \sa + * ::nvtxDomainRangePushEx + * ::nvtxRangePop + * + * \version \NVTX_VERSION_0 + * @{ */ +NVTX_DECLSPEC int NVTX_API nvtxRangePushA(const char* message); +NVTX_DECLSPEC int NVTX_API nvtxRangePushW(const wchar_t* message); +/** @} */ + + +/* ------------------------------------------------------------------------- */ +/** \brief Ends a nested thread range. +* +* \return The level of the range being ended. If an error occurs a negative +* value is returned on the current thread. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreate("example library"); +* nvtxDomainRangePushA(domain, "Level 0"); +* nvtxDomainRangePushW(domain, L"Level 1"); +* nvtxDomainRangePop(domain); +* nvtxDomainRangePop(domain); +* \endcode +* +* \sa +* ::nvtxRangePushEx +* ::nvtxRangePushA +* ::nvtxRangePushW +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC int NVTX_API nvtxDomainRangePop(nvtxDomainHandle_t domain); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Ends a nested thread range. + * + * \return The level of the range being ended. If an error occurs a negative + * value is returned on the current thread. + * + * \par Example: + * \code + * nvtxRangePushA("Level 0"); + * nvtxRangePushW(L"Level 1"); + * nvtxRangePop(); + * nvtxRangePop(); + * \endcode + * + * \sa + * ::nvtxRangePushEx + * ::nvtxRangePushA + * ::nvtxRangePushW + * + * \version \NVTX_VERSION_0 + * @{ */ +NVTX_DECLSPEC int NVTX_API nvtxRangePop(void); +/** @} */ + + +/** @} */ /*END defgroup*/ +/* ========================================================================= */ +/** \defgroup RESOURCE_NAMING Resource Naming + * + * See \ref RESOURCE_NAMING for more details + * + * @{ + */ + + +/* ------------------------------------------------------------------------- */ +/** \name Functions for Generic Resource Naming*/ +/* ------------------------------------------------------------------------- */ + +/* ------------------------------------------------------------------------- */ +/** \cond SHOW_HIDDEN +* \brief Resource typing helpers. +* +* Classes are used to make it easy to create a series of resource types +* per API without collisions +*/ +#define NVTX_RESOURCE_MAKE_TYPE(CLASS, INDEX) ((((uint32_t)(NVTX_RESOURCE_CLASS_ ## CLASS))<<16)|((uint32_t)(INDEX))) +#define NVTX_RESOURCE_CLASS_GENERIC 1 +/** \endcond */ + +/* ------------------------------------------------------------------------- */ +/** \brief Generic resource type for when a resource class is not available. +* +* \sa +* ::nvtxDomainResourceCreate +* +* \version \NVTX_VERSION_2 +*/ +typedef enum nvtxResourceGenericType_t +{ + NVTX_RESOURCE_TYPE_UNKNOWN = 0, + NVTX_RESOURCE_TYPE_GENERIC_POINTER = NVTX_RESOURCE_MAKE_TYPE(GENERIC, 1), /**< Generic pointer assumed to have no collisions with other pointers. */ + NVTX_RESOURCE_TYPE_GENERIC_HANDLE = NVTX_RESOURCE_MAKE_TYPE(GENERIC, 2), /**< Generic handle assumed to have no collisions with other handles. */ + NVTX_RESOURCE_TYPE_GENERIC_THREAD_NATIVE = NVTX_RESOURCE_MAKE_TYPE(GENERIC, 3), /**< OS native thread identifier. */ + NVTX_RESOURCE_TYPE_GENERIC_THREAD_POSIX = NVTX_RESOURCE_MAKE_TYPE(GENERIC, 4) /**< POSIX pthread identifier. */ +} nvtxResourceGenericType_t; + + + +/** \brief Resource Attribute Structure. +* \anchor RESOURCE_ATTRIBUTE_STRUCTURE +* +* This structure is used to describe the attributes of a resource. The layout of +* the structure is defined by a specific version of the tools extension +* library and can change between different versions of the Tools Extension +* library. +* +* \par Initializing the Attributes +* +* The caller should always perform the following three tasks when using +* attributes: +*
    +*
  • Zero the structure +*
  • Set the version field +*
  • Set the size field +*
+* +* Zeroing the structure sets all the resource attributes types and values +* to the default value. +* +* The version and size field are used by the Tools Extension +* implementation to handle multiple versions of the attributes structure. +* +* It is recommended that the caller use one of the following to methods +* to initialize the event attributes structure: +* +* \par Method 1: Initializing nvtxEventAttributes for future compatibility +* \code +* nvtxResourceAttributes_t attribs = {0}; +* attribs.version = NVTX_VERSION; +* attribs.size = NVTX_RESOURCE_ATTRIB_STRUCT_SIZE; +* \endcode +* +* \par Method 2: Initializing nvtxEventAttributes for a specific version +* \code +* nvtxResourceAttributes_v0 attribs = {0}; +* attribs.version = 2; +* attribs.size = (uint16_t)(sizeof(nvtxResourceAttributes_v0)); +* \endcode +* +* If the caller uses Method 1 it is critical that the entire binary +* layout of the structure be configured to 0 so that all fields +* are initialized to the default value. +* +* The caller should either use both NVTX_VERSION and +* NVTX_RESOURCE_ATTRIB_STRUCT_SIZE (Method 1) or use explicit values +* and a versioned type (Method 2). Using a mix of the two methods +* will likely cause either source level incompatibility or binary +* incompatibility in the future. +* +* \par Settings Attribute Types and Values +* +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("example domain"); +* +* // Initialize +* nvtxResourceAttributes_t attribs = {0}; +* attribs.version = NVTX_VERSION; +* attribs.size = NVTX_RESOURCE_ATTRIB_STRUCT_SIZE; +* +* // Configure the Attributes +* attribs.identifierType = NVTX_RESOURCE_TYPE_GENERIC_POINTER; +* attribs.identifier.pValue = (const void*)pMutex; +* attribs.messageType = NVTX_MESSAGE_TYPE_ASCII; +* attribs.message.ascii = "Single thread access to database."; +* +* nvtxResourceHandle_t handle = nvtxDomainResourceCreate(domain, attribs); +* \endcode +* +* \sa +* ::nvtxDomainResourceCreate +*/ +typedef struct nvtxResourceAttributes_v0 +{ + /** + * \brief Version flag of the structure. + * + * Needs to be set to NVTX_VERSION to indicate the version of NVTX APIs + * supported in this header file. This can optionally be overridden to + * another version of the tools extension library. + */ + uint16_t version; + + /** + * \brief Size of the structure. + * + * Needs to be set to the size in bytes of this attribute + * structure. + */ + uint16_t size; + + /** + * \brief Identifier type specifies how to interpret the identifier field + * + * Defines the identifier format of the attribute structure's \ref RESOURCE_IDENTIFIER_FIELD + * "identifier" field. + * + * Default Value is NVTX_RESOURCE_TYPE_UNKNOWN + */ + int32_t identifierType; /* values from enums following the pattern nvtxResource[name]Type_t */ + + /** + * \brief Identifier for the resource. + * \anchor RESOURCE_IDENTIFIER_FIELD + * + * An identifier may be a pointer or a handle to an OS or middleware API object. + * The resource type will assist in avoiding collisions where handles values may collide. + */ + union identifier_t + { + const void* pValue; + uint64_t ullValue; + } identifier; + + /** \brief Message type specified in this attribute structure. + * + * Defines the message format of the attribute structure's \ref RESOURCE_MESSAGE_FIELD + * "message" field. + * + * Default Value is NVTX_MESSAGE_UNKNOWN + */ + int32_t messageType; /* nvtxMessageType_t */ + + /** \brief Message assigned to this attribute structure. \anchor RESOURCE_MESSAGE_FIELD + * + * The text message that is attached to a resource. + */ + nvtxMessageValue_t message; + +} nvtxResourceAttributes_v0; + +typedef struct nvtxResourceAttributes_v0 nvtxResourceAttributes_t; + +/* \cond SHOW_HIDDEN +* \version \NVTX_VERSION_2 +*/ +#define NVTX_RESOURCE_ATTRIB_STRUCT_SIZE ( (uint16_t)( sizeof(nvtxResourceAttributes_v0) ) ) +typedef struct nvtxResourceHandle* nvtxResourceHandle_t; +/** \endcond */ + + + +/* ------------------------------------------------------------------------- */ +/** \brief Create a resource object to track and associate data with OS and middleware objects +* +* Allows users to associate an API handle or pointer with a user-provided name. +* +* +* \param domain - Domain to own the resource object +* \param attribs - Attributes to be associated with the resource +* +* \return A handle that represents the newly created resource object. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("example domain"); +* nvtxResourceAttributes_t attribs = {0}; +* attribs.version = NVTX_VERSION; +* attribs.size = NVTX_RESOURCE_ATTRIB_STRUCT_SIZE; +* attribs.identifierType = NVTX_RESOURCE_TYPE_GENERIC_POINTER; +* attribs.identifier.pValue = (const void*)pMutex; +* attribs.messageType = NVTX_MESSAGE_TYPE_ASCII; +* attribs.message.ascii = "Single thread access to database."; +* nvtxResourceHandle_t handle = nvtxDomainResourceCreate(domain, attribs); +* \endcode +* +* \sa +* ::nvtxResourceAttributes_t +* ::nvtxDomainResourceDestroy +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC nvtxResourceHandle_t NVTX_API nvtxDomainResourceCreate(nvtxDomainHandle_t domain, nvtxResourceAttributes_t* attribs); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Destroy a resource object to track and associate data with OS and middleware objects +* +* Allows users to associate an API handle or pointer with a user-provided name. +* +* \param resource - Handle to the resource in which to operate. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("example domain"); +* nvtxResourceAttributes_t attribs = {0}; +* attribs.version = NVTX_VERSION; +* attribs.size = NVTX_RESOURCE_ATTRIB_STRUCT_SIZE; +* attribs.identifierType = NVTX_RESOURCE_TYPE_GENERIC_POINTER; +* attribs.identifier.pValue = (const void*)pMutex; +* attribs.messageType = NVTX_MESSAGE_TYPE_ASCII; +* attribs.message.ascii = "Single thread access to database."; +* nvtxResourceHandle_t handle = nvtxDomainResourceCreate(domain, attribs); +* nvtxDomainResourceDestroy(handle); +* \endcode +* +* \sa +* ::nvtxDomainResourceCreate +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC void NVTX_API nvtxDomainResourceDestroy(nvtxResourceHandle_t resource); +/** @} */ + + +/** \name Functions for NVTX Category Naming*/ + +/* ------------------------------------------------------------------------- */ +/** +* \brief Annotate an NVTX category used within a domain. +* +* Categories are used to group sets of events. Each category is identified +* through a unique ID and that ID is passed into any of the marker/range +* events to assign that event to a specific category. The nvtxDomainNameCategory +* function calls allow the user to assign a name to a category ID that is +* specific to the domain. +* +* nvtxDomainNameCategory(NULL, category, name) is equivalent to calling +* nvtxNameCategory(category, name). +* +* \param domain - The domain of scoping the category. +* \param category - The category ID to name. +* \param name - The name of the category. +* +* \remarks The category names are tracked per domain. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("example"); +* nvtxDomainNameCategoryA(domain, 1, "Memory Allocation"); +* nvtxDomainNameCategoryW(domain, 2, L"Memory Transfer"); +* \endcode +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC void NVTX_API nvtxDomainNameCategoryA(nvtxDomainHandle_t domain, uint32_t category, const char* name); +NVTX_DECLSPEC void NVTX_API nvtxDomainNameCategoryW(nvtxDomainHandle_t domain, uint32_t category, const wchar_t* name); +/** @} */ + +/** \brief Annotate an NVTX category. + * + * Categories are used to group sets of events. Each category is identified + * through a unique ID and that ID is passed into any of the marker/range + * events to assign that event to a specific category. The nvtxNameCategory + * function calls allow the user to assign a name to a category ID. + * + * \param category - The category ID to name. + * \param name - The name of the category. + * + * \remarks The category names are tracked per process. + * + * \par Example: + * \code + * nvtxNameCategory(1, "Memory Allocation"); + * nvtxNameCategory(2, "Memory Transfer"); + * nvtxNameCategory(3, "Memory Object Lifetime"); + * \endcode + * + * \version \NVTX_VERSION_1 + * @{ */ +NVTX_DECLSPEC void NVTX_API nvtxNameCategoryA(uint32_t category, const char* name); +NVTX_DECLSPEC void NVTX_API nvtxNameCategoryW(uint32_t category, const wchar_t* name); +/** @} */ + +/** \name Functions for OS Threads Naming*/ + +/* ------------------------------------------------------------------------- */ +/** \brief Annotate an OS thread. + * + * Allows the user to name an active thread of the current process. If an + * invalid thread ID is provided or a thread ID from a different process is + * used the behavior of the tool is implementation dependent. + * + * The thread name is associated to the default domain. To support domains + * use resource objects via ::nvtxDomainResourceCreate. + * + * \param threadId - The ID of the thread to name. + * \param name - The name of the thread. + * + * \par Example: + * \code + * nvtxNameOsThread(GetCurrentThreadId(), "MAIN_THREAD"); + * \endcode + * + * \version \NVTX_VERSION_1 + * @{ */ +NVTX_DECLSPEC void NVTX_API nvtxNameOsThreadA(uint32_t threadId, const char* name); +NVTX_DECLSPEC void NVTX_API nvtxNameOsThreadW(uint32_t threadId, const wchar_t* name); +/** @} */ + + +/** @} */ /*END defgroup*/ +/* ========================================================================= */ +/** \defgroup STRING_REGISTRATION String Registration +* +* Registered strings are intended to increase performance by lowering instrumentation +* overhead. String may be registered once and the handle may be passed in place of +* a string where an the APIs may allow. +* +* See \ref STRING_REGISTRATION for more details +* +* @{ +*/ + +/* ------------------------------------------------------------------------- */ +/** \brief Register a string. + +* Registers an immutable string with NVTX. Once registered the pointer used +* to register the domain name can be used in nvtxEventAttributes_t +* \ref MESSAGE_FIELD. This allows NVTX implementation to skip copying the +* contents of the message on each event invocation. +* +* String registration is an optimization. It is recommended to use string +* registration if the string will be passed to an event many times. +* +* String are not unregistered, except that by unregistering the entire domain +* +* \param domain - Domain handle. If NULL then the global domain is used. +* \param string - A unique pointer to a sequence of characters. +* +* \return A handle representing the registered string. +* +* \par Example: +* \code +* nvtxDomainCreateA("com.nvidia.nvtx.example"); +* nvtxStringHandle_t message = nvtxDomainRegisterStringA(domain, "registered string"); +* nvtxEventAttributes_t eventAttrib = {0}; +* eventAttrib.version = NVTX_VERSION; +* eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib.messageType = NVTX_MESSAGE_TYPE_REGISTERED; +* eventAttrib.message.registered = message; +* \endcode +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC nvtxStringHandle_t NVTX_API nvtxDomainRegisterStringA(nvtxDomainHandle_t domain, const char* string); +NVTX_DECLSPEC nvtxStringHandle_t NVTX_API nvtxDomainRegisterStringW(nvtxDomainHandle_t domain, const wchar_t* string); +/** @} */ + +/** @} */ /*END defgroup*/ +/* ========================================================================= */ +/** \defgroup DOMAINS Domains +* +* Domains are used to group events to a developer defined scope. Middleware +* vendors may also scope their own events to avoid collisions with the +* the application developer's events, so that the application developer may +* inspect both parts and easily differentiate or filter them. By default +* all events are scoped to a global domain where NULL is provided or when +* using APIs provided b versions of NVTX below v2 +* +* Domains are intended to be typically long lived objects with the intention +* of logically separating events of large modules from each other such as +* middleware libraries from each other and the main application. +* +* See \ref DOMAINS for more details +* +* @{ +*/ + +/* ------------------------------------------------------------------------- */ +/** \brief Register a NVTX domain. +* +* Domains are used to scope annotations. All NVTX_VERSION_0 and NVTX_VERSION_1 +* annotations are scoped to the global domain. The function nvtxDomainCreate +* creates a new named domain. +* +* Each domain maintains its own nvtxRangePush and nvtxRangePop stack. +* +* \param name - A unique string representing the domain. +* +* \return A handle representing the domain. +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("com.nvidia.nvtx.example"); +* +* nvtxMarkA("nvtxMarkA to global domain"); +* +* nvtxEventAttributes_t eventAttrib1 = {0}; +* eventAttrib1.version = NVTX_VERSION; +* eventAttrib1.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib1.message.ascii = "nvtxDomainMarkEx to global domain"; +* nvtxDomainMarkEx(NULL, &eventAttrib1); +* +* nvtxEventAttributes_t eventAttrib2 = {0}; +* eventAttrib2.version = NVTX_VERSION; +* eventAttrib2.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; +* eventAttrib2.message.ascii = "nvtxDomainMarkEx to com.nvidia.nvtx.example"; +* nvtxDomainMarkEx(domain, &eventAttrib2); +* nvtxDomainDestroy(domain); +* \endcode +* +* \sa +* ::nvtxDomainDestroy +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC nvtxDomainHandle_t NVTX_API nvtxDomainCreateA(const char* name); +NVTX_DECLSPEC nvtxDomainHandle_t NVTX_API nvtxDomainCreateW(const wchar_t* name); +/** @} */ + +/* ------------------------------------------------------------------------- */ +/** \brief Unregister a NVTX domain. +* +* Unregisters the domain handle and frees all domain specific resources. +* +* \param domain - the domain handle +* +* \par Example: +* \code +* nvtxDomainHandle_t domain = nvtxDomainCreateA("com.nvidia.nvtx.example"); +* nvtxDomainDestroy(domain); +* \endcode +* +* \sa +* ::nvtxDomainCreateA +* ::nvtxDomainCreateW +* +* \version \NVTX_VERSION_2 +* @{ */ +NVTX_DECLSPEC void NVTX_API nvtxDomainDestroy(nvtxDomainHandle_t domain); +/** @} */ + + +/** @} */ /*END defgroup*/ +/* ========================================================================= */ +/** \cond SHOW_HIDDEN */ + +#ifdef UNICODE + #define nvtxMark nvtxMarkW + #define nvtxRangeStart nvtxRangeStartW + #define nvtxRangePush nvtxRangePushW + #define nvtxNameCategory nvtxNameCategoryW + #define nvtxNameOsThread nvtxNameOsThreadW + /* NVTX_VERSION_2 */ + #define nvtxDomainCreate nvtxDomainCreateW + #define nvtxDomainRegisterString nvtxDomainRegisterStringW + #define nvtxDomainNameCategory nvtxDomainNameCategoryW +#else + #define nvtxMark nvtxMarkA + #define nvtxRangeStart nvtxRangeStartA + #define nvtxRangePush nvtxRangePushA + #define nvtxNameCategory nvtxNameCategoryA + #define nvtxNameOsThread nvtxNameOsThreadA + /* NVTX_VERSION_2 */ + #define nvtxDomainCreate nvtxDomainCreateA + #define nvtxDomainRegisterString nvtxDomainRegisterStringA + #define nvtxDomainNameCategory nvtxDomainNameCategoryA +#endif + +/** \endcond */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* NVTOOLSEXT_H_ */ diff --git a/shared/package-files/3a/3a273cdc7f79e4227d673856005d4aca71a62ff07aaba2bb1d7e97d494be5f50/upsample_nearest1d_ops.h b/shared/package-files/3a/3a273cdc7f79e4227d673856005d4aca71a62ff07aaba2bb1d7e97d494be5f50/upsample_nearest1d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..44352f2778e6dfa283f466e86d11bcfff442a906 --- /dev/null +++ b/shared/package-files/3a/3a273cdc7f79e4227d673856005d4aca71a62ff07aaba2bb1d7e97d494be5f50/upsample_nearest1d_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API upsample_nearest1d_vec { + using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, ::std::optional>); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::upsample_nearest1d"; + static constexpr const char* overload_name = "vec"; + static constexpr const char* schema_str = "upsample_nearest1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor"; + static at::Tensor call(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, ::std::optional> scale_factors); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::OptionalSymIntArrayRef output_size, ::std::optional> scale_factors); +}; + +struct TORCH_API upsample_nearest1d_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::upsample_nearest1d"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "upsample_nearest1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales, at::Tensor & out); +}; + +struct TORCH_API upsample_nearest1d { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::upsample_nearest1d"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3a2a935586b794c32c459bfbb34d54a242f30d332cf443f2fae686e0e68b5a81/backward_compatibility.cpython-311.pyc b/shared/package-files/3a/3a2a935586b794c32c459bfbb34d54a242f30d332cf443f2fae686e0e68b5a81/backward_compatibility.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f16f9ece47801a800cc8cc2272550a01f132dca3 Binary files /dev/null and b/shared/package-files/3a/3a2a935586b794c32c459bfbb34d54a242f30d332cf443f2fae686e0e68b5a81/backward_compatibility.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a2ae0319705454f7c307d0ae6bb61046a86d88b3ccb161d9c07177cb98a080d/_init_utils.py b/shared/package-files/3a/3a2ae0319705454f7c307d0ae6bb61046a86d88b3ccb161d9c07177cb98a080d/_init_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..feaf8b8829630d7126aa0c58f2b5fdaeedaf0df2 --- /dev/null +++ b/shared/package-files/3a/3a2ae0319705454f7c307d0ae6bb61046a86d88b3ccb161d9c07177cb98a080d/_init_utils.py @@ -0,0 +1,1186 @@ +# mypy: allow-untyped-defs +import collections +import itertools +import os +import warnings +from collections.abc import Generator, Iterable, Iterator +from typing import Any, Callable, no_type_check, Optional, TYPE_CHECKING, Union + +import torch +import torch.distributed as dist +import torch.distributed.fsdp._exec_order_utils as exec_order_utils +import torch.distributed.fsdp._traversal_utils as traversal_utils +import torch.distributed.fsdp.fully_sharded_data_parallel as fsdp_file +import torch.nn as nn +from torch.distributed.algorithms._comm_hooks import default_hooks +from torch.distributed.device_mesh import _mesh_resources, DeviceMesh +from torch.distributed.distributed_c10d import _get_default_group +from torch.distributed.fsdp._common_utils import ( + _FSDPDeviceHandle, + _FSDPState, + _get_module_fsdp_state, + _is_fsdp_flattened, + _named_parameters_with_duplicates, + clean_tensor_name, + TrainingState, +) +from torch.distributed.fsdp._flat_param import ( + _FSDP_USE_FULL_PREC_IN_EVAL, + FlatParameter, + FlatParamHandle, + HandleShardingStrategy, +) +from torch.distributed.fsdp._limiter_utils import _FreeEventQueue +from torch.distributed.fsdp.api import ( + BackwardPrefetch, + CPUOffload, + FullOptimStateDictConfig, + FullStateDictConfig, + MixedPrecision, + ShardingStrategy, + StateDictConfig, + StateDictType, +) +from torch.distributed.fsdp.wrap import _Policy +from torch.distributed.tensor.parallel.fsdp import DTensorExtensions +from torch.distributed.utils import _sync_params_and_buffers +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + +if TYPE_CHECKING: + from torch.utils.hooks import RemovableHandle + +_TORCHDISTX_AVAIL = True +try: + from torchdistx import deferred_init, fake # type: ignore[import] +except ImportError: + _TORCHDISTX_AVAIL = False + +PARAM_BROADCAST_BUCKET_SIZE = int(250 * 1024 * 1024) +FSDP_SYNCED = "_fsdp_synced" +# Specification of process groups for hybrid sharding strategies. +HybridShardProcessGroupType = tuple[dist.ProcessGroup, dist.ProcessGroup] +# Overall specification of process group. +ProcessGroupType = Optional[Union[dist.ProcessGroup, HybridShardProcessGroupType]] + + +# TODO (awgu): Refactor this later +SHARDING_STRATEGY_MAP = { + ShardingStrategy.NO_SHARD: HandleShardingStrategy.NO_SHARD, + ShardingStrategy.FULL_SHARD: HandleShardingStrategy.FULL_SHARD, + ShardingStrategy.SHARD_GRAD_OP: HandleShardingStrategy.SHARD_GRAD_OP, + ShardingStrategy.HYBRID_SHARD: HandleShardingStrategy.HYBRID_SHARD, + ShardingStrategy._HYBRID_SHARD_ZERO2: HandleShardingStrategy._HYBRID_SHARD_ZERO2, +} +HYBRID_SHARDING_STRATEGIES = [ + ShardingStrategy.HYBRID_SHARD, + ShardingStrategy._HYBRID_SHARD_ZERO2, +] +NO_RESHARD_AFTER_FORWARD_STRATEGIES = ( + ShardingStrategy.SHARD_GRAD_OP, + ShardingStrategy._HYBRID_SHARD_ZERO2, +) + + +# NOTE: Since non-self attributes cannot be type annotated, several attributes +# on `state` are defined first as local variables before being assigned. + + +@no_type_check +def _init_process_group_state( + state: _FSDPState, + process_group: ProcessGroupType, + sharding_strategy: ShardingStrategy, + policy: Optional[_Policy], + device_mesh: Optional[DeviceMesh] = None, +) -> _FSDPState: + if process_group is not None and device_mesh is not None: + raise ValueError( + "Cannot pass both process_group and device_mesh at the " + "same time. Please just pass only one of them." + ) + is_hybrid_strategy = sharding_strategy in HYBRID_SHARDING_STRATEGIES + if is_hybrid_strategy: + if process_group is None and policy is None and device_mesh is None: + # Raise an error here, since this is manual wrapping with no process group + # passed in, there is no way to ensure all wrapped FSDP instances use the same + # process groups. + raise ValueError( + f"Manual wrapping with {sharding_strategy} " + "requires explicit specification of process group or device_mesh." + ) + else: + state = _init_process_group_state_for_hybrid_shard( + state, process_group, device_mesh + ) + else: + if device_mesh: + state._device_mesh = device_mesh + state.process_group = device_mesh.get_group(mesh_dim=0) + else: + state.process_group = ( + process_group if process_group is not None else _get_default_group() + ) + + state.rank = state.process_group.rank() + state.world_size = state.process_group.size() + data_parallel_world_size = state.world_size + if is_hybrid_strategy: + data_parallel_world_size *= state._inter_node_pg.size() + state._gradient_predivide_factor = ( + default_hooks.DefaultState._get_gradient_predivide_factor( + data_parallel_world_size + ) + ) + state._gradient_postdivide_factor = ( + data_parallel_world_size / state._gradient_predivide_factor + ) + return state + + +@no_type_check +def _init_process_group_state_for_hybrid_shard( + state: _FSDPState, + process_group: ProcessGroupType, + device_mesh: DeviceMesh, +) -> _FSDPState: + if device_mesh: + if _is_valid_hybrid_shard_device_mesh(device_mesh): + state._device_mesh = device_mesh + # We currently only allow _inter_node_pg to be the outermost dimension, and the + # process_group(intra_node) to be the innermost dimension. + state._inter_node_pg = device_mesh.get_group(mesh_dim=0) + state.process_group = device_mesh.get_group(mesh_dim=1) + else: + raise ValueError( + f"Expected device_mesh to have ndim=2 but got {device_mesh.ndim}" + ) + elif process_group is None: + default_group = _get_default_group() + intra_node_group, inter_node_group = _init_intra_and_inter_node_groups( + default_group, state._device_handle.device_count() + ) + # we shard across intra-node + state.process_group = intra_node_group + # save _inter_node_pg to allreduce across. + state._inter_node_pg = inter_node_group + else: + # Check type and assign state.process_group and state._inter_node_pg. + if _is_valid_hybrid_shard_pg_type(process_group): + # Assuming that user passed in as intra node group and inter node group + # as documented. + state.process_group, state._inter_node_pg = process_group + else: + raise ValueError( + "Expected process_group to be passed in as either None or " + f"Tuple[dist.ProcessGroup, dist.ProcessGroup] but got {type(process_group)}" + ) + # Create state for allreduce + state._inter_node_state = _get_default_comm_hook_state( + process_group=state._inter_node_pg, + ) + return state + + +@no_type_check +def _is_valid_hybrid_shard_pg_type(process_group: Any) -> bool: + return ( + isinstance(process_group, tuple) + and len(process_group) == 2 + and all(isinstance(pg, dist.ProcessGroup) for pg in process_group) + ) + + +@no_type_check +def _is_valid_hybrid_shard_device_mesh(device_mesh: DeviceMesh) -> bool: + return isinstance(device_mesh, DeviceMesh) and device_mesh.ndim == 2 + + +@no_type_check +def _init_intra_node_process_group(num_devices_per_node: int) -> dist.ProcessGroup: + """ + Return a process group across the current node. + + For example, given each row is a distinct node: + 0 1 2 3 4 5 6 7 + 8 9 10 11 12 13 14 15 + This API would return an intra-node subgroup across + [0, 1, ..., 7] or [8, 9, ..., 15] depending on the process's rank. + For example, rank 3 would get [0, 1, ..., 7]. + """ + intra_node_subgroup, _ = dist.new_subgroups(num_devices_per_node) + return intra_node_subgroup + + +@no_type_check +def _init_inter_node_process_group( + global_process_group: dist.ProcessGroup, + num_devices_per_node: int, +) -> dist.ProcessGroup: + """ + Return an inter-node process group where each contained rank has the same local rank. + + For example, given each row is a distinct node: + 0 1 2 3 4 5 6 7 + 8 9 10 11 12 13 14 15 + This API would return inter-node process group [0, 8], [1, 9], [2, 10], and so forth + depending on the process's rank. For example, rank 1 would get [1, 9], rank 5 + would get [5, 13]. + """ + # the inter-node pg that is returned + inter_node_pg = None + sharding_backend = dist.get_backend(global_process_group) + world_size = dist.get_world_size(global_process_group) + # Assuming fully homogeneous setup + num_nodes = world_size // num_devices_per_node + my_local_rank = dist.get_rank(global_process_group) % num_devices_per_node + for local_rank in range(num_devices_per_node): + ranks_for_inter_group = [ + local_rank + (i * num_devices_per_node) for i in range(num_nodes) + ] + # every rank always needs to call dist.new_group + grp = dist.new_group(ranks=ranks_for_inter_group, backend=sharding_backend) + if local_rank == my_local_rank: + inter_node_pg = grp + + assert inter_node_pg is not None, ( + f"{my_local_rank} expected to assign inter-node pg, but did not" + ) + return inter_node_pg + + +def _init_intra_and_inter_node_groups( + global_process_group: dist.ProcessGroup, + num_devices_per_node: int, +) -> tuple[dist.ProcessGroup, dist.ProcessGroup]: + """ + Initialize intra and inter-node process groups and return the ones corresponding to this process's rank. + + This function can be used to initialize process groups for ``HYBRID_SHARD`` or + ``_HYBRID_SHARD_ZERO2`` in FSDP. + This function assumes each node has an equal number of CUDA-enabled devices. + Returns: + Tuple[dist.ProcessGroup, dist.ProcessGroup]: Intra and inter-node process group. + """ + return ( + _init_intra_node_process_group(num_devices_per_node), + _init_inter_node_process_group(global_process_group, num_devices_per_node), + ) + + +@no_type_check +def _init_ignored_module_states( + state: _FSDPState, + module: nn.Module, + ignored_modules: Optional[Iterable[torch.nn.Module]], + ignored_states: Union[ + Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]] + ] = None, +) -> _FSDPState: + if ignored_modules is not None and ignored_states is not None: + raise ValueError( + "Cannot pass both ignored_modules and ignored_states at the " + "same time. Please just pass ignored_states." + ) + ignored_parameters = None + passed_as_ignored_states = ignored_states is not None + if passed_as_ignored_states: + ignored_states_list = list(ignored_states) + _check_ignored_states(ignored_states_list, True) + else: + ignored_states_list = [] + _check_ignored_states( + list(ignored_modules) if ignored_modules is not None else [], False + ) + if len(ignored_states_list) > 0: + if isinstance(ignored_states_list[0], nn.Parameter): + ignored_parameters = ignored_states_list + else: + ignored_modules = ignored_states_list + state._ignored_modules = _get_ignored_modules(module, ignored_modules) + state._ignored_params = _get_ignored_params( + module, + state._ignored_modules, + ignored_parameters, + ) + state._ignored_buffer_names = _get_ignored_buffer_names( + module, + state._ignored_modules, + ) + # TODO: FSDP's contract for buffers is not well-defined. They are + # implicitly ignored for most functionality since they are not sharded; + # however, FSDP still imposes some semantics on buffers (e.g. buffer mixed + # precision). We should formalize this contract and decide if we need to + # compute and store `_ignored_buffers`. + return state + + +def _check_ignored_states( + ignored_states: list[Any], passed_as_ignored_states: bool +) -> None: + """ + Check that the ignored states are uniformly parameters or uniformly modules. + + We may remove this check in the future if we permit mixing. + """ + if len(ignored_states) == 0: + return + if passed_as_ignored_states: + all_params = all(isinstance(state, nn.Parameter) for state in ignored_states) + all_modules = all(isinstance(state, nn.Module) for state in ignored_states) + if not all_params and not all_modules: + # Sort for consistent ordering for unit test regex matching + sorted_types = sorted({type(state) for state in ignored_states}, key=repr) + raise ValueError( + "ignored_states expects all nn.Parameter or all nn.Module list " + f"elements but got types {sorted_types}" + ) + else: + if not all(isinstance(state, nn.Module) for state in ignored_states): + sorted_types = sorted({type(state) for state in ignored_states}, key=repr) + raise ValueError( + "ignored_modules expects nn.Module list elements but got " + f"types {sorted_types}" + ) + + +@no_type_check +def _init_device_handle( + state: _FSDPState, + module: nn.Module, + ignored_params: set[nn.Parameter], + device_id: Optional[Union[int, torch.device]], +) -> _FSDPState: + """ + Determine device handle used for initializing FSDP. + + If a device is specified by ``device_id``, + then returns device handle corresponds to that device type. Otherwise, If the + module is already on a non-CPU device, then the device type is that non-CPU device type. + If the module is on CPU or meta, then the device type is the current accelerator device. + See the :ref:`Accelerators` for details. + + + This method will be called once ignored paramters was determined, as the device handle maybe needed + for other initialization. + """ + determined_device = None + if device_id is not None: + determined_device = ( + device_id + if isinstance(device_id, torch.device) + else torch.device(device_id) + ) + if determined_device is None: + for param in _get_orig_params(module, ignored_params): + if param.device.type in {"cpu", "meta"}: + continue + if determined_device is None: + determined_device = param.device + else: + if param.device.type != determined_device.type: + raise RuntimeError( + f"FSDP does not support modules with different device types " + f"but got params on {determined_device.type} and {param.device.type}" + ) + determined_device = determined_device or torch._C._get_accelerator() + if determined_device.type == "cpu": + raise RuntimeError( + "FSDP needs a non-CPU accelerator device, but no accelerator device is detected." + ) + + state._device_handle = _FSDPDeviceHandle.from_device(determined_device) + return state + + +@no_type_check +def _init_buffer_state( + state: _FSDPState, + module: nn.Module, +) -> _FSDPState: + state._buffer_names = _get_buffer_names(module) + # Save a mapping from clean fully-qualified buffer name (starting from + # `module`) to its original dtype for restoring that dtype during model + # checkpointing when buffer mixed precision is enabled. The names should + # be clean since the casting happens in a `summon_full_params()` context. + _buffer_name_to_orig_dtype: dict[str, torch.dtype] = {} + for buffer_name, buffer in module.named_buffers(): + buffer_name = clean_tensor_name(buffer_name) + _buffer_name_to_orig_dtype[buffer_name] = buffer.dtype + state._buffer_name_to_orig_dtype = _buffer_name_to_orig_dtype + return state + + +@no_type_check +def _init_core_state( + state: _FSDPState, + sharding_strategy: Optional[ShardingStrategy], + mixed_precision: Optional[MixedPrecision], + cpu_offload: Optional[CPUOffload], + limit_all_gathers: bool, + use_orig_params: bool, + backward_prefetch_limit: int, + forward_prefetch_limit: int, +) -> _FSDPState: + # We clamp the strategy to `NO_SHARD` for world size of 1 since they are + # currently functionally equivalent. This may change if/when we integrate + # FSDP with MoE. + if state.world_size == 1: + if sharding_strategy != ShardingStrategy.NO_SHARD: + warnings.warn( + "FSDP is switching to use `NO_SHARD` instead of " + f"{sharding_strategy or ShardingStrategy.FULL_SHARD} since " + "the world size is 1." + ) + sharding_strategy = ShardingStrategy.NO_SHARD + elif sharding_strategy == ShardingStrategy.NO_SHARD: + warnings.warn( + "The `NO_SHARD` sharding strategy is deprecated. If having issues, " + "please use `DistributedDataParallel` instead.", + FutureWarning, + # Level 1 is here, level 2 is from `FullyShardedDataParallel`, and + # level 3 is from the true caller + stacklevel=3, + ) + state.sharding_strategy = sharding_strategy or ShardingStrategy.FULL_SHARD + state.mixed_precision = mixed_precision or MixedPrecision() + if mixed_precision is not None: + torch._C._log_api_usage_once( + f"torch.distributed.fsdp.mixed_precision.{str(state.mixed_precision)}" + ) + state._use_full_prec_in_eval = ( + os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1" + ) + state.cpu_offload = cpu_offload or CPUOffload() + state.limit_all_gathers = limit_all_gathers + state._use_orig_params = use_orig_params + state.training_state = TrainingState.IDLE + state._is_root = None + state._free_event_queue = _FreeEventQueue() + state._debug_level = dist.get_debug_level() + state._exec_order_data = exec_order_utils._ExecOrderData( + state._debug_level, + backward_prefetch_limit, + forward_prefetch_limit, + ) + state._unshard_event = None + # Mapping from fully sharded module to the handles it is responsible to + # unshard and reshard (see [Note: Fully Sharded Module]) + _fully_sharded_module_to_handle: dict[nn.Module, FlatParamHandle] = {} + state._fully_sharded_module_to_handle = _fully_sharded_module_to_handle + # Invariant: `state.params` contains exactly the `FlatParameter`s of the + # handles in `state._handle` + _handle: Optional[FlatParamHandle] = None + state._handle = _handle + params: list[FlatParameter] = [] + state.params = params + return state + + +@no_type_check +def _init_runtime_state( + state: _FSDPState, +) -> _FSDPState: + _root_pre_forward_handles: list[RemovableHandle] = [] + state._root_pre_forward_handles = _root_pre_forward_handles + _pre_forward_handles: list[RemovableHandle] = [] + state._pre_forward_handles = _pre_forward_handles + _post_forward_handles: list[RemovableHandle] = [] + state._post_forward_handles = _post_forward_handles + state._sync_gradients = True + state._comm_hook = None + state._comm_hook_state = None + # Used to prevent running the pre-backward hook multiple times + return state + + +@no_type_check +def _init_prefetching_state( + state: _FSDPState, + backward_prefetch: BackwardPrefetch, + forward_prefetch: bool, +) -> _FSDPState: + state.backward_prefetch = backward_prefetch + state.forward_prefetch = forward_prefetch + # The data structures use tuples of handles to generalize over the case + # where a module's forward involves multiple handles. + return state + + +@no_type_check +def _init_extension(state: _FSDPState, device_mesh: DeviceMesh = None) -> _FSDPState: + # TODO: we need to add additional check once we support FSDP + PiPPy. + # This check is currently sufficient, since we only support FSDP + TP. + root_mesh = _mesh_resources.get_root_mesh(device_mesh) + # if a root mesh is not the same as device_mesh, + # meaning the device_mesh is sliced out from the root mesh. + if device_mesh and root_mesh != state._device_mesh: + state._fsdp_extension = DTensorExtensions(state._device_handle) + else: + # We need to explicilty set _fsdp_extension to None. + # Otherwise, we will run into an infinite recursion when getting the attribute. + state._fsdp_extension = None + return state + + +@no_type_check +def _init_state_dict_state(state: _FSDPState) -> _FSDPState: + state._state_dict_type = StateDictType.FULL_STATE_DICT + state_dict_config: StateDictConfig = FullStateDictConfig() + state._optim_state_dict_config = FullOptimStateDictConfig() + state._state_dict_config = state_dict_config + unshard_params_ctx: dict[nn.Module, Generator] = {} + state._unshard_params_ctx = unshard_params_ctx + + return state + + +def _verify_managed_params(module: nn.Module, params: list[nn.Parameter]) -> None: + """ + Verify if the parameters are accepted by FSDP. The only restriction now + is that the parameter cannot be a scalar tensor (param.shape == []). + """ + for param in params: + if len(param.shape) == 0: + param_name = "" + for name, param_ in module.named_parameters(): + if param is param_: + param_name = name + break + assert param_name + raise ValueError( + "FSDP doesn't support scalar parameters. " + f"Change {param_name} to a 1D tensor with numel equal to 1." + ) + + +@no_type_check +def _init_param_handle_from_module( + state: _FSDPState, + fully_sharded_module: nn.Module, + device_id: Optional[Union[int, torch.device]], + param_init_fn: Optional[Callable[[nn.Module], None]], + sync_module_states: bool, +) -> _FSDPState: + """Initialize a ``FlatParamHandle`` from a module ``fully_sharded_module``.""" + _check_single_device_module(fully_sharded_module, state._ignored_params, device_id) + device_from_device_id = _get_device_from_device_id( + device_id, state.rank, state._device_handle + ) + is_meta_module, is_torchdistX_deferred_init = _need_to_materialize_module( + fully_sharded_module, state._ignored_params, state._ignored_modules + ) + # Materialize the module if needed + if (is_meta_module or is_torchdistX_deferred_init) and param_init_fn is not None: + _materialize_with_param_init_fn( + fully_sharded_module, param_init_fn, state._ignored_modules + ) + elif is_meta_module: + _materialize_meta_module( + fully_sharded_module, + device_id, + state._ignored_modules, + state._device_handle, + ) + elif is_torchdistX_deferred_init: + deferred_init.materialize_module( + fully_sharded_module, + check_fn=lambda submodule: _get_module_fsdp_state(submodule) is None + and submodule not in state._ignored_modules, + ) + + ignored_buffers = { + buffer + for ignored_module in state._ignored_modules + for buffer in ignored_module.buffers() + } + + _move_module_to_device( + fully_sharded_module, + state._ignored_params, + ignored_buffers, + device_from_device_id, + ) + state.compute_device = _get_compute_device( + fully_sharded_module, + state._ignored_params, + device_from_device_id, + state.rank, + state._device_handle, + ) + + managed_params = list(_get_orig_params(fully_sharded_module, state._ignored_params)) + _verify_managed_params(fully_sharded_module, managed_params) + if sync_module_states: + _sync_module_params_and_buffers( + fully_sharded_module, managed_params, state.process_group + ) + if state.sharding_strategy in HYBRID_SHARDING_STRATEGIES: + _sync_module_params_and_buffers( + fully_sharded_module, managed_params, state._inter_node_pg + ) + _init_param_handle_from_params(state, managed_params, fully_sharded_module) + return state + + +@no_type_check +def _init_param_handle_from_params( + state: _FSDPState, + params: list[nn.Parameter], + fully_sharded_module: nn.Module, +): + if len(params) == 0: + return + handle = FlatParamHandle( + params, + fully_sharded_module, + state.compute_device, + SHARDING_STRATEGY_MAP[state.sharding_strategy], + state.cpu_offload.offload_params, + state.mixed_precision.param_dtype, + state.mixed_precision.reduce_dtype, + state.mixed_precision.keep_low_precision_grads, + state.process_group, + state._use_orig_params, + fsdp_extension=state._fsdp_extension, + ) + handle.shard() + assert not state._handle + state.params.append(handle.flat_param) + state._handle = handle + state._fully_sharded_module_to_handle[handle._fully_sharded_module] = handle + cpu_device = torch.device("cpu") + if state.cpu_offload.offload_params and handle.flat_param.device != cpu_device: + handle.flat_param_to(cpu_device) + + +def _get_ignored_modules( + root_module: nn.Module, + _ignored_modules: Optional[Iterable[torch.nn.Module]], +) -> set[nn.Module]: + """ + Check that ``_ignored_modules`` is an iterable of ``nn.Module`` s without any FSDP instances. + + Return the modules contained in their module + subtrees as a :class:`set`. Nested FSDP instances are excluded, but their + already-computed ignored modules are included. + + ``_ignored_modules`` represents the argument passed by the user to FSDP. + """ + msg_prefix = "`ignored_modules` should be an iterable of `torch.nn.Module`s " + try: + ignored_root_modules = ( + set(_ignored_modules) if _ignored_modules is not None else set() + ) + except TypeError as e: + raise TypeError(msg_prefix + f"but got {type(_ignored_modules)}") from e + for module in ignored_root_modules: + if not isinstance(module, torch.nn.Module): + raise TypeError(msg_prefix + f"but got an iterable with {type(module)}") + if _get_module_fsdp_state(module): + # TODO: We may relax this by taking the FSDP instance's wrapped + # module to provide more flexibility to the user. + raise ValueError("`ignored_modules` should not include FSDP modules") + # Treat modules that cannot compose with `fully_shard` as ignored modules, + # meaning that their subtrees are ignored + for module in root_module.modules(): + if not traversal_utils._composable(module): + ignored_root_modules.add(module) + # NOTE: Even if `ignored_root_modules` is empty, do not return early so + # that this FSDP instance can get any ignored modules from its children. + + # Include child modules and exclude nested FSDP modules themselves + ignored_modules = { + child + for module in ignored_root_modules + for child in module.modules() + if not isinstance(child, fsdp_file.FullyShardedDataParallel) + } + if root_module in ignored_modules: + warnings.warn( + "Trying to ignore the top-level module passed into the FSDP " + "constructor itself will result in all parameters being " + f"ignored and is not well-supported: {module}" + ) + # Include nested FSDP modules' ignored modules + for submodule in root_module.modules(): + optional_fsdp_state = _get_module_fsdp_state(submodule) + if optional_fsdp_state is not None: + assert hasattr(optional_fsdp_state, "_ignored_modules") + ignored_modules.update(optional_fsdp_state._ignored_modules) + return ignored_modules + + +def _get_ignored_params( + root_module: torch.nn.Module, + ignored_modules: set[torch.nn.Module], + ignored_parameters: Optional[Iterable[torch.nn.Parameter]] = None, +) -> set[torch.nn.Parameter]: + """ + Return the parameters of the modules in ``ignored_modules`` and the parameters in ``ignored_parameters``. + + :class:`FlatParameter` s are excluded from the result. + """ + all_ignored_params: set[torch.nn.Parameter] = set() + + params_in_ignored_modules = { + p for m in ignored_modules for p in m.parameters() if not _is_fsdp_flattened(p) + } + + all_ignored_params.update(params_in_ignored_modules) + + if ignored_parameters is not None: + params_in_ignored_parameters = { + p for p in ignored_parameters if not _is_fsdp_flattened(p) + } + all_ignored_params.update(params_in_ignored_parameters) + + # Always include nested FSDP modules' ignored parameters + for submodule in root_module.modules(): + optional_fsdp_state = _get_module_fsdp_state(submodule) + if optional_fsdp_state is not None: + assert hasattr(optional_fsdp_state, "_ignored_params") + all_ignored_params.update(optional_fsdp_state._ignored_params) + + return all_ignored_params + + +def _get_ignored_buffer_names( + root_module: torch.nn.Module, + ignored_modules: set[torch.nn.Module], +) -> set[str]: + """Return the cleaned buffer FQNs in ``ignored_modules``.""" + all_ignored_buffer_names: set[str] = set() + + buffers_in_ignored_modules = { + buffer for m in ignored_modules for buffer in m.buffers() + } + + all_ignored_buffer_names.update( + { + clean_tensor_name(buffer_name) + for buffer_name, buffer in root_module.named_buffers() + if buffer in buffers_in_ignored_modules + } + ) + + # Always include nested FSDP modules' ignored buffer names + for submodule in root_module.modules(): + optional_fsdp_state = _get_module_fsdp_state(submodule) + if optional_fsdp_state is not None: + assert hasattr(optional_fsdp_state, "_ignored_buffer_names") + all_ignored_buffer_names.update(optional_fsdp_state._ignored_buffer_names) + + return all_ignored_buffer_names + + +def _get_buffer_names(root_module: nn.Module) -> set[str]: + """Return the fully prefixed names of all buffers in the module hierarchy rooted at ``root_module`` as a class:`set`.""" + return { + clean_tensor_name(buffer_name) for buffer_name, _ in root_module.named_buffers() + } + + +def _check_single_device_module( + module: nn.Module, + ignored_params: set[nn.Parameter], + device_id: Optional[Union[int, torch.device]], +) -> None: + """ + Raise an error if ``module`` has original parameters on multiple devices, ignoring the parameters in ``ignored_params``. + + Thus, after this method, the + module must be either fully on the CPU or fully on a non-CPU device. + """ + devices = {param.device for param in _get_orig_params(module, ignored_params)} + # We allow module to be partially on CPU and partially on GPU if device_id is not + # None, since the device_id arg will result in the CPU portion being moved to + # GPU. This is useful in cases where part of the module may be parallelized + # by another algorithm and may already be on GPU. We'd like to enforce device_id + # to not be None, otherwise we'd flatten parameters in a mixed module which is + # not supported. + if len(devices) == 2 and torch.device("cpu") in devices: + if device_id is None: + raise RuntimeError( + "To support a module with both CPU and GPU params, " + "please pass in device_id argument." + ) + elif len(devices) > 1: + raise RuntimeError( + f"FSDP only supports single device modules but got params on {devices}" + ) + + +def _get_device_from_device_id( + device_id: Optional[Union[int, torch.device]], + rank: int, + device_handle: _FSDPDeviceHandle, +) -> Optional[torch.device]: + """ + Return a ``torch.device`` for the specified ``device_id``. + + Processes ``device_id`` and returns either the corresponding device or + ``None`` if ``device_id`` is ``None``. + """ + if device_id is None: + return None + device = ( + device_id if isinstance(device_id, torch.device) else torch.device(device_id) + ) + if device.type != "cpu" and device.index is None: + warnings.warn( + f"FSDP got the argument `device_id` {device_id} on rank " + f"{rank}, which does not have an explicit index. " + f"FSDP will use the current device {device_handle.current_device()}. " + f"If this is incorrect, please explicitly call `torch.{device.type}.set_device()` " + "before FSDP initialization or pass in the explicit device " + "index as the `device_id` argument." + ) + device = torch.device(device_handle.current_device()) + return device + + +def _need_to_materialize_module( + module: nn.Module, + ignored_params: set[nn.Parameter], + ignored_modules: set[nn.Module], +) -> tuple[bool, bool]: + """ + Return if ``module`` has parameters on meta device and if ``module`` is using torchdistX deferred initialization. + + At most of the returned bools can + be ``True``. If either is ``True``, then ``module`` needs to be + materialized. + """ + managed_params = list(_get_orig_params(module, ignored_params)) + is_meta_module = any(param.is_meta for param in managed_params) + # TODO: We need to establish a contract for FSDP and buffers. For now, we + # skip checking for meta buffers from ignored modules. We should consider + # refactoring the initialization holistically to avoid so many traversals. + for submodule in module.modules(): + if submodule in ignored_modules: + continue + for buf in submodule.buffers(recurse=False): + is_meta_module |= buf.is_meta + is_torchdistX_deferred_init = ( + not is_meta_module + and _TORCHDISTX_AVAIL + and any(fake.is_fake(param) for param in managed_params) + ) + return is_meta_module, is_torchdistX_deferred_init + + +def _materialize_with_param_init_fn( + root_module: nn.Module, + param_init_fn: Callable[[nn.Module], None], + ignored_modules: set[nn.Module], +) -> None: + if not callable(param_init_fn): + raise ValueError( + f"Expected {param_init_fn} to be callable but got {type(param_init_fn)}" + ) + modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules) + for module in modules_to_materialize: + param_init_fn(module) + + +def _materialize_meta_module( + root_module: nn.Module, + device_from_device_id: Optional[torch.device], + ignored_modules: set[nn.Module], + device_handle: _FSDPDeviceHandle, +): + # Run default meta device initialization + materialization_device = device_from_device_id or torch.device( + device_handle.current_device() + ) + modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules) + module = None + try: + # Assume that each module's `reset_parameters()` only initializes its + # own parameters and not those of its children + with torch.no_grad(): + for module in modules_to_materialize: + # As a contract to the user, only call `reset_parameters()` if + # the module has directly managed parameters/buffers + module_state_iter = itertools.chain( + module.parameters(recurse=False), module.buffers(recurse=False) + ) + has_module_states = len(list(module_state_iter)) > 0 + if has_module_states: + module.to_empty(device=materialization_device, recurse=False) + module.reset_parameters() # type: ignore[operator] + except BaseException as e: + warnings.warn( + "Unable to call `reset_parameters()` for module on meta " + f"device with error {str(e)}. Please ensure that your module of" + f"type {type(module)} implements a `reset_parameters()` method." # type: ignore[possibly-undefined] + ) + raise e + + +def _get_modules_to_materialize( + root_module: nn.Module, ignored_modules: set[nn.Module] +) -> list[nn.Module]: + # Run BFS to collect the modules to materialize via `reset_parameters()`, + # stopping at any module with FSDP already applied or at ignored modules. + modules_to_materialize: list[nn.Module] = [] + queue = collections.deque([root_module]) + visited_modules: set[nn.Module] = {root_module} + while queue: + module = queue.popleft() + modules_to_materialize.append(module) + for child_module in module.children(): + if ( + child_module not in visited_modules + and _get_module_fsdp_state(child_module) is None + and child_module not in ignored_modules + ): + visited_modules.add(child_module) + queue.append(child_module) + return modules_to_materialize + + +def _move_module_to_device( + module: nn.Module, + ignored_params: set[nn.Parameter], + ignored_buffers: set[torch.Tensor], + device_from_device_id: Optional[torch.device], +) -> None: + """ + Move ``module`` depending on ``device_from_device_id`` and its current device. + + This includes moving ignored modules' parameters. + + - If ``device_from_device_id`` is not ``None``, then this moves + ``module`` to the device. + - If ``device_from_device_id`` is ``None``, then this does not move + ``module`` but warns the user if it is on CPU. + + Precondition: ``_check_single_device_module()``. + """ + cpu_device = torch.device("cpu") + if device_from_device_id is not None: + # BFS from `module` without traversing any nested FSDP instances to + # collect the parameters/buffers that have not yet been managed + queue: collections.deque[nn.Module] = collections.deque() + queue.append(module) + params: list[nn.Parameter] = [] + buffers: list[torch.Tensor] = [] + while queue: + curr_module = queue.popleft() + # NOTE: We include a check to only move parameters/buffers that are + # on CPU device. If they are on a CUDA device different from the + # one specified by `device_id`, then this does NOT move them. This + # is so that we can raise an error in `_get_compute_device()`. + params.extend( + param + for param in curr_module.parameters(recurse=False) + if param.device == cpu_device + ) + buffers.extend( + buffer + for buffer in curr_module.buffers(recurse=False) + if buffer.device == cpu_device + ) + for submodule in curr_module.children(): + if not isinstance(submodule, fsdp_file.FullyShardedDataParallel): + queue.append(submodule) + params_to_move = [p for p in params if p not in ignored_params] + bufs_to_move = [p for p in buffers if p not in ignored_buffers] + _move_states_to_device(params_to_move, bufs_to_move, device_from_device_id) + return + param = next(_get_orig_params(module, ignored_params), None) + if param is not None and param.device == cpu_device: + _warn_cpu_init() + + +def _move_states_to_device( + params: list[nn.Parameter], + buffers: list[torch.Tensor], + device_from_device_id: Optional[torch.device], +) -> None: + """ + Move states to the specified device. + + Precondition: ``_check_single_device_module()`` and module's parameters and + buffers have been materialized if needed. + """ + if len(params) == 0 and len(buffers) == 0: + return + if len(params) > 0: + current_device = params[0].device + elif len(buffers) > 0: + current_device = buffers[0].device + cpu_device = torch.device("cpu") + if device_from_device_id is not None: + # Move the parameters and buffers like the `.data` code path in + # `nn.Module._apply()`, which underlies `nn.Module.to()` + for param in params: + with torch.no_grad(): + param.data = param.to(device_from_device_id) + if param.grad is not None: + param.grad.data = param.grad.to(device_from_device_id) + for buffer in buffers: + buffer.data = buffer.to(device_from_device_id) + elif current_device == cpu_device: # type: ignore[possibly-undefined] + _warn_cpu_init() + + +def _warn_cpu_init(): + warnings.warn( + "The passed-in `module` is on CPU and will thus have FSDP's sharding " + "initialization run on CPU, which may be slower than on GPU. We " + "recommend passing in the `device_id` argument for FSDP to move " + "`module` to GPU for the sharding initialization. `module` must also " + "be on GPU device to work with the `sync_module_states=True` flag " + "since that requires GPU communication." + ) + + +def _get_compute_device( + module: nn.Module, + ignored_params: set[nn.Parameter], + device_from_device_id: Optional[torch.device], + rank: int, + device_handle: _FSDPDeviceHandle, +) -> torch.device: + """ + Determine and return this FSDP instance's compute device. + + If the module is already on a non-CPU device, then the compute device is that non-CPU + device. If the module is on CPU, then the compute device is the current + device. + + Since this method should be called after materializing the module, any + non-CPU device should not be meta device. For now, the compute device is + always a CUDA or CUDA-like device with its explicit index. + + Precondition: ``_check_single_device_module()`` and + ``_move_module_to_device()``. + """ + param = next(_get_orig_params(module, ignored_params), None) + if param is not None and param.device.type != "cpu": + compute_device = param.device # Determined by model param placement + else: + compute_device = torch.device(device_handle.current_device()) + if device_from_device_id is not None and compute_device != device_from_device_id: + raise ValueError( + f"Inconsistent compute device and `device_id` on rank {rank}: " + f"{compute_device} vs {device_from_device_id}" + ) + return compute_device + + +# TODO: See how to deprecate! +def _sync_module_params_and_buffers( + module: nn.Module, + params: list[nn.Parameter], + process_group: dist.ProcessGroup, +) -> None: + """ + Synchronize module states (i.e. parameters ``params`` and all not-yet-synced buffers) by broadcasting from rank 0 to all ranks. + + Precondition: ``sync_module_states == True`` and ``self.process_group`` has + been set. + """ + module_states: list[torch.Tensor] = [] + for buffer in module.buffers(): + # Avoid re-synchronizing buffers in case of nested wrapping + if not getattr(buffer, FSDP_SYNCED, False): + setattr(buffer, FSDP_SYNCED, True) + detached_buffer = buffer.detach() + if is_traceable_wrapper_subclass(detached_buffer): + # NOTE: Here we assume no nested subclasses, at most one level of subclass + # in both model's buffers and params + attrs, _ = detached_buffer.__tensor_flatten__() # type: ignore[attr-defined] + inner_buffers = [getattr(detached_buffer, attr) for attr in attrs] + module_states.extend(inner_buffers) + else: + module_states.append(detached_buffer) + + for param in params: + detached_param = param.detach() + if is_traceable_wrapper_subclass(detached_param): + attrs, _ = detached_param.__tensor_flatten__() # type: ignore[attr-defined] + inner_params = [getattr(detached_param, attr) for attr in attrs] + module_states.extend(inner_params) + else: + module_states.append(detached_param) + + _check_module_states_for_sync_module_states(module_states) + _sync_params_and_buffers( + process_group, + module_states, + PARAM_BROADCAST_BUCKET_SIZE, + src=0, + ) + + +def _check_module_states_for_sync_module_states( + module_states: list[torch.Tensor], +) -> None: + if module_states and any( + tensor.device == torch.device("cpu") for tensor in module_states + ): + raise ValueError( + "The module has CPU parameters or buffers when `sync_module_states=True`, " + "which requires them to be on GPU. Please specify the `device_id` argument " + "or move the module to GPU before passing it to FSDP." + ) + + +def _get_orig_params( + module: nn.Module, + ignored_params: set[nn.Parameter], +) -> Iterator[nn.Parameter]: + """ + Return an iterator over the original parameters in ``module``. + + The iterator does not return + the parameters in ``ignored_params``, any ``FlatParameter`` s (which may be + present due to nested FSDP wrapping), or any original parameters already + flattened (only relevant when ``use_orig_params=True``). + """ + param_gen = module.parameters() + try: + while True: + param = next(param_gen) + if param not in ignored_params and not _is_fsdp_flattened(param): + yield param + except StopIteration: + pass + + +def _check_orig_params_flattened( + fsdp_module, + ignored_params: set[nn.Parameter], +) -> None: + """ + Check that original parameters in ``fsdp_module`` have been flattened. + + The flattened parameters are made + invisible to ``named_parameters()`` for the module hierarchy rooted at + ``fsdp_module``. This should be called as a sanity check after flattening + the wrapped module's parameters. + """ + for param_name, param in _named_parameters_with_duplicates(fsdp_module): + if param not in ignored_params and not _is_fsdp_flattened(param): + raise RuntimeError( + f"Found an unflattened parameter: {param_name}; " + f"{param.size()} {param.__class__}" + ) + + +def _get_default_comm_hook(sharding_strategy: ShardingStrategy): + return ( + default_hooks.allreduce_hook + if sharding_strategy == ShardingStrategy.NO_SHARD + else default_hooks.reduce_scatter_hook + ) + + +def _get_default_comm_hook_state( + process_group: dist.ProcessGroup, +) -> default_hooks.DefaultState: + return default_hooks.DefaultState(process_group=process_group) diff --git a/shared/package-files/3a/3a2dd06e2c40a6f586a06226896ecf023476f1c4d0aa545764a308dceec4e146/encryption.py b/shared/package-files/3a/3a2dd06e2c40a6f586a06226896ecf023476f1c4d0aa545764a308dceec4e146/encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..d07f8ae2735207f5f6c4e6463e123ff04c539e47 --- /dev/null +++ b/shared/package-files/3a/3a2dd06e2c40a6f586a06226896ecf023476f1c4d0aa545764a308dceec4e146/encryption.py @@ -0,0 +1,61 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import base64 + +import pyarrow.parquet.encryption as pe + + +class InMemoryKmsClient(pe.KmsClient): + """This is a mock class implementation of KmsClient, built for testing + only. + """ + + def __init__(self, config): + """Create an InMemoryKmsClient instance.""" + pe.KmsClient.__init__(self) + self.master_keys_map = config.custom_kms_conf + + def wrap_key(self, key_bytes, master_key_identifier): + """Not a secure cipher - the wrapped key + is just the master key concatenated with key bytes""" + master_key_bytes = self.master_keys_map[master_key_identifier].encode( + 'utf-8') + wrapped_key = b"".join([master_key_bytes, key_bytes]) + result = base64.b64encode(wrapped_key) + return result + + def unwrap_key(self, wrapped_key, master_key_identifier): + """Not a secure cipher - just extract the key from + the wrapped key""" + expected_master_key = self.master_keys_map[master_key_identifier] + decoded_wrapped_key = base64.b64decode(wrapped_key) + master_key_bytes = decoded_wrapped_key[:16] + decrypted_key = decoded_wrapped_key[16:] + if (expected_master_key == master_key_bytes.decode('utf-8')): + return decrypted_key + raise ValueError("Incorrect master key used", + master_key_bytes, decrypted_key) + + +def verify_file_encrypted(path): + """Verify that the file is encrypted by looking at its first 4 bytes. + If it's the magic string PARE + then this is a parquet with encrypted footer.""" + with open(path, "rb") as file: + magic_str = file.read(4) + # Verify magic string for parquet with encrypted footer is PARE + assert magic_str == b'PARE' diff --git a/shared/package-files/3a/3a310acad65de7373fef8d88449cfcde3cf4e1f5cec32cc3c4119c34512893ff/_standard_gamma_cpu_dispatch.h b/shared/package-files/3a/3a310acad65de7373fef8d88449cfcde3cf4e1f5cec32cc3c4119c34512893ff/_standard_gamma_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9738b8cef0b330c3bcf11e59ae8159d2a6d25942 --- /dev/null +++ b/shared/package-files/3a/3a310acad65de7373fef8d88449cfcde3cf4e1f5cec32cc3c4119c34512893ff/_standard_gamma_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _standard_gamma(const at::Tensor & self, ::std::optional generator=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3a/3a35acb19c9f85a5eadc39edc37e695a9d19b3d43436de80cee032b673c6f5dc/test_anticommutator.cpython-311.pyc b/shared/package-files/3a/3a35acb19c9f85a5eadc39edc37e695a9d19b3d43436de80cee032b673c6f5dc/test_anticommutator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfcbacbcb334a5523caebcc0db479bd3bcbb59fe Binary files /dev/null and b/shared/package-files/3a/3a35acb19c9f85a5eadc39edc37e695a9d19b3d43436de80cee032b673c6f5dc/test_anticommutator.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a388da3f4a3f5848faa9c51c0c917234253eaafacb516d573f4d50c53b7c030/fuse_attention.cpython-311.pyc b/shared/package-files/3a/3a388da3f4a3f5848faa9c51c0c917234253eaafacb516d573f4d50c53b7c030/fuse_attention.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97d9a5cb0d4356b0cefb8a54e699e99995baccc2 Binary files /dev/null and b/shared/package-files/3a/3a388da3f4a3f5848faa9c51c0c917234253eaafacb516d573f4d50c53b7c030/fuse_attention.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a3bc509319954b941b5b4ef68be310db0408b3ca77e1c0eff67ce34e6da2129/error.py b/shared/package-files/3a/3a3bc509319954b941b5b4ef68be310db0408b3ca77e1c0eff67ce34e6da2129/error.py new file mode 100644 index 0000000000000000000000000000000000000000..03b7f52fb9de435b9e58fa4a0bb141cc191e84c5 --- /dev/null +++ b/shared/package-files/3a/3a3bc509319954b941b5b4ef68be310db0408b3ca77e1c0eff67ce34e6da2129/error.py @@ -0,0 +1,56 @@ +from enum import Enum + + +class ExportErrorType(Enum): + # User providing invalid inputs to either tracer, or other public facing APIs + INVALID_INPUT_TYPE = 1 + + # User returning values from their models that we don't support. + INVALID_OUTPUT_TYPE = 2 + + # Generated IR does not conform to Export IR Specification. + VIOLATION_OF_SPEC = 3 + + # User's code contains types and functionalities we don't support. + NOT_SUPPORTED = 4 + + # User's code didn't provide necessary details for us to successfully trace and export. + # For example, we use a lot of decorators and ask users to annotate their model. + MISSING_PROPERTY = 5 + + # User is using an API without proper initialization step. + UNINITIALIZED = 6 + + +def internal_assert(pred: bool, assert_msg: str) -> None: + """ + This is exir's custom assert method. It internally just throws InternalError. + Note that the sole purpose is to throw our own error while maintaining similar syntax + as python assert. + """ + + if not pred: + raise InternalError(assert_msg) + + +class InternalError(Exception): + """ + Raised when an internal invariance is violated in EXIR stack. + Should hint users to report a bug to dev and expose the original + error message. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class ExportError(Exception): + """ + This type of exception is raised for errors that are directly caused by the user + code. In general, user errors happen during model authoring, tracing, using our public + facing APIs, and writing graph passes. + """ + + def __init__(self, error_code: ExportErrorType, message: str) -> None: + prefix = f"[{error_code}]: " + super().__init__(prefix + message) diff --git a/shared/package-files/3a/3a3d09a8df27d098017e75dcfb54f2e0582936ea4ca6c1c3788497c10c297dba/__init__.cpython-311.pyc b/shared/package-files/3a/3a3d09a8df27d098017e75dcfb54f2e0582936ea4ca6c1c3788497c10c297dba/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..489377040fd16c7616347c25eac3fe5c5b6b43ad Binary files /dev/null and b/shared/package-files/3a/3a3d09a8df27d098017e75dcfb54f2e0582936ea4ca6c1c3788497c10c297dba/__init__.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a4296fcca7ec136f320392a08e7d87ab4095919eea87719fc3706d50e9586d0/matrices.cpython-311.pyc b/shared/package-files/3a/3a4296fcca7ec136f320392a08e7d87ab4095919eea87719fc3706d50e9586d0/matrices.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd58358693de65cdbc900382dbef3aa93704318 Binary files /dev/null and b/shared/package-files/3a/3a4296fcca7ec136f320392a08e7d87ab4095919eea87719fc3706d50e9586d0/matrices.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a4304ddd15fafaedc1910c1efbd362915080354ff79dbfafe977ee749dbd8fb/mkldnn_tensor.h b/shared/package-files/3a/3a4304ddd15fafaedc1910c1efbd362915080354ff79dbfafe977ee749dbd8fb/mkldnn_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..adf0927ca0a5eb5473cd7499e642a0b42afaa412 --- /dev/null +++ b/shared/package-files/3a/3a4304ddd15fafaedc1910c1efbd362915080354ff79dbfafe977ee749dbd8fb/mkldnn_tensor.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch::aot_inductor { + +void* data_ptr_from_mkldnn(at::Tensor* mkldnn_tensor); + +at::Tensor mkldnn_tensor_from_data_ptr( + void* data_ptr, + at::IntArrayRef dims, + at::ScalarType dtype, + at::Device device, + const uint8_t* opaque_metadata, + int64_t opaque_metadata_size); + +} // namespace torch::aot_inductor diff --git a/shared/package-files/3a/3a43441aacfdbe39c99b078cce24c7a8464e8e5d052f366561d6bf8740e5e2ff/_linalg_svd_meta.h b/shared/package-files/3a/3a43441aacfdbe39c99b078cce24c7a8464e8e5d052f366561d6bf8740e5e2ff/_linalg_svd_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..8fea5a4e9d7579738c2838a7f4706fd73787d9f5 --- /dev/null +++ b/shared/package-files/3a/3a43441aacfdbe39c99b078cce24c7a8464e8e5d052f366561d6bf8740e5e2ff/_linalg_svd_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured__linalg_svd : public at::impl::MetaBase { + + + void meta(const at::Tensor & A, bool full_matrices, bool compute_uv, ::std::optional driver); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a4689eef46dcb4964a32f03467175913f90db21f76ecf1993499abc1a115900/cuda.h b/shared/package-files/3a/3a4689eef46dcb4964a32f03467175913f90db21f76ecf1993499abc1a115900/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..1eecfe9b5ddf9c8538113b09c8de01d1e7099cc7 --- /dev/null +++ b/shared/package-files/3a/3a4689eef46dcb4964a32f03467175913f90db21f76ecf1993499abc1a115900/cuda.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include + +namespace torch::cuda { + +/// Returns the number of CUDA devices available. +c10::DeviceIndex TORCH_API device_count(); + +/// Returns true if at least one CUDA device is available. +bool TORCH_API is_available(); + +/// Returns true if CUDA is available, and CuDNN is available. +bool TORCH_API cudnn_is_available(); + +/// Sets the seed for the current GPU. +void TORCH_API manual_seed(uint64_t seed); + +/// Sets the seed for all available GPUs. +void TORCH_API manual_seed_all(uint64_t seed); + +/// Waits for all kernels in all streams on a CUDA device to complete. +void TORCH_API synchronize(int64_t device_index = -1); + +} // namespace torch::cuda diff --git a/shared/package-files/3a/3a4771fff878e81918db2e7276fd5f39f1216917f3d5978a8a05aa20054b41cc/array_manager.cpython-311.pyc b/shared/package-files/3a/3a4771fff878e81918db2e7276fd5f39f1216917f3d5978a8a05aa20054b41cc/array_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16722978bff69022c52ac19c7ac80848c9549786 Binary files /dev/null and b/shared/package-files/3a/3a4771fff878e81918db2e7276fd5f39f1216917f3d5978a8a05aa20054b41cc/array_manager.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a4bc8be447d9b68a523df62ab1bad9a74096b32c2ec246835610bb0ab7325f6/test_install_scripts.cpython-311.pyc b/shared/package-files/3a/3a4bc8be447d9b68a523df62ab1bad9a74096b32c2ec246835610bb0ab7325f6/test_install_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26ccaafe91441256062048ba7c876896bec43d6 Binary files /dev/null and b/shared/package-files/3a/3a4bc8be447d9b68a523df62ab1bad9a74096b32c2ec246835610bb0ab7325f6/test_install_scripts.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a50132fee323f0146f74311c297ddf002a046fde863212e54f1342e2b4716e6/format_utils.py b/shared/package-files/3a/3a50132fee323f0146f74311c297ddf002a046fde863212e54f1342e2b4716e6/format_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc695c495cb59f959c43cfe3276942fcaadc66a8 --- /dev/null +++ b/shared/package-files/3a/3a50132fee323f0146f74311c297ddf002a046fde863212e54f1342e2b4716e6/format_utils.py @@ -0,0 +1,280 @@ +# mypy: allow-untyped-defs +import argparse +import os +from enum import Enum +from typing import cast, Optional, Union + +import torch +import torch.distributed as dist +from torch.distributed._shard._utils import narrow_tensor_by_index +from torch.distributed.checkpoint import FileSystemReader, FileSystemWriter +from torch.distributed.checkpoint._nested_dict import flatten_state_dict +from torch.distributed.checkpoint.default_planner import ( + _EmptyStateDictLoadPlanner, + DefaultLoadPlanner, +) +from torch.distributed.checkpoint.metadata import ( + Metadata, + STATE_DICT_TYPE, + STORAGE_TYPES, + TensorProperties, + TensorStorageMetadata, +) +from torch.distributed.checkpoint.planner import LoadItemType, LoadPlan, LoadPlanner +from torch.distributed.checkpoint.planner_helpers import _create_chunk_list +from torch.distributed.checkpoint.state_dict_loader import _load_state_dict +from torch.distributed.checkpoint.state_dict_saver import _save_state_dict +from torch.distributed.checkpoint.storage import StorageReader +from torch.futures import Future + + +__all__ = [ + "dcp_to_torch_save", + "torch_save_to_dcp", + "BroadcastingTorchSaveReader", + "DynamicMetaLoadPlanner", +] + + +class BroadcastingTorchSaveReader(StorageReader): + """ + StorageReader for reading a Torch Save file. This reader will read the entire checkpoint + on the coordinator rank, and then broadcast and shard each tensor to all ranks. + + . N.B. Intended to be used with DynamicMetaLoadPlanner + + .. warning:: + Current implementation only supports loading Tensors. + + >>> # xdoctest: +SKIP("undefined vars") + >>> sd = {"mode": model} + >>> dcp.load( + >>> sd, + >>> storage_reader=BroadcastingTorchSaveReader(), + >>> planner=DynamicMetaLoadPlanner(), + >>> checkpoint_id="path_to_model.pt" + >>> ) + """ + + def __init__( + self, + checkpoint_id: Optional[Union[str, os.PathLike]] = None, + coordinator_rank: int = 0, + ) -> None: + self.checkpoint_id = checkpoint_id + self.coordinator_rank = coordinator_rank + + def read_metadata(self) -> Metadata: + """Extends the default StorageReader to support building the metadata file""" + # Metadata is built in planner.set_up_planner, since we are not actually reading metadata from + # the disk + return Metadata(state_dict_metadata={}) + + def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]: + """ + Reads torch save data on the coordinator rank, and broadcast afterwards + this incurrs a communication cost, but avoids having to load + the entire checkpoint on each rank, hopefully preventing OOM issues + """ + planner = cast(DefaultLoadPlanner, planner) + + # data is read in on the coordinator rank, and broadcast afterwards + # this incurrs a communication cost, but it avoids having to load + # the entire checkpoint on each rank, hopefully preventing OOM issues + # TODO: read on each host, instead of only the coordinator + if self.is_coordinator: + assert self.checkpoint_id is not None + torch_state_dict = torch.load( + self.checkpoint_id, map_location="cpu", weights_only=False + ) + if planner.flatten_state_dict: + torch_state_dict, _ = flatten_state_dict(torch_state_dict) + else: + torch_state_dict = None + + for req in plan.items: + if req.type == LoadItemType.BYTE_IO: + raise RuntimeError( + f"Non-tensor value identified at {req.storage_index.fqn}. " + f"At this time {type(self).__name__} only supports loading Tensors." + ) + + # Broadcast the tensor from the coordinator rank + if self.is_coordinator: + pg_device = dist.distributed_c10d._get_pg_default_device() + tensor = torch_state_dict[req.storage_index.fqn].to(pg_device) + else: + tensor = torch.empty_like(planner.state_dict[req.storage_index.fqn]) + + dist.broadcast(tensor, src=self.coordinator_rank, async_op=False) + + tensor = narrow_tensor_by_index(tensor, req.storage_offsets, req.lengths) + target_tensor = planner.resolve_tensor(req).detach() + assert target_tensor.size() == tensor.size(), ( + f"req {req.storage_index} mismatch sizes, " + f"{target_tensor.size()} vs {tensor.size()}" + ) + target_tensor.copy_(tensor) + planner.commit_tensor(req, target_tensor) + + fut: Future = Future() + fut.set_result(None) + return fut + + def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None: + """Implementation of the StorageReader method""" + self.is_coordinator = is_coordinator + if self.is_coordinator: + assert dist.get_rank() == self.coordinator_rank + + assert self.checkpoint_id is not None + + def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan: + """Implementation of the StorageReader method""" + return plan + + def prepare_global_plan(self, global_plan: list[LoadPlan]) -> list[LoadPlan]: + """Implementation of the StorageReader method""" + return global_plan + + def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None: + """Implementation of the StorageReader method""" + self.checkpoint_id = checkpoint_id + + @classmethod + def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool: + """Implementation of the StorageReader method""" + return os.path.isfile(checkpoint_id) + + +class DynamicMetaLoadPlanner(DefaultLoadPlanner): + """ + Extension of DefaultLoadPlanner, which creates a new Metadata object based on the passed in state dict, + avoiding the need to read metadata from disk. This is useful when reading formats which don't have a + metadata file, like Torch Save files. + + . N.B. Intended to be used with BroadcastingTorchSaveReader + + .. warning:: + Current implementation only supports loading Tensors. + + >>> # xdoctest: +SKIP("undefined vars") + >>> sd = {"mode": model} + >>> dcp.load( + >>> sd, + >>> storage_reader=BroadcastingTorchSaveReader(), + >>> planner=DynamicMetaLoadPlanner(), + >>> checkpoint_id="path_to_model.pt" + >>> ) + """ + + def set_up_planner( + self, + state_dict: STATE_DICT_TYPE, + metadata: Optional[Metadata] = None, + is_coordinator: bool = False, + ) -> None: + """Setups of the planner, extnding default behavior by creating the Metadata object from the state dict""" + super().set_up_planner(state_dict, metadata, is_coordinator) + + state_dict_metadata: dict[str, STORAGE_TYPES] = {} + for key, tensor in self.state_dict.items(): + if not torch.is_tensor(tensor): + raise RuntimeError( + f"Non-tensor value identified at {key}. " + f"At this time {type(self).__name__} only supports loading Tensors." + ) + + state_dict_metadata[key] = TensorStorageMetadata( + TensorProperties(dtype=tensor.dtype), + tensor.size(), + _create_chunk_list(tensor), + ) + self.metadata = Metadata(state_dict_metadata=state_dict_metadata) + + +def dcp_to_torch_save( + dcp_checkpoint_dir: Union[str, os.PathLike], + torch_save_path: Union[str, os.PathLike], +): + """ + Given a directory containing a DCP checkpoint, this function will convert it into a + Torch save file. + + Args: + dcp_checkpoint_dir: Directory containing the DCP checkpoint. + torch_save_path: Filename to store the converted Torch save file. + + .. warning:: + To avoid OOM, it's recommended to only run this function on a single rank. + """ + sd: STATE_DICT_TYPE = {} + _load_state_dict( + sd, + storage_reader=FileSystemReader(dcp_checkpoint_dir), + planner=_EmptyStateDictLoadPlanner(), + no_dist=True, + ) + torch.save(sd, torch_save_path) + + +def torch_save_to_dcp( + torch_save_path: Union[str, os.PathLike], + dcp_checkpoint_dir: Union[str, os.PathLike], +): + """ + Given the location of a torch save file, converts it into a DCP checkpoint. + + Args: + torch_save_path: Filename of the Torch save file. + dcp_checkpoint_dir: Directory to store the DCP checkpoint. + + .. warning:: + To avoid OOM, it's recommended to only run this function on a single rank. + """ + + state_dict = torch.load(torch_save_path, weights_only=False) + # we don't need stateful behavior here because the expectation is anything loaded by + # torch.load would not contain stateful objects. + _save_state_dict( + state_dict, storage_writer=FileSystemWriter(dcp_checkpoint_dir), no_dist=True + ) + + +if __name__ == "__main__": + + class FormatMode(Enum): + TORCH_TO_DCP = "torch_to_dcp" + DCP_TO_TORCH = "dcp_to_torch" + + # Parse command-line arguments + parser = argparse.ArgumentParser() + parser.add_argument( + "mode", + type=str, + help="Conversion mode", + choices=[m.value for m in FormatMode], + default=FormatMode.TORCH_TO_DCP, + ) + parser.add_argument("src", type=str, help="Path to the source model") + parser.add_argument("dst", type=str, help="Path to the destination model") + args = parser.parse_args() + + print( + f"Converting checkpoint from {args.src} to {args.dst} using method: '{args.mode}'" + ) + checkpoint_missing_warning = ( + f"No checkpoint found at {args.src}. Skipping conversion." + ) + if args.mode == FormatMode.TORCH_TO_DCP.value: + if os.path.isfile(args.src): + torch_save_to_dcp(args.src, args.dst) + else: + print(checkpoint_missing_warning) + elif args.mode == FormatMode.DCP_TO_TORCH.value: + if os.path.isdir(args.src): + dcp_to_torch_save(args.src, args.dst) + else: + print(checkpoint_missing_warning) + else: + raise ValueError(f"Unknown conversion mode: {args.mode}") diff --git a/shared/package-files/3a/3a51d754e876047c9891c29817d979edf4e717801ad283b2cfcf242cc196ad7e/pprint.py b/shared/package-files/3a/3a51d754e876047c9891c29817d979edf4e717801ad283b2cfcf242cc196ad7e/pprint.py new file mode 100644 index 0000000000000000000000000000000000000000..d63879400478fe06f65cbfc1d4be2ba9d963d4d9 --- /dev/null +++ b/shared/package-files/3a/3a51d754e876047c9891c29817d979edf4e717801ad283b2cfcf242cc196ad7e/pprint.py @@ -0,0 +1,674 @@ +# Author: Fred L. Drake, Jr. +# fdrake@acm.org +# +# This is a simple little module I wrote to make life easier. I didn't +# see anything quite like it in the library, though I may have overlooked +# something. I wrote this when I was trying to read some heavily nested +# tuples with fairly non-descriptive content. This is modeled very much +# after Lisp/Scheme - style pretty-printing of lists. If you find it +# useful, thank small children who sleep at night. + +"""Support to pretty-print lists, tuples, & dictionaries recursively. + +Very simple, but useful, especially in debugging data structures. + +Classes +------- + +PrettyPrinter() + Handle pretty-printing operations onto a stream using a configured + set of formatting parameters. + +Functions +--------- + +pformat() + Format a Python object into a pretty-printed representation. + +pprint() + Pretty-print a Python object to a stream [default is sys.stdout]. + +saferepr() + Generate a 'standard' repr()-like value, but protect against recursive + data structures. + +""" + +import collections as _collections +import dataclasses as _dataclasses +import re +import sys as _sys +import types as _types +from io import StringIO as _StringIO + +__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", + "PrettyPrinter", "pp"] + + +def pprint(object, stream=None, indent=1, width=80, depth=None, *, + compact=False, sort_dicts=True, underscore_numbers=False): + """Pretty-print a Python object to a stream [default is sys.stdout].""" + printer = PrettyPrinter( + stream=stream, indent=indent, width=width, depth=depth, + compact=compact, sort_dicts=sort_dicts, + underscore_numbers=underscore_numbers) + printer.pprint(object) + +def pformat(object, indent=1, width=80, depth=None, *, + compact=False, sort_dicts=True, underscore_numbers=False): + """Format a Python object into a pretty-printed representation.""" + return PrettyPrinter(indent=indent, width=width, depth=depth, + compact=compact, sort_dicts=sort_dicts, + underscore_numbers=underscore_numbers).pformat(object) + +def pp(object, *args, sort_dicts=False, **kwargs): + """Pretty-print a Python object""" + pprint(object, *args, sort_dicts=sort_dicts, **kwargs) + +def saferepr(object): + """Version of repr() which can handle recursive data structures.""" + return PrettyPrinter()._safe_repr(object, {}, None, 0)[0] + +def isreadable(object): + """Determine if saferepr(object) is readable by eval().""" + return PrettyPrinter()._safe_repr(object, {}, None, 0)[1] + +def isrecursive(object): + """Determine if object requires a recursive representation.""" + return PrettyPrinter()._safe_repr(object, {}, None, 0)[2] + +class _safe_key: + """Helper function for key functions when sorting unorderable objects. + + The wrapped-object will fallback to a Py2.x style comparison for + unorderable types (sorting first comparing the type name and then by + the obj ids). Does not work recursively, so dict.items() must have + _safe_key applied to both the key and the value. + + """ + + __slots__ = ['obj'] + + def __init__(self, obj): + self.obj = obj + + def __lt__(self, other): + try: + return self.obj < other.obj + except TypeError: + return ((str(type(self.obj)), id(self.obj)) < \ + (str(type(other.obj)), id(other.obj))) + +def _safe_tuple(t): + "Helper function for comparing 2-tuples" + return _safe_key(t[0]), _safe_key(t[1]) + +class PrettyPrinter: + def __init__(self, indent=1, width=80, depth=None, stream=None, *, + compact=False, sort_dicts=True, underscore_numbers=False): + """Handle pretty printing operations onto a stream using a set of + configured parameters. + + indent + Number of spaces to indent for each level of nesting. + + width + Attempted maximum number of columns in the output. + + depth + The maximum depth to print out nested structures. + + stream + The desired output stream. If omitted (or false), the standard + output stream available at construction will be used. + + compact + If true, several items will be combined in one line. + + sort_dicts + If true, dict keys are sorted. + + underscore_numbers + If true, digit groups are separated with underscores. + + """ + indent = int(indent) + width = int(width) + if indent < 0: + raise ValueError('indent must be >= 0') + if depth is not None and depth <= 0: + raise ValueError('depth must be > 0') + if not width: + raise ValueError('width must be != 0') + self._depth = depth + self._indent_per_level = indent + self._width = width + if stream is not None: + self._stream = stream + else: + self._stream = _sys.stdout + self._compact = bool(compact) + self._sort_dicts = sort_dicts + self._underscore_numbers = underscore_numbers + + def pprint(self, object): + if self._stream is not None: + self._format(object, self._stream, 0, 0, {}, 0) + self._stream.write("\n") + + def pformat(self, object): + sio = _StringIO() + self._format(object, sio, 0, 0, {}, 0) + return sio.getvalue() + + def isrecursive(self, object): + return self.format(object, {}, 0, 0)[2] + + def isreadable(self, object): + s, readable, recursive = self.format(object, {}, 0, 0) + return readable and not recursive + + def _format(self, object, stream, indent, allowance, context, level): + objid = id(object) + if objid in context: + stream.write(_recursion(object)) + self._recursive = True + self._readable = False + return + rep = self._repr(object, context, level) + max_width = self._width - indent - allowance + if len(rep) > max_width: + p = self._dispatch.get(type(object).__repr__, None) + if p is not None: + context[objid] = 1 + p(self, object, stream, indent, allowance, context, level + 1) + del context[objid] + return + elif (_dataclasses.is_dataclass(object) and + not isinstance(object, type) and + object.__dataclass_params__.repr and + # Check dataclass has generated repr method. + hasattr(object.__repr__, "__wrapped__") and + "__create_fn__" in object.__repr__.__wrapped__.__qualname__): + context[objid] = 1 + self._pprint_dataclass(object, stream, indent, allowance, context, level + 1) + del context[objid] + return + stream.write(rep) + + def _pprint_dataclass(self, object, stream, indent, allowance, context, level): + cls_name = object.__class__.__name__ + indent += len(cls_name) + 1 + items = [(f.name, getattr(object, f.name)) for f in _dataclasses.fields(object) if f.repr] + stream.write(cls_name + '(') + self._format_namespace_items(items, stream, indent, allowance, context, level) + stream.write(')') + + _dispatch = {} + + def _pprint_dict(self, object, stream, indent, allowance, context, level): + write = stream.write + write('{') + if self._indent_per_level > 1: + write((self._indent_per_level - 1) * ' ') + length = len(object) + if length: + if self._sort_dicts: + items = sorted(object.items(), key=_safe_tuple) + else: + items = object.items() + self._format_dict_items(items, stream, indent, allowance + 1, + context, level) + write('}') + + _dispatch[dict.__repr__] = _pprint_dict + + def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level): + if not len(object): + stream.write(repr(object)) + return + cls = object.__class__ + stream.write(cls.__name__ + '(') + self._format(list(object.items()), stream, + indent + len(cls.__name__) + 1, allowance + 1, + context, level) + stream.write(')') + + _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict + + def _pprint_list(self, object, stream, indent, allowance, context, level): + stream.write('[') + self._format_items(object, stream, indent, allowance + 1, + context, level) + stream.write(']') + + _dispatch[list.__repr__] = _pprint_list + + def _pprint_tuple(self, object, stream, indent, allowance, context, level): + stream.write('(') + endchar = ',)' if len(object) == 1 else ')' + self._format_items(object, stream, indent, allowance + len(endchar), + context, level) + stream.write(endchar) + + _dispatch[tuple.__repr__] = _pprint_tuple + + def _pprint_set(self, object, stream, indent, allowance, context, level): + if not len(object): + stream.write(repr(object)) + return + typ = object.__class__ + if typ is set: + stream.write('{') + endchar = '}' + else: + stream.write(typ.__name__ + '({') + endchar = '})' + indent += len(typ.__name__) + 1 + object = sorted(object, key=_safe_key) + self._format_items(object, stream, indent, allowance + len(endchar), + context, level) + stream.write(endchar) + + _dispatch[set.__repr__] = _pprint_set + _dispatch[frozenset.__repr__] = _pprint_set + + def _pprint_str(self, object, stream, indent, allowance, context, level): + write = stream.write + if not len(object): + write(repr(object)) + return + chunks = [] + lines = object.splitlines(True) + if level == 1: + indent += 1 + allowance += 1 + max_width1 = max_width = self._width - indent + for i, line in enumerate(lines): + rep = repr(line) + if i == len(lines) - 1: + max_width1 -= allowance + if len(rep) <= max_width1: + chunks.append(rep) + else: + # A list of alternating (non-space, space) strings + parts = re.findall(r'\S*\s*', line) + assert parts + assert not parts[-1] + parts.pop() # drop empty last part + max_width2 = max_width + current = '' + for j, part in enumerate(parts): + candidate = current + part + if j == len(parts) - 1 and i == len(lines) - 1: + max_width2 -= allowance + if len(repr(candidate)) > max_width2: + if current: + chunks.append(repr(current)) + current = part + else: + current = candidate + if current: + chunks.append(repr(current)) + if len(chunks) == 1: + write(rep) + return + if level == 1: + write('(') + for i, rep in enumerate(chunks): + if i > 0: + write('\n' + ' '*indent) + write(rep) + if level == 1: + write(')') + + _dispatch[str.__repr__] = _pprint_str + + def _pprint_bytes(self, object, stream, indent, allowance, context, level): + write = stream.write + if len(object) <= 4: + write(repr(object)) + return + parens = level == 1 + if parens: + indent += 1 + allowance += 1 + write('(') + delim = '' + for rep in _wrap_bytes_repr(object, self._width - indent, allowance): + write(delim) + write(rep) + if not delim: + delim = '\n' + ' '*indent + if parens: + write(')') + + _dispatch[bytes.__repr__] = _pprint_bytes + + def _pprint_bytearray(self, object, stream, indent, allowance, context, level): + write = stream.write + write('bytearray(') + self._pprint_bytes(bytes(object), stream, indent + 10, + allowance + 1, context, level + 1) + write(')') + + _dispatch[bytearray.__repr__] = _pprint_bytearray + + def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level): + stream.write('mappingproxy(') + self._format(object.copy(), stream, indent + 13, allowance + 1, + context, level) + stream.write(')') + + _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy + + def _pprint_simplenamespace(self, object, stream, indent, allowance, context, level): + if type(object) is _types.SimpleNamespace: + # The SimpleNamespace repr is "namespace" instead of the class + # name, so we do the same here. For subclasses; use the class name. + cls_name = 'namespace' + else: + cls_name = object.__class__.__name__ + indent += len(cls_name) + 1 + items = object.__dict__.items() + stream.write(cls_name + '(') + self._format_namespace_items(items, stream, indent, allowance, context, level) + stream.write(')') + + _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace + + def _format_dict_items(self, items, stream, indent, allowance, context, + level): + write = stream.write + indent += self._indent_per_level + delimnl = ',\n' + ' ' * indent + last_index = len(items) - 1 + for i, (key, ent) in enumerate(items): + last = i == last_index + rep = self._repr(key, context, level) + write(rep) + write(': ') + self._format(ent, stream, indent + len(rep) + 2, + allowance if last else 1, + context, level) + if not last: + write(delimnl) + + def _format_namespace_items(self, items, stream, indent, allowance, context, level): + write = stream.write + delimnl = ',\n' + ' ' * indent + last_index = len(items) - 1 + for i, (key, ent) in enumerate(items): + last = i == last_index + write(key) + write('=') + if id(ent) in context: + # Special-case representation of recursion to match standard + # recursive dataclass repr. + write("...") + else: + self._format(ent, stream, indent + len(key) + 1, + allowance if last else 1, + context, level) + if not last: + write(delimnl) + + def _format_items(self, items, stream, indent, allowance, context, level): + write = stream.write + indent += self._indent_per_level + if self._indent_per_level > 1: + write((self._indent_per_level - 1) * ' ') + delimnl = ',\n' + ' ' * indent + delim = '' + width = max_width = self._width - indent + 1 + it = iter(items) + try: + next_ent = next(it) + except StopIteration: + return + last = False + while not last: + ent = next_ent + try: + next_ent = next(it) + except StopIteration: + last = True + max_width -= allowance + width -= allowance + if self._compact: + rep = self._repr(ent, context, level) + w = len(rep) + 2 + if width < w: + width = max_width + if delim: + delim = delimnl + if width >= w: + width -= w + write(delim) + delim = ', ' + write(rep) + continue + write(delim) + delim = delimnl + self._format(ent, stream, indent, + allowance if last else 1, + context, level) + + def _repr(self, object, context, level): + repr, readable, recursive = self.format(object, context.copy(), + self._depth, level) + if not readable: + self._readable = False + if recursive: + self._recursive = True + return repr + + def format(self, object, context, maxlevels, level): + """Format object for a specific context, returning a string + and flags indicating whether the representation is 'readable' + and whether the object represents a recursive construct. + """ + return self._safe_repr(object, context, maxlevels, level) + + def _pprint_default_dict(self, object, stream, indent, allowance, context, level): + if not len(object): + stream.write(repr(object)) + return + rdf = self._repr(object.default_factory, context, level) + cls = object.__class__ + indent += len(cls.__name__) + 1 + stream.write('%s(%s,\n%s' % (cls.__name__, rdf, ' ' * indent)) + self._pprint_dict(object, stream, indent, allowance + 1, context, level) + stream.write(')') + + _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict + + def _pprint_counter(self, object, stream, indent, allowance, context, level): + if not len(object): + stream.write(repr(object)) + return + cls = object.__class__ + stream.write(cls.__name__ + '({') + if self._indent_per_level > 1: + stream.write((self._indent_per_level - 1) * ' ') + items = object.most_common() + self._format_dict_items(items, stream, + indent + len(cls.__name__) + 1, allowance + 2, + context, level) + stream.write('})') + + _dispatch[_collections.Counter.__repr__] = _pprint_counter + + def _pprint_chain_map(self, object, stream, indent, allowance, context, level): + if not len(object.maps): + stream.write(repr(object)) + return + cls = object.__class__ + stream.write(cls.__name__ + '(') + indent += len(cls.__name__) + 1 + for i, m in enumerate(object.maps): + if i == len(object.maps) - 1: + self._format(m, stream, indent, allowance + 1, context, level) + stream.write(')') + else: + self._format(m, stream, indent, 1, context, level) + stream.write(',\n' + ' ' * indent) + + _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map + + def _pprint_deque(self, object, stream, indent, allowance, context, level): + if not len(object): + stream.write(repr(object)) + return + cls = object.__class__ + stream.write(cls.__name__ + '(') + indent += len(cls.__name__) + 1 + stream.write('[') + if object.maxlen is None: + self._format_items(object, stream, indent, allowance + 2, + context, level) + stream.write('])') + else: + self._format_items(object, stream, indent, 2, + context, level) + rml = self._repr(object.maxlen, context, level) + stream.write('],\n%smaxlen=%s)' % (' ' * indent, rml)) + + _dispatch[_collections.deque.__repr__] = _pprint_deque + + def _pprint_user_dict(self, object, stream, indent, allowance, context, level): + self._format(object.data, stream, indent, allowance, context, level - 1) + + _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict + + def _pprint_user_list(self, object, stream, indent, allowance, context, level): + self._format(object.data, stream, indent, allowance, context, level - 1) + + _dispatch[_collections.UserList.__repr__] = _pprint_user_list + + def _pprint_user_string(self, object, stream, indent, allowance, context, level): + self._format(object.data, stream, indent, allowance, context, level - 1) + + _dispatch[_collections.UserString.__repr__] = _pprint_user_string + + def _safe_repr(self, object, context, maxlevels, level): + # Return triple (repr_string, isreadable, isrecursive). + typ = type(object) + if typ in _builtin_scalars: + return repr(object), True, False + + r = getattr(typ, "__repr__", None) + + if issubclass(typ, int) and r is int.__repr__: + if self._underscore_numbers: + return f"{object:_d}", True, False + else: + return repr(object), True, False + + if issubclass(typ, dict) and r is dict.__repr__: + if not object: + return "{}", True, False + objid = id(object) + if maxlevels and level >= maxlevels: + return "{...}", False, objid in context + if objid in context: + return _recursion(object), False, True + context[objid] = 1 + readable = True + recursive = False + components = [] + append = components.append + level += 1 + if self._sort_dicts: + items = sorted(object.items(), key=_safe_tuple) + else: + items = object.items() + for k, v in items: + krepr, kreadable, krecur = self.format( + k, context, maxlevels, level) + vrepr, vreadable, vrecur = self.format( + v, context, maxlevels, level) + append("%s: %s" % (krepr, vrepr)) + readable = readable and kreadable and vreadable + if krecur or vrecur: + recursive = True + del context[objid] + return "{%s}" % ", ".join(components), readable, recursive + + if (issubclass(typ, list) and r is list.__repr__) or \ + (issubclass(typ, tuple) and r is tuple.__repr__): + if issubclass(typ, list): + if not object: + return "[]", True, False + format = "[%s]" + elif len(object) == 1: + format = "(%s,)" + else: + if not object: + return "()", True, False + format = "(%s)" + objid = id(object) + if maxlevels and level >= maxlevels: + return format % "...", False, objid in context + if objid in context: + return _recursion(object), False, True + context[objid] = 1 + readable = True + recursive = False + components = [] + append = components.append + level += 1 + for o in object: + orepr, oreadable, orecur = self.format( + o, context, maxlevels, level) + append(orepr) + if not oreadable: + readable = False + if orecur: + recursive = True + del context[objid] + return format % ", ".join(components), readable, recursive + + rep = repr(object) + return rep, (rep and not rep.startswith('<')), False + +_builtin_scalars = frozenset({str, bytes, bytearray, float, complex, + bool, type(None)}) + +def _recursion(object): + return ("" + % (type(object).__name__, id(object))) + + +def _perfcheck(object=None): + import time + if object is None: + object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000 + p = PrettyPrinter() + t1 = time.perf_counter() + p._safe_repr(object, {}, None, 0, True) + t2 = time.perf_counter() + p.pformat(object) + t3 = time.perf_counter() + print("_safe_repr:", t2 - t1) + print("pformat:", t3 - t2) + +def _wrap_bytes_repr(object, width, allowance): + current = b'' + last = len(object) // 4 * 4 + for i in range(0, len(object), 4): + part = object[i: i+4] + candidate = current + part + if i == last: + width -= allowance + if len(repr(candidate)) > width: + if current: + yield repr(current) + current = part + else: + current = candidate + if current: + yield repr(current) + +if __name__ == "__main__": + _perfcheck() diff --git a/shared/package-files/3a/3a5442ad441789b68b6502f0ad32dfb47874115e6fef7ae0fb93021819a25aa7/tril_indices_native.h b/shared/package-files/3a/3a5442ad441789b68b6502f0ad32dfb47874115e6fef7ae0fb93021819a25aa7/tril_indices_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9a46e9bb9856e20879034a78364f466718d45b8d --- /dev/null +++ b/shared/package-files/3a/3a5442ad441789b68b6502f0ad32dfb47874115e6fef7ae0fb93021819a25aa7/tril_indices_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & tril_indices_out(int64_t row, int64_t col, int64_t offset, at::Tensor & out); +TORCH_API at::Tensor tril_indices_cpu(int64_t row, int64_t col, int64_t offset=0, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor tril_indices_cuda(int64_t row, int64_t col, int64_t offset=0, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a567679a8b83d1da56c0848ad4f7e711d8e289b253b77f03a09a47675285265/traversaltools.cpython-311.pyc b/shared/package-files/3a/3a567679a8b83d1da56c0848ad4f7e711d8e289b253b77f03a09a47675285265/traversaltools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6900a0f94a122f23db29a9cdc499ebd0aab4f338 Binary files /dev/null and b/shared/package-files/3a/3a567679a8b83d1da56c0848ad4f7e711d8e289b253b77f03a09a47675285265/traversaltools.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a58ad0fdd4019dbab179f8fee1213ca0c9602b5f9bcbf622fde62665c241970/partitioner_utils.py b/shared/package-files/3a/3a58ad0fdd4019dbab179f8fee1213ca0c9602b5f9bcbf622fde62665c241970/partitioner_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3658dd1a9ce96aff26adbc5f47818e9e57e13d35 --- /dev/null +++ b/shared/package-files/3a/3a58ad0fdd4019dbab179f8fee1213ca0c9602b5f9bcbf622fde62665c241970/partitioner_utils.py @@ -0,0 +1,317 @@ +# mypy: allow-untyped-defs +from enum import Enum +from typing import NamedTuple + +from torch.fx.node import map_arg, Node + + +class Partition: + """Partition class contains all the information about an individual partition. + It also provides necessary methods for manipulation the partition. + """ + + def __init__(self, partition_id: int) -> None: + self.nodes: set[Node] = set() + self.partition_id = partition_id + self.parents: set[Partition] = set() + self.children: set[Partition] = set() + self.bfs_level: int = -1 + self.used_mem_bytes: int = 0 + self.logical_device_ids: list[int] = [] + + def __str__(self): + return str(self.partition_id) + + def recalculate_mem_size(self): + self.used_mem_bytes = 0 + for node in self.nodes: + self.used_mem_bytes += get_extra_size_of(node, self.nodes) + + def add_node(self, node): + input_nodes: dict[Node, None] = {} + map_arg(node.args, input_nodes.setdefault) + map_arg(node.kwargs, input_nodes.setdefault) + # Add current node's input nodes if they are placeholder or constants + for n in input_nodes: + if n.op in {"placeholder", "get_attr"}: + self.nodes.add(n) + self.nodes.add(node) + self.recalculate_mem_size() + + def remove_node(self, node): + # Remove a node only if the node is in the partition + if node in self.nodes: + self.nodes.remove(node) + # Collect the node's input nodes + input_nodes: dict[Node, None] = {} + map_arg(node.args, input_nodes.setdefault) + map_arg(node.kwargs, input_nodes.setdefault) + # Check if an input node is a placeholder or get_attr, + # and this input node is not used by some other nodes in this partition, + # the remove this input node + for input_node in input_nodes: + if all( + n not in self.nodes for n in input_node.users + ) and input_node.op in {"placeholder", "get_attr"}: + self.nodes.remove(input_node) + self.recalculate_mem_size() + + +class Device(NamedTuple): + name: str + available_mem_bytes: int + logical_id: int + + +class NodeLatency(NamedTuple): + # Latency due to the memory bandwidth + mem_latency_sec: float + # Latency due to the computation + computer_latency_sec: float + + +class PartitionLatency(NamedTuple): + # Sum of all nodes' memory latency on the critical path + mem_latency_sec: float + # Sum of all nodes' compute latency on the critical path + computer_latency_sec: float + # Latency of the critical path + overall_latency_sec: float + + +class PartitionMode(Enum): + size_based = 0 + sparse_nn = 1 + cost_aware = 2 + kl_based = 3 + aot_based = 4 + + +class PartitionerConfig(NamedTuple): + devices: list[Device] + mode: PartitionMode = PartitionMode.size_based + transfer_rate_bytes_per_sec: float = 0.0 + node_to_latency_mapping: dict[Node, NodeLatency] = {} + node_to_partition_mapping: dict[Node, int] = {} + partition_to_logical_device_mapping: dict[int, list[int]] = {} + # Saturate host by replicating partitions to the remaining idle devices. + saturate_host: bool = False + + +def get_extra_size_of(node: Node, nodes: set[Node]) -> int: + """Given a node and a set of nodes, + this function return the extra size that needed + if this node is included in this set. + """ + # Find all its input nodes + input_nodes: dict[Node, None] = {} + map_arg(node.args, input_nodes.setdefault) + map_arg(node.kwargs, input_nodes.setdefault) + # Calculate total size of related nodes + total_size_of_input_nodes = 0 + for n in input_nodes: + # Make sure this node hasn't been in this set yet + if n not in nodes: + size_bytes = getattr(n, "size_bytes", None) + if size_bytes: + total_size_of_input_nodes += size_bytes.output_size + else: + raise RuntimeError("node has no size_bytes attr") + # Don't forget the op node itself + size_bytes = getattr(node, "size_bytes", None) + if size_bytes: + total_size_of_input_nodes += size_bytes.total_size + else: + raise RuntimeError("node has no size_bytes attr") + return total_size_of_input_nodes + + +def get_latency_of_one_partition( + partition: Partition, node_to_latency_mapping: dict[Node, NodeLatency] +) -> PartitionLatency: + """Given a partition and its nodes' latency, return a PartitionLatency for this partition""" + + def get_top_nodes(partition: Partition) -> list[Node]: + """Given a partition, return a list of nodes on the top bfs level""" + top_nodes: list[Node] = [] + for node in partition.nodes: + # Skip placeholder and get_attr nodes + if node.op in {"placeholder", "get_attr"}: + continue + input_nodes: dict[Node, None] = {} + map_arg(node.args, input_nodes.setdefault) + map_arg(node.kwargs, input_nodes.setdefault) + # If a node has no input nodes in this partition, + # or its input nodes in this partition are placeholders and get_attrs + # this node is on the top bfs level in this partition + if not any( + n in partition.nodes and n.op not in {"placeholder", "get_attr"} + for n in input_nodes + ): + top_nodes.append(node) + return top_nodes + + def dfs_helper(node: Node, partition_latency) -> PartitionLatency: + """Given a top node of a partition, this function returns + the latency of the critical path in the partition + """ + node_latency = node_to_latency_mapping[node] + # Calculate the current overall latency of the partition + overall_latency_sec = partition_latency.overall_latency_sec + max( + node_latency.computer_latency_sec, node_latency.mem_latency_sec + ) + # Update the mem latency of this path + mem_latency_sec = ( + partition_latency.mem_latency_sec + node_latency.mem_latency_sec + ) + # Update the compute latency of this path + computer_latency_sec = ( + partition_latency.computer_latency_sec + node_latency.computer_latency_sec + ) + # Get all users of this node that are in this partition + users = set(node.users).intersection(partition.nodes) + if users: + max_latency = PartitionLatency( + mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0 + ) + for n in users: + # Get new partition latency recursively + new_partition_latency = dfs_helper( + n, + PartitionLatency( + mem_latency_sec, computer_latency_sec, overall_latency_sec + ), + ) + if ( + new_partition_latency.overall_latency_sec + > max_latency.overall_latency_sec + ): + max_latency = new_partition_latency + return max_latency + # If there is no user, the node is at bottom of the partition + return PartitionLatency( + mem_latency_sec, computer_latency_sec, overall_latency_sec + ) + + # Main part starts + # Get all top level nodes of this partition + top_nodes = get_top_nodes(partition) + critical_path_latency = PartitionLatency( + mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0 + ) + # Go through all top nodes and find the largest latency (critical pass latency) + for node in top_nodes: + partition_latency = dfs_helper( + node, + PartitionLatency( + mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0 + ), + ) + if ( + partition_latency.overall_latency_sec + > critical_path_latency.overall_latency_sec + ): + critical_path_latency = partition_latency + return critical_path_latency + + +def get_partition_to_latency_mapping( + partitions: list[Partition], node_to_latency_mapping: dict[Node, NodeLatency] +) -> dict[Partition, PartitionLatency]: + """Given all the partitions and node_to_latency_mapping dictionary, + return a mapping dictionary of each partition to its overall latency + """ + partition_to_latency_mapping: dict[Partition, PartitionLatency] = {} + # Go through each partition and get its latency + for partition in partitions: + partition_latency = get_latency_of_one_partition( + partition, node_to_latency_mapping + ) + partition_to_latency_mapping[partition] = partition_latency + return partition_to_latency_mapping + + +def get_comm_latency_between( + parent_partition: Partition, + child_partition: Partition, + transfer_rate_bytes_per_sec: float, +): + """Given two partitions (parent and child), + calculate the communication latency between the two. + """ + # If two partitions are on the same device, the comm latency is 0. + if ( + parent_partition.logical_device_ids != [] + and child_partition.logical_device_ids != [] + and parent_partition.logical_device_ids == child_partition.logical_device_ids + ): + return 0.0 + # Keep tracking the communication size between parent and child + comm_size = 0 + # Keep tracking all the counted node + visited_nodes = set() + # Go through all nodes in the child partition + # If a node has input nodes from the parent partition, + # the output size of those input nodes will be counted + # and added to comm_size + for node in child_partition.nodes: + input_nodes: dict[Node, None] = {} + map_arg(node.args, input_nodes.setdefault) + map_arg(node.kwargs, input_nodes.setdefault) + for n in input_nodes: + if n in parent_partition.nodes and n not in visited_nodes: + size_bytes = getattr(n, "size_bytes", None) + if size_bytes is not None: + comm_size += size_bytes.output_size + visited_nodes.add(n) + return comm_size / transfer_rate_bytes_per_sec + + +def get_latency_of_partitioned_graph( + partitions: list[Partition], + partition_to_latency_mapping: dict[Partition, PartitionLatency], + transfer_rate_bytes_per_sec: float, +): + """Given all partitions in a graph, find the critical path among all partitions + and return its latency as the latency of the whole graph + """ + + def dfs_helper(partition: Partition, latency_so_far_sec: float) -> float: + """This function helps to recursively get the latency of a path of partitions""" + # Update latency by adding current partition's latency + latency_so_far_sec += partition_to_latency_mapping[ + partition + ].overall_latency_sec + + if partition.children: + max_latency_sec = 0.0 + for child in partition.children: + # Calculate latency between + comm_latency_sec = get_comm_latency_between( + partition, child, transfer_rate_bytes_per_sec + ) + new_latency_sec = dfs_helper( + child, latency_so_far_sec + comm_latency_sec + ) + if new_latency_sec > max_latency_sec: + max_latency_sec = new_latency_sec + return max_latency_sec + return latency_so_far_sec + + def get_top_partitions(partitions: list[Partition]) -> list[Partition]: + """This function is to return all the partitions without parents + as the starting points of all the paths + """ + # If a partition has no parents, then it is a top partition + top_partitions = [ + partition for partition in partitions if len(partition.parents) == 0 + ] + return top_partitions + + top_partitions = get_top_partitions(partitions) + critical_path_latency_sec = 0.0 + for partition in top_partitions: + latency_sec = dfs_helper(partition, 0.0) + if latency_sec > critical_path_latency_sec: + critical_path_latency_sec = latency_sec + return critical_path_latency_sec diff --git a/shared/package-files/3a/3a603984acc63eac041fada5b71b943989220c21fe7c2fb406b1a707a20b0758/functional_sgd.py b/shared/package-files/3a/3a603984acc63eac041fada5b71b943989220c21fe7c2fb406b1a707a20b0758/functional_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a00cf02e976365373c7c7183b2056bd62cc304 --- /dev/null +++ b/shared/package-files/3a/3a603984acc63eac041fada5b71b943989220c21fe7c2fb406b1a707a20b0758/functional_sgd.py @@ -0,0 +1,166 @@ +# mypy: allow-untyped-defs +from typing import Optional + +import torch +import torch.optim._functional as F +from torch import Tensor +from torch.distributed.optim._deprecation_warning import ( + _scripted_functional_optimizer_deprecation_warning, +) + + +__all__: list[str] = [] + + +# Define a TorchScript compatible Functional SGD Optimizer +# where we use these optimizer in a functional way. +# Instead of using the `param.grad` when updating parameters, +# we explicitly allow the distributed optimizer pass gradients to +# the `step` function. In this way, we could separate the gradients +# and parameters and allow multithreaded trainer to update the +# parameters without data traces on accumulating to the same .grad. +# NOTE: This should be only used by distributed optimizer internals +# and not meant to expose to the user. +@torch.jit.script +class _FunctionalSGD: + def __init__( + self, + params: list[Tensor], + lr: float = 1e-2, + momentum: float = 0.0, + dampening: float = 0.0, + weight_decay: float = 0.0, + nesterov: bool = False, + maximize: bool = False, + foreach: bool = False, + fused: bool = False, + _allow_empty_param_list: bool = False, + ): + _scripted_functional_optimizer_deprecation_warning(stacklevel=2) + self.defaults = { + "lr": lr, + "momentum": momentum, + "dampening": dampening, + "weight_decay": weight_decay, + } + self.nesterov = nesterov + self.maximize = maximize + self.foreach = foreach + self.fused = fused + self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {}) + + if len(params) == 0 and not _allow_empty_param_list: + raise ValueError("optimizer got an empty parameter list") + + # NOTE: we only have one param_group and don't allow user to add additional + # param group as it's not a common use case. + self.param_group = {"params": params} + + def step_param(self, param: Tensor, grad: Optional[Tensor]): + """Similar to self.step, but operates on a single parameter and + its gradient. + """ + # TODO: Once step_param interface is robust, refactor step to call + # step param on each param. + weight_decay = self.defaults["weight_decay"] + momentum = self.defaults["momentum"] + dampening = self.defaults["dampening"] + lr = self.defaults["lr"] + params = [param] + momentum_buffer_list: list[Optional[Tensor]] = [] + grads = [] + + has_sparse_grad = False + if grad is not None: + grads.append(grad) + if grad.is_sparse: + has_sparse_grad = True + if param not in self.state: + self.state[param] = {} + state = self.state[param] + if "momentum_buffer" not in state: + momentum_buffer_list.append(None) + else: + momentum_buffer_list.append(state["momentum_buffer"]) + + with torch.no_grad(): + F.sgd( + params, + grads, + momentum_buffer_list, + weight_decay=weight_decay, + momentum=momentum, + lr=lr, + dampening=dampening, + nesterov=self.nesterov, + maximize=self.maximize, + has_sparse_grad=has_sparse_grad, + foreach=self.foreach, + fused=self.fused, + grad_scale=None, + found_inf=None, + ) + # update momentum_buffer in state + state = self.state[param] + momentum_buffer = momentum_buffer_list[0] + if momentum_buffer is not None: + state["momentum_buffer"] = momentum_buffer + + def step(self, gradients: list[Optional[Tensor]]): + params = self.param_group["params"] + params_with_grad = [] + grads = [] + momentum_buffer_list: list[Optional[Tensor]] = [] + lr = self.defaults["lr"] + weight_decay = self.defaults["weight_decay"] + momentum = self.defaults["momentum"] + dampening = self.defaults["dampening"] + + if len(params) != len(gradients): + raise ValueError( + "the gradients passed in does not equal to the size of the parameters!" + + f"Params length: {len(params)}. " + + f"Gradients length: {len(gradients)}" + ) + + has_sparse_grad = False + for param, gradient in zip(params, gradients): + if gradient is not None: + params_with_grad.append(param) + grads.append(gradient) + if gradient.is_sparse: + has_sparse_grad = True + + if param not in self.state: + self.state[param] = {} + + state = self.state[param] + if "momentum_buffer" not in state: + momentum_buffer_list.append(None) + else: + momentum_buffer_list.append(state["momentum_buffer"]) + + with torch.no_grad(): + F.sgd( + params_with_grad, + grads, + momentum_buffer_list, + weight_decay=weight_decay, + momentum=momentum, + lr=lr, + dampening=dampening, + nesterov=self.nesterov, + maximize=self.maximize, + has_sparse_grad=has_sparse_grad, + foreach=self.foreach, + fused=self.fused, + grad_scale=None, + found_inf=None, + ) + + # update momentum_buffers in state + for i, p in enumerate(params_with_grad): + state = self.state[p] + momentum_buffer = momentum_buffer_list[i] + if momentum_buffer is not None: + state["momentum_buffer"] = momentum_buffer diff --git a/shared/package-files/3a/3a62891ab085327c6143d1888ab08a5ed0f0366ac03600a7cd9caf590e47439f/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h b/shared/package-files/3a/3a62891ab085327c6143d1888ab08a5ed0f0366ac03600a7cd9caf590e47439f/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..74e4428242d52f45e00854a6b1d889e1a5e6b11d --- /dev/null +++ b/shared/package-files/3a/3a62891ab085327c6143d1888ab08a5ed0f0366ac03600a7cd9caf590e47439f/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _embedding_bag_sparse_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional & per_sample_weights, int64_t padding_idx=-1); +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 & per_sample_weights, int64_t padding_idx=-1); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3a/3a65d8dd112d4f865a8c78249b0ce40288e7bc1c175b64eee6febd906e4acd9f/test_msvc9compiler.py b/shared/package-files/3a/3a65d8dd112d4f865a8c78249b0ce40288e7bc1c175b64eee6febd906e4acd9f/test_msvc9compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..60b99e25f8a02ce7cf36dbb4d15e5bbf1be91722 --- /dev/null +++ b/shared/package-files/3a/3a65d8dd112d4f865a8c78249b0ce40288e7bc1c175b64eee6febd906e4acd9f/test_msvc9compiler.py @@ -0,0 +1,180 @@ +"""Tests for distutils.msvc9compiler.""" +import sys +import unittest +import os + +from distutils.errors import DistutilsPlatformError +from distutils.tests import support + +# A manifest with the only assembly reference being the msvcrt assembly, so +# should have the assembly completely stripped. Note that although the +# assembly has a reference the assembly is removed - that is +# currently a "feature", not a bug :) +_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ + + + + + + + + + + + + + + + + + +""" + +# A manifest with references to assemblies other than msvcrt. When processed, +# this assembly should be returned with just the msvcrt part removed. +_MANIFEST_WITH_MULTIPLE_REFERENCES = """\ + + + + + + + + + + + + + + + + + + + + + + +""" + +_CLEANED_MANIFEST = """\ + + + + + + + + + + + + + + + + + + +""" + +if sys.platform=="win32": + from distutils.msvccompiler import get_build_version + if get_build_version()>=8.0: + SKIP_MESSAGE = None + else: + SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" +else: + SKIP_MESSAGE = "These tests are only for win32" + +@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) +class msvc9compilerTestCase(support.TempdirManager, + unittest.TestCase): + + def test_no_compiler(self): + # makes sure query_vcvarsall raises + # a DistutilsPlatformError if the compiler + # is not found + from distutils.msvc9compiler import query_vcvarsall + def _find_vcvarsall(version): + return None + + from distutils import msvc9compiler + old_find_vcvarsall = msvc9compiler.find_vcvarsall + msvc9compiler.find_vcvarsall = _find_vcvarsall + try: + self.assertRaises(DistutilsPlatformError, query_vcvarsall, + 'wont find this version') + finally: + msvc9compiler.find_vcvarsall = old_find_vcvarsall + + def test_reg_class(self): + from distutils.msvc9compiler import Reg + self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') + + # looking for values that should exist on all + # windows registry versions. + path = r'Control Panel\Desktop' + v = Reg.get_value(path, 'dragfullwindows') + self.assertIn(v, ('0', '1', '2')) + + import winreg + HKCU = winreg.HKEY_CURRENT_USER + keys = Reg.read_keys(HKCU, 'xxxx') + self.assertEqual(keys, None) + + keys = Reg.read_keys(HKCU, r'Control Panel') + self.assertIn('Desktop', keys) + + def test_remove_visual_c_ref(self): + from distutils.msvc9compiler import MSVCCompiler + tempdir = self.mkdtemp() + manifest = os.path.join(tempdir, 'manifest') + f = open(manifest, 'w') + try: + f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) + finally: + f.close() + + compiler = MSVCCompiler() + compiler._remove_visual_c_ref(manifest) + + # see what we got + f = open(manifest) + try: + # removing trailing spaces + content = '\n'.join([line.rstrip() for line in f.readlines()]) + finally: + f.close() + + # makes sure the manifest was properly cleaned + self.assertEqual(content, _CLEANED_MANIFEST) + + def test_remove_entire_manifest(self): + from distutils.msvc9compiler import MSVCCompiler + tempdir = self.mkdtemp() + manifest = os.path.join(tempdir, 'manifest') + f = open(manifest, 'w') + try: + f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) + finally: + f.close() + + compiler = MSVCCompiler() + got = compiler._remove_visual_c_ref(manifest) + self.assertIsNone(got) + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/3a/3a69adec9c7d92d448ad6df253b98466896eca89eca94d274e63a9ef651781c7/source_range.h b/shared/package-files/3a/3a69adec9c7d92d448ad6df253b98466896eca89eca94d274e63a9ef651781c7/source_range.h new file mode 100644 index 0000000000000000000000000000000000000000..4e36f31f0e057702ef39f7f791330993f9ad16ea --- /dev/null +++ b/shared/package-files/3a/3a69adec9c7d92d448ad6df253b98466896eca89eca94d274e63a9ef651781c7/source_range.h @@ -0,0 +1,455 @@ +#pragma once +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class SourceRangeUnpickler; +struct SourceRange; + +// A stringlike class backed by a vector of string_view +// the string represented are logically the concatenation of the string_views +// This has advantage of not needing continues memory. +struct TORCH_API StringCordView { + StringCordView(); + StringCordView(const StringCordView&) = default; + StringCordView(StringCordView&&) noexcept = default; + StringCordView( + std::vector inputs, + std::vector> ownerships); + + StringCordView& operator=(const StringCordView&) = default; + StringCordView& operator=(StringCordView&&) noexcept = default; + + size_t size() const { + return accumulated_sizes_.back(); + } + + size_t find(const std::string& tok, size_t start) const; + size_t find_regex(const std::string& tok, size_t start) const; + StringCordView substr(size_t start, size_t size) const; + + char at(size_t index) const { + return *iter_for_pos(index); + } + char operator[](size_t index) const { + return at(index); + } + + std::string str() const { + std::stringstream ss; + for (auto s : pieces_) { + ss << std::string(s); + } + return ss.str(); + } + + bool operator==(const std::string& rhs) const; + + bool operator==(const StringCordView& rhs) const; + + std::string_view piece(size_t index) const { + return pieces_[index]; + } + + struct Iterator { + Iterator( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : line_(start_line), pos_(start_pos), str_(str), size_(size) {} + explicit Iterator(const StringCordView* str) + : Iterator(str, 0, 0, str->size()) {} + + Iterator() : Iterator(nullptr, 0, 0, 0) {} + + Iterator(const Iterator&) = default; + Iterator(Iterator&&) = default; + Iterator& operator=(const Iterator&) = default; + Iterator& operator=(Iterator&&) = default; + + Iterator operator++() { + if (size_ == 0) { + return *this; + } + if ((pos_ + 1) < str_->pieces_[line_].size()) { + pos_++; + } else { + line_++; + pos_ = 0; + } + return *this; + } + + Iterator operator++(int) { + Iterator prev(*this); + ++(*this); + return prev; + } + + Iterator next_iter() const { + Iterator next(*this); + ++next; + return next; + } + + Iterator& operator+=(size_t num) { + if (!has_next()) { + return *this; + } + size_t target_pos = pos_ + num; + if (target_pos >= str_->accumulated_sizes_[line_] && + (line_ + 1) < str_->accumulated_sizes_.size() && + target_pos < str_->accumulated_sizes_[line_ + 1]) { + pos_ = target_pos; + return *this; + } + + size_t target_abs_pos = pos() + num; + *this = str_->iter_for_pos(target_abs_pos); + return *this; + } + + bool operator==(const Iterator& rhs) const { + if (!has_next() && !rhs.has_next()) { + return true; + } + return (str_ == rhs.str_) && (line_ == rhs.line_) && (pos_ == rhs.pos_); + } + bool operator!=(const Iterator& rhs) { + return !((*this) == rhs); + } + bool has_next() const { + return size_ > 0 && (line_ < str_->pieces_.size()); + } + + char operator*() const { + TORCH_INTERNAL_ASSERT(line_ < str_->pieces_.size()); + TORCH_INTERNAL_ASSERT(pos_ < str_->pieces_[line_].size()); + return str_->pieces_[line_].at(pos_); + } + + // returns rest of the line of the current iterator + std::string_view rest_line() const { + if (line_ >= str_->pieces_.size()) { + return ""; + } + + std::string_view cur_line = str_->pieces_[line_]; + return cur_line.substr(pos_, std::string::npos); + } + + size_t pos() const { + if (size_ == 0) { + return 0; + } + return str_->accumulated_sizes_[line_] + pos_; + } + + private: + size_t line_; + size_t pos_; + const StringCordView* str_; + size_t size_; + friend struct StringCordView; + }; + + Iterator begin() const { + return Iterator(this, 0, 0, size()); + } + Iterator end() const { + return Iterator(this, pieces_.size(), 0, 0); + } + Iterator iter_for_pos(size_t pos) const; + + private: + std::vector pieces_; + std::vector accumulated_sizes_; + std::vector> owned_strings_; +}; + +// Source represents a code segment. It keeps track of: +// - text_view : the view into text of the code segment +// - filename (optional) : if present, represents the name of the file from +// which the code segment originated. +// - starting_line_no : represents the line in the original file where the +// code segment started. +struct TORCH_API Source { + // Whether or not Source should copy the string passed in the constructor. + enum CopiesString { COPIES_STRING, DONT_COPY }; + + explicit Source( + std::string_view text_view, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr, + CopiesString copies_str = COPIES_STRING) + : filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + if (copies_str == COPIES_STRING) { + std::shared_ptr allocated_str = + std::make_shared(text_view.data(), text_view.size()); + text_view_ = StringCordView({*allocated_str}, {allocated_str}); + } else { + text_view_ = StringCordView({text_view}, {}); + } + + calc_line_start_offsets(); + } + + explicit Source( + StringCordView str, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr) + : text_view_(std::move(str)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + calc_line_start_offsets(); + } + // Given a line number (within source_), return the byte offset of the + // beginning of that line. + size_t offset_for_line(size_t line) const { + return line_starting_offsets_.at(line); + } + + // Returns number of lines present. + size_t num_lines() const { + return line_starting_offsets_.size(); + } + + // Calculate the line (within the code segment) on which `offset` resides. + size_t lineno_for_offset(size_t offset) const { + auto iter = std::upper_bound( + line_starting_offsets_.begin(), line_starting_offsets_.end(), offset); + return iter - line_starting_offsets_.begin() - 1; + } + + // Calculate the line (within the original source file, if present) on which + // `lineno` resides. + size_t lineno_to_source_lineno(size_t lineno) const { + if (filename_) { + return lineno + starting_line_no_; + } else { + return lineno; + } + } + + StringCordView get_line(size_t lineno) const { + auto start = offset_for_line(lineno); + auto size = (lineno + 1) < num_lines() ? offset_for_line(lineno + 1) - start + : text_view_.size() - start; + return text_view_.substr(start, size); + } + + const StringCordView& text_str() const { + return text_view_; + } + + char char_at(size_t index) const { + return text_view_.at(index); + } + + size_t size() const { + return text_view_.size(); + } + + std::optional& filename() { + return filename_; + } + + size_t starting_line_no() const { + return starting_line_no_; + } + + std::optional findSourceRangeThatGenerated( + const SourceRange& range); + + ~Source() = default; + + private: + void calc_line_start_offsets() { + line_starting_offsets_.clear(); + line_starting_offsets_.push_back(0); + size_t pos = 0; + while ((pos = text_view_.find("\n", pos)) != std::string::npos) { + line_starting_offsets_.push_back(++pos); + } + } + + StringCordView text_view_; + + std::optional filename_; + // If filename_ is not present, starting_line_no_ is don't care + size_t starting_line_no_; + // Starting offsets for lines into the source. e.g. line 0 starts at + // line_starting_offsets_[0], etc. + std::vector line_starting_offsets_; + + std::shared_ptr gen_ranges_; +}; + +// A SourceRange is a reference to subset of a Source, specified by `start` and +// `end` byte offsets into the source text. +struct TORCH_API SourceRange { + SourceRange(std::shared_ptr source_view, size_t start_, size_t end_) + : source_view_(std::move(source_view)), start_(start_), end_(end_) { + if (source_view_) { + start_iter_ = source_view_->text_str().iter_for_pos(start_); + } + } + + SourceRange() : source_view_(nullptr), start_(0), end_(0) {} + + SourceRange( + std::shared_ptr source_view_, + StringCordView::Iterator start_iter, + size_t end_) + : source_view_(std::move(source_view_)), + start_(start_iter.pos()), + end_(end_), + start_iter_(start_iter) {} + + const std::string_view token_text() const { + size_t size = end() - start(); + return start_iter_.rest_line().substr(0, size); + } + + const StringCordView text() const { + return source_view_->text_str().substr(start(), end() - start()); + } + size_t size() const { + return end() - start(); + } + static const size_t CONTEXT = 3; + void highlight(std::ostream& out) const; + + // Customizable version of 'highlight' method. + void print_with_context( + std::ostream& out, + size_t context, + bool highlight, + const std::string& funcname) const; + + const std::shared_ptr& source() const { + return source_view_; + } + size_t start() const { + return start_; + } + size_t end() const { + return end_; + } + std::string str() const { + std::stringstream ss; + highlight(ss); + return ss.str(); + } + + std::optional> file_line_col() const { + if (!source_view_ || !source()->filename()) { + return std::nullopt; + } + + auto lineno = source_view_->lineno_for_offset(start_); + auto col_offset = (int)start_ - (int)source_view_->offset_for_line(lineno); + // TODO: std::optional<>::value returns an rvalue ref so can't use it here?? + return std::make_tuple( + source_view_->filename().value_or(""), + source_view_->lineno_to_source_lineno(lineno), + (size_t)col_offset); + } + + bool operator==(const SourceRange& rhs) const { + return start() == rhs.start() && end() == rhs.end() && + source() == rhs.source(); + } + + bool operator!=(const SourceRange& rhs) const { + return !(*this == rhs); + } + + std::optional findSourceRangeThatGenerated() const { + if (!source_view_) { + return std::nullopt; + } + return source_view_->findSourceRangeThatGenerated(*this); + } + + protected: + std::shared_ptr source_view_; + + private: + size_t start_; + size_t end_; + StringCordView::Iterator start_iter_; +}; + +// OwnedSourceRange is just like a SourceRange except that it owns a `Source` +// instead of `Source`. Thus OwnedSourceRange owns a copy of source text. +struct OwnedSourceRange : public SourceRange { + explicit OwnedSourceRange(const SourceRange& source_range) + : SourceRange(source_range) { + const auto& source = source_range.source(); + if (source) { + source_view_ = std::make_shared( + source->text_str().str(), + source->filename(), + source->starting_line_no()); + } + } +}; + +struct TORCH_API SourceRangeHasher { + public: + size_t operator()(const torch::jit::SourceRange& key) const; +}; + +struct StackEntry { + std::string filename; + SourceRange range; +}; + +TORCH_API void format_stack_trace( + std::ostream& out, + const std::vector& entries); + +inline std::ostream& operator<<(std::ostream& out, const SourceRange& range) { + range.highlight(out); + return out; +} + +// A pair of (byte offset, SourceRange) describing a specific segment +// of the output stream +struct TaggedRange { + TaggedRange(size_t bytes, SourceRange range) + : bytes(bytes), range(std::move(range)) {} + size_t bytes; + SourceRange range; +}; +using SourceRangeRecords = std::vector; +using SourceRangeTagMap = + std::unordered_map; + +} // namespace torch::jit + +namespace std { +template <> +struct iterator_traits { + using value_type = char; + using difference_type = ptrdiff_t; + using pointer = char*; + using reference = char&; + using iterator_category = std::forward_iterator_tag; +}; +} // namespace std diff --git a/shared/package-files/3a/3a6a5ccb7e05ff432d0f8fb6cc7a1c290d2e6c6c7ebb61e3b646c62898d51f99/mem_tracker.py b/shared/package-files/3a/3a6a5ccb7e05ff432d0f8fb6cc7a1c290d2e6c6c7ebb61e3b646c62898d51f99/mem_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..38a25eb2a29453e532d617a752b19d72cdc649ac --- /dev/null +++ b/shared/package-files/3a/3a6a5ccb7e05ff432d0f8fb6cc7a1c290d2e6c6c7ebb61e3b646c62898d51f99/mem_tracker.py @@ -0,0 +1,949 @@ +import math +import os +import re +import warnings +from contextlib import nullcontext +from copy import deepcopy +from enum import auto, Enum +from functools import partial, wraps +from typing import Any, Callable, Optional, TYPE_CHECKING, Union +from typing_extensions import Self + +import torch +import torch.distributed._tools.fake_collectives +from torch import nn, optim +from torch._guards import active_fake_mode +from torch.distributed._tools.common_utils import get_untyped_storages +from torch.distributed._tools.mod_tracker import ModTracker +from torch.distributed.tensor import DTensor +from torch.optim.optimizer import ( + register_optimizer_step_post_hook, + register_optimizer_step_pre_hook, +) +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils._pytree import tree_flatten, tree_map_only +from torch.utils.weak import WeakIdKeyDictionary, weakref + + +if TYPE_CHECKING: + from torch.utils.hooks import RemovableHandle + +# This value is hard-coded here: +# https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117 +_PYTORCH_MIN_ALLOCATE = ( + 2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1 +) +_TOTAL_KEY = "Total" + +__all__ = ["MemTracker"] + + +class _RefType(str, Enum): + """Base Class for defining memory reference types, categorizing tensors based on their usage within a model.""" + + +class _State(str, Enum): + """Base Class for defining module state to capture snapshots .""" + + +class _MemRefType(_RefType): + """ + An enum to define memory reference types, categorizing tensors based on their usage within a model. + + - PARAM: Tensors registered as nn.Parameter within modules. + - BUFFER: Tensors registered as nn.Buffer within modules. + - GRAD: Gradients associated with parameters. + - ACT: Tensors produced during the forward pass and recomputation in activation checkpointing. + - TMP: Temporary memory used during the backward pass, including gradients of activations. + - OPT: Tensors holding optimizer states. + - OTH: Tensors registered via `track_external` that do not fit the above categories. + """ + + PARAM = "Parameter" + BUFFER = "Buffer" + GRAD = "Gradient" + ACT = "Activation" + TEMP = "Temp" + OPT = "Optstate" + OTH = "Other" + + +class _ModState(_State): + """ + An enum to define the state of a module. + + - PRE_FW: The module is about to run the forward pass. + - POST_FW: The module has finished running the forward pass. + - PEAK_FW: The module has reached the peak memory usage during the forward pass. + - PRE_BW: The module is about to run the backward pass. + - PRE_FW_AC: The module is about to run the forward pass with activation checkpointing. + - POST_FW_AC: The module has finished running the forward pass with activation checkpointing. + - POST_BW: The module has finished running the backward pass. + - PEAK_BW: The module has reached the peak memory usage during the backward pass. + """ + + PRE_FW = "Pre-Forward" + POST_FW = "Post-Forward" + PEAK_FW = "Peak-Forward" + PRE_BW = "Pre-Backward" + PRE_FW_AC = "Pre-Forward-AC" + POST_FW_AC = "Post-Forward-AC" + POST_BW = "Post-Backward" + PEAK_BW = "Peak-Backward" + + +class _ModMemStats: + """ + A class to store the memory statistics of a module. + + Args: + mod_fqn (str): The fully qualified name of the module. + Attributes: + mod_fqn (str): The fully qualified name of the module. + parameter_mem (int): The memory usage of the parameters of the module. + buffer_mem (int): The memory usage of the buffers of the module. + input_mem (int): The memory usage of the inputs to the module. + output_mem (int): The memory usage of the outputs from the module. + snapshots (Dict[_ModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots + of the module at different states defined by ``_ModState``. + Note: + The memory snapshot is stored as a dictionary - Dict[torch.device, Dict[str, int]], where each key is a device, + and each value is another dictionary with keys as memory reference types defined by `_MemRefType` and + values as the memory consumed in bytes. + """ + + def __init__(self, mod_fqn: str): + self.mod_fqn = mod_fqn + self.parameter_mem: int + self.buffer_mem: int + self.input_mem: int + self.output_mem: int + self.local_peak: dict[torch.device, int] = {} + self.snapshots: dict[_ModState, list[dict[torch.device, dict[str, int]]]] = {} + + +class _WeakRefInfo: + """ + Manages memory statistics and device attributes for tensor storages. + """ + + def __init__( + self, size: int, element_size: int, device: torch.device, reftype: _RefType + ) -> None: + """ + Initializes the ``_WeakRefInfo`` object with tensor storage properties. + + Args: + size (int): The number of elements in the tensor storage. + element_size (int): The size of each element in the tensor storage. + device (torch.device): The device on which the tensor is allocated. + reftype (_RefType): The reference type of the tensor. + """ + self.size = size + self.element_size = element_size + self.reftype = reftype + self.device = device + self.mem_consumed = self._calculate_mem_consumed() + + def _calculate_mem_consumed(self) -> int: + """ + Calculates the memory consumed by the tensor storage, considering device-specific allocation rules. + + Returns: + int: The memory consumed in bytes. + """ + mem = self.size * self.element_size + if self.device.type == "cuda": + return math.ceil((mem) / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE + return mem + + def update_mem_consumed(self, st: torch.UntypedStorage) -> int: + """ + Updates and returns the memory consumed if the storage size has changed. + + Args: + st (torch.UntypedStorage): The tensor storage to check for size updates. + + Returns: + int: The updated memory consumed in bytes. + """ + if st.size() != self.size: + self.size = st.size() + self.mem_consumed = self._calculate_mem_consumed() + return self.mem_consumed + + @classmethod + def create_winfo( + cls, + st: torch.UntypedStorage, + device: torch.device, + reftype: _RefType, + callback: Optional[Callable[[Self, weakref.ref], Any]] = None, + ) -> tuple[Self, weakref.ref]: + """ + Creates a new ``_WeakRefInfo`` instance and a weak reference to a ``torch.UntypedStorage`` object, + optionally attaching a callback to the weak reference. + + Args: + st (torch.UntypedStorage): The storage object for which to create the weak reference info. + device (torch.device): The device associated with the storage object. + reftype (_RefType): The type of reference, used to categorize the storage. + callback (Optional[Callable[[Self, weakref.ref]]]): A callback function that is called when + the storage object is about to be finalized (garbage collected). The callback function + should accept two arguments: the ``_WeakRefInfo`` instance and the weak reference to the storage. + Returns: + Tuple[Self, weakref.ref]: A tuple containing the newly created ``_WeakRefInfo`` instance and the + weak reference to the storage object. The weak reference may have an attached callback if provided. + """ + + winfo = cls(st.size(), st.element_size(), device, reftype) + w_st = weakref.ref(st, partial(callback, winfo) if callback else None) + return winfo, w_st + + +def _get_mem_divisor(units: str) -> int: + unit_dict = {"B": 1, "KiB": 2**10, "MiB": 2**20, "GiB": 2**30} + if units in unit_dict: + return unit_dict[units] + else: + raise ValueError( + f"Unsupported unit: {units}. Supported units are: {', '.join(unit_dict.keys())}" + ) + + +def _rounding_fn(value: int, divisor: int, precision: int) -> Union[float, int]: + return value if divisor == 1 else round(value / divisor, precision) + + +def _print_snapshot(snapshot: dict[torch.device, dict[str, int]], units: str) -> None: + if len(snapshot) == 0: + print("No memory tracked.") + return + divisor = _get_mem_divisor(units) + for dev, dev_snap in snapshot.items(): + if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0: + continue + print( + f"Device: {dev}", + *( + f"\t{k.value}: {_rounding_fn(v, divisor, 2)} {units}" + if isinstance(k, _RefType) + else f"\t{k}: {_rounding_fn(v, divisor, 2)} {units}" + for k, v in dev_snap.items() + ), + sep="\n", + ) + + +def _print_snapshot_tabular( + snapshot: dict[torch.device, dict[str, int]], units: str +) -> None: + if len(snapshot) == 0: + print("No memory tracked.") + return + try: + from tabulate import tabulate + except ImportError as err: + raise ImportError( + "Please install tabulate to use the tabulate option." + ) from err + divisor = _get_mem_divisor(units) + table_data = [] + key_list = list(next(iter(snapshot.values())).keys()) + headers = ["Device"] + [ + f"{key.value}" if isinstance(key, _RefType) else f"{key}" for key in key_list + ] + + for dev, dev_snap in snapshot.items(): + if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0: + continue + row = [str(dev)] + row.extend(f"{_rounding_fn(v, divisor, 2)} {units}" for v in dev_snap.values()) + table_data.append(row) + print(tabulate(table_data, headers=headers, tablefmt="rst")) + + +def _print_state_snapshots( + snapshots: dict[_State, list[dict[torch.device, dict[str, int]]]], units: str +) -> None: + for state, snapshot_list in snapshots.items(): + print(f"{state.value}") + for i, snapshot in enumerate(snapshot_list): + print(f"# {i + 1}:") + _print_snapshot(snapshot, units) + print() + + +def _print_state_snapshots_tabular( + snapshots: dict[_State, list[dict[torch.device, dict[str, int]]]], units: str +) -> None: + try: + from tabulate import tabulate + except ImportError as err: + raise ImportError( + "Please install tabulate to use the tabulate option." + ) from err + + table_data = [] + last_state_call = None + divisor = _get_mem_divisor(units) + for state, snapshot_list in snapshots.items(): + for i, snapshot in enumerate(snapshot_list): + state_call = f"{state.value} # {i + 1}" + for dev, dev_snap in snapshot.items(): + if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0: + continue + row = { + "State & Call": ( + state_call if state_call != last_state_call else "" + ), + "Device": str(dev), + } + last_state_call = state_call + for k, v in dev_snap.items(): + row[f"{k.value}" if isinstance(k, _RefType) else f"{k}"] = ( + f"{_rounding_fn(v, divisor, 2)} {units}" + ) + table_data.append(row) + print(tabulate(table_data, headers="keys", tablefmt="rst")) + + +class _UpdateType(Enum): + # These are used for tracking updates to the continuouly maintained memory snapshot. + # ADD - When a new tensor storage is tracked + # DEL - When a tensor storage is about to be finalized (garbage collected). + # REF - When a tensor reference is updated, for instance, the gradients are marked as + # generic backward reference types until the grad_hook categorizes them as gradients. + # SIZE - When a tensor's storage is resized. + ADD = auto() + DEL = auto() + REF = auto() + SIZE = auto() + + +class MemTracker(TorchDispatchMode): + """ + A TorchDispatchMode to track, categorize and attribute the tensor memory created or accessed within its context. + + It categorizes the tracked tensors as parameters, buffers, activations, gradients, temporary memory and optimizer states + as defined by ``_MemRefType`` within its context. It captures memory `snapshots` for the modules, called within its context, + at various states defined by ``_ModState``. + + Attributes: + memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key + is a reference to a module, and each value is a ``_ModMemStats`` object that stores the memory + statistics of the module. + + Note: + The MemTracker should be used as a context manager. The modules, optimizers, and any other tensors created within + the context of MemTracker will be tracked by default. Any tensors or stateful objects such as modules, optimizers etc. + that need to be tracked but are created outside the MemTracker should be registered using the `track_external` method. + The `track_external` method should be called before the MemTracker is used. Any tensors created outside the ``MemTracker`` + and not supplied to the `track_external` method will not be tracked by the ``MemTracker``. + + Example usage: + + .. code-block:: python + + module = ... + optimizer = ... + inp = ... + mem_tracker = MemTracker() + mem_tracker.track_external(module, optimizer, inp) + with mem_tracker as mt: + loss = module(inp) + print("After Forward:") + mt.display_snapshot("current") + loss.backward() + optimizer.step() + optimizer.zero_grad() + mt.display_snapshot("peak") + mt.display_modulewise_snapshots(depth=3, units="MiB") + + Known Limitations: + - The ``MemTracker`` does not track memory for tensors that bypass the ``TorchDispatchMode`` ex. under ``no_dispatch``. + - Resizing tensor storages directly by using non-Tensor methods other than using ``torch.Untyped_Storage.resize_`` + is not tracked. File a Github issue if you have use-cases for this. + - If the tensors are not traceable or wrappable subclasses of ``torch.Tensor``, then the tracker does not know how to + track their storages. File a Github issue if you have use-cases for this. + - During AC in the backward pass there might be misattribution between activation and temp memory, but the peak memory + will be tracked accurately. This will be fixed in the next update by hooking intricately with ``torch.uitls.checkpoint``. + """ + + def __init__(self) -> None: + self.memory_tracking = WeakIdKeyDictionary() + self._curr_mem_snap: dict[torch.device, dict[str, int]] = {} + self._peak_mem: dict[torch.device, int] = {} + self._peak_mem_snap: dict[torch.device, dict[str, int]] = {} + self._param_to_grad_hook_handles = WeakIdKeyDictionary() + self._optimizer_hook_handles: Optional[ + tuple[RemovableHandle, RemovableHandle] + ] = None + # Dictionary to store the ``_WeakRefInfo`` instances corresponding to each tensor's storage. + self._WINFO = WeakIdKeyDictionary() + self._mod_tracker = ModTracker() + # This is a general memory tracker which can be used with any ``_RefType`` subclass + self._ref_class: type[_RefType] = _MemRefType + # Flags to track if we are in the AC region or optimizer step region + self._in_opt: bool = False + self._in_ac: bool = False + # Weak references to the topmost AC module currently active + self._ac_mod: Optional[weakref.ref] = None + self._orig_resize = torch.UntypedStorage.resize_ + self._orig_dtensor_dispatch = DTensor._op_dispatcher.dispatch + self._depth = 0 + + def _update_snap( + self, + u_type: _UpdateType, + winfo: _WeakRefInfo, + old_mem_consumed: Optional[int] = None, + old_reftype: Optional[_RefType] = None, + ) -> None: + # Initialize a flag to track if the total memory might drop to zero after updates. + maybe_zero = False + # Ensure the device entry exists in the current memory snapshot, initializing if necessary. + dev_snap = self._curr_mem_snap.setdefault( + winfo.device, dict.fromkeys(self._ref_class, 0) + ) + dev_snap.setdefault(_TOTAL_KEY, 0) + # Handle different types of updates based on the update type (`u_type`). + if u_type == _UpdateType.ADD: + # Increase the memory consumed for the specific reference type and update the total. + dev_snap[winfo.reftype] += winfo.mem_consumed + dev_snap[_TOTAL_KEY] += winfo.mem_consumed + elif u_type == _UpdateType.DEL: + # Decrease the memory consumed for the specific reference type and reduce the total. + dev_snap[winfo.reftype] -= winfo.mem_consumed + dev_snap[_TOTAL_KEY] -= winfo.mem_consumed + maybe_zero = True + elif u_type == _UpdateType.REF: + assert old_reftype is not None + # Adjust memory consumption between two reference types within the same device. + dev_snap[old_reftype] -= winfo.mem_consumed + dev_snap[winfo.reftype] += winfo.mem_consumed + elif u_type == _UpdateType.SIZE: + assert old_mem_consumed is not None + # Adjust the memory consumed for a reference type due to a change in size. + change = winfo.mem_consumed - old_mem_consumed + dev_snap[winfo.reftype] += change + dev_snap[_TOTAL_KEY] += change + maybe_zero = True + else: + raise ValueError(f"Invalid update type: {u_type}") + # Check if the total memory for the device has dropped to zero. + if maybe_zero: + if self._curr_mem_snap[winfo.device][_TOTAL_KEY] == 0: + # Remove the device entry from the memory snapshot if the total memory is zero. + del self._curr_mem_snap[winfo.device] + + def _update_and_maybe_create_winfos( + self, + t: torch.Tensor, + reftype: _RefType, + update_existing: bool = False, + ) -> set[_WeakRefInfo]: + sts = get_untyped_storages(t) + winfos = set() + for st in sts: + # Attempt to retrieve existing ``_WeakRefInfo`` and its weak reference from the tracking dictionary. + winfo, _ = self._WINFO.get(st, (None, None)) + if winfo is not None: + # If ``_WeakRefInfo`` exists, check if the reference type needs to be updated. + old_reftype = winfo.reftype + if old_reftype != reftype: + # Update the reference type and apply changes via ``_update_snap``. + winfo.reftype = reftype + self._update_snap(_UpdateType.REF, winfo, old_reftype=old_reftype) + winfos.add(winfo) + elif update_existing: + # If no existing ``_WeakRefInfo`` is found and update_existing is True, raise an error. + raise KeyError("No existing winfo found") + else: + # If no existing _WeakRefInfo is found and update_existing is False, create a new ``_WeakRefInfo``. + winfo, w_st = _WeakRefInfo.create_winfo( + st, t.device, reftype, self._delete_callback + ) + # Store the new ``_WeakRefInfo`` and its weak reference in the tracking dictionary. + self._WINFO[st] = (winfo, w_st) + # Update the snapshot for the newly added ``_WeakRefInfo``. + if winfo.mem_consumed > 0: + self._update_snap(_UpdateType.ADD, winfo) + winfos.add(winfo) + return winfos + + def _delete_callback(self, winfo: _WeakRefInfo, w_st: weakref.ref) -> None: + # Callback to be called when the storage object corresponding to the ``_WeakRefInfo`` + # instance is about to be finalized. + if winfo.mem_consumed > 0: + self._update_snap(_UpdateType.DEL, winfo) + + def _track_resize(self) -> None: + # Need to monkey-patch this because ``torch.UntypedStorage.resize_`` is not captured + # by ``TorchDispatchMode``. + @wraps(self._orig_resize) + def resize_(st: torch.UntypedStorage, size: int) -> None: + self._orig_resize(st, size) + winfo, _ = self._WINFO.get(st, (None, None)) + if winfo is not None and winfo.size != st.size(): + old_mem_consumed = winfo.mem_consumed + winfo.update_mem_consumed(st) + self._update_snap( + _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed + ) + + torch.UntypedStorage.resize_ = resize_ # type: ignore[method-assign, assignment] + + def _restore_resize(self) -> None: + torch.UntypedStorage.resize_ = self._orig_resize # type: ignore[method-assign] + + def _update_peak_stats(self, peak_state: _State) -> None: + # We first capture the current memory snapshot of the current tracker state then, + # We step through each of the modules we have tracked so far in ``memory_tracking`` + # and check if it is currently active by querying ``_mod_tracker.parents`` + # If it is active, we update the per device peak memory usage for the module + # corresponding to the ``_State`` which can be ``PEAK_FW`` or ``PEAK_BW``. + curr_snap = self._curr_mem_snap + + for mod_stats in self.memory_tracking.values(): + if mod_stats.mod_fqn in self._mod_tracker.parents: + if peak_state in mod_stats.snapshots: + for dev, dev_snap in curr_snap.items(): + if mod_stats.local_peak.get(dev, 0) < dev_snap[_TOTAL_KEY]: + mod_stats.local_peak[dev] = dev_snap[_TOTAL_KEY] + mod_stats.snapshots[peak_state][-1][dev] = deepcopy( + dev_snap + ) + + for dev, dev_snap in curr_snap.items(): + if self._peak_mem.get(dev, 0) < dev_snap[_TOTAL_KEY]: + self._peak_mem[dev] = dev_snap[_TOTAL_KEY] + self._peak_mem_snap[dev] = deepcopy(dev_snap) + + def _track(self, reftype: _RefType, t: torch.Tensor) -> None: + # Get the storages of the tensor and check if we have already tracked them. + # If yes, then check if the storage size has changed and update the current snapshot. + # Else create a new ``_WeakRefInfo`` instance and add it to the dictionary. + sts = get_untyped_storages(t) + for st in sts: + winfo, _ = self._WINFO.get(st, (None, None)) + if winfo is not None: + if winfo.size != st.size(): + old_mem_consumed = winfo.mem_consumed + winfo.update_mem_consumed(st) + self._update_snap( + _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed + ) + return + else: + winfo, w_st = _WeakRefInfo.create_winfo( + st, t.device, reftype, self._delete_callback + ) + self._WINFO[st] = (winfo, w_st) + # Update the current snapshot for the newly added ``_WeakRefInfo``. + if winfo.mem_consumed > 0: + self._update_snap(_UpdateType.ADD, winfo) + + def get_tracker_snapshot( + self, type: str = "current" + ) -> dict[torch.device, dict[str, int]]: + """ + Capture a snapshot of the memory usage breakdown per device, based on the specified type. + + Args: + type (str): The type of snapshot to capture. Can be "current" for the current memory usage or "peak" for the + peak memory usage. Defaults to "current". + Returns: + Dict[torch.device, Dict[str, int]]: A dictionary where each key is a torch.device, and each value is another + dictionary. This inner dictionary has keys representing memory reference + types as defined in ``_MemRefType`` and values representing the amount of + memory consumed in bytes. + Raises: + ValueError: If an invalid type is specified. + """ + if type == "current": + return deepcopy(self._curr_mem_snap) + elif type == "peak": + return deepcopy(self._peak_mem_snap) + else: + raise ValueError(f"Invalid type {type}") + + def _track_module_params_and_buffers( + self, module: nn.Module, install_grad_hooks: bool = True + ) -> tuple[int, int]: + # Track the parameters and buffers of the module if not already tracked. + # If the parameters have gradients, track the gradients as well. + # If install_grad_hooks is True, install a gradient hook on the parameters + # to track the gradients, if it has not already been installed. + # Return the total memory consumed by the parameters and buffers. + def _grad_hook(grad: torch.Tensor) -> None: + self._update_and_maybe_create_winfos( + grad, + _MemRefType.GRAD, + ) + + param_memory = 0 + for param in module.parameters(): + winfos = self._update_and_maybe_create_winfos( + param, + _MemRefType.PARAM, + ) + param_memory += sum(winfo.mem_consumed for winfo in winfos) + if param.grad is not None: + self._update_and_maybe_create_winfos( + param.grad, + _MemRefType.GRAD, + ) + if ( + self._param_to_grad_hook_handles.get(param, None) is None + and install_grad_hooks + ): + grad_hook_handle = param.register_hook(_grad_hook) + post_acc_grad_hook_handle = param.register_post_accumulate_grad_hook( + lambda p: (_grad_hook(p.grad)) + ) + self._param_to_grad_hook_handles[param] = ( + grad_hook_handle, + post_acc_grad_hook_handle, + ) + buffer_memory = 0 + for buffer in module.buffers(): + winfos = self._update_and_maybe_create_winfos( + buffer, + _MemRefType.BUFFER, + ) + buffer_memory += sum(winfo.mem_consumed for winfo in winfos) + return (param_memory, buffer_memory) + + def _track_inputs_or_outputs(self, args: Any) -> int: + # Calculate the memory consumed by the inputs or outputs of the module. + input_or_output_memory = 0 + + def add_inps_or_outs(t: torch.Tensor) -> None: + nonlocal input_or_output_memory + sts = get_untyped_storages(t) + for st in sts: + winfo, _ = self._WINFO.get(st, (None, None)) + if winfo is not None: + input_or_output_memory += winfo.mem_consumed + + tree_map_only(torch.Tensor, add_inps_or_outs, args) + return input_or_output_memory + + def _pre_fw_hook(self, module: nn.Module, inputs: Any) -> None: + # This is installed as a pre-fwd user hook with ``ModTracker.`` Based on the following cases we + # set the state and capture the memory snapshot for the module. + # Case 1: If the module is not in the ``memory_tracking`` dictionary, we track the parameters, buffers, + # input and output memory of the module. Create a new ``_ModMemStats`` instance for the module + # and add it to the ``memory_tracking`` dictionary. + # Case 2: If the module is already in the ``memory_tracking`` dictionary and we are in backward, this means + # we are in the AC region. We check if this is the top most module in the AC region. If it is, + # we store a weak reference and set the flag ``_in_ac`` to True. + # Case 3: If the module is already in the ``memory_tracking`` dictionary and we are in forward, this means + # this module is called for the second time. If it is a root module, that means we are in the next + # iteration and we error out. If it is not a root module, that means it's a submodule that is being + # used multiple times in the same iteration, which we allow and track. + # For Case 1 and 3, we also initialiaze the ``local_peak`` and ``PEAK_FW`` snapshot for the module. + mod_name = self._mod_tracker.get_known_fqn(module) + assert mod_name is not None + if module not in self.memory_tracking: + mod_stats = _ModMemStats(mod_name) + param_mem, buffer_mem = self._track_module_params_and_buffers( + module, install_grad_hooks=True + ) + input_mem = self._track_inputs_or_outputs(inputs) + mod_stats.parameter_mem = param_mem + mod_stats.buffer_mem = buffer_mem + mod_stats.input_mem = input_mem + self.memory_tracking[module] = mod_stats + state = _ModState.PRE_FW + + elif self._mod_tracker.is_bw: + mod_stats = self.memory_tracking[module] + state = _ModState.PRE_FW_AC + if self._ac_mod is None: + self._ac_mod = weakref.ref(module) + self._in_ac = True + else: + parents = set(self._mod_tracker.parents) - {mod_name} + if len(parents) == 1 and "Global" in parents: + raise NotImplementedError( + "MemTracker does not support memory tracking for multiple iterative calls." + " Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration" + " or file a github issue if you need this feature." + ) + mod_stats = self.memory_tracking[module] + state = _ModState.PRE_FW + input_mem = self._track_inputs_or_outputs(inputs) + mod_stats.mod_fqn = mod_name + mod_stats.input_mem = input_mem + + mem_snapshot = self.get_tracker_snapshot() + if state == _ModState.PRE_FW: + mod_stats.local_peak = { + dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items() + } + mod_stats.snapshots.setdefault(_ModState.PEAK_FW, []).append(mem_snapshot) + mod_stats.snapshots.setdefault(state, []).append(deepcopy(mem_snapshot)) + + def _post_fw_hook(self, module: nn.Module, inputs: Any, outputs: Any) -> None: + # This is installed as a post-fwd user hook with ``ModTracker``. Based on the following cases we + # set the state and capture the memory snapshot for the module. + # Case 1: This is called in backward, which means we are in the AC region. If this is the top most module + # in the AC region, we set the flag ``_in_ac`` to False. + # Case 2: This is called in forward so we calculate the output memory + # of the module and update its mod_stats. + mod_stats = self.memory_tracking[module] + if self._mod_tracker.is_bw: + state = _ModState.POST_FW_AC + if self._ac_mod is not None and self._ac_mod() is module: + self._ac_mod = None + self._in_ac = False + else: + state = _ModState.POST_FW + output_mem = self._track_inputs_or_outputs(outputs) + mod_stats.output_mem = output_mem + mod_stats.snapshots.setdefault(state, []).append(self.get_tracker_snapshot()) + + def _pre_bw_hook(self, module: nn.Module, args: Any) -> None: + # This is installed as a pre-bwd user hook with ``ModTracker``. We set the state and capture the + # snapshot for the module. We also initialize the ``local_peak`` and ``PEAK_BW`` snapshot for it. + # If the module is None, we skip the hook. + # This can happen since this installed inside a multi-grad hook on the module's output tensors + # and the module itself may not be alive during backward. + if module is None: + warnings.warn("Module is None. Skipping PRE_BW hook.", stacklevel=2) + return + mod_stats = self.memory_tracking[module] + mem_snapshot = self.get_tracker_snapshot() + mod_stats.local_peak = { + dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items() + } + mod_stats.snapshots.setdefault(_ModState.PEAK_BW, []).append(mem_snapshot) + mod_stats.snapshots.setdefault(_ModState.PRE_BW, []).append( + deepcopy(mem_snapshot) + ) + + def _post_bw_hook(self, module: nn.Module, args: Any) -> None: + # This is installed as a post-bwd user hook with ``ModTracker``. We set the state and capture the + # snapshot for the module if it is not None. + # This can happen since this installed inside a multi-grad hook on the module's input tensors + # and the module itself may not be alive during backward. + if module is None: + warnings.warn("Module is None. Skipping POST_BW hook.", stacklevel=2) + return + mod_stats = self.memory_tracking[module] + mod_stats.snapshots.setdefault(_ModState.POST_BW, []).append( + self.get_tracker_snapshot() + ) + + def _track_optimizer_states( + self, reftype: _RefType, optimizer: optim.Optimizer + ) -> None: + for states in optimizer.state.values(): + for val in states.values(): + if isinstance(val, torch.Tensor): + self._update_and_maybe_create_winfos( + val, + reftype, + ) + + def _register_global_optimizer_hook(self) -> None: + # Register a hook on the optimizer step to track the optimizer states. + # The pre-hook is to set the flag ``_in_opt`` to True. The post-hook unsets the flag, + # and also tracks any optimizer states that are created during the optimizer step. + def _opt_step_pre_hook( + optimizer: optim.Optimizer, args: Any, kwargs: Any + ) -> None: + self._in_opt = True + + def _opt_step_post_hook( + optimizer: optim.Optimizer, args: Any, kwargs: Any + ) -> None: + self._track_optimizer_states(_MemRefType.OPT, optimizer) + self._in_opt = False + + self._optimizer_hook_handles = ( + register_optimizer_step_pre_hook(_opt_step_pre_hook), + register_optimizer_step_post_hook(_opt_step_post_hook), + ) + + def _deregister_param_and_optimizer_hooks(self) -> None: + for ( + grad_hook_handle, + post_acc_grad_hook_handle, + ) in self._param_to_grad_hook_handles.values(): + grad_hook_handle.remove() + post_acc_grad_hook_handle.remove() + self._param_to_grad_hook_handles.clear() + + if self._optimizer_hook_handles is not None: + for handle in self._optimizer_hook_handles: + handle.remove() + self._optimizer_hook_handles = None + + def track_external( + self, *external: Union[nn.Module, optim.Optimizer, torch.Tensor] + ) -> None: + """ + Track tensors and stateful objects like modules, optimizers etc. that are created outside the MemTracker. + + This method should be called before the ``MemTracker`` is used. Any tensors that are not module parameters, buffers, + gradients activations, or optimizer states will be categorized as ``Other``. If you want them categorized with a + custom name, please file a GitHub issue. Any tensors created outside the MemTracker and not supplied to this + method will not be be tracked by ``MemTracker``. + + Args: + *external (Union[nn.Module, optim.Optimizer, torch.Tensor]): The external modules, optimizers, and + tensors to be tracked. + """ + flat_external, _ = tree_flatten(external) + for obj in flat_external: + if isinstance(obj, torch.Tensor): + self._update_and_maybe_create_winfos( + obj, + _MemRefType.OTH, + ) + elif isinstance(obj, torch.nn.Module): + self._track_module_params_and_buffers(obj, install_grad_hooks=False) + elif isinstance(obj, optim.Optimizer): + self._track_optimizer_states(_MemRefType.OPT, obj) + elif obj is None: + continue + else: + raise TypeError( + f"Object of type {type(obj)} is not supported for tracking. " + f"Only stateful objects like modules, optimizers, and tensors are supported." + ) + + def display_snapshot( + self, type: str = "current", units: str = "B", tabulate: bool = False + ) -> None: + """ + Display the memory usage breakdown snapshot of the tracker based on the specified type and units. + + Keyword args: + type (str): The type of snapshot to display. Can be "current" for the current memory usage or "peak" for the + peak memory usage. Defaults to "current". + units (str): The units to use for displaying memory usage. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"]. + tabulate (bool): Whether to display the snapshot in a tabular format. Defaults to False. + """ + snapshot = self.get_tracker_snapshot(type) + if tabulate: + _print_snapshot_tabular(snapshot, units) + else: + _print_snapshot(snapshot, units) + + def display_modulewise_snapshots( + self, depth: int = 2, units: str = "B", tabulate: bool = False + ) -> None: + """ + Print per device memory breakdown snapshot for each module called within MemTracker. + + Snapshots are displayed for the states defined by ``_ModState``. + The module hierarchy is displayed up to the specified depth. + + Keyword Args: + depth (int, optional): The depth of the module hierarchy to display. Defaults to 2. + units (str, optional): The units to use for memory tracking. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"]. + tabulate (bool, optional): Whether to display the snapshot in a tabular format. Defaults to False. + """ + + def natural_sort_key(s: str) -> list[Union[int, str]]: + return [ + int(text) if text.isdigit() else text.lower() + for text in re.split("([0-9]+)", s) + ] + + for mod_stats in sorted( + self.memory_tracking.values(), + key=lambda m_stats: natural_sort_key(m_stats.mod_fqn), + ): + mod_fqn = mod_stats.mod_fqn + mod_depth = mod_fqn.count(".") + 1 + if mod_depth > depth: + continue + print(f"Module: {mod_fqn}") + if tabulate: + _print_state_snapshots_tabular(mod_stats.snapshots, units) + else: + _print_state_snapshots(mod_stats.snapshots, units) + + def reset_mod_stats(self) -> None: + """ + Reset all the module memory stats. Clears ``memory_tracking`` dictionary. + """ + self.memory_tracking.clear() + + def _track_dtensor_dispatch(self) -> None: + def track_dtensor_dispatch( + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], + ) -> object: + with ( + self + if op_call in DTensor._op_dispatcher._custom_op_handlers + else nullcontext() + ): + return self._orig_dtensor_dispatch(op_call, args, kwargs) + + DTensor._op_dispatcher.dispatch = track_dtensor_dispatch # type: ignore[method-assign, assignment] + + def _restore_dtensor_dispatch(self) -> None: + DTensor._op_dispatcher.dispatch = self._orig_dtensor_dispatch # type: ignore[method-assign] + + def __enter__(self) -> "MemTracker": + if self._depth == 0: + self._register_global_optimizer_hook() + self._mod_tracker.register_user_hooks( + self._pre_fw_hook, + self._post_fw_hook, + self._pre_bw_hook, + self._post_bw_hook, + ) + self._track_resize() + self._track_dtensor_dispatch() + self._peak_mem_snap = self.get_tracker_snapshot() + self._peak_mem = { + dev: dev_snap[_TOTAL_KEY] + for dev, dev_snap in self._peak_mem_snap.items() + } + self._mod_tracker.__enter__() + super().__enter__() + self._depth += 1 + return self + + def __exit__(self, *args: Any) -> None: + self._depth -= 1 + if self._depth == 0: + self._deregister_param_and_optimizer_hooks() + self._mod_tracker.clear_user_hooks() + self._restore_resize() + self._restore_dtensor_dispatch() + self._mod_tracker.__exit__(*args) + super().__exit__(*args) + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): # type: ignore[no-untyped-def] + if ( + func == torch.ops._c10d_functional.wait_tensor.default + and active_fake_mode() + ): + # N.B: This is a hacky way to override the Meta IMPL of wait_tensor. The original impl returns + # a new tensor which does not happen in eager mode, when a wait_tensor is called. + res = args[0] + else: + res = func(*args, **kwargs or {}) + # If we are tracking an optimizer state, we use the optimizer reference type. + # If we are in backward region and not in AC region, we use the backward reference type. + # Else we use the forward reference type. + if self._in_opt: + reftype = _MemRefType.OPT + elif self._mod_tracker.is_bw and not self._in_ac: + reftype = _MemRefType.TEMP + else: + reftype = _MemRefType.ACT + tree_map_only(torch.Tensor, partial(self._track, reftype), res) + peak_state = _ModState.PEAK_BW if self._mod_tracker.is_bw else _ModState.PEAK_FW + self._update_peak_stats(peak_state) + return res diff --git a/shared/package-files/3a/3a6e2a7dce7c6facfec0868c109ca050e917c5cd572894f7501272228a1512cf/contiguous_compositeimplicitautograd_dispatch.h b/shared/package-files/3a/3a6e2a7dce7c6facfec0868c109ca050e917c5cd572894f7501272228a1512cf/contiguous_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..989ed99b6b77f66f3befc830db24d0c38e2cdc27 --- /dev/null +++ b/shared/package-files/3a/3a6e2a7dce7c6facfec0868c109ca050e917c5cd572894f7501272228a1512cf/contiguous_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor contiguous(const at::Tensor & self, at::MemoryFormat memory_format=c10::MemoryFormat::Contiguous); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3a/3a76498b537874cd23543abbeafc9d51529b8ba6aec59fb8e3fa6b6b466689f8/api.cpython-311.pyc b/shared/package-files/3a/3a76498b537874cd23543abbeafc9d51529b8ba6aec59fb8e3fa6b6b466689f8/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..383199084676ef912e8aae819dfb5c2df7cdb487 Binary files /dev/null and b/shared/package-files/3a/3a76498b537874cd23543abbeafc9d51529b8ba6aec59fb8e3fa6b6b466689f8/api.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a7878c37f1e94f0a3b65714dc963d93787bd0d8ecc5722401f966427f99d056/__init__.py b/shared/package-files/3a/3a7878c37f1e94f0a3b65714dc963d93787bd0d8ecc5722401f966427f99d056/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6781cad094b29db0959df4fb0c29c0fa9d480c0c --- /dev/null +++ b/shared/package-files/3a/3a7878c37f1e94f0a3b65714dc963d93787bd0d8ecc5722401f966427f99d056/__init__.py @@ -0,0 +1,48 @@ +import os +from typing import Any + +from ._checkers import TypeCheckerCallable as TypeCheckerCallable +from ._checkers import TypeCheckLookupCallback as TypeCheckLookupCallback +from ._checkers import check_type_internal as check_type_internal +from ._checkers import checker_lookup_functions as checker_lookup_functions +from ._checkers import load_plugins as load_plugins +from ._config import CollectionCheckStrategy as CollectionCheckStrategy +from ._config import ForwardRefPolicy as ForwardRefPolicy +from ._config import TypeCheckConfiguration as TypeCheckConfiguration +from ._decorators import typechecked as typechecked +from ._decorators import typeguard_ignore as typeguard_ignore +from ._exceptions import InstrumentationWarning as InstrumentationWarning +from ._exceptions import TypeCheckError as TypeCheckError +from ._exceptions import TypeCheckWarning as TypeCheckWarning +from ._exceptions import TypeHintWarning as TypeHintWarning +from ._functions import TypeCheckFailCallback as TypeCheckFailCallback +from ._functions import check_type as check_type +from ._functions import warn_on_error as warn_on_error +from ._importhook import ImportHookManager as ImportHookManager +from ._importhook import TypeguardFinder as TypeguardFinder +from ._importhook import install_import_hook as install_import_hook +from ._memo import TypeCheckMemo as TypeCheckMemo +from ._suppression import suppress_type_checks as suppress_type_checks +from ._utils import Unset as Unset + +# Re-export imports so they look like they live directly in this package +for value in list(locals().values()): + if getattr(value, "__module__", "").startswith(f"{__name__}."): + value.__module__ = __name__ + + +config: TypeCheckConfiguration + + +def __getattr__(name: str) -> Any: + if name == "config": + from ._config import global_config + + return global_config + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +# Automatically load checker lookup functions unless explicitly disabled +if "TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD" not in os.environ: + load_plugins() diff --git a/shared/package-files/3a/3a7bf637893cdb142bcfe665c59faaa41dcf6375b866a896d712c320c2725d42/euc_jis_2004.cpython-311.pyc b/shared/package-files/3a/3a7bf637893cdb142bcfe665c59faaa41dcf6375b866a896d712c320c2725d42/euc_jis_2004.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e133c8bb3c6f43d05bca0ebdcead7f9eaaf5a2ec Binary files /dev/null and b/shared/package-files/3a/3a7bf637893cdb142bcfe665c59faaa41dcf6375b866a896d712c320c2725d42/euc_jis_2004.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a7cf31e851fc5e8fdbfcfd52ba7a23f17e07ba47c2a96cb70836887ceb8c915/_constant_symnode.cpython-311.pyc b/shared/package-files/3a/3a7cf31e851fc5e8fdbfcfd52ba7a23f17e07ba47c2a96cb70836887ceb8c915/_constant_symnode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edcc0837dec13876d46cf9c0e55fc2c8d81f6080 Binary files /dev/null and b/shared/package-files/3a/3a7cf31e851fc5e8fdbfcfd52ba7a23f17e07ba47c2a96cb70836887ceb8c915/_constant_symnode.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a7e0aefcb66ab8b72aff405b37528d3579f765563e51eb27e7e8256cee4b271/test_inertia.py b/shared/package-files/3a/3a7e0aefcb66ab8b72aff405b37528d3579f765563e51eb27e7e8256cee4b271/test_inertia.py new file mode 100644 index 0000000000000000000000000000000000000000..8d29e5f31868e539c4b50575af5180e5eb96f2cd --- /dev/null +++ b/shared/package-files/3a/3a7e0aefcb66ab8b72aff405b37528d3579f765563e51eb27e7e8256cee4b271/test_inertia.py @@ -0,0 +1,71 @@ +from sympy import symbols +from sympy.testing.pytest import raises +from sympy.physics.mechanics import (inertia, inertia_of_point_mass, + Inertia, ReferenceFrame, Point) + + +def test_inertia_dyadic(): + N = ReferenceFrame('N') + ixx, iyy, izz = symbols('ixx iyy izz') + ixy, iyz, izx = symbols('ixy iyz izx') + assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy * + (N.y | N.y) + izz * (N.z | N.z)) + assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x) + raises(TypeError, lambda: inertia(0, 0, 0, 0)) + assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) + + ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy * + (N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z | + N.y) + izz * (N.z | N.z)) + + +def test_inertia_of_point_mass(): + r, s, t, m = symbols('r s t m') + N = ReferenceFrame('N') + + px = r * N.x + I = inertia_of_point_mass(m, px, N) + assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z) + + py = s * N.y + I = inertia_of_point_mass(m, py, N) + assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z) + + pz = t * N.z + I = inertia_of_point_mass(m, pz, N) + assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y) + + p = px + py + pz + I = inertia_of_point_mass(m, p, N) + assert I == (m * (s**2 + t**2) * (N.x | N.x) - + m * r * s * (N.x | N.y) - + m * r * t * (N.x | N.z) - + m * r * s * (N.y | N.x) + + m * (r**2 + t**2) * (N.y | N.y) - + m * s * t * (N.y | N.z) - + m * r * t * (N.z | N.x) - + m * s * t * (N.z | N.y) + + m * (r**2 + s**2) * (N.z | N.z)) + + +def test_inertia_object(): + N = ReferenceFrame('N') + O = Point('O') + ixx, iyy, izz = symbols('ixx iyy izz') + I_dyadic = ixx * (N.x | N.x) + iyy * (N.y | N.y) + izz * (N.z | N.z) + I = Inertia(inertia(N, ixx, iyy, izz), O) + assert isinstance(I, tuple) + assert I.__repr__() == ('Inertia(dyadic=ixx*(N.x|N.x) + iyy*(N.y|N.y) + ' + 'izz*(N.z|N.z), point=O)') + assert I.dyadic == I_dyadic + assert I.point == O + assert I[0] == I_dyadic + assert I[1] == O + assert I == (I_dyadic, O) # Test tuple equal + raises(TypeError, lambda: I != (O, I_dyadic)) # Incorrect tuple order + assert I == Inertia(O, I_dyadic) # Parse changed argument order + assert I == Inertia.from_inertia_scalars(O, N, ixx, iyy, izz) + # Test invalid tuple operations + raises(TypeError, lambda: I + (1, 2)) + raises(TypeError, lambda: (1, 2) + I) + raises(TypeError, lambda: I * 2) + raises(TypeError, lambda: 2 * I) diff --git a/shared/package-files/3a/3a808852c3f9c920fa03be380aeb97e0b9b170ff9b8c8081a453e829e6217c87/package_importer.cpython-311.pyc b/shared/package-files/3a/3a808852c3f9c920fa03be380aeb97e0b9b170ff9b8c8081a453e829e6217c87/package_importer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..254e9e38b5eb6b3dd2df4a089710699517718765 Binary files /dev/null and b/shared/package-files/3a/3a808852c3f9c920fa03be380aeb97e0b9b170ff9b8c8081a453e829e6217c87/package_importer.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a84bea28841625d0ee6b12962b303ca52923072f2ad165c74554ac69549aa55/mish_backward_native.h b/shared/package-files/3a/3a84bea28841625d0ee6b12962b303ca52923072f2ad165c74554ac69549aa55/mish_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..97f1f1af2a0ade645f594a3953930c70d247bcf1 --- /dev/null +++ b/shared/package-files/3a/3a84bea28841625d0ee6b12962b303ca52923072f2ad165c74554ac69549aa55/mish_backward_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor math_mish_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API at::Tensor mish_backward(const at::Tensor & grad_output, const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3a90a1a9ed26cee0292a5181a778d1e0c04134e8d5a842a7edb1466f170c52b1/retain_grad.h b/shared/package-files/3a/3a90a1a9ed26cee0292a5181a778d1e0c04134e8d5a842a7edb1466f170c52b1/retain_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..8b637691470655ef63d1a204b1cf8c711b3d830d --- /dev/null +++ b/shared/package-files/3a/3a90a1a9ed26cee0292a5181a778d1e0c04134e8d5a842a7edb1466f170c52b1/retain_grad.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/shared/package-files/3a/3a91eafcfbf98945826f7404ea5747f96588557fe5cf62defb3b1e0a56f7da83/sparse_compressed_tensor.h b/shared/package-files/3a/3a91eafcfbf98945826f7404ea5747f96588557fe5cf62defb3b1e0a56f7da83/sparse_compressed_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..f794d9de607936735e9dc50e3ff11b0f485f6f9a --- /dev/null +++ b/shared/package-files/3a/3a91eafcfbf98945826f7404ea5747f96588557fe5cf62defb3b1e0a56f7da83/sparse_compressed_tensor.h @@ -0,0 +1,79 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template >> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} +namespace symint { + template >> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template >> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); +} +namespace symint { + template >> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, dtype, layout, device, pin_memory); +} + +} diff --git a/shared/package-files/3a/3a94936a389231c68e09faf8d8c3135960c117da978402ab03a2593b9e0dd0ad/_conv_depthwise2d.h b/shared/package-files/3a/3a94936a389231c68e09faf8d8c3135960c117da978402ab03a2593b9e0dd0ad/_conv_depthwise2d.h new file mode 100644 index 0000000000000000000000000000000000000000..7fc7912d370e90973562aaf77e69e48036fd819c --- /dev/null +++ b/shared/package-files/3a/3a94936a389231c68e09faf8d8c3135960c117da978402ab03a2593b9e0dd0ad/_conv_depthwise2d.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _conv_depthwise2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template >> + at::Tensor & _conv_depthwise2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::_conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _conv_depthwise2d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template >> + at::Tensor & _conv_depthwise2d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::_conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _conv_depthwise2d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, kernel_size, bias, stride, padding, dilation, out); +} +namespace symint { + template >> + at::Tensor & _conv_depthwise2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, kernel_size, bias, stride, padding, dilation, out); + } +} + +// aten::_conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _conv_depthwise2d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, kernel_size, bias, stride, padding, dilation, out); +} +namespace symint { + template >> + at::Tensor & _conv_depthwise2d_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::_conv_depthwise2d_out::call(self, weight, kernel_size, bias, stride, padding, dilation, out); + } +} + +// aten::_conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor +inline at::Tensor _conv_depthwise2d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation) { + return at::_ops::_conv_depthwise2d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation)); +} +namespace symint { + template >> + at::Tensor _conv_depthwise2d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation) { + return at::_ops::_conv_depthwise2d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation)); + } +} + +// aten::_conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor +inline at::Tensor _conv_depthwise2d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation) { + return at::_ops::_conv_depthwise2d::call(self, weight, kernel_size, bias, stride, padding, dilation); +} +namespace symint { + template >> + at::Tensor _conv_depthwise2d(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation) { + return at::_ops::_conv_depthwise2d::call(self, weight, kernel_size, bias, stride, padding, dilation); + } +} + +} diff --git a/shared/package-files/3a/3a9c70428b17f4fbf9ddcb19e195ca8453a4c9afed5cc6ed9dd0cc4844c9295f/batchnorm.py b/shared/package-files/3a/3a9c70428b17f4fbf9ddcb19e195ca8453a4c9afed5cc6ed9dd0cc4844c9295f/batchnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..8489cdb596ef44ce15d79530c80a9c7ea512e975 --- /dev/null +++ b/shared/package-files/3a/3a9c70428b17f4fbf9ddcb19e195ca8453a4c9afed5cc6ed9dd0cc4844c9295f/batchnorm.py @@ -0,0 +1,11 @@ +# flake8: noqa: F401 +r"""Quantized Modules. + +This file is in the process of migration to `torch/ao/nn/quantized`, and +is kept here for compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +appropriate file under the `torch/ao/nn/quantized/modules`, +while adding an import statement here. +""" + +from torch.ao.nn.quantized.modules.batchnorm import BatchNorm2d, BatchNorm3d diff --git a/shared/package-files/3a/3a9e840b9ad5af45d1c540715c72258006067719c500f1d34b486b3a40ae951c/__init__.cpython-311.pyc b/shared/package-files/3a/3a9e840b9ad5af45d1c540715c72258006067719c500f1d34b486b3a40ae951c/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21495f0c0f53707f6823494cb0709657b1b3fee8 Binary files /dev/null and b/shared/package-files/3a/3a9e840b9ad5af45d1c540715c72258006067719c500f1d34b486b3a40ae951c/__init__.cpython-311.pyc differ diff --git a/shared/package-files/3a/3a9f9157bffc52717f75bc4efa167c5feec3067147b0ff6cd7570cd099093966/RegisterBackendSelect.cpp b/shared/package-files/3a/3a9f9157bffc52717f75bc4efa167c5feec3067147b0ff6cd7570cd099093966/RegisterBackendSelect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..018cf358f11237d5bdc9bca01aa8d09d1462f574 --- /dev/null +++ b/shared/package-files/3a/3a9f9157bffc52717f75bc4efa167c5feec3067147b0ff6cd7570cd099093966/RegisterBackendSelect.cpp @@ -0,0 +1,29 @@ +// We register ops with a higher priority dispatch key (BackendSelect) than the usual backend-specific keys (e.g. CPU) +// which makes calls to the factory functions dispatch to here. +// We then 'manually' compute a lower-priority to re-dispatch to (e.g. CPU) to get to the eventually correct backend. +// ${generated_comment} + +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else + +${ops_headers} +#endif + +namespace at { + +namespace { + +${backend_select_method_definitions} + +TORCH_LIBRARY_IMPL(aten, BackendSelect, m) { + ${backend_select_function_registrations}; +} + +} // namespace +} // at diff --git a/shared/package-files/3a/3aa396bb64704b29ef730039d9809115884f26a1cfd28c8f7525c9b936ddf0a0/traverse.cpython-311.pyc b/shared/package-files/3a/3aa396bb64704b29ef730039d9809115884f26a1cfd28c8f7525c9b936ddf0a0/traverse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f57f1a976d092338cee4bd4a367e018c4079f8 Binary files /dev/null and b/shared/package-files/3a/3aa396bb64704b29ef730039d9809115884f26a1cfd28c8f7525c9b936ddf0a0/traverse.cpython-311.pyc differ diff --git a/shared/package-files/3a/3ab564cc90dcca718fa8efb2ddf72641fbe65bb15be7d9498b809a54da755288/shape_inference.h b/shared/package-files/3a/3ab564cc90dcca718fa8efb2ddf72641fbe65bb15be7d9498b809a54da755288/shape_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..7a44454da654a04ff3b2b44b66762fb976de7de1 --- /dev/null +++ b/shared/package-files/3a/3ab564cc90dcca718fa8efb2ddf72641fbe65bb15be7d9498b809a54da755288/shape_inference.h @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::lazy { +// Turn clang-format off, as we rely on the whole signature being on one line +// for codegen. +// clang-format off +TORCH_API std::vector compute_shape__adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API std::vector compute_shape__adaptive_avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape__adaptive_avg_pool3d(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API std::vector compute_shape__adaptive_avg_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape_abs(const at::Tensor & self); +TORCH_API std::vector compute_shape_arange_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out); +TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, ::std::optional generator); +TORCH_API std::vector compute_shape_bernoulli(const at::Tensor & self, double p, ::std::optional generator); +TORCH_API std::vector compute_shape_binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +TORCH_API std::vector compute_shape_binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction); +TORCH_API std::vector compute_shape_cat(at::TensorList tensors, int64_t dim); +TORCH_API std::vector compute_shape_cholesky(const at::Tensor & self, bool upper); +TORCH_API std::vector compute_shape_clamp_min(const at::Tensor & self, const at::Scalar & min); +TORCH_API std::vector compute_shape_clone(const at::Tensor & self, ::std::optional memory_format); +TORCH_API std::vector compute_shape_constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value); +TORCH_API std::vector compute_shape_convolution(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups); +TORCH_API std::vector compute_shape_convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask); +TORCH_API std::vector compute_shape_embedding(const at::Tensor & weight, const at::Tensor & indices, int64_t padding_idx, bool scale_grad_by_freq, bool sparse); +TORCH_API std::vector compute_shape_embedding_dense_backward(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +TORCH_API std::vector compute_shape_expand(const at::Tensor & self, at::IntArrayRef size, bool implicit); +TORCH_API std::vector compute_shape_expand(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit); +TORCH_API std::vector compute_shape_flip(const at::Tensor & self, at::IntArrayRef dims); +TORCH_API std::vector compute_shape_glu_backward(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +TORCH_API std::vector compute_shape_glu_jvp(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim); +TORCH_API std::vector compute_shape_grid_sampler_2d(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); +TORCH_API std::vector compute_shape_grid_sampler_2d_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array output_mask); +TORCH_API std::vector compute_shape_index_select(const at::Tensor & self, int64_t dim, const at::Tensor & index); +TORCH_API std::vector compute_shape_inverse(const at::Tensor & self); +TORCH_API std::vector compute_shape_isnan(const at::Tensor & self); +TORCH_API std::vector compute_shape_log_sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer); +TORCH_API std::vector compute_shape_log_sigmoid_forward(const at::Tensor & self); +TORCH_API std::vector compute_shape_logdet(const at::Tensor & self); +TORCH_API std::vector compute_shape_logical_and(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_logical_not(const at::Tensor & self); +TORCH_API std::vector compute_shape_logical_or(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_logical_xor(const at::Tensor & self, const at::Tensor & other); +TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); +TORCH_API std::vector compute_shape_masked_fill(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); +TORCH_API std::vector compute_shape_max(const at::Tensor & self); +TORCH_API std::vector compute_shape_mean(const at::Tensor & self, ::std::optional dtype); +TORCH_API std::vector compute_shape_min(const at::Tensor & self); +TORCH_API std::vector compute_shape_mv(const at::Tensor & self, const at::Tensor & vec); +TORCH_API std::vector compute_shape_native_batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps); +TORCH_API std::vector compute_shape_native_batch_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & running_mean, const ::std::optional & running_var, const ::std::optional & save_mean, const ::std::optional & save_invstd, bool train, double eps, ::std::array output_mask); +TORCH_API std::vector compute_shape_native_dropout(const at::Tensor & input, double p, ::std::optional train); +TORCH_API std::vector compute_shape_native_dropout_backward(const at::Tensor & grad_output, const at::Tensor & mask, double scale); +TORCH_API std::vector compute_shape_native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional & weight, const ::std::optional & bias, double eps); +TORCH_API std::vector compute_shape_native_layer_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const ::std::optional & weight, const ::std::optional & bias, ::std::array output_mask); +TORCH_API std::vector compute_shape_new_empty_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API std::vector compute_shape_nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +TORCH_API std::vector compute_shape_nll_loss2d_forward(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index); +TORCH_API std::vector compute_shape_nonzero(const at::Tensor & self); +TORCH_API std::vector compute_shape_normal_functional(const at::Tensor & self, double mean, double std, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t to, ::std::optional generator); +TORCH_API std::vector compute_shape_random(const at::Tensor & self, int64_t from, ::std::optional to, ::std::optional generator); +TORCH_API std::vector compute_shape_relu(const at::Tensor & self); +TORCH_API std::vector compute_shape_repeat(const at::Tensor & self, at::IntArrayRef repeats); +TORCH_API std::vector compute_shape_slogdet(const at::Tensor & self); +TORCH_API std::vector compute_shape_smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta); +TORCH_API std::vector compute_shape_sort(const at::Tensor & self, int64_t dim, bool descending); +TORCH_API std::vector compute_shape_stack(at::TensorList tensors, int64_t dim); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, bool unbiased); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim); +TORCH_API std::vector compute_shape_std(const at::Tensor & self, at::OptionalIntArrayRef dim, const ::std::optional & correction, bool keepdim); +TORCH_API std::vector compute_shape_sum(const at::Tensor & self, ::std::optional dtype); +TORCH_API std::vector compute_shape__to_copy(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format); +TORCH_API std::vector compute_shape_take(const at::Tensor & self, const at::Tensor & index); +TORCH_API std::vector compute_shape_trace(const at::Tensor & self); +TORCH_API std::vector compute_shape_zero(const at::Tensor & self); +TORCH_API std::vector compute_shape_narrow_copy_symint(const at::Tensor & self, int64_t dim, int64_t start, c10::SymInt length); +TORCH_API std::vector compute_shape_hardswish(const at::Tensor & self); +TORCH_API std::vector compute_shape_hardswish_backward(const at::Tensor & grad_output, const at::Tensor & self); +TORCH_API std::vector compute_shape_selu(const at::Tensor & self); +TORCH_API std::vector compute_shape_uniform(const at::Tensor & self, double from, double to, ::std::optional generator); + +// Non-Native ops +TORCH_API std::vector compute_shape_scalar(const at::Scalar& value, const at::ScalarType& type); +TORCH_API std::vector compute_shape_expand(const Output& input0, const std::vector& size, const bool& is_scalar_expand); +TORCH_API std::vector compute_shape_view(const Output& input0, const std::vector& output_sizes); +TORCH_API std::vector compute_shape_cast(const Output& input0, const at::ScalarType& dtype, const ::std::optional& stype); + +// View Ops +// (Now that functionalization pass is used, we should kill these in a later PR) +TORCH_API std::vector compute_shape_as_strided_view_update(const Output& target, const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset); +TORCH_API std::vector compute_shape_as_strided(const Output& input, const std::vector& size, const std::vector& stride, const int64_t& storage_offset); +TORCH_API std::vector compute_shape_diagonal_view_update(const Output& target, const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2); +TORCH_API std::vector compute_shape_diagonal(const Output& input, const int64_t& offset, const int64_t& dim1, const int64_t& dim2); +TORCH_API std::vector compute_shape_narrow_view_update(const Output& input, const Output& source, const std::vector& base_indices); +TORCH_API std::vector compute_shape_narrow(const Output& input, const std::vector& base_indices, const std::vector& sizes); +TORCH_API std::vector compute_shape_permute(const Output& input, const std::vector& dims); +TORCH_API std::vector compute_shape_resize(const Output& input, const std::vector& size); +TORCH_API std::vector compute_shape_select_view_update(const Output& target, const Output& source, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride); +TORCH_API std::vector compute_shape_select(const Output& input, const int64_t& dim, const int64_t& start, const int64_t& end, const int64_t& stride); +TORCH_API std::vector compute_shape_squeeze(const Output& input, const int& dim); +TORCH_API std::vector compute_shape_unsqueeze(const Output& input, const int& dim); + +TORCH_API std::vector compute_shape_select_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim, int64_t index); +TORCH_API std::vector compute_shape_diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2); +TORCH_API std::vector compute_shape_slice_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +TORCH_API std::vector compute_shape_as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset); +// clang-format on +} // namespace torch::lazy diff --git a/shared/package-files/3a/3ab5734b0bde03cf227c5f0d6a3426c4e542990e2fd690ea88fa0fa9c05d09f7/corrcoef_ops.h b/shared/package-files/3a/3ab5734b0bde03cf227c5f0d6a3426c4e542990e2fd690ea88fa0fa9c05d09f7/corrcoef_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c61d287a780325ce69ed7a0a784ee1f2c52a8bf9 --- /dev/null +++ b/shared/package-files/3a/3ab5734b0bde03cf227c5f0d6a3426c4e542990e2fd690ea88fa0fa9c05d09f7/corrcoef_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API corrcoef { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::corrcoef"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "corrcoef(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3ab607952e2bb90493f9d9503ae95e8aa1c52a955534ebeb1b968334581f7248/extendability.py b/shared/package-files/3a/3ab607952e2bb90493f9d9503ae95e8aa1c52a955534ebeb1b968334581f7248/extendability.py new file mode 100644 index 0000000000000000000000000000000000000000..61d8d067d9792659ed7097340c5ece28d9dc2e8c --- /dev/null +++ b/shared/package-files/3a/3ab607952e2bb90493f9d9503ae95e8aa1c52a955534ebeb1b968334581f7248/extendability.py @@ -0,0 +1,105 @@ +"""Provides a function for computing the extendability of a graph which is +undirected, simple, connected and bipartite and contains at least one perfect matching.""" + +import networkx as nx +from networkx.utils import not_implemented_for + +__all__ = ["maximal_extendability"] + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +@nx._dispatchable +def maximal_extendability(G): + """Computes the extendability of a graph. + + The extendability of a graph is defined as the maximum $k$ for which `G` + is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a + perfect matching and every set of $k$ independent edges can be extended + to a perfect matching in `G`. + + Parameters + ---------- + G : NetworkX Graph + A fully-connected bipartite graph without self-loops + + Returns + ------- + extendability : int + + Raises + ------ + NetworkXError + If the graph `G` is disconnected. + If the graph `G` is not bipartite. + If the graph `G` does not contain a perfect matching. + If the residual graph of `G` is not strongly connected. + + Notes + ----- + Definition: + Let `G` be a simple, connected, undirected and bipartite graph with a perfect + matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$, + is the graph obtained from G by directing the edges of M from V to U and the + edges that do not belong to M from U to V. + + Lemma [1]_ : + Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual + graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed + paths between every vertex of U and every vertex of V. + + Assuming that input graph `G` is undirected, simple, connected, bipartite and contains + a perfect matching M, this function constructs the residual graph $G_M$ of G and + returns the minimum value among the maximum vertex-disjoint directed paths between + every vertex of U and every vertex of V in $G_M$. By combining the definitions + and the lemma, this value represents the extendability of the graph `G`. + + Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices + and $m$ is the number of edges. + + References + ---------- + .. [1] "A polynomial algorithm for the extendability problem in bipartite graphs", + J. Lakhal, L. Litzler, Information Processing Letters, 1998. + .. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980 + https://doi.org/10.1016/0012-365X(80)90037-0 + + """ + if not nx.is_connected(G): + raise nx.NetworkXError("Graph G is not connected") + + if not nx.bipartite.is_bipartite(G): + raise nx.NetworkXError("Graph G is not bipartite") + + U, V = nx.bipartite.sets(G) + + maximum_matching = nx.bipartite.hopcroft_karp_matching(G) + + if not nx.is_perfect_matching(G, maximum_matching): + raise nx.NetworkXError("Graph G does not contain a perfect matching") + + # list of edges in perfect matching, directed from V to U + pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()] + + # Direct all the edges of G, from V to U if in matching, else from U to V + directed_edges = [ + (x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x) + for x, y in G.edges + ] + + # Construct the residual graph of G + residual_G = nx.DiGraph() + residual_G.add_nodes_from(G) + residual_G.add_edges_from(directed_edges) + + if not nx.is_strongly_connected(residual_G): + raise nx.NetworkXError("The residual graph of G is not strongly connected") + + # For node-pairs between V & U, keep min of max number of node-disjoint paths + # Variable $k$ stands for the extendability of graph G + k = float("inf") + for u in U: + for v in V: + num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v)) + k = k if k < num_paths else num_paths + return k diff --git a/shared/package-files/3a/3abb6db441e78dbb46d305a54444df2c8c54b6719eb65b94919925d800577f12/l1_loss.h b/shared/package-files/3a/3abb6db441e78dbb46d305a54444df2c8c54b6719eb65b94919925d800577f12/l1_loss.h new file mode 100644 index 0000000000000000000000000000000000000000..337edd9a3e45c69bf6c7e0b95d35a717aa87fa69 --- /dev/null +++ b/shared/package-files/3a/3abb6db441e78dbb46d305a54444df2c8c54b6719eb65b94919925d800577f12/l1_loss.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor +inline at::Tensor l1_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean) { + return at::_ops::l1_loss::call(self, target, reduction); +} + +} diff --git a/shared/package-files/3a/3abbe3f7211d41b4078572fc059da463bb2ced7e3bd975501ba41bf5fda3e79c/slow_conv_transpose3d_cpu_dispatch.h b/shared/package-files/3a/3abbe3f7211d41b4078572fc059da463bb2ced7e3bd975501ba41bf5fda3e79c/slow_conv_transpose3d_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ca01d6473d25fc83bee001a36f965b7a5b52c951 --- /dev/null +++ b/shared/package-files/3a/3abbe3f7211d41b4078572fc059da463bb2ced7e3bd975501ba41bf5fda3e79c/slow_conv_transpose3d_cpu_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor slow_conv_transpose3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_transpose3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); +TORCH_API at::Tensor & slow_conv_transpose3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor & slow_conv_transpose3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out); +TORCH_API at::Tensor & slow_conv_transpose3d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); +TORCH_API at::Tensor & slow_conv_transpose3d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/3a/3ac004fbff9060bd8fa8cd534d9e7ba4075c3b3e1fc8146d2bc0890ff7f4e4e9/isnan_ops.h b/shared/package-files/3a/3ac004fbff9060bd8fa8cd534d9e7ba4075c3b3e1fc8146d2bc0890ff7f4e4e9/isnan_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..77d43462949e0a484ebb9217560b073cc87a8abb --- /dev/null +++ b/shared/package-files/3a/3ac004fbff9060bd8fa8cd534d9e7ba4075c3b3e1fc8146d2bc0890ff7f4e4e9/isnan_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API isnan { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::isnan"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "isnan(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API isnan_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::isnan"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "isnan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3ac48bbe04731b530abad6136573ea907c22372ebe4335ea37e2ada2167bc18b/test_convert_dtypes.py b/shared/package-files/3a/3ac48bbe04731b530abad6136573ea907c22372ebe4335ea37e2ada2167bc18b/test_convert_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a920ba02cadeb21a7c0cc93f615cb1bc49dcbb --- /dev/null +++ b/shared/package-files/3a/3ac48bbe04731b530abad6136573ea907c22372ebe4335ea37e2ada2167bc18b/test_convert_dtypes.py @@ -0,0 +1,306 @@ +from itertools import product + +import numpy as np +import pytest + +from pandas._libs import lib + +import pandas as pd +import pandas._testing as tm + +# Each test case consists of a tuple with the data and dtype to create the +# test Series, the default dtype for the expected result (which is valid +# for most cases), and the specific cases where the result deviates from +# this default. Those overrides are defined as a dict with (keyword, val) as +# dictionary key. In case of multiple items, the last override takes precedence. + + +@pytest.fixture( + params=[ + ( + # data + [1, 2, 3], + # original dtype + np.dtype("int32"), + # default expected dtype + "Int32", + # exceptions on expected dtype + {("convert_integer", False): np.dtype("int32")}, + ), + ( + [1, 2, 3], + np.dtype("int64"), + "Int64", + {("convert_integer", False): np.dtype("int64")}, + ), + ( + ["x", "y", "z"], + np.dtype("O"), + pd.StringDtype(), + {("convert_string", False): np.dtype("O")}, + ), + ( + [True, False, np.nan], + np.dtype("O"), + pd.BooleanDtype(), + {("convert_boolean", False): np.dtype("O")}, + ), + ( + ["h", "i", np.nan], + np.dtype("O"), + pd.StringDtype(), + {("convert_string", False): np.dtype("O")}, + ), + ( # GH32117 + ["h", "i", 1], + np.dtype("O"), + np.dtype("O"), + {}, + ), + ( + [10, np.nan, 20], + np.dtype("float"), + "Int64", + { + ("convert_integer", False, "convert_floating", True): "Float64", + ("convert_integer", False, "convert_floating", False): np.dtype( + "float" + ), + }, + ), + ( + [np.nan, 100.5, 200], + np.dtype("float"), + "Float64", + {("convert_floating", False): np.dtype("float")}, + ), + ( + [3, 4, 5], + "Int8", + "Int8", + {}, + ), + ( + [[1, 2], [3, 4], [5]], + None, + np.dtype("O"), + {}, + ), + ( + [4, 5, 6], + np.dtype("uint32"), + "UInt32", + {("convert_integer", False): np.dtype("uint32")}, + ), + ( + [-10, 12, 13], + np.dtype("i1"), + "Int8", + {("convert_integer", False): np.dtype("i1")}, + ), + ( + [1.2, 1.3], + np.dtype("float32"), + "Float32", + {("convert_floating", False): np.dtype("float32")}, + ), + ( + [1, 2.0], + object, + "Int64", + { + ("convert_integer", False): "Float64", + ("convert_integer", False, "convert_floating", False): np.dtype( + "float" + ), + ("infer_objects", False): np.dtype("object"), + }, + ), + ( + [1, 2.5], + object, + "Float64", + { + ("convert_floating", False): np.dtype("float"), + ("infer_objects", False): np.dtype("object"), + }, + ), + (["a", "b"], pd.CategoricalDtype(), pd.CategoricalDtype(), {}), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("s"), + pd.DatetimeTZDtype(tz="UTC"), + pd.DatetimeTZDtype(tz="UTC"), + {}, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ms"), + pd.DatetimeTZDtype(tz="UTC"), + pd.DatetimeTZDtype(tz="UTC"), + {}, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("us"), + pd.DatetimeTZDtype(tz="UTC"), + pd.DatetimeTZDtype(tz="UTC"), + {}, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"), + pd.DatetimeTZDtype(tz="UTC"), + pd.DatetimeTZDtype(tz="UTC"), + {}, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"), + "datetime64[ns]", + np.dtype("datetime64[ns]"), + {}, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]).as_unit("ns"), + object, + np.dtype("datetime64[ns]"), + {("infer_objects", False): np.dtype("object")}, + ), + ( + pd.period_range("1/1/2011", freq="M", periods=3), + None, + pd.PeriodDtype("M"), + {}, + ), + ( + pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]), + None, + pd.IntervalDtype("int64", "right"), + {}, + ), + ] +) +def test_cases(request): + return request.param + + +class TestSeriesConvertDtypes: + @pytest.mark.parametrize("params", product(*[(True, False)] * 5)) + def test_convert_dtypes( + self, + test_cases, + params, + using_infer_string, + ): + data, maindtype, expected_default, expected_other = test_cases + if ( + hasattr(data, "dtype") + and lib.is_np_dtype(data.dtype, "M") + and isinstance(maindtype, pd.DatetimeTZDtype) + ): + # this astype is deprecated in favor of tz_localize + msg = "Cannot use .astype to convert from timezone-naive dtype" + with pytest.raises(TypeError, match=msg): + pd.Series(data, dtype=maindtype) + return + + if maindtype is not None: + series = pd.Series(data, dtype=maindtype) + else: + series = pd.Series(data) + + result = series.convert_dtypes(*params) + + param_names = [ + "infer_objects", + "convert_string", + "convert_integer", + "convert_boolean", + "convert_floating", + ] + params_dict = dict(zip(param_names, params)) + + expected_dtype = expected_default + for spec, dtype in expected_other.items(): + if all(params_dict[key] is val for key, val in zip(spec[::2], spec[1::2])): + expected_dtype = dtype + if ( + using_infer_string + and expected_default == "string" + and expected_dtype == object + and params[0] + and not params[1] + ): + # If we would convert with convert strings then infer_objects converts + # with the option + expected_dtype = "string[pyarrow_numpy]" + + expected = pd.Series(data, dtype=expected_dtype) + tm.assert_series_equal(result, expected) + + # Test that it is a copy + copy = series.copy(deep=True) + + if result.notna().sum() > 0 and result.dtype in ["interval[int64, right]"]: + with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): + result[result.notna()] = np.nan + else: + result[result.notna()] = np.nan + + # Make sure original not changed + tm.assert_series_equal(series, copy) + + def test_convert_string_dtype(self, nullable_string_dtype): + # https://github.com/pandas-dev/pandas/issues/31731 -> converting columns + # that are already string dtype + df = pd.DataFrame( + {"A": ["a", "b", pd.NA], "B": ["ä", "ö", "ü"]}, dtype=nullable_string_dtype + ) + result = df.convert_dtypes() + tm.assert_frame_equal(df, result) + + def test_convert_bool_dtype(self): + # GH32287 + df = pd.DataFrame({"A": pd.array([True])}) + tm.assert_frame_equal(df, df.convert_dtypes()) + + def test_convert_byte_string_dtype(self): + # GH-43183 + byte_str = b"binary-string" + + df = pd.DataFrame(data={"A": byte_str}, index=[0]) + result = df.convert_dtypes() + expected = df + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "infer_objects, dtype", [(True, "Int64"), (False, "object")] + ) + def test_convert_dtype_object_with_na(self, infer_objects, dtype): + # GH#48791 + ser = pd.Series([1, pd.NA]) + result = ser.convert_dtypes(infer_objects=infer_objects) + expected = pd.Series([1, pd.NA], dtype=dtype) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "infer_objects, dtype", [(True, "Float64"), (False, "object")] + ) + def test_convert_dtype_object_with_na_float(self, infer_objects, dtype): + # GH#48791 + ser = pd.Series([1.5, pd.NA]) + result = ser.convert_dtypes(infer_objects=infer_objects) + expected = pd.Series([1.5, pd.NA], dtype=dtype) + tm.assert_series_equal(result, expected) + + def test_convert_dtypes_pyarrow_to_np_nullable(self): + # GH 53648 + pytest.importorskip("pyarrow") + ser = pd.Series(range(2), dtype="int32[pyarrow]") + result = ser.convert_dtypes(dtype_backend="numpy_nullable") + expected = pd.Series(range(2), dtype="Int32") + tm.assert_series_equal(result, expected) + + def test_convert_dtypes_pyarrow_null(self): + # GH#55346 + pa = pytest.importorskip("pyarrow") + ser = pd.Series([None, None]) + result = ser.convert_dtypes(dtype_backend="pyarrow") + expected = pd.Series([None, None], dtype=pd.ArrowDtype(pa.null())) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/3a/3ac735dcbe6cfdf0607d526aaea5a3fa9a87c072c6b6788b2b40faa6b0268e48/codeprinter.cpython-311.pyc b/shared/package-files/3a/3ac735dcbe6cfdf0607d526aaea5a3fa9a87c072c6b6788b2b40faa6b0268e48/codeprinter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ac0fc8e9ef42c659ec2a54ad6796bb438d277a3 Binary files /dev/null and b/shared/package-files/3a/3ac735dcbe6cfdf0607d526aaea5a3fa9a87c072c6b6788b2b40faa6b0268e48/codeprinter.cpython-311.pyc differ diff --git a/shared/package-files/3a/3ac81ccec37bb7e3fad0744434dd467bb54e114136ee2d5d971b4253e04e1b73/algebraicconnectivity.py b/shared/package-files/3a/3ac81ccec37bb7e3fad0744434dd467bb54e114136ee2d5d971b4253e04e1b73/algebraicconnectivity.py new file mode 100644 index 0000000000000000000000000000000000000000..55073c21c00e01dcd6a59a87556c71d73270b7d9 --- /dev/null +++ b/shared/package-files/3a/3ac81ccec37bb7e3fad0744434dd467bb54e114136ee2d5d971b4253e04e1b73/algebraicconnectivity.py @@ -0,0 +1,655 @@ +""" +Algebraic connectivity and Fiedler vectors of undirected graphs. +""" + +import networkx as nx +from networkx.utils import ( + not_implemented_for, + np_random_state, + reverse_cuthill_mckee_ordering, +) + +__all__ = [ + "algebraic_connectivity", + "fiedler_vector", + "spectral_ordering", + "spectral_bisection", +] + + +class _PCGSolver: + """Preconditioned conjugate gradient method. + + To solve Ax = b: + M = A.diagonal() # or some other preconditioner + solver = _PCGSolver(lambda x: A * x, lambda x: M * x) + x = solver.solve(b) + + The inputs A and M are functions which compute + matrix multiplication on the argument. + A - multiply by the matrix A in Ax=b + M - multiply by M, the preconditioner surrogate for A + + Warning: There is no limit on number of iterations. + """ + + def __init__(self, A, M): + self._A = A + self._M = M + + def solve(self, B, tol): + import numpy as np + + # Densifying step - can this be kept sparse? + B = np.asarray(B) + X = np.ndarray(B.shape, order="F") + for j in range(B.shape[1]): + X[:, j] = self._solve(B[:, j], tol) + return X + + def _solve(self, b, tol): + import numpy as np + import scipy as sp + + A = self._A + M = self._M + tol *= sp.linalg.blas.dasum(b) + # Initialize. + x = np.zeros(b.shape) + r = b.copy() + z = M(r) + rz = sp.linalg.blas.ddot(r, z) + p = z.copy() + # Iterate. + while True: + Ap = A(p) + alpha = rz / sp.linalg.blas.ddot(p, Ap) + x = sp.linalg.blas.daxpy(p, x, a=alpha) + r = sp.linalg.blas.daxpy(Ap, r, a=-alpha) + if sp.linalg.blas.dasum(r) < tol: + return x + z = M(r) + beta = sp.linalg.blas.ddot(r, z) + beta, rz = beta / rz, beta + p = sp.linalg.blas.daxpy(p, z, a=beta) + + +class _LUSolver: + """LU factorization. + + To solve Ax = b: + solver = _LUSolver(A) + x = solver.solve(b) + + optional argument `tol` on solve method is ignored but included + to match _PCGsolver API. + """ + + def __init__(self, A): + import scipy as sp + + self._LU = sp.sparse.linalg.splu( + A, + permc_spec="MMD_AT_PLUS_A", + diag_pivot_thresh=0.0, + options={"Equil": True, "SymmetricMode": True}, + ) + + def solve(self, B, tol=None): + import numpy as np + + B = np.asarray(B) + X = np.ndarray(B.shape, order="F") + for j in range(B.shape[1]): + X[:, j] = self._LU.solve(B[:, j]) + return X + + +def _preprocess_graph(G, weight): + """Compute edge weights and eliminate zero-weight edges.""" + if G.is_directed(): + H = nx.MultiGraph() + H.add_nodes_from(G) + H.add_weighted_edges_from( + ((u, v, e.get(weight, 1.0)) for u, v, e in G.edges(data=True) if u != v), + weight=weight, + ) + G = H + if not G.is_multigraph(): + edges = ( + (u, v, abs(e.get(weight, 1.0))) for u, v, e in G.edges(data=True) if u != v + ) + else: + edges = ( + (u, v, sum(abs(e.get(weight, 1.0)) for e in G[u][v].values())) + for u, v in G.edges() + if u != v + ) + H = nx.Graph() + H.add_nodes_from(G) + H.add_weighted_edges_from((u, v, e) for u, v, e in edges if e != 0) + return H + + +def _rcm_estimate(G, nodelist): + """Estimate the Fiedler vector using the reverse Cuthill-McKee ordering.""" + import numpy as np + + G = G.subgraph(nodelist) + order = reverse_cuthill_mckee_ordering(G) + n = len(nodelist) + index = dict(zip(nodelist, range(n))) + x = np.ndarray(n, dtype=float) + for i, u in enumerate(order): + x[index[u]] = i + x -= (n - 1) / 2.0 + return x + + +def _tracemin_fiedler(L, X, normalized, tol, method): + """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm. + + The Fiedler vector of a connected undirected graph is the eigenvector + corresponding to the second smallest eigenvalue of the Laplacian matrix + of the graph. This function starts with the Laplacian L, not the Graph. + + Parameters + ---------- + L : Laplacian of a possibly weighted or normalized, but undirected graph + + X : Initial guess for a solution. Usually a matrix of random numbers. + This function allows more than one column in X to identify more than + one eigenvector if desired. + + normalized : bool + Whether the normalized Laplacian matrix is used. + + tol : float + Tolerance of relative residual in eigenvalue computation. + Warning: There is no limit on number of iterations. + + method : string + Should be 'tracemin_pcg' or 'tracemin_lu'. + Otherwise exception is raised. + + Returns + ------- + sigma, X : Two NumPy arrays of floats. + The lowest eigenvalues and corresponding eigenvectors of L. + The size of input X determines the size of these outputs. + As this is for Fiedler vectors, the zero eigenvalue (and + constant eigenvector) are avoided. + """ + import numpy as np + import scipy as sp + + n = X.shape[0] + + if normalized: + # Form the normalized Laplacian matrix and determine the eigenvector of + # its nullspace. + e = np.sqrt(L.diagonal()) + # TODO: rm csr_array wrapper when spdiags array creation becomes available + D = sp.sparse.csr_array(sp.sparse.spdiags(1 / e, 0, n, n, format="csr")) + L = D @ L @ D + e *= 1.0 / np.linalg.norm(e, 2) + + if normalized: + + def project(X): + """Make X orthogonal to the nullspace of L.""" + X = np.asarray(X) + for j in range(X.shape[1]): + X[:, j] -= (X[:, j] @ e) * e + + else: + + def project(X): + """Make X orthogonal to the nullspace of L.""" + X = np.asarray(X) + for j in range(X.shape[1]): + X[:, j] -= X[:, j].sum() / n + + if method == "tracemin_pcg": + D = L.diagonal().astype(float) + solver = _PCGSolver(lambda x: L @ x, lambda x: D * x) + elif method == "tracemin_lu": + # Convert A to CSC to suppress SparseEfficiencyWarning. + A = sp.sparse.csc_array(L, dtype=float, copy=True) + # Force A to be nonsingular. Since A is the Laplacian matrix of a + # connected graph, its rank deficiency is one, and thus one diagonal + # element needs to modified. Changing to infinity forces a zero in the + # corresponding element in the solution. + i = (A.indptr[1:] - A.indptr[:-1]).argmax() + A[i, i] = np.inf + solver = _LUSolver(A) + else: + raise nx.NetworkXError(f"Unknown linear system solver: {method}") + + # Initialize. + Lnorm = abs(L).sum(axis=1).flatten().max() + project(X) + W = np.ndarray(X.shape, order="F") + + while True: + # Orthonormalize X. + X = np.linalg.qr(X)[0] + # Compute iteration matrix H. + W[:, :] = L @ X + H = X.T @ W + sigma, Y = sp.linalg.eigh(H, overwrite_a=True) + # Compute the Ritz vectors. + X = X @ Y + # Test for convergence exploiting the fact that L * X == W * Y. + res = sp.linalg.blas.dasum(W @ Y[:, 0] - sigma[0] * X[:, 0]) / Lnorm + if res < tol: + break + # Compute X = L \ X / (X' * (L \ X)). + # L \ X can have an arbitrary projection on the nullspace of L, + # which will be eliminated. + W[:, :] = solver.solve(X, tol) + X = (sp.linalg.inv(W.T @ X) @ W.T).T # Preserves Fortran storage order. + project(X) + + return sigma, np.asarray(X) + + +def _get_fiedler_func(method): + """Returns a function that solves the Fiedler eigenvalue problem.""" + import numpy as np + + if method == "tracemin": # old style keyword `. + + Returns + ------- + algebraic_connectivity : float + Algebraic connectivity. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + NetworkXError + If G has less than two nodes. + + Notes + ----- + Edge weights are interpreted by their absolute values. For MultiGraph's, + weights of parallel edges are summed. Zero-weighted edges are ignored. + + See Also + -------- + laplacian_matrix + + Examples + -------- + For undirected graphs algebraic connectivity can tell us if a graph is connected or not + `G` is connected iff ``algebraic_connectivity(G) > 0``: + + >>> G = nx.complete_graph(5) + >>> nx.algebraic_connectivity(G) > 0 + True + >>> G.add_node(10) # G is no longer connected + >>> nx.algebraic_connectivity(G) > 0 + False + + """ + if len(G) < 2: + raise nx.NetworkXError("graph has less than two nodes.") + G = _preprocess_graph(G, weight) + if not nx.is_connected(G): + return 0.0 + + L = nx.laplacian_matrix(G) + if L.shape[0] == 2: + return 2.0 * float(L[0, 0]) if not normalized else 2.0 + + find_fiedler = _get_fiedler_func(method) + x = None if method != "lobpcg" else _rcm_estimate(G, G) + sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) + return float(sigma) + + +@not_implemented_for("directed") +@np_random_state(5) +@nx._dispatchable(edge_attrs="weight") +def fiedler_vector( + G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None +): + """Returns the Fiedler vector of a connected undirected graph. + + The Fiedler vector of a connected undirected graph is the eigenvector + corresponding to the second smallest eigenvalue of the Laplacian matrix + of the graph. + + Parameters + ---------- + G : NetworkX graph + An undirected graph. + + weight : object, optional (default: None) + The data key used to determine the weight of each edge. If None, then + each edge has unit weight. + + normalized : bool, optional (default: False) + Whether the normalized Laplacian matrix is used. + + tol : float, optional (default: 1e-8) + Tolerance of relative residual in eigenvalue computation. + + method : string, optional (default: 'tracemin_pcg') + Method of eigenvalue computation. It must be one of the tracemin + options shown below (TraceMIN), 'lanczos' (Lanczos iteration) + or 'lobpcg' (LOBPCG). + + The TraceMIN algorithm uses a linear system solver. The following + values allow specifying the solver to be used. + + =============== ======================================== + Value Solver + =============== ======================================== + 'tracemin_pcg' Preconditioned conjugate gradient method + 'tracemin_lu' LU factorization + =============== ======================================== + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + fiedler_vector : NumPy array of floats. + Fiedler vector. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + NetworkXError + If G has less than two nodes or is not connected. + + Notes + ----- + Edge weights are interpreted by their absolute values. For MultiGraph's, + weights of parallel edges are summed. Zero-weighted edges are ignored. + + See Also + -------- + laplacian_matrix + + Examples + -------- + Given a connected graph the signs of the values in the Fiedler vector can be + used to partition the graph into two components. + + >>> G = nx.barbell_graph(5, 0) + >>> nx.fiedler_vector(G, normalized=True, seed=1) + array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899, + 0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129]) + + The connected components are the two 5-node cliques of the barbell graph. + """ + import numpy as np + + if len(G) < 2: + raise nx.NetworkXError("graph has less than two nodes.") + G = _preprocess_graph(G, weight) + if not nx.is_connected(G): + raise nx.NetworkXError("graph is not connected.") + + if len(G) == 2: + return np.array([1.0, -1.0]) + + find_fiedler = _get_fiedler_func(method) + L = nx.laplacian_matrix(G) + x = None if method != "lobpcg" else _rcm_estimate(G, G) + sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) + return fiedler + + +@np_random_state(5) +@nx._dispatchable(edge_attrs="weight") +def spectral_ordering( + G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None +): + """Compute the spectral_ordering of a graph. + + The spectral ordering of a graph is an ordering of its nodes where nodes + in the same weakly connected components appear contiguous and ordered by + their corresponding elements in the Fiedler vector of the component. + + Parameters + ---------- + G : NetworkX graph + A graph. + + weight : object, optional (default: None) + The data key used to determine the weight of each edge. If None, then + each edge has unit weight. + + normalized : bool, optional (default: False) + Whether the normalized Laplacian matrix is used. + + tol : float, optional (default: 1e-8) + Tolerance of relative residual in eigenvalue computation. + + method : string, optional (default: 'tracemin_pcg') + Method of eigenvalue computation. It must be one of the tracemin + options shown below (TraceMIN), 'lanczos' (Lanczos iteration) + or 'lobpcg' (LOBPCG). + + The TraceMIN algorithm uses a linear system solver. The following + values allow specifying the solver to be used. + + =============== ======================================== + Value Solver + =============== ======================================== + 'tracemin_pcg' Preconditioned conjugate gradient method + 'tracemin_lu' LU factorization + =============== ======================================== + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + spectral_ordering : NumPy array of floats. + Spectral ordering of nodes. + + Raises + ------ + NetworkXError + If G is empty. + + Notes + ----- + Edge weights are interpreted by their absolute values. For MultiGraph's, + weights of parallel edges are summed. Zero-weighted edges are ignored. + + See Also + -------- + laplacian_matrix + """ + if len(G) == 0: + raise nx.NetworkXError("graph is empty.") + G = _preprocess_graph(G, weight) + + find_fiedler = _get_fiedler_func(method) + order = [] + for component in nx.connected_components(G): + size = len(component) + if size > 2: + L = nx.laplacian_matrix(G, component) + x = None if method != "lobpcg" else _rcm_estimate(G, component) + sigma, fiedler = find_fiedler(L, x, normalized, tol, seed) + sort_info = zip(fiedler, range(size), component) + order.extend(u for x, c, u in sorted(sort_info)) + else: + order.extend(component) + + return order + + +@nx._dispatchable(edge_attrs="weight") +def spectral_bisection( + G, weight="weight", normalized=False, tol=1e-8, method="tracemin_pcg", seed=None +): + """Bisect the graph using the Fiedler vector. + + This method uses the Fiedler vector to bisect a graph. + The partition is defined by the nodes which are associated with + either positive or negative values in the vector. + + Parameters + ---------- + G : NetworkX Graph + + weight : str, optional (default: weight) + The data key used to determine the weight of each edge. If None, then + each edge has unit weight. + + normalized : bool, optional (default: False) + Whether the normalized Laplacian matrix is used. + + tol : float, optional (default: 1e-8) + Tolerance of relative residual in eigenvalue computation. + + method : string, optional (default: 'tracemin_pcg') + Method of eigenvalue computation. It must be one of the tracemin + options shown below (TraceMIN), 'lanczos' (Lanczos iteration) + or 'lobpcg' (LOBPCG). + + The TraceMIN algorithm uses a linear system solver. The following + values allow specifying the solver to be used. + + =============== ======================================== + Value Solver + =============== ======================================== + 'tracemin_pcg' Preconditioned conjugate gradient method + 'tracemin_lu' LU factorization + =============== ======================================== + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + bisection : tuple of sets + Sets with the bisection of nodes + + Examples + -------- + >>> G = nx.barbell_graph(3, 0) + >>> nx.spectral_bisection(G) + ({0, 1, 2}, {3, 4, 5}) + + References + ---------- + .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370 + Oxford University Press 2011. + """ + import numpy as np + + v = nx.fiedler_vector(G, weight, normalized, tol, method, seed) + nodes = np.array(list(G)) + pos_vals = v >= 0 + + return set(nodes[~pos_vals].tolist()), set(nodes[pos_vals].tolist()) diff --git a/shared/package-files/3a/3acab72beb59b971d508c409ef4f0f8cfa3e0703218e18c0a4ee1bd1360b1498/invoke.h b/shared/package-files/3a/3acab72beb59b971d508c409ef4f0f8cfa3e0703218e18c0a4ee1bd1360b1498/invoke.h new file mode 100644 index 0000000000000000000000000000000000000000..f00314ce140e390be90a1ab3c328fd73d73c0d46 --- /dev/null +++ b/shared/package-files/3a/3acab72beb59b971d508c409ef4f0f8cfa3e0703218e18c0a4ee1bd1360b1498/invoke.h @@ -0,0 +1,189 @@ +/* + * Copyright 1993-2022 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#ifndef _CG_INVOKE_H +#define _CG_INVOKE_H + +#include "info.h" +#include "helpers.h" + +#if defined(_CG_CPP11_FEATURES) + +_CG_BEGIN_NAMESPACE + +namespace details { + + template + struct _elect_group_supported : _CG_STL_NAMESPACE::false_type {}; +#ifdef _CG_HAS_INSTR_ELECT + template<> + struct _elect_group_supported : _CG_STL_NAMESPACE::true_type {}; + template + struct _elect_group_supported> : + _CG_STL_NAMESPACE::integral_constant {}; +#endif + + template + struct elect_group_supported : public _elect_group_supported> {}; + + template + _CG_STATIC_QUALIFIER bool elect_one(const Group& group, unsigned int mask, unsigned int& leader_lane) { + int is_leader = 0; +#ifdef _CG_HAS_INSTR_ELECT + asm("{\n\t" + " .reg .pred p;\n\t" + " elect.sync %0|p, %2;\n\t" + " @p mov.s32 %1, 1;\n\t" + "}" + : "+r"(leader_lane), "+r"(is_leader) : "r" (mask)); +#endif + return is_leader; + } + + template + struct invoke_one_impl {}; + + template<> + struct invoke_one_impl { + template + _CG_STATIC_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) { + auto mask = details::_coalesced_group_data_access::get_mask(group); + unsigned int leader_lane = 0; + + if (elect_one(group, mask, leader_lane)) { + _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...); + } + } + + template + _CG_STATIC_QUALIFIER auto invoke_one_broadcast(const Group& group, Fn&& fn, Args&&... args) + -> typename _CG_STL_NAMESPACE::remove_reference< + decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type { + + using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...)); + details::remove_qual result; + auto mask = details::_coalesced_group_data_access::get_mask(group); + unsigned int leader_lane = 0; + + if (elect_one(group, mask, leader_lane)) { + result = _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...); + } + + // Need to use low level api instead of group.shfl, because elect_one returns lane id, not group rank. + return tile::shuffle_dispatch::shfl(result, mask, leader_lane, 32); + } + }; + + template<> + struct invoke_one_impl { + template + _CG_STATIC_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) { + if (group.thread_rank() == 0) { + _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...); + } + } + + template + _CG_STATIC_QUALIFIER auto invoke_one_broadcast(const Group& group, Fn&& fn, Args&&... args) + -> typename _CG_STL_NAMESPACE::remove_reference< + decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type { + + using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...)); + details::remove_qual result; + + if (group.thread_rank() == 0) { + result = _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...); + } + + return group.shfl(result, 0); + } + }; + + +}; // namespace details + +template +_CG_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) { + using impl = details::invoke_one_impl::value>; + impl::invoke_one(group, _CG_STL_NAMESPACE::forward(fn), _CG_STL_NAMESPACE::forward(args)...); +} + +template +_CG_QUALIFIER auto invoke_one_broadcast(const coalesced_group& group, Fn&& fn, Args&&... args) + -> typename _CG_STL_NAMESPACE::remove_reference< + decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type { + + using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...)); + static_assert(!_CG_STL_NAMESPACE::is_same::value, + "For invocables returning void invoke_one should be used instead"); + using impl = details::invoke_one_impl::value>; + return impl::invoke_one_broadcast(group, + _CG_STL_NAMESPACE::forward(fn), + _CG_STL_NAMESPACE::forward(args)...); +} + +template +_CG_QUALIFIER auto invoke_one_broadcast(const thread_block_tile& group, Fn&& fn, Args&&... args) + -> typename _CG_STL_NAMESPACE::remove_reference< + decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type { + + using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...)); + static_assert(!_CG_STL_NAMESPACE::is_same::value, + "For invocables returning void invoke_one should be used instead"); + using impl = details::invoke_one_impl>::value>; + return impl::invoke_one_broadcast(group, + _CG_STL_NAMESPACE::forward(fn), + _CG_STL_NAMESPACE::forward(args)...); +} + +_CG_END_NAMESPACE + +#endif //_CG_CPP11_FEATURES + +#endif // _CG_INVOKE_H diff --git a/shared/package-files/3a/3acb7df3986616be742ac03e403d2c858de13f8297e6a27dadbe42f97e1e84af/gist.py b/shared/package-files/3a/3acb7df3986616be742ac03e403d2c858de13f8297e6a27dadbe42f97e1e84af/gist.py new file mode 100644 index 0000000000000000000000000000000000000000..74117b544b02108fd2a7be06c716df477481ed47 --- /dev/null +++ b/shared/package-files/3a/3acb7df3986616be742ac03e403d2c858de13f8297e6a27dadbe42f97e1e84af/gist.py @@ -0,0 +1,232 @@ +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GistFileSystem(AbstractFileSystem): + """ + Interface to files in a single GitHub Gist. + + Provides read-only access to a gist's files. Gists do not contain + subdirectories, so file listing is straightforward. + + Parameters + ---------- + gist_id : str + The ID of the gist you want to access (the long hex value from the URL). + filenames : list[str] (optional) + If provided, only make a file system representing these files, and do not fetch + the list of all files for this gist. + sha : str (optional) + If provided, fetch a particular revision of the gist. If omitted, + the latest revision is used. + username : str (optional) + GitHub username for authentication (required if token is given). + token : str (optional) + GitHub personal access token (required if username is given). + timeout : (float, float) or float, optional + Connect and read timeouts for requests (default 60s each). + kwargs : dict + Stored on `self.request_kw` and passed to `requests.get` when fetching Gist + metadata or reading ("opening") a file. + """ + + protocol = "gist" + gist_url = "https://api.github.com/gists/{gist_id}" + gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}" + + def __init__( + self, + gist_id, + filenames=None, + sha=None, + username=None, + token=None, + timeout=None, + **kwargs, + ): + super().__init__() + self.gist_id = gist_id + self.filenames = filenames + self.sha = sha # revision of the gist (optional) + if (username is None) ^ (token is None): + # Both or neither must be set + if username or token: + raise ValueError("Auth requires both username and token, or neither.") + self.username = username + self.token = token + self.request_kw = kwargs + # Default timeouts to 60s connect/read if none provided + self.timeout = timeout if timeout is not None else (60, 60) + + # We use a single-level "directory" cache, because a gist is essentially flat + self.dircache[""] = self._fetch_file_list() + + @property + def kw(self): + """Auth parameters passed to 'requests' if we have username/token.""" + if self.username is not None and self.token is not None: + return {"auth": (self.username, self.token), **self.request_kw} + return self.request_kw + + def _fetch_gist_metadata(self): + """ + Fetch the JSON metadata for this gist (possibly for a specific revision). + """ + if self.sha: + url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) + else: + url = self.gist_url.format(gist_id=self.gist_id) + + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError( + f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" + ) + r.raise_for_status() + return r.json() + + def _fetch_file_list(self): + """ + Returns a list of dicts describing each file in the gist. These get stored + in self.dircache[""]. + """ + meta = self._fetch_gist_metadata() + if self.filenames: + available_files = meta.get("files", {}) + files = {} + for fn in self.filenames: + if fn not in available_files: + raise FileNotFoundError(fn) + files[fn] = available_files[fn] + else: + files = meta.get("files", {}) + + out = [] + for fname, finfo in files.items(): + if finfo is None: + # Occasionally GitHub returns a file entry with null if it was deleted + continue + # Build a directory entry + out.append( + { + "name": fname, # file's name + "type": "file", # gists have no subdirectories + "size": finfo.get("size", 0), # file size in bytes + "raw_url": finfo.get("raw_url"), + } + ) + return out + + @classmethod + def _strip_protocol(cls, path): + """ + Remove 'gist://' from the path, if present. + """ + # The default infer_storage_options can handle gist://username:token@id/file + # or gist://id/file, but let's ensure we handle a normal usage too. + # We'll just strip the protocol prefix if it exists. + path = infer_storage_options(path).get("path", path) + return path.lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + """ + Parse 'gist://' style URLs into GistFileSystem constructor kwargs. + For example: + gist://:TOKEN@/file.txt + gist://username:TOKEN@/file.txt + """ + so = infer_storage_options(path) + out = {} + if "username" in so and so["username"]: + out["username"] = so["username"] + if "password" in so and so["password"]: + out["token"] = so["password"] + if "host" in so and so["host"]: + # We interpret 'host' as the gist ID + out["gist_id"] = so["host"] + + # Extract SHA and filename from path + if "path" in so and so["path"]: + path_parts = so["path"].rsplit("/", 2)[-2:] + if len(path_parts) == 2: + if path_parts[0]: # SHA present + out["sha"] = path_parts[0] + if path_parts[1]: # filename also present + out["filenames"] = [path_parts[1]] + + return out + + def ls(self, path="", detail=False, **kwargs): + """ + List files in the gist. Gists are single-level, so any 'path' is basically + the filename, or empty for all files. + + Parameters + ---------- + path : str, optional + The filename to list. If empty, returns all files in the gist. + detail : bool, default False + If True, return a list of dicts; if False, return a list of filenames. + """ + path = self._strip_protocol(path or "") + # If path is empty, return all + if path == "": + results = self.dircache[""] + else: + # We want just the single file with this name + all_files = self.dircache[""] + results = [f for f in all_files if f["name"] == path] + if not results: + raise FileNotFoundError(path) + if detail: + return results + else: + return sorted(f["name"] for f in results) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + Read a single file from the gist. + """ + if mode != "rb": + raise NotImplementedError("GitHub Gist FS is read-only (no write).") + + path = self._strip_protocol(path) + # Find the file entry in our dircache + matches = [f for f in self.dircache[""] if f["name"] == path] + if not matches: + raise FileNotFoundError(path) + finfo = matches[0] + + raw_url = finfo.get("raw_url") + if not raw_url: + raise FileNotFoundError(f"No raw_url for file: {path}") + + r = requests.get(raw_url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + return MemoryFile(path, None, r.content) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """ + Return {path: contents} for the given file or files. If 'recursive' is True, + and path is empty, returns all files in the gist. + """ + paths = self.expand_path(path, recursive=recursive) + out = {} + for p in paths: + try: + with self.open(p, "rb") as f: + out[p] = f.read() + except FileNotFoundError as e: + if on_error == "raise": + raise e + elif on_error == "omit": + pass # skip + else: + out[p] = e + return out diff --git a/shared/package-files/3a/3accb82c0551419eee5177f43a55582260f50107dcd0bf33b7f148b9311b0551/samtools.pysam.c b/shared/package-files/3a/3accb82c0551419eee5177f43a55582260f50107dcd0bf33b7f148b9311b0551/samtools.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..10740a4848109786f40a0bea17c3f0c723e8cd08 --- /dev/null +++ b/shared/package-files/3a/3accb82c0551419eee5177f43a55582260f50107dcd0bf33b7f148b9311b0551/samtools.pysam.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include +#include +#include + +#include "samtools.pysam.h" + +FILE * samtools_stderr = NULL; +FILE * samtools_stdout = NULL; +const char * samtools_stdout_fn = NULL; + + +FILE * samtools_set_stderr(int fd) +{ + if (samtools_stderr != NULL) + fclose(samtools_stderr); + samtools_stderr = fdopen(fd, "w"); + return samtools_stderr; +} + +void samtools_close_stderr(void) +{ + fclose(samtools_stderr); + samtools_stderr = NULL; +} + +FILE * samtools_set_stdout(int fd) +{ + if (samtools_stdout != NULL) + fclose(samtools_stdout); + samtools_stdout = fdopen(fd, "w"); + if (samtools_stdout == NULL) + { + fprintf(samtools_stderr, "could not set stdout to fd %i", fd); + } + return samtools_stdout; +} + +void samtools_set_stdout_fn(const char *fn) +{ + samtools_stdout_fn = fn; +} + +void samtools_close_stdout(void) +{ + fclose(samtools_stdout); + samtools_stdout = NULL; +} + +int samtools_puts(const char *s) +{ + if (fputs(s, samtools_stdout) == EOF) return EOF; + return putc('\n', samtools_stdout); +} + + +static jmp_buf samtools_jmpbuf; +static int samtools_status = 0; + +int samtools_dispatch(int argc, char *argv[]) +{ + /* Reset getopt()/getopt_long() processing. */ +#if defined __GLIBC__ + optind = 0; +#elif defined _OPTRESET || defined _OPTRESET_DECLARED + optreset = optind = 1; +#else + optind = 1; +#endif + + if (setjmp(samtools_jmpbuf) == 0) + return samtools_main(argc, argv); + else + return samtools_status; +} + +void samtools_exit(int status) +{ + samtools_status = status; + longjmp(samtools_jmpbuf, 1); +} diff --git a/shared/package-files/3a/3acf1a363ce54417d018a6e84fa693f221d5feb32d2c457a42b477b31a3c9dfc/test_writers.cpython-311.pyc b/shared/package-files/3a/3acf1a363ce54417d018a6e84fa693f221d5feb32d2c457a42b477b31a3c9dfc/test_writers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46a4352df7b0bb18de2b95b986c5c7959c7ab1d4 Binary files /dev/null and b/shared/package-files/3a/3acf1a363ce54417d018a6e84fa693f221d5feb32d2c457a42b477b31a3c9dfc/test_writers.cpython-311.pyc differ diff --git a/shared/package-files/3a/3acfac25038523fd006e1f10974e6cd11b5faee93836c48c7e0ec1b6e8313208/hsa_helpers.hpp b/shared/package-files/3a/3acfac25038523fd006e1f10974e6cd11b5faee93836c48c7e0ec1b6e8313208/hsa_helpers.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0c1708502219abcafef174f434c3be20d61f6e96 --- /dev/null +++ b/shared/package-files/3a/3acfac25038523fd006e1f10974e6cd11b5faee93836c48c7e0ec1b6e8313208/hsa_helpers.hpp @@ -0,0 +1,102 @@ +/* +Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +#pragma once + +#include + +#include +#include +#include + +namespace hip_impl { +inline void* address(hsa_executable_symbol_t x) { + void* r = nullptr; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS, &r); + + return r; +} + +inline hsa_agent_t agent(hsa_executable_symbol_t x) { + hsa_agent_t r = {}; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_AGENT, &r); + + return r; +} + +inline std::uint32_t group_size(hsa_executable_symbol_t x) { + std::uint32_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE, &r); + + return r; +} + +inline hsa_isa_t isa(hsa_agent_t x) { + hsa_isa_t r = {}; + hsa_agent_iterate_isas(x, + [](hsa_isa_t i, void* o) { + *static_cast(o) = i; // Pick the first. + + return HSA_STATUS_INFO_BREAK; + }, + &r); + + return r; +} + +inline std::uint64_t kernel_object(hsa_executable_symbol_t x) { + std::uint64_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &r); + + return r; +} + +inline std::string name(hsa_executable_symbol_t x) { + std::uint32_t sz = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH, &sz); + + std::string r(sz, '\0'); + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_NAME, &r.front()); + + return r; +} + +inline std::uint32_t private_size(hsa_executable_symbol_t x) { + std::uint32_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE, &r); + + return r; +} + +inline std::uint32_t size(hsa_executable_symbol_t x) { + std::uint32_t r = 0; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE, &r); + + return r; +} + +inline hsa_symbol_kind_t type(hsa_executable_symbol_t x) { + hsa_symbol_kind_t r = {}; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_TYPE, &r); + + return r; +} +} // namespace hip_impl \ No newline at end of file diff --git a/shared/package-files/3a/3ad17dfb868f0aa1a899dbe02ca0090049d1c74de1cf73ba295cad5f33378af3/_sfdp_pattern_11.py b/shared/package-files/3a/3ad17dfb868f0aa1a899dbe02ca0090049d1c74de1cf73ba295cad5f33378af3/_sfdp_pattern_11.py new file mode 100644 index 0000000000000000000000000000000000000000..d8119c33ed93b8534270e8ea85410e94a549d027 --- /dev/null +++ b/shared/package-files/3a/3ad17dfb868f0aa1a899dbe02ca0090049d1c74de1cf73ba295cad5f33378af3/_sfdp_pattern_11.py @@ -0,0 +1,203 @@ +# mypy: ignore-errors + +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_11_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_11_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_11_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_11_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/shared/package-files/3a/3ad5857196e320baa3920afc9fb7bda918dcc1c4c40fe57b21ff80bf97335fc0/printing.cpython-311.pyc b/shared/package-files/3a/3ad5857196e320baa3920afc9fb7bda918dcc1c4c40fe57b21ff80bf97335fc0/printing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b53f563c25006e9bcf1c48b9be42d92e430e41 Binary files /dev/null and b/shared/package-files/3a/3ad5857196e320baa3920afc9fb7bda918dcc1c4c40fe57b21ff80bf97335fc0/printing.cpython-311.pyc differ diff --git a/shared/package-files/3a/3ad8fc6d241aaa51413c4bddad31a8f358ffc1293a576a24e190f483d45ab588/__init__.py b/shared/package-files/3a/3ad8fc6d241aaa51413c4bddad31a8f358ffc1293a576a24e190f483d45ab588/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4feeda1e59fb9a5089f7df871d1c8b29a2cd3835 --- /dev/null +++ b/shared/package-files/3a/3ad8fc6d241aaa51413c4bddad31a8f358ffc1293a576a24e190f483d45ab588/__init__.py @@ -0,0 +1,77 @@ +from torch.utils.data.dataloader import ( + _DatasetKind, + DataLoader, + default_collate, + default_convert, + get_worker_info, +) +from torch.utils.data.datapipes._decorator import ( + argument_validation, + functional_datapipe, + guaranteed_datapipes_determinism, + non_deterministic, + runtime_validation, + runtime_validation_disabled, +) +from torch.utils.data.datapipes.datapipe import ( + DataChunk, + DFIterDataPipe, + IterDataPipe, + MapDataPipe, +) +from torch.utils.data.dataset import ( + ChainDataset, + ConcatDataset, + Dataset, + IterableDataset, + random_split, + StackDataset, + Subset, + TensorDataset, +) +from torch.utils.data.distributed import DistributedSampler +from torch.utils.data.sampler import ( + BatchSampler, + RandomSampler, + Sampler, + SequentialSampler, + SubsetRandomSampler, + WeightedRandomSampler, +) + + +__all__ = [ + "BatchSampler", + "ChainDataset", + "ConcatDataset", + "DFIterDataPipe", + "DataChunk", + "DataLoader", + "Dataset", + "DistributedSampler", + "IterDataPipe", + "IterableDataset", + "MapDataPipe", + "RandomSampler", + "Sampler", + "SequentialSampler", + "StackDataset", + "Subset", + "SubsetRandomSampler", + "TensorDataset", + "WeightedRandomSampler", + "_DatasetKind", + "argument_validation", + "default_collate", + "default_convert", + "functional_datapipe", + "get_worker_info", + "guaranteed_datapipes_determinism", + "non_deterministic", + "random_split", + "runtime_validation", + "runtime_validation_disabled", +] + +# Please keep this list sorted +assert __all__ == sorted(__all__) diff --git a/shared/package-files/3a/3adec21b8baf3986cb9d277a470860e598360f2e292e92c87fe6bed0dd3ae1dd/_efficient_attention_forward_native.h b/shared/package-files/3a/3adec21b8baf3986cb9d277a470860e598360f2e292e92c87fe6bed0dd3ae1dd/_efficient_attention_forward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7522d8baa78c9b734fcd1b71a9d21ab89e8424f9 --- /dev/null +++ b/shared/package-files/3a/3adec21b8baf3986cb9d277a470860e598360f2e292e92c87fe6bed0dd3ae1dd/_efficient_attention_forward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _efficient_attention_forward(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & bias, const ::std::optional & cu_seqlens_q, const ::std::optional & cu_seqlens_k, ::std::optional max_seqlen_q, ::std::optional max_seqlen_k, double dropout_p, int64_t custom_mask_type, bool compute_log_sumexp=false, ::std::optional scale=::std::nullopt, const ::std::optional & seqlen_k={}, ::std::optional window_size=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/3a/3ae0d3fabfad2772c9b57316ba1d42234060aecb317faa8f0a886b2ef8e6dc27/utils.cpython-311.pyc b/shared/package-files/3a/3ae0d3fabfad2772c9b57316ba1d42234060aecb317faa8f0a886b2ef8e6dc27/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6cd4b2a37ed371b979bf629ab2ee38491a1f9a7 Binary files /dev/null and b/shared/package-files/3a/3ae0d3fabfad2772c9b57316ba1d42234060aecb317faa8f0a886b2ef8e6dc27/utils.cpython-311.pyc differ diff --git a/shared/package-files/3a/3ae11d80aff3cee456a39fef7ccfd5853a285409b50574c19145b12e463ace55/__init__.py b/shared/package-files/3a/3ae11d80aff3cee456a39fef7ccfd5853a285409b50574c19145b12e463ace55/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..263908eff68bab7c7d9a123bd77a5f5c048b8c5a --- /dev/null +++ b/shared/package-files/3a/3ae11d80aff3cee456a39fef7ccfd5853a285409b50574c19145b12e463ace55/__init__.py @@ -0,0 +1,9 @@ +from .autocast_mode import ( + _enter_autocast, + _exit_autocast, + autocast, + custom_bwd, + custom_fwd, + is_autocast_available, +) +from .grad_scaler import GradScaler diff --git a/shared/package-files/3a/3ae3c45f98dd131df4e94bcccf557da47a4d152a6f65c07a7191b717015a337a/htscodecs_bundled.mk b/shared/package-files/3a/3ae3c45f98dd131df4e94bcccf557da47a4d152a6f65c07a7191b717015a337a/htscodecs_bundled.mk new file mode 100644 index 0000000000000000000000000000000000000000..6274350f52e8f461413fbacf7d35ca9db03e5af9 --- /dev/null +++ b/shared/package-files/3a/3ae3c45f98dd131df4e94bcccf557da47a4d152a6f65c07a7191b717015a337a/htscodecs_bundled.mk @@ -0,0 +1,72 @@ +# Makefile fragment to add settings needed when bundling htscodecs functions +# +# Copyright (C) 2021-2022 Genome Research Ltd. +# +# Author: Rob Davies +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + + +HTSCODECS_SOURCES = $(HTSPREFIX)htscodecs/htscodecs/arith_dynamic.c \ + $(HTSPREFIX)htscodecs/htscodecs/fqzcomp_qual.c \ + $(HTSPREFIX)htscodecs/htscodecs/htscodecs.c \ + $(HTSPREFIX)htscodecs/htscodecs/pack.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static4x16pr.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static32x16pr_avx2.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static32x16pr_avx512.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static32x16pr_sse4.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static32x16pr_neon.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static32x16pr.c \ + $(HTSPREFIX)htscodecs/htscodecs/rANS_static.c \ + $(HTSPREFIX)htscodecs/htscodecs/rle.c \ + $(HTSPREFIX)htscodecs/htscodecs/tokenise_name3.c \ + $(HTSPREFIX)htscodecs/htscodecs/utils.c + + +HTSCODECS_OBJS = $(HTSCODECS_SOURCES:.c=.o) + +# htscodecs public headers +htscodecs_arith_dynamic_h = htscodecs/htscodecs/arith_dynamic.h +htscodecs_fqzcomp_qual_h = htscodecs/htscodecs/fqzcomp_qual.h +htscodecs_htscodecs_h = htscodecs/htscodecs/htscodecs.h $(htscodecs_version_h) +htscodecs_pack_h = htscodecs/htscodecs/pack.h +htscodecs_rANS_static_h = htscodecs/htscodecs/rANS_static.h +htscodecs_rANS_static4x16_h = htscodecs/htscodecs/rANS_static4x16.h +htscodecs_rle_h = htscodecs/htscodecs/rle.h +htscodecs_tokenise_name3_h = htscodecs/htscodecs/tokenise_name3.h +htscodecs_varint_h = htscodecs/htscodecs/varint.h + +# htscodecs internal headers +htscodecs_htscodecs_endian_h = htscodecs/htscodecs/htscodecs_endian.h +htscodecs_c_range_coder_h = htscodecs/htscodecs/c_range_coder.h +htscodecs_c_simple_model_h = htscodecs/htscodecs/c_simple_model.h $(htscodecs_c_range_coder_h) +htscodecs_permute_h = htscodecs/htscodecs/permute.h +htscodecs_pooled_alloc_h = htscodecs/htscodecs/pooled_alloc.h +htscodecs_rANS_byte_h = htscodecs/htscodecs/rANS_byte.h +htscodecs_rANS_static16_int_h = htscodecs/htscodecs/rANS_static16_int.h $(htscodecs_varint_h) $(htscodecs_utils_h) +htscodecs_rANS_static32x16pr_h = htscodecs/htscodecs/rANS_static32x16pr.h +htscodecs_rANS_word_h = htscodecs/htscodecs/rANS_word.h $(htscodecs_htscodecs_endian_h) +htscodecs_utils_h = htscodecs/htscodecs/utils.h +htscodecs_version_h = htscodecs/htscodecs/version.h + +# Add htscodecs tests into the HTSlib test framework + +HTSCODECS_TEST_TARGETS = test_htscodecs_rans4x8 \ + test_htscodecs_rans4x16 test_htscodecs_arith test_htscodecs_tok3 \ + test_htscodecs_fqzcomp test_htscodecs_varint diff --git a/shared/package-files/3a/3ae529c6bb5a7edab6bb67f7234a4bd3ef520319cc2aab2d6de8be34e0ba73d0/embedding_sparse_backward_ops.h b/shared/package-files/3a/3ae529c6bb5a7edab6bb67f7234a4bd3ef520319cc2aab2d6de8be34e0ba73d0/embedding_sparse_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d4f0e72d000a5be2ce469eb794f39e5535770298 --- /dev/null +++ b/shared/package-files/3a/3ae529c6bb5a7edab6bb67f7234a4bd3ef520319cc2aab2d6de8be34e0ba73d0/embedding_sparse_backward_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API embedding_sparse_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::embedding_sparse_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor"; + static at::Tensor call(const at::Tensor & grad, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3a/3ae56942bd8d131650dfa165e515b8726fb6b03177fc280485b3fedd6db18d43/test_online.py b/shared/package-files/3a/3ae56942bd8d131650dfa165e515b8726fb6b03177fc280485b3fedd6db18d43/test_online.py new file mode 100644 index 0000000000000000000000000000000000000000..14d3a39107bc4de7ee3d39e3a5968ab381bc1569 --- /dev/null +++ b/shared/package-files/3a/3ae56942bd8d131650dfa165e515b8726fb6b03177fc280485b3fedd6db18d43/test_online.py @@ -0,0 +1,103 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Series, +) +import pandas._testing as tm + +pytestmark = pytest.mark.single_cpu + +pytest.importorskip("numba") + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +class TestEWM: + def test_invalid_update(self): + df = DataFrame({"a": range(5), "b": range(5)}) + online_ewm = df.head(2).ewm(0.5).online() + with pytest.raises( + ValueError, + match="Must call mean with update=None first before passing update", + ): + online_ewm.mean(update=df.head(1)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")] + ) + def test_online_vs_non_online_mean( + self, obj, nogil, parallel, nopython, adjust, ignore_na + ): + expected = obj.ewm(0.5, adjust=adjust, ignore_na=ignore_na).mean() + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + + online_ewm = ( + obj.head(2) + .ewm(0.5, adjust=adjust, ignore_na=ignore_na) + .online(engine_kwargs=engine_kwargs) + ) + # Test resetting once + for _ in range(2): + result = online_ewm.mean() + tm.assert_equal(result, expected.head(2)) + + result = online_ewm.mean(update=obj.tail(3)) + tm.assert_equal(result, expected.tail(3)) + + online_ewm.reset() + + @pytest.mark.xfail(raises=NotImplementedError) + @pytest.mark.parametrize( + "obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")] + ) + def test_update_times_mean( + self, obj, nogil, parallel, nopython, adjust, ignore_na, halflife_with_times + ): + times = Series( + np.array( + ["2020-01-01", "2020-01-05", "2020-01-07", "2020-01-17", "2020-01-21"], + dtype="datetime64[ns]", + ) + ) + expected = obj.ewm( + 0.5, + adjust=adjust, + ignore_na=ignore_na, + times=times, + halflife=halflife_with_times, + ).mean() + + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + online_ewm = ( + obj.head(2) + .ewm( + 0.5, + adjust=adjust, + ignore_na=ignore_na, + times=times.head(2), + halflife=halflife_with_times, + ) + .online(engine_kwargs=engine_kwargs) + ) + # Test resetting once + for _ in range(2): + result = online_ewm.mean() + tm.assert_equal(result, expected.head(2)) + + result = online_ewm.mean(update=obj.tail(3), update_times=times.tail(3)) + tm.assert_equal(result, expected.tail(3)) + + online_ewm.reset() + + @pytest.mark.parametrize("method", ["aggregate", "std", "corr", "cov", "var"]) + def test_ewm_notimplementederror_raises(self, method): + ser = Series(range(10)) + kwargs = {} + if method == "aggregate": + kwargs["func"] = lambda x: x + + with pytest.raises(NotImplementedError, match=".* is not implemented."): + getattr(ser.ewm(1).online(), method)(**kwargs) diff --git a/shared/package-files/3a/3ae6980fcc2495fb111908bd9d91ba12f1071ac8a7a425c062ad66bc1ced35d8/Event.h b/shared/package-files/3a/3ae6980fcc2495fb111908bd9d91ba12f1071ac8a7a425c062ad66bc1ced35d8/Event.h new file mode 100644 index 0000000000000000000000000000000000000000..b94db9f4f26d0bad670b1b1b0c2d508a42943615 --- /dev/null +++ b/shared/package-files/3a/3ae6980fcc2495fb111908bd9d91ba12f1071ac8a7a425c062ad66bc1ced35d8/Event.h @@ -0,0 +1,137 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace c10 { + +/** + * A backend-generic movable, not copyable, not thread-safe event. + * + * The design of this event follows that of CUDA and HIP events. These events + * are recorded and waited on by streams and can be rerecorded to, + * each rerecording essentially creating a new version of the event. + * For example, if (in CPU time), stream X is asked to record E, + * stream Y waits on E, and stream X is asked to record E again, then Y will + * wait for X to finish the first call to record and not the second, because + * it's waiting on the first version of event E, not the second. + * Querying an event only returns the status of its most recent version. + * + * Backend-generic events are implemented by this class and + * impl::InlineEvent. In addition to these events there are also + * some backend-specific events, like ATen's CUDAEvent. Each of these + * classes has its own use. + * + * impl::InlineEvent<...> or a backend-specific event should be + * preferred when the backend is known at compile time and known to + * be compiled. Backend-specific events may have additional functionality. + * + * This Event should be used if a particular backend may not be available, + * or the backend required is not known at compile time. + * + * These generic events are built on top of DeviceGuardImpls, analogous + * to DeviceGuard and InlineDeviceGuard. The name "DeviceGuardImpls," + * is no longer entirely accurate, as these classes implement the + * backend-specific logic for a generic backend interface. + * + * See DeviceGuardImplInterface.h for a list of all supported flags. + */ + +struct Event final { + // Constructors + Event() = delete; + Event( + const DeviceType _device_type, + const EventFlag _flag = EventFlag::PYTORCH_DEFAULT) + : impl_{_device_type, _flag} {} + + // Copy constructor and copy assignment operator (deleted) + Event(const Event&) = delete; + Event& operator=(const Event&) = delete; + + // Move constructor and move assignment operator + Event(Event&&) noexcept = default; + Event& operator=(Event&&) noexcept = default; + + // Destructor + ~Event() = default; + + // Getters + Device device() const noexcept { + return Device(device_type(), device_index()); + } + DeviceType device_type() const noexcept { + return impl_.device_type(); + } + DeviceIndex device_index() const noexcept { + return impl_.device_index(); + } + EventFlag flag() const noexcept { + return impl_.flag(); + } + bool was_marked_for_recording() const noexcept { + return impl_.was_marked_for_recording(); + } + + /** + * Calls record() if and only if record() has never been called for this + * event. Note: because Event is not thread-safe recordOnce() may call + * record() multiple times if called from multiple threads. + */ + void recordOnce(const Stream& stream) { + impl_.recordOnce(stream); + } + + /** + * Increments the event's version and enqueues a job with this version + * in the stream's work queue. When the stream process that job + * it notifies all streams waiting on / blocked by that version of the + * event to continue and marks that version as recorded. + * */ + void record(const Stream& stream) { + impl_.record(stream); + } + + /** + * Does nothing if the event has not been scheduled to be recorded. + * If the event was previously enqueued to be recorded, a command + * to wait for the version of the event that exists at the time of this call + * is inserted in the stream's work queue. + * When the stream reaches this command it will stop processing + * additional commands until that version of the event is marked as recorded. + */ + void block(const Stream& stream) const { + impl_.block(stream); + } + + /** + * Returns true if (and only if) + * (1) the event has never been scheduled to be recorded + * (2) the current version is marked as recorded. + * Returns false otherwise. + */ + bool query() const { + return impl_.query(); + } + + double elapsedTime(const Event& event) const { + return impl_.elapsedTime(event.impl_); + } + + void* eventId() const { + return impl_.eventId(); + } + + void synchronize() const { + return impl_.synchronize(); + } + + private: + impl::InlineEvent impl_; +}; + +} // namespace c10 diff --git a/shared/package-files/3a/3ae7fe8ec40a0b49635f0b4853615a843326e009db5c043d64f5512c391c07e1/__config__.py b/shared/package-files/3a/3ae7fe8ec40a0b49635f0b4853615a843326e009db5c043d64f5512c391c07e1/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..7178014c55cf87c471d1f510854c64ef51fbd6e8 --- /dev/null +++ b/shared/package-files/3a/3ae7fe8ec40a0b49635f0b4853615a843326e009db5c043d64f5512c391c07e1/__config__.py @@ -0,0 +1,162 @@ +# This file is generated by numpy's build process +# It contains system_info results at the time of building this package. +from enum import Enum +from numpy.core._multiarray_umath import ( + __cpu_features__, + __cpu_baseline__, + __cpu_dispatch__, +) + +__all__ = ["show"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)} + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.2.1", + "commands": r"cc", + "args": r"-fno-strict-aliasing", + "linker args": r"-Wl,--strip-debug, -fno-strict-aliasing", + }, + "cython": { + "name": "cython", + "linker": r"cython", + "version": "3.0.8", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.2.1", + "commands": r"c++", + "args": r"", + "linker args": r"-Wl,--strip-debug", + }, + }, + "Machine Information": { + "host": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "linux", + }, + "build": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "linux", + }, + "cross-compiled": bool("False".lower().replace("false", "")), + }, + "Build Dependencies": { + "blas": { + "name": "openblas64", + "found": bool("True".lower().replace("false", "")), + "version": "0.3.23.dev", + "detection method": "pkgconfig", + "include directory": r"/usr/local/include", + "lib directory": r"/usr/local/lib", + "openblas configuration": r"USE_64BITINT=1 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS= NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= HASWELL MAX_THREADS=2", + "pc file directory": r"/usr/local/lib/pkgconfig", + }, + "lapack": { + "name": "dep140213194937296", + "found": bool("True".lower().replace("false", "")), + "version": "1.26.4", + "detection method": "internal", + "include directory": r"unknown", + "lib directory": r"unknown", + "openblas configuration": r"unknown", + "pc file directory": r"unknown", + }, + }, + "Python Information": { + "path": r"/opt/python/cp311-cp311/bin/python", + "version": "3.11", + }, + "SIMD Extensions": { + "baseline": __cpu_baseline__, + "found": [ + feature for feature in __cpu_dispatch__ if __cpu_features__[feature] + ], + "not found": [ + feature for feature in __cpu_dispatch__ if not __cpu_features__[feature] + ], + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which NumPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + See Also + -------- + get_include : Returns the directory containing NumPy C + header files. + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) diff --git a/shared/package-files/3a/3ae9165e837a6e04650bea7c0856e150dd06d2e0096ffce8b359823da82c7272/cuda_bf16.hpp b/shared/package-files/3a/3ae9165e837a6e04650bea7c0856e150dd06d2e0096ffce8b359823da82c7272/cuda_bf16.hpp new file mode 100644 index 0000000000000000000000000000000000000000..55568d4e4dd07a42b616593c621637f56a030f69 --- /dev/null +++ b/shared/package-files/3a/3ae9165e837a6e04650bea7c0856e150dd06d2e0096ffce8b359823da82c7272/cuda_bf16.hpp @@ -0,0 +1,3865 @@ +/* +* Copyright 1993-2024 NVIDIA Corporation. All rights reserved. +* +* NOTICE TO LICENSEE: +* +* This source code and/or documentation ("Licensed Deliverables") are +* subject to NVIDIA intellectual property rights under U.S. and +* international Copyright laws. +* +* These Licensed Deliverables contained herein is PROPRIETARY and +* CONFIDENTIAL to NVIDIA and is being provided under the terms and +* conditions of a form of NVIDIA software license agreement by and +* between NVIDIA and Licensee ("License Agreement") or electronically +* accepted by Licensee. Notwithstanding any terms or conditions to +* the contrary in the License Agreement, reproduction or disclosure +* of the Licensed Deliverables to any third party without the express +* written consent of NVIDIA is prohibited. +* +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE +* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS +* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. +* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED +* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, +* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY +* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY +* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +* OF THESE LICENSED DELIVERABLES. +* +* U.S. Government End Users. These Licensed Deliverables are a +* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT +* 1995), consisting of "commercial computer software" and "commercial +* computer software documentation" as such terms are used in 48 +* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government +* only as a commercial end item. Consistent with 48 C.F.R.12.212 and +* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all +* U.S. Government End Users acquire the Licensed Deliverables with +* only those rights set forth herein. +* +* Any use of the Licensed Deliverables in individual and commercial +* software must include, in the user documentation and internal +* comments to the code, the above Disclaimer and U.S. Government End +* Users Notice. +*/ + +#if !defined(__CUDA_BF16_HPP__) +#define __CUDA_BF16_HPP__ + +#if !defined(__CUDA_BF16_H__) +#error "Do not include this file directly. Instead, include cuda_bf16.h." +#endif + +#if !defined(IF_DEVICE_OR_CUDACC) +#if defined(__CUDACC__) + #define IF_DEVICE_OR_CUDACC(d, c, f) NV_IF_ELSE_TARGET(NV_IS_DEVICE, d, c) +#else + #define IF_DEVICE_OR_CUDACC(d, c, f) NV_IF_ELSE_TARGET(NV_IS_DEVICE, d, f) +#endif +#endif + +/* All other definitions in this file are only visible to C++ compilers */ +#if defined(__cplusplus) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines floating-point positive infinity value for the \p nv_bfloat16 data type + */ +#define CUDART_INF_BF16 __ushort_as_bfloat16((unsigned short)0x7F80U) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines canonical NaN value for the \p nv_bfloat16 data type + */ +#define CUDART_NAN_BF16 __ushort_as_bfloat16((unsigned short)0x7FFFU) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines a minimum representable (denormalized) value for the \p nv_bfloat16 data type + */ +#define CUDART_MIN_DENORM_BF16 __ushort_as_bfloat16((unsigned short)0x0001U) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines a maximum representable value for the \p nv_bfloat16 data type + */ +#define CUDART_MAX_NORMAL_BF16 __ushort_as_bfloat16((unsigned short)0x7F7FU) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines a negative zero value for the \p nv_bfloat16 data type + */ +#define CUDART_NEG_ZERO_BF16 __ushort_as_bfloat16((unsigned short)0x8000U) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines a positive zero value for the \p nv_bfloat16 data type + */ +#define CUDART_ZERO_BF16 __ushort_as_bfloat16((unsigned short)0x0000U) +/** + * \ingroup CUDA_MATH_INTRINSIC_BFLOAT16_CONSTANTS + * \brief Defines a value of 1.0 for the \p nv_bfloat16 data type + */ +#define CUDART_ONE_BF16 __ushort_as_bfloat16((unsigned short)0x3F80U) + +#if !(defined __DOXYGEN_ONLY__) + + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(const __nv_bfloat16_raw &hr) { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ volatile __nv_bfloat16 &__nv_bfloat16::operator=(const __nv_bfloat16_raw &hr) volatile { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ volatile __nv_bfloat16 &__nv_bfloat16::operator=(const volatile __nv_bfloat16_raw &hr) volatile { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator __nv_bfloat16_raw() const { __nv_bfloat16_raw ret; ret.x = __x; return ret; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator __nv_bfloat16_raw() const volatile { __nv_bfloat16_raw ret; ret.x = __x; return ret; } + +#if !defined(__CUDA_NO_BFLOAT16_CONVERSIONS__) + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator float() const { return __bfloat162float(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(const float f) { __x = __float2bfloat16(f).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(const double f) { __x = __double2bfloat16(f).__x; return *this; } + +/* + * Implicit type conversions to/from integer types were only available to nvcc compilation. + * Introducing them for all compilers is a potentially breaking change that may affect + * overloads resolution and will require users to update their code. + * Define __CUDA_BF16_DISABLE_IMPLICIT_INTEGER_CONVERTS_FOR_HOST_COMPILERS__ to opt-out. + */ +#if !(defined __CUDA_BF16_DISABLE_IMPLICIT_INTEGER_CONVERTS_FOR_HOST_COMPILERS__) || (defined __CUDACC__) + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator signed char() const { return __bfloat162char_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator unsigned char() const { return __bfloat162uchar_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator char() const { + char value; + /* Suppress VS warning: warning C4127: conditional expression is constant */ +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (((char)-1) < (char)0) +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + { + value = static_cast(__bfloat162char_rz(*this)); + } + else + { + value = static_cast(__bfloat162uchar_rz(*this)); + } + return value; + } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator short() const { return __bfloat162short_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator unsigned short() const { return __bfloat162ushort_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator int() const { return __bfloat162int_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator unsigned int() const { return __bfloat162uint_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator long() const { + long retval; + /* Suppress VS warning: warning C4127: conditional expression is constant */ +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(long) == sizeof(long long)) +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + { + retval = static_cast(__bfloat162ll_rz(*this)); + } + else + { + retval = static_cast(__bfloat162int_rz(*this)); + } + return retval; + } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator unsigned long() const { + unsigned long retval; + /* Suppress VS warning: warning C4127: conditional expression is constant */ +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long) == sizeof(unsigned long long)) +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + { + retval = static_cast(__bfloat162ull_rz(*this)); + } + else + { + retval = static_cast(__bfloat162uint_rz(*this)); + } + return retval; + } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator long long() const { return __bfloat162ll_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16::operator unsigned long long() const { return __bfloat162ull_rz(*this); } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(short val) { __x = __short2bfloat16_rn(val).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(unsigned short val) { __x = __ushort2bfloat16_rn(val).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(int val) { __x = __int2bfloat16_rn(val).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(unsigned int val) { __x = __uint2bfloat16_rn(val).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(long long val) { __x = __ll2bfloat16_rn(val).__x; return *this; } + __CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat16 &__nv_bfloat16::operator=(unsigned long long val) { __x = __ull2bfloat16_rn(val).__x; return *this; } +#endif /* !(defined __CUDA_BF16_DISABLE_IMPLICIT_INTEGER_CONVERTS_FOR_HOST_COMPILERS__) || (defined __CUDACC__) */ +#endif /* !defined(__CUDA_NO_BFLOAT16_CONVERSIONS__) */ + + +#if !defined(__CUDA_NO_BFLOAT16_OPERATORS__) +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator+(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hadd(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator-(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hsub(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator*(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hmul(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator/(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hdiv(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator+=(__nv_bfloat16 &lh, const __nv_bfloat16 &rh) { lh = __hadd(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator-=(__nv_bfloat16 &lh, const __nv_bfloat16 &rh) { lh = __hsub(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator*=(__nv_bfloat16 &lh, const __nv_bfloat16 &rh) { lh = __hmul(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator/=(__nv_bfloat16 &lh, const __nv_bfloat16 &rh) { lh = __hdiv(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator++(__nv_bfloat16 &h) { __nv_bfloat16_raw one; one.x = 0x3F80U; h += one; return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 &operator--(__nv_bfloat16 &h) { __nv_bfloat16_raw one; one.x = 0x3F80U; h -= one; return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator++(__nv_bfloat16 &h, const int ignored) +{ + // ignored on purpose. Parameter only needed to distinguish the function declaration from other types of operators. + static_cast(ignored); + + const __nv_bfloat16 ret = h; + __nv_bfloat16_raw one; + one.x = 0x3F80U; + h += one; + return ret; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator--(__nv_bfloat16 &h, const int ignored) +{ + // ignored on purpose. Parameter only needed to distinguish the function declaration from other types of operators. + static_cast(ignored); + + const __nv_bfloat16 ret = h; + __nv_bfloat16_raw one; + one.x = 0x3F80U; + h -= one; + return ret; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator+(const __nv_bfloat16 &h) { return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat16 operator-(const __nv_bfloat16 &h) { return __hneg(h); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator==(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __heq(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator!=(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hneu(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator> (const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hgt(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator< (const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hlt(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator>=(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hge(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator<=(const __nv_bfloat16 &lh, const __nv_bfloat16 &rh) { return __hle(lh, rh); } +#endif /* !defined(__CUDA_NO_BFLOAT16_OPERATORS__) */ + +#if defined(__CPP_VERSION_AT_LEAST_11_BF16) +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162::__nv_bfloat162(__nv_bfloat162 &&src) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = std::move(__BFLOAT162_TO_CUI(src)); +, + this->x = src.x; + this->y = src.y; +) +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162 &__nv_bfloat162::operator=(__nv_bfloat162 &&src) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = std::move(__BFLOAT162_TO_CUI(src)); +, + this->x = src.x; + this->y = src.y; +) + return *this; +} +#else +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162::__nv_bfloat162() { } +#endif /* defined(__CPP_VERSION_AT_LEAST_11_BF16) */ +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162::__nv_bfloat162(const __nv_bfloat162 &src) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = __BFLOAT162_TO_CUI(src); +, + this->x = src.x; + this->y = src.y; +) +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162 &__nv_bfloat162::operator=(const __nv_bfloat162 &src) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = __BFLOAT162_TO_CUI(src); +, + this->x = src.x; + this->y = src.y; +) + return *this; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162::__nv_bfloat162(const __nv_bfloat162_raw &h2r ) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = __BFLOAT162_TO_CUI(h2r); +, + __nv_bfloat16_raw tr; + tr.x = h2r.x; + this->x = static_cast<__nv_bfloat16>(tr); + tr.x = h2r.y; + this->y = static_cast<__nv_bfloat16>(tr); +) +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162 &__nv_bfloat162::operator=(const __nv_bfloat162_raw &h2r) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __BFLOAT162_TO_UI(*this) = __BFLOAT162_TO_CUI(h2r); +, + __nv_bfloat16_raw tr; + tr.x = h2r.x; + this->x = static_cast<__nv_bfloat16>(tr); + tr.x = h2r.y; + this->y = static_cast<__nv_bfloat16>(tr); +) + return *this; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_INLINE__ __nv_bfloat162::operator __nv_bfloat162_raw() const { + __nv_bfloat162_raw ret; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + ret.x = 0U; + ret.y = 0U; + __BFLOAT162_TO_UI(ret) = __BFLOAT162_TO_CUI(*this); +, + ret.x = static_cast<__nv_bfloat16_raw>(this->x).x; + ret.y = static_cast<__nv_bfloat16_raw>(this->y).x; +) + return ret; +} + +#if !defined(__CUDA_NO_BFLOAT162_OPERATORS__) +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator+(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hadd2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator-(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hsub2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator*(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hmul2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator/(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __h2div(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162& operator+=(__nv_bfloat162 &lh, const __nv_bfloat162 &rh) { lh = __hadd2(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162& operator-=(__nv_bfloat162 &lh, const __nv_bfloat162 &rh) { lh = __hsub2(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162& operator*=(__nv_bfloat162 &lh, const __nv_bfloat162 &rh) { lh = __hmul2(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162& operator/=(__nv_bfloat162 &lh, const __nv_bfloat162 &rh) { lh = __h2div(lh, rh); return lh; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 &operator++(__nv_bfloat162 &h) { __nv_bfloat162_raw one; one.x = 0x3F80U; one.y = 0x3F80U; h = __hadd2(h, one); return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 &operator--(__nv_bfloat162 &h) { __nv_bfloat162_raw one; one.x = 0x3F80U; one.y = 0x3F80U; h = __hsub2(h, one); return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator++(__nv_bfloat162 &h, const int ignored) +{ + // ignored on purpose. Parameter only needed to distinguish the function declaration from other types of operators. + static_cast(ignored); + + const __nv_bfloat162 ret = h; + __nv_bfloat162_raw one; + one.x = 0x3F80U; + one.y = 0x3F80U; + h = __hadd2(h, one); + return ret; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator--(__nv_bfloat162 &h, const int ignored) +{ + // ignored on purpose. Parameter only needed to distinguish the function declaration from other types of operators. + static_cast(ignored); + + const __nv_bfloat162 ret = h; + __nv_bfloat162_raw one; + one.x = 0x3F80U; + one.y = 0x3F80U; + h = __hsub2(h, one); + return ret; +} +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator+(const __nv_bfloat162 &h) { return h; } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ __nv_bfloat162 operator-(const __nv_bfloat162 &h) { return __hneg2(h); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator==(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hbeq2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator!=(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hbneu2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator>(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hbgt2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator<(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hblt2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator>=(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hbge2(lh, rh); } +__CUDA_HOSTDEVICE__ __CUDA_BF16_FORCEINLINE__ bool operator<=(const __nv_bfloat162 &lh, const __nv_bfloat162 &rh) { return __hble2(lh, rh); } +#endif /* !defined(__CUDA_NO_BFLOAT162_OPERATORS__) */ + +/* Restore warning for multiple assignment operators */ +#if defined(_MSC_VER) && _MSC_VER >= 1500 +#pragma warning( pop ) +#endif /* defined(_MSC_VER) && _MSC_VER >= 1500 */ + +/* Restore -Weffc++ warnings from here on */ +#if defined(__GNUC__) +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) +#pragma GCC diagnostic pop +#endif /* __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) */ +#endif /* defined(__GNUC__) */ + +#undef __CUDA_HOSTDEVICE__ +#undef __CUDA_ALIGN__ + +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __internal_float_as_uint(const float f) +{ + unsigned int u; +IF_DEVICE_OR_CUDACC( + u = __float_as_uint(f); +, + memcpy(&u, &f, sizeof(f)); +, + std::memcpy(&u, &f, sizeof(f)); +) + return u; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ float __internal_uint_as_float(const unsigned int u) +{ + float f; +IF_DEVICE_OR_CUDACC( + f = __uint_as_float(u); +, + memcpy(&f, &u, sizeof(u)); +, + std::memcpy(&f, &u, sizeof(u)); +) + return f; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned short __internal_float2bfloat16(const float f, unsigned int &sign, unsigned int &remainder) +{ + unsigned int x; + + x = __internal_float_as_uint(f); + + if ((x & 0x7fffffffU) > 0x7f800000U) { + sign = 0U; + remainder = 0U; + return static_cast(0x7fffU); + } + sign = x >> 31U; + remainder = x << 16U; + return static_cast(x >> 16U); +} + +__CUDA_HOSTDEVICE_BF16_DECL__ float __internal_double2float_rn(const double x) +{ + float r; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("cvt.rn.f32.f64 %0, %1;" : "=f"(r) : "d"(x)); +, + r = static_cast(x); +) + return r; +} +__CUDA_HOSTDEVICE_BF16_DECL__ double __internal_float2double(const float x) +{ + double r; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("cvt.f64.f32 %0, %1;" : "=d"(r) : "f"(x)); +, + r = static_cast(x); +) + return r; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __double2bfloat16(const double x) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("{ cvt.rn.bf16.f64 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "d"(x)); + return val; +, + float f = __internal_double2float_rn(x); + const double d = __internal_float2double(f); + unsigned int u = __internal_float_as_uint(f); + + bool x_is_not_nan = ((u << (unsigned)1U) <= (unsigned)0xFF000000U); + + + if ((x > 0.0) && (d > x)) { + u--; + } + if ((x < 0.0) && (d < x)) { + u--; + } + if ((d != x) && x_is_not_nan) { + u |= 1U; + } + + f = __internal_uint_as_float(u); + + return __float2bfloat16(f); +) +} + +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __float2bfloat16(const float a) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{ cvt.rn.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); +, + __nv_bfloat16_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __float2bfloat16_rn(const float a) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{ cvt.rn.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); +, + __nv_bfloat16_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __float2bfloat16_rz(const float a) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{ cvt.rz.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); +, + __nv_bfloat16_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2bfloat16(a, sign, remainder); + val = r; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __float2bfloat16_rd(const float a) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("{ cvt.rm.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); + return val; +, + __nv_bfloat16 val; + __nv_bfloat16_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder != 0U) && (sign != 0U)) { + r.x++; + } + val = r; + return val; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __float2bfloat16_ru(const float a) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("{ cvt.rp.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); + return val; +, + __nv_bfloat16 val; + __nv_bfloat16_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder != 0U) && (sign == 0U)) { + r.x++; + } + val = r; + return val; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __float2bfloat162_rn(const float a) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{.reg .b16 low;\n" + " cvt.rn.bf16.f32 low, %1;\n" + " mov.b32 %0, {low,low};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "f"(a)); +, + val = __nv_bfloat162(__float2bfloat16_rn(a), __float2bfloat16_rn(a)); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __floats2bfloat162_rn(const float a, const float b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{ cvt.rn.bf16x2.f32 %0, %2, %1;}\n" + : "=r"(__BFLOAT162_TO_UI(val)) : "f"(a), "f"(b)); +, + val = __nv_bfloat162(__float2bfloat16_rn(a), __float2bfloat16_rn(b)); +) + return val; +} + +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ float __internal_device_bfloat162float(const unsigned short h) +{ + float f; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("{ cvt.f32.bf16 %0, %1;}\n" : "=f"(f) : "h"(h)); +, + asm("{ mov.b32 %0, {0,%1};}\n" : "=f"(f) : "h"(h)); +) + return f; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ + +__CUDA_HOSTDEVICE_BF16_DECL__ float __internal_bfloat162float(const unsigned short h) +{ + float f; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + f = __internal_device_bfloat162float(h); +, + unsigned int u = static_cast(h) << 16; + f = __internal_uint_as_float(u); +) + return f; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ float __bfloat162float(const __nv_bfloat16 a) +{ + return __internal_bfloat162float(static_cast<__nv_bfloat16_raw>(a).x); +} +__CUDA_HOSTDEVICE_BF16_DECL__ float __low2float(const __nv_bfloat162 a) +{ + return __internal_bfloat162float(static_cast<__nv_bfloat162_raw>(a).x); +} + +__CUDA_HOSTDEVICE_BF16_DECL__ float __high2float(const __nv_bfloat162 a) +{ + return __internal_bfloat162float(static_cast<__nv_bfloat162_raw>(a).y); +} + +/* CUDA vector-types compatible vector creation function (note returns __nv_bfloat162, not nv_bfloat162) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 make_bfloat162(const __nv_bfloat16 x, const __nv_bfloat16 y) +{ + __nv_bfloat162 t; t.x = x; t.y = y; return t; +} + +/* Definitions of intrinsics */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __float22bfloat162_rn(const float2 a) +{ + __nv_bfloat162 val = __floats2bfloat162_rn(a.x, a.y); + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ float2 __bfloat1622float2(const __nv_bfloat162 a) +{ + float hi_float; + float lo_float; + lo_float = __internal_bfloat162float(((__nv_bfloat162_raw)a).x); + hi_float = __internal_bfloat162float(((__nv_bfloat162_raw)a).y); + return make_float2(lo_float, hi_float); +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ int __bfloat162int_rn(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + int val; + asm("{ cvt.rni.s32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); + return val; +, + return __float2int_rn(__bfloat162float(h)); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ + +__CUDA_HOSTDEVICE_BF16_DECL__ int __internal_bfloat162int_rz(const __nv_bfloat16 h) +{ + const float f = __bfloat162float(h); + int i; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + i = __float2int_rz(f); +, + const int max_val = (int)0x7fffffffU; + const int min_val = (int)0x80000000U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = 0; + } else if (f >= static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + i = static_cast(f); + } +) + return i; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ int __bfloat162int_rz(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + int val; + asm("{ cvt.rzi.s32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); + return val; +, + return __internal_bfloat162int_rz(h); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ int __bfloat162int_rd(const __nv_bfloat16 h) +{ + int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("{ cvt.rmi.s32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rmi.s32.f32 %0, %1;" : "=r"(val) : "f"(f)); +) + return val; +} +__CUDA_BF16_DECL__ int __bfloat162int_ru(const __nv_bfloat16 h) +{ + int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("{ cvt.rpi.s32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rpi.s32.f32 %0, %1;" : "=r"(val) : "f"(f)); +) + return val; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_int2bfloat16_rn(const int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rn.bf16.s32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + const float ru = __int2float_ru(i); + const float rd = __int2float_rd(i); + float rz = __int2float_rz(i); + if (ru != rd) { + rz = __uint_as_float(__float_as_uint(rz) | 1U); + } + return __float2bfloat16_rn(rz); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __int2bfloat16_rn(const int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_int2bfloat16_rn(i); +, + const double d = static_cast(i); + return __double2bfloat16(d); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ signed char __bfloat162char_rz(const __nv_bfloat16 h) +{ + signed char i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned short tmp = 0; + asm("{ .reg.b8 myreg;\n" + " cvt.rzi.s8.bf16 myreg, %1;\n" + " mov.b16 %0, {myreg, 0};\n}" + :"=h"(tmp) : "h"(__BFLOAT16_TO_CUS(h))); + const unsigned char u = static_cast(tmp); + i = static_cast(u); +, + const float f = __bfloat162float(h); + const signed char max_val = (signed char)0x7fU; + const signed char min_val = (signed char)0x80U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = 0; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + // normal value, conversion is well-defined + i = static_cast(f); + } +) + return i; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned char __bfloat162uchar_rz(const __nv_bfloat16 h) +{ + unsigned char i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned short tmp = 0; + asm("{ .reg.b8 myreg;\n" + " cvt.rzi.u8.bf16 myreg, %1;\n" + " mov.b16 %0, {myreg, 0};\n}" + :"=h"(tmp) : "h"(__BFLOAT16_TO_CUS(h))); + i = static_cast(tmp); +, + const float f = __bfloat162float(h); + const unsigned char max_val = 0xffU; + const unsigned char min_val = 0U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = 0U; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + // normal value, conversion is well-defined + i = static_cast(f); + } +) + return i; +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __int2bfloat16_rz(const int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rz.bf16.s32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_rz(__int2float_rz(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __int2bfloat16_rd(const int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rm.bf16.s32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_rd(__int2float_rd(i)); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat16 __int2bfloat16_ru(const int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rp.bf16.s32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_ru(__int2float_ru(i)); +) +} + +__CUDA_BF16_DECL__ short int __bfloat162short_rn(const __nv_bfloat16 h) +{ + short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rni.s16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rni.s16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} + +__CUDA_BF16_DECL__ short int __internal_device_bfloat162short_rz(const __nv_bfloat16 h) +{ + short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rzi.s16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rzi.s16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ short int __bfloat162short_rz(const __nv_bfloat16 h) +{ + short int val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + val = __internal_device_bfloat162short_rz(h); +, + const float f = __bfloat162float(h); + const short int max_val = (short int)0x7fffU; + const short int min_val = (short int)0x8000U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + val = 0; + } else if (f > static_cast(max_val)) { + // saturate maximum + val = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + val = min_val; + } else { + val = static_cast(f); + } +) + return val; +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ short int __bfloat162short_rd(const __nv_bfloat16 h) +{ + short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rmi.s16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rmi.s16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +__CUDA_BF16_DECL__ short int __bfloat162short_ru(const __nv_bfloat16 h) +{ + short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rpi.s16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rpi.s16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __short2bfloat16_rn(const short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rn.bf16.s16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + const float f = static_cast(i); + return __float2bfloat16_rn(f); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __short2bfloat16_rz(const short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rz.bf16.s16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_rz(__int2float_rz(static_cast(i))); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __short2bfloat16_rd(const short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rm.bf16.s16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_rd(__int2float_rd(static_cast(i))); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __short2bfloat16_ru(const short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rp.bf16.s16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_ru(__int2float_ru(static_cast(i))); +) +} + +__CUDA_BF16_DECL__ unsigned int __bfloat162uint_rn(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned int val; + asm("{ cvt.rni.u32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); + return val; +, + return __float2uint_rn(__bfloat162float(h)); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __internal_bfloat162uint_rz(const __nv_bfloat16 h) +{ + const float f = __bfloat162float(h); + unsigned int i; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + i = __float2uint_rz(f); +, + const unsigned int max_val = 0xffffffffU; + const unsigned int min_val = 0U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = 0U; + } else if (f >= static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + i = static_cast(f); + } +) + return i; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __bfloat162uint_rz(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned int val; + asm("{ cvt.rzi.u32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); + return val; +, + return __internal_bfloat162uint_rz(h); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ unsigned int __bfloat162uint_rd(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned int val; + asm("{ cvt.rmi.u32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); + return val; +, + return __float2uint_rd(__bfloat162float(h)); +) +} +__CUDA_BF16_DECL__ unsigned int __bfloat162uint_ru(const __nv_bfloat16 h) +{ + unsigned int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("{ cvt.rpi.u32.bf16 %0, %1;}\n" : "=r"(val) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rpi.u32.f32 %0, %1;" : "=r"(val) : "f"(f)); +) + return val; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_uint2bfloat16_rn(const unsigned int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rn.bf16.u32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + const float ru = __uint2float_ru(i); + const float rd = __uint2float_rd(i); + float rz = __uint2float_rz(i); + if (ru != rd) { + rz = __uint_as_float(__float_as_uint(rz) | 1U); + } + return __float2bfloat16_rn(rz); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __uint2bfloat16_rn(const unsigned int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_uint2bfloat16_rn(i); +, + const double d = static_cast(i); + return __double2bfloat16(d); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __uint2bfloat16_rz(const unsigned int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rz.bf16.u32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_rz(__uint2float_rz(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __uint2bfloat16_rd(const unsigned int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rm.bf16.u32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_rd(__uint2float_rd(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __uint2bfloat16_ru(const unsigned int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rp.bf16.u32 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "r"(i)); + return val; +, + return __float2bfloat16_ru(__uint2float_ru(i)); +) +} + +__CUDA_BF16_DECL__ unsigned short int __bfloat162ushort_rn(const __nv_bfloat16 h) +{ + unsigned short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rni.u16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rni.u16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} + +__CUDA_BF16_DECL__ unsigned short int __internal_device_bfloat162ushort_rz(const __nv_bfloat16 h) +{ + unsigned short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rzi.u16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rzi.u16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned short int __bfloat162ushort_rz(const __nv_bfloat16 h) +{ + unsigned short int val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + val = __internal_device_bfloat162ushort_rz(h); +, + const float f = __bfloat162float(h); + const unsigned short int max_val = 0xffffU; + const unsigned short int min_val = 0U; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + val = 0U; + } else if (f > static_cast(max_val)) { + // saturate maximum + val = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + val = min_val; + } else { + val = static_cast(f); + } +) + return val; +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ unsigned short int __bfloat162ushort_rd(const __nv_bfloat16 h) +{ + unsigned short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rmi.u16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rmi.u16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +__CUDA_BF16_DECL__ unsigned short int __bfloat162ushort_ru(const __nv_bfloat16 h) +{ + unsigned short int val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rpi.u16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +, + asm("{ .reg.f32 f;\n" + " mov.b32 f, {0,%1};\n" + " cvt.rpi.u16.f32 %0,f;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(h))); +) + return val; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __ushort2bfloat16_rn(const unsigned short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rn.bf16.u16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + const float f = static_cast(i); + return __float2bfloat16_rn(f); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __ushort2bfloat16_rz(const unsigned short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rz.bf16.u16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_rz(__uint2float_rz(static_cast(i))); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ushort2bfloat16_rd(const unsigned short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rm.bf16.u16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_rd(__uint2float_rd(static_cast(i))); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ushort2bfloat16_ru(const unsigned short int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 val; + asm("cvt.rp.bf16.u16 %0, %1;" : "=h"(__BFLOAT16_TO_US(val)) : "h"(i)); + return val; +, + return __float2bfloat16_ru(__uint2float_ru(static_cast(i))); +) +} + +__CUDA_BF16_DECL__ unsigned long long int __bfloat162ull_rn(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned long long int i; + asm("cvt.rni.u64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); + return i; +, + return __float2ull_rn(__bfloat162float(h)); +) +} + +__CUDA_BF16_DECL__ unsigned long long int __internal_device_bfloat162ull_rz(const __nv_bfloat16 h) +{ + unsigned long long int i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rzi.u64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + i = __float2ull_rz(f); +) + return i; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned long long int __bfloat162ull_rz(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_bfloat162ull_rz(h); +, + const float f = __bfloat162float(h); + unsigned long long int i; + const unsigned long long int max_val = 0xffffffffffffffffULL; + const unsigned long long int min_val = 0ULL; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = 0x8000000000000000ULL; + } else if (f >= static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + i = static_cast(f); + } + return i; +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ unsigned long long int __bfloat162ull_rd(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + unsigned long long int i; + asm("cvt.rmi.u64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); + return i; +, + return __float2ull_rd(__bfloat162float(h)); +) +} +__CUDA_BF16_DECL__ unsigned long long int __bfloat162ull_ru(const __nv_bfloat16 h) +{ + unsigned long long int i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rpi.u64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rpi.u64.f32 %0, %1;" : "=l"(i) : "f"(f)); +) + return i; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_ull2bfloat16_rn(const unsigned long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rn.bf16.u64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + const float ru = __ull2float_ru(i); + const float rd = __ull2float_rd(i); + float rz = __ull2float_rz(i); + if (ru != rd) { + rz = __uint_as_float(__float_as_uint(rz) | 1U); + } + return __float2bfloat16_rn(rz); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __ull2bfloat16_rn(const unsigned long long int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_ull2bfloat16_rn(i); +, + float f = static_cast(i); + const unsigned long long int uf = static_cast(f); + unsigned int u = __internal_float_as_uint(f); + // round up happened here + // note: no need to handle round up to f == 0x1.p64 specially + if (uf > i) { + u--; + } + if (uf != i) { + u |= 1U; + } + f = __internal_uint_as_float(u); + return __float2bfloat16_rn(f); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __ull2bfloat16_rz(const unsigned long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rz.bf16.u64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_rz(__ull2float_rz(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ull2bfloat16_rd(const unsigned long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rm.bf16.u64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_rd(__ull2float_rd(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ull2bfloat16_ru(const unsigned long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rp.bf16.u64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_ru(__ull2float_ru(i)); +) +} +__CUDA_BF16_DECL__ long long int __bfloat162ll_rn(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + long long int i; + asm("cvt.rni.s64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); + return i; +, + return __float2ll_rn(__bfloat162float(h)); +) +} + +__CUDA_BF16_DECL__ long long int __internal_device_bfloat162ll_rz(const __nv_bfloat16 h) +{ + long long int i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rzi.s64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + i = __float2ll_rz(f); +) + return i; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ long long int __bfloat162ll_rz(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_bfloat162ll_rz(h); +, + long long int i; + const float f = __bfloat162float(h); + const long long int max_val = (long long int)0x7fffffffffffffffULL; + const long long int min_val = (long long int)0x8000000000000000ULL; + const unsigned short bits = static_cast(static_cast<__nv_bfloat16_raw>(h).x << 1U); + // saturation fixup + if (bits > (unsigned short)0xFF00U) { + // NaN + i = min_val; + } else if (f >= static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } else { + i = static_cast(f); + } + return i; +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ long long int __bfloat162ll_rd(const __nv_bfloat16 h) +{ + long long int i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rmi.s64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rmi.s64.f32 %0, %1;" : "=l"(i) : "f"(f)); +) + return i; +} +__CUDA_BF16_DECL__ long long int __bfloat162ll_ru(const __nv_bfloat16 h) +{ + long long int i; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("cvt.rpi.s64.bf16 %0, %1;" : "=l"(i) : "h"(__BFLOAT16_TO_CUS(h))); +, + const float f = __bfloat162float(h); + asm("cvt.rpi.s64.f32 %0, %1;" : "=l"(i) : "f"(f)); +) + return i; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_ll2bfloat16_rn(const long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rn.bf16.s64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + const float ru = __ll2float_ru(i); + const float rd = __ll2float_rd(i); + float rz = __ll2float_rz(i); + if (ru != rd) { + rz = __uint_as_float(__float_as_uint(rz) | 1U); + } + return __float2bfloat16_rn(rz); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __ll2bfloat16_rn(const long long int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_ll2bfloat16_rn(i); +, + float f = static_cast(i); + const long long int lf = static_cast(f); + unsigned int u = __internal_float_as_uint(f); + + if ((f > 0.0f) && (lf > i)) { + u--; + } + if ((f < 0.0f) && (lf < i)) { + u--; + } + if (lf != i) { + u |= 1U; + } + + f = __internal_uint_as_float(u); + return __float2bfloat16_rn(f); +) +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __ll2bfloat16_rz(const long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rz.bf16.s64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_rz(__ll2float_rz(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ll2bfloat16_rd(const long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rm.bf16.s64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_rd(__ll2float_rd(i)); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ll2bfloat16_ru(const long long int i) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 h; + asm("cvt.rp.bf16.s64 %0, %1;" : "=h"(__BFLOAT16_TO_US(h)) : "l"(i)); + return h; +, + return __float2bfloat16_ru(__ll2float_ru(i)); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat16 htrunc(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm("cvt.rzi.bf16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(h))); + return r; +, + return __float2bfloat16_rz(truncf(__bfloat162float(h))); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 hceil(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm("cvt.rpi.bf16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(h))); + return r; +, + float fh = __bfloat162float(h); + asm( "{ cvt.rpi.f32.f32 %0, %0; }\n" + :"+f"(fh)); + return __float2bfloat16_rz(fh); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 hfloor(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm("cvt.rmi.bf16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(h))); + return r; +, + float fh = __bfloat162float(h); + asm( "{ cvt.rmi.f32.f32 %0, %0; }\n" + :"+f"(fh)); + return __float2bfloat16_rz(fh); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 hrint(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm("cvt.rni.bf16.bf16 %0, %1;" : "=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(h))); + return r; +, + return __float2bfloat16_rz(rintf(__bfloat162float(h))); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat162 h2trunc(const __nv_bfloat162 h) +{ + const __nv_bfloat16 low = htrunc(h.x); + const __nv_bfloat16 high = htrunc(h.y); + return __nv_bfloat162(low, high); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2ceil(const __nv_bfloat162 h) +{ + const __nv_bfloat16 low = hceil(h.x); + const __nv_bfloat16 high = hceil(h.y); + return __nv_bfloat162(low, high); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2floor(const __nv_bfloat162 h) +{ + const __nv_bfloat16 low = hfloor(h.x); + const __nv_bfloat16 high = hfloor(h.y); + return __nv_bfloat162(low, high); +} + +__CUDA_BF16_DECL__ __nv_bfloat162 h2rint(const __nv_bfloat162 h) +{ + return __halves2bfloat162(hrint(__low2bfloat16(h)), hrint(__high2bfloat16(h))); +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __lows2bfloat162(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 alow,ahigh,blow,bhigh;\n" + " mov.b32 {alow,ahigh}, %1;\n" + " mov.b32 {blow,bhigh}, %2;\n" + " mov.b32 %0, {alow,blow};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)), "r"(__BFLOAT162_TO_CUI(b))); +, + val.x = a.x; + val.y = b.x; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __highs2bfloat162(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 alow,ahigh,blow,bhigh;\n" + " mov.b32 {alow,ahigh}, %1;\n" + " mov.b32 {blow,bhigh}, %2;\n" + " mov.b32 %0, {ahigh,bhigh};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)), "r"(__BFLOAT162_TO_CUI(b))); +, + val.x = a.y; + val.y = b.y; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __low2bfloat16(const __nv_bfloat162 a) +{ + __nv_bfloat16 ret; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b16 %0, low;}" : "=h"(__BFLOAT16_TO_US(ret)) : "r"(__BFLOAT162_TO_CUI(a))); +, + ret = a.x; +) + return ret; +} +__CUDA_HOSTDEVICE_BF16_DECL__ int __hisinf(const __nv_bfloat16 a) +{ + int retval; + const __nv_bfloat16_raw araw = __nv_bfloat16_raw(a); + if (araw.x == 0xFF80U) { + retval = -1; + } else if (araw.x == 0x7F80U) { + retval = 1; + } else { + retval = 0; + } + return retval; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __low2bfloat162(const __nv_bfloat162 a) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {low,low};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); +, + val.x = a.x; + val.y = a.x; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __high2bfloat162(const __nv_bfloat162 a) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {high,high};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); +, + val.x = a.y; + val.y = a.y; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __high2bfloat16(const __nv_bfloat162 a) +{ + __nv_bfloat16 ret; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b16 %0, high;}" : "=h"(__BFLOAT16_TO_US(ret)) : "r"(__BFLOAT162_TO_CUI(a))); +, + ret = a.y; +) + return ret; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __halves2bfloat162(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{ mov.b32 %0, {%1,%2};}\n" + : "=r"(__BFLOAT162_TO_UI(val)) : "h"(__BFLOAT16_TO_CUS(a)), "h"(__BFLOAT16_TO_CUS(b))); +, + val.x = a; + val.y = b; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __bfloat162bfloat162(const __nv_bfloat16 a) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{ mov.b32 %0, {%1,%1};}\n" + : "=r"(__BFLOAT162_TO_UI(val)) : "h"(__BFLOAT16_TO_CUS(a))); +, + val.x = a; + val.y = a; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __lowhigh2highlow(const __nv_bfloat162 a) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + asm("{.reg .b16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {high,low};}\n" : "=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); +, + val.x = a.y; + val.y = a.x; +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ short int __bfloat16_as_short(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return static_cast(__BFLOAT16_TO_CUS(h)); +, + return static_cast(__nv_bfloat16_raw(h).x); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned short int __bfloat16_as_ushort(const __nv_bfloat16 h) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __BFLOAT16_TO_CUS(h); +, + return __nv_bfloat16_raw(h).x; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __short_as_bfloat16(const short int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __nv_bfloat16 h; + __BFLOAT16_TO_US(h) = static_cast(i); + return h; +, + __nv_bfloat16_raw hr; + hr.x = static_cast(i); + return __nv_bfloat16(hr); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __ushort_as_bfloat16(const unsigned short int i) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __nv_bfloat16 h; + __BFLOAT16_TO_US(h) = i; + return h; +, + __nv_bfloat16_raw hr; + hr.x = i; + return __nv_bfloat16(hr); +) +} + +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 300))) || defined(_NVHPC_CUDA) +/****************************************************************************** +* __nv_bfloat16, __nv_bfloat162 warp shuffle * +******************************************************************************/ +#define __SHUFFLE_SYNC_BFLOAT162_MACRO(name, var, delta, c, mask) /* do */ {\ + __nv_bfloat162 r; \ + asm volatile ("{" __CUDA_BF16_STRINGIFY(name) " %0,%1,%2,%3,%4;\n}" \ + :"=r"(__BFLOAT162_TO_UI(r)): "r"(__BFLOAT162_TO_CUI(var)), "r"(delta), "r"(c), "r"(mask)); \ + return r; \ +} /* while(0) */ + +__CUDA_BF16_DECL__ __nv_bfloat162 __shfl_sync(const unsigned int mask, const __nv_bfloat162 var, const int srcLane, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_BFLOAT162_MACRO(shfl.sync.idx.b32, var, srcLane, c, mask) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __shfl_up_sync(const unsigned int mask, const __nv_bfloat162 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = (warp_size - static_cast(width)) << 8U; + __SHUFFLE_SYNC_BFLOAT162_MACRO(shfl.sync.up.b32, var, delta, c, mask) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __shfl_down_sync(const unsigned int mask, const __nv_bfloat162 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_BFLOAT162_MACRO(shfl.sync.down.b32, var, delta, c, mask) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __shfl_xor_sync(const unsigned int mask, const __nv_bfloat162 var, const int laneMask, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_BFLOAT162_MACRO(shfl.sync.bfly.b32, var, laneMask, c, mask) +} + +#undef __SHUFFLE_SYNC_BFLOAT162_MACRO + +__CUDA_BF16_DECL__ __nv_bfloat16 __shfl_sync(const unsigned int mask, const __nv_bfloat16 var, const int srcLane, const int width) +{ + const __nv_bfloat162 temp1 = __halves2bfloat162(var, var); + const __nv_bfloat162 temp2 = __shfl_sync(mask, temp1, srcLane, width); + return __low2bfloat16(temp2); +} +__CUDA_BF16_DECL__ __nv_bfloat16 __shfl_up_sync(const unsigned int mask, const __nv_bfloat16 var, const unsigned int delta, const int width) +{ + const __nv_bfloat162 temp1 = __halves2bfloat162(var, var); + const __nv_bfloat162 temp2 = __shfl_up_sync(mask, temp1, delta, width); + return __low2bfloat16(temp2); +} +__CUDA_BF16_DECL__ __nv_bfloat16 __shfl_down_sync(const unsigned int mask, const __nv_bfloat16 var, const unsigned int delta, const int width) +{ + const __nv_bfloat162 temp1 = __halves2bfloat162(var, var); + const __nv_bfloat162 temp2 = __shfl_down_sync(mask, temp1, delta, width); + return __low2bfloat16(temp2); +} +__CUDA_BF16_DECL__ __nv_bfloat16 __shfl_xor_sync(const unsigned int mask, const __nv_bfloat16 var, const int laneMask, const int width) +{ + const __nv_bfloat162 temp1 = __halves2bfloat162(var, var); + const __nv_bfloat162 temp2 = __shfl_xor_sync(mask, temp1, laneMask, width); + return __low2bfloat16(temp2); +} + +/****************************************************************************** +* __nv_bfloat16 and __nv_bfloat162 __ldg,__ldcg,__ldca,__ldcs * +******************************************************************************/ + +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __LDG_PTR "l" +#else +#define __LDG_PTR "r" +#endif /*(defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)*/ +__CUDA_BF16_DECL__ __nv_bfloat162 __ldg(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.nc.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldg(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.nc.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __ldcg(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.cg.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldcg(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.cg.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __ldca(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.ca.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldca(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.ca.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __ldcs(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.cs.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldcs(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.cs.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __ldlu(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.lu.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldlu(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.lu.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __ldcv(const __nv_bfloat162 *const ptr) +{ + __nv_bfloat162 ret; + asm ("ld.global.cv.b32 %0, [%1];" : "=r"(__BFLOAT162_TO_UI(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __ldcv(const __nv_bfloat16 *const ptr) +{ + __nv_bfloat16 ret; + asm ("ld.global.cv.b16 %0, [%1];" : "=h"(__BFLOAT16_TO_US(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} + +__CUDA_BF16_DECL__ void __stwb(__nv_bfloat162 *const ptr, const __nv_bfloat162 value) +{ + asm ("st.global.wb.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__BFLOAT162_TO_CUI(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stwb(__nv_bfloat16 *const ptr, const __nv_bfloat16 value) +{ + asm ("st.global.wb.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__BFLOAT16_TO_CUS(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stcg(__nv_bfloat162 *const ptr, const __nv_bfloat162 value) +{ + asm ("st.global.cg.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__BFLOAT162_TO_CUI(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stcg(__nv_bfloat16 *const ptr, const __nv_bfloat16 value) +{ + asm ("st.global.cg.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__BFLOAT16_TO_CUS(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stcs(__nv_bfloat162 *const ptr, const __nv_bfloat162 value) +{ + asm ("st.global.cs.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__BFLOAT162_TO_CUI(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stcs(__nv_bfloat16 *const ptr, const __nv_bfloat16 value) +{ + asm ("st.global.cs.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__BFLOAT16_TO_CUS(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stwt(__nv_bfloat162 *const ptr, const __nv_bfloat162 value) +{ + asm ("st.global.wt.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__BFLOAT162_TO_CUI(value)) : "memory"); +} +__CUDA_BF16_DECL__ void __stwt(__nv_bfloat16 *const ptr, const __nv_bfloat16 value) +{ + asm ("st.global.wt.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__BFLOAT16_TO_CUS(value)) : "memory"); +} + +#undef __LDG_PTR +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 300))) || defined(_NVHPC_CUDA) */ +/****************************************************************************** +* __nv_bfloat162 comparison * +******************************************************************************/ +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +#define __COMPARISON_OP_BFLOAT162_MACRO(name) {\ + __nv_bfloat162 val; \ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90,\ + asm( "{ " __CUDA_BF16_STRINGIFY(name) ".bf16x2.bf16x2 %0,%1,%2;\n}" \ + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); \ +,\ + asm( "{.reg .b32 low_a,low_b,high_a,high_b,high_res,low_res;\n"\ + " and.b32 high_a, %1, 0xffff0000U;\n"\ + " and.b32 high_b, %2, 0xffff0000U;\n"\ + " shl.b32 low_a, %1, 16;\n"\ + " shl.b32 low_b, %2, 16;\n"\ + " " __CUDA_BF16_STRINGIFY(name) ".f32.f32 low_res, low_a, low_b;\n"\ + " " __CUDA_BF16_STRINGIFY(name) ".f32.f32 high_res, high_a, high_b;\n"\ + " shr.u32 low_res, low_res, 16;\n"\ + " or.b32 %0, high_res, low_res;}\n"\ + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); \ +)\ + return val; \ +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_heq2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.eq) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hne2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.ne) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hle2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.le) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hge2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.ge) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hlt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.lt) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hgt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.gt) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hequ2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.equ) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hneu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.neu) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hleu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.leu) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hgeu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.geu) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hltu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.ltu) +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hgtu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __COMPARISON_OP_BFLOAT162_MACRO(set.gtu) +} +#undef __COMPARISON_OP_BFLOAT162_MACRO +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ + +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __heq2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_heq2(a, b); +, + __nv_bfloat162_raw val; + val.x = __heq(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __heq(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hne2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hne2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hne(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hne(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hle2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hle2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hle(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hle(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hge2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hge2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hge(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hge(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hlt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hlt2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hlt(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hlt(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hgt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hgt2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hgt(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hgt(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hequ2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hequ2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hequ(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hequ(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hneu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hneu2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hneu(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hneu(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hleu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hleu2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hleu(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hleu(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hgeu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hgeu2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hgeu(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hgeu(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hltu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hltu2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hltu(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hltu(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hgtu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hgtu2(a, b); +, + __nv_bfloat162_raw val; + val.x = __hgtu(a.x, b.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hgtu(a.y, b.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + return __nv_bfloat162(val); +) +} + +/****************************************************************************** +* __nv_bfloat162 comparison with mask output * +******************************************************************************/ +#define __COMPARISON_OP_BFLOAT162_MACRO_MASK(name) {\ + unsigned val; \ + asm( "{ " __CUDA_BF16_STRINGIFY(name) ".u32.bf16x2 %0,%1,%2;\n}" \ + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); \ + return val; \ +} + +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __heq2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.eq) +, + const unsigned short px = __heq(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __heq(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hne2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.ne) +, + const unsigned short px = __hne(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hne(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hle2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.le) +, + const unsigned short px = __hle(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hle(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hge2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.ge) +, + const unsigned short px = __hge(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hge(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hlt2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.lt) +, + const unsigned short px = __hlt(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hlt(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hgt2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.gt) +, + const unsigned short px = __hgt(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hgt(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hequ2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.equ) +, + const unsigned short px = __hequ(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hequ(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hneu2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.neu) +, + const unsigned short px = __hneu(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hneu(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hleu2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.leu) +, + const unsigned short px = __hleu(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hleu(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hgeu2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.geu) +, + const unsigned short px = __hgeu(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hgeu(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hltu2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.ltu) +, + const unsigned short px = __hltu(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hltu(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ unsigned int __hgtu2_mask(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __COMPARISON_OP_BFLOAT162_MACRO_MASK(set.gtu) +, + const unsigned short px = __hgtu(a.x, b.x) ? (unsigned short)0xFFFFU : (unsigned short)0U; + const unsigned short py = __hgtu(a.y, b.y) ? (unsigned short)0xFFFFU : (unsigned short)0U; + unsigned ur = (unsigned)py; + ur <<= (unsigned)16U; + ur |= (unsigned)px; + return ur; +) +} +#undef __COMPARISON_OP_BFLOAT162_MACRO_MASK + +#define __BOOL_COMPARISON_OP_BFLOAT162_MACRO(name) {\ + unsigned int val; \ + bool retval; \ + asm( "{ " __CUDA_BF16_STRINGIFY(name) ".bf16x2.bf16x2 %0,%1,%2;\n}" \ + :"=r"(val) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); \ + if (val == 0x3F803F80U) {\ + retval = true; \ + } else { \ + retval = false; \ + }\ + return retval;\ +} + +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbeq2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.eq) +, + return (__heq(a.x, b.x) && __heq(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbne2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.ne) +, + return (__hne(a.x, b.x) && __hne(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hble2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.le) +, + return (__hle(a.x, b.x) && __hle(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbge2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.ge) +, + return (__hge(a.x, b.x) && __hge(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hblt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.lt) +, + return (__hlt(a.x, b.x) && __hlt(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbgt2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.gt) +, + return (__hgt(a.x, b.x) && __hgt(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbequ2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.equ) +, + return (__hequ(a.x, b.x) && __hequ(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbneu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.neu) +, + return (__hneu(a.x, b.x) && __hneu(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbleu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.leu) +, + return (__hleu(a.x, b.x) && __hleu(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbgeu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.geu) +, + return (__hgeu(a.x, b.x) && __hgeu(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbltu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.ltu) +, + return (__hltu(a.x, b.x) && __hltu(a.y, b.y)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hbgtu2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __BOOL_COMPARISON_OP_BFLOAT162_MACRO(set.gtu) +, + return (__hgtu(a.x, b.x) && __hgtu(a.y, b.y)); +) +} +#undef __BOOL_COMPARISON_OP_BFLOAT162_MACRO +/****************************************************************************** +* __nv_bfloat16 comparison * +******************************************************************************/ +#define __COMPARISON_OP_BFLOAT16_MACRO(name) {\ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90,\ + unsigned short val; \ + asm( "{ .reg .pred __$temp3;\n" \ + " setp." __CUDA_BF16_STRINGIFY(name) ".bf16 __$temp3, %1, %2;\n" \ + " selp.u16 %0, 1, 0, __$temp3;}" \ + : "=h"(val) : "h"(__BFLOAT16_TO_CUS(a)), "h"(__BFLOAT16_TO_CUS(b))); \ + return (val != 0U) ? true : false; \ +,\ + unsigned int val; \ + asm( "{.reg .b32 a,b;\n"\ + " mov.b32 a, {0, %1};\n"\ + " mov.b32 b, {0, %2};\n"\ + " set." __CUDA_BF16_STRINGIFY(name) ".f32.f32 %0, a, b;}\n"\ + :"=r"(val) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); \ + return (val != 0U) ? true : false; \ +)\ +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __heq(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(eq) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa == fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hne(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(ne) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa != fb) && (!__hisnan(a)) && (!__hisnan(b)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hle(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(le) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa <= fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hge(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(ge) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa >= fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hlt(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(lt) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa < fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hgt(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(gt) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa > fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hequ(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(equ) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa == fb) || (__hisnan(a)) || (__hisnan(b)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hneu(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(neu) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa != fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hleu(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(leu) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa <= fb) || (__hisnan(a)) || (__hisnan(b)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hgeu(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(geu) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa >= fb) || (__hisnan(a)) || (__hisnan(b)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hltu(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(ltu) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa < fb) || (__hisnan(a)) || (__hisnan(b)); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hgtu(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __COMPARISON_OP_BFLOAT16_MACRO(gtu) +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return (fa > fb) || (__hisnan(a)) || (__hisnan(b)); +) +} +#undef __COMPARISON_OP_BFLOAT16_MACRO +/****************************************************************************** +* __nv_bfloat162 arithmetic * +******************************************************************************/ +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hadd2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ add.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0x3f803f80U;\n" + " fma.rn.bf16x2 %0,%1,c,%2;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} + +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hsub2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ sub.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0xbf80bf80U;\n" + " fma.rn.bf16x2 %0,%2,c,%1;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hmul2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ mul.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0x80008000U;\n" + " fma.rn.bf16x2 %0,%1,%2,c;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hadd2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ add.rn.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0x3f803f80U;\n" + " fma.rn.bf16x2 %0,%1,c,%2;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hsub2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ sub.rn.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0xbf80bf80U;\n" + " fma.rn.bf16x2 %0,%2,c,%1;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __internal_device_hmul2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ mul.rn.bf16x2 %0,%1,%2; }\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + asm( "{.reg .b32 c;\n" + " mov.b32 c, 0x80008000U;\n" + " fma.rn.bf16x2 %0,%1,%2,c;}\n" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +) + return val; +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hadd2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hadd2(a, b); +, + val.x = __hadd(a.x, b.x); + val.y = __hadd(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hsub2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hsub2(a, b); +, + val.x = __hsub(a.x, b.x); + val.y = __hsub(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmul2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hmul2(a, b); +, + val.x = __hmul(a.x, b.x); + val.y = __hmul(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hadd2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hadd2_rn(a, b); +, + val.x = __hadd_rn(a.x, b.x); + val.y = __hadd_rn(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hsub2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hsub2_rn(a, b); +, + val.x = __hsub_rn(a.x, b.x); + val.y = __hsub_rn(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmul2_rn(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_device_hmul2_rn(a, b); +, + val.x = __hmul_rn(a.x, b.x); + val.y = __hmul_rn(a.y, b.y); +) + return val; +} + +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hadd2_sat(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{.reg .b32 f, one, zero;\n" + " mov.b32 one, 0x3f803f80U;\n" + " mov.b32 zero, 0;\n" + " fma.rn.bf16x2 f,%1,one,%2;\n" + " max.bf16x2 f, f, zero;\n" + " min.bf16x2 %0, f, one;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + val.x = __hadd_sat(a.x, b.x); + val.y = __hadd_sat(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hsub2_sat(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{.reg .b32 f, one, zero, mone;\n" + " mov.b32 one, 0x3f803f80U;\n" + " mov.b32 zero, 0;\n" + " mov.b32 mone, 0xbf80bf80U;\n" + " fma.rn.bf16x2 f,%2,mone,%1;\n" + " max.bf16x2 f, f, zero;\n" + " min.bf16x2 %0, f, one;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + val.x = __hsub_sat(a.x, b.x); + val.y = __hsub_sat(a.y, b.y); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmul2_sat(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ + __nv_bfloat162 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{.reg .b32 f, one, zero, mzero;\n" + " mov.b32 one, 0x3f803f80U;\n" + " mov.b32 zero, 0;\n" + " mov.b32 mzero, 0x80008000U;\n" + " fma.rn.bf16x2 f,%1,%2,mzero;\n" + " max.bf16x2 f, f, zero;\n" + " min.bf16x2 %0, f, one;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); +, + val.x = __hmul_sat(a.x, b.x); + val.y = __hmul_sat(a.y, b.y); +) + return val; +} +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat162 __hfma2(const __nv_bfloat162 a, const __nv_bfloat162 b, const __nv_bfloat162 c) +{ + __nv_bfloat162 val; + asm( "{fma.rn.bf16x2 %0,%1,%2,%3;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b)),"r"(__BFLOAT162_TO_CUI(c))); + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat162 __hfma2_sat(const __nv_bfloat162 a, const __nv_bfloat162 b, const __nv_bfloat162 c) +{ + __nv_bfloat162 val; + asm( "{ .reg .b32 f, one, zero;\n" + " mov.b32 one, 0x3f803f80U;\n" + " mov.b32 zero, 0;\n" + " fma.rn.bf16x2 f, %1, %2, %3;\n" + " max.bf16x2 f, f, zero;\n" + " min.bf16x2 %0, f, one;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b)),"r"(__BFLOAT162_TO_CUI(c))); + return val; +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __h2div(const __nv_bfloat162 a, const __nv_bfloat162 b) { + __nv_bfloat16 ha, hb; + + ha = __low2bfloat16(a); + hb = __low2bfloat16(b); + + const __nv_bfloat16 v1 = __hdiv(ha, hb); + + ha = __high2bfloat16(a); + hb = __high2bfloat16(b); + + const __nv_bfloat16 v2 = __hdiv(ha, hb); + + return __halves2bfloat162(v1, v2); +} +/****************************************************************************** +* __nv_bfloat16 arithmetic * +******************************************************************************/ +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hadd(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ add.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0x3f80U;\n" + " fma.rn.bf16 %0,%1,c,%2;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hsub(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ sub.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0xbf80U;\n" + " fma.rn.bf16 %0,%2,c,%1;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hmul(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ mul.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0x8000U;\n" + " fma.rn.bf16 %0,%1,%2,c;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hadd_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ add.rn.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0x3f80U;\n" + " fma.rn.bf16 %0,%1,c,%2;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hsub_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ sub.rn.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0xbf80U;\n" + " fma.rn.bf16 %0,%2,c,%1;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_sm80_device_hmul_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm( "{ mul.rn.bf16 %0,%1,%2; }\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + asm( "{.reg .b16 c;\n" + " mov.b16 c, 0x8000U;\n" + " fma.rn.bf16 %0,%1,%2,c;}\n" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +) + return val; +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_hadd(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_sm80_device_hadd(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + // avoid ftz in device code + val = __float2bfloat16(__fmaf_ieee_rn(fa, 1.0f, fb)); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_hsub(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_sm80_device_hsub(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + // avoid ftz in device code + val = __float2bfloat16(__fmaf_ieee_rn(fb, -1.0f, fa)); +) + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_hmul(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + val = __internal_sm80_device_hmul(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + // avoid ftz in device code + val = __float2bfloat16(__fmaf_ieee_rn(fa, fb, -0.0f)); +) + return val; +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hadd(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hadd(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return __float2bfloat16(fa + fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hsub(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hsub(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return __float2bfloat16(fa - fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmul(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hmul(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return __float2bfloat16(fa * fb); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hadd_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + return __internal_sm80_device_hadd_rn(a, b); +, + return __hadd(a, b); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hsub_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + return __internal_sm80_device_hsub_rn(a, b); +, + return __hsub(a, b); + +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmul_rn(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + return __internal_sm80_device_hmul_rn(a, b); +, + return __hmul(a, b); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hadd_sat(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{ .reg .b16 f, one, zero;\n" + " mov.b16 one, 0x3f80U;\n" + " mov.b16 zero, 0;\n" + " fma.rn.bf16 f, %1, one, %2;\n" + " max.bf16 f, f, zero;\n" + " min.bf16 %0, f, one;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + val = __hmin(__hmax(__hadd(a, b), CUDART_ZERO_BF16), CUDART_ONE_BF16); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hsub_sat(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{ .reg .b16 f, one, zero, mone;\n" + " mov.b16 one, 0x3f80U;\n" + " mov.b16 zero, 0;\n" + " mov.b16 mone, 0xbf80U;\n" + " fma.rn.bf16 f, %2, mone, %1;\n" + " max.bf16 f, f, zero;\n" + " min.bf16 %0, f, one;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + val = __hmin(__hmax(__hsub(a, b), CUDART_ZERO_BF16), CUDART_ONE_BF16); +) + return val; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmul_sat(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ + __nv_bfloat16 val; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm( "{ .reg .b16 f, one, zero, mzero;\n" + " mov.b16 one, 0x3f80U;\n" + " mov.b16 zero, 0;\n" + " mov.b16 mzero, 0x8000U;\n" + " fma.rn.bf16 f, %1, %2, mzero;\n" + " max.bf16 f, f, zero;\n" + " min.bf16 %0, f, one;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); +, + val = __hmin(__hmax(__hmul(a, b), CUDART_ZERO_BF16), CUDART_ONE_BF16); +) + return val; +} +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __hfma(const __nv_bfloat16 a, const __nv_bfloat16 b, const __nv_bfloat16 c) +{ + __nv_bfloat16 val; + asm( "{fma.rn.bf16 %0,%1,%2,%3;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b)),"h"(__BFLOAT16_TO_CUS(c))); + return val; +} +__CUDA_BF16_DECL__ __nv_bfloat16 __hfma_sat(const __nv_bfloat16 a, const __nv_bfloat16 b, const __nv_bfloat16 c) +{ + __nv_bfloat16 val; + asm( "{ .reg .b16 f, one, zero;\n" + " mov.b16 one, 0x3f80U;\n" + " mov.b16 zero, 0;\n" + " fma.rn.bf16 f, %1, %2, %3;\n" + " max.bf16 f, f, zero;\n" + " min.bf16 %0, f, one;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b)),"h"(__BFLOAT16_TO_CUS(c))); + return val; +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +#define __BINARY_OP_BFLOAT16_MACRO(name) /* do */ {\ + __nv_bfloat16 val; \ + asm( "{.reg .b32 a,b,res;\n"\ + " mov.b32 a, {0,%1};\n"\ + " mov.b32 b, {0,%2};\n"\ + " " __CUDA_BF16_STRINGIFY(name) ".f32 res, a, b;\n"\ + " cvt.rn.bf16.f32 %0, res;}\n"\ + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); \ + return val; \ +} /* while(0) */ +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_hdiv(const __nv_bfloat16 a, const __nv_bfloat16 b) { + const float two_126 = __uint_as_float(0x7E800000U) ; //2^126 + const float a_f = __bfloat162float(a); + float b_f = __bfloat162float(b); + float ans; + bool b_big = (fabsf(b_f) >= two_126); + if(b_big){b_f *= 0.25f;} + + // f32 div approximation. Good enough for c-r bfloat div. + asm("{ div.approx.f32 %0, %1, %2; }" : "=f"(ans) : "f"(a_f), "f"(b_f)); + + // Prevent ftz: + if(b_big){ans = __fmaf_ieee_rn(ans, 0.25f, -0.0f);} + return __float2bfloat16(ans); +} + +#undef __BINARY_OP_BFLOAT16_MACRO +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hdiv(const __nv_bfloat16 a, const __nv_bfloat16 b) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hdiv(a, b); +, + const float fa = __bfloat162float(a); + const float fb = __bfloat162float(b); + return __float2bfloat16(fa / fb); +) +} + +/****************************************************************************** +* __nv_bfloat162 functions * +******************************************************************************/ +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __hsin_internal(const __nv_bfloat16 a) { + float f = __bfloat162float(a); + float r = sinf(f); + // Detect compile-time FTZ setting: + // if subnormal constant is not flushed to zero at compile-time, then + // ftz=off, and it is safe to return result of sinf() + // Otherwise, ftz=on, then sinf() result is valid for non-flushed + // values, and subnormal input is returned unchanged via else + // branch. + if ((__uint_as_float(0x00000001U) > 0.0f) || (f != 0.0f)) + { + f = r; + } + return __float2bfloat16_rn(f); +} +__CUDA_BF16_DECL__ __nv_bfloat16 hsin(const __nv_bfloat16 a) { + return __hsin_internal(a); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2sin(const __nv_bfloat162 a) { + const __nv_bfloat16 l = __low2bfloat16(a); + const __nv_bfloat16 h = __high2bfloat16(a); + return __halves2bfloat162(__hsin_internal(l), __hsin_internal(h)); +} +__CUDA_BF16_DECL__ __nv_bfloat16 __hcos_internal(const __nv_bfloat16 a) { + float f = __bfloat162float(a); + f = cosf(f); + return __float2bfloat16_rn(f); +} +__CUDA_BF16_DECL__ __nv_bfloat16 hcos(const __nv_bfloat16 a) { + return __hcos_internal(a); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2cos(const __nv_bfloat162 a) { + const __nv_bfloat16 l = __low2bfloat16(a); + const __nv_bfloat16 h = __high2bfloat16(a); + return __halves2bfloat162(__hcos_internal(l), __hcos_internal(h)); +} + +__CUDA_BF16_DECL__ float __internal_device_fast_bf16exp(const float x) +{ + const float log2e_up = __uint_as_float(0x3FB8AA3CU); + float fa = x * log2e_up; + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fa)); + return fa; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hexp(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + fa = __internal_device_fast_bf16exp(fa); + return __float2bfloat16_rn(fa); +} + +#define __APPROX_FCAST2(fun) /* do */ {\ + __nv_bfloat162 val;\ + asm("{.reg.b16 hl, hu; \n"\ + " .reg.b32 fl, fu; \n"\ + " mov.b32 {hl, hu}, %1; \n"\ + " mov.b32 fl, {0,hl}; \n"\ + " mov.b32 fu, {0,hu}; \n"\ + " " __CUDA_BF16_STRINGIFY(fun) ".approx.f32 fl, fl; \n"\ + " " __CUDA_BF16_STRINGIFY(fun) ".approx.f32 fu, fu; \n"\ + " cvt.rn.bf16.f32 hl, fl; \n"\ + " cvt.rn.bf16.f32 hu, fu; \n"\ + " mov.b32 %0, {hl, hu}; \n"\ + "}":"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); \ + return val;\ +} /* while(0) */ +#define __BF16_SPEC_CASE2(i,r, spc, ulp) \ + "{.reg.b32 spc, ulp, p;\n"\ + " mov.b32 spc," __CUDA_BF16_STRINGIFY(spc) ";\n"\ + " mov.b32 ulp," __CUDA_BF16_STRINGIFY(ulp) ";\n"\ + " set.eq.f16x2.f16x2 p," __CUDA_BF16_STRINGIFY(i) ", spc;\n"\ + " fma.rn.bf16x2 " __CUDA_BF16_STRINGIFY(r) ",p,ulp," __CUDA_BF16_STRINGIFY(r) ";\n}\n" + +__CUDA_BF16_DECL__ __nv_bfloat162 h2exp(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 h,r,fl,fu, C; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " mov.b32 fl, {0,hl}; \n" + " mov.b32 fu, {0,hu}; \n" + " mov.b32 C, 0x3FB8AA3CU; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " ex2.approx.f32 fl, fl; \n" + " ex2.approx.f32 fu, fu; \n" + " cvt.rn.bf16.f32 hl, fl; \n" + " cvt.rn.bf16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + " mov.b32 %0, r; \n" + "}":"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); + return val; +, + return __floats2bfloat162_rn( __internal_device_fast_bf16exp(__low2float(a)), __internal_device_fast_bf16exp(__high2float(a)) ); +) +} + +__CUDA_BF16_DECL__ float __internal_device_tanhf_noftz(const float x) +{ + float f = x; + float r = tanhf(x); + // Detect compile-time FTZ setting: + // if subnormal constant is not flushed to zero at compile-time, then + // ftz=off, and it is safe to return result of tanhf() + // Otherwise, ftz=on, then tanhf() result is valid for non-flushed + // values, and subnormal input is returned unchanged via else + // branch. + if ((__uint_as_float(0x00000001U) > 0.0f) || (f != 0.0f)) + { + f = r; + } + return f; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 htanh(const __nv_bfloat16 a) { + float f = __bfloat162float(a); +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_75, + asm("{ tanh.approx.f32 %0, %0; }" : "+f"(f)); +, + f = __internal_device_tanhf_noftz(f); +) + __nv_bfloat16 h = __float2bfloat16_rn(f); + return h; +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2tanh(const __nv_bfloat162 a) { + float2 f = __bfloat1622float2(a); +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_75, + asm("{ tanh.approx.f32 %0, %0; }" : "+f"(f.x)); + asm("{ tanh.approx.f32 %0, %0; }" : "+f"(f.y)); +, + f.x = __internal_device_tanhf_noftz(f.x); + f.y = __internal_device_tanhf_noftz(f.y); +) + __nv_bfloat162 h = __float22bfloat162_rn(f); + return h; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 htanh_approx(const __nv_bfloat16 a) { + __nv_bfloat16 r; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16_raw hr = (__nv_bfloat16_raw)a; + asm("tanh.approx.bf16 %0, %0;" : "+h"(hr.x)); + r = (__nv_bfloat16)hr; +, + r = htanh(a); +) + return r; +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2tanh_approx(const __nv_bfloat162 a) { + __nv_bfloat162 res; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("tanh.approx.bf16x2 %0, %1;" : "=r"(__BFLOAT162_TO_UI(res)) : "r"(__BFLOAT162_TO_CUI(a))); +, + res = h2tanh(a); +) + return res; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hexp2(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fa)); + return __float2bfloat16_rn(fa); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2exp2(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __APPROX_FCAST2(ex2) +, + float fl = __low2float(a); + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fl)); + float fh = __high2float(a); + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fh)); + return __floats2bfloat162_rn( fl, fh ); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hexp10(const __nv_bfloat16 a) { + const float log10_2 = __uint_as_float(0x40549A78U); + float fa = __bfloat162float(a) * log10_2; + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fa)); + __nv_bfloat16 r = __float2bfloat16_rn(fa); + __nv_bfloat16_raw araw = static_cast<__nv_bfloat16_raw>(a); + if (araw.x == (unsigned short)0xBC95U) + { + araw.x = 0x3f75U; + r = static_cast<__nv_bfloat16>(araw); + } + return r; +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2exp10(const __nv_bfloat162 a) { + __nv_bfloat162 r; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 h,r,fl,fu, C; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 fl, {0,hl}; \n" + " mov.b32 fu, {0,hu}; \n" + " mov.b32 C, 0x40549A78U; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " ex2.approx.f32 fl, fl; \n" + " ex2.approx.f32 fu, fu; \n" + " cvt.rn.bf16.f32 hl, fl; \n" + " cvt.rn.bf16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __BF16_SPEC_CASE2(%1, r, 0xBC95BC95U,0xBF00BF00U) + " mov.b32 %0, r; \n" + "}":"=r"(__BFLOAT162_TO_UI(r)) : "r"(__BFLOAT162_TO_CUI(a))); +, + const float log10_2 = __uint_as_float(0x40549A78U); + float fl = __low2float(a) * log10_2; + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fl)); + + float fh = __high2float(a) * log10_2; + asm("{ ex2.approx.f32 %0, %0; }" : "+f"(fh)); + + r = __floats2bfloat162_rn( fl, fh ); + + const __nv_bfloat162_raw araw = static_cast<__nv_bfloat162_raw>(a); + if (araw.x == (unsigned short)0xBC95U) + { + __nv_bfloat16_raw raw_fix; + raw_fix.x = (unsigned short)0x3f75U; + r.x = static_cast<__nv_bfloat16>(raw_fix); + } + if (araw.y == (unsigned short)0xBC95U) + { + __nv_bfloat16_raw raw_fix; + raw_fix.x = (unsigned short)0x3f75U; + r.y = static_cast<__nv_bfloat16>(raw_fix); + } +) + return r; +} + +__CUDA_BF16_DECL__ float __internal_device_fast_bf16log2(float x) +{ + asm("{ lg2.approx.f32 %0, %0; }" : "+f"(x)); + return x; +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hlog2(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + fa = __internal_device_fast_bf16log2(fa); + return __float2bfloat16_rn(fa); +} + +__CUDA_BF16_DECL__ __nv_bfloat162 h2log2(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __APPROX_FCAST2(lg2) +, + float fl = __low2float(a); + fl = __internal_device_fast_bf16log2(fl); + float fh = __high2float(a); + fh = __internal_device_fast_bf16log2(fh); + return __floats2bfloat162_rn( fl, fh ); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hlog(const __nv_bfloat16 a) { + const float flt_ln2 = __uint_as_float(0x3f317218U); + float fa = __bfloat162float(a); + fa = __internal_device_fast_bf16log2(fa); + fa = fa * flt_ln2; + return __float2bfloat16_rn(fa); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2log(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 r, fl, fu, C, h; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " mov.b32 fl, {0,hl}; \n" + " mov.b32 fu, {0,hu}; \n" + " lg2.approx.f32 fl, fl; \n" + " lg2.approx.f32 fu, fu; \n" + " mov.b32 C, 0x3f317218U; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " cvt.rn.bf16.f32 hl, fl; \n" + " cvt.rn.bf16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + " mov.b32 %0, r; \n" + "}":"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); + return val; +, + const float flt_ln2 = __uint_as_float(0x3f317218U); + + float fl = __low2float(a); + fl = __internal_device_fast_bf16log2(fl); + fl = fl * flt_ln2; + + float fh = __high2float(a); + fh = __internal_device_fast_bf16log2(fh); + fh = fh * flt_ln2; + + return __floats2bfloat162_rn( fl, fh ); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat16 hlog10(const __nv_bfloat16 a) { + const float flt_log10_2 = __uint_as_float(0x3E9A209BU); + float fa = __bfloat162float(a); + fa = __internal_device_fast_bf16log2(fa); + fa = fa * flt_log10_2; + return __float2bfloat16_rn(fa); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2log10(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 r, fl, fu, C, h; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " mov.b32 fl, {0,hl}; \n" + " mov.b32 fu, {0,hu}; \n" + " lg2.approx.f32 fl, fl; \n" + " lg2.approx.f32 fu, fu; \n" + " mov.b32 C, 0x3E9A209BU; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " cvt.rn.bf16.f32 hl, fl; \n" + " cvt.rn.bf16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + " mov.b32 %0, r; \n" + "}":"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a))); + return val; +, + const float flt_log10_2 = __uint_as_float(0x3E9A209BU); + + float fl = __low2float(a); + fl = __internal_device_fast_bf16log2(fl); + fl = fl * flt_log10_2; + + float fh = __high2float(a); + fh = __internal_device_fast_bf16log2(fh); + fh = fh * flt_log10_2; + + return __floats2bfloat162_rn( fl, fh ); +) +} + +__CUDA_BF16_DECL__ __nv_bfloat162 h2rcp(const __nv_bfloat162 a) { + float fl = __low2float(a); + asm("{ rcp.approx.f32 %0, %0; }" : "+f"(fl)); + float fh = __high2float(a); + asm("{ rcp.approx.f32 %0, %0; }" : "+f"(fh)); + return __floats2bfloat162_rn( fl, fh ); +} +__CUDA_BF16_DECL__ __nv_bfloat16 hrcp(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + asm("{ rcp.approx.f32 %0, %0; }" : "+f"(fa)); + return __float2bfloat16_rn(fa); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2rsqrt(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __APPROX_FCAST2(rsqrt) +, + float fl = __low2float(a); + asm("{ rsqrt.approx.f32 %0, %0; }" : "+f"(fl)); + float fh = __high2float(a); + asm("{ rsqrt.approx.f32 %0, %0; }" : "+f"(fh)); + return __floats2bfloat162_rn( fl, fh ); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 hrsqrt(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + asm("{ rsqrt.approx.f32 %0, %0; }" : "+f"(fa)); + return __float2bfloat16_rn(fa); +} +__CUDA_BF16_DECL__ __nv_bfloat162 h2sqrt(const __nv_bfloat162 a) { +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __APPROX_FCAST2(sqrt) +, + float fl = __low2float(a); + asm("{ sqrt.approx.f32 %0, %0; }" : "+f"(fl)); + float fh = __high2float(a); + asm("{ sqrt.approx.f32 %0, %0; }" : "+f"(fh)); + return __floats2bfloat162_rn( fl, fh ); +) +} +__CUDA_BF16_DECL__ __nv_bfloat16 hsqrt(const __nv_bfloat16 a) { + float fa = __bfloat162float(a); + asm("{ sqrt.approx.f32 %0, %0; }" : "+f"(fa)); + return __float2bfloat16_rn(fa); +} +#undef __APPROX_FCAST2 +#undef __BF16_SPEC_CASE2 + +__CUDA_BF16_DECL__ bool __internal_device_hisnan(const __nv_bfloat16 a) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm("{set.nan.bf16.bf16 %0,%1,%1;\n}" + :"=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(a))); + return __BFLOAT16_TO_CUS(r) != 0U; +, + unsigned int r; + asm( "{.reg .b32 a;\n" + " mov.b32 a, {0,%1};\n" + " set.nan.f32.f32 %0, a, a;}\n" + :"=r"(r) : "h"(__BFLOAT16_TO_CUS(a))); + return r != 0U; +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hisnan2(const __nv_bfloat162 a) +{ + __nv_bfloat162 r; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + asm("{set.nan.bf16x2.bf16x2 %0,%1,%1;\n}" + :"=r"(__BFLOAT162_TO_UI(r)) : "r"(__BFLOAT162_TO_CUI(a))); +, + __nv_bfloat162_raw val; + val.x = __hisnan(a.x) ? (unsigned short)0x3F80U : (unsigned short)0U; + val.y = __hisnan(a.y) ? (unsigned short)0x3F80U : (unsigned short)0U; + r = __nv_bfloat162(val); +) + return r; +} +__CUDA_HOSTDEVICE_BF16_DECL__ bool __hisnan(const __nv_bfloat16 a) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hisnan(a); +, + const __nv_bfloat16_raw hr = static_cast<__nv_bfloat16_raw>(a); + return ((hr.x & 0x7FFFU) > 0x7F80U); +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hneg2(const __nv_bfloat162 a) +{ + __nv_bfloat162 r; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{neg.bf16x2 %0,%1;\n}" + :"=r"(__BFLOAT162_TO_UI(r)) : "r"(__BFLOAT162_TO_CUI(a))); +, + r.x = __hneg(a.x); + r.y = __hneg(a.y); +) + return r; +} +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __internal_device_hneg(const __nv_bfloat16 a) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 r; + asm("{neg.bf16 %0,%1;\n}" + :"=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(a))); + return r; +, + const float fa = __bfloat162float(a); + return __float2bfloat16(__fmaf_ieee_rn(fa, -1.0f, -0.0f)); +) +} +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hneg(const __nv_bfloat16 a) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + return __internal_device_hneg(a); +, + const float fa = __bfloat162float(a); + return __float2bfloat16(-fa); +) +} + +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __habs2(const __nv_bfloat162 a) +{ + __nv_bfloat162 r; +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + asm("{abs.bf16x2 %0,%1;\n}" + :"=r"(__BFLOAT162_TO_UI(r)) : "r"(__BFLOAT162_TO_CUI(a))); +, + r.x = __habs(a.x); + r.y = __habs(a.y); +) + return r; +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __habs(const __nv_bfloat16 a) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 r; + asm("{abs.bf16 %0,%1;\n}" + :"=h"(__BFLOAT16_TO_US(r)) : "h"(__BFLOAT16_TO_CUS(a))); + return r; +, + __nv_bfloat16_raw abs_a_raw = static_cast<__nv_bfloat16_raw>(a); + abs_a_raw.x &= (unsigned short)0x7FFFU; + if (abs_a_raw.x > (unsigned short)0x7F80U) + { + // return canonical NaN + abs_a_raw.x = (unsigned short)0x7FFFU; + } + return static_cast<__nv_bfloat16>(abs_a_raw); +) +} + +/****************************************************************************** +* __nv_bfloat16 arithmetic * +******************************************************************************/ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmax(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 val; + asm( "{ max.bf16 %0,%1,%2;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); + return val; +, + __nv_bfloat16 maxval; + + maxval = (__hge(a, b) || __hisnan(b)) ? a : b; + + if (__hisnan(maxval)) + { + // if both inputs are NaN, return canonical NaN + maxval = CUDART_NAN_BF16; + } + else if (__heq(a, b)) + { + // hmax(+0.0, -0.0) = +0.0 + // unsigned compare 0x8000U > 0x0000U + __nv_bfloat16_raw ra = __nv_bfloat16_raw(a); + __nv_bfloat16_raw rb = __nv_bfloat16_raw(b); + maxval = (ra.x > rb.x) ? b : a; + } + + return maxval; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmin(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 val; + asm( "{ min.bf16 %0,%1,%2;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); + return val; +, + __nv_bfloat16 minval; + + minval = (__hle(a, b) || __hisnan(b)) ? a : b; + + if (__hisnan(minval)) + { + // if both inputs are NaN, return canonical NaN + minval = CUDART_NAN_BF16; + } + else if (__heq(a, b)) + { + // hmin(+0.0, -0.0) = -0.0 + // unsigned compare 0x8000U > 0x0000U + __nv_bfloat16_raw ra = __nv_bfloat16_raw(a); + __nv_bfloat16_raw rb = __nv_bfloat16_raw(b); + minval = (ra.x > rb.x) ? a : b; + } + + return minval; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmax_nan(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 val; + asm( "{ max.NaN.bf16 %0,%1,%2;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); + return val; +, + __nv_bfloat16 maxval; + + if (__hisnan(a) || __hisnan(b)) + { + // if either input is NaN, return canonical NaN + maxval = CUDART_NAN_BF16; + } + else + { + maxval = __hge(a, b) ? a : b; + } + + return maxval; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat16 __hmin_nan(const __nv_bfloat16 a, const __nv_bfloat16 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat16 val; + asm( "{ min.NaN.bf16 %0,%1,%2;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b))); + return val; +, + __nv_bfloat16 minval; + + if (__hisnan(a) || __hisnan(b)) + { + // if either input is NaN, return canonical NaN + minval = CUDART_NAN_BF16; + } + else + { + minval = __hle(a, b) ? a : b; + } + + return minval; +) +} +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 __hfma_relu(const __nv_bfloat16 a, const __nv_bfloat16 b, const __nv_bfloat16 c) +{ + __nv_bfloat16 val; + asm( "{ fma.rn.relu.bf16 %0,%1,%2,%3;\n}" + :"=h"(__BFLOAT16_TO_US(val)) : "h"(__BFLOAT16_TO_CUS(a)),"h"(__BFLOAT16_TO_CUS(b)),"h"(__BFLOAT16_TO_CUS(c))); + return val; +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ +/****************************************************************************** +* __nv_bfloat162 arithmetic * +******************************************************************************/ +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmax2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm( "{ max.bf16x2 %0,%1,%2;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); + return val; +, + __nv_bfloat162 val; + val.x = __hmax(a.x, b.x); + val.y = __hmax(a.y, b.y); + return val; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmin2(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm( "{ min.bf16x2 %0,%1,%2;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); + return val; +, + __nv_bfloat162 val; + val.x = __hmin(a.x, b.x); + val.y = __hmin(a.y, b.y); + return val; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmax2_nan(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm( "{ max.NaN.bf16x2 %0,%1,%2;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); + return val; +, + __nv_bfloat162 val; + val.x = __hmax_nan(a.x, b.x); + val.y = __hmax_nan(a.y, b.y); + return val; +) +} +__CUDA_HOSTDEVICE_BF16_DECL__ __nv_bfloat162 __hmin2_nan(const __nv_bfloat162 a, const __nv_bfloat162 b) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80, + __nv_bfloat162 val; + asm( "{ min.NaN.bf16x2 %0,%1,%2;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b))); + return val; +, + __nv_bfloat162 val; + val.x = __hmin_nan(a.x, b.x); + val.y = __hmin_nan(a.y, b.y); + return val; +) +} +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat162 __hfma2_relu(const __nv_bfloat162 a, const __nv_bfloat162 b, const __nv_bfloat162 c) +{ + __nv_bfloat162 val; + asm( "{ fma.rn.relu.bf16x2 %0,%1,%2,%3;\n}" + :"=r"(__BFLOAT162_TO_UI(val)) : "r"(__BFLOAT162_TO_CUI(a)),"r"(__BFLOAT162_TO_CUI(b)),"r"(__BFLOAT162_TO_CUI(c))); + return val; +} + +__CUDA_BF16_DECL__ __nv_bfloat162 __hcmadd(const __nv_bfloat162 a, const __nv_bfloat162 b, const __nv_bfloat162 c) +{ + // fast version of complex multiply-accumulate + // (a.re, a.im) * (b.re, b.im) + (c.re, c.im) + // acc.re = (c.re + a.re*b.re) - a.im*b.im + // acc.im = (c.im + a.re*b.im) + a.im*b.re + __nv_bfloat16 real_tmp = __hfma(a.x, b.x, c.x); + __nv_bfloat16 img_tmp = __hfma(a.x, b.y, c.y); + real_tmp = __hfma(__hneg(a.y), b.y, real_tmp); + img_tmp = __hfma(a.y, b.x, img_tmp); + return make_bfloat162(real_tmp, img_tmp); +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800))) || defined(_NVHPC_CUDA) */ + +#if defined(__CUDACC__) || defined(_NVHPC_CUDA) +/* Define __PTR for atomicAdd prototypes below, undef after done */ +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __PTR "l" +#else +#define __PTR "r" +#endif /*(defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)*/ + +__CUDA_BF16_DECL__ __nv_bfloat162 atomicAdd(__nv_bfloat162 *const address, const __nv_bfloat162 val) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat162 r; + asm volatile ("{ atom.add.noftz.bf16x2 %0,[%1],%2; }\n" + : "=r"(__BFLOAT162_TO_UI(r)) : __PTR(address), "r"(__BFLOAT162_TO_CUI(val)) + : "memory"); + return r; +, + unsigned int* address_as_uint = (unsigned int*)address; + unsigned int old = *address_as_uint; + unsigned int assumed; + do { + assumed = old; + __nv_bfloat162 new_val = __hadd2(val, *(__nv_bfloat162*)&assumed); + old = atomicCAS(address_as_uint, assumed, *(unsigned int*)&new_val); + } while (assumed != old); + return *(__nv_bfloat162*)&old; +) +} + +#if (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700))) || defined(_NVHPC_CUDA) +__CUDA_BF16_DECL__ __nv_bfloat16 atomicAdd(__nv_bfloat16 *const address, const __nv_bfloat16 val) +{ +NV_IF_ELSE_TARGET(NV_PROVIDES_SM_90, + __nv_bfloat16 r; + asm volatile ("{ atom.add.noftz.bf16 %0,[%1],%2; }\n" + : "=h"(__BFLOAT16_TO_US(r)) + : __PTR(address), "h"(__BFLOAT16_TO_CUS(val)) + : "memory"); + return r; +, + unsigned short int* address_as_us = (unsigned short int*)address; + unsigned short int old = *address_as_us; + unsigned short int assumed; + do { + assumed = old; + old = atomicCAS(address_as_us, assumed, + __bfloat16_as_ushort(__hadd(val, __ushort_as_bfloat16(assumed)))); + } while (assumed != old); + return __ushort_as_bfloat16(old); +) +} +#endif /* (defined(__CUDACC__) && (!defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 700))) || defined(_NVHPC_CUDA) */ + +#undef __PTR +#endif /* defined(__CUDACC__) || defined(_NVHPC_CUDA) */ + +#endif /* !(defined __DOXYGEN_ONLY__) */ + +#endif /* defined(__cplusplus) */ + +#undef __CUDA_HOSTDEVICE_BF16_DECL__ +#undef __CUDA_BF16_DECL__ +#undef __CUDA_BF16_CONSTEXPR__ + +#if defined(__CPP_VERSION_AT_LEAST_11_BF16) +#undef __CPP_VERSION_AT_LEAST_11_BF16 +#endif /* defined(__CPP_VERSION_AT_LEAST_11_BF16) */ + +#undef ___CUDA_BF16_STRINGIFY_INNERMOST +#undef __CUDA_BF16_STRINGIFY + +#endif /* end of include guard: __CUDA_BF16_HPP__ */ diff --git a/shared/package-files/3a/3aeb05710d79dca365f5061ce8ef667427fa71a917219d6165d803ffdbd9e873/errors.cpython-311.pyc b/shared/package-files/3a/3aeb05710d79dca365f5061ce8ef667427fa71a917219d6165d803ffdbd9e873/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d237c16f6a5a8a3ce13ec4af4161f07256e07f4 Binary files /dev/null and b/shared/package-files/3a/3aeb05710d79dca365f5061ce8ef667427fa71a917219d6165d803ffdbd9e873/errors.cpython-311.pyc differ diff --git a/shared/package-files/3a/3af4cf9c189c7dee90c9e4c2c2e04c4b428a6677e798c99e66e6331b7e8e4b97/small.py b/shared/package-files/3a/3af4cf9c189c7dee90c9e4c2c2e04c4b428a6677e798c99e66e6331b7e8e4b97/small.py new file mode 100644 index 0000000000000000000000000000000000000000..719cf49cf9e3d5be715313bb3e531f235b8ce292 --- /dev/null +++ b/shared/package-files/3a/3af4cf9c189c7dee90c9e4c2c2e04c4b428a6677e798c99e66e6331b7e8e4b97/small.py @@ -0,0 +1,996 @@ +""" +Various small and named graphs, together with some compact generators. + +""" + +__all__ = [ + "LCF_graph", + "bull_graph", + "chvatal_graph", + "cubical_graph", + "desargues_graph", + "diamond_graph", + "dodecahedral_graph", + "frucht_graph", + "heawood_graph", + "hoffman_singleton_graph", + "house_graph", + "house_x_graph", + "icosahedral_graph", + "krackhardt_kite_graph", + "moebius_kantor_graph", + "octahedral_graph", + "pappus_graph", + "petersen_graph", + "sedgewick_maze_graph", + "tetrahedral_graph", + "truncated_cube_graph", + "truncated_tetrahedron_graph", + "tutte_graph", +] + +from functools import wraps + +import networkx as nx +from networkx.exception import NetworkXError +from networkx.generators.classic import ( + complete_graph, + cycle_graph, + empty_graph, + path_graph, +) + + +def _raise_on_directed(func): + """ + A decorator which inspects the `create_using` argument and raises a + NetworkX exception when `create_using` is a DiGraph (class or instance) for + graph generators that do not support directed outputs. + + `create_using` may be a keyword argument or the first positional argument. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + create_using = args[0] if args else kwargs.get("create_using") + if create_using is not None: + G = nx.empty_graph(create_using=create_using) + if G.is_directed(): + raise NetworkXError("Directed Graph not supported") + return func(*args, **kwargs) + + return wrapper + + +@nx._dispatchable(graphs=None, returns_graph=True) +def LCF_graph(n, shift_list, repeats, create_using=None): + """ + Return the cubic graph specified in LCF notation. + + LCF (Lederberg-Coxeter-Fruchte) notation[1]_ is a compressed + notation used in the generation of various cubic Hamiltonian + graphs of high symmetry. See, for example, `dodecahedral_graph`, + `desargues_graph`, `heawood_graph` and `pappus_graph`. + + Nodes are drawn from ``range(n)``. Each node ``n_i`` is connected with + node ``n_i + shift % n`` where ``shift`` is given by cycling through + the input `shift_list` `repeat` s times. + + Parameters + ---------- + n : int + The starting graph is the `n`-cycle with nodes ``0, ..., n-1``. + The null graph is returned if `n` < 1. + + shift_list : list + A list of integer shifts mod `n`, ``[s1, s2, .., sk]`` + + repeats : int + Integer specifying the number of times that shifts in `shift_list` + are successively applied to each current node in the n-cycle + to generate an edge between ``n_current`` and ``n_current + shift mod n``. + + Returns + ------- + G : Graph + A graph instance created from the specified LCF notation. + + Examples + -------- + The utility graph $K_{3,3}$ + + >>> G = nx.LCF_graph(6, [3, -3], 3) + >>> G.edges() + EdgeView([(0, 1), (0, 5), (0, 3), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)]) + + The Heawood graph: + + >>> G = nx.LCF_graph(14, [5, -5], 7) + >>> nx.is_isomorphic(G, nx.heawood_graph()) + True + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/LCF_notation + + """ + if n <= 0: + return empty_graph(0, create_using) + + # start with the n-cycle + G = cycle_graph(n, create_using) + if G.is_directed(): + raise NetworkXError("Directed Graph not supported") + G.name = "LCF_graph" + nodes = sorted(G) + + n_extra_edges = repeats * len(shift_list) + # edges are added n_extra_edges times + # (not all of these need be new) + if n_extra_edges < 1: + return G + + for i in range(n_extra_edges): + shift = shift_list[i % len(shift_list)] # cycle through shift_list + v1 = nodes[i % n] # cycle repeatedly through nodes + v2 = nodes[(i + shift) % n] + G.add_edge(v1, v2) + return G + + +# ------------------------------------------------------------------------------- +# Various small and named graphs +# ------------------------------------------------------------------------------- + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def bull_graph(create_using=None): + """ + Returns the Bull Graph + + The Bull Graph has 5 nodes and 5 edges. It is a planar undirected + graph in the form of a triangle with two disjoint pendant edges [1]_ + The name comes from the triangle and pendant edges representing + respectively the body and legs of a bull. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + A bull graph with 5 nodes + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Bull_graph. + + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 4], 3: [1], 4: [2]}, + create_using=create_using, + ) + G.name = "Bull Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def chvatal_graph(create_using=None): + """ + Returns the Chvátal Graph + + The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_. + It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized + LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + The Chvátal graph with 12 nodes and 24 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph + .. [2] https://mathworld.wolfram.com/ChvatalGraph.html + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 4, 6, 9], + 1: [2, 5, 7], + 2: [3, 6, 8], + 3: [4, 7, 9], + 4: [5, 8], + 5: [10, 11], + 6: [10, 11], + 7: [8, 11], + 8: [10], + 9: [10, 11], + }, + create_using=create_using, + ) + G.name = "Chvatal Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def cubical_graph(create_using=None): + """ + Returns the 3-regular Platonic Cubical Graph + + The skeleton of the cube (the nodes and edges) form a graph, with 8 + nodes, and 12 edges. It is a special case of the hypercube graph. + It is one of 5 Platonic graphs, each a skeleton of its + Platonic solid [1]_. + Such graphs arise in parallel processing in computers. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + A cubical graph with 8 nodes and 12 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 3, 4], + 1: [0, 2, 7], + 2: [1, 3, 6], + 3: [0, 2, 5], + 4: [0, 5, 7], + 5: [3, 4, 6], + 6: [2, 5, 7], + 7: [1, 4, 6], + }, + create_using=create_using, + ) + G.name = "Platonic Cubical Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def desargues_graph(create_using=None): + """ + Returns the Desargues Graph + + The Desargues Graph is a non-planar, distance-transitive cubic graph + with 20 nodes and 30 edges [1]_. + It is a symmetric graph. It can be represented in LCF notation + as [5,-5,9,-9]^5 [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Desargues Graph with 20 nodes and 30 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Desargues_graph + .. [2] https://mathworld.wolfram.com/DesarguesGraph.html + """ + G = LCF_graph(20, [5, -5, 9, -9], 5, create_using) + G.name = "Desargues Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def diamond_graph(create_using=None): + """ + Returns the Diamond graph + + The Diamond Graph is planar undirected graph with 4 nodes and 5 edges. + It is also sometimes known as the double triangle graph or kite graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Diamond Graph with 4 nodes and 5 edges + + References + ---------- + .. [1] https://mathworld.wolfram.com/DiamondGraph.html + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 2, 3], 2: [0, 1, 3], 3: [1, 2]}, create_using=create_using + ) + G.name = "Diamond Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def dodecahedral_graph(create_using=None): + """ + Returns the Platonic Dodecahedral graph. + + The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the + dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_. + It can be described in LCF notation as: + ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Dodecahedral Graph with 20 nodes and 30 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph + .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html + + """ + G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using) + G.name = "Dodecahedral Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def frucht_graph(create_using=None): + """ + Returns the Frucht Graph. + + The Frucht Graph is the smallest cubical graph whose + automorphism group consists only of the identity element [1]_. + It has 12 nodes and 18 edges and no nontrivial symmetries. + It is planar and Hamiltonian [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Frucht Graph with 12 nodes and 18 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Frucht_graph + .. [2] https://mathworld.wolfram.com/FruchtGraph.html + + """ + G = cycle_graph(7, create_using) + G.add_edges_from( + [ + [0, 7], + [1, 7], + [2, 8], + [3, 9], + [4, 9], + [5, 10], + [6, 10], + [7, 11], + [8, 11], + [8, 9], + [10, 11], + ] + ) + + G.name = "Frucht Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def heawood_graph(create_using=None): + """ + Returns the Heawood Graph, a (3,6) cage. + + The Heawood Graph is an undirected graph with 14 nodes and 21 edges, + named after Percy John Heawood [1]_. + It is cubic symmetric, nonplanar, Hamiltonian, and can be represented + in LCF notation as ``[5,-5]^7`` [2]_. + It is the unique (3,6)-cage: the regular cubic graph of girth 6 with + minimal number of vertices [3]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Heawood Graph with 14 nodes and 21 edges + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Heawood_graph + .. [2] https://mathworld.wolfram.com/HeawoodGraph.html + .. [3] https://www.win.tue.nl/~aeb/graphs/Heawood.html + + """ + G = LCF_graph(14, [5, -5], 7, create_using) + G.name = "Heawood Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def hoffman_singleton_graph(): + """ + Returns the Hoffman-Singleton Graph. + + The Hoffman–Singleton graph is a symmetrical undirected graph + with 50 nodes and 175 edges. + All indices lie in ``Z % 5``: that is, the integers mod 5 [1]_. + It is the only regular graph of vertex degree 7, diameter 2, and girth 5. + It is the unique (7,5)-cage graph and Moore graph, and contains many + copies of the Petersen graph [2]_. + + Returns + ------- + G : networkx Graph + Hoffman–Singleton Graph with 50 nodes and 175 edges + + Notes + ----- + Constructed from pentagon and pentagram as follows: Take five pentagons $P_h$ + and five pentagrams $Q_i$ . Join vertex $j$ of $P_h$ to vertex $h·i+j$ of $Q_i$ [3]_. + + References + ---------- + .. [1] https://blogs.ams.org/visualinsight/2016/02/01/hoffman-singleton-graph/ + .. [2] https://mathworld.wolfram.com/Hoffman-SingletonGraph.html + .. [3] https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph + + """ + G = nx.Graph() + for i in range(5): + for j in range(5): + G.add_edge(("pentagon", i, j), ("pentagon", i, (j - 1) % 5)) + G.add_edge(("pentagon", i, j), ("pentagon", i, (j + 1) % 5)) + G.add_edge(("pentagram", i, j), ("pentagram", i, (j - 2) % 5)) + G.add_edge(("pentagram", i, j), ("pentagram", i, (j + 2) % 5)) + for k in range(5): + G.add_edge(("pentagon", i, j), ("pentagram", k, (i * k + j) % 5)) + G = nx.convert_node_labels_to_integers(G) + G.name = "Hoffman-Singleton Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def house_graph(create_using=None): + """ + Returns the House graph (square with triangle on top) + + The house graph is a simple undirected graph with + 5 nodes and 6 edges [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + House graph in the form of a square with a triangle on top + + References + ---------- + .. [1] https://mathworld.wolfram.com/HouseGraph.html + """ + G = nx.from_dict_of_lists( + {0: [1, 2], 1: [0, 3], 2: [0, 3, 4], 3: [1, 2, 4], 4: [2, 3]}, + create_using=create_using, + ) + G.name = "House Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def house_x_graph(create_using=None): + """ + Returns the House graph with a cross inside the house square. + + The House X-graph is the House graph plus the two edges connecting diagonally + opposite vertices of the square base. It is also one of the two graphs + obtained by removing two edges from the pentatope graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + House graph with diagonal vertices connected + + References + ---------- + .. [1] https://mathworld.wolfram.com/HouseGraph.html + """ + G = house_graph(create_using) + G.add_edges_from([(0, 3), (1, 2)]) + G.name = "House-with-X-inside Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def icosahedral_graph(create_using=None): + """ + Returns the Platonic Icosahedral graph. + + The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph + whose nodes have the connectivity of the icosahedron. It is undirected, + regular and Hamiltonian [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Icosahedral graph with 12 nodes and 30 edges. + + References + ---------- + .. [1] https://mathworld.wolfram.com/IcosahedralGraph.html + """ + G = nx.from_dict_of_lists( + { + 0: [1, 5, 7, 8, 11], + 1: [2, 5, 6, 8], + 2: [3, 6, 8, 9], + 3: [4, 6, 9, 10], + 4: [5, 6, 10, 11], + 5: [6, 11], + 7: [8, 9, 10, 11], + 8: [9], + 9: [10], + 10: [11], + }, + create_using=create_using, + ) + G.name = "Platonic Icosahedral Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def krackhardt_kite_graph(create_using=None): + """ + Returns the Krackhardt Kite Social Network. + + A 10 actor social network introduced by David Krackhardt + to illustrate different centrality measures [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Krackhardt Kite graph with 10 nodes and 18 edges + + Notes + ----- + The traditional labeling is: + Andre=1, Beverley=2, Carol=3, Diane=4, + Ed=5, Fernando=6, Garth=7, Heather=8, Ike=9, Jane=10. + + References + ---------- + .. [1] Krackhardt, David. "Assessing the Political Landscape: Structure, + Cognition, and Power in Organizations". Administrative Science Quarterly. + 35 (2): 342–369. doi:10.2307/2393394. JSTOR 2393394. June 1990. + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 3, 5], + 1: [0, 3, 4, 6], + 2: [0, 3, 5], + 3: [0, 1, 2, 4, 5, 6], + 4: [1, 3, 6], + 5: [0, 2, 3, 6, 7], + 6: [1, 3, 4, 5, 7], + 7: [5, 6, 8], + 8: [7, 9], + 9: [8], + }, + create_using=create_using, + ) + G.name = "Krackhardt Kite Social Network" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def moebius_kantor_graph(create_using=None): + """ + Returns the Moebius-Kantor graph. + + The Möbius-Kantor graph is the cubic symmetric graph on 16 nodes. + Its LCF notation is [5,-5]^8, and it is isomorphic to the generalized + Petersen graph [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Moebius-Kantor graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph + + """ + G = LCF_graph(16, [5, -5], 8, create_using) + G.name = "Moebius-Kantor Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def octahedral_graph(create_using=None): + """ + Returns the Platonic Octahedral graph. + + The octahedral graph is the 6-node 12-edge Platonic graph having the + connectivity of the octahedron [1]_. If 6 couples go to a party, + and each person shakes hands with every person except his or her partner, + then this graph describes the set of handshakes that take place; + for this reason it is also called the cocktail party graph [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Octahedral graph + + References + ---------- + .. [1] https://mathworld.wolfram.com/OctahedralGraph.html + .. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases + + """ + G = nx.from_dict_of_lists( + {0: [1, 2, 3, 4], 1: [2, 3, 5], 2: [4, 5], 3: [4, 5], 4: [5]}, + create_using=create_using, + ) + G.name = "Platonic Octahedral Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def pappus_graph(): + """ + Returns the Pappus graph. + + The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes + and 27 edges. It is Hamiltonian and can be represented in LCF notation as + [5,7,-7,7,-7,-5]^3 [1]_. + + Returns + ------- + G : networkx Graph + Pappus graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Pappus_graph + """ + G = LCF_graph(18, [5, 7, -7, 7, -7, -5], 3) + G.name = "Pappus Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def petersen_graph(create_using=None): + """ + Returns the Petersen graph. + + The Peterson graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_. + Julius Petersen constructed the graph as the smallest counterexample + against the claim that a connected bridgeless cubic graph + has an edge colouring with three colours [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Petersen graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Petersen_graph + .. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html + """ + G = nx.from_dict_of_lists( + { + 0: [1, 4, 5], + 1: [0, 2, 6], + 2: [1, 3, 7], + 3: [2, 4, 8], + 4: [3, 0, 9], + 5: [0, 7, 8], + 6: [1, 8, 9], + 7: [2, 5, 9], + 8: [3, 5, 6], + 9: [4, 6, 7], + }, + create_using=create_using, + ) + G.name = "Petersen Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def sedgewick_maze_graph(create_using=None): + """ + Return a small maze with a cycle. + + This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph + Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. + Nodes are numbered 0,..,7 + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Small maze with a cycle + + References + ---------- + .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick + """ + G = empty_graph(0, create_using) + G.add_nodes_from(range(8)) + G.add_edges_from([[0, 2], [0, 7], [0, 5]]) + G.add_edges_from([[1, 7], [2, 6]]) + G.add_edges_from([[3, 4], [3, 5]]) + G.add_edges_from([[4, 5], [4, 7], [4, 6]]) + G.name = "Sedgewick Maze" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def tetrahedral_graph(create_using=None): + """ + Returns the 3-regular Platonic Tetrahedral graph. + + Tetrahedral graph has 4 nodes and 6 edges. It is a + special case of the complete graph, K4, and wheel graph, W4. + It is one of the 5 platonic graphs [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Tetrahedral Graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph + + """ + G = complete_graph(4, create_using) + G.name = "Platonic Tetrahedral Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def truncated_cube_graph(create_using=None): + """ + Returns the skeleton of the truncated cube. + + The truncated cube is an Archimedean solid with 14 regular + faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_. + The truncated cube is created by truncating (cutting off) the tips + of the cube one third of the way into each edge [2]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Skeleton of the truncated cube + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Truncated_cube + .. [2] https://www.coolmath.com/reference/polyhedra-truncated-cube + + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 4], + 1: [11, 14], + 2: [3, 4], + 3: [6, 8], + 4: [5], + 5: [16, 18], + 6: [7, 8], + 7: [10, 12], + 8: [9], + 9: [17, 20], + 10: [11, 12], + 11: [14], + 12: [13], + 13: [21, 22], + 14: [15], + 15: [19, 23], + 16: [17, 18], + 17: [20], + 18: [19], + 19: [23], + 20: [21], + 21: [22], + 22: [23], + }, + create_using=create_using, + ) + G.name = "Truncated Cube Graph" + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def truncated_tetrahedron_graph(create_using=None): + """ + Returns the skeleton of the truncated Platonic tetrahedron. + + The truncated tetrahedron is an Archimedean solid with 4 regular hexagonal faces, + 4 equilateral triangle faces, 12 nodes and 18 edges. It can be constructed by truncating + all 4 vertices of a regular tetrahedron at one third of the original edge length [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Skeleton of the truncated tetrahedron + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Truncated_tetrahedron + + """ + G = path_graph(12, create_using) + G.add_edges_from([(0, 2), (0, 9), (1, 6), (3, 11), (4, 11), (5, 7), (8, 10)]) + G.name = "Truncated Tetrahedron Graph" + return G + + +@_raise_on_directed +@nx._dispatchable(graphs=None, returns_graph=True) +def tutte_graph(create_using=None): + """ + Returns the Tutte graph. + + The Tutte graph is a cubic polyhedral, non-Hamiltonian graph. It has + 46 nodes and 69 edges. + It is a counterexample to Tait's conjecture that every 3-regular polyhedron + has a Hamiltonian cycle. + It can be realized geometrically from a tetrahedron by multiply truncating + three of its vertices [1]_. + + Parameters + ---------- + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : networkx Graph + Tutte graph + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Tutte_graph + """ + G = nx.from_dict_of_lists( + { + 0: [1, 2, 3], + 1: [4, 26], + 2: [10, 11], + 3: [18, 19], + 4: [5, 33], + 5: [6, 29], + 6: [7, 27], + 7: [8, 14], + 8: [9, 38], + 9: [10, 37], + 10: [39], + 11: [12, 39], + 12: [13, 35], + 13: [14, 15], + 14: [34], + 15: [16, 22], + 16: [17, 44], + 17: [18, 43], + 18: [45], + 19: [20, 45], + 20: [21, 41], + 21: [22, 23], + 22: [40], + 23: [24, 27], + 24: [25, 32], + 25: [26, 31], + 26: [33], + 27: [28], + 28: [29, 32], + 29: [30], + 30: [31, 33], + 31: [32], + 34: [35, 38], + 35: [36], + 36: [37, 39], + 37: [38], + 40: [41, 44], + 41: [42], + 42: [43, 45], + 43: [44], + }, + create_using=create_using, + ) + G.name = "Tutte's Graph" + return G diff --git a/shared/package-files/3a/3afc2530e519d65e3f2612cffdf9380ea74788070ff52d74a67ca3ed63ae257b/swapaxes.h b/shared/package-files/3a/3afc2530e519d65e3f2612cffdf9380ea74788070ff52d74a67ca3ed63ae257b/swapaxes.h new file mode 100644 index 0000000000000000000000000000000000000000..42b17db70574532447bb5c98f2a6e2b2b952013e --- /dev/null +++ b/shared/package-files/3a/3afc2530e519d65e3f2612cffdf9380ea74788070ff52d74a67ca3ed63ae257b/swapaxes.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a) +inline at::Tensor swapaxes(const at::Tensor & self, int64_t axis0, int64_t axis1) { + return at::_ops::swapaxes::call(self, axis0, axis1); +} + +} diff --git a/shared/package-files/3a/3afdb9a3fe57a2e08a22aa732b8db1730f1d03055dd36b4666a4b85cbf013883/__init__.py b/shared/package-files/3a/3afdb9a3fe57a2e08a22aa732b8db1730f1d03055dd36b4666a4b85cbf013883/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce645703ddb584c34d80c15b562f0dacd14350b4 --- /dev/null +++ b/shared/package-files/3a/3afdb9a3fe57a2e08a22aa732b8db1730f1d03055dd36b4666a4b85cbf013883/__init__.py @@ -0,0 +1 @@ +from torch.nn.intrinsic.quantized.dynamic.modules import * # noqa: F403 diff --git a/shared/package-files/3c/3c01345621af8c73bae576c87be08ce41811c7d28db152f8c54ed0454caa2fd3/__init__.py b/shared/package-files/3c/3c01345621af8c73bae576c87be08ce41811c7d28db152f8c54ed0454caa2fd3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..108c765ba4766bf7d9110aa67e09ac02cab00410 --- /dev/null +++ b/shared/package-files/3c/3c01345621af8c73bae576c87be08ce41811c7d28db152f8c54ed0454caa2fd3/__init__.py @@ -0,0 +1,3 @@ +from torch.distributed.fsdp import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy + +from .fully_shard import FSDPModule, fully_shard, register_fsdp_forward_method diff --git a/shared/package-files/3c/3c043aecde8aa7c95117898241eec2bd2b376ed16e8f1214821a79151b567802/test_non_randomness.cpython-311.pyc b/shared/package-files/3c/3c043aecde8aa7c95117898241eec2bd2b376ed16e8f1214821a79151b567802/test_non_randomness.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0960acd3347c801ff2423702bbf55515be501b5 Binary files /dev/null and b/shared/package-files/3c/3c043aecde8aa7c95117898241eec2bd2b376ed16e8f1214821a79151b567802/test_non_randomness.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c04b134aa71ef5571d926d3a0c1bf342ba342ce1d32f40840881d886dfbf641/prim_ops_registery.h b/shared/package-files/3c/3c04b134aa71ef5571d926d3a0c1bf342ba342ce1d32f40840881d886dfbf641/prim_ops_registery.h new file mode 100644 index 0000000000000000000000000000000000000000..d7fe9521fd320f7910b1a245fa873b08aa0f6251 --- /dev/null +++ b/shared/package-files/3c/3c04b134aa71ef5571d926d3a0c1bf342ba342ce1d32f40840881d886dfbf641/prim_ops_registery.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +namespace torch::jit::mobile { + +using Stack = std::vector; + +void registerPrimOpsFunction( + const std::string& name, + const std::function& fn); + +bool hasPrimOpsFn(const std::string& name); + +std::function& getPrimOpsFn(const std::string& name); + +class prim_op_fn_register { + public: + prim_op_fn_register( + const std::string& name, + const std::function& fn) { + registerPrimOpsFunction(name, fn); + } +}; + +} // namespace torch::jit::mobile diff --git a/shared/package-files/3c/3c058a31e673c4e08f90bbf73eb4792f810ed0ed2ca5c100b8db35223fd63d19/nll_loss2d_backward_cuda_dispatch.h b/shared/package-files/3c/3c058a31e673c4e08f90bbf73eb4792f810ed0ed2ca5c100b8db35223fd63d19/nll_loss2d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..87156b90bee56f01ea1f9bb9ee6847e44f2d4b32 --- /dev/null +++ b/shared/package-files/3c/3c058a31e673c4e08f90bbf73eb4792f810ed0ed2ca5c100b8db35223fd63d19/nll_loss2d_backward_cuda_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +TORCH_API at::Tensor nll_loss2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight); +TORCH_API at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight); +TORCH_API at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input); +TORCH_API at::Tensor & nll_loss2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight); +TORCH_API at::Tensor & nll_loss2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/3c/3c08241269383c05fb4447f2369af300d7b40889905ae320b85db9898d542c07/glu.h b/shared/package-files/3c/3c08241269383c05fb4447f2369af300d7b40889905ae320b85db9898d542c07/glu.h new file mode 100644 index 0000000000000000000000000000000000000000..666e59879b39d6043b2b04e39b1046c631eaec9e --- /dev/null +++ b/shared/package-files/3c/3c08241269383c05fb4447f2369af300d7b40889905ae320b85db9898d542c07/glu.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & glu_out(at::Tensor & out, const at::Tensor & self, int64_t dim=-1) { + return at::_ops::glu_out::call(self, dim, out); +} +// aten::glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & glu_outf(const at::Tensor & self, int64_t dim, at::Tensor & out) { + return at::_ops::glu_out::call(self, dim, out); +} + +// aten::glu(Tensor self, int dim=-1) -> Tensor +inline at::Tensor glu(const at::Tensor & self, int64_t dim=-1) { + return at::_ops::glu::call(self, dim); +} + +} diff --git a/shared/package-files/3c/3c0a436be8980ccdbfbc9ab8609bf5a19be40ce709ee167b7b530c4a4c2fb0a9/__init__.cpython-311.pyc b/shared/package-files/3c/3c0a436be8980ccdbfbc9ab8609bf5a19be40ce709ee167b7b530c4a4c2fb0a9/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1110505f870bd9ee0257001e81bf24e096bd833c Binary files /dev/null and b/shared/package-files/3c/3c0a436be8980ccdbfbc9ab8609bf5a19be40ce709ee167b7b530c4a4c2fb0a9/__init__.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c0eb369156b216c901eae9b18a7b3a8d07a6164df7279c1f551f6bf36847da4/test_autowrap.py b/shared/package-files/3c/3c0eb369156b216c901eae9b18a7b3a8d07a6164df7279c1f551f6bf36847da4/test_autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a33d77adb46710cfa3cfeb1ea39402e35c76cf --- /dev/null +++ b/shared/package-files/3c/3c0eb369156b216c901eae9b18a7b3a8d07a6164df7279c1f551f6bf36847da4/test_autowrap.py @@ -0,0 +1,467 @@ +# Tests that require installed backends go into +# sympy/test_external/test_autowrap + +import os +import tempfile +import shutil +from io import StringIO +from pathlib import Path + +from sympy.core import symbols, Eq +from sympy.utilities.autowrap import (autowrap, binary_function, + CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) +from sympy.utilities.codegen import ( + CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine +) +from sympy.testing.pytest import raises +from sympy.testing.tmpfiles import TmpFileManager + + +def get_string(dump_fn, routines, prefix="file", **kwargs): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generator to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, **kwargs) + source = output.getvalue() + output.close() + return source + + +def test_cython_wrapper_scalar_function(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + + expected = ( + "cdef extern from 'file.h':\n" + " double test(double x, double y, double z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " return test(x, y, z)") + assert source == expected + + +def test_cython_wrapper_outarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + + routine = make_routine("test", Equality(z, x + y)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y):\n" + "\n" + " cdef double z = 0\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_inoutarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + routine = make_routine("test", Equality(z, x + y + z)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_compile_flags(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + routine = make_routine("test", Equality(z, x + y)) + + code_gen = CythonCodeWrapper(CCodeGen()) + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'language_level': '3'}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=[], + library_dirs=[], + libraries=[], + extra_compile_args=['-std=c99'], + extra_link_args=[] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + temp_dir = tempfile.mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + setup_file_path = os.path.join(temp_dir, 'setup.py') + + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + code_gen = CythonCodeWrapper(CCodeGen(), + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math'], + extra_link_args=['-lswamp', '-ltrident'], + cythonize_options={'compiler_directives': {'boundscheck': False}} + ) + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} +import numpy as np + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._need_numpy = True + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + TmpFileManager.cleanup() + +def test_cython_wrapper_unique_dummyvars(): + from sympy.core.relational import Equality + from sympy.core.symbol import Dummy + x, y, z = Dummy('x'), Dummy('y'), Dummy('z') + x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] + expr = Equality(z, x + y) + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + expected_template = ( + "cdef extern from 'file.h':\n" + " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" + "\n" + "def test_c(double x_{x_id}, double y_{y_id}):\n" + "\n" + " cdef double z_{z_id} = 0\n" + " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" + " return z_{z_id}") + expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) + assert source == expected + +def test_autowrap_dummy(): + x, y, z = symbols('x y z') + + # Uses DummyWrapper to test that codegen works as expected + + f = autowrap(x + y, backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "nameless" + f = autowrap(Eq(z, x + y), backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "z" + f = autowrap(Eq(z, x + y + z), backend='dummy') + assert f() == str(x + y + z) + assert f.args == "x, y, z" + assert f.returns == "z" + + +def test_autowrap_args(): + x, y, z = symbols('x y z') + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), + backend='dummy', args=[x])) + f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) + assert f() == str(x + y) + assert f.args == "y, x" + assert f.returns == "z" + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), + backend='dummy', args=[x, y])) + f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + + f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + +def test_autowrap_store_files(): + x, y = symbols('x y') + tmp = tempfile.mkdtemp() + TmpFileManager.tmp_folder(tmp) + + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + + TmpFileManager.cleanup() + +def test_autowrap_store_files_issue_gh12939(): + x, y = symbols('x y') + tmp = './tmp' + saved_cwd = os.getcwd() + temp_cwd = tempfile.mkdtemp() + try: + os.chdir(temp_cwd) + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + finally: + os.chdir(saved_cwd) + shutil.rmtree(temp_cwd) + + +def test_binary_function(): + x, y = symbols('x y') + f = binary_function('f', x + y, backend='dummy') + assert f._imp_() == str(x + y) + + +def test_ufuncify_source(): + x, y, z = symbols('x,y,z') + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routine = make_routine("test", x + y + z) + source = get_string(code_wrapper.dump_c, [routine]) + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void test_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + for (i = 0; i < n; i++) { + *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + } +} +PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; +static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *test_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected + + +def test_ufuncify_source_multioutput(): + x, y, z = symbols('x,y,z') + var_symbols = (x, y, z) + expr = x + y**3 + 10*z**2 + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] + source = get_string(code_wrapper.dump_c, routines, funcname='multitest') + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void multitest_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + char *out1 = args[4]; + char *out2 = args[5]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + npy_intp out1_step = steps[4]; + npy_intp out2_step = steps[5]; + for (i = 0; i < n; i++) { + *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + out1 += out1_step; + out2 += out2_step; + } +} +PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; +static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *multitest_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected diff --git a/shared/package-files/3c/3c15bca2ae0fbcb997e52344055612de300448f112e666cbac43a133e0e36a84/choose_qparams_optimized_ops.h b/shared/package-files/3c/3c15bca2ae0fbcb997e52344055612de300448f112e666cbac43a133e0e36a84/choose_qparams_optimized_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eb31ee3f032a9ad8af728b3c4322c594e1d4cab6 --- /dev/null +++ b/shared/package-files/3c/3c15bca2ae0fbcb997e52344055612de300448f112e666cbac43a133e0e36a84/choose_qparams_optimized_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API choose_qparams_optimized { + using schema = ::std::tuple (const at::Tensor &, int64_t, int64_t, double, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::choose_qparams_optimized"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "choose_qparams_optimized(Tensor input, int numel, int n_bins, float ratio, int bit_width) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & input, int64_t numel, int64_t n_bins, double ratio, int64_t bit_width); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, int64_t numel, int64_t n_bins, double ratio, int64_t bit_width); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3c/3c1b0bf6415bd606c1118d97616cc2b66e3069b8fe11ca2ef0a44077764c24d8/vcfbuf.c b/shared/package-files/3c/3c1b0bf6415bd606c1118d97616cc2b66e3069b8fe11ca2ef0a44077764c24d8/vcfbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..22390d0fab096a7e35942d6ec240bcd02e2bb8e6 --- /dev/null +++ b/shared/package-files/3c/3c1b0bf6415bd606c1118d97616cc2b66e3069b8fe11ca2ef0a44077764c24d8/vcfbuf.c @@ -0,0 +1,897 @@ +/* The MIT License + + Copyright (c) 2016-2024 Genome Research Ltd. + + Author: Petr Danecek + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + */ + +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "vcfbuf.h" +#include "rbuf.h" + +typedef struct +{ + double max[VCFBUF_LD_N]; + int rand_missing, filter1; +} +ld_t; + +typedef struct +{ + bcf1_t *rec; + double af; + unsigned int af_set:1, filter:1, idx:30; +} +vcfrec_t; + +#define PRUNE_MODE_MAX_AF 1 +#define PRUNE_MODE_1ST 2 +#define PRUNE_MODE_RAND 3 +typedef struct +{ + int max_sites, mvrec, mac, mfarr, mode; + int *ac, *idx; + float *farr; + char *af_tag; + vcfrec_t **vrec; +} +prune_t; + + +#define MARK_OVERLAP 1 +#define MARK_DUP 2 +#define MARK_EXPR 3 + +#define MARK_MISSING_SCALAR 0 // actual value to use +#define MARK_MISSING_MAX_DP 1 // max overlap_t.value scaled by INFO/DP + +// temporary internal structure for iterative overlap removal by mark_t.expr +typedef struct +{ + double value; // the sort value + int rmme, idx; // mark for removal, index in vcfbuf_t.rbuf + int dp; // with MARK_MISSING_MAX_DP, INFO/DP is used extrapolate missing QUAL + kbitset_t *bset; // mark which records it overlaps with, given as 0-based indexes to vcfbuf_t.rbuf + bcf1_t *rec; +} +overlap_t; +typedef struct +{ + // modes + int mode; + char *expr; + + // sites marked according to expr, returned to the caller via vcfbuf_get() + rbuf_t rbuf; + uint8_t *mark; + int last; + + // MARK_OVERLAP + int overlap_rid, overlap_end; + + // MARK_EXPR + int nbuf; + overlap_t *buf, **buf_ptr; + int missing_expr; // the value to use when min(QUAL) encounters a missing value + float missing_value; // the default missing value + float max_qual; // with MARK_MISSING_MAX_DP + int max_qual_dp; // + int ntmpi; // temporary int array and the allocated memory + int32_t *tmpi; +} +mark_t; + +struct _vcfbuf_t +{ + int win, // maximum number of sites in the buffer, either number of sites (<0) or bp (<0) + dummy; // the caller maintains the buffer via push/peek/flush + bcf_hdr_t *hdr; + vcfrec_t *vcf; + rbuf_t rbuf; + ld_t ld; + prune_t prune; + mark_t mark; + enum { clean, dirty } status; +}; + +vcfbuf_t *vcfbuf_init(bcf_hdr_t *hdr, int win) +{ + vcfbuf_t *buf = (vcfbuf_t*) calloc(1,sizeof(vcfbuf_t)); + buf->hdr = hdr; + buf->win = win; + buf->status = clean; + buf->mark.overlap_rid = -1; + int i; + for (i=0; ild.max[i] = HUGE_VAL; + rbuf_init(&buf->rbuf, 0); + return buf; +} + +void vcfbuf_destroy(vcfbuf_t *buf) +{ + int i; + for (i=0; irbuf.m; i++) + if ( buf->vcf[i].rec ) bcf_destroy(buf->vcf[i].rec); + free(buf->vcf); + free(buf->prune.farr); + free(buf->prune.vrec); + free(buf->prune.ac); + free(buf->prune.af_tag); + free(buf->prune.idx); + free(buf->mark.mark); + free(buf->mark.expr); + for (i=0; imark.nbuf; i++) kbs_destroy(buf->mark.buf[i].bset); + free(buf->mark.buf); + free(buf->mark.buf_ptr); + free(buf->mark.tmpi); + free(buf); +} + +int vcfbuf_set(vcfbuf_t *buf, vcfbuf_opt_t key, ...) +{ + va_list args; + switch (key) + { + case LD_FILTER1: + va_start(args, key); + buf->ld.filter1 = va_arg(args,int); + va_end(args); + return 0; + + case LD_RAND_MISSING: + va_start(args, key); + buf->ld.rand_missing = va_arg(args,int); + va_end(args); + return 0; + + case LD_MAX_R2: + va_start(args, key); + buf->ld.max[VCFBUF_LD_IDX_R2] = va_arg(args,double); + va_end(args); + return 0; + + case LD_MAX_LD: + va_start(args, key); + buf->ld.max[VCFBUF_LD_IDX_LD] = va_arg(args,double); + va_end(args); + return 0; + + case LD_MAX_HD: + va_start(args, key); + buf->ld.max[VCFBUF_LD_IDX_HD] = va_arg(args,double); + va_end(args); + return 0; + + case VCFBUF_DUMMY: + va_start(args, key); + buf->dummy = va_arg(args,int); + va_end(args); + return 0; + + case PRUNE_NSITES: + va_start(args, key); + buf->prune.max_sites = va_arg(args,int); + if ( !buf->prune.mode ) buf->prune.mode = PRUNE_MODE_MAX_AF; + va_end(args); + return 0; + + case PRUNE_NSITES_MODE: + va_start(args, key); + char *mode = va_arg(args,char*); + va_end(args); + if ( !strcasecmp(mode,"maxAF") ) buf->prune.mode = PRUNE_MODE_MAX_AF; + else if ( !strcasecmp(mode,"1st") ) buf->prune.mode = PRUNE_MODE_1ST; + else if ( !strcasecmp(mode,"rand") ) buf->prune.mode = PRUNE_MODE_RAND; + else error("The mode \"%s\" is not recognised\n",mode); + return 0; + + case PRUNE_AF_TAG: + va_start(args, key); + buf->prune.af_tag = strdup(va_arg(args,char*)); + va_end(args); + return 0; + + case MARK: + va_start(args, key); + buf->mark.expr = strdup(va_arg(args,char*)); + if ( !strcasecmp(buf->mark.expr,"overlap") ) buf->mark.mode = MARK_OVERLAP; + else if ( !strcasecmp(buf->mark.expr,"dup") ) buf->mark.mode = MARK_DUP; + else buf->mark.mode = MARK_EXPR; + va_end(args); + return 0; + + case MARK_MISSING_EXPR: + va_start(args, key); + char *expr = va_arg(args,char*); + if ( !strcasecmp(expr,"0") ) + { + buf->mark.missing_expr = MARK_MISSING_SCALAR; + buf->mark.missing_value = 0; + } + else if ( !strcasecmp(expr,"DP") ) + { + if ( buf->mark.mode!=MARK_EXPR ) error("Only the combination of --mark 'min(QUAL)' with --missing DP is currently supported\n"); + buf->mark.missing_expr = MARK_MISSING_MAX_DP; + } + else + error("todo: MARK_MISSING_EXPR=%s\n",expr); + va_end(args); + return 0; + } + return 0; +} + +void *vcfbuf_get(vcfbuf_t *buf, vcfbuf_opt_t key, ...) +{ + va_list args; + va_start(args, key); + if ( key==MARK ) + return &buf->mark.last; + va_end(args); + return NULL; +} + +int vcfbuf_nsites(vcfbuf_t *buf) +{ + return buf->rbuf.n; +} + +bcf1_t *vcfbuf_push(vcfbuf_t *buf, bcf1_t *rec) +{ + // make sure the caller is using the buffer correctly and calls vcfbuf_flush() + // before placing next vcfbuf_push() call + assert(buf->status!=dirty); + if ( !buf->dummy ) buf->status = dirty; + + rbuf_expand0(&buf->rbuf, vcfrec_t, buf->rbuf.n+1, buf->vcf); + int i = rbuf_append(&buf->rbuf); + if ( !buf->vcf[i].rec ) buf->vcf[i].rec = bcf_init1(); + + bcf1_t *ret = buf->vcf[i].rec; + buf->vcf[i].rec = rec; + buf->vcf[i].af_set = 0; + buf->vcf[i].filter = buf->ld.filter1; + buf->ld.filter1 = 0; + + return ret; +} + +bcf1_t *vcfbuf_peek(vcfbuf_t *buf, int idx) +{ + buf->status = clean; + int i = rbuf_kth(&buf->rbuf, idx); + return i<0 ? NULL : buf->vcf[i].rec; +} + +bcf1_t *vcfbuf_remove(vcfbuf_t *buf, int idx) +{ + int i = rbuf_kth(&buf->rbuf, idx); + if ( i<0 ) return NULL; + bcf1_t *rec = buf->vcf[i].rec; + rbuf_remove_kth(&buf->rbuf, vcfrec_t, idx, buf->vcf); + return rec; +} + +static int cmpvrec(const void *_a, const void *_b) +{ + vcfrec_t *a = *((vcfrec_t**) _a); + vcfrec_t *b = *((vcfrec_t**) _b); + if ( a->af < b->af ) return -1; + if ( a->af == b->af ) return 0; + return 1; +} +static int cmpint_desc(const void *_a, const void *_b) +{ + int a = *((int*)_a); + int b = *((int*)_b); + if ( a < b ) return 1; + if ( a == b ) return 0; + return -1; +} + +static void _prune_sites(vcfbuf_t *buf, int flush_all) +{ + + int nbuf = flush_all ? buf->rbuf.n : buf->rbuf.n - 1; + + int nprune = nbuf - buf->prune.max_sites; + int i,k,irec = 0; + if ( buf->prune.mode==PRUNE_MODE_1ST ) + { + int eoff = flush_all ? 1 : 2; + for (i=0; irbuf, vcfrec_t, buf->rbuf.n - eoff, buf->vcf); + return; + } + if ( buf->prune.mode==PRUNE_MODE_RAND ) + { + int eoff = flush_all ? 0 : 1; + for (i=0; irbuf.n - eoff) * hts_drand48(); + rbuf_remove_kth(&buf->rbuf, vcfrec_t, j, buf->vcf); + } + return; + } + + if ( nbuf > buf->prune.mvrec ) + { + buf->prune.idx = (int*) realloc(buf->prune.idx, nbuf*sizeof(int)); + buf->prune.vrec = (vcfrec_t**) realloc(buf->prune.vrec, nbuf*sizeof(vcfrec_t*)); + buf->prune.mvrec = nbuf; + } + + // set allele frequency and prepare buffer for sorting + for (i=-1; rbuf_next(&buf->rbuf,&i) && irecvcf[i].rec; + if ( line->n_allele > buf->prune.mac ) + { + buf->prune.ac = (int*) realloc(buf->prune.ac, line->n_allele*sizeof(*buf->prune.ac)); + buf->prune.mac = line->n_allele; + } + if ( !buf->vcf[i].af_set ) + { + buf->vcf[i].af = 0; + if ( buf->prune.af_tag ) + { + if ( bcf_get_info_float(buf->hdr,line,buf->prune.af_tag,&buf->prune.farr, &buf->prune.mfarr) > 0 ) buf->vcf[i].af = buf->prune.farr[0]; + } + else if ( bcf_calc_ac(buf->hdr, line, buf->prune.ac, BCF_UN_INFO|BCF_UN_FMT) ) + { + int ntot = buf->prune.ac[0], nalt = 0; + for (k=1; kn_allele; k++) nalt += buf->prune.ac[k]; + buf->vcf[i].af = ntot ? (float)nalt/ntot : 0; + } + buf->vcf[i].af_set = 1; + } + buf->vcf[i].idx = irec; + buf->prune.vrec[irec++] = &buf->vcf[i]; + } + + // sort by allele frequency, low AF will be removed preferentially + qsort(buf->prune.vrec, nbuf, sizeof(*buf->prune.vrec), cmpvrec); + + // sort the rbuf indexes to be pruned descendently so that j-th rbuf index + // is removed before i-th index if iprune.idx[i] = buf->prune.vrec[i]->idx; + + qsort(buf->prune.idx, nprune, sizeof(int), cmpint_desc); + + for (i=0; irbuf, vcfrec_t, buf->prune.idx[i], buf->vcf); +} + +static int mark_dup_can_flush_(vcfbuf_t *buf, int flush_all) +{ + int flush = flush_all; + mark_t *mark = &buf->mark; + if ( buf->status==dirty ) + { + // a new site was just added by vcfbuf_push() + rbuf_expand0(&mark->rbuf, uint8_t, buf->rbuf.n, mark->mark); + int i = rbuf_append(&mark->rbuf); + mark->mark[i] = 0; + + if ( buf->rbuf.n==1 ) goto flush; + + // there is at least one previous site, check if it's a duplicate + int k1 = rbuf_kth(&buf->rbuf, -1); + int k2 = rbuf_kth(&buf->rbuf, -2); + vcfrec_t *rec1 = &buf->vcf[k1]; + vcfrec_t *rec2 = &buf->vcf[k2]; + + int is_dup = 1; + if ( rec1->rec->rid!=rec2->rec->rid ) is_dup = 0; + else if ( rec1->rec->pos!=rec2->rec->pos ) is_dup = 0; + + if ( is_dup ) + { + // it is, mark the last two sites as duplicates + int k1 = rbuf_kth(&mark->rbuf, -1); + int k2 = rbuf_kth(&mark->rbuf, -2); + mark->mark[k1] = 1; + mark->mark[k2] = 1; + goto flush; + } + + // the last site is not a duplicate with the previous, all sites but the last one can be flushed + flush = 1; + } + else if ( buf->rbuf.n > 1 ) flush = 1; + +flush: + if ( !flush ) return 0; + + int i = rbuf_shift(&mark->rbuf); + mark->last = mark->mark[i]; + return 1; +} + +static int mark_overlap_helper_(vcfbuf_t *buf, int flush_all) +{ + if ( buf->status!=dirty ) return flush_all; + + int flush = flush_all; + mark_t *mark = &buf->mark; + + // a new site was just added by vcfbuf_push() + buf->status = clean; + + rbuf_expand0(&mark->rbuf, uint8_t, buf->rbuf.n, mark->mark); + int i = rbuf_append(&mark->rbuf); + mark->mark[i] = 0; + + // determine beg and end of the last record that was just added + i = rbuf_last(&buf->rbuf); + vcfrec_t *last = &buf->vcf[i]; + if ( mark->overlap_rid != last->rec->rid ) mark->overlap_end = 0; + int beg_pos = last->rec->pos; + int end_pos = last->rec->pos + last->rec->rlen - 1; + + // Assuming left-aligned indels. In case it is a deletion, the real variant + // starts one base after. If an insertion, the overlap with previous is zero + int imin = last->rec->rlen; + for (i=0; irec->n_allele; i++) + { + char *ref = last->rec->d.allele[0]; + char *alt = last->rec->d.allele[i]; + if ( *alt == '<' ) continue; // ignore symbolic alleles + while ( *ref && *alt && nt_to_upper(*ref)==nt_to_upper(*alt) ) { ref++; alt++; } + if ( imin > ref - last->rec->d.allele[0] ) imin = ref - last->rec->d.allele[0]; + } + if ( beg_pos <= mark->overlap_end ) + { + // the new site overlaps with the previous + beg_pos += imin; + if ( beg_pos > end_pos ) end_pos = beg_pos; + } + if ( buf->rbuf.n==1 ) + { + mark->overlap_rid = last->rec->rid; + mark->overlap_end = end_pos; + return flush; + } + if ( beg_pos <= mark->overlap_end ) + { + if ( mark->overlap_end < end_pos ) mark->overlap_end = end_pos; + int k1 = rbuf_kth(&mark->rbuf, -1); + int k2 = rbuf_kth(&mark->rbuf, -2); + mark->mark[k1] = 1; + mark->mark[k2] = 1; + } + else + { + if ( mark->overlap_end < end_pos ) mark->overlap_end = end_pos; + flush = 1; + } + return flush; +} + + +static int mark_overlap_can_flush_(vcfbuf_t *buf, int flush_all) +{ + int flush = flush_all; + if ( buf->status==dirty ) flush = mark_overlap_helper_(buf,flush_all); + else if ( buf->rbuf.n > 1 ) flush = 1; + if ( !flush ) return 0; + + mark_t *mark = &buf->mark; + int i = rbuf_shift(&mark->rbuf); + mark->last = mark->mark[i]; + return 1; +} + + +static int records_overlap(bcf1_t *a, bcf1_t *b) +{ + if ( a->rid != b->rid ) return 0; + if ( a->pos + a->rlen - 1 < b->pos ) return 0; + return 1; +} + +static int cmp_overlap_ptr_asc(const void *aptr, const void *bptr) +{ + overlap_t *a = *((overlap_t**)aptr); + overlap_t *b = *((overlap_t**)bptr); + if ( a->value < b->value ) return -1; + if ( a->value > b->value ) return 1; + return 0; +} +static void mark_expr_missing_reset_(vcfbuf_t *buf) +{ + buf->mark.max_qual = 0; + buf->mark.max_qual_dp = 0; +} +static void mark_expr_missing_prep_(vcfbuf_t *buf, overlap_t *olap) +{ + int nval = bcf_get_info_int32(buf->hdr,olap->rec,"DP",&buf->mark.tmpi,&buf->mark.ntmpi); + if ( nval!=1 ) return; + + olap->dp = buf->mark.tmpi[0]; + if ( bcf_float_is_missing(olap->rec->qual) ) return; + if ( buf->mark.max_qual < olap->rec->qual ) + { + buf->mark.max_qual = olap->rec->qual; + buf->mark.max_qual_dp = olap->dp; + } +} +static void mark_expr_missing_set_(vcfbuf_t *buf, overlap_t *olap) +{ + if ( !bcf_float_is_missing(olap->rec->qual) ) return; + if ( !buf->mark.max_qual_dp ) return; + + // scale QUAL of the most confident variant in the overlap proportionally to the coverage + // and use that to prioritize the records + olap->value = buf->mark.max_qual * olap->dp / buf->mark.max_qual_dp; +} +static int mark_expr_can_flush_(vcfbuf_t *buf, int flush_all) +{ + mark_t *mark = &buf->mark; + if ( strcasecmp("min(QUAL)",mark->expr) ) error("Todo; at this time only min(QUAL) is supported\n"); + + int flush = flush_all; + if ( buf->status==dirty ) + { + flush = mark_overlap_helper_(buf,flush_all); + if ( !flush ) return 0; + + if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_reset_(buf); + + // init overlaps, each overlap_t structure keeps a list of overlapping records, symmetrical + size_t nori = mark->nbuf; + hts_resize(overlap_t, buf->rbuf.n, &mark->nbuf, &mark->buf, HTS_RESIZE_CLEAR); + hts_resize(overlap_t*, buf->rbuf.n, &nori, &mark->buf_ptr, HTS_RESIZE_CLEAR); + int i; + for (i=0; irbuf.n; i++) + { + overlap_t *oi = &mark->buf[i]; + int j = rbuf_kth(&buf->rbuf, i); + assert(j>=0); + bcf1_t *rec = buf->vcf[j].rec; + assert(rec); + oi->rec = rec; + + // todo: other than QUAL values + oi->value = bcf_float_is_missing(rec->qual) ? mark->missing_value : rec->qual; + if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_prep_(buf,oi); + if ( oi->bset ) + { + kbs_resize(&oi->bset,buf->rbuf.n); + kbs_clear(oi->bset); + } + else + oi->bset = kbs_init(buf->rbuf.n); + oi->idx = i; + mark->buf_ptr[i] = oi; + mark->mark[oi->idx] = 0; + } + int nolap = 0; + for (i=0; irbuf.n; i++) + { + overlap_t *oi = &mark->buf[i]; + if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_set_(buf,oi); + int j; + for (j=i+1; jrbuf.n; j++) + { + overlap_t *oj = &mark->buf[j]; + if ( !records_overlap(oi->rec,oj->rec) ) continue; + kbs_insert(oi->bset,j); + kbs_insert(oj->bset,i); + nolap++; + } + } + + // sort according to the requested criteria, currently only min(QUAL) + qsort(mark->buf_ptr,buf->rbuf.n,sizeof(*mark->buf_ptr),cmp_overlap_ptr_asc); // todo: other than min() + + // go through the list sorted by overlap_t.value, eg QUAL + for (i=0; nolap && irbuf.n; i++) + { + kbitset_iter_t itr; + overlap_t *oi = mark->buf_ptr[i]; + kbs_start(&itr); + int j; + while ((j=kbs_next(oi->bset, &itr)) >= 0) + { + kbs_delete(oi->bset,j); + assert(nolap); + assert(kbs_exists(mark->buf[j].bset,oi->idx)); + kbs_delete(mark->buf[j].bset,oi->idx); + nolap--; + } + j = rbuf_kth(&mark->rbuf,oi->idx); + mark->mark[j] = 1; + } + } + else if ( buf->rbuf.n > 1 ) flush = 1; + if ( !flush ) return 0; + + int i = rbuf_shift(&mark->rbuf); + mark->last = mark->mark[i]; + return 1; +} + +bcf1_t *vcfbuf_flush(vcfbuf_t *buf, int flush_all) +{ + int i,j; + + // nothing to do, no lines in the buffer + if ( buf->rbuf.n==0 ) return NULL; + + // dummy mode, always flushing + if ( buf->dummy ) goto ret; + + // pruning mode + if ( buf->win ) + { + int can_flush = flush_all; + i = rbuf_kth(&buf->rbuf, 0); // first + j = rbuf_last(&buf->rbuf); // last + if ( buf->vcf[i].rec->rid != buf->vcf[j].rec->rid ) can_flush = 1; + else if ( buf->win > 0 ) + { + if ( buf->rbuf.n > buf->win ) can_flush = 1; + } + else if ( buf->win < 0 ) + { + if ( !(buf->vcf[i].rec->pos - buf->vcf[j].rec->pos > buf->win) ) can_flush = 1; + } + buf->status = clean; + if ( !can_flush ) return NULL; + if ( buf->prune.max_sites && buf->prune.max_sites < buf->rbuf.n ) _prune_sites(buf, flush_all); + goto ret; + } + + // overlaps and duplicates + if ( buf->mark.mode ) + { + int can_flush = 0; + if ( buf->mark.mode==MARK_OVERLAP ) + { + if ( mark_overlap_can_flush_(buf,flush_all) ) can_flush = 1; + } + else if ( buf->mark.mode==MARK_DUP ) + { + if ( mark_dup_can_flush_(buf,flush_all) ) can_flush = 1; + } + if ( buf->mark.mode==MARK_EXPR ) + { + if ( mark_expr_can_flush_(buf,flush_all) ) can_flush = 1; + } + buf->status = clean; + if ( !can_flush ) return NULL; + goto ret; + } + +ret: + buf->status = clean; + i = rbuf_shift(&buf->rbuf); + return buf->vcf[i].rec; +} + +static double _estimate_af(int8_t *ptr, int size, int nvals, int nsamples) +{ + int i,j, nref = 0, nalt = 0; + for (i=0; in_sample!=brec->n_sample ) error("Different number of samples: %d vs %d\n",arec->n_sample,brec->n_sample); + assert( arec->n_sample ); + + int i,j,igt = bcf_hdr_id2int(buf->hdr, BCF_DT_ID, "GT"); + bcf_unpack(arec, BCF_UN_FMT); + bcf_unpack(brec, BCF_UN_FMT); + bcf_fmt_t *afmt = NULL, *bfmt = NULL; + for (i=0; in_fmt; i++) + if ( arec->d.fmt[i].id==igt ) { afmt = &arec->d.fmt[i]; break; } + if ( !afmt ) return -1; // no GT tag + for (i=0; in_fmt; i++) + if ( brec->d.fmt[i].id==igt ) { bfmt = &brec->d.fmt[i]; break; } + if ( !bfmt ) return -1; // no GT tag + + if ( afmt->n==0 ) return -1; // empty?! + if ( bfmt->n==0 ) return -1; // empty?! + if ( afmt->type!=BCF_BT_INT8 ) error("TODO: the GT fmt_type is not int8!\n"); + if ( bfmt->type!=BCF_BT_INT8 ) error("TODO: the GT fmt_type is not int8!\n"); + + // Determine allele frequencies, this is to sample randomly missing genotypes + double aaf = 0, baf = 0; + if ( buf->ld.rand_missing ) + { + aaf = _estimate_af((int8_t*)afmt->p, afmt->size, afmt->n, arec->n_sample); + baf = _estimate_af((int8_t*)bfmt->p, bfmt->size, bfmt->n, brec->n_sample); + } + + // Calculate r2, lf, hd + double nhd[] = {0,0,0,0,0,0,0,0,0}; + double ab = 0, aa = 0, bb = 0, a = 0, b = 0; + int nab = 0, ndiff = 0; + int an_tot = 0, bn_tot = 0; + for (i=0; in_sample; i++) + { + int8_t *aptr = (int8_t*) (afmt->p + i*afmt->size); + int8_t *bptr = (int8_t*) (bfmt->p + i*bfmt->size); + int adsg = 0, bdsg = 0; // dosages (0,1,2) at sites (a,b) + int an = 0, bn = 0; // number of alleles at sites (a,b) + for (j=0; jn; j++) + { + if ( aptr[j]==bcf_int8_vector_end ) break; + if ( aptr[j]==bcf_gt_missing ) + { + if ( !buf->ld.rand_missing ) break; + if ( hts_drand48() >= aaf ) adsg += 1; + } + else if ( bcf_gt_allele(aptr[j]) ) adsg += 1; + an++; + } + for (j=0; jn; j++) + { + if ( bptr[j]==bcf_int8_vector_end ) break; + if ( bptr[j]==bcf_gt_missing ) + { + if ( !buf->ld.rand_missing ) break; + if ( hts_drand48() >= baf ) bdsg += 1; + } + else if ( bcf_gt_allele(bptr[j]) ) bdsg += 1; + bn++; + } + if ( an && bn ) + { + an_tot += an; + aa += adsg*adsg; + a += adsg; + + bn_tot += bn; + bb += bdsg*bdsg; + b += bdsg; + + if ( adsg!=bdsg ) ndiff++; + ab += adsg*bdsg; + nab++; + } + if ( an==2 && bn==2 ) // for now only diploid genotypes + { + assert( adsg<=2 && bdsg<=2 ); + nhd[ bdsg*3 + adsg ]++; + } + } + if ( !nab ) return -1; // no data in common for the two sites + + double pa = a/an_tot; + double pb = b/bn_tot; + double cor; + if ( !ndiff ) cor = 1; + else + { + if ( aa == a*a/nab || bb == b*b/nab ) // zero variance, add small noise + { + aa += 1e-4; + bb += 1e-4; + ab += 1e-4; + a += 1e-2; + b += 1e-2; + nab++; + } + cor = (ab - a*b/nab) / sqrt(aa - a*a/nab) / sqrt(bb - b*b/nab); + } + + ld->val[VCFBUF_LD_IDX_R2] = cor * cor; + + // Lewontin's normalization of D. Also we cap at 1 as the calculation + // can result in values bigger than 1 for high AFs. + ld->val[VCFBUF_LD_IDX_LD] = cor * sqrt(pa*(1-pa)*pb*(1-pb)); + double norm; + if ( ld->val[VCFBUF_LD_IDX_LD] < 0 ) + norm = -pa*pb > -(1-pa)*(1-pb) ? -pa*pb : -(1-pa)*(1-pb); + else + norm = pa*(1-pb) > (1-pa)*pb ? pa*(1-pb) : (1-pa)*pb; + if ( norm ) + ld->val[VCFBUF_LD_IDX_LD] = fabs(norm) > fabs(ld->val[VCFBUF_LD_IDX_LD]) ? ld->val[VCFBUF_LD_IDX_LD]/norm : 1; + if ( !ld->val[VCFBUF_LD_IDX_LD] ) + ld->val[VCFBUF_LD_IDX_LD] = fabs(ld->val[VCFBUF_LD_IDX_LD]); // avoid "-0" on output + + ld->val[VCFBUF_LD_IDX_HD] = + (nhd[0] + nhd[1]/2. + nhd[3]/2. + nhd[4]/4.)*(nhd[4]/4. + nhd[5]/2. + nhd[7]/2. + nhd[8]) + - (nhd[1]/2. + nhd[2] + nhd[4]/4. + nhd[5]/2.)*(nhd[3]/2. + nhd[4]/4. + nhd[6] + nhd[7]/2.); + ld->val[VCFBUF_LD_IDX_HD] /= nab; + ld->val[VCFBUF_LD_IDX_HD] /= nab+1; + + return 0; +} + +int vcfbuf_ld(vcfbuf_t *buf, bcf1_t *rec, vcfbuf_ld_t *ld) +{ + int ret = -1; + if ( !buf->rbuf.n ) return ret; + + int j, i = buf->rbuf.f; + + // Relying on vcfbuf being properly flushed - all sites in the buffer + // must come from the same chromosome + if ( buf->vcf[i].rec->rid != rec->rid ) return ret; + + vcfbuf_ld_t tmp; + for (j=0; jval[j] = -HUGE_VAL; + ld->rec[j] = NULL; + } + + for (i=-1; rbuf_next(&buf->rbuf,&i); ) + { + if ( buf->vcf[i].filter ) continue; + if ( _calc_r2_ld(buf, buf->vcf[i].rec, rec, &tmp) < 0 ) continue; // missing genotypes + + int done = 0; + for (j=0; jval[j] < tmp.val[j] ) + { + ld->val[j] = tmp.val[j]; + ld->rec[j] = buf->vcf[i].rec; + } + if ( buf->ld.max[j] < tmp.val[j] ) done = 1; + ret = 0; + } + if ( done ) return ret; + } + return ret; +} + + diff --git a/shared/package-files/3c/3c21cd0797c79db2455f1f7058f01d9dc4f78c2489dce963e3aaccedbad2055f/_values_copy_native.h b/shared/package-files/3c/3c21cd0797c79db2455f1f7058f01d9dc4f78c2489dce963e3aaccedbad2055f/_values_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..5fba88bfa4ef1f9c5d2851ac91b4306acab0396c --- /dev/null +++ b/shared/package-files/3c/3c21cd0797c79db2455f1f7058f01d9dc4f78c2489dce963e3aaccedbad2055f/_values_copy_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _values_copy_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor _values_copy(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/3c/3c22177f5c83fbc5d3c975307332c1ccf7d931a4d0153719bea12409c0e6f9ee/times.cpython-311.pyc b/shared/package-files/3c/3c22177f5c83fbc5d3c975307332c1ccf7d931a4d0153719bea12409c0e6f9ee/times.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0337c5eb50a7e6f01785595d8f825c0f99fcf510 Binary files /dev/null and b/shared/package-files/3c/3c22177f5c83fbc5d3c975307332c1ccf7d931a4d0153719bea12409c0e6f9ee/times.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c248bf14e77e3fdde669b9a396a5ec746877d0290cd496b468bf38efa501bbc/_thnn_fused_gru_cell_backward_ops.h b/shared/package-files/3c/3c248bf14e77e3fdde669b9a396a5ec746877d0290cd496b468bf38efa501bbc/_thnn_fused_gru_cell_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..93e59c3de570f26f17d746f3713f668ac77d50d8 --- /dev/null +++ b/shared/package-files/3c/3c248bf14e77e3fdde669b9a396a5ec746877d0290cd496b468bf38efa501bbc/_thnn_fused_gru_cell_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _thnn_fused_gru_cell_backward { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_thnn_fused_gru_cell_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_thnn_fused_gru_cell_backward(Tensor grad_hy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias); +}; + +struct TORCH_API _thnn_fused_gru_cell_backward_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_thnn_fused_gru_cell_backward"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_thnn_fused_gru_cell_backward.out(Tensor grad_hy, Tensor workspace, bool has_bias, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))"; + static ::std::tuple call(const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/3c/3c2835085174030ad4462f15f681a837a83bc6cc51ccac6c5142f4359ff137c3/test_kcutsets.py b/shared/package-files/3c/3c2835085174030ad4462f15f681a837a83bc6cc51ccac6c5142f4359ff137c3/test_kcutsets.py new file mode 100644 index 0000000000000000000000000000000000000000..67c0bfd1f337f38b9dd91b655162fee3d9386ab0 --- /dev/null +++ b/shared/package-files/3c/3c2835085174030ad4462f15f681a837a83bc6cc51ccac6c5142f4359ff137c3/test_kcutsets.py @@ -0,0 +1,270 @@ +# Jordi Torrents +# Test for k-cutsets +import itertools + +import pytest + +import networkx as nx +from networkx.algorithms import flow +from networkx.algorithms.connectivity.kcutsets import _is_separating_set + +MAX_CUTSETS_TO_TEST = 4 # originally 100. cut to decrease testing time + +flow_funcs = [ + flow.boykov_kolmogorov, + flow.dinitz, + flow.edmonds_karp, + flow.preflow_push, + flow.shortest_augmenting_path, +] + + +## +# Some nice synthetic graphs +## +def graph_example_1(): + G = nx.convert_node_labels_to_integers( + nx.grid_graph([5, 5]), label_attribute="labels" + ) + rlabels = nx.get_node_attributes(G, "labels") + labels = {v: k for k, v in rlabels.items()} + + for nodes in [ + (labels[(0, 0)], labels[(1, 0)]), + (labels[(0, 4)], labels[(1, 4)]), + (labels[(3, 0)], labels[(4, 0)]), + (labels[(3, 4)], labels[(4, 4)]), + ]: + new_node = G.order() + 1 + # Petersen graph is triconnected + P = nx.petersen_graph() + G = nx.disjoint_union(G, P) + # Add two edges between the grid and P + G.add_edge(new_node + 1, nodes[0]) + G.add_edge(new_node, nodes[1]) + # K5 is 4-connected + K = nx.complete_graph(5) + G = nx.disjoint_union(G, K) + # Add three edges between P and K5 + G.add_edge(new_node + 2, new_node + 11) + G.add_edge(new_node + 3, new_node + 12) + G.add_edge(new_node + 4, new_node + 13) + # Add another K5 sharing a node + G = nx.disjoint_union(G, K) + nbrs = G[new_node + 10] + G.remove_node(new_node + 10) + for nbr in nbrs: + G.add_edge(new_node + 17, nbr) + G.add_edge(new_node + 16, new_node + 5) + return G + + +def torrents_and_ferraro_graph(): + G = nx.convert_node_labels_to_integers( + nx.grid_graph([5, 5]), label_attribute="labels" + ) + rlabels = nx.get_node_attributes(G, "labels") + labels = {v: k for k, v in rlabels.items()} + + for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]: + new_node = G.order() + 1 + # Petersen graph is triconnected + P = nx.petersen_graph() + G = nx.disjoint_union(G, P) + # Add two edges between the grid and P + G.add_edge(new_node + 1, nodes[0]) + G.add_edge(new_node, nodes[1]) + # K5 is 4-connected + K = nx.complete_graph(5) + G = nx.disjoint_union(G, K) + # Add three edges between P and K5 + G.add_edge(new_node + 2, new_node + 11) + G.add_edge(new_node + 3, new_node + 12) + G.add_edge(new_node + 4, new_node + 13) + # Add another K5 sharing a node + G = nx.disjoint_union(G, K) + nbrs = G[new_node + 10] + G.remove_node(new_node + 10) + for nbr in nbrs: + G.add_edge(new_node + 17, nbr) + # Commenting this makes the graph not biconnected !! + # This stupid mistake make one reviewer very angry :P + G.add_edge(new_node + 16, new_node + 8) + + for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]: + new_node = G.order() + 1 + # Petersen graph is triconnected + P = nx.petersen_graph() + G = nx.disjoint_union(G, P) + # Add two edges between the grid and P + G.add_edge(new_node + 1, nodes[0]) + G.add_edge(new_node, nodes[1]) + # K5 is 4-connected + K = nx.complete_graph(5) + G = nx.disjoint_union(G, K) + # Add three edges between P and K5 + G.add_edge(new_node + 2, new_node + 11) + G.add_edge(new_node + 3, new_node + 12) + G.add_edge(new_node + 4, new_node + 13) + # Add another K5 sharing two nodes + G = nx.disjoint_union(G, K) + nbrs = G[new_node + 10] + G.remove_node(new_node + 10) + for nbr in nbrs: + G.add_edge(new_node + 17, nbr) + nbrs2 = G[new_node + 9] + G.remove_node(new_node + 9) + for nbr in nbrs2: + G.add_edge(new_node + 18, nbr) + return G + + +# Helper function +def _check_separating_sets(G): + for cc in nx.connected_components(G): + if len(cc) < 3: + continue + Gc = G.subgraph(cc) + node_conn = nx.node_connectivity(Gc) + all_cuts = nx.all_node_cuts(Gc) + # Only test a limited number of cut sets to reduce test time. + for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST): + assert node_conn == len(cut) + assert not nx.is_connected(nx.restricted_view(G, cut, [])) + + +@pytest.mark.slow +def test_torrents_and_ferraro_graph(): + G = torrents_and_ferraro_graph() + _check_separating_sets(G) + + +def test_example_1(): + G = graph_example_1() + _check_separating_sets(G) + + +def test_random_gnp(): + G = nx.gnp_random_graph(100, 0.1, seed=42) + _check_separating_sets(G) + + +def test_shell(): + constructor = [(20, 80, 0.8), (80, 180, 0.6)] + G = nx.random_shell_graph(constructor, seed=42) + _check_separating_sets(G) + + +def test_configuration(): + deg_seq = nx.random_powerlaw_tree_sequence(100, tries=5, seed=72) + G = nx.Graph(nx.configuration_model(deg_seq)) + G.remove_edges_from(nx.selfloop_edges(G)) + _check_separating_sets(G) + + +def test_karate(): + G = nx.karate_club_graph() + _check_separating_sets(G) + + +def _generate_no_biconnected(max_attempts=50): + attempts = 0 + while True: + G = nx.fast_gnp_random_graph(100, 0.0575, seed=42) + if nx.is_connected(G) and not nx.is_biconnected(G): + attempts = 0 + yield G + else: + if attempts >= max_attempts: + msg = f"Tried {attempts} times: no suitable Graph." + raise Exception(msg) + else: + attempts += 1 + + +def test_articulation_points(): + Ggen = _generate_no_biconnected() + for i in range(1): # change 1 to 3 or more for more realizations. + G = next(Ggen) + articulation_points = [{a} for a in nx.articulation_points(G)] + for cut in nx.all_node_cuts(G): + assert cut in articulation_points + + +def test_grid_2d_graph(): + # All minimum node cuts of a 2d grid + # are the four pairs of nodes that are + # neighbors of the four corner nodes. + G = nx.grid_2d_graph(5, 5) + solution = [{(0, 1), (1, 0)}, {(3, 0), (4, 1)}, {(3, 4), (4, 3)}, {(0, 3), (1, 4)}] + for cut in nx.all_node_cuts(G): + assert cut in solution + + +def test_disconnected_graph(): + G = nx.fast_gnp_random_graph(100, 0.01, seed=42) + cuts = nx.all_node_cuts(G) + pytest.raises(nx.NetworkXError, next, cuts) + + +@pytest.mark.slow +def test_alternative_flow_functions(): + graphs = [nx.grid_2d_graph(4, 4), nx.cycle_graph(5)] + for G in graphs: + node_conn = nx.node_connectivity(G) + for flow_func in flow_funcs: + all_cuts = nx.all_node_cuts(G, flow_func=flow_func) + # Only test a limited number of cut sets to reduce test time. + for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST): + assert node_conn == len(cut) + assert not nx.is_connected(nx.restricted_view(G, cut, [])) + + +def test_is_separating_set_complete_graph(): + G = nx.complete_graph(5) + assert _is_separating_set(G, {0, 1, 2, 3}) + + +def test_is_separating_set(): + for i in [5, 10, 15]: + G = nx.star_graph(i) + max_degree_node = max(G, key=G.degree) + assert _is_separating_set(G, {max_degree_node}) + + +def test_non_repeated_cuts(): + # The algorithm was repeating the cut {0, 1} for the giant biconnected + # component of the Karate club graph. + K = nx.karate_club_graph() + bcc = max(list(nx.biconnected_components(K)), key=len) + G = K.subgraph(bcc) + solution = [{32, 33}, {2, 33}, {0, 3}, {0, 1}, {29, 33}] + cuts = list(nx.all_node_cuts(G)) + assert len(solution) == len(cuts) + for cut in cuts: + assert cut in solution + + +def test_cycle_graph(): + G = nx.cycle_graph(5) + solution = [{0, 2}, {0, 3}, {1, 3}, {1, 4}, {2, 4}] + cuts = list(nx.all_node_cuts(G)) + assert len(solution) == len(cuts) + for cut in cuts: + assert cut in solution + + +def test_complete_graph(): + G = nx.complete_graph(5) + assert nx.node_connectivity(G) == 4 + assert list(nx.all_node_cuts(G)) == [] + + +def test_all_node_cuts_simple_case(): + G = nx.complete_graph(5) + G.remove_edges_from([(0, 1), (3, 4)]) + expected = [{0, 1, 2}, {2, 3, 4}] + actual = list(nx.all_node_cuts(G)) + assert len(actual) == len(expected) + for cut in actual: + assert cut in expected diff --git a/shared/package-files/3c/3c2a7fd17a1b5f681d433158aa73ecc9302cc2abe2198a0feae2454392fc2325/test_qs.cpython-311.pyc b/shared/package-files/3c/3c2a7fd17a1b5f681d433158aa73ecc9302cc2abe2198a0feae2454392fc2325/test_qs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91d4c3814b263633d71a4c459e3fcfda111a6f88 Binary files /dev/null and b/shared/package-files/3c/3c2a7fd17a1b5f681d433158aa73ecc9302cc2abe2198a0feae2454392fc2325/test_qs.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c2cbb06ca086f2f1571a9aa0e365088d01eff97a023458a52afb2e6773dba74/filters.py b/shared/package-files/3c/3c2cbb06ca086f2f1571a9aa0e365088d01eff97a023458a52afb2e6773dba74/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e989e22bb6d7e79b6eab34103edd263d82694fd4 --- /dev/null +++ b/shared/package-files/3c/3c2cbb06ca086f2f1571a9aa0e365088d01eff97a023458a52afb2e6773dba74/filters.py @@ -0,0 +1,95 @@ +"""Filter factories to hide or show sets of nodes and edges. + +These filters return the function used when creating `SubGraph`. +""" + +__all__ = [ + "no_filter", + "hide_nodes", + "hide_edges", + "hide_multiedges", + "hide_diedges", + "hide_multidiedges", + "show_nodes", + "show_edges", + "show_multiedges", + "show_diedges", + "show_multidiedges", +] + + +def no_filter(*items): + """Returns a filter function that always evaluates to True.""" + return True + + +def hide_nodes(nodes): + """Returns a filter function that hides specific nodes.""" + nodes = set(nodes) + return lambda node: node not in nodes + + +def hide_diedges(edges): + """Returns a filter function that hides specific directed edges.""" + edges = {(u, v) for u, v in edges} + return lambda u, v: (u, v) not in edges + + +def hide_edges(edges): + """Returns a filter function that hides specific undirected edges.""" + alledges = set(edges) | {(v, u) for (u, v) in edges} + return lambda u, v: (u, v) not in alledges + + +def hide_multidiedges(edges): + """Returns a filter function that hides specific multi-directed edges.""" + edges = {(u, v, k) for u, v, k in edges} + return lambda u, v, k: (u, v, k) not in edges + + +def hide_multiedges(edges): + """Returns a filter function that hides specific multi-undirected edges.""" + alledges = set(edges) | {(v, u, k) for (u, v, k) in edges} + return lambda u, v, k: (u, v, k) not in alledges + + +# write show_nodes as a class to make SubGraph pickleable +class show_nodes: + """Filter class to show specific nodes. + + Attach the set of nodes as an attribute to speed up this commonly used filter + + Note that another allowed attribute for filters is to store the number of nodes + on the filter as attribute `length` (used in `__len__`). It is a user + responsibility to ensure this attribute is accurate if present. + """ + + def __init__(self, nodes): + self.nodes = set(nodes) + + def __call__(self, node): + return node in self.nodes + + +def show_diedges(edges): + """Returns a filter function that shows specific directed edges.""" + edges = {(u, v) for u, v in edges} + return lambda u, v: (u, v) in edges + + +def show_edges(edges): + """Returns a filter function that shows specific undirected edges.""" + alledges = set(edges) | {(v, u) for (u, v) in edges} + return lambda u, v: (u, v) in alledges + + +def show_multidiedges(edges): + """Returns a filter function that shows specific multi-directed edges.""" + edges = {(u, v, k) for u, v, k in edges} + return lambda u, v, k: (u, v, k) in edges + + +def show_multiedges(edges): + """Returns a filter function that shows specific multi-undirected edges.""" + alledges = set(edges) | {(v, u, k) for (u, v, k) in edges} + return lambda u, v, k: (u, v, k) in alledges diff --git a/shared/package-files/3c/3c2cff9f89f3a55a322dda1ab92c5b21e6fda78a2219f30c21f0eb0e4d507c68/mac_croatian.cpython-311.pyc b/shared/package-files/3c/3c2cff9f89f3a55a322dda1ab92c5b21e6fda78a2219f30c21f0eb0e4d507c68/mac_croatian.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58526a33eb93581038e85d0b1006e6a8f381fe02 Binary files /dev/null and b/shared/package-files/3c/3c2cff9f89f3a55a322dda1ab92c5b21e6fda78a2219f30c21f0eb0e4d507c68/mac_croatian.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c2eac68df76a9838aa75c888331710bb34392ea8b474816c88ca0dd8a48e07c/_sfdp_pattern_16.cpython-311.pyc b/shared/package-files/3c/3c2eac68df76a9838aa75c888331710bb34392ea8b474816c88ca0dd8a48e07c/_sfdp_pattern_16.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f0941cd7b734abf7f731b212eba9507cd3f4d8d Binary files /dev/null and b/shared/package-files/3c/3c2eac68df76a9838aa75c888331710bb34392ea8b474816c88ca0dd8a48e07c/_sfdp_pattern_16.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c34d06284b34bbfd6c990b0ab9ac5cc4ae5ccc7202ca5858dcdd8492b5d7779/dataframe.cpython-311.pyc b/shared/package-files/3c/3c34d06284b34bbfd6c990b0ab9ac5cc4ae5ccc7202ca5858dcdd8492b5d7779/dataframe.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d208b00ad3725f623344089a6ac9176e699c11f4 Binary files /dev/null and b/shared/package-files/3c/3c34d06284b34bbfd6c990b0ab9ac5cc4ae5ccc7202ca5858dcdd8492b5d7779/dataframe.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c366c0d6063e3c2518bbd975086c2c0b20cc724d72aa6ec4a81b88c30f829a7/_comm_mode.py b/shared/package-files/3c/3c366c0d6063e3c2518bbd975086c2c0b20cc724d72aa6ec4a81b88c30f829a7/_comm_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..570161b676823382608d8a721b953b474cca1465 --- /dev/null +++ b/shared/package-files/3c/3c366c0d6063e3c2518bbd975086c2c0b20cc724d72aa6ec4a81b88c30f829a7/_comm_mode.py @@ -0,0 +1,735 @@ +# mypy: allow-untyped-defs +import copy +import json +import re +import weakref +from collections import defaultdict +from typing import Any + +import torch +import torch.nn +from torch._guards import detect_fake_mode +from torch.autograd.graph import register_multi_grad_hook +from torch.distributed._tools.mod_tracker import ModTracker +from torch.distributed.tensor._api import DTensor +from torch.nn.modules.module import ( + register_module_forward_hook, + register_module_forward_pre_hook, + register_module_full_backward_pre_hook, +) +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils._pytree import tree_flatten + + +__all__ = ["CommDebugMode"] + +funcol_native = torch.ops._c10d_functional +funcol_py = torch.ops.c10d_functional +funcol_autograd = torch.ops._c10d_functional_autograd +c10d_ops = torch.ops.c10d + +NATIVE_TO_PY_MAPPING = { + funcol_native.all_gather_into_tensor: funcol_py.all_gather_into_tensor, + funcol_native.all_gather_into_tensor_coalesced: funcol_py.all_gather_into_tensor_coalesced, + funcol_native.all_reduce: funcol_py.all_reduce, + funcol_native.all_reduce_coalesced: funcol_py.all_reduce_coalesced, + funcol_native.all_to_all_single: funcol_py.all_to_all_single, + funcol_native.broadcast: funcol_py.broadcast, + funcol_native.reduce_scatter_tensor: funcol_py.reduce_scatter_tensor, + funcol_native.reduce_scatter_tensor_coalesced: funcol_py.reduce_scatter_tensor_coalesced, + # functional ops + funcol_autograd.all_to_all_single: funcol_py.all_to_all_single, +} + +c10d_collective_ops = { + c10d_ops._allgather_base_, + c10d_ops._reduce_scatter_base_, + c10d_ops.allgather_, + c10d_ops.allgather_coalesced_, + c10d_ops.allgather_into_tensor_coalesced_, + c10d_ops.allreduce_, + c10d_ops.allreduce_coalesced_, + c10d_ops.alltoall_, + c10d_ops.alltoall_base_, + c10d_ops.broadcast_, + c10d_ops.gather_, + c10d_ops.scatter_, + c10d_ops.reduce_, + c10d_ops.reduce_scatter_, + c10d_ops.reduce_scatter_tensor_coalesced_, +} + +trivial_ops = { + "aten.detach.default", + "aten.t.default", + "aten.view.default", + "aten._to_copy.default", + "aten.as_strided.default", + "aten.transpose.int", +} + + +class _CommModeModuleTracker(ModTracker): + """ + Inherits ModuleTracker and expands on its functionality to track the + parameters and sharding information of a model at a module-level + """ + + def __init__(self): + super().__init__() + self.module_helper_dict = {} + self.module_parameters_dict = {} + self.module_parents_dict = {} + self.register_forward_hook_handles = {} + self.parent_dict = {} + self.parent_list = [] + self.sharding_dict = {} + self.activation_checkpointing = False + self.name = "" + + def _fw_set_module_hook(self, mod, input, output): + """ + Updates the current module after module finishes running and + all other hooks are resolved + """ + + if self.is_bw: + self.activation_checkpointing = True + else: + self.activation_checkpointing = False + + if not self.activation_checkpointing: + # module is no longer parent of next modules + self.parent_list.pop() + + # set current module to previous parent module + self.name = self.parent_list[-1] + + def _fw_pre_hook(self, mod, input): + """ + This function is called before the forward pass of a module. It + collects the parameters and sharding information of a module and + stores it in a dictionary. + """ + if self.is_bw: + self.activation_checkpointing = True + else: + self.activation_checkpointing = False + + self.name = super()._get_mod_name(mod) + w_mod = weakref.ref(mod) + + # adds current sub-module to module tracker parent class + super()._get_append_fn(w_mod, self.name, False)() + + args, _ = tree_flatten(input) + tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad] + if not self.is_bw and tensors: + register_multi_grad_hook( + tensors, super()._get_pop_fn(w_mod, self.name, True) + ) + + if not self.activation_checkpointing: + # contains information about module ordering and depth in the module tree + if self.name not in self.module_helper_dict: + self.module_helper_dict[self.name] = {} + + self.module_helper_dict[self.name]["module_type"] = ( + str(type(mod)).replace("<", "").replace(">", "") + ) + self.module_helper_dict[self.name]["depth"] = len(self.parents) - 1 + + for param_name, param in mod.named_parameters(recurse=False): + if self.name not in self.module_parameters_dict: + self.module_parameters_dict[self.name] = {} + + self.module_parameters_dict[self.name][param_name] = param.data + + if isinstance(param.data, DTensor): + key_name = self.name + "." + param_name + self.sharding_dict[key_name] = param.data.placements + + if "parameters" not in self.module_helper_dict[self.name]: + self.module_helper_dict[self.name]["parameters"] = {} + + self.module_helper_dict[self.name]["parameters"][param_name] = str( + param.data.placements + ) + + # used to store module's parents to ensure correctness in backward pass/checkpointing + if self.name not in self.module_parents_dict: + self.module_parents_dict[self.name] = copy.deepcopy(self.parents) + + # used to create parent-child module associations for json dumps + parent = self.parent_list[-1] + if parent not in self.parent_dict: + self.parent_dict[parent] = [] + + self.parent_dict[parent].append(self.name) + self.parent_list.append(self.name) + + self.register_forward_hook_handles[self.name] = mod.register_forward_hook( + self._fw_set_module_hook + ) + + def _fw_post_hook(self, mod, input, output): + """ + This function is called when the forward pass of a module is called. + It updates the module tracker and removes the module from parent data + """ + + super()._fw_post_hook(mod, input, output) + + def _bw_hook(self, mod, output): + """ + This function is called when the backward pass of a module is called. It + updates the current module for backward passes + """ + self.activation_checkpointing = False + self.name = super()._get_mod_name(mod) + + def __enter__(self): + self.activation_checkpointing = False + self.module_parameters_dict.clear() + self.sharding_dict.clear() + self.parent_dict.clear() + self.parent_list = ["Global"] + self.module_helper_dict.clear() + self.module_helper_dict["Global"] = {"depth": 0} + self.module_parents_dict.clear() + self.module_parents_dict["Global"] = set() + self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook) + self._fw_post_handle = register_module_forward_hook(self._fw_post_hook) + self.register_forward_hook_handles.clear() + self._bw_handle = register_module_full_backward_pre_hook(self._bw_hook) + self.name = "Global" + + def __exit__(self, *args): + super().__exit__(*args) + self._bw_handle.remove() + + # removes all forward_hook handles added in the pre-hook + for handle in self.register_forward_hook_handles.values(): + handle.remove() + + def print_paramater_info(self): + print(self.module_parameters_dict) + + def print_sharding_info(self): + for key, value in self.sharding_dict.items(): + print(key + ": " + str(value)) + + +class CommDebugMode(TorchDispatchMode): + """ + :class:`CommDebugMode` is a context manager that counts the number of + functional collectives within its context. It does this using a + ``TorchDispatchMode``. + + .. note:: Not all collectives are supported yet. + + Example usage + + .. code-block:: python + + mod = ... + comm_mode = CommDebugMode() + with comm_mode: + mod.sum().backward() + print(comm_mode.get_comm_counts()) + """ + + def __init__(self): + self.comm_counts: dict[Any, int] = defaultdict(int) + self.comm_module_counts = {} + self.comm_module_operation_counts = {} + self.comm_registry = set() + for native_op, py_op in NATIVE_TO_PY_MAPPING.items(): + self.comm_registry.add(native_op) + self.comm_registry.add(py_op) + + self.comm_registry.add(torch.ops._dtensor.shard_dim_alltoall) + self.advanced_module_tracker = _CommModeModuleTracker() + + def generate_json_dump(self, file_name="comm_mode_log.json", noise_level=3): + """ + Creates json file used to build browser visual + 0. prints module-level collective counts + 1. prints dTensor operations not included in trivial operations + 2. prints operations not included in trivial operations + 3. prints all operations + """ + + ( + include_DTensor_ops, + include_module_data, + include_ops, + include_trivial_ops, + ) = self._set_noise_parameters(noise_level) + + # recursively builds json data + def add_json_information(json_dict, fqn): + json_dict["fqn"] = fqn + json_dict["module_type"] = "" + json_dict["parameters"] = [] + json_dict["children"] = [] + json_dict["collectives_forward"] = [] + json_dict["collectives_backward"] = [] + json_dict["operations_forward"] = [] + json_dict["operations_backward"] = [] + + # adds module layer type and parameters, and their sharding + if ( + "module_type" in self.advanced_module_tracker.module_helper_dict[fqn] + and include_module_data + ): + json_dict["module_type"] = ( + self.advanced_module_tracker.module_helper_dict[fqn]["module_type"] + ) + + if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]: + for ( + param_name, + placement, + ) in self.advanced_module_tracker.module_helper_dict[fqn][ + "parameters" + ].items(): + json_dict["parameters"].append((param_name, placement)) + + # adds module collective information + if fqn in self.comm_module_counts: + for collective, count in self.comm_module_counts[fqn][ + "forward" + ].items(): + json_dict["collectives_forward"].append((str(collective), count)) + + for collective, count in self.comm_module_counts[fqn][ + "backward" + ].items(): + json_dict["collectives_backward"].append((str(collective), count)) + + # adds module operation information + forward_operations = [] + backward_operations = [] + checkpointing_operations = [] + + # only get operations if the minimum operation noise level is set to true + if include_DTensor_ops: + if fqn in self.comm_module_operation_counts: + ( + forward_operations, + backward_operations, + checkpointing_operations, + ) = self._get_operations_list( + self.comm_module_operation_counts[fqn] + ) + + # remove all operations who don't have DTensor inputs + if not include_ops: + forward_operations = [ + op for op in forward_operations if len(op["input_sharding"]) + ] + backward_operations = [ + op for op in backward_operations if len(op["input_sharding"]) + ] + checkpointing_operations = [ + op for op in checkpointing_operations if len(op["input_sharding"]) + ] + + # remove all operations in trivial operations set + if not include_trivial_ops: + forward_operations = [ + op + for op in forward_operations + if str(op["name"]) not in trivial_ops + ] + backward_operations = [ + op + for op in backward_operations + if str(op["name"]) not in trivial_ops + ] + checkpointing_operations = [ + op + for op in checkpointing_operations + if str(op["name"]) not in trivial_ops + ] + + # converts operation information into string format for json.dumps() + forward_operations = copy.deepcopy(forward_operations) + for op in forward_operations: + op["name"] = str(op["name"]) + + for i in range(len(op["input_sharding"])): + op["input_sharding"][i] = str(op["input_sharding"][i]) + op["input_shape"][i] = str(op["input_shape"][i]) + + backward_operations = copy.deepcopy(backward_operations) + for op in backward_operations: + op["name"] = str(op["name"]) + + for i in range(len(op["input_sharding"])): + op["input_sharding"][i] = str(op["input_sharding"][i]) + op["input_shape"][i] = str(op["input_shape"][i]) + + checkpointing_operations = copy.deepcopy(checkpointing_operations) + for op in checkpointing_operations: + op["name"] = str(op["name"]) + + for i in range(len(op["input_sharding"])): + op["input_sharding"][i] = str(op["input_sharding"][i]) + op["input_shape"][i] = str(op["input_shape"][i]) + + json_dict["operations_forward"] = forward_operations + json_dict["operations_backward"] = backward_operations + json_dict["operations_checkpointing"] = checkpointing_operations + + if fqn not in self.advanced_module_tracker.parent_dict: + return json_dict + + # recursively adds module's children + for ele in self.advanced_module_tracker.parent_dict[fqn]: + json_dict["children"].append(add_json_information({}, ele)) + + return json_dict + + json_dict: dict[str, Any] = {} + add_json_information(json_dict, "Global") + + # converts dictonary into json file + with open(file_name, "w") as json_file: + json.dump(json_dict, json_file, indent=4) + + def generate_comm_debug_tracing_table(self, noise_level=3): + """ + Generates detailed table displaying operations and collective tracing information + on a module level. Amount of information is dependent on noise_level + + 0. prints module-level collective counts + 1. prints dTensor operations not included in trivial operations, module information + 2. prints operations not included in trivial operations + 3. prints all operations + """ + + ( + include_DTensor_ops, + include_module_data, + include_ops, + include_trivial_ops, + ) = self._set_noise_parameters(noise_level) + + table = "" + for fqn in self.advanced_module_tracker.module_helper_dict: + # setting up indentations for table formatting + indent = " " * ( + 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + ) + table += f"{indent}{fqn}\n" + + if include_module_data: + if ( + "module_type" + in self.advanced_module_tracker.module_helper_dict[fqn] + ): + module_type = self.advanced_module_tracker.module_helper_dict[fqn][ + "module_type" + ] + table += f"{indent}*module type: {module_type}\n" + + if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]: + table += f"{indent}*Parameter List\n" + for ( + param_name, + placement, + ) in self.advanced_module_tracker.module_helper_dict[fqn][ + "parameters" + ].items(): + table += f"{indent} *{param_name}: {placement}\n" + + indent += " " + collective_indent = " " * ( + 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 2 + ) + operation_indent = " " * ( + 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 3 + ) + + # separate the module's collective and operations by forward and backward + forward_collectives = {} + backward_collectives = {} + if fqn in self.comm_module_counts: + forward_collectives = self.comm_module_counts[fqn]["forward"] + backward_collectives = self.comm_module_counts[fqn]["backward"] + + forward_operations = [] + backward_operations = [] + checkpointing_operations = [] + + if include_DTensor_ops: + if fqn in self.comm_module_operation_counts: + ( + forward_operations, + backward_operations, + checkpointing_operations, + ) = self._get_operations_list( + self.comm_module_operation_counts[fqn] + ) + + def add_tracing_information(table, collectives_dict, operation_list): + """ + adds tracing information for module's forward or backward + """ + for collective, count in collectives_dict.items(): + table += ( + f"\033[1;33m{collective_indent}*{collective}: {count}\033[0m\n" + ) + + def add_operations( + table, operation, collective_indent, operation_indent + ): + """ + adds operation information to the table + """ + table += f"\033[1;33m{collective_indent}**{operation_name}\033[0m\n" + + if len(operation["input_shape"]): + operation_shape = operation["input_shape"] + operation_sharding = operation["input_sharding"] + operation_device_mesh = operation["device_mesh"] + + table += f"\033[1;31m{operation_indent}shape: {operation_shape}\033[0m\n" + table += f"\033[1;31m{operation_indent}sharding: {operation_sharding}\033[0m\n" + table += f"\033[1;31m{operation_indent}device mesh: {operation_device_mesh}\033[0m\n" + + return table + + for operation in operation_list: + operation_name = str(operation["name"]) + + # include all operations + if include_trivial_ops: + table = add_operations( + table, operation, collective_indent, operation_indent + ) + + # include all operations not in trivial operations + elif include_ops and operation_name not in trivial_ops: + table = add_operations( + table, operation, collective_indent, operation_indent + ) + + # only include dTensor operations not in trivial set + elif ( + include_DTensor_ops + and (operation_name not in trivial_ops) + and len(operation["input_shape"]) + ): + table = add_operations( + table, operation, collective_indent, operation_indent + ) + + return table + + if len(forward_collectives) or len(forward_operations): + table += f"{indent}FORWARD PASS\n" + table = add_tracing_information( + table, forward_collectives, forward_operations + ) + + if len(backward_collectives) or len(backward_operations): + table += f"{indent}BACKWARD PASS\n" + table = add_tracing_information( + table, backward_collectives, backward_operations + ) + + if len(checkpointing_operations): + table += f"{indent}ACTIVATION CHECKPOINTING\n" + table = add_tracing_information(table, {}, checkpointing_operations) + + return table + + def _get_operations_list(self, module_operation_counts): + forward_operations = [ + op for op in module_operation_counts["operations_list"] if not op["is_bw"] + ] + backward_operations = [ + op + for op in module_operation_counts["operations_list"] + if op["is_bw"] and not op["is_activation_checkpointing"] + ] + checkpointing_operations = [ + op + for op in module_operation_counts["operations_list"] + if op["is_activation_checkpointing"] + ] + + return forward_operations, backward_operations, checkpointing_operations + + def get_total_counts(self) -> int: + return sum(self.comm_counts.values()) + + def get_comm_counts(self) -> dict[Any, int]: + """Returns the communication counts as a dictionary. + + Returns: + Dict[Any, int]: The communication counts as a dictionary. + """ + return self.comm_counts + + def get_parameter_info(self) -> dict[str, dict[str, Any]]: + return self.advanced_module_tracker.module_parameters_dict + + def get_sharding_info(self) -> dict[str, dict[str, Any]]: + return self.advanced_module_tracker.sharding_dict + + def __enter__(self): + self.comm_counts.clear() + self.comm_module_counts.clear() + self.comm_module_counts["Global"] = {} + self.comm_module_counts["Global"]["forward"] = defaultdict(int) + self.comm_module_counts["Global"]["backward"] = defaultdict(int) + + self.comm_module_operation_counts.clear() + + super().__enter__() + self.advanced_module_tracker.__enter__() + return self + + def __exit__(self, *args): + self.advanced_module_tracker.__exit__() + super().__exit__(*args) + + def log_comm_debug_tracing_table_to_file( + self, file_name="comm_mode_log.txt", noise_level=3 + ): + """ + Alternative to console CommDebugMode output, writes to file specified by the user + """ + ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") + table = ansi_escape.sub("", self.generate_comm_debug_tracing_table(noise_level)) + + with open(file_name, "w") as log_file: + log_file.write(table) + + def _set_noise_parameters(self, noise_level): + """ + sets variables controlling what information displays based on noise level + """ + include_DTensor_ops = False + include_module_data = False + include_ops = False + include_trivial_ops = False + + if noise_level > 0: + include_DTensor_ops = True + include_module_data = True + + if noise_level > 1: + include_ops = True + + if noise_level > 2: + include_trivial_ops = True + + return ( + include_DTensor_ops, + include_module_data, + include_ops, + include_trivial_ops, + ) + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + # When running this mode with DTensor, ordinarily all modes will + # run **before** subclasses get a chance to run. + # Returning NotImplemented here gives us a chance to let DTensor + # run and desugar into comms ops, before CommDebugMode sees them. + + # sets up operation-level collective count + if self.advanced_module_tracker.name not in self.comm_module_operation_counts: + # dictionary should hold module input and output shape, operations list and collective counter + self.comm_module_operation_counts[self.advanced_module_tracker.name] = { + "operations_list": [] + } + operation_dict = {} + operation_dict["name"] = func + + operation_dict["input_shape"] = [] + operation_dict["input_sharding"] = [] + operation_dict["device_mesh"] = "" + + # tracks if the operation is part of the backward pass + operation_dict["is_bw"] = self.advanced_module_tracker.is_bw + + # tracks if the operation is part of activation checkpointing + operation_dict["is_activation_checkpointing"] = ( + self.advanced_module_tracker.activation_checkpointing + ) + + if any(t == DTensor for t in types): + for ele in args: + if isinstance(ele, DTensor): + # saves shapes and placements of all DTensor args + operation_dict["input_shape"].append(ele.shape) + operation_dict["input_sharding"].append(ele.placements) + operation_dict["device_mesh"] = str(ele.device_mesh) + + self.comm_module_operation_counts[self.advanced_module_tracker.name][ + "operations_list" + ].append(operation_dict) + + return NotImplemented + + kwargs = kwargs if kwargs else {} + out = func(*args, **kwargs) + func_packet = func._overloadpacket + + # We have many tests that use CommDebugMode to verify the occurrence of + # collectives. These tests do so by querying comm_counts with legacy + # funcol ops as key. For the purpose of native funcol migration, we + # need these tests to work for both legacy and native funcol. To avoid + # the need to modify all tests to accommodate the two implementations, + # we make CommDebugMode translate native funcol ops into legacy funcol + # ops until the migration finishes. + + if func_packet in self.comm_registry or func_packet in c10d_collective_ops: + if func_packet in NATIVE_TO_PY_MAPPING: + func_packet = NATIVE_TO_PY_MAPPING[func_packet] + self.comm_counts[func_packet] += 1 + + key = "forward" + if self.advanced_module_tracker.is_bw: + key = "backward" + + # adds collective count to current module + if self.advanced_module_tracker.name not in self.comm_module_counts: + self.comm_module_counts[self.advanced_module_tracker.name] = {} + self.comm_module_counts[self.advanced_module_tracker.name][ + "forward" + ] = defaultdict(int) + self.comm_module_counts[self.advanced_module_tracker.name][ + "backward" + ] = defaultdict(int) + self.comm_module_counts[self.advanced_module_tracker.name][key][ + func_packet + ] += 1 + + # adds collective count to parent modules + for par in self.advanced_module_tracker.module_parents_dict[ + self.advanced_module_tracker.name + ]: + # makes sure we aren't double counting when current sub-module hasn't been removed from parents + if par != self.advanced_module_tracker.name: + if par not in self.comm_module_counts: + self.comm_module_counts[par] = {} + self.comm_module_counts[par]["forward"] = defaultdict(int) + self.comm_module_counts[par]["backward"] = defaultdict(int) + self.comm_module_counts[par][key][func_packet] += 1 + + # if tensor op uses fake tensors, return + if detect_fake_mode(args): + return out + + # add tensor operation to module operation list + self.comm_module_operation_counts[self.advanced_module_tracker.name][ + "operations_list" + ].append(operation_dict) + + return out diff --git a/shared/package-files/3c/3c3b65b3e7e9d0d5f2054f206192596aa1beee570fcc0e430855eb0559f4053f/test_scalar_methods.cpython-311.pyc b/shared/package-files/3c/3c3b65b3e7e9d0d5f2054f206192596aa1beee570fcc0e430855eb0559f4053f/test_scalar_methods.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80b70501bff478da81939f1d10ec5015abf4f0df Binary files /dev/null and b/shared/package-files/3c/3c3b65b3e7e9d0d5f2054f206192596aa1beee570fcc0e430855eb0559f4053f/test_scalar_methods.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c3d56684106f7dcf3568870541aeb7ba31c150d40953c689bcd074e91b092b2/TypeInfo.h b/shared/package-files/3c/3c3d56684106f7dcf3568870541aeb7ba31c150d40953c689bcd074e91b092b2/TypeInfo.h new file mode 100644 index 0000000000000000000000000000000000000000..9eb03a49093fb4f7efecc73a32b2ef40f126718f --- /dev/null +++ b/shared/package-files/3c/3c3d56684106f7dcf3568870541aeb7ba31c150d40953c689bcd074e91b092b2/TypeInfo.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include + +struct THPDTypeInfo { + PyObject_HEAD + at::ScalarType type; +}; + +struct THPFInfo : THPDTypeInfo {}; + +struct THPIInfo : THPDTypeInfo {}; + +TORCH_PYTHON_API extern PyTypeObject THPFInfoType; +TORCH_PYTHON_API extern PyTypeObject THPIInfoType; + +inline bool THPFInfo_Check(PyObject* obj) { + return Py_TYPE(obj) == &THPFInfoType; +} + +inline bool THPIInfo_Check(PyObject* obj) { + return Py_TYPE(obj) == &THPIInfoType; +} + +void THPDTypeInfo_init(PyObject* module); diff --git a/shared/package-files/3c/3c3fa5dbf34c8ce63e0af36adb7177cd8fc352412915e082c1b285eaddfb1923/libmpf.cpython-311.pyc b/shared/package-files/3c/3c3fa5dbf34c8ce63e0af36adb7177cd8fc352412915e082c1b285eaddfb1923/libmpf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e40e02582b5942983812426857c05ef228919651 Binary files /dev/null and b/shared/package-files/3c/3c3fa5dbf34c8ce63e0af36adb7177cd8fc352412915e082c1b285eaddfb1923/libmpf.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c42302dfb5ebd2d95607693cf364c48e2cfcbb41204fb163de763c75951e82b/edmondskarp.py b/shared/package-files/3c/3c42302dfb5ebd2d95607693cf364c48e2cfcbb41204fb163de763c75951e82b/edmondskarp.py new file mode 100644 index 0000000000000000000000000000000000000000..50063268355ccc2e2ecbdf7f1a6704e7404475ec --- /dev/null +++ b/shared/package-files/3c/3c42302dfb5ebd2d95607693cf364c48e2cfcbb41204fb163de763c75951e82b/edmondskarp.py @@ -0,0 +1,241 @@ +""" +Edmonds-Karp algorithm for maximum flow problems. +""" + +import networkx as nx +from networkx.algorithms.flow.utils import build_residual_network + +__all__ = ["edmonds_karp"] + + +def edmonds_karp_core(R, s, t, cutoff): + """Implementation of the Edmonds-Karp algorithm.""" + R_nodes = R.nodes + R_pred = R.pred + R_succ = R.succ + + inf = R.graph["inf"] + + def augment(path): + """Augment flow along a path from s to t.""" + # Determine the path residual capacity. + flow = inf + it = iter(path) + u = next(it) + for v in it: + attr = R_succ[u][v] + flow = min(flow, attr["capacity"] - attr["flow"]) + u = v + if flow * 2 > inf: + raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.") + # Augment flow along the path. + it = iter(path) + u = next(it) + for v in it: + R_succ[u][v]["flow"] += flow + R_succ[v][u]["flow"] -= flow + u = v + return flow + + def bidirectional_bfs(): + """Bidirectional breadth-first search for an augmenting path.""" + pred = {s: None} + q_s = [s] + succ = {t: None} + q_t = [t] + while True: + q = [] + if len(q_s) <= len(q_t): + for u in q_s: + for v, attr in R_succ[u].items(): + if v not in pred and attr["flow"] < attr["capacity"]: + pred[v] = u + if v in succ: + return v, pred, succ + q.append(v) + if not q: + return None, None, None + q_s = q + else: + for u in q_t: + for v, attr in R_pred[u].items(): + if v not in succ and attr["flow"] < attr["capacity"]: + succ[v] = u + if v in pred: + return v, pred, succ + q.append(v) + if not q: + return None, None, None + q_t = q + + # Look for shortest augmenting paths using breadth-first search. + flow_value = 0 + while flow_value < cutoff: + v, pred, succ = bidirectional_bfs() + if pred is None: + break + path = [v] + # Trace a path from s to v. + u = v + while u != s: + u = pred[u] + path.append(u) + path.reverse() + # Trace a path from v to t. + u = v + while u != t: + u = succ[u] + path.append(u) + flow_value += augment(path) + + return flow_value + + +def edmonds_karp_impl(G, s, t, capacity, residual, cutoff): + """Implementation of the Edmonds-Karp algorithm.""" + if s not in G: + raise nx.NetworkXError(f"node {str(s)} not in graph") + if t not in G: + raise nx.NetworkXError(f"node {str(t)} not in graph") + if s == t: + raise nx.NetworkXError("source and sink are the same node") + + if residual is None: + R = build_residual_network(G, capacity) + else: + R = residual + + # Initialize/reset the residual network. + for u in R: + for e in R[u].values(): + e["flow"] = 0 + + if cutoff is None: + cutoff = float("inf") + R.graph["flow_value"] = edmonds_karp_core(R, s, t, cutoff) + + return R + + +@nx._dispatchable(edge_attrs={"capacity": float("inf")}, returns_graph=True) +def edmonds_karp( + G, s, t, capacity="capacity", residual=None, value_only=False, cutoff=None +): + """Find a maximum single-commodity flow using the Edmonds-Karp algorithm. + + This function returns the residual network resulting after computing + the maximum flow. See below for details about the conventions + NetworkX uses for defining residual networks. + + This algorithm has a running time of $O(n m^2)$ for $n$ nodes and $m$ + edges. + + + Parameters + ---------- + G : NetworkX graph + Edges of the graph are expected to have an attribute called + 'capacity'. If this attribute is not present, the edge is + considered to have infinite capacity. + + s : node + Source node for the flow. + + t : node + Sink node for the flow. + + capacity : string + Edges of the graph G are expected to have an attribute capacity + that indicates how much flow the edge can support. If this + attribute is not present, the edge is considered to have + infinite capacity. Default value: 'capacity'. + + residual : NetworkX graph + Residual network on which the algorithm is to be executed. If None, a + new residual network is created. Default value: None. + + value_only : bool + If True compute only the value of the maximum flow. This parameter + will be ignored by this algorithm because it is not applicable. + + cutoff : integer, float + If specified, the algorithm will terminate when the flow value reaches + or exceeds the cutoff. In this case, it may be unable to immediately + determine a minimum cut. Default value: None. + + Returns + ------- + R : NetworkX DiGraph + Residual network after computing the maximum flow. + + Raises + ------ + NetworkXError + The algorithm does not support MultiGraph and MultiDiGraph. If + the input graph is an instance of one of these two classes, a + NetworkXError is raised. + + NetworkXUnbounded + If the graph has a path of infinite capacity, the value of a + feasible flow on the graph is unbounded above and the function + raises a NetworkXUnbounded. + + See also + -------- + :meth:`maximum_flow` + :meth:`minimum_cut` + :meth:`preflow_push` + :meth:`shortest_augmenting_path` + + Notes + ----- + The residual network :samp:`R` from an input graph :samp:`G` has the + same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair + of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a + self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists + in :samp:`G`. + + For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']` + is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists + in :samp:`G` or zero otherwise. If the capacity is infinite, + :samp:`R[u][v]['capacity']` will have a high arbitrary finite value + that does not affect the solution of the problem. This value is stored in + :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`, + :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and + satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`. + + The flow value, defined as the total flow into :samp:`t`, the sink, is + stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not + specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such + that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum + :samp:`s`-:samp:`t` cut. + + Examples + -------- + >>> from networkx.algorithms.flow import edmonds_karp + + The functions that implement flow algorithms and output a residual + network, such as this one, are not imported to the base NetworkX + namespace, so you have to explicitly import them from the flow package. + + >>> G = nx.DiGraph() + >>> G.add_edge("x", "a", capacity=3.0) + >>> G.add_edge("x", "b", capacity=1.0) + >>> G.add_edge("a", "c", capacity=3.0) + >>> G.add_edge("b", "c", capacity=5.0) + >>> G.add_edge("b", "d", capacity=4.0) + >>> G.add_edge("d", "e", capacity=2.0) + >>> G.add_edge("c", "y", capacity=2.0) + >>> G.add_edge("e", "y", capacity=3.0) + >>> R = edmonds_karp(G, "x", "y") + >>> flow_value = nx.maximum_flow_value(G, "x", "y") + >>> flow_value + 3.0 + >>> flow_value == R.graph["flow_value"] + True + + """ + R = edmonds_karp_impl(G, s, t, capacity, residual, cutoff) + R.graph["algorithm"] = "edmonds_karp" + nx._clear_cache(R) + return R diff --git a/shared/package-files/3c/3c456f154ac47fe2304f07e74d8b4014b3cb3e38ea0359e69b7f6701282c3352/dpll2.py b/shared/package-files/3c/3c456f154ac47fe2304f07e74d8b4014b3cb3e38ea0359e69b7f6701282c3352/dpll2.py new file mode 100644 index 0000000000000000000000000000000000000000..4f18c81189d6be565dc9b7caa3f0bf48e978bb56 --- /dev/null +++ b/shared/package-files/3c/3c456f154ac47fe2304f07e74d8b4014b3cb3e38ea0359e69b7f6701282c3352/dpll2.py @@ -0,0 +1,688 @@ +"""Implementation of DPLL algorithm + +Features: + - Clause learning + - Watch literal scheme + - VSIDS heuristic + +References: + - https://en.wikipedia.org/wiki/DPLL_algorithm +""" + +from collections import defaultdict +from heapq import heappush, heappop + +from sympy.core.sorting import ordered +from sympy.assumptions.cnf import EncodedCNF + +from sympy.logic.algorithms.lra_theory import LRASolver + + +def dpll_satisfiable(expr, all_models=False, use_lra_theory=False): + """ + Check satisfiability of a propositional sentence. + It returns a model rather than True when it succeeds. + Returns a generator of all models if all_models is True. + + Examples + ======== + + >>> from sympy.abc import A, B + >>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable + >>> dpll_satisfiable(A & ~B) + {A: True, B: False} + >>> dpll_satisfiable(A & ~A) + False + + """ + if not isinstance(expr, EncodedCNF): + exprs = EncodedCNF() + exprs.add_prop(expr) + expr = exprs + + # Return UNSAT when False (encoded as 0) is present in the CNF + if {0} in expr.data: + if all_models: + return (f for f in [False]) + return False + + if use_lra_theory: + lra, immediate_conflicts = LRASolver.from_encoded_cnf(expr) + else: + lra = None + immediate_conflicts = [] + solver = SATSolver(expr.data + immediate_conflicts, expr.variables, set(), expr.symbols, lra_theory=lra) + models = solver._find_model() + + if all_models: + return _all_models(models) + + try: + return next(models) + except StopIteration: + return False + + # Uncomment to confirm the solution is valid (hitting set for the clauses) + #else: + #for cls in clauses_int_repr: + #assert solver.var_settings.intersection(cls) + + +def _all_models(models): + satisfiable = False + try: + while True: + yield next(models) + satisfiable = True + except StopIteration: + if not satisfiable: + yield False + + +class SATSolver: + """ + Class for representing a SAT solver capable of + finding a model to a boolean theory in conjunctive + normal form. + """ + + def __init__(self, clauses, variables, var_settings, symbols=None, + heuristic='vsids', clause_learning='none', INTERVAL=500, + lra_theory = None): + + self.var_settings = var_settings + self.heuristic = heuristic + self.is_unsatisfied = False + self._unit_prop_queue = [] + self.update_functions = [] + self.INTERVAL = INTERVAL + + if symbols is None: + self.symbols = list(ordered(variables)) + else: + self.symbols = symbols + + self._initialize_variables(variables) + self._initialize_clauses(clauses) + + if 'vsids' == heuristic: + self._vsids_init() + self.heur_calculate = self._vsids_calculate + self.heur_lit_assigned = self._vsids_lit_assigned + self.heur_lit_unset = self._vsids_lit_unset + self.heur_clause_added = self._vsids_clause_added + + # Note: Uncomment this if/when clause learning is enabled + #self.update_functions.append(self._vsids_decay) + + else: + raise NotImplementedError + + if 'simple' == clause_learning: + self.add_learned_clause = self._simple_add_learned_clause + self.compute_conflict = self._simple_compute_conflict + self.update_functions.append(self._simple_clean_clauses) + elif 'none' == clause_learning: + self.add_learned_clause = lambda x: None + self.compute_conflict = lambda: None + else: + raise NotImplementedError + + # Create the base level + self.levels = [Level(0)] + self._current_level.varsettings = var_settings + + # Keep stats + self.num_decisions = 0 + self.num_learned_clauses = 0 + self.original_num_clauses = len(self.clauses) + + self.lra = lra_theory + + def _initialize_variables(self, variables): + """Set up the variable data structures needed.""" + self.sentinels = defaultdict(set) + self.occurrence_count = defaultdict(int) + self.variable_set = [False] * (len(variables) + 1) + + def _initialize_clauses(self, clauses): + """Set up the clause data structures needed. + + For each clause, the following changes are made: + - Unit clauses are queued for propagation right away. + - Non-unit clauses have their first and last literals set as sentinels. + - The number of clauses a literal appears in is computed. + """ + self.clauses = [list(clause) for clause in clauses] + + for i, clause in enumerate(self.clauses): + + # Handle the unit clauses + if 1 == len(clause): + self._unit_prop_queue.append(clause[0]) + continue + + self.sentinels[clause[0]].add(i) + self.sentinels[clause[-1]].add(i) + + for lit in clause: + self.occurrence_count[lit] += 1 + + def _find_model(self): + """ + Main DPLL loop. Returns a generator of models. + + Variables are chosen successively, and assigned to be either + True or False. If a solution is not found with this setting, + the opposite is chosen and the search continues. The solver + halts when every variable has a setting. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> list(l._find_model()) + [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}] + + >>> from sympy.abc import A, B, C + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set(), [A, B, C]) + >>> list(l._find_model()) + [{A: True, B: False, C: False}, {A: True, B: True, C: True}] + + """ + + # We use this variable to keep track of if we should flip a + # variable setting in successive rounds + flip_var = False + + # Check if unit prop says the theory is unsat right off the bat + self._simplify() + if self.is_unsatisfied: + return + + # While the theory still has clauses remaining + while True: + # Perform cleanup / fixup at regular intervals + if self.num_decisions % self.INTERVAL == 0: + for func in self.update_functions: + func() + + if flip_var: + # We have just backtracked and we are trying to opposite literal + flip_var = False + lit = self._current_level.decision + + else: + # Pick a literal to set + lit = self.heur_calculate() + self.num_decisions += 1 + + # Stopping condition for a satisfying theory + if 0 == lit: + + # check if assignment satisfies lra theory + if self.lra: + for enc_var in self.var_settings: + res = self.lra.assert_lit(enc_var) + if res is not None: + break + res = self.lra.check() + self.lra.reset_bounds() + else: + res = None + if res is None or res[0]: + yield {self.symbols[abs(lit) - 1]: + lit > 0 for lit in self.var_settings} + else: + self._simple_add_learned_clause(res[1]) + + # backtrack until we unassign one of the literals causing the conflict + while not any(-lit in res[1] for lit in self._current_level.var_settings): + self._undo() + + while self._current_level.flipped: + self._undo() + if len(self.levels) == 1: + return + flip_lit = -self._current_level.decision + self._undo() + self.levels.append(Level(flip_lit, flipped=True)) + flip_var = True + continue + + # Start the new decision level + self.levels.append(Level(lit)) + + # Assign the literal, updating the clauses it satisfies + self._assign_literal(lit) + + # _simplify the theory + self._simplify() + + # Check if we've made the theory unsat + if self.is_unsatisfied: + + self.is_unsatisfied = False + + # We unroll all of the decisions until we can flip a literal + while self._current_level.flipped: + self._undo() + + # If we've unrolled all the way, the theory is unsat + if 1 == len(self.levels): + return + + # Detect and add a learned clause + self.add_learned_clause(self.compute_conflict()) + + # Try the opposite setting of the most recent decision + flip_lit = -self._current_level.decision + self._undo() + self.levels.append(Level(flip_lit, flipped=True)) + flip_var = True + + ######################## + # Helper Methods # + ######################## + @property + def _current_level(self): + """The current decision level data structure + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{1}, {2}], {1, 2}, set()) + >>> next(l._find_model()) + {1: True, 2: True} + >>> l._current_level.decision + 0 + >>> l._current_level.flipped + False + >>> l._current_level.var_settings + {1, 2} + + """ + return self.levels[-1] + + def _clause_sat(self, cls): + """Check if a clause is satisfied by the current variable setting. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{1}, {-1}], {1}, set()) + >>> try: + ... next(l._find_model()) + ... except StopIteration: + ... pass + >>> l._clause_sat(0) + False + >>> l._clause_sat(1) + True + + """ + for lit in self.clauses[cls]: + if lit in self.var_settings: + return True + return False + + def _is_sentinel(self, lit, cls): + """Check if a literal is a sentinel of a given clause. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> next(l._find_model()) + {1: True, 2: False, 3: False} + >>> l._is_sentinel(2, 3) + True + >>> l._is_sentinel(-3, 1) + False + + """ + return cls in self.sentinels[lit] + + def _assign_literal(self, lit): + """Make a literal assignment. + + The literal assignment must be recorded as part of the current + decision level. Additionally, if the literal is marked as a + sentinel of any clause, then a new sentinel must be chosen. If + this is not possible, then unit propagation is triggered and + another literal is added to the queue to be set in the future. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> next(l._find_model()) + {1: True, 2: False, 3: False} + >>> l.var_settings + {-3, -2, 1} + + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> l._assign_literal(-1) + >>> try: + ... next(l._find_model()) + ... except StopIteration: + ... pass + >>> l.var_settings + {-1} + + """ + self.var_settings.add(lit) + self._current_level.var_settings.add(lit) + self.variable_set[abs(lit)] = True + self.heur_lit_assigned(lit) + + sentinel_list = list(self.sentinels[-lit]) + + for cls in sentinel_list: + if not self._clause_sat(cls): + other_sentinel = None + for newlit in self.clauses[cls]: + if newlit != -lit: + if self._is_sentinel(newlit, cls): + other_sentinel = newlit + elif not self.variable_set[abs(newlit)]: + self.sentinels[-lit].remove(cls) + self.sentinels[newlit].add(cls) + other_sentinel = None + break + + # Check if no sentinel update exists + if other_sentinel: + self._unit_prop_queue.append(other_sentinel) + + def _undo(self): + """ + _undo the changes of the most recent decision level. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> next(l._find_model()) + {1: True, 2: False, 3: False} + >>> level = l._current_level + >>> level.decision, level.var_settings, level.flipped + (-3, {-3, -2}, False) + >>> l._undo() + >>> level = l._current_level + >>> level.decision, level.var_settings, level.flipped + (0, {1}, False) + + """ + # Undo the variable settings + for lit in self._current_level.var_settings: + self.var_settings.remove(lit) + self.heur_lit_unset(lit) + self.variable_set[abs(lit)] = False + + # Pop the level off the stack + self.levels.pop() + + ######################### + # Propagation # + ######################### + """ + Propagation methods should attempt to soundly simplify the boolean + theory, and return True if any simplification occurred and False + otherwise. + """ + def _simplify(self): + """Iterate over the various forms of propagation to simplify the theory. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> l.variable_set + [False, False, False, False] + >>> l.sentinels + {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}} + + >>> l._simplify() + + >>> l.variable_set + [False, True, False, False] + >>> l.sentinels + {-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3}, + ...3: {2, 4}} + + """ + changed = True + while changed: + changed = False + changed |= self._unit_prop() + changed |= self._pure_literal() + + def _unit_prop(self): + """Perform unit propagation on the current theory.""" + result = len(self._unit_prop_queue) > 0 + while self._unit_prop_queue: + next_lit = self._unit_prop_queue.pop() + if -next_lit in self.var_settings: + self.is_unsatisfied = True + self._unit_prop_queue = [] + return False + else: + self._assign_literal(next_lit) + + return result + + def _pure_literal(self): + """Look for pure literals and assign them when found.""" + return False + + ######################### + # Heuristics # + ######################### + def _vsids_init(self): + """Initialize the data structures needed for the VSIDS heuristic.""" + self.lit_heap = [] + self.lit_scores = {} + + for var in range(1, len(self.variable_set)): + self.lit_scores[var] = float(-self.occurrence_count[var]) + self.lit_scores[-var] = float(-self.occurrence_count[-var]) + heappush(self.lit_heap, (self.lit_scores[var], var)) + heappush(self.lit_heap, (self.lit_scores[-var], -var)) + + def _vsids_decay(self): + """Decay the VSIDS scores for every literal. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + + >>> l.lit_scores + {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0} + + >>> l._vsids_decay() + + >>> l.lit_scores + {-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0} + + """ + # We divide every literal score by 2 for a decay factor + # Note: This doesn't change the heap property + for lit in self.lit_scores.keys(): + self.lit_scores[lit] /= 2.0 + + def _vsids_calculate(self): + """ + VSIDS Heuristic Calculation + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + + >>> l.lit_heap + [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)] + + >>> l._vsids_calculate() + -3 + + >>> l.lit_heap + [(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)] + + """ + if len(self.lit_heap) == 0: + return 0 + + # Clean out the front of the heap as long the variables are set + while self.variable_set[abs(self.lit_heap[0][1])]: + heappop(self.lit_heap) + if len(self.lit_heap) == 0: + return 0 + + return heappop(self.lit_heap)[1] + + def _vsids_lit_assigned(self, lit): + """Handle the assignment of a literal for the VSIDS heuristic.""" + pass + + def _vsids_lit_unset(self, lit): + """Handle the unsetting of a literal for the VSIDS heuristic. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> l.lit_heap + [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)] + + >>> l._vsids_lit_unset(2) + + >>> l.lit_heap + [(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1), + ...(-2.0, 2), (0.0, 1)] + + """ + var = abs(lit) + heappush(self.lit_heap, (self.lit_scores[var], var)) + heappush(self.lit_heap, (self.lit_scores[-var], -var)) + + def _vsids_clause_added(self, cls): + """Handle the addition of a new clause for the VSIDS heuristic. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + + >>> l.num_learned_clauses + 0 + >>> l.lit_scores + {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0} + + >>> l._vsids_clause_added({2, -3}) + + >>> l.num_learned_clauses + 1 + >>> l.lit_scores + {-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0} + + """ + self.num_learned_clauses += 1 + for lit in cls: + self.lit_scores[lit] += 1 + + ######################## + # Clause Learning # + ######################## + def _simple_add_learned_clause(self, cls): + """Add a new clause to the theory. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + + >>> l.num_learned_clauses + 0 + >>> l.clauses + [[2, -3], [1], [3, -3], [2, -2], [3, -2]] + >>> l.sentinels + {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}} + + >>> l._simple_add_learned_clause([3]) + + >>> l.clauses + [[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]] + >>> l.sentinels + {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}} + + """ + cls_num = len(self.clauses) + self.clauses.append(cls) + + for lit in cls: + self.occurrence_count[lit] += 1 + + self.sentinels[cls[0]].add(cls_num) + self.sentinels[cls[-1]].add(cls_num) + + self.heur_clause_added(cls) + + def _simple_compute_conflict(self): + """ Build a clause representing the fact that at least one decision made + so far is wrong. + + Examples + ======== + + >>> from sympy.logic.algorithms.dpll2 import SATSolver + >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, + ... {3, -2}], {1, 2, 3}, set()) + >>> next(l._find_model()) + {1: True, 2: False, 3: False} + >>> l._simple_compute_conflict() + [3] + + """ + return [-(level.decision) for level in self.levels[1:]] + + def _simple_clean_clauses(self): + """Clean up learned clauses.""" + pass + + +class Level: + """ + Represents a single level in the DPLL algorithm, and contains + enough information for a sound backtracking procedure. + """ + + def __init__(self, decision, flipped=False): + self.decision = decision + self.var_settings = set() + self.flipped = flipped diff --git a/shared/package-files/3c/3c483e2e44a2c288f8492f64aa495226f20aa925c65c1a025251e98c06305db5/conv_transpose2d_compositeimplicitautograd_dispatch.h b/shared/package-files/3c/3c483e2e44a2c288f8492f64aa495226f20aa925c65c1a025251e98c06305db5/conv_transpose2d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c1104bcb83ab1aa0fd4409cbc17d3e2a479e8ab7 --- /dev/null +++ b/shared/package-files/3c/3c483e2e44a2c288f8492f64aa495226f20aa925c65c1a025251e98c06305db5/conv_transpose2d_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor conv_transpose2d(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1); +TORCH_API at::Tensor conv_transpose2d_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/3c/3c4c38ffdf24f3caee3a94073bd903ae5e64060e99c8c600612bb778f7ef8824/test_summarization.cpython-311.pyc b/shared/package-files/3c/3c4c38ffdf24f3caee3a94073bd903ae5e64060e99c8c600612bb778f7ef8824/test_summarization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d48a460cabbf2af38519966774be1af9a4eb065 Binary files /dev/null and b/shared/package-files/3c/3c4c38ffdf24f3caee3a94073bd903ae5e64060e99c8c600612bb778f7ef8824/test_summarization.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c50fe38e2db01f8fbf83026b068622175c36554bd574800a2f4ec49e4962efa/_equalize.cpython-311.pyc b/shared/package-files/3c/3c50fe38e2db01f8fbf83026b068622175c36554bd574800a2f4ec49e4962efa/_equalize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbd1928fef392f6b6d6aa5a883fabb8c464fc91b Binary files /dev/null and b/shared/package-files/3c/3c50fe38e2db01f8fbf83026b068622175c36554bd574800a2f4ec49e4962efa/_equalize.cpython-311.pyc differ diff --git a/shared/package-files/3c/3c525a6190f1060cb191f6211f7490c38a9f13d202096ad39a2b6fab5e32ddbb/version.py b/shared/package-files/3c/3c525a6190f1060cb191f6211f7490c38a9f13d202096ad39a2b6fab5e32ddbb/version.py new file mode 100644 index 0000000000000000000000000000000000000000..cda8e99935c8d92010b84437ae83d75031245d61 --- /dev/null +++ b/shared/package-files/3c/3c525a6190f1060cb191f6211f7490c38a9f13d202096ad39a2b6fab5e32ddbb/version.py @@ -0,0 +1,561 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +import itertools +import re +from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: Tuple[int, ...] + dev: Optional[Tuple[str, int]] + pre: Optional[Tuple[str, int]] + post: Optional[Tuple[str, int]] + local: Optional[LocalType] + + +def parse(version: str) -> "Version": + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: Tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +_VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be rounded-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> Optional[int]:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1.2.3+abc.dev1").public
+        '1.2.3'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3+abc.dev1").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
+) -> Optional[Tuple[str, int]]:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[LocalType],
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/shared/package-files/3c/3c52773d935791d8a758f02307a2ee28e1f8bdddae3ca30ed86f17de24afbebf/halide_helpers.py b/shared/package-files/3c/3c52773d935791d8a758f02307a2ee28e1f8bdddae3ca30ed86f17de24afbebf/halide_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4bf70fe9d8db1cb66379df11e025ad84cc0069b
--- /dev/null
+++ b/shared/package-files/3c/3c52773d935791d8a758f02307a2ee28e1f8bdddae3ca30ed86f17de24afbebf/halide_helpers.py
@@ -0,0 +1,118 @@
+# mypy: allow-untyped-defs
+try:
+    import halide as hl  # type: ignore[import-untyped, import-not-found]
+except ImportError:
+    hl = None
+
+PHILOX_N_ROUNDS_DEFAULT = 10  # Default number of rounds for philox
+
+if hl is not None:
+    PHILOX_KEY_A_U32 = hl.u32(0x9E3779B9)
+    PHILOX_KEY_B_U32 = hl.u32(0xBB67AE85)
+    PHILOX_ROUND_A_U32 = hl.u32(0xD2511F53)
+    PHILOX_ROUND_B_U32 = hl.u32(0xCD9E8D57)
+else:
+    PHILOX_KEY_A_U32 = None
+    PHILOX_KEY_B_U32 = None
+    PHILOX_ROUND_A_U32 = None
+    PHILOX_ROUND_B_U32 = None
+
+
+def _pair_uniform_to_normal(u1, u2):
+    """Box-Muller transform"""
+    u1 = hl.max(hl.f32(1.0e-7), u1)
+    th = hl.f32(6.283185307179586) * u2
+    r = hl.sqrt(hl.f32(-2.0) * hl.log(u1))
+    return r * hl.cos(th), r * hl.sin(th)
+
+
+def _uint_to_uniform_float(x):
+    """
+    Numerically stable function to convert a random uint into a random float uniformly sampled in [0, 1).
+    """
+
+    # TODO:
+    # conditions can be simplified
+    # scale is ((2**23 - 1) / 2**23) * 2**(N_BITS - 1)
+    # https://github.com/triton-lang/triton/blob/e4a0d93ff1a367c7d4eeebbcd7079ed267e6b06f/python/triton/language/random.py#L116-L132.
+    assert x.type() == hl.UInt(32) or x.type() == hl.Int(32)
+    x = hl.cast(hl.Int(32), x)
+    scale = hl.f64(4.6566127342e-10)
+    x = hl.select(x < 0, -x - 1, x)
+    return x * scale
+
+
+def philox_impl(c0, c1, c2, c3, k0, k1, n_rounds):
+    def umulhi(a, b):
+        a = hl.cast(hl.UInt(64), a)
+        b = hl.cast(hl.UInt(64), b)
+        return hl.cast(hl.UInt(32), ((a * b) >> 32) & hl.u64(0xFFFFFFFF))
+
+    for _ in range(n_rounds):
+        _c0, _c2 = c0, c2
+
+        c0 = umulhi(PHILOX_ROUND_B_U32, _c2) ^ c1 ^ k0
+        c2 = umulhi(PHILOX_ROUND_A_U32, _c0) ^ c3 ^ k1
+        c1 = PHILOX_ROUND_B_U32 * _c2
+        c3 = PHILOX_ROUND_A_U32 * _c0
+        # raise key
+        k0 = k0 + PHILOX_KEY_A_U32
+        k1 = k1 + PHILOX_KEY_B_U32
+
+    return c0, c1, c2, c3
+
+
+def halide_philox(seed, c0, c1, c2, c3, n_rounds):
+    seed = hl.cast(hl.UInt(64), seed)
+
+    assert c0.type().bits() == 32
+
+    seed_hi = hl.cast(hl.UInt(32), (seed >> 32) & hl.u64(0xFFFFFFFF))
+    seed_lo = hl.cast(hl.UInt(32), seed & hl.u64(0xFFFFFFFF))
+
+    return philox_impl(c0, c1, c2, c3, seed_lo, seed_hi, n_rounds)
+
+
+def randint4x(seed, offset, n_rounds):
+    offset = hl.cast(hl.UInt(32), offset)
+    _0 = hl.u32(0)
+    return halide_philox(seed, offset, _0, _0, _0, n_rounds)
+
+
+def rand4x(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
+    i1, i2, i3, i4 = randint4x(seed, offset, n_rounds)
+    u1 = _uint_to_uniform_float(i1)
+    u2 = _uint_to_uniform_float(i2)
+    u3 = _uint_to_uniform_float(i3)
+    u4 = _uint_to_uniform_float(i4)
+    return u1, u2, u3, u4
+
+
+def randint(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
+    ret, _, _, _ = randint4x(seed, offset, n_rounds)
+    return ret
+
+
+def rand(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
+    source = randint(seed, offset, n_rounds)
+    return _uint_to_uniform_float(source)
+
+
+def randn(seed, offset):
+    i1, i2, _, _ = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT)
+    u1 = _uint_to_uniform_float(i1)
+    u2 = _uint_to_uniform_float(i2)
+    n1, _ = _pair_uniform_to_normal(u1, u2)
+    return n1
+
+
+def randint64(seed, offset, low, high):
+    r0, r1, _r2, _r3 = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT)
+    r0 = hl.cast(hl.UInt(64), r0)
+    r1 = hl.cast(hl.UInt(64), r1)
+
+    result = r0 | (r1 << 32)
+    size = high - low
+    result = result % hl.cast(hl.UInt(64), size)
+    result = hl.cast(hl.Int(64), result) + low
+    return result
diff --git a/shared/package-files/3c/3c52cb48ffc271a64b0b1124dc86bf73a0c3174aa4aa8b4c37cfdd59aa57b11d/win32con.py b/shared/package-files/3c/3c52cb48ffc271a64b0b1124dc86bf73a0c3174aa4aa8b4c37cfdd59aa57b11d/win32con.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e21b0301ae97f0d71fb344c19513868854f1e4b
--- /dev/null
+++ b/shared/package-files/3c/3c52cb48ffc271a64b0b1124dc86bf73a0c3174aa4aa8b4c37cfdd59aa57b11d/win32con.py
@@ -0,0 +1,2 @@
+LOCKFILE_EXCLUSIVE_LOCK = 0x02
+LOCKFILE_FAIL_IMMEDIATELY = 0x01
diff --git a/shared/package-files/3c/3c5a1fe66f4022af57af929a6bffa663123520104fec71248dff91f70544ddba/matching.py b/shared/package-files/3c/3c5a1fe66f4022af57af929a6bffa663123520104fec71248dff91f70544ddba/matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc0891947cb88c38930e9f8c5479d397e3aa923b
--- /dev/null
+++ b/shared/package-files/3c/3c5a1fe66f4022af57af929a6bffa663123520104fec71248dff91f70544ddba/matching.py
@@ -0,0 +1,44 @@
+"""
+**************
+Graph Matching
+**************
+
+Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent
+edges; that is, no two edges share a common vertex.
+
+`Wikipedia: Matching `_
+"""
+
+import networkx as nx
+
+__all__ = ["min_maximal_matching"]
+
+
+@nx._dispatchable
+def min_maximal_matching(G):
+    r"""Returns the minimum maximal matching of G. That is, out of all maximal
+    matchings of the graph G, the smallest is returned.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+      Undirected graph
+
+    Returns
+    -------
+    min_maximal_matching : set
+      Returns a set of edges such that no two edges share a common endpoint
+      and every edge not in the set shares some common endpoint in the set.
+      Cardinality will be 2*OPT in the worst case.
+
+    Notes
+    -----
+    The algorithm computes an approximate solution for the minimum maximal
+    cardinality matching problem. The solution is no more than 2 * OPT in size.
+    Runtime is $O(|E|)$.
+
+    References
+    ----------
+    .. [1] Vazirani, Vijay Approximation Algorithms (2001)
+    """
+    return nx.maximal_matching(G)
diff --git a/shared/package-files/3c/3c5fec755690190709d4e562ac6954018ca464f77ff644fe67c919852166206f/fix_tuple_params.cpython-311.pyc b/shared/package-files/3c/3c5fec755690190709d4e562ac6954018ca464f77ff644fe67c919852166206f/fix_tuple_params.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fddaa791b51dce962dc37705171ea8e49b037f5
Binary files /dev/null and b/shared/package-files/3c/3c5fec755690190709d4e562ac6954018ca464f77ff644fe67c919852166206f/fix_tuple_params.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c620062a62011ad4ef8774c86f5aa6cbcb7a24c59d056d28f1f87eb95936e0c/test_functions.cpython-311.pyc b/shared/package-files/3c/3c620062a62011ad4ef8774c86f5aa6cbcb7a24c59d056d28f1f87eb95936e0c/test_functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd45381184f81de37efd99bf3d0ac832415b4a04
Binary files /dev/null and b/shared/package-files/3c/3c620062a62011ad4ef8774c86f5aa6cbcb7a24c59d056d28f1f87eb95936e0c/test_functions.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c64d27e656df0baaefb1f0953e25a865d18085b07422fdcfba8705c7b3893be/imp.py b/shared/package-files/3c/3c64d27e656df0baaefb1f0953e25a865d18085b07422fdcfba8705c7b3893be/imp.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc42c15765852e74f95f5bcec3b94bdd9e18112c
--- /dev/null
+++ b/shared/package-files/3c/3c64d27e656df0baaefb1f0953e25a865d18085b07422fdcfba8705c7b3893be/imp.py
@@ -0,0 +1,346 @@
+"""This module provides the components needed to build your own __import__
+function.  Undocumented functions are obsolete.
+
+In most cases it is preferred you consider using the importlib module's
+functionality over this module.
+
+"""
+# (Probably) need to stay in _imp
+from _imp import (lock_held, acquire_lock, release_lock,
+                  get_frozen_object, is_frozen_package,
+                  init_frozen, is_builtin, is_frozen,
+                  _fix_co_filename, _frozen_module_names)
+try:
+    from _imp import create_dynamic
+except ImportError:
+    # Platform doesn't support dynamic loading.
+    create_dynamic = None
+
+from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
+from importlib._bootstrap_external import SourcelessFileLoader
+
+from importlib import machinery
+from importlib import util
+import importlib
+import os
+import sys
+import tokenize
+import types
+import warnings
+
+warnings.warn("the imp module is deprecated in favour of importlib and slated "
+              "for removal in Python 3.12; "
+              "see the module's documentation for alternative uses",
+              DeprecationWarning, stacklevel=2)
+
+# DEPRECATED
+SEARCH_ERROR = 0
+PY_SOURCE = 1
+PY_COMPILED = 2
+C_EXTENSION = 3
+PY_RESOURCE = 4
+PKG_DIRECTORY = 5
+C_BUILTIN = 6
+PY_FROZEN = 7
+PY_CODERESOURCE = 8
+IMP_HOOK = 9
+
+
+def new_module(name):
+    """**DEPRECATED**
+
+    Create a new module.
+
+    The module is not entered into sys.modules.
+
+    """
+    return types.ModuleType(name)
+
+
+def get_magic():
+    """**DEPRECATED**
+
+    Return the magic number for .pyc files.
+    """
+    return util.MAGIC_NUMBER
+
+
+def get_tag():
+    """Return the magic tag for .pyc files."""
+    return sys.implementation.cache_tag
+
+
+def cache_from_source(path, debug_override=None):
+    """**DEPRECATED**
+
+    Given the path to a .py file, return the path to its .pyc file.
+
+    The .py file does not need to exist; this simply returns the path to the
+    .pyc file calculated as if the .py file were imported.
+
+    If debug_override is not None, then it must be a boolean and is used in
+    place of sys.flags.optimize.
+
+    If sys.implementation.cache_tag is None then NotImplementedError is raised.
+
+    """
+    with warnings.catch_warnings():
+        warnings.simplefilter('ignore')
+        return util.cache_from_source(path, debug_override)
+
+
+def source_from_cache(path):
+    """**DEPRECATED**
+
+    Given the path to a .pyc. file, return the path to its .py file.
+
+    The .pyc file does not need to exist; this simply returns the path to
+    the .py file calculated to correspond to the .pyc file.  If path does
+    not conform to PEP 3147 format, ValueError will be raised. If
+    sys.implementation.cache_tag is None then NotImplementedError is raised.
+
+    """
+    return util.source_from_cache(path)
+
+
+def get_suffixes():
+    """**DEPRECATED**"""
+    extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
+    source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
+    bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
+
+    return extensions + source + bytecode
+
+
+class NullImporter:
+
+    """**DEPRECATED**
+
+    Null import object.
+
+    """
+
+    def __init__(self, path):
+        if path == '':
+            raise ImportError('empty pathname', path='')
+        elif os.path.isdir(path):
+            raise ImportError('existing directory', path=path)
+
+    def find_module(self, fullname):
+        """Always returns None."""
+        return None
+
+
+class _HackedGetData:
+
+    """Compatibility support for 'file' arguments of various load_*()
+    functions."""
+
+    def __init__(self, fullname, path, file=None):
+        super().__init__(fullname, path)
+        self.file = file
+
+    def get_data(self, path):
+        """Gross hack to contort loader to deal w/ load_*()'s bad API."""
+        if self.file and path == self.path:
+            # The contract of get_data() requires us to return bytes. Reopen the
+            # file in binary mode if needed.
+            if not self.file.closed:
+                file = self.file
+                if 'b' not in file.mode:
+                    file.close()
+            if self.file.closed:
+                self.file = file = open(self.path, 'rb')
+
+            with file:
+                return file.read()
+        else:
+            return super().get_data(path)
+
+
+class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
+
+    """Compatibility support for implementing load_source()."""
+
+
+def load_source(name, pathname, file=None):
+    loader = _LoadSourceCompatibility(name, pathname, file)
+    spec = util.spec_from_file_location(name, pathname, loader=loader)
+    if name in sys.modules:
+        module = _exec(spec, sys.modules[name])
+    else:
+        module = _load(spec)
+    # To allow reloading to potentially work, use a non-hacked loader which
+    # won't rely on a now-closed file object.
+    module.__loader__ = machinery.SourceFileLoader(name, pathname)
+    module.__spec__.loader = module.__loader__
+    return module
+
+
+class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
+
+    """Compatibility support for implementing load_compiled()."""
+
+
+def load_compiled(name, pathname, file=None):
+    """**DEPRECATED**"""
+    loader = _LoadCompiledCompatibility(name, pathname, file)
+    spec = util.spec_from_file_location(name, pathname, loader=loader)
+    if name in sys.modules:
+        module = _exec(spec, sys.modules[name])
+    else:
+        module = _load(spec)
+    # To allow reloading to potentially work, use a non-hacked loader which
+    # won't rely on a now-closed file object.
+    module.__loader__ = SourcelessFileLoader(name, pathname)
+    module.__spec__.loader = module.__loader__
+    return module
+
+
+def load_package(name, path):
+    """**DEPRECATED**"""
+    if os.path.isdir(path):
+        extensions = (machinery.SOURCE_SUFFIXES[:] +
+                      machinery.BYTECODE_SUFFIXES[:])
+        for extension in extensions:
+            init_path = os.path.join(path, '__init__' + extension)
+            if os.path.exists(init_path):
+                path = init_path
+                break
+        else:
+            raise ValueError('{!r} is not a package'.format(path))
+    spec = util.spec_from_file_location(name, path,
+                                        submodule_search_locations=[])
+    if name in sys.modules:
+        return _exec(spec, sys.modules[name])
+    else:
+        return _load(spec)
+
+
+def load_module(name, file, filename, details):
+    """**DEPRECATED**
+
+    Load a module, given information returned by find_module().
+
+    The module name must include the full package name, if any.
+
+    """
+    suffix, mode, type_ = details
+    if mode and (not mode.startswith('r') or '+' in mode):
+        raise ValueError('invalid file open mode {!r}'.format(mode))
+    elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
+        msg = 'file object required for import (type code {})'.format(type_)
+        raise ValueError(msg)
+    elif type_ == PY_SOURCE:
+        return load_source(name, filename, file)
+    elif type_ == PY_COMPILED:
+        return load_compiled(name, filename, file)
+    elif type_ == C_EXTENSION and load_dynamic is not None:
+        if file is None:
+            with open(filename, 'rb') as opened_file:
+                return load_dynamic(name, filename, opened_file)
+        else:
+            return load_dynamic(name, filename, file)
+    elif type_ == PKG_DIRECTORY:
+        return load_package(name, filename)
+    elif type_ == C_BUILTIN:
+        return init_builtin(name)
+    elif type_ == PY_FROZEN:
+        return init_frozen(name)
+    else:
+        msg =  "Don't know how to import {} (type code {})".format(name, type_)
+        raise ImportError(msg, name=name)
+
+
+def find_module(name, path=None):
+    """**DEPRECATED**
+
+    Search for a module.
+
+    If path is omitted or None, search for a built-in, frozen or special
+    module and continue search in sys.path. The module name cannot
+    contain '.'; to search for a submodule of a package, pass the
+    submodule name and the package's __path__.
+
+    """
+    if not isinstance(name, str):
+        raise TypeError("'name' must be a str, not {}".format(type(name)))
+    elif not isinstance(path, (type(None), list)):
+        # Backwards-compatibility
+        raise RuntimeError("'path' must be None or a list, "
+                           "not {}".format(type(path)))
+
+    if path is None:
+        if is_builtin(name):
+            return None, None, ('', '', C_BUILTIN)
+        elif is_frozen(name):
+            return None, None, ('', '', PY_FROZEN)
+        else:
+            path = sys.path
+
+    for entry in path:
+        package_directory = os.path.join(entry, name)
+        for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
+            package_file_name = '__init__' + suffix
+            file_path = os.path.join(package_directory, package_file_name)
+            if os.path.isfile(file_path):
+                return None, package_directory, ('', '', PKG_DIRECTORY)
+        for suffix, mode, type_ in get_suffixes():
+            file_name = name + suffix
+            file_path = os.path.join(entry, file_name)
+            if os.path.isfile(file_path):
+                break
+        else:
+            continue
+        break  # Break out of outer loop when breaking out of inner loop.
+    else:
+        raise ImportError(_ERR_MSG.format(name), name=name)
+
+    encoding = None
+    if 'b' not in mode:
+        with open(file_path, 'rb') as file:
+            encoding = tokenize.detect_encoding(file.readline)[0]
+    file = open(file_path, mode, encoding=encoding)
+    return file, file_path, (suffix, mode, type_)
+
+
+def reload(module):
+    """**DEPRECATED**
+
+    Reload the module and return it.
+
+    The module must have been successfully imported before.
+
+    """
+    return importlib.reload(module)
+
+
+def init_builtin(name):
+    """**DEPRECATED**
+
+    Load and return a built-in module by name, or None is such module doesn't
+    exist
+    """
+    try:
+        return _builtin_from_name(name)
+    except ImportError:
+        return None
+
+
+if create_dynamic:
+    def load_dynamic(name, path, file=None):
+        """**DEPRECATED**
+
+        Load an extension module.
+        """
+        import importlib.machinery
+        loader = importlib.machinery.ExtensionFileLoader(name, path)
+
+        # Issue #24748: Skip the sys.modules check in _load_module_shim;
+        # always load new extension
+        spec = importlib.machinery.ModuleSpec(
+            name=name, loader=loader, origin=path)
+        return _load(spec)
+
+else:
+    load_dynamic = None
diff --git a/shared/package-files/3c/3c6a56f31df6812fc51477f99db2f1d309e68667d0755db102bd74999037a893/__init__.cpython-311.pyc b/shared/package-files/3c/3c6a56f31df6812fc51477f99db2f1d309e68667d0755db102bd74999037a893/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a86725a83c7cb4977aafde224f0519aa365590f
Binary files /dev/null and b/shared/package-files/3c/3c6a56f31df6812fc51477f99db2f1d309e68667d0755db102bd74999037a893/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c6ce300061f955e05a2d02c3de95bd8736d923bd53d408f1799bb37c0d8aa04/triu_meta.h b/shared/package-files/3c/3c6ce300061f955e05a2d02c3de95bd8736d923bd53d408f1799bb37c0d8aa04/triu_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..c0195c7af485a1226c4dc05e5408e066a7aae49b
--- /dev/null
+++ b/shared/package-files/3c/3c6ce300061f955e05a2d02c3de95bd8736d923bd53d408f1799bb37c0d8aa04/triu_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_triu : public at::impl::MetaBase {
+    
+    
+    void meta(const at::Tensor & self, int64_t diagonal);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/3c/3c6ff52271310f8180e3849f925d2fc90ccb1a6960796dea1ae939434eed2569/handlers.cpython-311.pyc b/shared/package-files/3c/3c6ff52271310f8180e3849f925d2fc90ccb1a6960796dea1ae939434eed2569/handlers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4531783b24ae19fd443226dad2215dab824de1f5
Binary files /dev/null and b/shared/package-files/3c/3c6ff52271310f8180e3849f925d2fc90ccb1a6960796dea1ae939434eed2569/handlers.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c721ef47de5d22b88990eb3dd6a8c916212dfb143415435eaf328d1ad3c9ad0/__init__.py b/shared/package-files/3c/3c721ef47de5d22b88990eb3dd6a8c916212dfb143415435eaf328d1ad3c9ad0/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a0eaf86bdbeacfe7d4e7cbd50daf11385955d7d
--- /dev/null
+++ b/shared/package-files/3c/3c721ef47de5d22b88990eb3dd6a8c916212dfb143415435eaf328d1ad3c9ad0/__init__.py
@@ -0,0 +1,10 @@
+from .conv_expanded_weights import ConvPerSampleGrad
+from .embedding_expanded_weights import EmbeddingPerSampleGrad
+from .expanded_weights_impl import ExpandedWeight
+from .group_norm_expanded_weights import GroupNormPerSampleGrad
+from .instance_norm_expanded_weights import InstanceNormPerSampleGrad
+from .layer_norm_expanded_weights import LayerNormPerSampleGrad
+from .linear_expanded_weights import LinearPerSampleGrad
+
+
+__all__ = ["ExpandedWeight"]
diff --git a/shared/package-files/3c/3c791bf007898cea41aad8c1fc9c947d107136cbb627e7e10189d2eafee3410c/empty_strided_cuda_dispatch.h b/shared/package-files/3c/3c791bf007898cea41aad8c1fc9c947d107136cbb627e7e10189d2eafee3410c/empty_strided_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..69af081ff95d52a37bba94cf1293a0dd1f5d3698
--- /dev/null
+++ b/shared/package-files/3c/3c791bf007898cea41aad8c1fc9c947d107136cbb627e7e10189d2eafee3410c/empty_strided_cuda_dispatch.h
@@ -0,0 +1,26 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options={});
+TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory);
+TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options={});
+TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory);
+
+} // namespace cuda
+} // namespace at
diff --git a/shared/package-files/3c/3c797625d97bb316f6c11f0f7a22891353bbc5c69aeaf3e982d2a5f44e4fd549/model.h b/shared/package-files/3c/3c797625d97bb316f6c11f0f7a22891353bbc5c69aeaf3e982d2a5f44e4fd549/model.h
new file mode 100644
index 0000000000000000000000000000000000000000..0015b476d178cc162677b02fe5e362dc117f2b74
--- /dev/null
+++ b/shared/package-files/3c/3c797625d97bb316f6c11f0f7a22891353bbc5c69aeaf3e982d2a5f44e4fd549/model.h
@@ -0,0 +1,736 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// WARNING: Be careful when adding new includes here. This header will be used
+// in model.so, and should not refer to any aten/c10 headers except the stable
+// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
+// applies to other files under torch/csrc/inductor/aoti_runtime/.
+#include 
+#ifdef USE_XPU
+#include 
+#else
+#include 
+#endif
+
+#define AOTI_RUNTIME_CHECK(EXPR, MSG) \
+  do {                                \
+    bool ok = EXPR;                   \
+    if (!ok) {                        \
+      throw std::runtime_error(MSG);  \
+    }                                 \
+  } while (0)
+
+// At codegen time, we write out a binary file called constants.bin.
+// We then turn the raw binary to an object file that exposes this
+// symbol and link it into the final .so.
+// For information on the binary format, see `man objcopy`, under
+// the "binary-architecture" flag:
+// https://man7.org/linux/man-pages/man1/objcopy.1.html
+// todo: use #embed in C++ 23 once available
+// The constants are NOT readonly because they may be mutated.
+// NOLINTNEXTLINE(*array*)
+extern uint8_t _binary_constants_bin_start[];
+// NOLINTNEXTLINE(*array*)
+extern uint8_t _binary_constants_bin_end[];
+
+#if defined(USE_CUDA) || defined(USE_XPU)
+// Compute required blob size with 64-alignment if on GPU.
+#define AOTI_CONST_ALIGNMENT 64
+#else
+// Use 64-alignment (use something >=64)for better performance on CPU.
+#define AOTI_CONST_ALIGNMENT 64
+#endif
+
+namespace {
+
+using RAIIDataPtr = std::unique_ptr>;
+
+#ifdef USE_CUDA
+
+RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) {
+  void* data_ptr;
+  AOTI_RUNTIME_DEVICE_CHECK(cudaMalloc((void**)&data_ptr, num_bytes));
+  auto deleter = [](void* ptr) { AOTI_RUNTIME_DEVICE_CHECK(cudaFree(ptr)); };
+  return RAIIDataPtr(data_ptr, deleter);
+}
+
+#elif defined(USE_XPU)
+
+RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) {
+  sycl::queue* queue_ptr = nullptr;
+  aoti_torch_get_current_sycl_queue((void**)&queue_ptr);
+  void* data_ptr = sycl::malloc_device(num_bytes, *queue_ptr);
+  auto deleter = [queue_ptr](void* ptr) { sycl::free(ptr, *queue_ptr); };
+  return RAIIDataPtr(data_ptr, deleter);
+}
+
+#else
+
+RAIIDataPtr RAII_cpuMalloc(size_t num_bytes) {
+  void* data_ptr = std::malloc(num_bytes);
+  if (!data_ptr) {
+    throw std::bad_alloc();
+  }
+  auto deleter = [](void* ptr) { std::free(ptr); };
+  return RAIIDataPtr(data_ptr, deleter);
+}
+
+#endif // USE_CUDA
+
+} // anonymous namespace
+
+namespace torch::aot_inductor {
+enum ConstantType : uint8_t {
+  Unknown = 0,
+  Parameter = 1,
+  Buffer = 2,
+  TensorConstant = 3,
+  FoldedConstant = 4,
+};
+
+using ConstantMap = std::unordered_map;
+
+// valid device strs are: cpu, cuda, cuda:0, cuda:1, ...
+// Update the list here if more devices are supported in the future
+inline void parse_device_str(
+    const std::string& device_str,
+    int32_t& device_type,
+    int32_t& device_idx) {
+  std::regex re("(cpu|cuda|xpu)(:([0-9]+))?");
+  std::smatch sm;
+  bool matched = std::regex_match(device_str, sm, re);
+  AOTI_RUNTIME_CHECK(matched, "Invalid device: " + device_str);
+
+  if (sm[1].str() == "cpu") {
+    device_type = aoti_torch_device_type_cpu();
+  } else if (sm[1].str() == "cuda") {
+    device_type = aoti_torch_device_type_cuda();
+#ifdef USE_XPU
+  } else if (sm[1].str() == "xpu") {
+    device_type = aoti_torch_device_type_xpu();
+#endif
+  } else {
+    AOTI_RUNTIME_CHECK(false, "Invalid device: " + device_str);
+  }
+
+  if (sm[3].matched) {
+    device_idx = stoi(sm[3].str());
+  } else {
+    device_idx = -1;
+  }
+}
+
+// Defines the base class for AOTInductorModel, which is generated by the
+// AOTInductor cpp codegen. Since we do not need dynamic dispatch, we rely
+// on curiously recurring template pattern (CRTP) to save some runtime
+// v-table overhead. The generated AOTInductorModel is specialized with
+// methods such as run_impl.
+template 
+class AOTInductorModelBase {
+ public:
+  AOTInductorModelBase(
+      size_t num_inputs,
+      size_t num_outputs,
+      size_t num_constants,
+      const std::string& device_str,
+      std::optional cubin_dir,
+      bool include_weights = true)
+      : inputs_info_(num_inputs),
+        outputs_info_(num_outputs),
+        constants_info_(num_constants),
+        cubin_dir_(std::move(cubin_dir)),
+        include_weights(include_weights) {
+    parse_device_str(device_str, device_type_, device_idx_);
+
+#ifdef USE_CUDA
+    if (device_idx_ == -1) {
+      AOTI_RUNTIME_DEVICE_CHECK(cudaGetDevice(&device_idx_));
+    } else {
+      // If device_idx_ is passed in, we need to set the current device to it
+      AOTI_RUNTIME_DEVICE_CHECK(cudaSetDevice(device_idx_));
+    }
+#endif // USE_CUDA
+#ifdef USE_XPU
+    if (device_idx_ == -1) {
+      aoti_torch_get_current_xpu_device(&device_idx_);
+    } else {
+      aoti_torch_set_current_xpu_device(device_idx_);
+    }
+#endif // USE_XPU
+  }
+
+  // NOLINTNEXTLINE(modernize-use-equals-default)
+  ~AOTInductorModelBase() {
+#ifdef USE_CUDA
+    if (run_finished_) {
+      auto code = cudaEventDestroy(*run_finished_);
+      if (code != cudaSuccess) {
+        std::cerr << "Failed to destroy CUDA event in AOTInductor model: "
+                  << cudaGetErrorString(code) << std::endl;
+      }
+    }
+#endif // USE_CUDA
+#ifdef USE_XPU
+    if (run_finished_) {
+      (*run_finished_)->wait_and_throw();
+      delete *run_finished_;
+    }
+#endif // USE_XPU
+  }
+
+  AOTInductorModelBase(AOTInductorModelBase&&) = delete;
+  AOTInductorModelBase& operator=(AOTInductorModelBase&&) = delete;
+  AOTInductorModelBase(const AOTInductorModelBase&) = delete;
+  AOTInductorModelBase& operator=(const AOTInductorModelBase&) = delete;
+
+  void run(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor) {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      cudaEvent_t run_finished;
+      AOTI_RUNTIME_DEVICE_CHECK(cudaEventCreate(&run_finished));
+      run_finished_.emplace(run_finished);
+    }
+#elif defined(USE_XPU)
+    if (run_finished_) {
+      (*run_finished_)->wait_and_throw();
+      delete *run_finished_;
+      run_finished_.reset();
+    }
+#else // !USE_CUDA && !USE_XPU
+    run_finished_ = false;
+#endif
+
+    auto* model = static_cast(this);
+    model->run_impl(input_handles, output_handles, stream, proxy_executor);
+
+#ifdef USE_CUDA
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventRecord(*run_finished_, stream));
+#elif defined(USE_XPU)
+    run_finished_ = std::make_optional(new sycl::event(
+        static_cast(stream)->ext_oneapi_submit_barrier()));
+#else // !USE_CUDA && !USE_XPU
+    run_finished_ = true;
+#endif // USE_CUDA
+  }
+
+  // Non-thread-aware variant of run(). Obviously unsafe to use in a threaded
+  // environment :)
+  void run_single_threaded(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor) {
+    // don't bother with any of the run_finished stuff; this is unsafe to call
+    // in a threaded context
+    auto* model = static_cast(this);
+    model->run_impl(input_handles, output_handles, stream, proxy_executor);
+  }
+
+  std::unordered_map run_const_fold(
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor,
+      bool initialization = false) {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      cudaEvent_t run_finished;
+      AOTI_RUNTIME_DEVICE_CHECK(cudaEventCreate(&run_finished));
+      run_finished_.emplace(run_finished);
+    }
+#elif defined(USE_XPU)
+    if (run_finished_) {
+      (*run_finished_)->wait_and_throw();
+      delete *run_finished_;
+      run_finished_.reset();
+    }
+#else // !USE_CUDA && !USE_XPU
+    run_finished_ = false;
+#endif
+
+    auto* model = static_cast(this);
+    auto folded_constants =
+        model->const_run_impl(stream, proxy_executor, initialization);
+
+#ifdef USE_CUDA
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventRecord(*run_finished_, stream));
+#elif defined(USE_XPU)
+    // sycl::queue* queue_ptr = nullptr;
+    // aoti_torch_get_current_sycl_queue((void**)&queue_ptr);
+    run_finished_ = std::make_optional(new sycl::event(
+        static_cast(stream)->ext_oneapi_submit_barrier()));
+
+#else // !USE_CUDA && !USE_XPU
+    run_finished_ = true;
+#endif // USE_CUDA
+
+    return folded_constants;
+  }
+
+  void load_constants() {
+    size_t num_constants = this->num_constants();
+    constants_map_->reserve(num_constants);
+
+    std::vector constants_internal_offset(num_constants);
+    size_t blob_size = 0;
+    compute_constant_blob(blob_size, constants_internal_offset);
+#if defined(USE_CUDA) || defined(USE_XPU)
+    constant_blob_ = RAII_gpuMalloc(blob_size);
+#else
+    constant_blob_ = RAII_cpuMalloc(blob_size);
+#endif
+    if (!include_weights) {
+      return;
+    }
+
+    size_t bytes_read = 0;
+    for (size_t i = 0; i < num_constants; i++) {
+      bool from_folded = this->constant_from_folded(i);
+      if (from_folded) {
+        continue;
+      }
+      std::string name = this->constant_name(i);
+      size_t data_size = this->constant_data_size(i);
+      uint8_t* internal_ptr = (data_size != 0)
+          ? constant_ptr(
+                constants_internal_offset[i],
+                bytes_read,
+                data_size,
+                from_folded)
+          : nullptr;
+      bytes_read += data_size;
+
+      // Create at::Tensor from copied memory.
+      auto dtype = this->constant_dtype(i);
+      auto ndim = this->constant_ndim(i);
+      auto size = this->constant_shape(i);
+      auto stride = this->constant_stride(i);
+      auto offset = this->constant_offset(i);
+      auto layout = this->constant_layout(i);
+      auto opaque_metadata_ptr = this->opaque_metadata(i);
+      auto opaque_metadata_size = this->opaque_metadata_size(i);
+
+      AtenTensorHandle tensor_handle = nullptr;
+      AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2(
+          internal_ptr,
+          ndim,
+          size,
+          stride,
+          offset,
+          dtype,
+          device_type_,
+          device_idx_,
+          &tensor_handle,
+          layout,
+          opaque_metadata_ptr,
+          opaque_metadata_size));
+      constants_map_->emplace(std::move(name), tensor_handle);
+    }
+    if (constants_map_) {
+      this->update_constants_array_from_map();
+    }
+  }
+
+  RAIIDataPtr&& release_constant_blob() {
+    return std::move(constant_blob_);
+  }
+
+  std::shared_ptr> get_constants_array() {
+    return constants_;
+  }
+
+  int32_t get_device_type() const {
+    return device_type_;
+  }
+
+  int32_t get_device_idx() const {
+    return device_idx_;
+  }
+
+  uint8_t* constant_ptr(
+      size_t constant_offset,
+      size_t bytes_read,
+      size_t data_size,
+      bool skip_copy) {
+    auto* constants_ptr = static_cast(constant_blob_.get());
+    uint8_t* internal_ptr = constants_ptr + constant_offset;
+    // TODO: Handle shared storage case.
+    if (!skip_copy) {
+#ifdef USE_XPU
+      sycl::queue* queue_ptr = nullptr;
+      aoti_torch_get_current_sycl_queue((void**)&queue_ptr);
+      queue_ptr
+          ->memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size)
+          .wait();
+#elif USE_CUDA
+      AOTI_RUNTIME_DEVICE_CHECK(cudaMemcpy(
+          internal_ptr,
+          _get_constants_start() + bytes_read,
+          data_size,
+          cudaMemcpyHostToDevice));
+#else
+      memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size);
+#endif
+    }
+    return internal_ptr;
+  }
+
+  void compute_constant_blob(
+      size_t& blob_size,
+      std::vector& constants_internal_offset) {
+    size_t num_constants = this->num_constants();
+    blob_size = 0;
+    for (size_t i = 0; i < num_constants; i++) {
+      size_t data_size = this->constant_data_size(i);
+      if (data_size % AOTI_CONST_ALIGNMENT) {
+        data_size = AOTI_CONST_ALIGNMENT +
+            (data_size / AOTI_CONST_ALIGNMENT) * AOTI_CONST_ALIGNMENT;
+      }
+      constants_internal_offset[i] = blob_size;
+      blob_size += data_size;
+    }
+  }
+
+  size_t num_inputs() const {
+    return inputs_info_.size();
+  }
+
+  size_t num_outputs() const {
+    return outputs_info_.size();
+  }
+
+  size_t num_constants() const {
+    return constants_info_.size();
+  }
+
+  const char* input_name(int64_t idx) const {
+    return inputs_info_.at(idx).name;
+  }
+
+  const char* output_name(int64_t idx) const {
+    return outputs_info_.at(idx).name;
+  }
+
+  const char* constant_name(int64_t idx) const {
+    return constants_info_.at(idx).name;
+  }
+
+  size_t constant_ndim(int64_t idx) {
+    return constants_info_.at(idx).shape.size();
+  }
+
+  const int64_t* constant_shape(int64_t idx) const {
+    return constants_info_.at(idx).shape.data();
+  }
+
+  const int64_t* constant_stride(int64_t idx) const {
+    return constants_info_.at(idx).stride.data();
+  }
+
+  int32_t constant_dtype(int64_t idx) const {
+    return constants_info_.at(idx).dtype;
+  }
+
+  int32_t constant_layout(int64_t idx) const {
+    return constants_info_.at(idx).layout;
+  }
+
+  size_t constant_offset(int64_t idx) const {
+    return constants_info_.at(idx).offset;
+  }
+
+  size_t constant_data_size(int64_t idx) const {
+    return constants_info_.at(idx).data_size;
+  }
+
+  const char* constant_original_fqn(int64_t idx) const {
+    return constants_info_.at(idx).original_fqn;
+  }
+
+  const uint8_t* opaque_metadata(int64_t idx) const {
+    return constants_info_.at(idx).opaque_metadata.data();
+  }
+
+  size_t opaque_metadata_size(int64_t idx) {
+    return constants_info_.at(idx).opaque_metadata.size();
+  }
+
+  bool constant_from_folded(int64_t idx) const {
+    return constants_info_.at(idx).from_folded;
+  }
+
+  int32_t constant_type(int64_t idx) const {
+    return constants_info_.at(idx).type;
+  }
+
+  const char* get_in_spec() const {
+    return in_spec_.c_str();
+  }
+
+  const char* get_out_spec() const {
+    return out_spec_.c_str();
+  }
+
+  void update_constants_array_from_map() {
+    if (!constants_map_) {
+      throw std::runtime_error{
+          "constants_map_ was not ready when constants_ is trying to be constructed from it!"};
+    }
+    if (!constants_) {
+      constants_ =
+          std::make_shared>(constants_info_.size());
+    } else {
+      constants_->resize(constants_info_.size());
+    }
+    int idx = 0;
+    for (const auto& info : constants_info_) {
+      const auto it = constants_map_->find(info.name);
+      if (it != constants_map_->end()) {
+        constants_->at(idx) = ConstantHandle(it->second);
+      }
+      idx++;
+    }
+  }
+
+  void update_constants_map(
+      std::shared_ptr constants_map,
+      bool remap_constants_array = true) {
+    constants_map_ = std::move(constants_map);
+    if (remap_constants_array) {
+      update_constants_array_from_map();
+    }
+  }
+
+  // This function allows us to update the constants_ that is used to look up
+  // the corresponding constant tensor during runtime.
+  void update_constants_array(
+      std::shared_ptr> constants_array) {
+    constants_ = std::move(constants_array);
+  }
+
+  /// Returns true if the model is complete.
+  bool is_finished() {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      throw std::runtime_error{"Model CUDA event was not initialized"};
+    }
+
+    auto event_status = cudaEventQuery(*run_finished_);
+    if (event_status == cudaSuccess) {
+      return true;
+    } else if (event_status == cudaErrorNotReady) {
+      return false;
+    }
+
+    throw std::runtime_error(
+        std::string("The model did not finish successfully. Error: ") +
+        cudaGetErrorString(cudaGetLastError()));
+#elif defined(USE_XPU)
+    if (!run_finished_) {
+      throw std::runtime_error{"Model XPU event was not initialized"};
+    }
+    using namespace sycl::info;
+    return (*run_finished_)->get_info() ==
+        event_command_status::complete;
+
+#else // !USE_CUDA && !USE_XPU
+    return run_finished_;
+#endif // USE_CUDA
+  }
+
+  /// Synchronizes completion event.
+  void wait_for_completion() {
+#ifdef USE_CUDA
+    if (!run_finished_) {
+      throw std::runtime_error{"Model event was not initialized"};
+    }
+
+    AOTI_RUNTIME_DEVICE_CHECK(cudaEventSynchronize(*run_finished_));
+#endif // USE_CUDA
+#ifdef USE_XPU
+    if (!run_finished_) {
+      throw std::runtime_error{"Model event was not initialized"};
+    }
+    (*run_finished_)->wait_and_throw();
+#endif
+  }
+
+ protected:
+  uint8_t* _get_constants_start() {
+#ifndef USE_MMAP_SELF
+    // NOLINTNEXTLINE(*const-cast*)
+    return const_cast(_binary_constants_bin_start);
+#else
+    if (self_mmap) {
+      return self_mmap;
+    }
+    Dl_info dl_info;
+    // get pointer to constant which are appended to the binary
+    AOTI_RUNTIME_CHECK(
+        dladdr(__func__, &dl_info), "Can't find shared library name");
+    int fd = open(dl_info.dli_fname, O_RDONLY);
+    AOTI_RUNTIME_CHECK(fd >= 0, "Shared library file cannot be opened");
+    auto fsize = lseek(fd, 0, SEEK_END);
+    auto weights_size =
+        reinterpret_cast(_binary_constants_bin_start)[0];
+    auto magic_number =
+        reinterpret_cast(_binary_constants_bin_start)[1];
+    auto weights_offset = fsize - weights_size;
+    AOTI_RUNTIME_CHECK(
+        (weights_offset & 0x3fff) == 0,
+        "weights_offset must be aligned to 16K boundary");
+    auto ptr = mmap(
+        NULL,
+        weights_size,
+        PROT_READ | PROT_WRITE,
+        MAP_PRIVATE,
+        fd,
+        weights_offset);
+    close(fd);
+    AOTI_RUNTIME_CHECK(ptr != MAP_FAILED, "mmap() failed");
+    self_mmap = static_cast(ptr);
+    AOTI_RUNTIME_CHECK(
+        reinterpret_cast(
+            self_mmap + weights_size - sizeof(uint64_t))[0] == magic_number,
+        "Weigths data seems corrupt");
+    return self_mmap;
+#endif
+  }
+  struct ParamInfo {
+    const char* name = nullptr;
+  };
+
+  struct ConstInfo {
+    const char* name = nullptr;
+    std::vector shape;
+    std::vector stride;
+    int32_t dtype{};
+    int64_t offset{};
+    size_t data_size{};
+    int32_t layout{};
+    std::vector opaque_metadata;
+    int64_t opaque_metadata_size{};
+    const char* original_fqn = nullptr;
+    bool from_folded{};
+    int32_t type{};
+  };
+
+  std::vector inputs_info_;
+  std::vector outputs_info_;
+  std::vector constants_info_;
+  std::string in_spec_;
+  std::string out_spec_;
+
+  std::shared_ptr constants_map_;
+  std::shared_ptr> constants_;
+
+  // Holds the blob storage for constants' at::Tensor.
+  RAIIDataPtr constant_blob_;
+
+#ifdef USE_MMAP_SELF
+  uint8_t* self_mmap = NULL;
+#endif
+
+  // A directory with CUDA binary files, e.g. compiled kernels, etc.
+  const std::optional cubin_dir_;
+
+  // This is the flag that implies whether the weight is included in the model.
+  // If True, we would prepare the weight when loading the model, otherwise the
+  // model will be loaded without weights, and need to be provided by the user.
+  bool include_weights;
+
+  // Record if the model finishes an inference run so that its owning
+  // AOTModelContainer can re-use this instance.
+#ifdef USE_CUDA
+  std::optional run_finished_;
+#elif defined(USE_XPU)
+  std::optional run_finished_;
+#else // !USE_CUDA
+  bool run_finished_{};
+#endif
+
+  // Generated model uses this device index to create CUDA guards.
+  int32_t device_type_{};
+  int32_t device_idx_{};
+};
+
+// Codegen-ed classes can derive from this to keep pointers to loaded kernels.
+class AOTInductorModelKernelsBase {
+ public:
+  virtual ~AOTInductorModelKernelsBase() = default;
+};
+
+class AOTInductorModel : public AOTInductorModelBase {
+ public:
+  AOTInductorModel(
+      std::shared_ptr constants_map,
+      std::shared_ptr> constants_array,
+      const std::string& device_str,
+      std::optional cubin_dir,
+      bool include_weights = true);
+
+  std::unordered_map const_run_impl(
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor,
+      bool initialization = false);
+
+  void _const_run_impl(
+      std::vector& output_handles,
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  void run_impl(
+      AtenTensorHandle*
+          input_handles, // array of input AtenTensorHandle; handles
+                         // are stolen; the array itself is borrowed
+      AtenTensorHandle*
+          output_handles, // array for writing output AtenTensorHandle; handles
+                          // will be stolen by the caller; the array itself is
+                          // borrowed
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  template 
+  Outputs run_impl_minimal_arrayref_interface(
+      const Inputs& inputs,
+      DeviceStreamType stream,
+      AOTIProxyExecutorHandle proxy_executor);
+
+  static std::unique_ptr Create(
+      std::shared_ptr constants_map,
+      std::shared_ptr> constants_array,
+      const std::string& device_str,
+      std::optional cubin_dir) {
+    return std::make_unique(
+        std::move(constants_map),
+        std::move(constants_array),
+        device_str,
+        std::move(cubin_dir));
+  }
+
+ private:
+  std::unique_ptr kernels_;
+};
+
+} // namespace torch::aot_inductor
diff --git a/shared/package-files/3c/3c8260fca9a5f0cc6626ce503c28c69912e38e513fe102a1b16854efe6a7ef1d/orthopolys.py b/shared/package-files/3c/3c8260fca9a5f0cc6626ce503c28c69912e38e513fe102a1b16854efe6a7ef1d/orthopolys.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee82457703a2be172951ee38e3cd67f221a438a0
--- /dev/null
+++ b/shared/package-files/3c/3c8260fca9a5f0cc6626ce503c28c69912e38e513fe102a1b16854efe6a7ef1d/orthopolys.py
@@ -0,0 +1,343 @@
+"""Efficient functions for generating orthogonal polynomials."""
+from sympy.core.symbol import Dummy
+from sympy.polys.densearith import (dup_mul, dup_mul_ground,
+    dup_lshift, dup_sub, dup_add, dup_sub_term, dup_sub_ground, dup_sqr)
+from sympy.polys.domains import ZZ, QQ
+from sympy.polys.polytools import named_poly
+from sympy.utilities import public
+
+def dup_jacobi(n, a, b, K):
+    """Low-level implementation of Jacobi polynomials."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [(a+b)/K(2) + K.one, (a-b)/K(2)]
+    for i in range(2, n+1):
+        den = K(i)*(a + b + i)*(a + b + K(2)*i - K(2))
+        f0 = (a + b + K(2)*i - K.one) * (a*a - b*b) / (K(2)*den)
+        f1 = (a + b + K(2)*i - K.one) * (a + b + K(2)*i - K(2)) * (a + b + K(2)*i) / (K(2)*den)
+        f2 = (a + i - K.one)*(b + i - K.one)*(a + b + K(2)*i) / den
+        p0 = dup_mul_ground(m1, f0, K)
+        p1 = dup_mul_ground(dup_lshift(m1, 1, K), f1, K)
+        p2 = dup_mul_ground(m2, f2, K)
+        m2, m1 = m1, dup_sub(dup_add(p0, p1, K), p2, K)
+    return m1
+
+@public
+def jacobi_poly(n, a, b, x=None, polys=False):
+    r"""Generates the Jacobi polynomial `P_n^{(a,b)}(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    a
+        Lower limit of minimal domain for the list of coefficients.
+    b
+        Upper limit of minimal domain for the list of coefficients.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_jacobi, None, "Jacobi polynomial", (x, a, b), polys)
+
+def dup_gegenbauer(n, a, K):
+    """Low-level implementation of Gegenbauer polynomials."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [K(2)*a, K.zero]
+    for i in range(2, n+1):
+        p1 = dup_mul_ground(dup_lshift(m1, 1, K), K(2)*(a-K.one)/K(i) + K(2), K)
+        p2 = dup_mul_ground(m2, K(2)*(a-K.one)/K(i) + K.one, K)
+        m2, m1 = m1, dup_sub(p1, p2, K)
+    return m1
+
+def gegenbauer_poly(n, a, x=None, polys=False):
+    r"""Generates the Gegenbauer polynomial `C_n^{(a)}(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    a
+        Decides minimal domain for the list of coefficients.
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_gegenbauer, None, "Gegenbauer polynomial", (x, a), polys)
+
+def dup_chebyshevt(n, K):
+    """Low-level implementation of Chebyshev polynomials of the first kind."""
+    if n < 1:
+        return [K.one]
+    # When n is small, it is faster to directly calculate the recurrence relation.
+    if n < 64: # The threshold serves as a heuristic
+        return _dup_chebyshevt_rec(n, K)
+    return _dup_chebyshevt_prod(n, K)
+
+def _dup_chebyshevt_rec(n, K):
+    r""" Chebyshev polynomials of the first kind using recurrence.
+
+    Explanation
+    ===========
+
+    Chebyshev polynomials of the first kind are defined by the recurrence
+    relation:
+
+    .. math::
+        T_0(x) &= 1\\
+        T_1(x) &= x\\
+        T_n(x) &= 2xT_{n-1}(x) - T_{n-2}(x)
+
+    This function calculates the Chebyshev polynomial of the first kind using
+    the above recurrence relation.
+
+    Parameters
+    ==========
+
+    n : int
+        n is a nonnegative integer.
+    K : domain
+
+    """
+    m2, m1 = [K.one], [K.one, K.zero]
+    for _ in range(n - 1):
+        m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K)
+    return m1
+
+def _dup_chebyshevt_prod(n, K):
+    r""" Chebyshev polynomials of the first kind using recursive products.
+
+    Explanation
+    ===========
+
+    Computes Chebyshev polynomials of the first kind using
+
+    .. math::
+        T_{2n}(x) &= 2T_n^2(x) - 1\\
+        T_{2n+1}(x) &= 2T_{n+1}(x)T_n(x) - x
+
+    This is faster than ``_dup_chebyshevt_rec`` for large ``n``.
+
+    Parameters
+    ==========
+
+    n : int
+        n is a nonnegative integer.
+    K : domain
+
+    """
+    m2, m1 = [K.one, K.zero], [K(2), K.zero, -K.one]
+    for i in bin(n)[3:]:
+        c = dup_sub_term(dup_mul_ground(dup_mul(m1, m2, K), K(2), K), K.one, 1, K)
+        if  i  == '1':
+            m2, m1 = c, dup_sub_ground(dup_mul_ground(dup_sqr(m1, K), K(2), K), K.one, K)
+        else:
+            m2, m1 = dup_sub_ground(dup_mul_ground(dup_sqr(m2, K), K(2), K), K.one, K), c
+    return m2
+
+def dup_chebyshevu(n, K):
+    """Low-level implementation of Chebyshev polynomials of the second kind."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [K(2), K.zero]
+    for i in range(2, n+1):
+        m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K)
+    return m1
+
+@public
+def chebyshevt_poly(n, x=None, polys=False):
+    r"""Generates the Chebyshev polynomial of the first kind `T_n(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_chebyshevt, ZZ,
+            "Chebyshev polynomial of the first kind", (x,), polys)
+
+@public
+def chebyshevu_poly(n, x=None, polys=False):
+    r"""Generates the Chebyshev polynomial of the second kind `U_n(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_chebyshevu, ZZ,
+            "Chebyshev polynomial of the second kind", (x,), polys)
+
+def dup_hermite(n, K):
+    """Low-level implementation of Hermite polynomials."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [K(2), K.zero]
+    for i in range(2, n+1):
+        a = dup_lshift(m1, 1, K)
+        b = dup_mul_ground(m2, K(i-1), K)
+        m2, m1 = m1, dup_mul_ground(dup_sub(a, b, K), K(2), K)
+    return m1
+
+def dup_hermite_prob(n, K):
+    """Low-level implementation of probabilist's Hermite polynomials."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [K.one, K.zero]
+    for i in range(2, n+1):
+        a = dup_lshift(m1, 1, K)
+        b = dup_mul_ground(m2, K(i-1), K)
+        m2, m1 = m1, dup_sub(a, b, K)
+    return m1
+
+@public
+def hermite_poly(n, x=None, polys=False):
+    r"""Generates the Hermite polynomial `H_n(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_hermite, ZZ, "Hermite polynomial", (x,), polys)
+
+@public
+def hermite_prob_poly(n, x=None, polys=False):
+    r"""Generates the probabilist's Hermite polynomial `He_n(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_hermite_prob, ZZ,
+            "probabilist's Hermite polynomial", (x,), polys)
+
+def dup_legendre(n, K):
+    """Low-level implementation of Legendre polynomials."""
+    if n < 1:
+        return [K.one]
+    m2, m1 = [K.one], [K.one, K.zero]
+    for i in range(2, n+1):
+        a = dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1, i), K)
+        b = dup_mul_ground(m2, K(i-1, i), K)
+        m2, m1 = m1, dup_sub(a, b, K)
+    return m1
+
+@public
+def legendre_poly(n, x=None, polys=False):
+    r"""Generates the Legendre polynomial `P_n(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_legendre, QQ, "Legendre polynomial", (x,), polys)
+
+def dup_laguerre(n, alpha, K):
+    """Low-level implementation of Laguerre polynomials."""
+    m2, m1 = [K.zero], [K.one]
+    for i in range(1, n+1):
+        a = dup_mul(m1, [-K.one/K(i), (alpha-K.one)/K(i) + K(2)], K)
+        b = dup_mul_ground(m2, (alpha-K.one)/K(i) + K.one, K)
+        m2, m1 = m1, dup_sub(a, b, K)
+    return m1
+
+@public
+def laguerre_poly(n, x=None, alpha=0, polys=False):
+    r"""Generates the Laguerre polynomial `L_n^{(\alpha)}(x)`.
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    alpha : optional
+        Decides minimal domain for the list of coefficients.
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+    """
+    return named_poly(n, dup_laguerre, None, "Laguerre polynomial", (x, alpha), polys)
+
+def dup_spherical_bessel_fn(n, K):
+    """Low-level implementation of fn(n, x)."""
+    if n < 1:
+        return [K.one, K.zero]
+    m2, m1 = [K.one], [K.one, K.zero]
+    for i in range(2, n+1):
+        m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1), K), m2, K)
+    return dup_lshift(m1, 1, K)
+
+def dup_spherical_bessel_fn_minus(n, K):
+    """Low-level implementation of fn(-n, x)."""
+    m2, m1 = [K.one, K.zero], [K.zero]
+    for i in range(2, n+1):
+        m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(3-2*i), K), m2, K)
+    return m1
+
+def spherical_bessel_fn(n, x=None, polys=False):
+    """
+    Coefficients for the spherical Bessel functions.
+
+    These are only needed in the jn() function.
+
+    The coefficients are calculated from:
+
+    fn(0, z) = 1/z
+    fn(1, z) = 1/z**2
+    fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z)
+
+    Parameters
+    ==========
+
+    n : int
+        Degree of the polynomial.
+    x : optional
+    polys : bool, optional
+        If True, return a Poly, otherwise (default) return an expression.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.orthopolys import spherical_bessel_fn as fn
+    >>> from sympy import Symbol
+    >>> z = Symbol("z")
+    >>> fn(1, z)
+    z**(-2)
+    >>> fn(2, z)
+    -1/z + 3/z**3
+    >>> fn(3, z)
+    -6/z**2 + 15/z**4
+    >>> fn(4, z)
+    1/z - 45/z**3 + 105/z**5
+
+    """
+    if x is None:
+        x = Dummy("x")
+    f = dup_spherical_bessel_fn_minus if n < 0 else dup_spherical_bessel_fn
+    return named_poly(abs(n), f, ZZ, "", (QQ(1)/x,), polys)
diff --git a/shared/package-files/3c/3c883ce6c461a64f594d0cc801065e39ca631233e87d45372dc8707c55c4a80a/test_indexed.cpython-311.pyc b/shared/package-files/3c/3c883ce6c461a64f594d0cc801065e39ca631233e87d45372dc8707c55c4a80a/test_indexed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7773f27bf9ecea5c5abdbb4557ed82ed831cfabf
Binary files /dev/null and b/shared/package-files/3c/3c883ce6c461a64f594d0cc801065e39ca631233e87d45372dc8707c55c4a80a/test_indexed.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c88d914d37363f2acae41d03e583456ddb88e54e2ea44e174e95d1098dc86d6/typing.h b/shared/package-files/3c/3c88d914d37363f2acae41d03e583456ddb88e54e2ea44e174e95d1098dc86d6/typing.h
new file mode 100644
index 0000000000000000000000000000000000000000..84aaf9f702d780b1415b806f4efc7ebfd3d2675d
--- /dev/null
+++ b/shared/package-files/3c/3c88d914d37363f2acae41d03e583456ddb88e54e2ea44e174e95d1098dc86d6/typing.h
@@ -0,0 +1,242 @@
+/*
+    pybind11/typing.h: Convenience wrapper classes for basic Python types
+    with more explicit annotations.
+
+    Copyright (c) 2023 Dustin Spicuzza 
+
+    All rights reserved. Use of this source code is governed by a
+    BSD-style license that can be found in the LICENSE file.
+*/
+
+#pragma once
+
+#include "detail/common.h"
+#include "cast.h"
+#include "pytypes.h"
+
+#include 
+
+PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
+PYBIND11_NAMESPACE_BEGIN(typing)
+
+/*
+    The following types can be used to direct pybind11-generated docstrings
+    to have have more explicit types (e.g., `list[str]` instead of `list`).
+    Just use these in place of existing types.
+
+    There is no additional enforcement of types at runtime.
+*/
+
+template 
+class Tuple : public tuple {
+    using tuple::tuple;
+};
+
+template 
+class Dict : public dict {
+    using dict::dict;
+};
+
+template 
+class List : public list {
+    using list::list;
+};
+
+template 
+class Set : public set {
+    using set::set;
+};
+
+template 
+class Iterable : public iterable {
+    using iterable::iterable;
+};
+
+template 
+class Iterator : public iterator {
+    using iterator::iterator;
+};
+
+template 
+class Callable;
+
+template 
+class Callable : public function {
+    using function::function;
+};
+
+template 
+class Type : public type {
+    using type::type;
+};
+
+template 
+class Union : public object {
+    PYBIND11_OBJECT_DEFAULT(Union, object, PyObject_Type)
+    using object::object;
+};
+
+template 
+class Optional : public object {
+    PYBIND11_OBJECT_DEFAULT(Optional, object, PyObject_Type)
+    using object::object;
+};
+
+template 
+class TypeGuard : public bool_ {
+    using bool_::bool_;
+};
+
+template 
+class TypeIs : public bool_ {
+    using bool_::bool_;
+};
+
+class NoReturn : public none {
+    using none::none;
+};
+
+class Never : public none {
+    using none::none;
+};
+
+#if defined(__cpp_nontype_template_args) && __cpp_nontype_template_args >= 201911L
+#    define PYBIND11_TYPING_H_HAS_STRING_LITERAL
+template 
+struct StringLiteral {
+    constexpr StringLiteral(const char (&str)[N]) { std::copy_n(str, N, name); }
+    char name[N];
+};
+
+template 
+class Literal : public object {
+    PYBIND11_OBJECT_DEFAULT(Literal, object, PyObject_Type)
+};
+
+// Example syntax for creating a TypeVar.
+// typedef typing::TypeVar<"T"> TypeVarT;
+template 
+class TypeVar : public object {
+    PYBIND11_OBJECT_DEFAULT(TypeVar, object, PyObject_Type)
+    using object::object;
+};
+#endif
+
+PYBIND11_NAMESPACE_END(typing)
+
+PYBIND11_NAMESPACE_BEGIN(detail)
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("tuple[")
+                                 + ::pybind11::detail::concat(make_caster::name...)
+                                 + const_name("]");
+};
+
+template <>
+struct handle_type_name> {
+    // PEP 484 specifies this syntax for an empty tuple
+    static constexpr auto name = const_name("tuple[()]");
+};
+
+template 
+struct handle_type_name> {
+    // PEP 484 specifies this syntax for a variable-length tuple
+    static constexpr auto name
+        = const_name("tuple[") + make_caster::name + const_name(", ...]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("dict[") + make_caster::name + const_name(", ")
+                                 + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("list[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("set[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("Iterable[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("Iterator[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    using retval_type = conditional_t::value, void_type, Return>;
+    static constexpr auto name
+        = const_name("Callable[[") + ::pybind11::detail::concat(make_caster::name...)
+          + const_name("], ") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    // PEP 484 specifies this syntax for defining only return types of callables
+    using retval_type = conditional_t::value, void_type, Return>;
+    static constexpr auto name
+        = const_name("Callable[..., ") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("type[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("Union[")
+                                 + ::pybind11::detail::concat(make_caster::name...)
+                                 + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("Optional[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("TypeGuard[") + make_caster::name + const_name("]");
+};
+
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("TypeIs[") + make_caster::name + const_name("]");
+};
+
+template <>
+struct handle_type_name {
+    static constexpr auto name = const_name("NoReturn");
+};
+
+template <>
+struct handle_type_name {
+    static constexpr auto name = const_name("Never");
+};
+
+#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name("Literal[")
+                                 + pybind11::detail::concat(const_name(Literals.name)...)
+                                 + const_name("]");
+};
+template 
+struct handle_type_name> {
+    static constexpr auto name = const_name(StrLit.name);
+};
+#endif
+
+PYBIND11_NAMESPACE_END(detail)
+PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
diff --git a/shared/package-files/3c/3c8a64c36925a225d4875095662b1f20fae509ff9b2a512cf3c920b831513829/quality.cpython-311.pyc b/shared/package-files/3c/3c8a64c36925a225d4875095662b1f20fae509ff9b2a512cf3c920b831513829/quality.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bdd392c435e98180eed1cbdbe852e908d10eecdd
Binary files /dev/null and b/shared/package-files/3c/3c8a64c36925a225d4875095662b1f20fae509ff9b2a512cf3c920b831513829/quality.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c8c355e591005bd029c012062251a181b0435d2e9e510586c89c5a3fdc203dd/_sorting_functions.cpython-311.pyc b/shared/package-files/3c/3c8c355e591005bd029c012062251a181b0435d2e9e510586c89c5a3fdc203dd/_sorting_functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..556c14456fc51cbbdf7e2c0c628b2dce2fa6f9da
Binary files /dev/null and b/shared/package-files/3c/3c8c355e591005bd029c012062251a181b0435d2e9e510586c89c5a3fdc203dd/_sorting_functions.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c8d189ee4758ba79539e96d6620aa1faebab35304a19bbdcb7429c2ed01c4da/copy_sparse_to_sparse.h b/shared/package-files/3c/3c8d189ee4758ba79539e96d6620aa1faebab35304a19bbdcb7429c2ed01c4da/copy_sparse_to_sparse.h
new file mode 100644
index 0000000000000000000000000000000000000000..736821f6ce08059b1d9c767a70e4dfe4794333ac
--- /dev/null
+++ b/shared/package-files/3c/3c8d189ee4758ba79539e96d6620aa1faebab35304a19bbdcb7429c2ed01c4da/copy_sparse_to_sparse.h
@@ -0,0 +1,45 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::copy_sparse_to_sparse_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
+inline at::Tensor & copy_sparse_to_sparse_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false) {
+    return at::_ops::copy_sparse_to_sparse_::call(self, src, non_blocking);
+}
+
+// aten::copy_sparse_to_sparse.out(Tensor self, Tensor src, bool non_blocking=False, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & copy_sparse_to_sparse_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, bool non_blocking=false) {
+    return at::_ops::copy_sparse_to_sparse_out::call(self, src, non_blocking, out);
+}
+// aten::copy_sparse_to_sparse.out(Tensor self, Tensor src, bool non_blocking=False, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & copy_sparse_to_sparse_outf(const at::Tensor & self, const at::Tensor & src, bool non_blocking, at::Tensor & out) {
+    return at::_ops::copy_sparse_to_sparse_out::call(self, src, non_blocking, out);
+}
+
+// aten::copy_sparse_to_sparse(Tensor self, Tensor src, bool non_blocking=False) -> Tensor
+inline at::Tensor copy_sparse_to_sparse(const at::Tensor & self, const at::Tensor & src, bool non_blocking=false) {
+    return at::_ops::copy_sparse_to_sparse::call(self, src, non_blocking);
+}
+
+}
diff --git a/shared/package-files/3c/3c8d4862ec147ca51c6a18a160ff2c954ecf90ac2348a3ec0bc4907216a11eb9/locks.py b/shared/package-files/3c/3c8d4862ec147ca51c6a18a160ff2c954ecf90ac2348a3ec0bc4907216a11eb9/locks.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd41dfd3f474a17b96bf08929923044b5fccf29d
--- /dev/null
+++ b/shared/package-files/3c/3c8d4862ec147ca51c6a18a160ff2c954ecf90ac2348a3ec0bc4907216a11eb9/locks.py
@@ -0,0 +1,587 @@
+"""Synchronization primitives."""
+
+__all__ = ('Lock', 'Event', 'Condition', 'Semaphore',
+           'BoundedSemaphore', 'Barrier')
+
+import collections
+import enum
+
+from . import exceptions
+from . import mixins
+from . import tasks
+
+class _ContextManagerMixin:
+    async def __aenter__(self):
+        await self.acquire()
+        # We have no use for the "as ..."  clause in the with
+        # statement for locks.
+        return None
+
+    async def __aexit__(self, exc_type, exc, tb):
+        self.release()
+
+
+class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
+    """Primitive lock objects.
+
+    A primitive lock is a synchronization primitive that is not owned
+    by a particular coroutine when locked.  A primitive lock is in one
+    of two states, 'locked' or 'unlocked'.
+
+    It is created in the unlocked state.  It has two basic methods,
+    acquire() and release().  When the state is unlocked, acquire()
+    changes the state to locked and returns immediately.  When the
+    state is locked, acquire() blocks until a call to release() in
+    another coroutine changes it to unlocked, then the acquire() call
+    resets it to locked and returns.  The release() method should only
+    be called in the locked state; it changes the state to unlocked
+    and returns immediately.  If an attempt is made to release an
+    unlocked lock, a RuntimeError will be raised.
+
+    When more than one coroutine is blocked in acquire() waiting for
+    the state to turn to unlocked, only one coroutine proceeds when a
+    release() call resets the state to unlocked; first coroutine which
+    is blocked in acquire() is being processed.
+
+    acquire() is a coroutine and should be called with 'await'.
+
+    Locks also support the asynchronous context management protocol.
+    'async with lock' statement should be used.
+
+    Usage:
+
+        lock = Lock()
+        ...
+        await lock.acquire()
+        try:
+            ...
+        finally:
+            lock.release()
+
+    Context manager usage:
+
+        lock = Lock()
+        ...
+        async with lock:
+             ...
+
+    Lock objects can be tested for locking state:
+
+        if not lock.locked():
+           await lock.acquire()
+        else:
+           # lock is acquired
+           ...
+
+    """
+
+    def __init__(self):
+        self._waiters = None
+        self._locked = False
+
+    def __repr__(self):
+        res = super().__repr__()
+        extra = 'locked' if self._locked else 'unlocked'
+        if self._waiters:
+            extra = f'{extra}, waiters:{len(self._waiters)}'
+        return f'<{res[1:-1]} [{extra}]>'
+
+    def locked(self):
+        """Return True if lock is acquired."""
+        return self._locked
+
+    async def acquire(self):
+        """Acquire a lock.
+
+        This method blocks until the lock is unlocked, then sets it to
+        locked and returns True.
+        """
+        if (not self._locked and (self._waiters is None or
+                all(w.cancelled() for w in self._waiters))):
+            self._locked = True
+            return True
+
+        if self._waiters is None:
+            self._waiters = collections.deque()
+        fut = self._get_loop().create_future()
+        self._waiters.append(fut)
+
+        # Finally block should be called before the CancelledError
+        # handling as we don't want CancelledError to call
+        # _wake_up_first() and attempt to wake up itself.
+        try:
+            try:
+                await fut
+            finally:
+                self._waiters.remove(fut)
+        except exceptions.CancelledError:
+            if not self._locked:
+                self._wake_up_first()
+            raise
+
+        self._locked = True
+        return True
+
+    def release(self):
+        """Release a lock.
+
+        When the lock is locked, reset it to unlocked, and return.
+        If any other coroutines are blocked waiting for the lock to become
+        unlocked, allow exactly one of them to proceed.
+
+        When invoked on an unlocked lock, a RuntimeError is raised.
+
+        There is no return value.
+        """
+        if self._locked:
+            self._locked = False
+            self._wake_up_first()
+        else:
+            raise RuntimeError('Lock is not acquired.')
+
+    def _wake_up_first(self):
+        """Wake up the first waiter if it isn't done."""
+        if not self._waiters:
+            return
+        try:
+            fut = next(iter(self._waiters))
+        except StopIteration:
+            return
+
+        # .done() necessarily means that a waiter will wake up later on and
+        # either take the lock, or, if it was cancelled and lock wasn't
+        # taken already, will hit this again and wake up a new waiter.
+        if not fut.done():
+            fut.set_result(True)
+
+
+class Event(mixins._LoopBoundMixin):
+    """Asynchronous equivalent to threading.Event.
+
+    Class implementing event objects. An event manages a flag that can be set
+    to true with the set() method and reset to false with the clear() method.
+    The wait() method blocks until the flag is true. The flag is initially
+    false.
+    """
+
+    def __init__(self):
+        self._waiters = collections.deque()
+        self._value = False
+
+    def __repr__(self):
+        res = super().__repr__()
+        extra = 'set' if self._value else 'unset'
+        if self._waiters:
+            extra = f'{extra}, waiters:{len(self._waiters)}'
+        return f'<{res[1:-1]} [{extra}]>'
+
+    def is_set(self):
+        """Return True if and only if the internal flag is true."""
+        return self._value
+
+    def set(self):
+        """Set the internal flag to true. All coroutines waiting for it to
+        become true are awakened. Coroutine that call wait() once the flag is
+        true will not block at all.
+        """
+        if not self._value:
+            self._value = True
+
+            for fut in self._waiters:
+                if not fut.done():
+                    fut.set_result(True)
+
+    def clear(self):
+        """Reset the internal flag to false. Subsequently, coroutines calling
+        wait() will block until set() is called to set the internal flag
+        to true again."""
+        self._value = False
+
+    async def wait(self):
+        """Block until the internal flag is true.
+
+        If the internal flag is true on entry, return True
+        immediately.  Otherwise, block until another coroutine calls
+        set() to set the flag to true, then return True.
+        """
+        if self._value:
+            return True
+
+        fut = self._get_loop().create_future()
+        self._waiters.append(fut)
+        try:
+            await fut
+            return True
+        finally:
+            self._waiters.remove(fut)
+
+
+class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
+    """Asynchronous equivalent to threading.Condition.
+
+    This class implements condition variable objects. A condition variable
+    allows one or more coroutines to wait until they are notified by another
+    coroutine.
+
+    A new Lock object is created and used as the underlying lock.
+    """
+
+    def __init__(self, lock=None):
+        if lock is None:
+            lock = Lock()
+
+        self._lock = lock
+        # Export the lock's locked(), acquire() and release() methods.
+        self.locked = lock.locked
+        self.acquire = lock.acquire
+        self.release = lock.release
+
+        self._waiters = collections.deque()
+
+    def __repr__(self):
+        res = super().__repr__()
+        extra = 'locked' if self.locked() else 'unlocked'
+        if self._waiters:
+            extra = f'{extra}, waiters:{len(self._waiters)}'
+        return f'<{res[1:-1]} [{extra}]>'
+
+    async def wait(self):
+        """Wait until notified.
+
+        If the calling coroutine has not acquired the lock when this
+        method is called, a RuntimeError is raised.
+
+        This method releases the underlying lock, and then blocks
+        until it is awakened by a notify() or notify_all() call for
+        the same condition variable in another coroutine.  Once
+        awakened, it re-acquires the lock and returns True.
+        """
+        if not self.locked():
+            raise RuntimeError('cannot wait on un-acquired lock')
+
+        self.release()
+        try:
+            fut = self._get_loop().create_future()
+            self._waiters.append(fut)
+            try:
+                await fut
+                return True
+            finally:
+                self._waiters.remove(fut)
+
+        finally:
+            # Must reacquire lock even if wait is cancelled
+            cancelled = False
+            while True:
+                try:
+                    await self.acquire()
+                    break
+                except exceptions.CancelledError:
+                    cancelled = True
+
+            if cancelled:
+                raise exceptions.CancelledError
+
+    async def wait_for(self, predicate):
+        """Wait until a predicate becomes true.
+
+        The predicate should be a callable which result will be
+        interpreted as a boolean value.  The final predicate value is
+        the return value.
+        """
+        result = predicate()
+        while not result:
+            await self.wait()
+            result = predicate()
+        return result
+
+    def notify(self, n=1):
+        """By default, wake up one coroutine waiting on this condition, if any.
+        If the calling coroutine has not acquired the lock when this method
+        is called, a RuntimeError is raised.
+
+        This method wakes up at most n of the coroutines waiting for the
+        condition variable; it is a no-op if no coroutines are waiting.
+
+        Note: an awakened coroutine does not actually return from its
+        wait() call until it can reacquire the lock. Since notify() does
+        not release the lock, its caller should.
+        """
+        if not self.locked():
+            raise RuntimeError('cannot notify on un-acquired lock')
+
+        idx = 0
+        for fut in self._waiters:
+            if idx >= n:
+                break
+
+            if not fut.done():
+                idx += 1
+                fut.set_result(False)
+
+    def notify_all(self):
+        """Wake up all threads waiting on this condition. This method acts
+        like notify(), but wakes up all waiting threads instead of one. If the
+        calling thread has not acquired the lock when this method is called,
+        a RuntimeError is raised.
+        """
+        self.notify(len(self._waiters))
+
+
+class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
+    """A Semaphore implementation.
+
+    A semaphore manages an internal counter which is decremented by each
+    acquire() call and incremented by each release() call. The counter
+    can never go below zero; when acquire() finds that it is zero, it blocks,
+    waiting until some other thread calls release().
+
+    Semaphores also support the context management protocol.
+
+    The optional argument gives the initial value for the internal
+    counter; it defaults to 1. If the value given is less than 0,
+    ValueError is raised.
+    """
+
+    def __init__(self, value=1):
+        if value < 0:
+            raise ValueError("Semaphore initial value must be >= 0")
+        self._waiters = None
+        self._value = value
+
+    def __repr__(self):
+        res = super().__repr__()
+        extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
+        if self._waiters:
+            extra = f'{extra}, waiters:{len(self._waiters)}'
+        return f'<{res[1:-1]} [{extra}]>'
+
+    def locked(self):
+        """Returns True if semaphore cannot be acquired immediately."""
+        return self._value == 0 or (
+            any(not w.cancelled() for w in (self._waiters or ())))
+
+    async def acquire(self):
+        """Acquire a semaphore.
+
+        If the internal counter is larger than zero on entry,
+        decrement it by one and return True immediately.  If it is
+        zero on entry, block, waiting until some other coroutine has
+        called release() to make it larger than 0, and then return
+        True.
+        """
+        if not self.locked():
+            self._value -= 1
+            return True
+
+        if self._waiters is None:
+            self._waiters = collections.deque()
+        fut = self._get_loop().create_future()
+        self._waiters.append(fut)
+
+        # Finally block should be called before the CancelledError
+        # handling as we don't want CancelledError to call
+        # _wake_up_first() and attempt to wake up itself.
+        try:
+            try:
+                await fut
+            finally:
+                self._waiters.remove(fut)
+        except exceptions.CancelledError:
+            if not fut.cancelled():
+                self._value += 1
+                self._wake_up_next()
+            raise
+
+        if self._value > 0:
+            self._wake_up_next()
+        return True
+
+    def release(self):
+        """Release a semaphore, incrementing the internal counter by one.
+
+        When it was zero on entry and another coroutine is waiting for it to
+        become larger than zero again, wake up that coroutine.
+        """
+        self._value += 1
+        self._wake_up_next()
+
+    def _wake_up_next(self):
+        """Wake up the first waiter that isn't done."""
+        if not self._waiters:
+            return
+
+        for fut in self._waiters:
+            if not fut.done():
+                self._value -= 1
+                fut.set_result(True)
+                return
+
+
+class BoundedSemaphore(Semaphore):
+    """A bounded semaphore implementation.
+
+    This raises ValueError in release() if it would increase the value
+    above the initial value.
+    """
+
+    def __init__(self, value=1):
+        self._bound_value = value
+        super().__init__(value)
+
+    def release(self):
+        if self._value >= self._bound_value:
+            raise ValueError('BoundedSemaphore released too many times')
+        super().release()
+
+
+
+class _BarrierState(enum.Enum):
+    FILLING = 'filling'
+    DRAINING = 'draining'
+    RESETTING = 'resetting'
+    BROKEN = 'broken'
+
+
+class Barrier(mixins._LoopBoundMixin):
+    """Asyncio equivalent to threading.Barrier
+
+    Implements a Barrier primitive.
+    Useful for synchronizing a fixed number of tasks at known synchronization
+    points. Tasks block on 'wait()' and are simultaneously awoken once they
+    have all made their call.
+    """
+
+    def __init__(self, parties):
+        """Create a barrier, initialised to 'parties' tasks."""
+        if parties < 1:
+            raise ValueError('parties must be > 0')
+
+        self._cond = Condition() # notify all tasks when state changes
+
+        self._parties = parties
+        self._state = _BarrierState.FILLING
+        self._count = 0       # count tasks in Barrier
+
+    def __repr__(self):
+        res = super().__repr__()
+        extra = f'{self._state.value}'
+        if not self.broken:
+            extra += f', waiters:{self.n_waiting}/{self.parties}'
+        return f'<{res[1:-1]} [{extra}]>'
+
+    async def __aenter__(self):
+        # wait for the barrier reaches the parties number
+        # when start draining release and return index of waited task
+        return await self.wait()
+
+    async def __aexit__(self, *args):
+        pass
+
+    async def wait(self):
+        """Wait for the barrier.
+
+        When the specified number of tasks have started waiting, they are all
+        simultaneously awoken.
+        Returns an unique and individual index number from 0 to 'parties-1'.
+        """
+        async with self._cond:
+            await self._block() # Block while the barrier drains or resets.
+            try:
+                index = self._count
+                self._count += 1
+                if index + 1 == self._parties:
+                    # We release the barrier
+                    await self._release()
+                else:
+                    await self._wait()
+                return index
+            finally:
+                self._count -= 1
+                # Wake up any tasks waiting for barrier to drain.
+                self._exit()
+
+    async def _block(self):
+        # Block until the barrier is ready for us,
+        # or raise an exception if it is broken.
+        #
+        # It is draining or resetting, wait until done
+        # unless a CancelledError occurs
+        await self._cond.wait_for(
+            lambda: self._state not in (
+                _BarrierState.DRAINING, _BarrierState.RESETTING
+            )
+        )
+
+        # see if the barrier is in a broken state
+        if self._state is _BarrierState.BROKEN:
+            raise exceptions.BrokenBarrierError("Barrier aborted")
+
+    async def _release(self):
+        # Release the tasks waiting in the barrier.
+
+        # Enter draining state.
+        # Next waiting tasks will be blocked until the end of draining.
+        self._state = _BarrierState.DRAINING
+        self._cond.notify_all()
+
+    async def _wait(self):
+        # Wait in the barrier until we are released. Raise an exception
+        # if the barrier is reset or broken.
+
+        # wait for end of filling
+        # unless a CancelledError occurs
+        await self._cond.wait_for(lambda: self._state is not _BarrierState.FILLING)
+
+        if self._state in (_BarrierState.BROKEN, _BarrierState.RESETTING):
+            raise exceptions.BrokenBarrierError("Abort or reset of barrier")
+
+    def _exit(self):
+        # If we are the last tasks to exit the barrier, signal any tasks
+        # waiting for the barrier to drain.
+        if self._count == 0:
+            if self._state in (_BarrierState.RESETTING, _BarrierState.DRAINING):
+                self._state = _BarrierState.FILLING
+            self._cond.notify_all()
+
+    async def reset(self):
+        """Reset the barrier to the initial state.
+
+        Any tasks currently waiting will get the BrokenBarrier exception
+        raised.
+        """
+        async with self._cond:
+            if self._count > 0:
+                if self._state is not _BarrierState.RESETTING:
+                    #reset the barrier, waking up tasks
+                    self._state = _BarrierState.RESETTING
+            else:
+                self._state = _BarrierState.FILLING
+            self._cond.notify_all()
+
+    async def abort(self):
+        """Place the barrier into a 'broken' state.
+
+        Useful in case of error.  Any currently waiting tasks and tasks
+        attempting to 'wait()' will have BrokenBarrierError raised.
+        """
+        async with self._cond:
+            self._state = _BarrierState.BROKEN
+            self._cond.notify_all()
+
+    @property
+    def parties(self):
+        """Return the number of tasks required to trip the barrier."""
+        return self._parties
+
+    @property
+    def n_waiting(self):
+        """Return the number of tasks currently waiting at the barrier."""
+        if self._state is _BarrierState.FILLING:
+            return self._count
+        return 0
+
+    @property
+    def broken(self):
+        """Return True if the barrier is in a broken state."""
+        return self._state is _BarrierState.BROKEN
diff --git a/shared/package-files/3c/3c8da7136a3aa8d04707be72bfc3559caa05b81bd4536d0a3a7db5e441ce42f1/div_meta.h b/shared/package-files/3c/3c8da7136a3aa8d04707be72bfc3559caa05b81bd4536d0a3a7db5e441ce42f1/div_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..0888b13f7fa482fb0a65d881ed7548f64e03cf86
--- /dev/null
+++ b/shared/package-files/3c/3c8da7136a3aa8d04707be72bfc3559caa05b81bd4536d0a3a7db5e441ce42f1/div_meta.h
@@ -0,0 +1,32 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_div_Tensor : public TensorIteratorBase {
+    
+    
+    void meta(const at::Tensor & self, const at::Tensor & other);
+};
+struct TORCH_API structured_div_Tensor_mode : public TensorIteratorBase {
+    
+    
+    void meta(const at::Tensor & self, const at::Tensor & other, ::std::optional rounding_mode);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/3c/3c958ab416950b8c0b0c6d25a41d5e5b836d238cef12da20e7fe3ec26083b8a4/__init__.cpython-311.pyc b/shared/package-files/3c/3c958ab416950b8c0b0c6d25a41d5e5b836d238cef12da20e7fe3ec26083b8a4/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..142d27a085d3b6db94da8bb4ffbe7298caf9b751
Binary files /dev/null and b/shared/package-files/3c/3c958ab416950b8c0b0c6d25a41d5e5b836d238cef12da20e7fe3ec26083b8a4/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3c979d632ddc5c47f39f738ec8deb17b09aa9d7be080f2e9b72b73c84b5b1afc/op_registry.h b/shared/package-files/3c/3c979d632ddc5c47f39f738ec8deb17b09aa9d7be080f2e9b72b73c84b5b1afc/op_registry.h
new file mode 100644
index 0000000000000000000000000000000000000000..85d9ac8c7d2872e9d373c723cc4f79a9f542b6aa
--- /dev/null
+++ b/shared/package-files/3c/3c979d632ddc5c47f39f738ec8deb17b09aa9d7be080f2e9b72b73c84b5b1afc/op_registry.h
@@ -0,0 +1,29 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace torch::jit {
+// Moved from shape_analysis.cpp
+
+// Requirements:
+//   dims           : preserved from the first argument
+//   scalar type    : preserved from the first argument (doesn't have to
+//                    match other arguments)
+//   device         : always matching and preserved
+//   tensor inputs  : *
+//   tensor outputs : 1
+// NB: those ops (with slight adjustments) are good candidates for restarts.
+//     Knowing the type and device of weights or biases is usually enough to
+//     infer the output type.
+std::shared_ptr nn_ops_first_input_preserving();
+
+// Requirements:
+//   dims           : Changed from first argument
+//   scalar type    : preserved from the first argument
+//   device         : always matching and preserved
+//   tensor inputs  : 1
+//   tensor outputs : 1
+std::shared_ptr ops_one_tensor_in_shape_transform();
+} // namespace torch::jit
diff --git a/shared/package-files/3c/3c9c453bb883492b672fcc49692f7e85c79de9bea1e241a8ab3f2c6d255ef212/to_dense_backward.h b/shared/package-files/3c/3c9c453bb883492b672fcc49692f7e85c79de9bea1e241a8ab3f2c6d255ef212/to_dense_backward.h
new file mode 100644
index 0000000000000000000000000000000000000000..747b399250b9bba1ba67fa04cf8ef4f1eaaeeea3
--- /dev/null
+++ b/shared/package-files/3c/3c9c453bb883492b672fcc49692f7e85c79de9bea1e241a8ab3f2c6d255ef212/to_dense_backward.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::to_dense_backward(Tensor grad, Tensor input, bool? masked_grad=None) -> Tensor
+inline at::Tensor to_dense_backward(const at::Tensor & grad, const at::Tensor & input, ::std::optional masked_grad=::std::nullopt) {
+    return at::_ops::to_dense_backward::call(grad, input, masked_grad);
+}
+
+}
diff --git a/shared/package-files/3c/3c9eb6e7249a5ff29505fd9d1b285457de4e292771ae0faf62838afa4f1f4a9f/utils.py b/shared/package-files/3c/3c9eb6e7249a5ff29505fd9d1b285457de4e292771ae0faf62838afa4f1f4a9f/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0870a077a4f4b2ad87052b23487af536f149f316
--- /dev/null
+++ b/shared/package-files/3c/3c9eb6e7249a5ff29505fd9d1b285457de4e292771ae0faf62838afa4f1f4a9f/utils.py
@@ -0,0 +1,653 @@
+# mypy: allow-untyped-defs
+import functools
+from contextlib import contextmanager, ExitStack
+from dataclasses import dataclass
+from typing import Any, Callable, Optional, Union
+
+import torch
+import torch.fx.traceback as fx_traceback
+import torch.utils._pytree as pytree
+from torch._guards import detect_fake_mode
+from torch._ops import OperatorBase
+from torch._subclasses.fake_tensor import FakeTensor
+from torch.fx.experimental.proxy_tensor import (
+    _temp_remove_metadata_torch_function_mode,
+    disable_proxy_modes_tracing,
+    make_fx,
+)
+from torch.fx.passes.shape_prop import TensorMetadata
+from torch.multiprocessing.reductions import StorageWeakRef
+
+
+@dataclass
+class UnsupportedAliasMutationException(RuntimeError):
+    reason: str
+
+
+def autograd_not_implemented_inner(
+    operator: OperatorBase, delayed_error: bool, *args: Any, **kwargs: Any
+) -> Any:
+    """If autograd is enabled and any of the arguments require grad this will either
+    raise an error or return a DelayedError depending on the value of delayed.
+
+    Args:
+        operator: The Operator to call with the *args and **kwargs with
+        op_name: The name of the Operator
+        delayed_error: If True, return a DelayedError instead of raising an error
+        args: The flattened operands to the Operator
+        kwargs: The keyword arguments to the Operator
+
+    Raises:
+        RuntimeError: If autograd is enabled and any of the arguments to the Operator
+    """
+    with torch._C._AutoDispatchBelowAutograd():
+        result = operator(*args, **kwargs)
+        flat_operands = pytree.arg_tree_leaves(*args)
+        if torch.is_grad_enabled() and any(
+            f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor)
+        ):
+            if delayed_error:
+                err_fn = torch._C._functions.DelayedError(
+                    f"Autograd not implemented for {str(operator)}",
+                    1,
+                )
+
+                def fake_requires_grad(tensor):
+                    if torch.is_floating_point(tensor) or torch.is_complex(tensor):
+                        tensor = tensor.detach()
+                        tensor.requires_grad = True
+                    return tensor
+
+                return pytree.tree_map_only(
+                    torch.Tensor, lambda x: err_fn(fake_requires_grad(x)), result
+                )
+            else:
+                raise RuntimeError(f"Autograd not implemented for {str(operator)}")
+        return result
+
+
+def autograd_not_implemented(op: OperatorBase, deferred_error: bool) -> Callable:
+    def inner(*args, **kwargs):
+        return autograd_not_implemented_inner(op, deferred_error, *args, **kwargs)
+
+    return inner
+
+
+def _maybe_run_with_interpreter(fn):
+    maybe_interpreted_fn = fn
+    if isinstance(fn, torch.fx.GraphModule) and fx_traceback.has_preserved_node_meta():
+        # Running graph with interpreter is needed for propagating the stack_trace
+        def graph_with_interpreter(*args):
+            with fx_traceback.preserve_node_meta():
+                return torch.fx.Interpreter(fn).run(*args)
+
+        maybe_interpreted_fn = graph_with_interpreter
+    return maybe_interpreted_fn
+
+
+def _maybe_compile_and_run_fn(fn, *args):
+    if not torch._dynamo.is_compiling():
+        from torch._dynamo.backends.debugging import (
+            make_eager_backend_with_torch_function_mode,
+        )
+
+        with _set_compilation_env(), torch._dynamo.utils.disable_cache_limit():
+            with _temp_remove_metadata_torch_function_mode() as metadata_mode:
+                if metadata_mode:
+                    backend = make_eager_backend_with_torch_function_mode(metadata_mode)
+                else:
+                    backend = "eager"
+                return torch.compile(fn, backend=backend, fullgraph=True)(*args)
+    else:
+        return fn(*args)
+
+
+def reenter_make_fx(fn):
+    from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER
+
+    @functools.wraps(fn)
+    def wrapped(*args):
+        assert (
+            _CURRENT_MAKE_FX_TRACER is not None
+        ), "Cannot reenter make_fx when we're not under a make_fx tracing session"
+        return _CURRENT_MAKE_FX_TRACER.trace_subgraph(
+            _maybe_run_with_interpreter(fn), *args
+        )
+
+    return wrapped
+
+
+def _maybe_reenter_make_fx(fn):
+    from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER
+
+    if _CURRENT_MAKE_FX_TRACER is not None:
+        return reenter_make_fx(fn)
+    else:
+
+        def _maybe_make_fx_with_fake_mode(fn):
+            @functools.wraps(fn)
+            def wrapped(*args):
+                from torch._guards import detect_fake_mode
+
+                fake_mode = detect_fake_mode(args)
+                if fake_mode is None:
+                    # we creaeta a fake_mode here to make sure we could
+                    # trace the graph with data-dependent calls e.g. .item()
+                    return make_fx(fn, tracing_mode="fake")(*args)
+                # Tracing with real if all inputs have been fakfied
+                return make_fx(fn)(*args)
+
+            return wrapped
+
+        return _maybe_make_fx_with_fake_mode(fn)
+
+
+@contextmanager
+def _set_compilation_env():
+    _old_is_tracing = torch.fx._symbolic_trace._is_fx_tracing_flag
+    _old_allow_empty_graphs = torch._dynamo.config.allow_empty_graphs
+    # The issue is tracked in https://github.com/pytorch/pytorch/issues/144360: when dynamo finds
+    # the top-level frame produces no graph, the default behavior is to fallback to eager.
+    # Then when it encounters an inner function, it will try to trace that function again, which is unnecessary.
+    # For while_loop, during inspecting the inner call, we trace into the python dispathcer
+    # logic, which is not tracable as of today. So the proper fix can be either 1. allow dispatch
+    # logic to be dynamo tracable or 2. fixing https://github.com/pytorch/pytorch/issues/144360.
+    # but it exposes some bugs in existing tests so we have to have a temporary flag to control
+    # the behavior, which allows dynamo to store an empty graph for a frame without falling back to eager
+    try:
+        # We need to turn off the is_fx_tracing_flag. Remove this flag check from dyanmo
+        # once we are confident fx tracing works with dynamo.
+        torch.fx._symbolic_trace._is_fx_tracing_flag = False
+        torch._dynamo.config.allow_empty_graphs = True
+        yield
+    finally:
+        torch.fx._symbolic_trace._is_fx_tracing_flag = _old_is_tracing
+        torch._dynamo.config.allow_empty_graphs = _old_allow_empty_graphs
+
+
+def _detect_input_mutation(gm: torch.fx.GraphModule) -> bool:
+    example_inputs = [
+        ph.meta.get("val", None) for ph in gm.graph.find_nodes(op="placeholder")
+    ]
+    inp_mutation, _, _, _ = check_input_alias_and_mutation(gm, example_inputs)
+    if len(inp_mutation) > 0:
+        return True
+
+    for _, module in gm.named_children():
+        if isinstance(module, torch.fx.GraphModule):
+            if _detect_input_mutation(module):
+                return True
+
+    return False
+
+
+def _detect_input_alias(gm: torch.fx.GraphModule) -> bool:
+    example_inputs = [
+        ph.meta.get("val", None) for ph in gm.graph.find_nodes(op="placeholder")
+    ]
+    _, inp_inp_alias_map, inp_out_alias_map, _ = check_input_alias_and_mutation(
+        gm, example_inputs
+    )
+    if len(inp_out_alias_map) > 0 or len(inp_inp_alias_map) > 0:
+        return True
+    return False
+
+
+# The invariant here is that we always trace the branch with fake tensor
+def _maybe_fake_tracing(fn, inputs: list[Any], pre_dispatch):
+    fake_mode = detect_fake_mode(inputs)
+    tracing_mode = "real"
+    if fake_mode is None:
+        tracing_mode = "fake"
+
+    # Note: we need to turn off proxy tensor mode to avoid tracing infra
+    # code that happens in make_fx e.g. we now call as_strided when wrapping tensor
+    # as fake tensor.
+    with disable_proxy_modes_tracing():
+        return make_fx(
+            fn,
+            tracing_mode=tracing_mode,
+            pre_dispatch=pre_dispatch,
+            _error_on_data_dependent_ops=False,
+        )(*inputs)
+
+
+def has_potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False):
+    try:
+        gm = _maybe_fake_tracing(gm, inputs, pre_dispatch)
+    except UnsupportedAliasMutationException:
+        # this can happen when nested cond_op is
+        # functionalized
+        return True
+    except Exception as e:
+        raise e
+
+    return _detect_input_mutation(gm) or _detect_input_alias(gm)
+
+
+def _has_potential_branch_input_mutation(branch, inputs, pre_dispatch=False):
+    """
+    Dispatch-trace the branch with inputs and check if
+    producing graph has mutable op on the input. This is
+    bit restrictive as the branch must be traceable.
+    """
+    try:
+        gm = _maybe_fake_tracing(branch, inputs, pre_dispatch)
+    except UnsupportedAliasMutationException:
+        # this can happen when nested cond_op is
+        # functionalized
+        return True
+    except Exception as e:
+        raise e
+
+    return _detect_input_mutation(gm)
+
+
+def _has_potential_branch_input_alias(branch, inputs, pre_dispatch=False):
+    """
+    Dispatch-trace the branch with inputs and check if
+    producing graph has output aliasing the branch input. This is
+    bit restrictive as the branch must be traceable.
+    """
+    try:
+        gm = _maybe_fake_tracing(branch, inputs, pre_dispatch)
+    except UnsupportedAliasMutationException:
+        # this can happen when nested cond_op is
+        # functionalized
+        return True
+    except Exception as e:
+        raise e
+
+    return _detect_input_alias(gm)
+
+
+def unique_graph_id(proxy_mode, prefix):
+    """Returns a unique name and id for a graph to be added to a proxy_mode tracer"""
+    # There are probably better ways - I know that create_arg has some self incrementing name
+    # magic to it, but since we explicitly have to get the name for register_module,
+    # I was not sure how to do that. This kinda simulates it.
+    next_name = None
+    i = 0
+    while not next_name:
+        candidate = f"{prefix}_{i}"
+        if hasattr(proxy_mode.tracer.root, candidate):
+            i += 1
+        else:
+            next_name = candidate
+    return i, next_name
+
+
+def _from_fun(t):
+    from torch._functorch.aot_autograd import from_fun
+    from torch._subclasses.functional_tensor import FunctionalTensor
+
+    if isinstance(t, torch.Tensor):
+        if t.dtype != torch.bool:
+            return torch.empty_strided(
+                t.size(),
+                t.stride(),
+                dtype=t.dtype,
+                requires_grad=t.requires_grad,
+                device=t.device,
+            )
+        else:
+            # clone of a functional tensor produces a functional tensor
+            # but we want to avoid it so we clone a non-functional version
+            maybe_unfunc_t = t
+            if isinstance(t, FunctionalTensor):
+                torch._sync(t)
+                maybe_unfunc_t = from_fun(t)
+            elif torch._is_functional_tensor(t):
+                # need to handle both types of functionalization here:
+                # these are the tensors that came from the user,
+                # which could be either FunctionalTensorWrapper or FunctionalTensor
+                torch._sync(t)
+                maybe_unfunc_t = torch._from_functional_tensor(t)
+            return maybe_unfunc_t.clone()
+    return t
+
+
+def clone_outputs_aliasing_inputs(args):
+    input_storage = {
+        StorageWeakRef(arg._typed_storage())
+        for arg in args
+        if isinstance(arg, torch.Tensor)
+    }
+
+    def maybe_clone(t):
+        if (
+            isinstance(t, torch.Tensor)
+            and StorageWeakRef(t._typed_storage()) in input_storage
+        ):
+            return t.clone()
+        return t
+
+    return maybe_clone
+
+
+def prepare_fw_with_masks(fn):
+    def fw_with_masks(*args):
+        fw_out = fn(*args)
+        return fw_out, [
+            True if isinstance(ret, torch.Tensor) and ret.requires_grad else False
+            for ret in fw_out
+        ]
+
+    return fw_with_masks
+
+
+# This function replaces None gradients with all-zero gradients.
+# `None` gradients are problematic for CUDA graphs. Those gradients are
+# replaced with an all-zero tensor for better optimization
+def unmask_none_gradients(grads, operands):
+    allowed_types = (torch.Tensor, int, torch.SymInt)
+    assert all(
+        isinstance(o, allowed_types) for o in operands
+    ), f"operands can only be of {allowed_types} but got {[type(o) for o in operands]}"
+
+    unmasked_grads = []
+    for g, o in zip(grads, operands):
+        if g is not None:
+            unmasked_grads.append(g)
+        else:
+            # In case the operand is an int or a torch.SymInt, return None
+            # This can happen for lifted_arguments. E.g., the shapes of a dynamic tensor are lifted and passed
+            # as additional arguments
+            unmasked_grads.append(
+                torch.zeros_like(o) if isinstance(o, torch.Tensor) else None
+            )
+
+    return unmasked_grads
+
+
+def _maybe_fake_prop_ignore_unbacked(fn, args):
+    with ExitStack() as ctx_stack:
+        if (fake_mode := detect_fake_mode(args)) is not None:
+            ctx_stack.enter_context(fake_mode)
+            if fake_mode.shape_env is not None:
+                ctx_stack.enter_context(
+                    fake_mode.shape_env.ignore_fresh_unbacked_symbols()
+                )
+        return fn(*args)
+
+
+# TODO: The parameter use_output_and_grad_bw is required because some operations
+# that utilize this function, such as the while_loop, may require (grad, fwd_outputs)
+def create_fw_bw_graph(fn, use_output_and_grad_bw, fw_inputs, fw_outputs):
+    from torch._functorch.aot_autograd import AOTConfig, create_joint
+
+    # Note:[HOP create fw_bw graph] We create "clean" environments for make_fx by suspending all dispatch keys
+    # between Autograd and Python key. Currently, we only suspend functionalization but more can be
+    # added when required. Will encounter two problems if we don't suspend functionalization:
+    #
+    # 1. make_fx fails to capture operations on input: the inputs are wrapped as _to_functional_tensor_wrapper,
+    # but they will be unwrapped before entering ProxyTorchDispatchMode as part of the dispatching.
+    # However, it's the outside wrapper that tracer creates proxies for. This casuses tracer fail to
+    # fetch the proxy for the inputs and fail to capture any operations on them.
+    #
+    # 2. make_fx fails to capture output: the outputs after ProxyTorchDispatchMode are further
+    # wrapped as FunctionalTensorWrapper in Functionalize key after return. However, the tracer
+    # only associates the inner tensor with proxy in ProxyTorchDispatchMode. Therefore,
+    # when creating the output node, it fails to associate the wrapped tensor with its proxy.
+    # Instead, it will create _tensor_constant as output.
+
+    dummy_aot_config = AOTConfig(
+        fw_compiler=None,  # type: ignore[arg-type]
+        bw_compiler=None,  # type: ignore[arg-type]
+        partition_fn=None,  # type: ignore[arg-type]
+        decompositions={},
+        num_params_buffers=0,
+        aot_id=0,
+        keep_inference_input_mutations=False,
+    )
+
+    example_grad = [_from_fun(out) for out in fw_outputs]
+    num_grads = len(example_grad)
+    fw_graph = _maybe_reenter_make_fx(fn)(*fw_inputs)
+
+    def joint_fn(*joint_operands_grads):
+        if use_output_and_grad_bw:
+            grads = joint_operands_grads[0]
+            inputs = joint_operands_grads[1][-1:]
+        else:
+            grads = joint_operands_grads[:num_grads]
+            inputs = joint_operands_grads[num_grads:]
+
+        joint = create_joint(prepare_fw_with_masks(fn), aot_config=dummy_aot_config)
+        _, grads = joint(
+            list(inputs),
+            [grad for grad in grads if grad is not None and grad.requires_grad],
+        )
+
+        # Unmask None gradients to all-zero gradients
+        unmasked_grads = unmask_none_gradients(grads, inputs)
+
+        # In order to keep map functional for backward graph,
+        # we clone outputs that are aliasing inputs
+        maybe_clone = clone_outputs_aliasing_inputs(joint_operands_grads)
+
+        return pytree.tree_map(maybe_clone, unmasked_grads)
+
+    if use_output_and_grad_bw:
+        example_xs_out = list(fw_inputs) + list(fw_outputs)
+        joint_graph = _maybe_reenter_make_fx(joint_fn)(
+            (list(example_grad), list(example_xs_out))
+        )
+    else:
+        example_xs_out = list(fw_inputs)
+        joint_graph = _maybe_reenter_make_fx(joint_fn)(
+            *(list(example_grad) + list(example_xs_out))
+        )
+
+    return fw_graph, joint_graph
+
+
+def _unstack_pytree(xs):
+    flat_xs, inspec = pytree.tree_flatten(xs)
+    if not all(isinstance(xs, torch.Tensor) for xs in flat_xs):
+        raise RuntimeError(f"Leaves of xs must be Tensor {flat_xs}")
+
+    if not all(xs.shape[0] == flat_xs[0].shape[0] for xs in flat_xs):
+        raise RuntimeError(
+            f"Leaves of xs must have same leading dimension size {[xs.shape for xs in flat_xs]}"
+        )
+
+    a = zip(*flat_xs)
+
+    pytrees = [pytree.tree_unflatten(tuple, inspec) for tuple in a]
+    return pytrees
+
+
+def _stack_pytree(pytrees):
+    flat_out = []
+    out_spec = None
+    for pt in pytrees:
+        flat_pt, out_spec = pytree.tree_flatten(pt)
+        flat_out.append(flat_pt)
+    assert out_spec is not None
+    b = zip(*flat_out)
+    stacked_out = []
+    for leaves in b:
+        if all(isinstance(leaf, torch.Tensor) for leaf in leaves):
+            stacked_out.append(torch.stack(leaves))
+        elif all(leaf is None for leaf in leaves):
+            # Backward graph can return None output when forward inputs doesn't require grad.
+            # When we eagerly execute backward graph, we need to call _stack_pytree on its output,
+            # therefore we need to deal with None output.
+            stacked_out.append(None)  # type: ignore[arg-type]
+        else:
+            raise RuntimeError(f"Cannot stack {leaves}.")
+    return pytree.tree_unflatten(stacked_out, out_spec)
+
+
+# We cannot call save_for_backward for symints. This helper function
+# can be used to save symints as direct attributes of ctx in autograd.Function.
+#
+# For example, if args = (x, y, s0, z, s1),
+# save_tensors_and_symints_for_backward will partition the args into two lists, and a bookkeeping list pos:
+#   partitioned_args[0] = (x, y, z)
+#   partitioned_args[1] = (s0, s1)
+#   pos = (0, 0, 1, 0, 1)
+# pos list keeps track of which partition the args
+# is partitioned into in order to recover it in saved_tensors_and_symints.
+#
+# In saved_tensors_and_symints, we can recover the original args by:
+# iterating over the pos list and pop one item from the front of paritioned_args[pos[i]].
+# We use t_idx and s_idx to keep track of the next index of the item we are going to pop for the two lists.
+def save_tensors_and_symints_for_backward(ctx, args):
+    assert all(
+        isinstance(arg, (torch.Tensor, torch.SymInt, int, type(None))) for arg in args
+    ), args
+    partitioned_args: list[Any] = [[], []]
+    pos = []
+    for arg in args:
+        idx = 0 if isinstance(arg, torch.Tensor) else 1
+        partitioned_args[idx].append(arg)
+        pos.append(idx)
+
+    assert not hasattr(ctx, "sym_int_args"), "ctx already has sym_int_args attribute."
+    assert not hasattr(ctx, "pos"), "ctx already has pos attribute."
+    ctx.save_for_backward(*partitioned_args[0])
+    ctx.sym_int_args = partitioned_args[1]
+    ctx.pos = pos
+
+
+def saved_tensors_and_symints(ctx):
+    args = []
+    t_idx = 0
+    s_idx = 0
+    saved_tensors = ctx.saved_tensors
+    for p in ctx.pos:
+        if p == 0:
+            args.append(saved_tensors[t_idx])
+            t_idx += 1
+        else:
+            args.append(ctx.sym_int_args[s_idx])
+            s_idx += 1
+    assert t_idx + s_idx == len(ctx.pos)
+    return tuple(args)
+
+
+def get_dummy_aot_autograd_config():
+    from torch._functorch.aot_autograd import AOTConfig
+
+    return AOTConfig(
+        fw_compiler=None,  # type: ignore[arg-type]
+        bw_compiler=None,  # type: ignore[arg-type]
+        partition_fn=None,  # type: ignore[arg-type]
+        decompositions={},
+        num_params_buffers=0,
+        aot_id=0,
+        keep_inference_input_mutations=False,
+    )
+
+
+# Slices off the first element of a given dimension
+def first_slice_copy(t: torch.Tensor, dim: int = 0) -> torch.Tensor:
+    return torch.select_copy(t, dim, 0)
+
+
+# Reports the difference between meta of two tensors in a string
+def diff_tensor_meta(
+    meta1: TensorMetadata, meta2: TensorMetadata, check_grad=True
+) -> list[str]:
+    from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode
+
+    pair_diffs = []
+    for meta_name in TensorMetadata._fields:
+        if not check_grad and meta_name == "requires_grad":
+            continue
+        val1 = getattr(meta1, meta_name)
+        val2 = getattr(meta2, meta_name)
+        try:
+            if val1 != val2:
+                pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'")
+        except GuardOnDataDependentSymNode as _:
+            pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'")
+            continue
+    return pair_diffs
+
+
+# Note [lifted arg types in hop]
+# For dynamoed hops, we automatically lift the free symbols in tensors as arguments.
+# This has implications for the types of lifted args for different dispatch keys:
+#   1. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd need to support torch.Symint
+#      lifted args because it's on the path of torch.compile(dynamic=True).
+#   2. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd, CompositeExplicitAutograd need
+#      to support int arguments. In the eager run case, we re-trace the subgraph in AutogradKey, so inner
+#      hops may receive int inputs from the shape of outer tensor inputs.
+#      However, CompositeExplicitAutograd won't receive SymInt inputs because it only accepts real tensor inputs.
+def validate_subgraph_args_types(lifted_args: Union[tuple[Any, ...], list[Any]]):
+    allowed_types = (torch.Tensor, int, torch.SymInt)
+    assert all(
+        isinstance(arg, (torch.Tensor, int, torch.SymInt)) for arg in lifted_args
+    ), f"{lifted_args} can only be of {allowed_types} but got {tuple(type(arg) for arg in lifted_args)}"
+
+
+def check_input_alias_and_mutation(
+    gm: torch.fx.GraphModule,
+    fake_args: list[FakeTensor],
+) -> tuple[list[int], dict[int, int], dict[int, int], dict[int, int]]:
+    with disable_proxy_modes_tracing():
+        """This function returns mutated inputs, inp-inp alias, inp-out alias, out-out alias
+        in the graph module gm. It checks whether input tensor versions have
+        changed after run gm once to detect mutation and checks tensor storage
+        to detect alias.
+        """
+        from torch._prims_common import clone_preserve_strides
+
+        def _tensor_version(t) -> Optional[int]:
+            if isinstance(t, torch.Tensor):
+                assert isinstance(t, FakeTensor), "Only fake tensor is allowed"
+                return t._version
+            return None
+
+        def _tensor_storage(t) -> StorageWeakRef:
+            return StorageWeakRef(t._typed_storage())
+
+        # Clone the fake args to avoid mutating the original fake args
+        with ExitStack() as ctx_stack:
+            # We need to temporarily turn inference_mode off because
+            # under inference mode, tensor version counter is not tracked.
+            ctx_stack.enter_context(torch.inference_mode(False))
+            cloned = [
+                clone_preserve_strides(arg) if isinstance(arg, torch.Tensor) else arg
+                for arg in fake_args
+            ]
+            before = [_tensor_version(arg) for arg in cloned]
+            outputs = _maybe_fake_prop_ignore_unbacked(gm, cloned)
+            outputs = [outputs] if not isinstance(outputs, (list, tuple)) else outputs
+            after = [_tensor_version(arg) for arg in cloned]
+            mutated_inputs = [
+                i for i, (v1, v2) in enumerate(zip(before, after)) if v1 != v2
+            ]
+        # We need to analyze the original fake_args to detect
+        # inp-inp alias.
+        inp_storage_map = {
+            _tensor_storage(inp): i
+            for i, inp in enumerate(fake_args)
+            if isinstance(inp, torch.Tensor)
+        }
+        inp_inp_alias_map = {
+            i: inp_storage_map[_tensor_storage(inp)]
+            for i, inp in enumerate(fake_args)
+            if isinstance(inp, torch.Tensor)
+            and inp_storage_map[_tensor_storage(inp)] != i
+        }
+        out_storage_map = {
+            _tensor_storage(out): i
+            for i, out in enumerate(outputs)
+            if isinstance(out, torch.Tensor)
+        }
+        out_out_alias_map = {
+            i: out_storage_map[_tensor_storage(out)]
+            for i, out in enumerate(outputs)
+            if isinstance(out, torch.Tensor)
+            and out_storage_map[_tensor_storage(out)] != i
+        }
+        inp_out_alias_map = {
+            i: out_storage_map[_tensor_storage(inp)]
+            for i, inp in enumerate(cloned)
+            if isinstance(inp, torch.Tensor) and _tensor_storage(inp) in out_storage_map
+        }
+        return mutated_inputs, inp_inp_alias_map, inp_out_alias_map, out_out_alias_map
diff --git a/shared/package-files/3c/3c9fbf52906a1d7b35ff6f50eb4c6584ae09d26db25fe1c8bd6fc0ba49ecafdf/test_object.py b/shared/package-files/3c/3c9fbf52906a1d7b35ff6f50eb4c6584ae09d26db25fe1c8bd6fc0ba49ecafdf/test_object.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ffd76722286ab0e6729334216652f4613d9769f
--- /dev/null
+++ b/shared/package-files/3c/3c9fbf52906a1d7b35ff6f50eb4c6584ae09d26db25fe1c8bd6fc0ba49ecafdf/test_object.py
@@ -0,0 +1,420 @@
+# Arithmetic tests for DataFrame/Series/Index/Array classes that should
+# behave identically.
+# Specifically for object dtype
+import datetime
+from decimal import Decimal
+import operator
+
+import numpy as np
+import pytest
+
+from pandas._config import using_pyarrow_string_dtype
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+    Series,
+    Timestamp,
+    option_context,
+)
+import pandas._testing as tm
+from pandas.core import ops
+
+# ------------------------------------------------------------------
+# Comparisons
+
+
+class TestObjectComparisons:
+    def test_comparison_object_numeric_nas(self, comparison_op):
+        ser = Series(np.random.default_rng(2).standard_normal(10), dtype=object)
+        shifted = ser.shift(2)
+
+        func = comparison_op
+
+        result = func(ser, shifted)
+        expected = func(ser.astype(float), shifted.astype(float))
+        tm.assert_series_equal(result, expected)
+
+    @pytest.mark.parametrize(
+        "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
+    )
+    def test_object_comparisons(self, infer_string):
+        with option_context("future.infer_string", infer_string):
+            ser = Series(["a", "b", np.nan, "c", "a"])
+
+            result = ser == "a"
+            expected = Series([True, False, False, False, True])
+            tm.assert_series_equal(result, expected)
+
+            result = ser < "a"
+            expected = Series([False, False, False, False, False])
+            tm.assert_series_equal(result, expected)
+
+            result = ser != "a"
+            expected = -(ser == "a")
+            tm.assert_series_equal(result, expected)
+
+    @pytest.mark.parametrize("dtype", [None, object])
+    def test_more_na_comparisons(self, dtype):
+        left = Series(["a", np.nan, "c"], dtype=dtype)
+        right = Series(["a", np.nan, "d"], dtype=dtype)
+
+        result = left == right
+        expected = Series([True, False, False])
+        tm.assert_series_equal(result, expected)
+
+        result = left != right
+        expected = Series([False, True, True])
+        tm.assert_series_equal(result, expected)
+
+        result = left == np.nan
+        expected = Series([False, False, False])
+        tm.assert_series_equal(result, expected)
+
+        result = left != np.nan
+        expected = Series([True, True, True])
+        tm.assert_series_equal(result, expected)
+
+
+# ------------------------------------------------------------------
+# Arithmetic
+
+
+class TestArithmetic:
+    def test_add_period_to_array_of_offset(self):
+        # GH#50162
+        per = pd.Period("2012-1-1", freq="D")
+        pi = pd.period_range("2012-1-1", periods=10, freq="D")
+        idx = per - pi
+
+        expected = pd.Index([x + per for x in idx], dtype=object)
+        result = idx + per
+        tm.assert_index_equal(result, expected)
+
+        result = per + idx
+        tm.assert_index_equal(result, expected)
+
+    # TODO: parametrize
+    def test_pow_ops_object(self):
+        # GH#22922
+        # pow is weird with masking & 1, so testing here
+        a = Series([1, np.nan, 1, np.nan], dtype=object)
+        b = Series([1, np.nan, np.nan, 1], dtype=object)
+        result = a**b
+        expected = Series(a.values**b.values, dtype=object)
+        tm.assert_series_equal(result, expected)
+
+        result = b**a
+        expected = Series(b.values**a.values, dtype=object)
+
+        tm.assert_series_equal(result, expected)
+
+    @pytest.mark.parametrize("op", [operator.add, ops.radd])
+    @pytest.mark.parametrize("other", ["category", "Int64"])
+    def test_add_extension_scalar(self, other, box_with_array, op):
+        # GH#22378
+        # Check that scalars satisfying is_extension_array_dtype(obj)
+        # do not incorrectly try to dispatch to an ExtensionArray operation
+
+        arr = Series(["a", "b", "c"])
+        expected = Series([op(x, other) for x in arr])
+
+        arr = tm.box_expected(arr, box_with_array)
+        expected = tm.box_expected(expected, box_with_array)
+
+        result = op(arr, other)
+        tm.assert_equal(result, expected)
+
+    def test_objarr_add_str(self, box_with_array):
+        ser = Series(["x", np.nan, "x"])
+        expected = Series(["xa", np.nan, "xa"])
+
+        ser = tm.box_expected(ser, box_with_array)
+        expected = tm.box_expected(expected, box_with_array)
+
+        result = ser + "a"
+        tm.assert_equal(result, expected)
+
+    def test_objarr_radd_str(self, box_with_array):
+        ser = Series(["x", np.nan, "x"])
+        expected = Series(["ax", np.nan, "ax"])
+
+        ser = tm.box_expected(ser, box_with_array)
+        expected = tm.box_expected(expected, box_with_array)
+
+        result = "a" + ser
+        tm.assert_equal(result, expected)
+
+    @pytest.mark.parametrize(
+        "data",
+        [
+            [1, 2, 3],
+            [1.1, 2.2, 3.3],
+            [Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT],
+            ["x", "y", 1],
+        ],
+    )
+    @pytest.mark.parametrize("dtype", [None, object])
+    def test_objarr_radd_str_invalid(self, dtype, data, box_with_array):
+        ser = Series(data, dtype=dtype)
+
+        ser = tm.box_expected(ser, box_with_array)
+        msg = "|".join(
+            [
+                "can only concatenate str",
+                "did not contain a loop with signature matching types",
+                "unsupported operand type",
+                "must be str",
+            ]
+        )
+        with pytest.raises(TypeError, match=msg):
+            "foo_" + ser
+
+    @pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub])
+    def test_objarr_add_invalid(self, op, box_with_array):
+        # invalid ops
+        box = box_with_array
+
+        obj_ser = Series(list("abc"), dtype=object, name="objects")
+
+        obj_ser = tm.box_expected(obj_ser, box)
+        msg = "|".join(
+            [
+                "can only concatenate str",
+                "unsupported operand type",
+                "must be str",
+                "has no kernel",
+            ]
+        )
+        with pytest.raises(Exception, match=msg):
+            op(obj_ser, 1)
+        with pytest.raises(Exception, match=msg):
+            op(obj_ser, np.array(1, dtype=np.int64))
+
+    # TODO: Moved from tests.series.test_operators; needs cleanup
+    def test_operators_na_handling(self):
+        ser = Series(["foo", "bar", "baz", np.nan])
+        result = "prefix_" + ser
+        expected = Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan])
+        tm.assert_series_equal(result, expected)
+
+        result = ser + "_suffix"
+        expected = Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan])
+        tm.assert_series_equal(result, expected)
+
+    # TODO: parametrize over box
+    @pytest.mark.parametrize("dtype", [None, object])
+    def test_series_with_dtype_radd_timedelta(self, dtype):
+        # note this test is _not_ aimed at timedelta64-dtyped Series
+        # as of 2.0 we retain object dtype when ser.dtype == object
+        ser = Series(
+            [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")],
+            dtype=dtype,
+        )
+        expected = Series(
+            [pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")],
+            dtype=dtype,
+        )
+
+        result = pd.Timedelta("3 days") + ser
+        tm.assert_series_equal(result, expected)
+
+        result = ser + pd.Timedelta("3 days")
+        tm.assert_series_equal(result, expected)
+
+    # TODO: cleanup & parametrize over box
+    def test_mixed_timezone_series_ops_object(self):
+        # GH#13043
+        ser = Series(
+            [
+                Timestamp("2015-01-01", tz="US/Eastern"),
+                Timestamp("2015-01-01", tz="Asia/Tokyo"),
+            ],
+            name="xxx",
+        )
+        assert ser.dtype == object
+
+        exp = Series(
+            [
+                Timestamp("2015-01-02", tz="US/Eastern"),
+                Timestamp("2015-01-02", tz="Asia/Tokyo"),
+            ],
+            name="xxx",
+        )
+        tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp)
+        tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
+
+        # object series & object series
+        ser2 = Series(
+            [
+                Timestamp("2015-01-03", tz="US/Eastern"),
+                Timestamp("2015-01-05", tz="Asia/Tokyo"),
+            ],
+            name="xxx",
+        )
+        assert ser2.dtype == object
+        exp = Series(
+            [pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx", dtype=object
+        )
+        tm.assert_series_equal(ser2 - ser, exp)
+        tm.assert_series_equal(ser - ser2, -exp)
+
+        ser = Series(
+            [pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")],
+            name="xxx",
+            dtype=object,
+        )
+        assert ser.dtype == object
+
+        exp = Series(
+            [pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")],
+            name="xxx",
+            dtype=object,
+        )
+        tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp)
+        tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
+
+    # TODO: cleanup & parametrize over box
+    def test_iadd_preserves_name(self):
+        # GH#17067, GH#19723 __iadd__ and __isub__ should preserve index name
+        ser = Series([1, 2, 3])
+        ser.index.name = "foo"
+
+        ser.index += 1
+        assert ser.index.name == "foo"
+
+        ser.index -= 1
+        assert ser.index.name == "foo"
+
+    def test_add_string(self):
+        # from bug report
+        index = pd.Index(["a", "b", "c"])
+        index2 = index + "foo"
+
+        assert "a" not in index2
+        assert "afoo" in index2
+
+    def test_iadd_string(self):
+        index = pd.Index(["a", "b", "c"])
+        # doesn't fail test unless there is a check before `+=`
+        assert "a" in index
+
+        index += "_x"
+        assert "a_x" in index
+
+    @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="add doesn't work")
+    def test_add(self):
+        index = pd.Index([str(i) for i in range(10)])
+        expected = pd.Index(index.values * 2)
+        tm.assert_index_equal(index + index, expected)
+        tm.assert_index_equal(index + index.tolist(), expected)
+        tm.assert_index_equal(index.tolist() + index, expected)
+
+        # test add and radd
+        index = pd.Index(list("abc"))
+        expected = pd.Index(["a1", "b1", "c1"])
+        tm.assert_index_equal(index + "1", expected)
+        expected = pd.Index(["1a", "1b", "1c"])
+        tm.assert_index_equal("1" + index, expected)
+
+    def test_sub_fail(self, using_infer_string):
+        index = pd.Index([str(i) for i in range(10)])
+
+        if using_infer_string:
+            import pyarrow as pa
+
+            err = pa.lib.ArrowNotImplementedError
+            msg = "has no kernel"
+        else:
+            err = TypeError
+            msg = "unsupported operand type|Cannot broadcast"
+        with pytest.raises(err, match=msg):
+            index - "a"
+        with pytest.raises(err, match=msg):
+            index - index
+        with pytest.raises(err, match=msg):
+            index - index.tolist()
+        with pytest.raises(err, match=msg):
+            index.tolist() - index
+
+    def test_sub_object(self):
+        # GH#19369
+        index = pd.Index([Decimal(1), Decimal(2)])
+        expected = pd.Index([Decimal(0), Decimal(1)])
+
+        result = index - Decimal(1)
+        tm.assert_index_equal(result, expected)
+
+        result = index - pd.Index([Decimal(1), Decimal(1)])
+        tm.assert_index_equal(result, expected)
+
+        msg = "unsupported operand type"
+        with pytest.raises(TypeError, match=msg):
+            index - "foo"
+
+        with pytest.raises(TypeError, match=msg):
+            index - np.array([2, "foo"], dtype=object)
+
+    def test_rsub_object(self, fixed_now_ts):
+        # GH#19369
+        index = pd.Index([Decimal(1), Decimal(2)])
+        expected = pd.Index([Decimal(1), Decimal(0)])
+
+        result = Decimal(2) - index
+        tm.assert_index_equal(result, expected)
+
+        result = np.array([Decimal(2), Decimal(2)]) - index
+        tm.assert_index_equal(result, expected)
+
+        msg = "unsupported operand type"
+        with pytest.raises(TypeError, match=msg):
+            "foo" - index
+
+        with pytest.raises(TypeError, match=msg):
+            np.array([True, fixed_now_ts]) - index
+
+
+class MyIndex(pd.Index):
+    # Simple index subclass that tracks ops calls.
+
+    _calls: int
+
+    @classmethod
+    def _simple_new(cls, values, name=None, dtype=None):
+        result = object.__new__(cls)
+        result._data = values
+        result._name = name
+        result._calls = 0
+        result._reset_identity()
+
+        return result
+
+    def __add__(self, other):
+        self._calls += 1
+        return self._simple_new(self._data)
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+
+@pytest.mark.parametrize(
+    "other",
+    [
+        [datetime.timedelta(1), datetime.timedelta(2)],
+        [datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)],
+        [pd.Period("2000"), pd.Period("2001")],
+        ["a", "b"],
+    ],
+    ids=["timedelta", "datetime", "period", "object"],
+)
+def test_index_ops_defer_to_unknown_subclasses(other):
+    # https://github.com/pandas-dev/pandas/issues/31109
+    values = np.array(
+        [datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)], dtype=object
+    )
+    a = MyIndex._simple_new(values)
+    other = pd.Index(other)
+    result = other + a
+    assert isinstance(result, MyIndex)
+    assert a._calls == 1
diff --git a/shared/package-files/3c/3c9fe1179aa237d1c33c3bbdf276b65686eb57a49e151927ebf75b55aec1636d/numerictypes.cpython-311.pyc b/shared/package-files/3c/3c9fe1179aa237d1c33c3bbdf276b65686eb57a49e151927ebf75b55aec1636d/numerictypes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c599663efa1ab2043f3063258890138b78df04b
Binary files /dev/null and b/shared/package-files/3c/3c9fe1179aa237d1c33c3bbdf276b65686eb57a49e151927ebf75b55aec1636d/numerictypes.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3ca9ff5bf9b1a777f0b8d98092e5076a0b723df7e44862c5ad10107253899ea7/_fill_mem_eff_dropout_mask_native.h b/shared/package-files/3c/3ca9ff5bf9b1a777f0b8d98092e5076a0b723df7e44862c5ad10107253899ea7/_fill_mem_eff_dropout_mask_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e0388b7c46e91202cee1364a24b0d4c02f73736
--- /dev/null
+++ b/shared/package-files/3c/3ca9ff5bf9b1a777f0b8d98092e5076a0b723df7e44862c5ad10107253899ea7/_fill_mem_eff_dropout_mask_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & _fill_mem_eff_dropout_mask_(at::Tensor & self, double dropout_p, int64_t seed, int64_t offset);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/3c/3caa1037a8581c98d36e9e41555a91c66d4e43f56bc963c7b8db9b1f3578c714/poisson_cpu_dispatch.h b/shared/package-files/3c/3caa1037a8581c98d36e9e41555a91c66d4e43f56bc963c7b8db9b1f3578c714/poisson_cpu_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..fdf9871a0dba401411276572806333ddccccc581
--- /dev/null
+++ b/shared/package-files/3c/3caa1037a8581c98d36e9e41555a91c66d4e43f56bc963c7b8db9b1f3578c714/poisson_cpu_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cpu {
+
+TORCH_API at::Tensor poisson(const at::Tensor & self, ::std::optional generator=::std::nullopt);
+
+} // namespace cpu
+} // namespace at
diff --git a/shared/package-files/3c/3caa48f86280755303875d440c8a50dc95ef44c5cd1ae2532976c66ffbb24236/cond_predicate.py b/shared/package-files/3c/3caa48f86280755303875d440c8a50dc95ef44c5cd1ae2532976c66ffbb24236/cond_predicate.py
new file mode 100644
index 0000000000000000000000000000000000000000..68bb8850bba909a0c6546c8f12a1a3fa1bdc70d1
--- /dev/null
+++ b/shared/package-files/3c/3caa48f86280755303875d440c8a50dc95ef44c5cd1ae2532976c66ffbb24236/cond_predicate.py
@@ -0,0 +1,25 @@
+# mypy: allow-untyped-defs
+import torch
+
+from functorch.experimental.control_flow import cond
+
+class CondPredicate(torch.nn.Module):
+    """
+    The conditional statement (aka predicate) passed to cond() must be one of the following:
+      - torch.Tensor with a single element
+      - boolean expression
+
+    NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
+    """
+
+    def forward(self, x):
+        pred = x.dim() > 2 and x.shape[2] > 10
+
+        return cond(pred, lambda x: x.cos(), lambda y: y.sin(), [x])
+
+example_args = (torch.randn(6, 4, 3),)
+tags = {
+    "torch.cond",
+    "torch.dynamic-shape",
+}
+model = CondPredicate()
diff --git a/shared/package-files/3c/3cb301cf992b2708f7fb1a67b5c1b0be9acf009dc88bce3472101e34acbb80d0/test_lie_group.cpython-311.pyc b/shared/package-files/3c/3cb301cf992b2708f7fb1a67b5c1b0be9acf009dc88bce3472101e34acbb80d0/test_lie_group.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2670d70e69ac281f63004b882750a473fba6148d
Binary files /dev/null and b/shared/package-files/3c/3cb301cf992b2708f7fb1a67b5c1b0be9acf009dc88bce3472101e34acbb80d0/test_lie_group.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cb9e391e99526ddd2aabe3b3c56c899be6aac25a296d56c4768991217f40c07/batchnorm.cpython-311.pyc b/shared/package-files/3c/3cb9e391e99526ddd2aabe3b3c56c899be6aac25a296d56c4768991217f40c07/batchnorm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ad3d99a851b6c2ab3813652966af1af03c06daf
Binary files /dev/null and b/shared/package-files/3c/3cb9e391e99526ddd2aabe3b3c56c899be6aac25a296d56c4768991217f40c07/batchnorm.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cbb3b04edae1a3b6f9fc1a8d81712d029cc5a2fe0a91c6efd328ca03beb980a/transaction.cpython-311.pyc b/shared/package-files/3c/3cbb3b04edae1a3b6f9fc1a8d81712d029cc5a2fe0a91c6efd328ca03beb980a/transaction.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a1b7ec95f9f082acd502cc79b85e1f1d153f329
Binary files /dev/null and b/shared/package-files/3c/3cbb3b04edae1a3b6f9fc1a8d81712d029cc5a2fe0a91c6efd328ca03beb980a/transaction.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cbc4875f80cca3aa5bccce55ba0f7638aaf0f59500b79260baa7984a2e8f1aa/model_report_observer.cpython-311.pyc b/shared/package-files/3c/3cbc4875f80cca3aa5bccce55ba0f7638aaf0f59500b79260baa7984a2e8f1aa/model_report_observer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5cb582713e6fca6ebf1f86c71dd92fd8641446b
Binary files /dev/null and b/shared/package-files/3c/3cbc4875f80cca3aa5bccce55ba0f7638aaf0f59500b79260baa7984a2e8f1aa/model_report_observer.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cbe0ee7a4290b104ff4e3f7a95c56249474bca9a18e6c7b7b9405fe7f18057f/MPSProfiler.h b/shared/package-files/3c/3cbe0ee7a4290b104ff4e3f7a95c56249474bca9a18e6c7b7b9405fe7f18057f/MPSProfiler.h
new file mode 100644
index 0000000000000000000000000000000000000000..c1cb9090fc4af77eef1590aebdb85b583e70e2f9
--- /dev/null
+++ b/shared/package-files/3c/3cbe0ee7a4290b104ff4e3f7a95c56249474bca9a18e6c7b7b9405fe7f18057f/MPSProfiler.h
@@ -0,0 +1,467 @@
+//  Copyright © 2022 Apple Inc.
+
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifndef __OBJC__
+typedef void* MTLCaptureManager;
+#endif
+
+namespace at::mps {
+
+namespace Profiler {
+
+struct BaseInfo {
+  // profiling info types
+  enum class Type {
+    GRAPH,
+    KERNEL,
+    COPY,
+    CPU_FALLBACK,
+  };
+
+  BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle)
+      : type(infoType), profileId(Id), handle(Handle) {}
+  virtual ~BaseInfo() = default;
+
+  // type of profiling info
+  Type type;
+  // unique profile ID for execution instances of operations or copies
+  uint64_t profileId;
+  // ID generated by os_signpost
+  // since it's possible to use event and interval-based signposts at the
+  // same time, we need separate IDs for each.
+  os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0;
+  // accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime -
+  // GPUStartTime")
+  std::atomic totalGpuTime{0.0};
+  // accumulated Scheduling time in ms (obtained from CompletionHandler's
+  // "KernelEndTime - KernelStartTime")
+  std::atomic totalSchedulingTime{0.0};
+  // indicates if the operation or copy execution has completed
+  std::atomic_bool completed{false};
+  // handle used to identify the profile info's instance (usually the pointer)
+  const uintptr_t handle;
+
+  virtual const std::string toString(
+      double gpuTime = 0,
+      double schedulingTime = 0) const;
+  // builds a string for a tensor (format: Device:ScalarType[tensor.sizes()])
+  static std::string buildTensorString(
+      const Tensor& tensor,
+      bool includeBufferId = false);
+  static uint64_t getTime() {
+    return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
+  }
+};
+
+struct OperationInfo : BaseInfo {
+  OperationInfo(
+      const void* Handle,
+      bool IsGraph,
+      uint64_t Id,
+      const std::string& StrKey)
+      : BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)),
+        strKey(StrKey) {}
+
+  uint64_t runCount = 0;
+  std::string strKey;
+
+  const std::string toString(double gpuTime = 0, double schedulingTime = 0)
+      const override;
+
+  // builds a string for a kernel
+  static std::string buildKernelString(
+      const std::string& kernelName,
+      const TensorList& tensors,
+      bool includeBufferId = false) {
+    std::stringstream kernelStr;
+    kernelStr << kernelName;
+    for (const Tensor& tensor : tensors) {
+      kernelStr << ":" << BaseInfo::buildTensorString(tensor, includeBufferId);
+    }
+    return kernelStr.str();
+  }
+};
+
+struct CpuFbInfo : BaseInfo {
+  CpuFbInfo(uint64_t Id, const std::string& OpName)
+      : BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {}
+
+  uint64_t runCount = 0;
+  // the current and total overhead of copies in bytes required to convert the
+  // Op's input tensors from MPS to CPU and then output from CPU back to MPS
+  size_t currentCopyOverhead = 0;
+  size_t totalCopyOverhead = 0;
+  std::string opName;
+  std::string strKey;
+  uint64_t startTime = 0;
+
+  const std::string toString(double gpuTime = 0, double schedulingTime = 0)
+      const override;
+
+  void updateCopyOverhead(const TensorList& tensors) {
+    currentCopyOverhead = 0;
+    for (const Tensor& tensor : tensors) {
+      if (tensor.defined()) {
+        currentCopyOverhead += tensor.nbytes();
+      }
+    }
+    totalCopyOverhead += currentCopyOverhead;
+  }
+};
+
+struct CopyInfo : BaseInfo {
+  enum class Kind {
+    MPS_TO_MPS,
+    MPS_TO_CPU,
+    CPU_TO_MPS,
+  };
+
+  CopyInfo(
+      const void* Handle,
+      size_t Length,
+      uint64_t Id,
+      bool IsNonBlocking,
+      bool UsesBlitter)
+      : BaseInfo(Type::COPY, Id, uintptr_t(Handle)),
+        kind(Kind::MPS_TO_MPS),
+        length(Length),
+        isNonBlocking(IsNonBlocking),
+        usesBlitter(UsesBlitter) {}
+
+  Kind kind;
+  size_t length;
+  bool isNonBlocking;
+  bool usesBlitter;
+  std::string srcStrKey;
+  std::string dstStrKey;
+  // for copies that don't use blitters, we measure CPU time
+  uint64_t startTime = 0;
+
+  const std::string toString(double gpuTime = 0, double schedulingTime = 0)
+      const override;
+
+  static std::string buildTensorString(
+      const void* buffer,
+      const OptionalTensorRef tensor,
+      bool includeBufferId = false);
+
+  static bool isStorageOnMPS(
+      const void* buffer,
+      const OptionalTensorRef tensor) {
+    if (tensor.has_value()) {
+      return tensor->device().type() == at::kMPS;
+    }
+    TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer);
+    // getUnalignedBufferSize() returns -1 if input buffer is not on MPS device
+    return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0;
+  }
+
+  static Kind getCopyKind(
+      const void* srcBuffer,
+      const void* dstBuffer,
+      const OptionalTensorRef srcTensor,
+      const OptionalTensorRef dstTensor) {
+    const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor);
+    const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor);
+    TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS);
+    if (isSrcOnMPS && !isDstOnMPS) {
+      return Kind::MPS_TO_CPU;
+    } else if (!isSrcOnMPS && isDstOnMPS) {
+      return Kind::CPU_TO_MPS;
+    }
+    return Kind::MPS_TO_MPS;
+  }
+};
+
+struct CopyStat : CopyInfo {
+  explicit CopyStat(std::string CopyKindStr)
+      : CopyInfo(nullptr, 0, 0, false, false),
+        kindStr(std::move(CopyKindStr)) {}
+  // total number of copies
+  size_t totalCount = 0;
+  // number of Scalar copies (i.e., less than sizeof(int64))
+  size_t scalarsCount = 0;
+  // number of blocking copies (i.e., require syncing to GPU)
+  size_t blockingCount = 0;
+  // number of copies that used memcpy(), instead of Metal Blit Encoder
+  size_t memcpyCount = 0;
+  // accumulated GPU time in ms for the scalar copies
+  std::atomic scalarsGpuTime{0.0};
+  // copy kind in string type
+  std::string kindStr;
+};
+
+class MPSProfiler {
+ public:
+  // lower 16 bits used for profiler options
+  enum ProfileOptions : uint32_t {
+    OPTIONS_NONE = 0,
+    // ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK,
+    // etc.) (used for convenience to not compute bit flags by OR-ing manually)
+    // trace all signpost types using events
+    ALL_SIGNPOST_EVENTS = (1 << 0),
+    // trace all signpost types using intervals
+    ALL_SIGNPOST_INTERVALS = (1 << 1),
+    // always wait for command buffer to finish executing after each commit
+    WAIT_UNTIL_COMPLETED = (1 << 2),
+    // for interval-based signposts, include the scheduling portion of
+    // Graph/Kernel/Copy executions as well.
+    // if flag is disable, only "GPU run time" is included in interval,
+    // and not schedule time.
+    INCLUDE_SCHEDULE_INTERVAL = (1 << 3),
+
+    // use these if you need to trace signposts types individually (rarely
+    // required) trace signpost using intervals
+    USE_INTERVALS = (1 << 4),
+    // trace signpost by emitting events
+    USE_EVENTS = (1 << 5),
+    // used for sanity check (Change this when new option added)
+    OPTIONS_COUNT = (USE_EVENTS << 1) - 1,
+  };
+
+  // when adding new types, #define the type string in MPSProfiler.mm as well.
+  // upper 16 bits used for event types
+  enum SignpostTypes : uint32_t {
+    SIGNPOST_NONE = 0,
+    // trace signposts for PyTorch operation executions
+    RUN_OPERATION = (1 << 16),
+    // trace signposts for blitter copies
+    BLIT_COPY = (1 << 17),
+    // trace signposts for ops that fall back on CPU
+    CPU_FALLBACK = (1 << 18),
+    // used for sanity check (Change this when new type added)
+    SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1,
+  };
+
+  enum LogOptions : uint32_t {
+    LOG_NONE = 0,
+
+    // Info logging options during execution
+    // -------------------------------------
+    // prints operation info (id/key/run_count) during execution
+    OPERATION_INFO = (1 << 0),
+    // prints copy info (src/dst tensors/buffers, size, etc.) during execution
+    COPY_INFO = (1 << 1),
+    // prints CPU Fallback info (id/runCount/opName/copyOverhead) during
+    // execution
+    CPU_FALLBACK_INFO = (1 << 2),
+
+    // Profiling Statistics logging options when process terminates
+    // ------------------------------------------------------------
+    // prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before
+    // process terminates this is convenient to not combine following stats bit
+    // flags manually
+    ALL_STATS = (1 << 3),
+    // prints operation stats (GPU times, run count, etc.) before process
+    // terminates
+    OPERATION_STATS = (1 << 4),
+    // prints copies stats (GPU times, copy kinds, sizes, etc.) before process
+    // terminates
+    COPY_STATS = (1 << 5),
+    // prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies
+    // for tensors, etc.) before process terminates
+    CPU_FALLBACK_STATS = (1 << 6),
+
+    // Metadata format options when logging the info
+    // ---------------------------------------------
+    // if enabled, includes GPU run time in metadata (i.e.,
+    // GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324
+    // ms])
+    INCLUDE_GPU_TIME = (1 << 7),
+    // if enabled, includes GPU scheduling time in metadata separately
+    // (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers)
+    // e.g., [GPU=0.324 ms, KRNL=0.036 ms]
+    INCLUDE_KERNEL_TIME = (1 << 8),
+    // if enabled, includes the unique buffer ID in metadata for the storage
+    // of a tensor that was allocated on MPSAllocator. This is useful (along
+    // with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are
+    // involved with various operations.
+    INCLUDE_BUFFER_ID = (1 << 9),
+
+    // used for sanity check (Change this when new option added)
+    LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1,
+  };
+
+  explicit MPSProfiler();
+  ~MPSProfiler();
+
+  // the handle is either "MPSGraph*" or "id" for Metal
+  // Kernels the beginProfile*() functions return a profileId which is unique
+  // per graph/kernel/copy
+  uint64_t beginProfileKernel(
+      const void* handle,
+      const std::string& strKey,
+      bool isGraph);
+  uint64_t beginProfileKernel(
+      const void* handle,
+      const std::string& kernelName,
+      const TensorList& tensors);
+  uint64_t beginProfileCopy(
+      const void* srcBuffer,
+      const void* dstBuffer,
+      const OptionalTensorRef srcTensor,
+      const OptionalTensorRef dstTensor,
+      size_t length,
+      bool isNonBlocking,
+      bool usesBlitter = true);
+  uint64_t beginProfileCPUFallback(
+      const std::string& opName,
+      const TensorList& tensors);
+  void beginProfileGPUInterval(const void* handle);
+
+  void endProfileCopy(uint64_t profileId, SyncType syncType);
+  void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE);
+  void endProfileCPUFallback(const std::string& opName);
+
+  // these are used to hook into Python bindings for torch.mps.profiler module.
+  // this enables generating OS Signpost traces from MPSProfiler on-demand
+  // during runtime (instead of environment variables).
+  // The "mode" could be either "interval", "event", or both "interval,event"
+  // for interval-based and/or event-based signpost tracing.
+  void StartTrace(const std::string& mode, bool waitUntilCompleted);
+  void StopTrace();
+
+  // Abstractions for GPU trace capturing
+  bool isCaptureEnabled() const;
+  bool isCapturing() const;
+  void startCapture(const std::string& name, MPSStream* stream = nullptr);
+  void stopCapture(MPSStream* stream = nullptr);
+
+  // convenience functions to indicate whether signpost tracing or
+  // logging are enabled for the SignpostTypes
+  bool isOperationProfilingEnabled() const {
+    return (m_signpost_types & SignpostTypes::RUN_OPERATION) ||
+        (m_log_options &
+         (LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS));
+  }
+  bool isCopyProfilingEnabled() const {
+    return (m_signpost_types & SignpostTypes::BLIT_COPY) ||
+        (m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS));
+  }
+  bool isCPUFallbackProfilingEnabled() const {
+    return (m_signpost_types & SignpostTypes::CPU_FALLBACK) ||
+        (m_log_options &
+         (LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS));
+  }
+  bool isSignpostTracingEnabled() const {
+    return (m_signpost_types != SignpostTypes::SIGNPOST_NONE);
+  }
+
+ private:
+  // indicates what type of signpost types are enabled and traced by MPS
+  // profiler.
+  uint32_t m_signpost_types = 0;
+  uint32_t m_profile_options = 0;
+  uint32_t m_log_options = 0;
+  uint64_t m_kernel_counter = 0;
+  uint64_t m_graph_counter = 0;
+  uint64_t m_cpu_fb_counter = 0;
+  uint64_t m_copy_counter = 0;
+  // technically, it's possible to trace both events and intervals at the same
+  // time so we use separate os_log categories for them
+  os_log_t m_os_log_events;
+  os_log_t m_os_log_intervals;
+  // stats logging could run either from destructor or signal handler
+  // so this is used to check if logging has already started.
+  std::atomic_bool hasLoggedStats{false};
+  // indicates there are pending completionHandler callbacks that haven't been
+  // called yet.
+  std::atomic_bool hasPendingCompletionHandlers{false};
+  // used to capture sigint signal to log profiling stats
+  static struct sigaction currentSigint, previousSigint;
+
+  // We use the following lists for two reasons:
+  // 1- for interval-based signposts the "begin" point won't be in same function
+  // as the "end" point where we need to be able to retrieve signpost's info
+  // 2- if Operations info need to be logged when process ends using
+  // LogOptions::OPERATION_INFO.
+
+  // the pointer key for this map is either "MPSGraph*" or
+  // "id" for Metal Kernels this list is retained and
+  // could be logged along with aggregate profiling numbers when the process
+  // ends.
+  std::unordered_map>
+      m_op_info_list{};
+  // the string key for this map is the op name that we fall back to execute on
+  // CPU this list is retained and could be logged along with aggregate
+  // profiling numbers when the process ends.
+  std::unordered_map>
+      m_cpu_fb_info_list{};
+  // this list contains the info for copies, and its key is the unique profileId
+  // which is generated from m_copy_counter
+  // The copyInfo list is not retained.
+  std::unordered_map> m_copy_info_list{};
+  // a short list that contains copy stats
+  std::unordered_map>
+      m_copy_stat_list{};
+
+  mutable MTLCaptureManager* captureManager = nil;
+  unsigned captureCount = 0;
+
+  void initialize();
+  void beginProfileExecution(BaseInfo& info, bool cpuExecution = false);
+  void endProfileExecution(
+      BaseInfo& info,
+      os_signpost_id_t event_signpost_id,
+      os_signpost_id_t interval_signpost_id,
+      double gpuTime,
+      double schedulingTime);
+  void addProfilerScheduledHandler(BaseInfo& info);
+  void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType);
+  void emitSignpostEvent(
+      SignpostTypes signpost_type,
+      os_signpost_id_t signpost_id,
+      const std::string& msg) const;
+  void beginSignpostInterval(
+      SignpostTypes signpost_type,
+      os_signpost_id_t signpost_id,
+      const std::string& msg) const;
+  void endSignpostInterval(
+      SignpostTypes signpost_type,
+      os_signpost_id_t signpost_id) const;
+
+  void updateCopyStats(
+      const CopyInfo& copyInfo,
+      double gpuTime,
+      double schedulingTime);
+  // returns true if logging the profiling info "during the execution" is
+  // enabled
+  bool isProfileInfoLoggingEnabled(
+      BaseInfo::Type infoType,
+      bool isExecutionEnded);
+  // logs all the profiling stats that are enabled
+  void logProfilingStats();
+  // logs kernel profiling stats when the process ends.
+  void logOperationsProfilingStats(std::FILE* f) const;
+  // logs CPU Fallback profiling stats when the process ends.
+  void logCPUFallbackProfilingStats(std::FILE* f) const;
+  // logs copy profiling stats when the process ends.
+  void logCopyProfilingStats(std::FILE* f) const;
+
+  os_signpost_id_t generateSignpostId(
+      os_signpost_type_t signpostType,
+      const void* ptr = nullptr);
+  static SignpostTypes getSignpostType(BaseInfo::Type infoType);
+  static void handleIntSignal(int signal);
+};
+
+} // namespace Profiler
+
+Profiler::MPSProfiler& getMPSProfiler();
+
+} // namespace at::mps
diff --git a/shared/package-files/3c/3cbf51a83854694cec64c6d4eb833923668f99a5841268bf11836aa61ec5c607/FakeQuantAffine.h b/shared/package-files/3c/3cbf51a83854694cec64c6d4eb833923668f99a5841268bf11836aa61ec5c607/FakeQuantAffine.h
new file mode 100644
index 0000000000000000000000000000000000000000..e107fb4c62f098e2cff847c9d17cbdea05f72234
--- /dev/null
+++ b/shared/package-files/3c/3cbf51a83854694cec64c6d4eb833923668f99a5841268bf11836aa61ec5c607/FakeQuantAffine.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace at {
+
+struct TensorIterator;
+
+namespace native {
+
+using fake_quant_tensor_cachemask_fn = void (*)(
+    Tensor& output,
+    Tensor& mask,
+    const Tensor& input,
+    float sc,
+    int64_t z_point,
+    int64_t quant_min,
+    int64_t quant_max);
+
+using fake_quant_tensor_cachemask_tensor_qparams_fn = void (*)(
+    Tensor& output,
+    Tensor& mask,
+    const Tensor& input,
+    const Tensor& sc,
+    const Tensor& z_point,
+    const Tensor& fake_quant_enabled,
+    int64_t quant_min,
+    int64_t quant_max);
+
+using fake_quant_learnable_grad_tensor_fn = void (*)(
+    TensorIterator& iter,
+    float scale,
+    float inv_scale,
+    int64_t zero_point,
+    int64_t quant_min,
+    int64_t quant_max,
+    float grad_factor);
+
+DECLARE_DISPATCH(fake_quant_tensor_cachemask_fn, fake_quant_tensor_cachemask_stub)
+DECLARE_DISPATCH(fake_quant_tensor_cachemask_tensor_qparams_fn, fake_quant_tensor_cachemask_tensor_qparams_stub)
+DECLARE_DISPATCH(fake_quant_learnable_grad_tensor_fn, fake_quant_grad_learnable_tensor_stub)
+
+using fake_quant_per_channel_fn = void (*)(
+    TensorIterator &iter,
+    int64_t quant_min,
+    int64_t quant_max);
+
+using fake_quant_per_channel_cachemask_fn = void (*)(
+    TensorIterator &iter,
+    TensorIterator &iter_mask,
+    int64_t quant_min,
+    int64_t quant_max);
+
+DECLARE_DISPATCH(fake_quant_per_channel_cachemask_fn, fake_quant_per_channel_cachemask_stub)
+
+using fake_quant_learnable_per_channel_fn = void (*)(
+    TensorIterator &iter,
+    int64_t quant_min,
+    int64_t quant_max,
+    float grad_factor);
+
+DECLARE_DISPATCH(fake_quant_learnable_per_channel_fn, fake_quant_grad_learnable_channel_stub)
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/3c/3cc451f0c8f7f21527f5e9fe2d528ed248c431eaae68f5775da00bf5f4fce741/cram_size.c.pysam.c b/shared/package-files/3c/3cc451f0c8f7f21527f5e9fe2d528ed248c431eaae68f5775da00bf5f4fce741/cram_size.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..b3031d00eeb2cd53288db051fc50d3442c0f4838
--- /dev/null
+++ b/shared/package-files/3c/3cc451f0c8f7f21527f5e9fe2d528ed248c431eaae68f5775da00bf5f4fce741/cram_size.c.pysam.c
@@ -0,0 +1,667 @@
+#include "samtools.pysam.h"
+
+/*  cram_size.c -- produces summary of the size of each cram data-series
+
+    Copyright (C) 2023 Genome Research Ltd.
+
+    Author: James Bonfield 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+// TODO: add range query.  Eg the ability to look at size for "*" only
+// (unmapped), or in a specific region such as a centromere.
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "htslib/bgzf.h"
+#include "htslib/sam.h"
+#include "htslib/cram.h"
+#include "htslib/kstring.h"
+#include "htslib/khash.h"
+#include "samtools.h"
+#include "sam_opts.h"
+#include "htslib/hfile.h"
+
+/*----------------------------------------------------------------------
+ * Compression method handling
+ */
+
+// A numeric version of the cram_method_details struct.
+// We expand the myriad of struct field combinations into a single
+// enumerated type so we can index and accumulate statistics for
+// purposes of reporting.
+//
+// These expanded numeric values have no definition within CRAM itself
+// and never occur within the file format.
+enum comp_expanded {
+    //----
+    // Copies from htslib cram_block_method enum
+    COMP_RAW    = CRAM_COMP_RAW,
+    COMP_GZIP   = CRAM_COMP_GZIP,
+    COMP_BZIP2  = CRAM_COMP_BZIP2,
+    COMP_LZMA   = CRAM_COMP_LZMA,
+    COMP_RANS8  = CRAM_COMP_RANS4x8,
+    COMP_RANS16 = CRAM_COMP_RANSNx16,
+    COMP_ARITH  = CRAM_COMP_ARITH,
+    COMP_FQZ    = CRAM_COMP_FQZ,
+    COMP_TOK3   = CRAM_COMP_TOK3,
+
+    //----
+    // Localised variants.
+
+    // Gzip
+    COMP_GZIP_1,
+    COMP_GZIP_9,
+
+    // Bzip2
+    COMP_BZIP2_1,
+    COMP_BZIP2_2,
+    COMP_BZIP2_3,
+    COMP_BZIP2_4,
+    COMP_BZIP2_5,
+    COMP_BZIP2_6,
+    COMP_BZIP2_7,
+    COMP_BZIP2_8,
+    COMP_BZIP2_9,
+
+    // rans 4x8
+    COMP_RANS4x8_O0,
+    COMP_RANS4x8_O1,
+
+    // rans Nx16.  Note order here is to enable selection via bit-fields
+    // bit 0: O0/O1
+    // bit 1: RLE
+    // bit 2: PACK
+    // bit 3: 32x16
+    COMP_RANS4x16_O0,
+    COMP_RANS4x16_O1,
+    COMP_RANS4x16_O0R,   // +RLE
+    COMP_RANS4x16_O1R,
+    COMP_RANS4x16_O0P,   // +PACK
+    COMP_RANS4x16_O1P,
+    COMP_RANS4x16_O0PR,  // +PACK+RLE
+    COMP_RANS4x16_O1PR,
+    COMP_RANS32x16_O0,   // SIMD variants
+    COMP_RANS32x16_O1,
+    COMP_RANS32x16_O0R,  // +RLE
+    COMP_RANS32x16_O1R,
+    COMP_RANS32x16_O0P,  // +PACK
+    COMP_RANS32x16_O1P,
+    COMP_RANS32x16_O0PR, // +PACK+RLE
+    COMP_RANS32x16_O1PR,
+    COMP_RANSNx16_STRIPE,
+    COMP_RANSNx16_CAT,
+
+    // Arith
+    COMP_ARITH_O0,
+    COMP_ARITH_O1,
+    COMP_ARITH_O0R,   // +RLE
+    COMP_ARITH_O1R,
+    COMP_ARITH_O0P,   // +PACK
+    COMP_ARITH_O1P,
+    COMP_ARITH_O0PR,  // +PACK+RLE
+    COMP_ARITH_O1PR,
+    COMP_ARITH_STRIPE,
+    COMP_ARITH_CAT,   // no entropy encoder
+    COMP_ARITH_EXT,   // external entropy encode
+
+    // Nake tokeniser
+    COMP_TOK3_RANS,
+    COMP_TOK3_ARITH,
+
+    // To mark maximum size
+    COMP_MAX,
+};
+
+static enum comp_expanded comp_method2expanded(cram_method_details *cm) {
+    switch (cm->method) {
+    case CRAM_COMP_GZIP:
+        switch (cm->level) {
+        case 1:  return COMP_GZIP_1;
+        case 9:  return COMP_GZIP_9;
+        default: return COMP_GZIP;
+        }
+        break;
+
+    case CRAM_COMP_BZIP2:
+        if (cm->level >= 1 && cm->level <= 9)
+            return COMP_BZIP2_1 + cm->level-1;
+        else
+            return COMP_BZIP2;
+        break;
+
+    case CRAM_COMP_RANS4x8:
+        return cm->order ? COMP_RANS4x8_O1 : COMP_RANS4x8_O0;
+
+    case CRAM_COMP_RANSNx16: {
+        // 8 4x16, 8 32x16 and 2 stripe/cat
+        if (cm->stripe) return COMP_RANSNx16_STRIPE;
+        if (cm->cat)    return COMP_RANSNx16_CAT;
+        int c = COMP_RANS4x16_O0;
+        c += 1*cm->order;
+        c += 2*cm->rle;
+        c += 4*cm->pack;
+        c += 8*(cm->Nway==32);
+        return c;
+    }
+
+    case CRAM_COMP_ARITH: {
+        // 8 4x16, 8 32x16 and 2 stripe/cat
+        if (cm->stripe) return COMP_ARITH_STRIPE;
+        if (cm->cat)    return COMP_ARITH_CAT;
+        if (cm->ext)    return COMP_ARITH_EXT;
+        int c = COMP_ARITH_O0;
+        c += 1*cm->order;
+        c += 2*cm->rle;
+        c += 4*cm->pack;
+        return c;
+    }
+
+    case CRAM_COMP_TOK3:
+        return cm->level < 10
+            ? COMP_TOK3_RANS
+            : COMP_TOK3_ARITH;
+
+    default:
+        // Any unspecialised method
+        return (enum comp_expanded)cm->method;
+    }
+}
+
+// Short form of cram_block_method_int type
+static char comp_method2char[COMP_MAX] =
+    ".gblr0afn"           // standard CRAM methods
+    "_G"                  // gzip
+    "bbbbbbbbB"           // bzip2
+    "rR"                  // rans4x8
+    "010101014545454582"  // ransNx16
+    "aAaAaAaAaaa"         // arith
+    "nN";                 // tok3
+
+// Long form of cram_block_method_int type
+static char *comp_method2str[COMP_MAX] = {
+    // Standard CRAM methods
+    "raw", "gzip", "bzip2", "lzma", "r4x8", "rNx16",
+    "arith", "fqzcomp", "tok3",
+
+    // custom gzip
+    "gzip-min", "gzip-max",
+
+    // custom bzip2
+    "bzip2-1", "bzip2-2", "bzip2-3", "bzip2-4", "bzip2-5",
+    "bzip2-6", "bzip2-7", "bzip2-8", "bzip2-9",
+
+    // rANS 4x8
+    "r4x8-o0", "r4x8-o1",
+
+    // rANS 4x16
+    "r4x16-o0",   "r4x16-o1",
+
+    "r4x16-o0R",  "r4x16-o1R",
+    "r4x16-o0P",  "r4x16-o1P",
+    "r4x16-o0PR", "r4x16-o1PR",
+    "r32x16-o0",  "r32x16-o1",
+    "r32x16-o0R", "r32x16-o1R",
+    "r32x16-o0P", "r32x16-o1P",
+    "r32x16-o0PR","r32x16-o1PR",
+    "rNx16-xo0",  "rNx16-cat",
+
+    // Arith
+    "arith-o0",   "arith-o1",
+    "arith-o0R",  "arith-o1R",
+    "arith-o0P",  "arith-o1P",
+    "arith-o0PR", "arith-o1PR",
+    "arith-stripe", "arith-cat", "arith-ext",
+
+    // Name tokeniser
+    "tok3-rans", "tok3-arith",
+};
+
+/*----------------------------------------------------------------------
+ * Manipulation and sorting of Block Content-ID arrays and hashes
+ */
+
+typedef struct {
+    int64_t csize[COMP_MAX];
+    int64_t usize[COMP_MAX];
+} cusize_t;
+
+static int64_t total_csize(cusize_t *cu) {
+    int i;
+    int64_t tot = 0;
+    for (i = 0; i < COMP_MAX; i++)
+        tot += cu->csize[i];
+    return tot;
+}
+
+static int64_t total_usize(cusize_t *cu) {
+    int i;
+    int64_t tot = 0;
+    for (i = 0; i < COMP_MAX; i++)
+        tot += cu->usize[i];
+    return tot;
+}
+
+// cusize_t array and sorting by compressed size
+static cusize_t *sort_cusize_global; // avoids a messy extra data type
+static int sort_cusize_compar(const void *i1, const void *i2) {
+    int64_t n = sort_cusize_global->csize[*(const int *)i2] -
+                sort_cusize_global->csize[*(const int *)i1];
+    return n > 0 ? 1 : (n < 0 ? -1 : *(const int *)i1 - *(const int *)i2);
+}
+
+// Sort a cusize array by size of used method.
+// Returns cu->csize[comp] indices in descending size, as static mem
+static int *sort_cusize(cusize_t *cu) {
+    static int idx[COMP_MAX];
+    int i;
+    for (i = 0; i < COMP_MAX; i++)
+        idx[i] = i;
+    sort_cusize_global = cu;
+    qsort(idx, COMP_MAX, sizeof(*idx), sort_cusize_compar);
+
+    return idx;
+}
+
+// Hash table of cusize_t and sorting by key (content-id)
+KHASH_MAP_INIT_INT(cu, cusize_t)
+
+/* Sort by hash key. Global due to rubbish qsort API, but it's simple. */
+static khash_t(cu) *global_cu_hash = NULL;
+static int cu_compar(const void *i1, const void *i2) {
+    return kh_key(global_cu_hash, *(const int *)i1) -
+           kh_key(global_cu_hash, *(const int *)i2);
+}
+
+/*----------------------------------------------------------------------
+ * Main cram_size reporting and aggregation
+ */
+static off_t report_size(FILE *outfp, int verbose, int ref_seq_blk,
+                         khash_t(cu) *cu_size, cram_cid2ds_t *cid2ds) {
+    if (!cu_size || !cid2ds)
+        return -1;
+
+    khiter_t k;
+    off_t tot_size = 0;
+
+    fprintf(outfp, "#   Content_ID  Uncomp.size    Comp.size   Ratio Method%.*s  Data_series\n", verbose ? 4 : 0, "    ");
+    int *sorted_blocks = malloc(kh_end(cu_size)*sizeof(int));
+    if (!sorted_blocks)
+        return -1;
+    int nblocks = 0;
+    for (k = kh_begin(cu_size); k != kh_end(cu_size); k++) {
+        if (!kh_exist(cu_size, k))
+            continue;
+        sorted_blocks[nblocks++] = k;
+    }
+    global_cu_hash = cu_size;
+    qsort(sorted_blocks, nblocks, sizeof(int), cu_compar);
+
+    int i;
+    for (i = 0; i < nblocks; i++) {
+        k = sorted_blocks[i];
+
+        if (verbose) {
+            // FULL output
+            int *comp_idx = sort_cusize(&kh_value(cu_size, k));
+            int first_line = 1, c, j;
+            for (c = 0; c < COMP_MAX; c++) {
+                int comp = comp_idx[c];
+                if (!kh_value(cu_size, k).csize[comp] && c)
+                    break;
+
+                if (!first_line)
+                    fprintf(outfp, "\n");
+                first_line = 0;
+
+                if ((int)kh_key(cu_size, k) < 0)
+                    fprintf(outfp, "BLOCK %8s", "CORE");
+                else
+                    fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
+
+                fprintf(outfp, " %12"PRId64" %12"PRId64,
+                        kh_value(cu_size, k).usize[comp],
+                        kh_value(cu_size, k).csize[comp]);
+                double f = (100.0*(kh_value(cu_size, k).csize[comp]+.0001)) /
+                    (kh_value(cu_size, k).usize[comp]+.0001);
+                if (f > 999)
+                    fprintf(outfp, "   >999%% %-11s", comp_method2str[comp]);
+                else
+                    fprintf(outfp, " %6.2f%% %-11s",f, comp_method2str[comp]);
+
+                int n, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
+                for (j = 0; j < n; j++) {
+                    int d = dsa[j];
+                    if (d > 65535)
+                        fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
+                    else
+                        fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
+                }
+            }
+        } else {
+            // aggregate by compression type.
+            int64_t csize = total_csize(&kh_value(cu_size, k));
+            int64_t usize = total_usize(&kh_value(cu_size, k));
+            int *comp_idx = sort_cusize(&kh_value(cu_size, k));
+
+            char cstr[COMP_MAX+1] = {0};
+            int cidx = 0, c;
+            for (c = 0; c < COMP_MAX; c++) {
+                if (!kh_value(cu_size, k).csize[comp_idx[c]])
+                    break;
+                cstr[cidx++] = comp_method2char[comp_idx[c]];
+            }
+            if (!*cstr) *cstr = '.';
+
+            if ((int)kh_key(cu_size, k) < 0)
+                fprintf(outfp, "BLOCK %8s", "CORE");
+            else
+                fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
+            fprintf(outfp, " %12"PRId64" %12"PRId64, usize, csize);
+            double f = 100*(csize+.0001)/(usize+.0001);
+            if (f > 999)
+                fprintf(outfp, "   >999%% %-7s", cstr);
+            else
+                fprintf(outfp, " %6.2f%% %-7s", f, cstr);
+
+            int n, j, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
+            for (j = 0; j < n; j++) {
+                int d = dsa[j];
+                if (d > 65535)
+                    fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
+                else
+                    fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
+            }
+        }
+
+        if ((int)kh_key(cu_size, k) >= 0 &&
+            (int)kh_key(cu_size, k) == ref_seq_blk) {
+            fprintf(outfp, " embedded_ref");
+        }
+        fprintf(outfp, "\n");
+
+        tot_size += total_csize(&kh_value(cu_size, k));
+    }
+
+    free(sorted_blocks);
+
+    return tot_size;
+}
+
+/* Main processing loop */
+static int cram_size(hFILE *hf_in, samFile *in, sam_hdr_t *h, FILE *outfp,
+                     int verbose, int encodings) {
+    cram_fd *in_c;
+    cram_container *c = NULL;
+    cram_block *blk = NULL;
+    cram_block_slice_hdr *shdr = NULL;
+    khiter_t k;
+    int ret;
+    cram_cid2ds_t *cid2ds = NULL;
+    khash_t(cu) *cu_size = kh_init(cu);
+    int ref_seq_blk_used = -1;
+    int64_t nseqs = 0, nbases = 0, ncont = 0, nslice = 0;
+
+    if (!in->is_cram) {
+        print_error("cram_size", "Input is not a CRAM file");
+        goto err;
+    }
+    in_c = in->fp.cram; // low level htslib abuse?
+    while ((c = cram_read_container(in_c))) {
+        if (cram_container_is_empty(in_c)) {
+            cram_block *blk;
+            // Container compression header
+            if (!(blk = cram_read_block(in_c)))
+                goto err;
+            cram_free_block(blk);
+            cram_free_container(c);
+            c = NULL; blk = NULL;
+            continue;
+        }
+
+        nseqs  += cram_container_get_num_records(c);
+        nbases += cram_container_get_num_bases(c);
+
+        // Container compression header
+        int32_t num_slices;
+        if (!(blk = cram_read_block(in_c)))
+            goto err;
+
+        // Decode compression header...
+        cram_block_compression_hdr *chdr;
+        chdr = cram_decode_compression_header(in_c, blk);
+
+        if (encodings) {
+            kstring_t ks = KS_INITIALIZE;
+            if (cram_describe_encodings(chdr, &ks) < 0)
+                goto err;
+
+            fprintf(outfp, "Container encodings\n%s\n", ks_str(&ks));
+
+            ks_free(&ks);
+        }
+
+        cid2ds = cram_update_cid2ds_map(chdr, cid2ds);
+
+        cram_free_block(blk);
+        blk = NULL;
+
+        cram_free_compression_header(chdr);
+
+        // Container num_blocks can be invalid, due to a bug.
+        // Instead we iterate in slice context instead.
+        (void)cram_container_get_landmarks(c, &num_slices);
+        ncont++;
+        nslice += num_slices;
+
+        int i, j;
+        for (i = 0; i < num_slices; i++) {
+            // Slice header
+            if (!(blk = cram_read_block(in_c)))
+                goto err;
+            if (!(shdr = cram_decode_slice_header(in_c, blk)))
+                goto err;
+            cram_free_block(blk);
+            blk = NULL;
+
+            int ref_seq_blk = cram_slice_hdr_get_embed_ref_id(shdr);
+            int num_blocks = cram_slice_hdr_get_num_blocks(shdr);
+
+            // Embedded reference.  Check it's consistent (if used this is
+            // an almost guaranteed certainty, so we take the easy route).
+            if (ref_seq_blk >= 0) {
+                if (ref_seq_blk_used == -1)
+                    ref_seq_blk_used = ref_seq_blk;
+                else if (ref_seq_blk_used != ref_seq_blk)
+                    fprintf(samtools_stderr, "Embedded reference is not consistently using the same Content-Id.\n"
+                            "Reported figures for reference will be invalid.\n");
+            }
+
+            // Slice data blocks
+            for (j = 0; j < num_blocks; j++) {
+                // read and discard, unless it's the ref-ID block
+                if (!(blk = cram_read_block(in_c)))
+                    goto err;
+
+                int32_t csize = cram_block_get_comp_size(blk);
+                int32_t usize = cram_block_get_uncomp_size(blk);
+                int cid = cram_block_get_content_id(blk);
+                enum cram_block_method method = cram_block_get_method(blk);
+
+                // Expand comp to the internal sub-formats, eg
+                // rANS order-0/1, PACK+RLE, etc.
+                cram_method_details *cm;
+                cm = cram_expand_method(cram_block_get_data(blk),
+                                        cram_block_get_comp_size(blk),
+                                        method);
+                if (!cm)
+                    goto err;
+                enum comp_expanded comp
+                    = comp_method2expanded(cm);
+                free(cm);
+
+                k = kh_put(cu, cu_size, cid, &ret);
+                if (ret < 0)
+                    goto err;
+                if (ret == 0) {
+                    kh_value(cu_size, k).csize[comp] += csize;
+                    kh_value(cu_size, k).usize[comp] += usize;
+                } else {
+                    memset(&kh_value(cu_size, k), 0, sizeof(cusize_t));
+                    kh_value(cu_size, k).csize[comp]  = csize;
+                    kh_value(cu_size, k).usize[comp]  = usize;
+                }
+
+                cram_free_block(blk);
+                blk = NULL;
+            }
+            cram_free_slice_header(shdr);
+            shdr = NULL;
+        }
+
+        cram_free_container(c);
+        c = NULL;
+    }
+
+    off_t tot_size = report_size(outfp, verbose, ref_seq_blk_used,
+                                 cu_size, cid2ds);
+    if (tot_size < 0)
+        goto err;
+
+    kh_destroy(cu, cu_size);
+    cram_cid2ds_free(cid2ds);
+
+    off_t end = htell(hf_in);
+
+    fprintf(outfp, "\n");
+    fprintf(outfp, "Number of containers  %18"PRId64"\n", ncont);
+    fprintf(outfp, "Number of slices      %18"PRId64"\n", nslice);
+    fprintf(outfp, "Number of sequences   %18"PRId64"\n", nseqs);
+    fprintf(outfp, "Number of bases       %18"PRId64"\n", nbases);
+    fprintf(outfp, "Total file size       %18"PRId64"\n", (int64_t) end);
+    fprintf(outfp, "Format overhead size  %18"PRId64"\n", (int64_t) (end - tot_size));
+
+    return 0;
+
+ err:
+    // Report anyway so we can get stats on partial files, but be
+    // sure to error too.
+    report_size(outfp, verbose, ref_seq_blk_used, cu_size, cid2ds);
+
+    print_error("cram_size", "Failed in decoding CRAM file");
+    if (blk)
+        cram_free_block(blk);
+    if (shdr)
+        cram_free_slice_header(shdr);
+    if (c)
+        cram_free_container(c);
+    if (cid2ds)
+        cram_cid2ds_free(cid2ds);
+
+    return -1;
+}
+
+/* main() for cram_size */
+int main_cram_size(int argc, char *argv[]) {
+    int c, usage = 0, verbose = 0, encodings = 0;
+    sam_hdr_t *h = 0;
+    hFILE *hf_in = NULL;
+    samFile *in = NULL;
+    sam_global_args ga;
+    FILE *outfp = samtools_stdout;
+
+    static const struct option lopts[] = {
+        {"output", required_argument, NULL, 'o'},
+        {"verbose",  no_argument, NULL, 'v'},
+        {"encodings", no_argument, NULL, 'e'},
+        SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '-'),
+        { NULL, 0, NULL, 0 }
+    };
+
+    sam_global_args_init(&ga);
+
+    while ((c = getopt_long(argc, argv, "vo:e", lopts, NULL)) >= 0) {
+        switch (c) {
+        case 'o':
+            if (!(outfp = fopen(optarg, "w"))) {
+                perror(optarg);
+                goto err;
+            }
+            break;
+
+        case 'v':
+            verbose++;
+            break;
+
+        case 'e':
+            encodings++;
+            break;
+
+        default:
+            if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
+            /* else fall-through */
+        case '?': usage=1; break;
+        }
+    }
+
+    if ((optind == argc && isatty(0)) || usage) {
+        fprintf(samtools_stdout, "Usage: samtools cram_size [-ve] [-o out.size] [in.cram]\n");
+        return 0;
+    }
+
+    char *fn = optind < argc ? argv[optind] : "-";
+
+    // We want access to in->fp.cram->fp, but this is an opaque struct so we
+    // can't get that.  However we opened with hopen and then reopen as
+    // CRAM with hts_hopen, which will swallow the initial hFILE and take
+    // owenership of it.  Hence we now know in->fp.cram->fp.
+    if (!(hf_in = hopen(fn, "r"))) {
+        print_error_errno("cram_size", "failed to open file '%s'", fn);
+        return 1;
+    }
+    if (!(in = hts_hopen(hf_in, fn, "r"))) {
+        print_error_errno("cram_size", "failed to open file '%s'", fn);
+        goto err;
+    }
+
+    if (!(h = sam_hdr_read(in)))
+        goto err;
+
+    int ret = cram_size(hf_in, in, h, outfp, verbose, encodings);
+    sam_hdr_destroy(h);
+    sam_close(in);
+    if (outfp != samtools_stdout)
+        fclose(outfp);
+
+    return ret ? 1 : 0;
+
+ err:
+    if (in)
+        sam_close(in);
+    if (h)
+        sam_hdr_destroy(h);
+
+    return 1;
+}
diff --git a/shared/package-files/3c/3cc67ccef67333e1ab85cae89bb4bc668e17e2e734c23216f9b7cccb3ed65ca1/json.cpython-311-x86_64-linux-gnu.so b/shared/package-files/3c/3cc67ccef67333e1ab85cae89bb4bc668e17e2e734c23216f9b7cccb3ed65ca1/json.cpython-311-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0d67faaa5e74393dd209cfe1e1a3ace299c0de99
Binary files /dev/null and b/shared/package-files/3c/3cc67ccef67333e1ab85cae89bb4bc668e17e2e734c23216f9b7cccb3ed65ca1/json.cpython-311-x86_64-linux-gnu.so differ
diff --git a/shared/package-files/3c/3ccb2e860390656664d271f08da8c0bae9a4297cc7e90be664d7c82d364e442f/charset.py b/shared/package-files/3c/3ccb2e860390656664d271f08da8c0bae9a4297cc7e90be664d7c82d364e442f/charset.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d4db7cd227ee41270254023324845ca6ac2cb9f
--- /dev/null
+++ b/shared/package-files/3c/3ccb2e860390656664d271f08da8c0bae9a4297cc7e90be664d7c82d364e442f/charset.py
@@ -0,0 +1,399 @@
+# Copyright (C) 2001-2007 Python Software Foundation
+# Author: Ben Gertzfield, Barry Warsaw
+# Contact: email-sig@python.org
+
+__all__ = [
+    'Charset',
+    'add_alias',
+    'add_charset',
+    'add_codec',
+    ]
+
+from functools import partial
+
+import email.base64mime
+import email.quoprimime
+
+from email import errors
+from email.encoders import encode_7or8bit
+
+
+# Flags for types of header encodings
+QP          = 1 # Quoted-Printable
+BASE64      = 2 # Base64
+SHORTEST    = 3 # the shorter of QP and base64, but only for headers
+
+# In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
+RFC2047_CHROME_LEN = 7
+
+DEFAULT_CHARSET = 'us-ascii'
+UNKNOWN8BIT = 'unknown-8bit'
+EMPTYSTRING = ''
+
+
+# Defaults
+CHARSETS = {
+    # input        header enc  body enc output conv
+    'iso-8859-1':  (QP,        QP,      None),
+    'iso-8859-2':  (QP,        QP,      None),
+    'iso-8859-3':  (QP,        QP,      None),
+    'iso-8859-4':  (QP,        QP,      None),
+    # iso-8859-5 is Cyrillic, and not especially used
+    # iso-8859-6 is Arabic, also not particularly used
+    # iso-8859-7 is Greek, QP will not make it readable
+    # iso-8859-8 is Hebrew, QP will not make it readable
+    'iso-8859-9':  (QP,        QP,      None),
+    'iso-8859-10': (QP,        QP,      None),
+    # iso-8859-11 is Thai, QP will not make it readable
+    'iso-8859-13': (QP,        QP,      None),
+    'iso-8859-14': (QP,        QP,      None),
+    'iso-8859-15': (QP,        QP,      None),
+    'iso-8859-16': (QP,        QP,      None),
+    'windows-1252':(QP,        QP,      None),
+    'viscii':      (QP,        QP,      None),
+    'us-ascii':    (None,      None,    None),
+    'big5':        (BASE64,    BASE64,  None),
+    'gb2312':      (BASE64,    BASE64,  None),
+    'euc-jp':      (BASE64,    None,    'iso-2022-jp'),
+    'shift_jis':   (BASE64,    None,    'iso-2022-jp'),
+    'iso-2022-jp': (BASE64,    None,    None),
+    'koi8-r':      (BASE64,    BASE64,  None),
+    'utf-8':       (SHORTEST,  BASE64, 'utf-8'),
+    }
+
+# Aliases for other commonly-used names for character sets.  Map
+# them to the real ones used in email.
+ALIASES = {
+    'latin_1': 'iso-8859-1',
+    'latin-1': 'iso-8859-1',
+    'latin_2': 'iso-8859-2',
+    'latin-2': 'iso-8859-2',
+    'latin_3': 'iso-8859-3',
+    'latin-3': 'iso-8859-3',
+    'latin_4': 'iso-8859-4',
+    'latin-4': 'iso-8859-4',
+    'latin_5': 'iso-8859-9',
+    'latin-5': 'iso-8859-9',
+    'latin_6': 'iso-8859-10',
+    'latin-6': 'iso-8859-10',
+    'latin_7': 'iso-8859-13',
+    'latin-7': 'iso-8859-13',
+    'latin_8': 'iso-8859-14',
+    'latin-8': 'iso-8859-14',
+    'latin_9': 'iso-8859-15',
+    'latin-9': 'iso-8859-15',
+    'latin_10':'iso-8859-16',
+    'latin-10':'iso-8859-16',
+    'cp949':   'ks_c_5601-1987',
+    'euc_jp':  'euc-jp',
+    'euc_kr':  'euc-kr',
+    'ascii':   'us-ascii',
+    }
+
+
+# Map charsets to their Unicode codec strings.
+CODEC_MAP = {
+    'gb2312':      'eucgb2312_cn',
+    'big5':        'big5_tw',
+    # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
+    # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
+    # Let that stuff pass through without conversion to/from Unicode.
+    'us-ascii':    None,
+    }
+
+
+# Convenience functions for extending the above mappings
+def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
+    """Add character set properties to the global registry.
+
+    charset is the input character set, and must be the canonical name of a
+    character set.
+
+    Optional header_enc and body_enc is either Charset.QP for
+    quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
+    the shortest of qp or base64 encoding, or None for no encoding.  SHORTEST
+    is only valid for header_enc.  It describes how message headers and
+    message bodies in the input charset are to be encoded.  Default is no
+    encoding.
+
+    Optional output_charset is the character set that the output should be
+    in.  Conversions will proceed from input charset, to Unicode, to the
+    output charset when the method Charset.convert() is called.  The default
+    is to output in the same character set as the input.
+
+    Both input_charset and output_charset must have Unicode codec entries in
+    the module's charset-to-codec mapping; use add_codec(charset, codecname)
+    to add codecs the module does not know about.  See the codecs module's
+    documentation for more information.
+    """
+    if body_enc == SHORTEST:
+        raise ValueError('SHORTEST not allowed for body_enc')
+    CHARSETS[charset] = (header_enc, body_enc, output_charset)
+
+
+def add_alias(alias, canonical):
+    """Add a character set alias.
+
+    alias is the alias name, e.g. latin-1
+    canonical is the character set's canonical name, e.g. iso-8859-1
+    """
+    ALIASES[alias] = canonical
+
+
+def add_codec(charset, codecname):
+    """Add a codec that map characters in the given charset to/from Unicode.
+
+    charset is the canonical name of a character set.  codecname is the name
+    of a Python codec, as appropriate for the second argument to the unicode()
+    built-in, or to the encode() method of a Unicode string.
+    """
+    CODEC_MAP[charset] = codecname
+
+
+# Convenience function for encoding strings, taking into account
+# that they might be unknown-8bit (ie: have surrogate-escaped bytes)
+def _encode(string, codec):
+    if codec == UNKNOWN8BIT:
+        return string.encode('ascii', 'surrogateescape')
+    else:
+        return string.encode(codec)
+
+
+class Charset:
+    """Map character sets to their email properties.
+
+    This class provides information about the requirements imposed on email
+    for a specific character set.  It also provides convenience routines for
+    converting between character sets, given the availability of the
+    applicable codecs.  Given a character set, it will do its best to provide
+    information on how to use that character set in an email in an
+    RFC-compliant way.
+
+    Certain character sets must be encoded with quoted-printable or base64
+    when used in email headers or bodies.  Certain character sets must be
+    converted outright, and are not allowed in email.  Instances of this
+    module expose the following information about a character set:
+
+    input_charset: The initial character set specified.  Common aliases
+                   are converted to their `official' email names (e.g. latin_1
+                   is converted to iso-8859-1).  Defaults to 7-bit us-ascii.
+
+    header_encoding: If the character set must be encoded before it can be
+                     used in an email header, this attribute will be set to
+                     Charset.QP (for quoted-printable), Charset.BASE64 (for
+                     base64 encoding), or Charset.SHORTEST for the shortest of
+                     QP or BASE64 encoding.  Otherwise, it will be None.
+
+    body_encoding: Same as header_encoding, but describes the encoding for the
+                   mail message's body, which indeed may be different than the
+                   header encoding.  Charset.SHORTEST is not allowed for
+                   body_encoding.
+
+    output_charset: Some character sets must be converted before they can be
+                    used in email headers or bodies.  If the input_charset is
+                    one of them, this attribute will contain the name of the
+                    charset output will be converted to.  Otherwise, it will
+                    be None.
+
+    input_codec: The name of the Python codec used to convert the
+                 input_charset to Unicode.  If no conversion codec is
+                 necessary, this attribute will be None.
+
+    output_codec: The name of the Python codec used to convert Unicode
+                  to the output_charset.  If no conversion codec is necessary,
+                  this attribute will have the same value as the input_codec.
+    """
+    def __init__(self, input_charset=DEFAULT_CHARSET):
+        # RFC 2046, $4.1.2 says charsets are not case sensitive.  We coerce to
+        # unicode because its .lower() is locale insensitive.  If the argument
+        # is already a unicode, we leave it at that, but ensure that the
+        # charset is ASCII, as the standard (RFC XXX) requires.
+        try:
+            if isinstance(input_charset, str):
+                input_charset.encode('ascii')
+            else:
+                input_charset = str(input_charset, 'ascii')
+        except UnicodeError:
+            raise errors.CharsetError(input_charset)
+        input_charset = input_charset.lower()
+        # Set the input charset after filtering through the aliases
+        self.input_charset = ALIASES.get(input_charset, input_charset)
+        # We can try to guess which encoding and conversion to use by the
+        # charset_map dictionary.  Try that first, but let the user override
+        # it.
+        henc, benc, conv = CHARSETS.get(self.input_charset,
+                                        (SHORTEST, BASE64, None))
+        if not conv:
+            conv = self.input_charset
+        # Set the attributes, allowing the arguments to override the default.
+        self.header_encoding = henc
+        self.body_encoding = benc
+        self.output_charset = ALIASES.get(conv, conv)
+        # Now set the codecs.  If one isn't defined for input_charset,
+        # guess and try a Unicode codec with the same name as input_codec.
+        self.input_codec = CODEC_MAP.get(self.input_charset,
+                                         self.input_charset)
+        self.output_codec = CODEC_MAP.get(self.output_charset,
+                                          self.output_charset)
+
+    def __repr__(self):
+        return self.input_charset.lower()
+
+    def __eq__(self, other):
+        return str(self) == str(other).lower()
+
+    def get_body_encoding(self):
+        """Return the content-transfer-encoding used for body encoding.
+
+        This is either the string `quoted-printable' or `base64' depending on
+        the encoding used, or it is a function in which case you should call
+        the function with a single argument, the Message object being
+        encoded.  The function should then set the Content-Transfer-Encoding
+        header itself to whatever is appropriate.
+
+        Returns "quoted-printable" if self.body_encoding is QP.
+        Returns "base64" if self.body_encoding is BASE64.
+        Returns conversion function otherwise.
+        """
+        assert self.body_encoding != SHORTEST
+        if self.body_encoding == QP:
+            return 'quoted-printable'
+        elif self.body_encoding == BASE64:
+            return 'base64'
+        else:
+            return encode_7or8bit
+
+    def get_output_charset(self):
+        """Return the output character set.
+
+        This is self.output_charset if that is not None, otherwise it is
+        self.input_charset.
+        """
+        return self.output_charset or self.input_charset
+
+    def header_encode(self, string):
+        """Header-encode a string by converting it first to bytes.
+
+        The type of encoding (base64 or quoted-printable) will be based on
+        this charset's `header_encoding`.
+
+        :param string: A unicode string for the header.  It must be possible
+            to encode this string to bytes using the character set's
+            output codec.
+        :return: The encoded string, with RFC 2047 chrome.
+        """
+        codec = self.output_codec or 'us-ascii'
+        header_bytes = _encode(string, codec)
+        # 7bit/8bit encodings return the string unchanged (modulo conversions)
+        encoder_module = self._get_encoder(header_bytes)
+        if encoder_module is None:
+            return string
+        return encoder_module.header_encode(header_bytes, codec)
+
+    def header_encode_lines(self, string, maxlengths):
+        """Header-encode a string by converting it first to bytes.
+
+        This is similar to `header_encode()` except that the string is fit
+        into maximum line lengths as given by the argument.
+
+        :param string: A unicode string for the header.  It must be possible
+            to encode this string to bytes using the character set's
+            output codec.
+        :param maxlengths: Maximum line length iterator.  Each element
+            returned from this iterator will provide the next maximum line
+            length.  This parameter is used as an argument to built-in next()
+            and should never be exhausted.  The maximum line lengths should
+            not count the RFC 2047 chrome.  These line lengths are only a
+            hint; the splitter does the best it can.
+        :return: Lines of encoded strings, each with RFC 2047 chrome.
+        """
+        # See which encoding we should use.
+        codec = self.output_codec or 'us-ascii'
+        header_bytes = _encode(string, codec)
+        encoder_module = self._get_encoder(header_bytes)
+        encoder = partial(encoder_module.header_encode, charset=codec)
+        # Calculate the number of characters that the RFC 2047 chrome will
+        # contribute to each line.
+        charset = self.get_output_charset()
+        extra = len(charset) + RFC2047_CHROME_LEN
+        # Now comes the hard part.  We must encode bytes but we can't split on
+        # bytes because some character sets are variable length and each
+        # encoded word must stand on its own.  So the problem is you have to
+        # encode to bytes to figure out this word's length, but you must split
+        # on characters.  This causes two problems: first, we don't know how
+        # many octets a specific substring of unicode characters will get
+        # encoded to, and second, we don't know how many ASCII characters
+        # those octets will get encoded to.  Unless we try it.  Which seems
+        # inefficient.  In the interest of being correct rather than fast (and
+        # in the hope that there will be few encoded headers in any such
+        # message), brute force it. :(
+        lines = []
+        current_line = []
+        maxlen = next(maxlengths) - extra
+        for character in string:
+            current_line.append(character)
+            this_line = EMPTYSTRING.join(current_line)
+            length = encoder_module.header_length(_encode(this_line, charset))
+            if length > maxlen:
+                # This last character doesn't fit so pop it off.
+                current_line.pop()
+                # Does nothing fit on the first line?
+                if not lines and not current_line:
+                    lines.append(None)
+                else:
+                    separator = (' ' if lines else '')
+                    joined_line = EMPTYSTRING.join(current_line)
+                    header_bytes = _encode(joined_line, codec)
+                    lines.append(encoder(header_bytes))
+                current_line = [character]
+                maxlen = next(maxlengths) - extra
+        joined_line = EMPTYSTRING.join(current_line)
+        header_bytes = _encode(joined_line, codec)
+        lines.append(encoder(header_bytes))
+        return lines
+
+    def _get_encoder(self, header_bytes):
+        if self.header_encoding == BASE64:
+            return email.base64mime
+        elif self.header_encoding == QP:
+            return email.quoprimime
+        elif self.header_encoding == SHORTEST:
+            len64 = email.base64mime.header_length(header_bytes)
+            lenqp = email.quoprimime.header_length(header_bytes)
+            if len64 < lenqp:
+                return email.base64mime
+            else:
+                return email.quoprimime
+        else:
+            return None
+
+    def body_encode(self, string):
+        """Body-encode a string by converting it first to bytes.
+
+        The type of encoding (base64 or quoted-printable) will be based on
+        self.body_encoding.  If body_encoding is None, we assume the
+        output charset is a 7bit encoding, so re-encoding the decoded
+        string using the ascii codec produces the correct string version
+        of the content.
+        """
+        if not string:
+            return string
+        if self.body_encoding is BASE64:
+            if isinstance(string, str):
+                string = string.encode(self.output_charset)
+            return email.base64mime.body_encode(string)
+        elif self.body_encoding is QP:
+            # quopromime.body_encode takes a string, but operates on it as if
+            # it were a list of byte codes.  For a (minimal) history on why
+            # this is so, see changeset 0cf700464177.  To correctly encode a
+            # character set, then, we must turn it into pseudo bytes via the
+            # latin1 charset, which will encode any byte as a single code point
+            # between 0 and 255, which is what body_encode is expecting.
+            if isinstance(string, str):
+                string = string.encode(self.output_charset)
+            string = string.decode('latin1')
+            return email.quoprimime.body_encode(string)
+        else:
+            if isinstance(string, str):
+                string = string.encode(self.output_charset).decode('ascii')
+            return string
diff --git a/shared/package-files/3c/3ccb4fbe529734d0fba29d346aec82773c5ff015220135f95fd43791ff7429ff/_creation.cpython-311.pyc b/shared/package-files/3c/3ccb4fbe529734d0fba29d346aec82773c5ff015220135f95fd43791ff7429ff/_creation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..288c22d689f41b0fa757ed9f050655621e250313
Binary files /dev/null and b/shared/package-files/3c/3ccb4fbe529734d0fba29d346aec82773c5ff015220135f95fd43791ff7429ff/_creation.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cd1f2bee10ceba5045cb17cc9ee8f32295c1032bbe41f7069bdda8bc6bd732a/timeutils.py b/shared/package-files/3c/3cd1f2bee10ceba5045cb17cc9ee8f32295c1032bbe41f7069bdda8bc6bd732a/timeutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1caae825103335f3e8afedeaf741cff2b0414fb2
--- /dev/null
+++ b/shared/package-files/3c/3cd1f2bee10ceba5045cb17cc9ee8f32295c1032bbe41f7069bdda8bc6bd732a/timeutils.py
@@ -0,0 +1,75 @@
+"""Simple tools for timing functions' execution, when IPython is not available. """
+
+
+import timeit
+import math
+
+
+_scales = [1e0, 1e3, 1e6, 1e9]
+_units = ['s', 'ms', '\N{GREEK SMALL LETTER MU}s', 'ns']
+
+
+def timed(func, setup="pass", limit=None):
+    """Adaptively measure execution time of a function. """
+    timer = timeit.Timer(func, setup=setup)
+    repeat, number = 3, 1
+
+    for i in range(1, 10):
+        if timer.timeit(number) >= 0.2:
+            break
+        elif limit is not None and number >= limit:
+            break
+        else:
+            number *= 10
+
+    time = min(timer.repeat(repeat, number)) / number
+
+    if time > 0.0:
+        order = min(-int(math.floor(math.log10(time)) // 3), 3)
+    else:
+        order = 3
+
+    return (number, time, time*_scales[order], _units[order])
+
+
+# Code for doing inline timings of recursive algorithms.
+
+def __do_timings():
+    import os
+    res = os.getenv('SYMPY_TIMINGS', '')
+    res = [x.strip() for x in res.split(',')]
+    return set(res)
+
+_do_timings = __do_timings()
+_timestack = None
+
+
+def _print_timestack(stack, level=1):
+    print('-'*level, '%.2f %s%s' % (stack[2], stack[0], stack[3]))
+    for s in stack[1]:
+        _print_timestack(s, level + 1)
+
+
+def timethis(name):
+    def decorator(func):
+        if name not in _do_timings:
+            return func
+
+        def wrapper(*args, **kwargs):
+            from time import time
+            global _timestack
+            oldtimestack = _timestack
+            _timestack = [func.func_name, [], 0, args]
+            t1 = time()
+            r = func(*args, **kwargs)
+            t2 = time()
+            _timestack[2] = t2 - t1
+            if oldtimestack is not None:
+                oldtimestack[1].append(_timestack)
+                _timestack = oldtimestack
+            else:
+                _print_timestack(_timestack)
+                _timestack = None
+            return r
+        return wrapper
+    return decorator
diff --git a/shared/package-files/3c/3cd5989ecdf4308cad2501d23a1ed46d96256935f97b46dabf32b5e2d75efc2f/cuda_egl_interop.h b/shared/package-files/3c/3cd5989ecdf4308cad2501d23a1ed46d96256935f97b46dabf32b5e2d75efc2f/cuda_egl_interop.h
new file mode 100644
index 0000000000000000000000000000000000000000..40ab01b33e0e9bec536192676c2a804809276fc4
--- /dev/null
+++ b/shared/package-files/3c/3cd5989ecdf4308cad2501d23a1ed46d96256935f97b46dabf32b5e2d75efc2f/cuda_egl_interop.h
@@ -0,0 +1,642 @@
+/*
+ * Copyright 1993-2019 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#if !defined(__CUDA_EGL_INTEROP_H__)
+#define __CUDA_EGL_INTEROP_H__
+
+#include "cuda_runtime_api.h"
+#include "cuda_runtime.h"
+#include "cudart_platform.h"
+#include "EGL/egl.h"
+#include "EGL/eglext.h"
+
+#if defined(__cplusplus)
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+ * \addtogroup CUDART_TYPES
+ * @{
+ */
+
+ /**
+ * Maximum number of planes per frame
+ */
+#define CUDA_EGL_MAX_PLANES 3
+
+/**
+ * CUDA EglFrame type - array or pointer
+ */
+typedef enum cudaEglFrameType_enum
+{
+    cudaEglFrameTypeArray = 0,  /**< Frame type CUDA array */
+    cudaEglFrameTypePitch = 1,  /**< Frame type CUDA pointer */
+} cudaEglFrameType;
+
+/**
+ * Resource location flags- sysmem or vidmem
+ *
+ * For CUDA context on iGPU, since video and system memory are equivalent -
+ * these flags will not have an effect on the execution.
+ *
+ * For CUDA context on dGPU, applications can use the flag ::cudaEglResourceLocationFlags
+ * to give a hint about the desired location.
+ *
+ * ::cudaEglResourceLocationSysmem - the frame data is made resident on the system memory
+ * to be accessed by CUDA.
+ *
+ * ::cudaEglResourceLocationVidmem - the frame data is made resident on the dedicated
+ * video memory to be accessed by CUDA.
+ *
+ * There may be an additional latency due to new allocation and data migration,
+ * if the frame is produced on a different memory.
+ */
+typedef enum cudaEglResourceLocationFlags_enum {
+    cudaEglResourceLocationSysmem   = 0x00,       /**< Resource location sysmem */
+    cudaEglResourceLocationVidmem   = 0x01,       /**< Resource location vidmem */
+} cudaEglResourceLocationFlags;
+
+/**
+ * CUDA EGL Color Format - The different planar and multiplanar formats currently supported for CUDA_EGL interops.
+ */
+typedef enum cudaEglColorFormat_enum {
+    cudaEglColorFormatYUV420Planar            = 0,  /**< Y, U, V in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYUV420SemiPlanar        = 1,  /**< Y, UV in two surfaces (UV as one surface) with VU byte ordering, width, height ratio same as YUV420Planar. */
+    cudaEglColorFormatYUV422Planar            = 2,  /**< Y, U, V  each in a separate  surface, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV422SemiPlanar        = 3,  /**< Y, UV in two surfaces with VU byte ordering, width, height ratio same as YUV422Planar. */
+    cudaEglColorFormatARGB                    = 6,  /**< R/G/B/A four channels in one surface with BGRA byte ordering. */
+    cudaEglColorFormatRGBA                    = 7,  /**< R/G/B/A four channels in one surface with ABGR byte ordering. */
+    cudaEglColorFormatL                       = 8,  /**< single luminance channel in one surface. */
+    cudaEglColorFormatR                       = 9,  /**< single color channel in one surface. */
+    cudaEglColorFormatYUV444Planar            = 10, /**< Y, U, V in three surfaces, each in a separate surface, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV444SemiPlanar        = 11, /**< Y, UV in two surfaces (UV as one surface) with VU byte ordering, width, height ratio same as YUV444Planar. */
+    cudaEglColorFormatYUYV422                 = 12, /**< Y, U, V in one surface, interleaved as UYVY in one channel. */
+    cudaEglColorFormatUYVY422                 = 13, /**< Y, U, V in one surface, interleaved as YUYV in one channel. */
+    cudaEglColorFormatABGR                    = 14, /**< R/G/B/A four channels in one surface with RGBA byte ordering. */
+    cudaEglColorFormatBGRA                    = 15, /**< R/G/B/A four channels in one surface with ARGB byte ordering. */
+    cudaEglColorFormatA                       = 16, /**< Alpha color format - one channel in one surface. */
+    cudaEglColorFormatRG                      = 17, /**< R/G color format - two channels in one surface with GR byte ordering */
+    cudaEglColorFormatAYUV                    = 18, /**< Y, U, V, A four channels in one surface, interleaved as VUYA. */
+    cudaEglColorFormatYVU444SemiPlanar        = 19, /**< Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU422SemiPlanar        = 20, /**< Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU420SemiPlanar        = 21, /**< Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_444SemiPlanar = 22, /**< Y10, V10U10 in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatY10V10U10_420SemiPlanar = 23, /**< Y10, V10U10 in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY12V12U12_444SemiPlanar = 24, /**< Y12, V12U12 in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatY12V12U12_420SemiPlanar = 25, /**< Y12, V12U12 in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatVYUY_ER                 = 26, /**< Extended Range Y, U, V in one surface, interleaved as YVYU in one channel. */
+    cudaEglColorFormatUYVY_ER                 = 27, /**< Extended Range Y, U, V in one surface, interleaved as YUYV in one channel. */
+    cudaEglColorFormatYUYV_ER                 = 28, /**< Extended Range Y, U, V in one surface, interleaved as UYVY in one channel. */
+    cudaEglColorFormatYVYU_ER                 = 29, /**< Extended Range Y, U, V in one surface, interleaved as VYUY in one channel. */
+    cudaEglColorFormatYUVA_ER                 = 31, /**< Extended Range Y, U, V, A four channels in one surface, interleaved as AVUY. */
+    cudaEglColorFormatAYUV_ER                 = 32, /**< Extended Range Y, U, V, A four channels in one surface, interleaved as VUYA. */
+    cudaEglColorFormatYUV444Planar_ER         = 33, /**< Extended Range Y, U, V in three surfaces, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV422Planar_ER         = 34, /**< Extended Range Y, U, V in three surfaces, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV420Planar_ER         = 35, /**< Extended Range Y, U, V in three surfaces, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYUV444SemiPlanar_ER     = 36, /**< Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV422SemiPlanar_ER     = 37, /**< Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYUV420SemiPlanar_ER     = 38, /**< Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU444Planar_ER         = 39, /**< Extended Range Y, V, U in three surfaces, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU422Planar_ER         = 40, /**< Extended Range Y, V, U in three surfaces, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU420Planar_ER         = 41, /**< Extended Range Y, V, U in three surfaces, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU444SemiPlanar_ER     = 42, /**< Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU422SemiPlanar_ER     = 43, /**< Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU420SemiPlanar_ER     = 44, /**< Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatBayerRGGB               = 45, /**< Bayer format - one channel in one surface with interleaved RGGB ordering. */
+    cudaEglColorFormatBayerBGGR               = 46, /**< Bayer format - one channel in one surface with interleaved BGGR ordering. */
+    cudaEglColorFormatBayerGRBG               = 47, /**< Bayer format - one channel in one surface with interleaved GRBG ordering. */
+    cudaEglColorFormatBayerGBRG               = 48, /**< Bayer format - one channel in one surface with interleaved GBRG ordering. */
+    cudaEglColorFormatBayer10RGGB             = 49, /**< Bayer10 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 10 bits used 6 bits No-op. */
+    cudaEglColorFormatBayer10BGGR             = 50, /**< Bayer10 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 10 bits used 6 bits No-op. */
+    cudaEglColorFormatBayer10GRBG             = 51, /**< Bayer10 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 10 bits used 6 bits No-op. */
+    cudaEglColorFormatBayer10GBRG             = 52, /**< Bayer10 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 10 bits used 6 bits No-op. */
+    cudaEglColorFormatBayer12RGGB             = 53, /**< Bayer12 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12BGGR             = 54, /**< Bayer12 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12GRBG             = 55, /**< Bayer12 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12GBRG             = 56, /**< Bayer12 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer14RGGB             = 57, /**< Bayer14 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 14 bits used 2 bits No-op. */
+    cudaEglColorFormatBayer14BGGR             = 58, /**< Bayer14 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 14 bits used 2 bits No-op. */
+    cudaEglColorFormatBayer14GRBG             = 59, /**< Bayer14 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 14 bits used 2 bits No-op. */
+    cudaEglColorFormatBayer14GBRG             = 60, /**< Bayer14 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 14 bits used 2 bits No-op. */
+    cudaEglColorFormatBayer20RGGB             = 61, /**< Bayer20 format - one channel in one surface with interleaved RGGB ordering. Out of 32 bits, 20 bits used 12 bits No-op. */
+    cudaEglColorFormatBayer20BGGR             = 62, /**< Bayer20 format - one channel in one surface with interleaved BGGR ordering. Out of 32 bits, 20 bits used 12 bits No-op. */
+    cudaEglColorFormatBayer20GRBG             = 63, /**< Bayer20 format - one channel in one surface with interleaved GRBG ordering. Out of 32 bits, 20 bits used 12 bits No-op. */
+    cudaEglColorFormatBayer20GBRG             = 64, /**< Bayer20 format - one channel in one surface with interleaved GBRG ordering. Out of 32 bits, 20 bits used 12 bits No-op. */
+    cudaEglColorFormatYVU444Planar            = 65, /**< Y, V, U in three surfaces, each in a separate surface, U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU422Planar            = 66, /**< Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = Y height. */
+    cudaEglColorFormatYVU420Planar            = 67, /**< Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatBayerIspRGGB            = 68, /**< Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved RGGB ordering and mapped to opaque integer datatype. */
+    cudaEglColorFormatBayerIspBGGR            = 69, /**< Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved BGGR ordering and mapped to opaque integer datatype. */
+    cudaEglColorFormatBayerIspGRBG            = 70, /**< Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved GRBG ordering and mapped to opaque integer datatype. */
+    cudaEglColorFormatBayerIspGBRG            = 71, /**< Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved GBRG ordering and mapped to opaque integer datatype. */
+    cudaEglColorFormatBayerBCCR               = 72, /**< Bayer format - one channel in one surface with interleaved BCCR ordering. */
+    cudaEglColorFormatBayerRCCB               = 73, /**< Bayer format - one channel in one surface with interleaved RCCB ordering. */
+    cudaEglColorFormatBayerCRBC               = 74, /**< Bayer format - one channel in one surface with interleaved CRBC ordering. */
+    cudaEglColorFormatBayerCBRC               = 75, /**< Bayer format - one channel in one surface with interleaved CBRC ordering. */
+    cudaEglColorFormatBayer10CCCC             = 76, /**< Bayer10 format - one channel in one surface with interleaved CCCC ordering. Out of 16 bits, 10 bits used 6 bits No-op. */
+    cudaEglColorFormatBayer12BCCR             = 77, /**< Bayer12 format - one channel in one surface with interleaved BCCR ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12RCCB             = 78, /**< Bayer12 format - one channel in one surface with interleaved RCCB ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12CRBC             = 79, /**< Bayer12 format - one channel in one surface with interleaved CRBC ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12CBRC             = 80, /**< Bayer12 format - one channel in one surface with interleaved CBRC ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatBayer12CCCC             = 81, /**< Bayer12 format - one channel in one surface with interleaved CCCC ordering. Out of 16 bits, 12 bits used 4 bits No-op. */
+    cudaEglColorFormatY                       = 82, /**< Color format for single Y plane. */
+    cudaEglColorFormatYUV420SemiPlanar_2020   = 83, /**< Y, UV in two surfaces (UV as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU420SemiPlanar_2020   = 84, /**< Y, VU in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYUV420Planar_2020       = 85, /**< Y, U, V in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU420Planar_2020       = 86, /**< Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYUV420SemiPlanar_709    = 87, /**< Y, UV in two surfaces (UV as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU420SemiPlanar_709    = 88, /**< Y, VU in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYUV420Planar_709        = 89, /**< Y, U, V in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatYVU420Planar_709        = 90, /**< Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_420SemiPlanar_709  = 91, /**< Y10, V10U10 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_420SemiPlanar_2020 = 92, /**< Y10, V10U10 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_422SemiPlanar_2020 = 93, /**< Y10, V10U10  in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height =  Y height. */
+    cudaEglColorFormatY10V10U10_422SemiPlanar      = 94, /**< Y10, V10U10  in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height =  Y height. */
+    cudaEglColorFormatY10V10U10_422SemiPlanar_709  = 95, /**< Y10, V10U10  in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height =  Y height. */
+    cudaEglColorFormatY_ER                         = 96, /**< Extended Range Color format for single Y plane. */
+    cudaEglColorFormatY_709_ER                     = 97, /**< Extended Range Color format for single Y plane. */
+    cudaEglColorFormatY10_ER                       = 98, /**< Extended Range Color format for single Y10 plane. */
+    cudaEglColorFormatY10_709_ER                   = 99, /**< Extended Range Color format for single Y10 plane. */
+    cudaEglColorFormatY12_ER                       = 100, /**< Extended Range Color format for single Y12 plane. */
+    cudaEglColorFormatY12_709_ER                   = 101, /**< Extended Range Color format for single Y12 plane. */
+    cudaEglColorFormatYUVA                         = 102, /**< Y, U, V, A four channels in one surface, interleaved as AVUY. */
+    cudaEglColorFormatYVYU                         = 104, /**< Y, U, V in one surface, interleaved as YVYU in one channel. */
+    cudaEglColorFormatVYUY                         = 105, /**< Y, U, V in one surface, interleaved as VYUY in one channel. */
+    cudaEglColorFormatY10V10U10_420SemiPlanar_ER     = 106, /**< Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_420SemiPlanar_709_ER = 107, /**< Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY10V10U10_444SemiPlanar_ER     = 108, /**< Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height. */ 
+    cudaEglColorFormatY10V10U10_444SemiPlanar_709_ER = 109, /**< Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatY12V12U12_420SemiPlanar_ER     = 110, /**< Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY12V12U12_420SemiPlanar_709_ER = 111, /**< Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height. */
+    cudaEglColorFormatY12V12U12_444SemiPlanar_ER     = 112, /**< Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height. */
+    cudaEglColorFormatY12V12U12_444SemiPlanar_709_ER = 113, /**< Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height. */
+} cudaEglColorFormat;
+
+/**
+ * CUDA EGL Plane Descriptor - structure defining each plane of a CUDA EGLFrame
+ */
+typedef struct cudaEglPlaneDesc_st {
+    unsigned int width;                         /**< Width of plane */
+    unsigned int height;                        /**< Height of plane */
+    unsigned int depth;                         /**< Depth of plane */
+    unsigned int pitch;                         /**< Pitch of plane */
+    unsigned int numChannels;                   /**< Number of channels for the plane */
+    struct cudaChannelFormatDesc channelDesc;   /**< Channel Format Descriptor */
+    unsigned int reserved[4];                   /**< Reserved for future use */
+} cudaEglPlaneDesc;
+
+/**
+ * CUDA EGLFrame Descriptor - structure defining one frame of EGL.
+ *
+ * Each frame may contain one or more planes depending on whether the surface is Multiplanar or not.
+ * Each plane of EGLFrame is represented by ::cudaEglPlaneDesc which is defined as:
+ * \code
+ * typedef struct cudaEglPlaneDesc_st {
+ *     unsigned int width;
+ *     unsigned int height;
+ *     unsigned int depth;
+ *     unsigned int pitch;
+ *     unsigned int numChannels;
+ *     struct cudaChannelFormatDesc channelDesc;
+ *     unsigned int reserved[4];
+ * } cudaEglPlaneDesc;
+ * \endcode
+
+*/
+typedef struct cudaEglFrame_st {
+   union {
+       cudaArray_t            pArray[CUDA_EGL_MAX_PLANES];     /**< Array of CUDA arrays corresponding to each plane*/
+       struct cudaPitchedPtr  pPitch[CUDA_EGL_MAX_PLANES];     /**< Array of Pointers corresponding to each plane*/
+   } frame;
+   cudaEglPlaneDesc planeDesc[CUDA_EGL_MAX_PLANES];     /**< CUDA EGL Plane Descriptor ::cudaEglPlaneDesc*/
+   unsigned int planeCount;                             /**< Number of planes */
+   cudaEglFrameType frameType;                          /**< Array or Pitch */
+   cudaEglColorFormat eglColorFormat;                   /**< CUDA EGL Color Format*/
+} cudaEglFrame;
+
+/**
+ * CUDA EGLSream Connection
+ */
+typedef struct  CUeglStreamConnection_st *cudaEglStreamConnection;
+
+/** @} */ /* END CUDART_TYPES */
+
+/**
+ * \addtogroup CUDART_EGL EGL Interoperability
+ * This section describes the EGL interoperability functions of the CUDA
+ * runtime application programming interface.
+ *
+ * @{
+ */
+
+/**
+ * \brief Registers an EGL image
+ *
+ * Registers the EGLImageKHR specified by \p image for access by
+ * CUDA. A handle to the registered object is returned as \p pCudaResource.
+ * Additional Mapping/Unmapping is not required for the registered resource and
+ * ::cudaGraphicsResourceGetMappedEglFrame can be directly called on the \p pCudaResource.
+ *
+ * The application will be responsible for synchronizing access to shared objects.
+ * The application must ensure that any pending operation which access the objects have completed
+ * before passing control to CUDA. This may be accomplished by issuing and waiting for
+ * glFinish command on all GLcontexts (for OpenGL and likewise for other APIs).
+ * The application will be also responsible for ensuring that any pending operation on the
+ * registered CUDA resource has completed prior to executing subsequent commands in other APIs
+ * accesing the same memory objects.
+ * This can be accomplished by calling cuCtxSynchronize or cuEventSynchronize (preferably).
+ *
+ * The surface's intended usage is specified using \p flags, as follows:
+ *
+ * - ::cudaGraphicsRegisterFlagsNone: Specifies no hints about how this
+ *   resource will be used. It is therefore assumed that this resource will be
+ *   read from and written to by CUDA. This is the default value.
+ * - ::cudaGraphicsRegisterFlagsReadOnly: Specifies that CUDA
+ *   will not write to this resource.
+ * - ::cudaGraphicsRegisterFlagsWriteDiscard: Specifies that
+ *   CUDA will not read from this resource and will write over the
+ *   entire contents of the resource, so none of the data previously
+ *   stored in the resource will be preserved.
+ *
+ * The EGLImageKHR is an object which can be used to create EGLImage target resource. It is defined as a void pointer.
+ * typedef void* EGLImageKHR
+ *
+ * \param pCudaResource   - Pointer to the returned object handle
+ * \param image           - An EGLImageKHR image which can be used to create target resource.
+ * \param flags           - Map flags
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidResourceHandle,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaGraphicsUnregisterResource,
+ * ::cudaGraphicsResourceGetMappedEglFrame,
+ * ::cuGraphicsEGLRegisterImage
+ */
+extern __host__ cudaError_t CUDARTAPI cudaGraphicsEGLRegisterImage(struct cudaGraphicsResource **pCudaResource, EGLImageKHR image, unsigned int flags);
+
+/**
+ * \brief Connect CUDA to EGLStream as a consumer.
+ *
+ * Connect CUDA as a consumer to EGLStreamKHR specified by \p eglStream.
+ *
+ * The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one
+ * API to another.
+ *
+ * \param conn              - Pointer to the returned connection handle
+ * \param eglStream         - EGLStreamKHR handle
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamConsumerDisconnect,
+ * ::cudaEGLStreamConsumerAcquireFrame,
+ * ::cudaEGLStreamConsumerReleaseFrame,
+ * ::cuEGLStreamConsumerConnect
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamConsumerConnect(cudaEglStreamConnection *conn, EGLStreamKHR eglStream);
+
+/**
+ * \brief Connect CUDA to EGLStream as a consumer with given flags.
+ *
+ * Connect CUDA as a consumer to EGLStreamKHR specified by \p stream with specified \p flags defined by
+ * ::cudaEglResourceLocationFlags.
+ *
+ * The flags specify whether the consumer wants to access frames from system memory or video memory.
+ * Default is ::cudaEglResourceLocationVidmem.
+ *
+ * \param conn              - Pointer to the returned connection handle
+ * \param eglStream         - EGLStreamKHR handle
+ * \param flags             - Flags denote intended location - system or video.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamConsumerDisconnect,
+ * ::cudaEGLStreamConsumerAcquireFrame,
+ * ::cudaEGLStreamConsumerReleaseFrame,
+ * ::cuEGLStreamConsumerConnectWithFlags
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamConsumerConnectWithFlags(cudaEglStreamConnection *conn, EGLStreamKHR eglStream, unsigned int flags);
+
+/**
+ * \brief Disconnect CUDA as a consumer to EGLStream .
+ *
+ * Disconnect CUDA as a consumer to EGLStreamKHR.
+ *
+ * \param conn            - Conection to disconnect.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamConsumerConnect,
+ * ::cudaEGLStreamConsumerAcquireFrame,
+ * ::cudaEGLStreamConsumerReleaseFrame,
+ * ::cuEGLStreamConsumerDisconnect
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamConsumerDisconnect(cudaEglStreamConnection *conn);
+
+/**
+ * \brief Acquire an image frame from the EGLStream with CUDA as a consumer.
+ *
+ * Acquire an image frame from EGLStreamKHR.
+ * ::cudaGraphicsResourceGetMappedEglFrame can be called on \p pCudaResource to get
+ * ::cudaEglFrame.
+ *
+ * \param conn            - Connection on which to acquire
+ * \param pCudaResource   - CUDA resource on which the EGLStream frame will be mapped for use.
+ * \param pStream         - CUDA stream for synchronization and any data migrations
+ * implied by ::cudaEglResourceLocationFlags.
+ * \param timeout         - Desired timeout in usec.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown,
+ * ::cudaErrorLaunchTimeout
+ *
+ * \sa
+ * ::cudaEGLStreamConsumerConnect,
+ * ::cudaEGLStreamConsumerDisconnect,
+ * ::cudaEGLStreamConsumerReleaseFrame,
+ * ::cuEGLStreamConsumerAcquireFrame
+ */
+
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamConsumerAcquireFrame(cudaEglStreamConnection *conn,
+        cudaGraphicsResource_t *pCudaResource, cudaStream_t *pStream, unsigned int timeout);
+/**
+ * \brief Releases the last frame acquired from the EGLStream.
+ *
+ * Release the acquired image frame specified by \p pCudaResource to EGLStreamKHR.
+ *
+ * \param conn            - Connection on which to release
+ * \param pCudaResource   - CUDA resource whose corresponding frame is to be released
+ * \param pStream         - CUDA stream on which release will be done.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamConsumerConnect,
+ * ::cudaEGLStreamConsumerDisconnect,
+ * ::cudaEGLStreamConsumerAcquireFrame,
+ * ::cuEGLStreamConsumerReleaseFrame
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamConsumerReleaseFrame(cudaEglStreamConnection *conn,
+                                                  cudaGraphicsResource_t pCudaResource, cudaStream_t *pStream);
+
+/**
+ * \brief Connect CUDA to EGLStream as a producer.
+ *
+ * Connect CUDA as a producer to EGLStreamKHR specified by \p stream.
+ *
+ * The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one
+ * API to another.
+ *
+ * \param conn   - Pointer to the returned connection handle
+ * \param eglStream - EGLStreamKHR handle
+ * \param width  - width of the image to be submitted to the stream
+ * \param height - height of the image to be submitted to the stream
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamProducerDisconnect,
+ * ::cudaEGLStreamProducerPresentFrame,
+ * ::cudaEGLStreamProducerReturnFrame,
+ * ::cuEGLStreamProducerConnect
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamProducerConnect(cudaEglStreamConnection *conn,
+                                                EGLStreamKHR eglStream, EGLint width, EGLint height);
+
+/**
+ * \brief Disconnect CUDA as a producer  to EGLStream .
+ *
+ * Disconnect CUDA as a producer to EGLStreamKHR.
+ *
+ * \param conn            - Conection to disconnect.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamProducerConnect,
+ * ::cudaEGLStreamProducerPresentFrame,
+ * ::cudaEGLStreamProducerReturnFrame,
+ * ::cuEGLStreamProducerDisconnect
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamProducerDisconnect(cudaEglStreamConnection *conn);
+
+/**
+ * \brief Present a CUDA eglFrame to the EGLStream with CUDA as a producer.
+ *
+ * The ::cudaEglFrame is defined as:
+ * \code
+ * typedef struct cudaEglFrame_st {
+ *     union {
+ *         cudaArray_t            pArray[CUDA_EGL_MAX_PLANES];
+ *         struct cudaPitchedPtr  pPitch[CUDA_EGL_MAX_PLANES];
+ *     } frame;
+ *     cudaEglPlaneDesc planeDesc[CUDA_EGL_MAX_PLANES];
+ *     unsigned int planeCount;
+ *     cudaEglFrameType frameType;
+ *     cudaEglColorFormat eglColorFormat;
+ * } cudaEglFrame;
+ * \endcode
+ *
+ * For ::cudaEglFrame of type ::cudaEglFrameTypePitch, the application may present sub-region of a memory
+ * allocation. In that case, ::cudaPitchedPtr::ptr will specify the start address of the sub-region in
+ * the allocation and ::cudaEglPlaneDesc will specify the dimensions of the sub-region.
+ *
+ * \param conn            - Connection on which to present the CUDA array
+ * \param eglframe        - CUDA Eglstream Proucer Frame handle to be sent to the consumer over EglStream.
+ * \param pStream         - CUDA stream on which to present the frame.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamProducerConnect,
+ * ::cudaEGLStreamProducerDisconnect,
+ * ::cudaEGLStreamProducerReturnFrame,
+ * ::cuEGLStreamProducerPresentFrame
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamProducerPresentFrame(cudaEglStreamConnection *conn,
+                                                 cudaEglFrame eglframe, cudaStream_t *pStream);
+
+/**
+ * \brief Return the CUDA eglFrame to the EGLStream last released by the consumer.
+ * 
+ * This API can potentially return cudaErrorLaunchTimeout if the consumer has not 
+ * returned a frame to EGL stream. If timeout is returned the application can retry.
+ *
+ * \param conn            - Connection on which to present the CUDA array
+ * \param eglframe        - CUDA Eglstream Proucer Frame handle returned from the consumer over EglStream.
+ * \param pStream         - CUDA stream on which to return the frame.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorLaunchTimeout,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \sa
+ * ::cudaEGLStreamProducerConnect,
+ * ::cudaEGLStreamProducerDisconnect,
+ * ::cudaEGLStreamProducerPresentFrame,
+ * ::cuEGLStreamProducerReturnFrame
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEGLStreamProducerReturnFrame(cudaEglStreamConnection *conn,
+                                                cudaEglFrame *eglframe, cudaStream_t *pStream);
+
+/**
+ * \brief Get an eglFrame through which to access a registered EGL graphics resource.
+ *
+ * Returns in \p *eglFrame an eglFrame pointer through which the registered graphics resource
+ * \p resource may be accessed.
+ * This API can only be called for EGL graphics resources.
+ *
+ * The ::cudaEglFrame is defined as
+ * \code
+ * typedef struct cudaEglFrame_st {
+ *     union {
+ *         cudaArray_t             pArray[CUDA_EGL_MAX_PLANES];
+ *         struct cudaPitchedPtr   pPitch[CUDA_EGL_MAX_PLANES];
+ *     } frame;
+ *     cudaEglPlaneDesc planeDesc[CUDA_EGL_MAX_PLANES];
+ *     unsigned int planeCount;
+ *     cudaEglFrameType frameType;
+ *     cudaEglColorFormat eglColorFormat;
+ * } cudaEglFrame;
+ * \endcode
+ *
+ *
+ * \param eglFrame   - Returned eglFrame.
+ * \param resource   - Registered resource to access.
+ * \param index      - Index for cubemap surfaces.
+ * \param mipLevel   - Mipmap level for the subresource to access.
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorUnknown
+ *
+ * \note Note that in case of multiplanar \p *eglFrame, pitch of only first plane (unsigned int cudaEglPlaneDesc::pitch) is to be considered by the application.
+ *
+ * \sa
+ * ::cudaGraphicsSubResourceGetMappedArray,
+ * ::cudaGraphicsResourceGetMappedPointer,
+ * ::cuGraphicsResourceGetMappedEglFrame
+ */
+extern __host__ cudaError_t CUDARTAPI cudaGraphicsResourceGetMappedEglFrame(cudaEglFrame* eglFrame,
+                                        cudaGraphicsResource_t resource, unsigned int index, unsigned int mipLevel);
+
+/**
+ * \brief Creates an event from EGLSync object
+ *
+ * Creates an event *phEvent from an EGLSyncKHR eglSync with the flages specified
+ * via \p flags. Valid flags include:
+ * - ::cudaEventDefault: Default event creation flag.
+ * - ::cudaEventBlockingSync: Specifies that the created event should use blocking
+ * synchronization.  A CPU thread that uses ::cudaEventSynchronize() to wait on
+ * an event created with this flag will block until the event has actually
+ * been completed.
+ *
+ * ::cudaEventRecord and TimingData are not supported for events created from EGLSync.
+ *
+ * The EGLSyncKHR is an opaque handle to an EGL sync object.
+ * typedef void* EGLSyncKHR
+ *
+ * \param phEvent - Returns newly created event
+ * \param eglSync - Opaque handle to EGLSync object
+ * \param flags   - Event creation flags
+ *
+ * \return
+ * ::cudaSuccess,
+ * ::cudaErrorInitializationError,
+ * ::cudaErrorInvalidValue,
+ * ::cudaErrorLaunchFailure,
+ * ::cudaErrorMemoryAllocation
+ *
+ * \sa
+ * ::cudaEventQuery,
+ * ::cudaEventSynchronize,
+ * ::cudaEventDestroy
+ */
+extern __host__ cudaError_t CUDARTAPI cudaEventCreateFromEGLSync(cudaEvent_t *phEvent, EGLSyncKHR eglSync, unsigned int flags);
+
+/** @} */ /* END CUDART_EGL */
+
+#if defined(__cplusplus)
+}
+#endif /* __cplusplus */
+
+#endif /* __CUDA_EGL_INTEROP_H__ */
+
diff --git a/shared/package-files/3c/3cdc3b46462101e778756bd03d4b4a9199605c9015ad4815c8d72890f00d8e1b/upsample_bicubic2d_backward.h b/shared/package-files/3c/3cdc3b46462101e778756bd03d4b4a9199605c9015ad4815c8d72890f00d8e1b/upsample_bicubic2d_backward.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad1ee462d12ed92b5d32d1a6b043022c7c9fadb7
--- /dev/null
+++ b/shared/package-files/3c/3cdc3b46462101e778756bd03d4b4a9199605c9015ad4815c8d72890f00d8e1b/upsample_bicubic2d_backward.h
@@ -0,0 +1,92 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+inline at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);
+}
+namespace symint {
+  template >>
+  at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);
+  }
+}
+
+// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+inline at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);
+}
+namespace symint {
+  template >>
+  at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);
+  }
+}
+
+// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+inline at::Tensor & upsample_bicubic2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);
+}
+namespace symint {
+  template >>
+  at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);
+  }
+}
+
+// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+inline at::Tensor & upsample_bicubic2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);
+}
+namespace symint {
+  template >>
+  at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input) {
+    return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);
+  }
+}
+
+// aten::upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+inline at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w);
+}
+namespace symint {
+  template >>
+  at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w);
+  }
+}
+
+// aten::upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+inline at::Tensor upsample_bicubic2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w);
+}
+namespace symint {
+  template >>
+  at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) {
+    return at::_ops::upsample_bicubic2d_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w);
+  }
+}
+
+}
diff --git a/shared/package-files/3c/3cdeb2f3e3bc2dccef6b62e9104ba03c35c89f277216299e73f6a64d9667dd65/mm_native.h b/shared/package-files/3c/3cdeb2f3e3bc2dccef6b62e9104ba03c35c89f277216299e73f6a64d9667dd65/mm_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..846c8432eb5270e4c4c369502e20a51640a395a9
--- /dev/null
+++ b/shared/package-files/3c/3cdeb2f3e3bc2dccef6b62e9104ba03c35c89f277216299e73f6a64d9667dd65/mm_native.h
@@ -0,0 +1,30 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_mm_out_cpu : public at::meta::structured_mm {
+void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
+};
+struct TORCH_API structured_mm_out_cuda : public at::meta::structured_mm {
+void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
+};
+TORCH_API at::Tensor _sparse_mm(const at::Tensor & self, const at::Tensor & mat2);
+TORCH_API at::Tensor & _sparse_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
+TORCH_API at::Tensor _sparse_csr_mm(const at::Tensor & self, const at::Tensor & mat2);
+TORCH_API at::Tensor & _sparse_csr_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/3c/3ce2ba6019da72a7222cddd34e2a3aa9da8a6556dad35dbdc6589bd5c092271a/_foreach_maximum.h b/shared/package-files/3c/3ce2ba6019da72a7222cddd34e2a3aa9da8a6556dad35dbdc6589bd5c092271a/_foreach_maximum.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b057b1cd09b97430e930eb839fb67bcf96fc2dc
--- /dev/null
+++ b/shared/package-files/3c/3ce2ba6019da72a7222cddd34e2a3aa9da8a6556dad35dbdc6589bd5c092271a/_foreach_maximum.h
@@ -0,0 +1,83 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+inline ::std::vector _foreach_maximum(at::TensorList self, const at::Scalar & scalar) {
+    return at::_ops::_foreach_maximum_Scalar::call(self, scalar);
+}
+
+// aten::_foreach_maximum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+inline void _foreach_maximum_(at::TensorList self, const at::Scalar & scalar) {
+    return at::_ops::_foreach_maximum__Scalar::call(self, scalar);
+}
+
+// aten::_foreach_maximum.List(Tensor[] self, Tensor[] other) -> Tensor[]
+inline ::std::vector _foreach_maximum(at::TensorList self, at::TensorList other) {
+    return at::_ops::_foreach_maximum_List::call(self, other);
+}
+
+// aten::_foreach_maximum_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+inline void _foreach_maximum_(at::TensorList self, at::TensorList other) {
+    return at::_ops::_foreach_maximum__List::call(self, other);
+}
+
+// aten::_foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+inline ::std::vector _foreach_maximum(at::TensorList self, at::ArrayRef scalars) {
+    return at::_ops::_foreach_maximum_ScalarList::call(self, scalars);
+}
+
+// aten::_foreach_maximum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+inline void _foreach_maximum_(at::TensorList self, at::ArrayRef scalars) {
+    return at::_ops::_foreach_maximum__ScalarList::call(self, scalars);
+}
+
+// aten::_foreach_maximum.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar) {
+    return at::_ops::_foreach_maximum_Scalar_out::call(self, scalar, out);
+}
+// aten::_foreach_maximum.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out) {
+    return at::_ops::_foreach_maximum_Scalar_out::call(self, scalar, out);
+}
+
+// aten::_foreach_maximum.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_out(at::TensorList out, at::TensorList self, at::TensorList other) {
+    return at::_ops::_foreach_maximum_List_out::call(self, other, out);
+}
+// aten::_foreach_maximum.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_outf(at::TensorList self, at::TensorList other, at::TensorList out) {
+    return at::_ops::_foreach_maximum_List_out::call(self, other, out);
+}
+
+// aten::_foreach_maximum.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_out(at::TensorList out, at::TensorList self, at::ArrayRef scalars) {
+    return at::_ops::_foreach_maximum_ScalarList_out::call(self, scalars, out);
+}
+// aten::_foreach_maximum.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()
+inline void _foreach_maximum_outf(at::TensorList self, at::ArrayRef scalars, at::TensorList out) {
+    return at::_ops::_foreach_maximum_ScalarList_out::call(self, scalars, out);
+}
+
+}
diff --git a/shared/package-files/3c/3ce3b871676fba383b5500b397d6c6be604714ad37b34bdf0d52c5e912938a0e/placement_types.py b/shared/package-files/3c/3ce3b871676fba383b5500b397d6c6be604714ad37b34bdf0d52c5e912938a0e/placement_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceb9f170fd3e634c3ac7982777110253af339234
--- /dev/null
+++ b/shared/package-files/3c/3ce3b871676fba383b5500b397d6c6be604714ad37b34bdf0d52c5e912938a0e/placement_types.py
@@ -0,0 +1,675 @@
+# mypy: allow-untyped-defs
+# Copyright (c) Meta Platforms, Inc. and affiliates
+
+from dataclasses import dataclass
+from typing import cast, Optional
+
+import torch
+import torch.distributed._functional_collectives as funcol
+from torch.distributed.device_mesh import DeviceMesh
+from torch.distributed.tensor._collective_utils import (
+    fill_empty_tensor_to_shards,
+    mesh_broadcast,
+    mesh_scatter,
+    pad_tensor,
+    shard_dim_alltoall,
+    unpad_tensor,
+)
+
+
+__all__ = ["Placement", "Shard", "Replicate", "Partial"]
+
+
+class Placement:
+    """
+    The base class for the Placement type, where it describes how a DTensor is placed onto the
+    ``DeviceMesh``. ``Placement`` and ``DeviceMesh`` together could describe the DTensor Layout.
+    It is the base class of the three main DTensor Placement types: ``Shard``, ``Replicate``,
+    and ``Partial``.
+
+    This class is not meant to be used directly, mainly served as a typing stub.
+    """
+
+    # convenient utils to check for placement types
+    def is_shard(self, dim: Optional[int] = None) -> bool:
+        is_shard_instance = isinstance(self, Shard)
+        if dim is not None and is_shard_instance:
+            return cast(Shard, self).dim == dim
+        else:
+            return is_shard_instance
+
+    def is_replicate(self) -> bool:
+        return isinstance(self, Replicate)
+
+    def is_partial(self) -> bool:
+        return isinstance(self, Partial)
+
+
+@dataclass(frozen=True)
+class Shard(Placement):
+    """
+    The ``Shard(dim)`` placement describes the DTensor sharding on tensor dimension
+    ``dim`` over a corresponding ``DeviceMesh`` dimension, where each rank on the
+    DeviceMesh dimension only holds a shard/piece of the global Tensor. The
+    ``Shard(dim)`` placement follows the ``torch.chunk(dim)`` semantic, where the
+    last few shards on the DeviceMesh dimension might be empty when the tensor dimension
+    is not evenly divisible on the DeviceMesh dimension. The ``Shard`` placement can be
+    used by all DTensor APIs (i.e. distribute_tensor, from_local, etc.)
+
+    Args:
+        dim (int): The tensor dimension that describes the DTensor is sharded over its
+            corresponding DeviceMesh dimension.
+
+    .. warning:: sharding on a tensor dimension where the tensor dimension size is not
+        evenly divisible on a DeviceMesh dimension is currently experimental and subject to change.
+    """
+
+    dim: int
+
+    def _split_tensor(
+        self,
+        tensor: torch.Tensor,
+        num_chunks: int,
+        *,
+        with_padding: bool = True,
+        contiguous: bool = True,
+    ) -> tuple[list[torch.Tensor], list[int]]:
+        """
+        This function uses torch.chunk to split a tensor into num_chunks shards along
+        the Shard placement dimension, and return a list of shards with their pad sizes.
+
+        Keyword args:
+            with_padding (bool, optional): when True, we pad the tensor on the last
+            few ranks before calling the collectives (i.e. scatter/all_gather, etc.).
+            This is because collectives usually require equal size tensor inputs
+        """
+        assert self.dim <= tensor.ndim, (
+            f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
+        )
+
+        # chunk tensor over dimension `dim` into n slices
+        tensor_list = list(torch.chunk(tensor, num_chunks, dim=self.dim))
+        num_empty_tensors = num_chunks - len(tensor_list)
+
+        # if no need to have padding or tensor dim size is evenly sharded already
+        # we can return early.
+        if not with_padding or tensor.size(self.dim) % num_chunks == 0:
+            if contiguous:
+                tensor_list = [t.contiguous() for t in tensor_list]
+            return (
+                fill_empty_tensor_to_shards(tensor_list, self.dim, num_empty_tensors),
+                [],
+            )
+
+        # compute the chunk size inline with ``torch.chunk`` to calculate padding
+        full_chunk_size = (tensor.size(self.dim) + num_chunks - 1) // num_chunks
+
+        # Compute chunk size for each chunk for ``self.dim``
+        chunk_sizes = [
+            tensor_list[idx].size(self.dim) if idx < len(tensor_list) else 0
+            for idx in range(num_chunks)
+        ]
+        # Compute pad size on each chunk
+        pad_sizes = [full_chunk_size - chunk_size for chunk_size in chunk_sizes]
+
+        # Reuse tensor to fill empty chunk with empty tensor
+        tensor_list = fill_empty_tensor_to_shards(
+            tensor_list, self.dim, num_empty_tensors
+        )
+        shard_list = []
+        for shard, pad_size in zip(tensor_list, pad_sizes):
+            # Fill the empty tensor with zeroes with padding.
+            if with_padding and pad_size > 0:
+                shard = pad_tensor(shard, self.dim, pad_size)
+            shard = shard.contiguous() if contiguous else shard
+            shard_list.append(shard)
+        return shard_list, pad_sizes
+
+    @staticmethod
+    def _local_shard_size_on_dim(
+        size_on_dim: int,
+        num_chunks: int,
+        rank: int,
+        return_offset: bool = False,
+    ) -> tuple[int, int]:
+        """
+        returns the local shard size and offset on a given tensor dim
+        """
+        # Compute the chunk size inline with ``torch.chunk``
+        if size_on_dim % num_chunks == 0:
+            full_chunk_size = size_on_dim // num_chunks
+            return full_chunk_size, full_chunk_size * rank if return_offset else -1
+
+        # uneven sharding case
+        full_chunk_size = (size_on_dim + num_chunks - 1) // num_chunks
+        shard_starting_idx = full_chunk_size * rank
+
+        if size_on_dim < shard_starting_idx:
+            return 0, size_on_dim if return_offset else -1
+        else:
+            local_shard_size = (
+                min(size_on_dim, shard_starting_idx + full_chunk_size)
+                - shard_starting_idx
+            )
+            return local_shard_size, shard_starting_idx if return_offset else -1
+
+    def _shard_tensor(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        src_data_rank: Optional[int] = 0,
+    ) -> torch.Tensor:
+        """
+        shard and scatter a tensor on a mesh dimension (use coordinate
+        0 on the mesh dimension as source of truth)
+        """
+        my_coordinate = mesh.get_coordinate()
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return an empty tensor
+            return tensor.new_empty(0, requires_grad=tensor.requires_grad)
+
+        mesh_dim_local_rank = my_coordinate[mesh_dim]
+
+        if src_data_rank is None:
+            # src_data_rank specified as None explicitly means to skip the
+            # communications, simply split
+            scatter_list, _ = self._split_tensor(
+                tensor, num_chunks, with_padding=False, contiguous=True
+            )
+
+            return scatter_list[mesh_dim_local_rank]
+
+        scatter_list, pad_sizes = self._split_tensor(
+            tensor, num_chunks, with_padding=True, contiguous=True
+        )
+        output = torch.empty_like(scatter_list[mesh_dim_local_rank])
+        # perform scatter from the src_data_rank as data source when it is not None
+        mesh_scatter(
+            output, scatter_list, mesh, mesh_dim=mesh_dim, group_src=src_data_rank
+        )
+
+        # Only unpad if the local_tensor was padded on the dimension.
+        if pad_sizes and pad_sizes[mesh_dim_local_rank] > 0:
+            output = unpad_tensor(output, self.dim, pad_sizes[mesh_dim_local_rank])
+        return output
+
+    def _reduce_shard_tensor(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        reduce_op: str,
+        mesh_dim: int,
+    ) -> torch.Tensor:
+        """
+        reduce and scatter a tensor on a mesh dimension
+        """
+        my_coordinate = mesh.get_coordinate()
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return local_tensor,
+            # which should be an empty tensor
+            return tensor
+
+        is_padded = tensor.size(self.dim) % num_chunks != 0
+        if is_padded:
+            scattered_list, pad_sizes = self._split_tensor(
+                tensor, num_chunks, with_padding=True, contiguous=True
+            )
+            tensor = torch.cat(scattered_list, dim=self.dim)
+        elif not tensor.is_contiguous():
+            tensor = tensor.contiguous()
+
+        output = funcol.reduce_scatter_tensor(
+            tensor, reduce_op, scatter_dim=self.dim, group=(mesh, mesh_dim)
+        )
+
+        if is_padded:
+            output = unpad_tensor(output, self.dim, pad_sizes[my_coordinate[mesh_dim]])  # type: ignore[possibly-undefined]
+        return output
+
+    def _to_replicate_tensor(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: list[int],
+    ) -> torch.Tensor:
+        """
+        This function all_gather all shards and return a tensor that
+        is replicated on the previously sharded mesh dimension
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        # check if it's uneven, so we need to pad input tensor before all_gather
+        local_shape = list(local_tensor.size())
+
+        logical_dim_size = current_logical_shape[self.dim]
+        is_padded = logical_dim_size % num_chunks != 0
+
+        if is_padded:
+            full_chunk_size = (logical_dim_size + num_chunks - 1) // num_chunks
+            pad_size = full_chunk_size - local_shape[self.dim]
+            local_tensor = pad_tensor(local_tensor, self.dim, pad_size)
+
+        if not local_tensor.is_contiguous():
+            local_tensor = local_tensor.contiguous()
+
+        result = funcol.all_gather_tensor(
+            local_tensor,
+            gather_dim=self.dim,
+            group=(mesh, mesh_dim),
+        )
+        if is_padded:
+            unpad_size = full_chunk_size * num_chunks - logical_dim_size  # type: ignore[possibly-undefined]
+            result = unpad_tensor(result, self.dim, unpad_size)
+        return result
+
+    def _replicate_to_shard(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_index: int,
+    ) -> torch.Tensor:
+        """
+        transform from replicated tensor to a sharded tensor on
+        the current rank, which would perform a local chunk
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        shards, _ = self._split_tensor(
+            local_tensor,
+            num_chunks,
+            with_padding=False,
+            contiguous=False,
+        )
+        return shards[shard_index].clone()
+
+    def _to_new_shard_dim(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: list[int],
+        new_shard_dim: int,
+    ) -> torch.Tensor:
+        """
+        transform from existing sharded tensor to a new sharded tensor on
+        that shard on a new dimension, which performs an alltoall
+        """
+        my_coordinate = mesh.get_coordinate()
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return local_tensor,
+            # which should be an empty tensor
+            return local_tensor
+
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+
+        old_dim_logical_size = current_logical_shape[self.dim]
+        new_dim_logical_size = current_logical_shape[new_shard_dim]
+        old_dim_padding = old_dim_logical_size % num_chunks != 0
+        new_dim_padding = new_dim_logical_size % num_chunks != 0
+        if old_dim_padding:
+            old_dim_full_chunk_size = (
+                old_dim_logical_size + num_chunks - 1
+            ) // num_chunks
+            old_dim_pad_size = old_dim_full_chunk_size - local_tensor.size(self.dim)
+            local_tensor = pad_tensor(local_tensor, self.dim, old_dim_pad_size)
+        if new_dim_padding:
+            new_dim_full_chunk_size = (
+                new_dim_logical_size + num_chunks - 1
+            ) // num_chunks
+            new_dim_pad_size = new_dim_full_chunk_size * num_chunks - local_tensor.size(
+                new_shard_dim
+            )
+            local_tensor = pad_tensor(local_tensor, new_shard_dim, new_dim_pad_size)
+
+        if not local_tensor.is_contiguous():
+            local_tensor = local_tensor.contiguous()
+
+        new_tensor = shard_dim_alltoall(
+            local_tensor, self.dim, new_shard_dim, mesh, mesh_dim
+        )
+
+        if old_dim_padding:
+            old_dim_unpad_size = (
+                old_dim_full_chunk_size * num_chunks - current_logical_shape[self.dim]  # type: ignore[possibly-undefined]
+            )
+            new_tensor = unpad_tensor(new_tensor, self.dim, old_dim_unpad_size)  # type: ignore[possibly-undefined]
+
+        if new_dim_padding:
+            local_shard_size_on_new_dim = self._local_shard_size_on_dim(
+                new_dim_logical_size, num_chunks, my_coordinate[mesh_dim]
+            )[0]
+            new_dim_unpad_size = new_dim_full_chunk_size - local_shard_size_on_new_dim  # type: ignore[possibly-undefined]
+            new_tensor = unpad_tensor(new_tensor, new_shard_dim, new_dim_unpad_size)  # type: ignore[possibly-undefined]
+
+        return new_tensor
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Shard):
+            return False
+        return self.dim == other.dim
+
+    def __hash__(self) -> int:
+        return hash(self.dim)
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Shard placement
+        """
+        return f"Shard(dim={self.dim})"
+
+    def __str__(self) -> str:
+        """human readable representation of the Shard placement"""
+        return f"S({self.dim})"
+
+
+# kw_only is only available in python >= 3.10
+kw_only_dataclass = dict(kw_only=True) if "kw_only" in dataclass.__kwdefaults__ else {}
+
+
+@dataclass(frozen=True, **kw_only_dataclass)
+class _StridedShard(Shard):
+    """
+    _StridedShard is only introduced to support 2D FSDP2 + TP sharding where the tensor
+    is sharded on the TP mesh dimension first, then sharded on the FSDP mesh dimension.
+    We call this right-to-left sharding which is the opposite of the default
+    left-to-right sharding. See the example below:
+        tensor shape: [8, 8]
+        mesh: [[0, 1], [2, 3]], names=("dp", "tp")
+        placements: [Shard(0), Shard(0)]
+
+    The default sharding behavior shards the tensor on "dp" mesh dimension first then
+    "tp" dimension. The sharding result will be:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   1 (row 2-3)
+        2       |   (1, 0)          |   2 (row 4-5)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    While the FSDP2 + TP sharding behavior does the opposite: it shards the tensor on
+    "tp" mesh dim first then "dp" dim. This right-to-left sharding will produce the
+    result:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   2 (row 4-5)
+        2       |   (1, 0)          |   1 (row 2-3)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    The consequence is, any attempt to redistribute this DTensor to a full replica will
+    produce a wrong result because the shard-to-replicate redistribution always happens
+    right-to-left, regardless it's left-to-right sharding or right-to-left. To address
+    this, we use _StridedShard placement to make this right-to-left sharding compatible
+    with our left-to-right convention on both tensor distribution and redistribution.
+
+    Now with _StridedShard, the right-to-left sharding above can be represented as:
+        tensor shape: [8, 8]
+        mesh: [[0, 1], [2, 3]], names=("dp", "tp")
+        placements: [_StridedShard(0, split_factor=2), Shard(0)]
+
+    And a left-to-right processing of `placements` will produce the same result, which is
+    different from using the `Shard` placement:
+        Rank    |   Mesh Coordinate |   Shard Index
+        ------------------------------------------------
+        0       |   (0, 0)          |   0 (row 0-1)
+        1       |   (0, 1)          |   2 (row 4-5)
+        2       |   (1, 0)          |   1 (row 2-3)
+        3       |   (1, 1)          |   3 (row 6-7)
+
+    The argument `split_factor` is the number of existing shards over the tensor sharding
+    dimension before processing the _StridedShard placement, as if the sharding happened
+    right-to-left. In the example above, the tensor should first be sharded on the "tp"
+    dimension into 2 shards before being sharded on the "dp" dimension. Therefore, the
+    `split_factor` of the _StridedShard placement on "dp" dim is 2.
+
+    TODO: strided sharding needs to work fine with uneven sharding. Now it forbids
+    resharding if the tensor is unevenly sharded.
+    TODO: we should remove _StridedShard placement once we can unify it with Shard
+    """
+
+    split_factor: int
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, _StridedShard):
+            return self.dim == other.dim and self.split_factor == other.split_factor
+        elif isinstance(other, Shard):
+            # TODO: this is to avoid extra all-gather in dtensor op dispatch
+            # note that sharding prop would not produce _StridedShard and an
+            # placement inequality would introduce an all-gather for resharding
+            return self.dim == other.dim
+        return False
+
+    def __hash__(self) -> int:
+        return hash((self.dim, self.split_factor))
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the _StridedShard placement
+        """
+        return f"_StridedShard(dim={self.dim}, sf={self.split_factor})"
+
+    def __str__(self) -> str:
+        """human readable representation of the _StridedShard placement"""
+        return f"_S({self.dim}, {self.split_factor})"
+
+    def _split_tensor(
+        self,
+        tensor: torch.Tensor,
+        num_chunks: int,
+        *,
+        with_padding: bool = True,
+        contiguous: bool = True,
+    ) -> tuple[list[torch.Tensor], list[int]]:
+        """
+        TODO: currently _StridedShard does not support padding
+        """
+        assert self.dim <= tensor.ndim, (
+            f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
+        )
+
+        total_split = num_chunks * self.split_factor
+        assert tensor.size(self.dim) % total_split == 0, (
+            "_StridedShard currently only allows even sharding but got tensor size"
+            f" {tensor.size(self.dim)} on dim {self.dim} and total split"
+            f" {total_split}={num_chunks} * {self.split_factor}"
+        )
+
+        group_size = self.split_factor
+        total_split_tensor_list = list(torch.chunk(tensor, total_split, dim=self.dim))
+        tensor_list = [
+            torch.cat(
+                [
+                    total_split_tensor_list[i + j * num_chunks]  # stride is num_chunks
+                    for j in range(group_size)
+                ],
+                dim=self.dim,
+            )
+            for i in range(num_chunks)
+        ]
+
+        if contiguous:
+            tensor_list = [t.contiguous() for t in tensor_list]
+
+        return tensor_list, []
+
+    def _to_replicate_tensor(
+        self,
+        local_tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        current_logical_shape: list[int],
+    ) -> torch.Tensor:
+        """
+        Note: currently _StridedShard does not support padding
+        """
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        total_split = num_chunks * self.split_factor
+        # NOTE: we require Strided Sharding to be even for now
+        assert current_logical_shape[self.dim] % total_split == 0, (
+            "_StridedShard requires even sharding but got tensor size "
+            f"{current_logical_shape[self.dim]} on dim {self.dim} and "
+            f"total split {total_split}=num_chunks {num_chunks} "
+            f"* split_factor {self.split_factor}"
+        )
+
+        result = funcol.all_gather_tensor(
+            local_tensor,
+            gather_dim=self.dim,
+            group=(mesh, mesh_dim),
+        )
+        if isinstance(result, funcol.AsyncCollectiveTensor):
+            result = result.wait()
+
+        tensor_shard_list = torch.chunk(result, total_split, dim=self.dim)
+        # rearrange the order
+        new_tensor_shard_list = []
+        for idx in range(len(tensor_shard_list)):
+            # the shard split of index `idx` is assigned a new index within
+            # _StridedShard._split_tensor:
+            # the original tensor was split into `total_split` chunks,
+            # all chunks with the same `idx % num_chunks` are merged into one
+            # new shard and placed on mesh's local rank `idx % num_chunks`
+            idx_after_split = idx % num_chunks * self.split_factor + idx // num_chunks
+            new_tensor_shard_list.append(tensor_shard_list[idx_after_split])
+
+        return torch.cat(new_tensor_shard_list, dim=self.dim).contiguous()
+
+
+@dataclass(frozen=True)
+class Replicate(Placement):
+    """
+    The ``Replicate()`` placement describes the DTensor replicating on a corresponding
+    ``DeviceMesh`` dimension, where each rank on the DeviceMesh dimension holds a
+    replica of the global Tensor. The ``Replicate`` placement can be used by all
+    DTensor APIs (i.e. ``distribute_tensor``, ``DTensor.from_local``, etc.)
+    """
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, Replicate)
+
+    def __hash__(self) -> int:
+        # every replicate placement is the same
+        return -1
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Replicate placement
+        """
+        return "Replicate()"
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the Replicate placement
+        """
+        return "R"
+
+    def _replicate_tensor(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        src_data_rank: Optional[int] = 0,
+    ) -> torch.Tensor:
+        """
+        Replicate (broadcast) a torch.Tensor on a mesh dimension (use
+        the first coordinate on the mesh dimension as source of truth)
+        """
+        my_coordinate = mesh.get_coordinate()
+        if my_coordinate is None:
+            # if rank is not part of mesh, we simply return an empty tensor
+            return tensor.new_empty(0, requires_grad=tensor.requires_grad)
+
+        tensor = tensor.contiguous()
+
+        if src_data_rank is not None:
+            # perform broadcast from the src_data_rank as data source when it is not None
+            mesh_broadcast(tensor, mesh, mesh_dim=mesh_dim, group_src=src_data_rank)
+        return tensor
+
+
+@dataclass(frozen=True)
+class Partial(Placement):
+    """
+    The ``Partial(reduce_op)`` placement describes the DTensor that is pending
+    reduction on a specified ``DeviceMesh`` dimension, where each rank on the
+    DeviceMesh dimension holds the partial value of the global Tensor. User can
+    redistribute the ``Partial`` DTensor to a ``Replicate`` or ``Shard(dim)``
+    placement on the specified ``DeviceMesh`` dimension using ``redistribute``,
+    which would trigger necessary communication operations under the hood (i.e.
+    ``allreduce``, ``reduce_scatter``).
+
+    Args:
+        reduce_op (str, optional): The reduction op to be used for the partial DTensor
+            to produce Replicated/Sharded DTensor. Only element-wise reduction operations
+            are supported, including: "sum", "avg", "product", "max", "min", default: "sum".
+
+    .. note:: The ``Partial`` placement can be generated as a result of the DTensor operators,
+        and can only be used by the ``DTensor.from_local`` API.
+    """
+
+    reduce_op: str = "sum"
+
+    def _reduce_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # Partial placement contract #1:
+        # _reduce_value: reduce the value of the tensor on the mesh dimension
+        return funcol.all_reduce(
+            tensor, reduceOp=self.reduce_op, group=(mesh, mesh_dim)
+        )
+
+    def _reduce_shard_value(
+        self,
+        tensor: torch.Tensor,
+        mesh: DeviceMesh,
+        mesh_dim: int,
+        shard_spec: Placement,
+    ) -> torch.Tensor:
+        # Partial placement contract #2:
+        # _reduce_shard_value: reduce_scatter the value of the tensor over the mesh dimension
+        shard_spec = cast(Shard, shard_spec)
+        return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim)
+
+    def _partition_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # Partial placement contract #3:
+        # _partition_value: partition the value of a replicated tensor on the mesh dimension
+
+        # _partition_value is the conjugate operation of _reduce_value
+        # - i.e. _partition_value on a sum reduce op is just a divison operation
+        # - the _reduce_value on a sum reduce op would just be a sum(allreduce) operation
+        # TODO: if the reduce_op is min/max, etc. the _partition_value should be a
+        # different operation
+        assert self.reduce_op == "sum", "only support replicate to PartialSUM for now!"
+        num_chunks = mesh.size(mesh_dim=mesh_dim)
+        return tensor / num_chunks
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Partial):
+            return False
+        return self.reduce_op == other.reduce_op
+
+    def __hash__(self) -> int:
+        return 1 + hash(self.reduce_op)
+
+    def __repr__(self) -> str:
+        """
+        machine readable representation of the Partial placement
+        """
+        return f"Partial({self.reduce_op})"
+
+    def __str__(self) -> str:
+        """
+        human readable representation of the Partial placement
+        """
+        return "P"
+
+
+# We keep the old _Partial name for a while for BC reason
+_Partial = Partial
diff --git a/shared/package-files/3c/3ce3b9e2c672c0ebdba44a6f5e91544c832d9cd2fb7d9917d483019e89363642/_foreach_log2.h b/shared/package-files/3c/3ce3b9e2c672c0ebdba44a6f5e91544c832d9cd2fb7d9917d483019e89363642/_foreach_log2.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0cf1ac4ff1fce8ec894f53bcd70e4ade8e562d2
--- /dev/null
+++ b/shared/package-files/3c/3ce3b9e2c672c0ebdba44a6f5e91544c832d9cd2fb7d9917d483019e89363642/_foreach_log2.h
@@ -0,0 +1,45 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_foreach_log2(Tensor[] self) -> Tensor[]
+inline ::std::vector _foreach_log2(at::TensorList self) {
+    return at::_ops::_foreach_log2::call(self);
+}
+
+// aten::_foreach_log2_(Tensor(a!)[] self) -> ()
+inline void _foreach_log2_(at::TensorList self) {
+    return at::_ops::_foreach_log2_::call(self);
+}
+
+// aten::_foreach_log2.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
+inline void _foreach_log2_out(at::TensorList out, at::TensorList self) {
+    return at::_ops::_foreach_log2_out::call(self, out);
+}
+// aten::_foreach_log2.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
+inline void _foreach_log2_outf(at::TensorList self, at::TensorList out) {
+    return at::_ops::_foreach_log2_out::call(self, out);
+}
+
+}
diff --git a/shared/package-files/3c/3cec01539fa408e20c82f8ff0bd6ed19b89d9a687c8f1d2a1b1079937ea50d19/__init__.cpython-311.pyc b/shared/package-files/3c/3cec01539fa408e20c82f8ff0bd6ed19b89d9a687c8f1d2a1b1079937ea50d19/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3de396e272bc483e64ee8d3eaabc44147e07105e
Binary files /dev/null and b/shared/package-files/3c/3cec01539fa408e20c82f8ff0bd6ed19b89d9a687c8f1d2a1b1079937ea50d19/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cf09a3e31f78174e8a72824dd7df5a8256335b342966f2ba2f378f5327e7e65/run_cpu.cpython-311.pyc b/shared/package-files/3c/3cf09a3e31f78174e8a72824dd7df5a8256335b342966f2ba2f378f5327e7e65/run_cpu.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0faa0ac05d94c1aefa613dcf14d7473207054fb6
Binary files /dev/null and b/shared/package-files/3c/3cf09a3e31f78174e8a72824dd7df5a8256335b342966f2ba2f378f5327e7e65/run_cpu.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cf3b7ea75b09322df0c3aeb17a5be147dd26e8731f4130f909b28deabdcc477/_nested_from_padded_and_nested_example_ops.h b/shared/package-files/3c/3cf3b7ea75b09322df0c3aeb17a5be147dd26e8731f4130f909b28deabdcc477/_nested_from_padded_and_nested_example_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..1f6df6895b626a227252e6c4c5395f38de68f1ae
--- /dev/null
+++ b/shared/package-files/3c/3cf3b7ea75b09322df0c3aeb17a5be147dd26e8731f4130f909b28deabdcc477/_nested_from_padded_and_nested_example_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _nested_from_padded_and_nested_example {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_nested_from_padded_and_nested_example";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_nested_from_padded_and_nested_example(Tensor padded, Tensor nt_example) -> Tensor";
+  static at::Tensor call(const at::Tensor & padded, const at::Tensor & nt_example);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & padded, const at::Tensor & nt_example);
+};
+
+struct TORCH_API _nested_from_padded_and_nested_example_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_nested_from_padded_and_nested_example";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "_nested_from_padded_and_nested_example.out(Tensor padded, Tensor nt_example, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & padded, const at::Tensor & nt_example, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & padded, const at::Tensor & nt_example, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/3c/3cf63b379a2e9e1b0a0fcc910c18dc604bbd1d255649d8b822e7ca3f7ce9fee4/approximations.cpython-311.pyc b/shared/package-files/3c/3cf63b379a2e9e1b0a0fcc910c18dc604bbd1d255649d8b822e7ca3f7ce9fee4/approximations.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1913e15417730b3b645c449ee3f306876629d4d1
Binary files /dev/null and b/shared/package-files/3c/3cf63b379a2e9e1b0a0fcc910c18dc604bbd1d255649d8b822e7ca3f7ce9fee4/approximations.cpython-311.pyc differ
diff --git a/shared/package-files/3c/3cf7c3a179d817b23b8b8568211769fefdf93797d207d984b8b2fa24d0220b33/LICENSE.txt b/shared/package-files/3c/3cf7c3a179d817b23b8b8568211769fefdf93797d207d984b8b2fa24d0220b33/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0bf9a8f3f4922a0b70aac95ac7aab9574975342b
--- /dev/null
+++ b/shared/package-files/3c/3cf7c3a179d817b23b8b8568211769fefdf93797d207d984b8b2fa24d0220b33/LICENSE.txt
@@ -0,0 +1,37 @@
+NetworkX is distributed with the 3-clause BSD license.
+
+::
+
+   Copyright (c) 2004-2025, NetworkX Developers
+   Aric Hagberg 
+   Dan Schult 
+   Pieter Swart 
+   All rights reserved.
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are
+   met:
+
+     * Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+
+     * Redistributions in binary form must reproduce the above
+       copyright notice, this list of conditions and the following
+       disclaimer in the documentation and/or other materials provided
+       with the distribution.
+
+     * Neither the name of the NetworkX Developers nor the names of its
+       contributors may be used to endorse or promote products derived
+       from this software without specific prior written permission.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/shared/package-files/3c/3cf892ab9f86b13d4bb1ff1fc2d1b018355fd6186fe592daae25ad7f39016c0c/chains.py b/shared/package-files/3c/3cf892ab9f86b13d4bb1ff1fc2d1b018355fd6186fe592daae25ad7f39016c0c/chains.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae342d9c8669acd832a3bdb4fe8eecf3e300464f
--- /dev/null
+++ b/shared/package-files/3c/3cf892ab9f86b13d4bb1ff1fc2d1b018355fd6186fe592daae25ad7f39016c0c/chains.py
@@ -0,0 +1,172 @@
+"""Functions for finding chains in a graph."""
+
+import networkx as nx
+from networkx.utils import not_implemented_for
+
+__all__ = ["chain_decomposition"]
+
+
+@not_implemented_for("directed")
+@not_implemented_for("multigraph")
+@nx._dispatchable
+def chain_decomposition(G, root=None):
+    """Returns the chain decomposition of a graph.
+
+    The *chain decomposition* of a graph with respect a depth-first
+    search tree is a set of cycles or paths derived from the set of
+    fundamental cycles of the tree in the following manner. Consider
+    each fundamental cycle with respect to the given tree, represented
+    as a list of edges beginning with the nontree edge oriented away
+    from the root of the tree. For each fundamental cycle, if it
+    overlaps with any previous fundamental cycle, just take the initial
+    non-overlapping segment, which is a path instead of a cycle. Each
+    cycle or path is called a *chain*. For more information, see [1]_.
+
+    Parameters
+    ----------
+    G : undirected graph
+
+    root : node (optional)
+       A node in the graph `G`. If specified, only the chain
+       decomposition for the connected component containing this node
+       will be returned. This node indicates the root of the depth-first
+       search tree.
+
+    Yields
+    ------
+    chain : list
+       A list of edges representing a chain. There is no guarantee on
+       the orientation of the edges in each chain (for example, if a
+       chain includes the edge joining nodes 1 and 2, the chain may
+       include either (1, 2) or (2, 1)).
+
+    Raises
+    ------
+    NodeNotFound
+       If `root` is not in the graph `G`.
+
+    Examples
+    --------
+    >>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)])
+    >>> list(nx.chain_decomposition(G))
+    [[(4, 5), (5, 3), (3, 4)]]
+
+    Notes
+    -----
+    The worst-case running time of this implementation is linear in the
+    number of nodes and number of edges [1]_.
+
+    References
+    ----------
+    .. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex-
+       and 2-edge-connectivity." *Information Processing Letters*,
+       113, 241–244. Elsevier. 
+
+    """
+
+    def _dfs_cycle_forest(G, root=None):
+        """Builds a directed graph composed of cycles from the given graph.
+
+        `G` is an undirected simple graph. `root` is a node in the graph
+        from which the depth-first search is started.
+
+        This function returns both the depth-first search cycle graph
+        (as a :class:`~networkx.DiGraph`) and the list of nodes in
+        depth-first preorder. The depth-first search cycle graph is a
+        directed graph whose edges are the edges of `G` oriented toward
+        the root if the edge is a tree edge and away from the root if
+        the edge is a non-tree edge. If `root` is not specified, this
+        performs a depth-first search on each connected component of `G`
+        and returns a directed forest instead.
+
+        If `root` is not in the graph, this raises :exc:`KeyError`.
+
+        """
+        # Create a directed graph from the depth-first search tree with
+        # root node `root` in which tree edges are directed toward the
+        # root and nontree edges are directed away from the root. For
+        # each node with an incident nontree edge, this creates a
+        # directed cycle starting with the nontree edge and returning to
+        # that node.
+        #
+        # The `parent` node attribute stores the parent of each node in
+        # the DFS tree. The `nontree` edge attribute indicates whether
+        # the edge is a tree edge or a nontree edge.
+        #
+        # We also store the order of the nodes found in the depth-first
+        # search in the `nodes` list.
+        H = nx.DiGraph()
+        nodes = []
+        for u, v, d in nx.dfs_labeled_edges(G, source=root):
+            if d == "forward":
+                # `dfs_labeled_edges()` yields (root, root, 'forward')
+                # if it is beginning the search on a new connected
+                # component.
+                if u == v:
+                    H.add_node(v, parent=None)
+                    nodes.append(v)
+                else:
+                    H.add_node(v, parent=u)
+                    H.add_edge(v, u, nontree=False)
+                    nodes.append(v)
+            # `dfs_labeled_edges` considers nontree edges in both
+            # orientations, so we need to not add the edge if it its
+            # other orientation has been added.
+            elif d == "nontree" and v not in H[u]:
+                H.add_edge(v, u, nontree=True)
+            else:
+                # Do nothing on 'reverse' edges; we only care about
+                # forward and nontree edges.
+                pass
+        return H, nodes
+
+    def _build_chain(G, u, v, visited):
+        """Generate the chain starting from the given nontree edge.
+
+        `G` is a DFS cycle graph as constructed by
+        :func:`_dfs_cycle_graph`. The edge (`u`, `v`) is a nontree edge
+        that begins a chain. `visited` is a set representing the nodes
+        in `G` that have already been visited.
+
+        This function yields the edges in an initial segment of the
+        fundamental cycle of `G` starting with the nontree edge (`u`,
+        `v`) that includes all the edges up until the first node that
+        appears in `visited`. The tree edges are given by the 'parent'
+        node attribute. The `visited` set is updated to add each node in
+        an edge yielded by this function.
+
+        """
+        while v not in visited:
+            yield u, v
+            visited.add(v)
+            u, v = v, G.nodes[v]["parent"]
+        yield u, v
+
+    # Check if the root is in the graph G. If not, raise NodeNotFound
+    if root is not None and root not in G:
+        raise nx.NodeNotFound(f"Root node {root} is not in graph")
+
+    # Create a directed version of H that has the DFS edges directed
+    # toward the root and the nontree edges directed away from the root
+    # (in each connected component).
+    H, nodes = _dfs_cycle_forest(G, root)
+
+    # Visit the nodes again in DFS order. For each node, and for each
+    # nontree edge leaving that node, compute the fundamental cycle for
+    # that nontree edge starting with that edge. If the fundamental
+    # cycle overlaps with any visited nodes, just take the prefix of the
+    # cycle up to the point of visited nodes.
+    #
+    # We repeat this process for each connected component (implicitly,
+    # since `nodes` already has a list of the nodes grouped by connected
+    # component).
+    visited = set()
+    for u in nodes:
+        visited.add(u)
+        # For each nontree edge going out of node u...
+        edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d)
+        for u, v in edges:
+            # Create the cycle or cycle prefix starting with the
+            # nontree edge.
+            chain = list(_build_chain(H, u, v, visited))
+            yield chain
diff --git a/shared/package-files/3c/3cfaaf5405552aaf34fecda1136a58b3131dc7ebfb136147fc755d23f7118a98/_cummin_helper.h b/shared/package-files/3c/3cfaaf5405552aaf34fecda1136a58b3131dc7ebfb136147fc755d23f7118a98/_cummin_helper.h
new file mode 100644
index 0000000000000000000000000000000000000000..d2d2bc3b9c600b98ecfa3d425f6ce495d7c0e36c
--- /dev/null
+++ b/shared/package-files/3c/3cfaaf5405552aaf34fecda1136a58b3131dc7ebfb136147fc755d23f7118a98/_cummin_helper.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
+inline void _cummin_helper(const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim) {
+    return at::_ops::_cummin_helper::call(self, values, indices, dim);
+}
+
+}
diff --git a/shared/package-files/3c/3cfe07529fb682db280ad199c2ac696ea677defb68457fb26136c8a8e422691d/traversal.py b/shared/package-files/3c/3cfe07529fb682db280ad199c2ac696ea677defb68457fb26136c8a8e422691d/traversal.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4e000ef44bf636b9adc700964a7ee4c2372a019
--- /dev/null
+++ b/shared/package-files/3c/3cfe07529fb682db280ad199c2ac696ea677defb68457fb26136c8a8e422691d/traversal.py
@@ -0,0 +1,304 @@
+from __future__ import annotations
+
+from typing import Iterator
+
+from .basic import Basic
+from .sorting import ordered
+from .sympify import sympify
+from sympy.utilities.iterables import iterable
+
+
+
+def iterargs(expr):
+    """Yield the args of a Basic object in a breadth-first traversal.
+    Depth-traversal stops if `arg.args` is either empty or is not
+    an iterable.
+
+    Examples
+    ========
+
+    >>> from sympy import Integral, Function
+    >>> from sympy.abc import x
+    >>> f = Function('f')
+    >>> from sympy.core.traversal import iterargs
+    >>> list(iterargs(Integral(f(x), (f(x), 1))))
+    [Integral(f(x), (f(x), 1)), f(x), (f(x), 1), x, f(x), 1, x]
+
+    See Also
+    ========
+    iterfreeargs, preorder_traversal
+    """
+    args = [expr]
+    for i in args:
+        yield i
+        args.extend(i.args)
+
+
+def iterfreeargs(expr, _first=True):
+    """Yield the args of a Basic object in a breadth-first traversal.
+    Depth-traversal stops if `arg.args` is either empty or is not
+    an iterable. The bound objects of an expression will be returned
+    as canonical variables.
+
+    Examples
+    ========
+
+    >>> from sympy import Integral, Function
+    >>> from sympy.abc import x
+    >>> f = Function('f')
+    >>> from sympy.core.traversal import iterfreeargs
+    >>> list(iterfreeargs(Integral(f(x), (f(x), 1))))
+    [Integral(f(x), (f(x), 1)), 1]
+
+    See Also
+    ========
+    iterargs, preorder_traversal
+    """
+    args = [expr]
+    for i in args:
+        yield i
+        if _first and hasattr(i, 'bound_symbols'):
+            void = i.canonical_variables.values()
+            for i in iterfreeargs(i.as_dummy(), _first=False):
+                if not i.has(*void):
+                    yield i
+        args.extend(i.args)
+
+
+class preorder_traversal:
+    """
+    Do a pre-order traversal of a tree.
+
+    This iterator recursively yields nodes that it has visited in a pre-order
+    fashion. That is, it yields the current node then descends through the
+    tree breadth-first to yield all of a node's children's pre-order
+    traversal.
+
+
+    For an expression, the order of the traversal depends on the order of
+    .args, which in many cases can be arbitrary.
+
+    Parameters
+    ==========
+    node : SymPy expression
+        The expression to traverse.
+    keys : (default None) sort key(s)
+        The key(s) used to sort args of Basic objects. When None, args of Basic
+        objects are processed in arbitrary order. If key is defined, it will
+        be passed along to ordered() as the only key(s) to use to sort the
+        arguments; if ``key`` is simply True then the default keys of ordered
+        will be used.
+
+    Yields
+    ======
+    subtree : SymPy expression
+        All of the subtrees in the tree.
+
+    Examples
+    ========
+
+    >>> from sympy import preorder_traversal, symbols
+    >>> x, y, z = symbols('x y z')
+
+    The nodes are returned in the order that they are encountered unless key
+    is given; simply passing key=True will guarantee that the traversal is
+    unique.
+
+    >>> list(preorder_traversal((x + y)*z, keys=None)) # doctest: +SKIP
+    [z*(x + y), z, x + y, y, x]
+    >>> list(preorder_traversal((x + y)*z, keys=True))
+    [z*(x + y), z, x + y, x, y]
+
+    """
+    def __init__(self, node, keys=None):
+        self._skip_flag = False
+        self._pt = self._preorder_traversal(node, keys)
+
+    def _preorder_traversal(self, node, keys):
+        yield node
+        if self._skip_flag:
+            self._skip_flag = False
+            return
+        if isinstance(node, Basic):
+            if not keys and hasattr(node, '_argset'):
+                # LatticeOp keeps args as a set. We should use this if we
+                # don't care about the order, to prevent unnecessary sorting.
+                args = node._argset
+            else:
+                args = node.args
+            if keys:
+                if keys != True:
+                    args = ordered(args, keys, default=False)
+                else:
+                    args = ordered(args)
+            for arg in args:
+                yield from self._preorder_traversal(arg, keys)
+        elif iterable(node):
+            for item in node:
+                yield from self._preorder_traversal(item, keys)
+
+    def skip(self):
+        """
+        Skip yielding current node's (last yielded node's) subtrees.
+
+        Examples
+        ========
+
+        >>> from sympy import preorder_traversal, symbols
+        >>> x, y, z = symbols('x y z')
+        >>> pt = preorder_traversal((x + y*z)*z)
+        >>> for i in pt:
+        ...     print(i)
+        ...     if i == x + y*z:
+        ...             pt.skip()
+        z*(x + y*z)
+        z
+        x + y*z
+        """
+        self._skip_flag = True
+
+    def __next__(self):
+        return next(self._pt)
+
+    def __iter__(self) -> Iterator[Basic]:
+        return self
+
+
+def use(expr, func, level=0, args=(), kwargs={}):
+    """
+    Use ``func`` to transform ``expr`` at the given level.
+
+    Examples
+    ========
+
+    >>> from sympy import use, expand
+    >>> from sympy.abc import x, y
+
+    >>> f = (x + y)**2*x + 1
+
+    >>> use(f, expand, level=2)
+    x*(x**2 + 2*x*y + y**2) + 1
+    >>> expand(f)
+    x**3 + 2*x**2*y + x*y**2 + 1
+
+    """
+    def _use(expr, level):
+        if not level:
+            return func(expr, *args, **kwargs)
+        else:
+            if expr.is_Atom:
+                return expr
+            else:
+                level -= 1
+                _args = [_use(arg, level) for arg in expr.args]
+                return expr.__class__(*_args)
+
+    return _use(sympify(expr), level)
+
+
+def walk(e, *target):
+    """Iterate through the args that are the given types (target) and
+    return a list of the args that were traversed; arguments
+    that are not of the specified types are not traversed.
+
+    Examples
+    ========
+
+    >>> from sympy.core.traversal import walk
+    >>> from sympy import Min, Max
+    >>> from sympy.abc import x, y, z
+    >>> list(walk(Min(x, Max(y, Min(1, z))), Min))
+    [Min(x, Max(y, Min(1, z)))]
+    >>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max))
+    [Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)]
+
+    See Also
+    ========
+
+    bottom_up
+    """
+    if isinstance(e, target):
+        yield e
+        for i in e.args:
+            yield from walk(i, *target)
+
+
+def bottom_up(rv, F, atoms=False, nonbasic=False):
+    """Apply ``F`` to all expressions in an expression tree from the
+    bottom up. If ``atoms`` is True, apply ``F`` even if there are no args;
+    if ``nonbasic`` is True, try to apply ``F`` to non-Basic objects.
+    """
+    args = getattr(rv, 'args', None)
+    if args is not None:
+        if args:
+            args = tuple([bottom_up(a, F, atoms, nonbasic) for a in args])
+            if args != rv.args:
+                rv = rv.func(*args)
+            rv = F(rv)
+        elif atoms:
+            rv = F(rv)
+    else:
+        if nonbasic:
+            try:
+                rv = F(rv)
+            except TypeError:
+                pass
+
+    return rv
+
+
+def postorder_traversal(node, keys=None):
+    """
+    Do a postorder traversal of a tree.
+
+    This generator recursively yields nodes that it has visited in a postorder
+    fashion. That is, it descends through the tree depth-first to yield all of
+    a node's children's postorder traversal before yielding the node itself.
+
+    Parameters
+    ==========
+
+    node : SymPy expression
+        The expression to traverse.
+    keys : (default None) sort key(s)
+        The key(s) used to sort args of Basic objects. When None, args of Basic
+        objects are processed in arbitrary order. If key is defined, it will
+        be passed along to ordered() as the only key(s) to use to sort the
+        arguments; if ``key`` is simply True then the default keys of
+        ``ordered`` will be used (node count and default_sort_key).
+
+    Yields
+    ======
+    subtree : SymPy expression
+        All of the subtrees in the tree.
+
+    Examples
+    ========
+
+    >>> from sympy import postorder_traversal
+    >>> from sympy.abc import w, x, y, z
+
+    The nodes are returned in the order that they are encountered unless key
+    is given; simply passing key=True will guarantee that the traversal is
+    unique.
+
+    >>> list(postorder_traversal(w + (x + y)*z)) # doctest: +SKIP
+    [z, y, x, x + y, z*(x + y), w, w + z*(x + y)]
+    >>> list(postorder_traversal(w + (x + y)*z, keys=True))
+    [w, z, x, y, x + y, z*(x + y), w + z*(x + y)]
+
+
+    """
+    if isinstance(node, Basic):
+        args = node.args
+        if keys:
+            if keys != True:
+                args = ordered(args, keys, default=False)
+            else:
+                args = ordered(args)
+        for arg in args:
+            yield from postorder_traversal(arg, keys)
+    elif iterable(node):
+        for item in node:
+            yield from postorder_traversal(item, keys)
+    yield node
diff --git a/shared/package-files/56/5600372819d9ee59bcc4d55c813ba0c01404a087d0af12fecb629dd6e95f495a/source_ref.h b/shared/package-files/56/5600372819d9ee59bcc4d55c813ba0c01404a087d0af12fecb629dd6e95f495a/source_ref.h
new file mode 100644
index 0000000000000000000000000000000000000000..c9ea38fa777503fe5a5b4bd8af382e799c651659
--- /dev/null
+++ b/shared/package-files/56/5600372819d9ee59bcc4d55c813ba0c01404a087d0af12fecb629dd6e95f495a/source_ref.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace torch::jit {
+
+/**
+ * SourceRef does two things:
+ *   1. Owns a Source object.
+ *   2. Serves as lookup key to the owned Source in associative containers, for
+ *      runtime data aggregation.
+ * We don't want to use std::shared_ptr directly because we want to
+ * support heteogeneous lookup, and also shared_ptr is an implementation detail
+ * which should be encapsulated.
+ */
+class TORCH_API SourceRef : public CustomClassHolder {
+ public:
+  explicit SourceRef(std::shared_ptr source_view)
+      : source_view_(std::move(source_view)) {}
+  bool operator==(const SourceRef& other) const {
+    return source_view_ == other.source_view_;
+  }
+  bool operator<(const Source& other) const {
+    return source_view_.get() < &other;
+  }
+  friend bool operator<(const Source& other, const SourceRef& self) {
+    return &other < self.source_view_.get();
+  }
+  bool operator<(const SourceRef& other) const {
+    return *this < *other.source_view_;
+  }
+  const Source* operator->() const {
+    return source_view_.get();
+  }
+
+ private:
+  std::shared_ptr source_view_;
+};
+
+} // namespace torch::jit
diff --git a/shared/package-files/56/5602d3facb6b8e6f6da6453a76250d653db6ba316880b7f510815fe434054995/test_astype.cpython-311.pyc b/shared/package-files/56/5602d3facb6b8e6f6da6453a76250d653db6ba316880b7f510815fe434054995/test_astype.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ce63bf2c7ca515f96cd71f1b4519a50bd661216
Binary files /dev/null and b/shared/package-files/56/5602d3facb6b8e6f6da6453a76250d653db6ba316880b7f510815fe434054995/test_astype.cpython-311.pyc differ
diff --git a/shared/package-files/56/560606135e3fe07051b91be0be77829001d7bba5de1eebddceedc920feb32bfc/ProcessGroupUCC.hpp b/shared/package-files/56/560606135e3fe07051b91be0be77829001d7bba5de1eebddceedc920feb32bfc/ProcessGroupUCC.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..a0955f783ed6292396f3cc22ebc3cb29ce2c0d85
--- /dev/null
+++ b/shared/package-files/56/560606135e3fe07051b91be0be77829001d7bba5de1eebddceedc920feb32bfc/ProcessGroupUCC.hpp
@@ -0,0 +1,358 @@
+#pragma once
+
+#ifdef USE_C10D_UCC
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#ifdef USE_CUDA
+#include 
+#include 
+#endif
+
+namespace c10d {
+
+#define TORCH_UCC_DEVICE_NOT_SET -2
+
+#ifdef USE_CUDA
+#define SAVE_TENSORS(_TENSORS, _DATA)                       \
+  do {                                                      \
+    if ((_TENSORS)[0].device().is_cuda()) {                 \
+      for (const auto i : c10::irange((_TENSORS).size())) { \
+        c10::cuda::CUDACachingAllocator::recordStream(      \
+            (_TENSORS)[i].storage().data_ptr(), (*stream)); \
+      }                                                     \
+    } else {                                                \
+      (_DATA) = (_TENSORS);                                 \
+    }                                                       \
+  } while (0)
+
+#else
+#define SAVE_TENSORS(_TENSORS, _DATA) (_DATA) = (_TENSORS);
+#endif
+
+constexpr const char* UCC_BACKEND_NAME = "ucc";
+
+struct event_pool_t {
+#ifdef USE_CUDA
+  std::queue> event_pool;
+#endif
+  std::mutex event_pool_mutex;
+};
+
+class Comm;
+
+// UCC does not support multiple CUDA devices per process.
+class TORCH_API ProcessGroupUCC : public Backend {
+ private:
+  void set_timeout(ucc_coll_args_t& args);
+
+ public:
+  class WorkData {
+   public:
+    std::vector src;
+    std::vector dst;
+    std::vector flat;
+    WorkData() {}
+    virtual ~WorkData() = default;
+  };
+  class AlltoallWorkData : public WorkData {
+   public:
+    AlltoallWorkData(int size)
+        : send_lengths(size),
+          send_offsets(size),
+          recv_lengths(size),
+          recv_offsets(size) {}
+    std::vector send_lengths;
+    std::vector send_offsets;
+    std::vector recv_lengths;
+    std::vector recv_offsets;
+  };
+
+  class AllgathervWorkData : public WorkData {
+   public:
+    AllgathervWorkData(int size) : recv_lengths(size), recv_offsets(size) {}
+    std::vector recv_lengths;
+    std::vector recv_offsets;
+  };
+
+  class ScattervWorkData : public WorkData {
+   public:
+    ScattervWorkData(int size) : send_lengths(size), send_offsets(size) {}
+    std::vector send_lengths;
+    std::vector send_offsets;
+  };
+
+  class ProgressEntry {
+    friend class ProcessGroupUCC;
+    friend class Comm;
+
+   public:
+    ProgressEntry(CommBase* comm, ucc_coll_req_h request)
+        : status_(UCC_INPROGRESS), comm_(comm), request_(request) {}
+    // Finalizes UCC status or exception of collective request.
+    void finalize(std::exception_ptr eptr = nullptr);
+    ucc_status_t status_;
+    CommBase* comm_;
+    ucc_coll_req_h request_;
+    std::unique_ptr data;
+    c10::intrusive_ptr future_;
+    std::exception_ptr eptr_;
+  };
+
+  class WorkUCC : public Work {
+    friend class ProcessGroupUCC;
+    friend class Comm;
+
+   public:
+    WorkUCC(
+        OpType opType,
+        uint64_t seq,
+        const char* prof_title,
+        const std::optional>& inputs,
+        const c10::intrusive_ptr& logger)
+        : Work(-1, opType, prof_title, inputs), logger_(logger), seq_(seq) {}
+    ~WorkUCC();
+    void setException();
+    void setAndThrowException();
+    bool isCompleted() override;
+    bool isSuccess() const override;
+    bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override;
+    c10::intrusive_ptr getFuture() override;
+    std::vector result() override;
+    int sourceRank() const override;
+#ifdef USE_CUDA
+    std::unique_ptr fence = nullptr;
+    event_pool_t* ep = nullptr;
+#endif
+    int sourceRank_;
+
+   protected:
+    std::shared_ptr entry_;
+    c10::intrusive_ptr logger_;
+    uint64_t seq_;
+
+   private:
+    // The future returned by getFuture.
+    c10::intrusive_ptr future_;
+    // Store a reference to collective's outputs, used by result
+    std::shared_ptr> outputs_;
+  };
+
+  explicit ProcessGroupUCC(
+      const c10::intrusive_ptr& store,
+      int rank = -1,
+      int size = -1,
+      std::chrono::duration timeout = kBackendDefaultTimeout);
+
+  void initComm(c10::Device dev);
+
+  ~ProcessGroupUCC() override;
+
+  const std::string getBackendName() const override {
+    return std::string(UCC_BACKEND_NAME);
+  }
+
+#ifdef USE_CUDA
+  std::unique_ptr getPooledEvent();
+#endif
+
+  // Performs a health check by initializing dummy UCC & UCX communicators and
+  // then destroying them. This will help indicate and signal any
+  // UCC/UCX-related issues prior to the first collective. The actual
+  // initialization and subsequent destruction is ran on a separate thread and
+  // the main thread is signalled about timeouts/errors to report to the
+  // application.
+  void runHealthCheck();
+
+  template 
+  c10::intrusive_ptr collective_post(
+      OpType opType,
+      PreProcess preproc,
+      PostProcess postproc,
+      ucc_coll_args_t& coll,
+      std::unique_ptr data,
+      c10::Device dev,
+      std::vector& inputTensors,
+      std::vector& outputTensors,
+      const char* prof_title);
+
+  c10::intrusive_ptr broadcast(
+      std::vector& data,
+      const BroadcastOptions& opts = BroadcastOptions()) override;
+
+  c10::intrusive_ptr allreduce(
+      std::vector& tensors,
+      const AllreduceOptions& opts = AllreduceOptions()) override;
+
+  c10::intrusive_ptr allreduce_coalesced(
+      std::vector& tensors,
+      const AllreduceCoalescedOptions& opts =
+          AllreduceCoalescedOptions()) override;
+
+  c10::intrusive_ptr reduce(
+      std::vector& tensors,
+      const ReduceOptions& opts = ReduceOptions()) override;
+
+  c10::intrusive_ptr allgather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr _allgather_base(
+      at::Tensor& outputBuffer,
+      at::Tensor& inputBuffer,
+      const AllgatherOptions& opts = AllgatherOptions()) override;
+
+  c10::intrusive_ptr barrier(
+      const BarrierOptions& opts = BarrierOptions()) override;
+
+  c10::intrusive_ptr gather(
+      std::vector>& outputTensors,
+      std::vector& inputTensors,
+      const GatherOptions& opts = GatherOptions()) override;
+
+  c10::intrusive_ptr scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ScatterOptions& opts = ScatterOptions()) override;
+
+  c10::intrusive_ptr reduce_scatter(
+      std::vector& outputTensors,
+      std::vector>& inputTensors,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
+
+  c10::intrusive_ptr alltoall_base(
+      at::Tensor& outputTensor,
+      at::Tensor& inputTensor,
+      std::vector& outputSplitSizes,
+      std::vector& inputSplitSizes,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr alltoall(
+      std::vector& outputTensors,
+      std::vector& inputTensors,
+      const AllToAllOptions& opts = AllToAllOptions()) override;
+
+  c10::intrusive_ptr send(
+      std::vector& tensors,
+      int dstRank,
+      int tag) override;
+
+  c10::intrusive_ptr recv(
+      std::vector& tensors,
+      int srcRank,
+      int tag) override;
+
+  // Counting for the sequential number of UCC collective_post call.
+  uint64_t seq_{0};
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store.
+  void setSequenceNumberForGroup() override;
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  uint64_t getSequenceNumberForGroup() override;
+
+  static c10::intrusive_ptr createProcessGroupUCC(
+      const c10::intrusive_ptr<::c10d::Store>& store,
+      int rank,
+      int size,
+      const std::chrono::duration& timeout);
+
+ protected:
+  const std::chrono::duration timeout_;
+  std::shared_ptr oob;
+  std::shared_ptr comm = {nullptr};
+  uint32_t comm_id;
+  ucc_team_h team{nullptr};
+  ucc_ee_h cuda_ee{nullptr};
+  ucc_ee_h cuda_ee_p2p[2]{nullptr, nullptr};
+
+#ifdef USE_CUDA
+  std::unique_ptr stream = nullptr;
+  std::unique_ptr stream_p2p[2] = {nullptr, nullptr};
+  event_pool_t ep;
+#endif
+  c10::intrusive_ptr logger;
+};
+
+class Comm {
+  c10::intrusive_ptr logger;
+  std::shared_ptr oob;
+  CommUCC ucc_comm;
+  std::mutex mutex;
+  std::thread progress_thread;
+  std::condition_variable queue_produce_cv;
+  std::condition_variable queue_consume_cv;
+  std::deque> progress_queue;
+  bool stop_progress_loop;
+  bool collective_inprogress;
+  torch_ucc_phase_t finalize_phase;
+
+ public:
+  c10::DeviceIndex cuda_device_index;
+  Comm(
+      const c10::intrusive_ptr& logger,
+      std::shared_ptr oob,
+      c10::Device dev,
+      bool is_health_check);
+
+  ~Comm();
+
+  void ucc_create_team(
+      ucc_team_h& team,
+      std::shared_ptr oob);
+
+  void ucc_destroy_team(ucc_team_h& team);
+
+  c10::intrusive_ptr enqueue_p2p(
+      OpType opType,
+      ucc_coll_req_h request,
+      const char* prof_title);
+
+#ifdef USE_CUDA
+  void enqueue_cuda_collective(
+      std::unique_ptr data,
+      c10::intrusive_ptr work,
+      ucc_coll_args_t& coll,
+      ucc_team_h team,
+      ucc_ee_h ee);
+#endif
+
+  void enqueue_collective(
+      std::unique_ptr data,
+      c10::intrusive_ptr work,
+      ucc_coll_args_t& coll,
+      ucc_team_h team);
+
+  static std::shared_ptr get_comm(
+      uint32_t& id,
+      c10::Device dev,
+      std::shared_ptr oob,
+      const c10::intrusive_ptr& logger,
+      bool is_health_check = false);
+
+  void progress_loop();
+};
+
+} // namespace c10d
+
+#endif // USE_C10D_UCC
diff --git a/shared/package-files/56/56068105438794e265939379ba0efd691ce42e48e9228b3624d53fb45e2d1a11/bam_quickcheck.c.pysam.c b/shared/package-files/56/56068105438794e265939379ba0efd691ce42e48e9228b3624d53fb45e2d1a11/bam_quickcheck.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..15ea8f605254a42d0553de8bcffd858271a0cc45
--- /dev/null
+++ b/shared/package-files/56/56068105438794e265939379ba0efd691ce42e48e9228b3624d53fb45e2d1a11/bam_quickcheck.c.pysam.c
@@ -0,0 +1,192 @@
+#include "samtools.pysam.h"
+
+/*  bam_quickcheck.c -- quickcheck subcommand.
+
+    Copyright (C) 2015-2017 Genome Research Ltd.
+
+    Author: Joshua C. Randall 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+/* File status flags (zero means OK). It's possible for more than one to be
+ * set on a single file.   The final exit status is the bitwise-or of the
+ * status of all the files. */
+#define QC_FAIL_OPEN     2
+#define QC_NOT_SEQUENCE  4
+#define QC_BAD_HEADER    8
+#define QC_NO_EOF_BLOCK 16
+#define QC_FAIL_CLOSE   32
+
+static void usage_quickcheck(FILE *write_to)
+{
+    fprintf(write_to,
+"Usage: samtools quickcheck [options]  [...]\n"
+"Options:\n"
+"  -v              verbose output (repeat for more verbosity)\n"
+"  -q              suppress warning messages\n"
+"  -u              unmapped input (do not require targets in header)\n"
+"\n"
+"Notes:\n"
+"\n"
+"1. By default quickcheck will emit a warning message if and only if a file\n"
+"   fails the checks, in which case the exit status is non-zero.  Under normal\n"
+"   behaviour with valid data it will be silent and has a zero exit status.\n"
+"   The warning messages are purely for manual inspection and should not be \n"
+"   parsed by scripts.\n"
+"\n"
+"2. In order to use this command programmatically, you should check its exit\n"
+"   status.  One way to use quickcheck might be as a check that all BAM files in\n"
+"   a directory are okay:\n"
+"\n"
+"\tsamtools quickcheck *.bam && echo 'all ok' \\\n"
+"\t   || echo 'fail!'\n"
+"\n"
+"   The first level of verbosity lists only files that fail to samtools_stdout.\n"
+"   To obtain a parsable list of files that have failed, use this option:\n"
+"\n"
+"\tsamtools quickcheck -qv *.bam > bad_bams.fofn \\\n"
+"\t   && echo 'all ok' \\\n"
+"\t   || echo 'some files failed check, see bad_bams.fofn'\n"
+    );
+}
+
+#define QC_ERR(state, v, msg, arg1)                                     \
+    file_state |= (state);                                              \
+    if (!quiet || verbose >= (v)) fprintf(samtools_stderr, (msg), (arg1))
+
+int main_quickcheck(int argc, char** argv)
+{
+    int verbose = 0, quiet = 0, unmapped = 0;
+    hts_verbose = 0;
+
+    const char* optstring = "vqu";
+    int opt;
+    while ((opt = getopt(argc, argv, optstring)) != -1) {
+        switch (opt) {
+        case 'u':
+            unmapped = 1;
+            break;
+        case 'v':
+            verbose++;
+            break;
+        case 'q':
+            quiet = 1;
+            break;
+        default:
+            usage_quickcheck(samtools_stderr);
+            return 1;
+        }
+    }
+
+    argc -= optind;
+    argv += optind;
+
+    if (argc < 1) {
+        usage_quickcheck(samtools_stdout);
+        return 1;
+    }
+
+    if (verbose >= 2) {
+        fprintf(samtools_stderr, "verbosity set to %d\n", verbose);
+    }
+
+    if (verbose >= 4) {
+        hts_verbose = 3;
+    }
+
+    int ret = 0;
+    int i;
+
+    for (i = 0; i < argc; i++) {
+        char* fn = argv[i];
+        int file_state = 0;
+
+        if (verbose >= 3) fprintf(samtools_stderr, "checking %s\n", fn);
+
+        // attempt to open
+        htsFile *hts_fp = hts_open(fn, "r");
+        if (hts_fp == NULL) {
+            QC_ERR(QC_FAIL_OPEN, 2, "%s could not be opened for reading.\n", fn);
+        }
+        else {
+            if (verbose >= 3) fprintf(samtools_stderr, "opened %s\n", fn);
+            // make sure we have sequence data
+            const htsFormat *fmt = hts_get_format(hts_fp);
+            if (fmt->category != sequence_data ) {
+                QC_ERR(QC_NOT_SEQUENCE, 2, "%s was not identified as sequence data.\n", fn);
+            }
+            else {
+                if (verbose >= 3) fprintf(samtools_stderr, "%s is sequence data\n", fn);
+                // check header
+                sam_hdr_t *header = sam_hdr_read(hts_fp);
+                if (header == NULL) {
+                    QC_ERR(QC_BAD_HEADER, 2, "%s caused an error whilst reading its header.\n", fn);
+                } else {
+                    if (!unmapped && sam_hdr_nref(header) <= 0) {
+                        QC_ERR(QC_BAD_HEADER, 2, "%s had no targets in header.\n", fn);
+                    }
+                    else {
+                        if (verbose >= 3) fprintf(samtools_stderr, "%s has %d targets in header.\n", fn, sam_hdr_nref(header));
+                    }
+                    sam_hdr_destroy(header);
+                }
+            }
+            // check EOF on formats that support this
+            int ret;
+            if ((ret = hts_check_EOF(hts_fp)) < 0) {
+                QC_ERR(QC_NO_EOF_BLOCK, 2, "%s caused an error whilst checking for EOF block.\n", fn);
+           }
+            else {
+                switch (ret) {
+                    case 0:
+                        QC_ERR(QC_NO_EOF_BLOCK, 2, "%s was missing EOF block when one should be present.\n", fn);
+                        break;
+                    case 1:
+                        if (verbose >= 3) fprintf(samtools_stderr, "%s has good EOF block.\n", fn);
+                        break;
+                    case 2:
+                        if (verbose >= 3) fprintf(samtools_stderr, "%s cannot be checked for EOF block as it is not seekable.\n", fn);
+                        break;
+                    case 3:
+                        if (verbose >= 3) fprintf(samtools_stderr, "%s cannot be checked for EOF block because its filetype does not contain one.\n", fn);
+                        break;
+                }
+            }
+
+            if (hts_close(hts_fp) < 0) {
+                QC_ERR(QC_FAIL_CLOSE, 2, "%s did not close cleanly.\n", fn);
+            }
+        }
+
+        if (file_state > 0 && verbose >= 1) {
+            fprintf(samtools_stdout, "%s\n", fn);
+        }
+        ret |= file_state;
+    }
+
+    return ret;
+}
diff --git a/shared/package-files/56/560b319985d41f4f1230995a090a689929a37a2b9192d0929c156d8fcb7b1e5c/test_getitem.cpython-311.pyc b/shared/package-files/56/560b319985d41f4f1230995a090a689929a37a2b9192d0929c156d8fcb7b1e5c/test_getitem.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c759c8ce27ec68ce4d05c93fdce9bdee3b26de2
Binary files /dev/null and b/shared/package-files/56/560b319985d41f4f1230995a090a689929a37a2b9192d0929c156d8fcb7b1e5c/test_getitem.cpython-311.pyc differ
diff --git a/shared/package-files/56/560ba79fb7a58168508248804855125ee4e7286c9224fda70dc61891e92b9bcc/vec256_double.h b/shared/package-files/56/560ba79fb7a58168508248804855125ee4e7286c9224fda70dc61891e92b9bcc/vec256_double.h
new file mode 100644
index 0000000000000000000000000000000000000000..b4b878859cbb871be29c49a050d350b35b335c77
--- /dev/null
+++ b/shared/package-files/56/560ba79fb7a58168508248804855125ee4e7286c9224fda70dc61891e92b9bcc/vec256_double.h
@@ -0,0 +1,450 @@
+#pragma once
+
+// DO NOT DEFINE STATIC DATA IN THIS HEADER!
+// See Note [Do not compile initializers with AVX]
+
+#include 
+#include 
+#include 
+#if defined(CPU_CAPABILITY_AVX2)
+#define SLEEF_STATIC_LIBS
+#include 
+#endif
+
+namespace at::vec {
+// See Note [CPU_CAPABILITY namespace]
+inline namespace CPU_CAPABILITY {
+
+
+#if defined(CPU_CAPABILITY_AVX2)
+
+template <> class Vectorized {
+private:
+  __m256d values;
+public:
+  using value_type = double;
+  using size_type = int;
+  static constexpr size_type size() {
+    return 4;
+  }
+  Vectorized() {}
+  Vectorized(__m256d v) : values(v) {}
+  Vectorized(double val) {
+    values = _mm256_set1_pd(val);
+  }
+  Vectorized(double val1, double val2, double val3, double val4) {
+    values = _mm256_setr_pd(val1, val2, val3, val4);
+  }
+  operator __m256d() const {
+    return values;
+  }
+  template 
+  static Vectorized blend(const Vectorized& a, const Vectorized& b) {
+    return _mm256_blend_pd(a.values, b.values, mask);
+  }
+  static Vectorized blendv(const Vectorized& a, const Vectorized& b,
+                               const Vectorized& mask) {
+    return _mm256_blendv_pd(a.values, b.values, mask.values);
+  }
+  template
+  static Vectorized arange(double base = 0., step_t step = static_cast(1)) {
+    return Vectorized(base, base + step, base + 2 * step, base + 3 * step);
+  }
+  static Vectorized set(const Vectorized& a, const Vectorized& b,
+                            int64_t count = size()) {
+    switch (count) {
+      case 0:
+        return a;
+      case 1:
+        return blend<1>(a, b);
+      case 2:
+        return blend<3>(a, b);
+      case 3:
+        return blend<7>(a, b);
+    }
+    return b;
+  }
+  static Vectorized loadu(const void* ptr, int64_t count = size()) {
+    if (count == size())
+      return _mm256_loadu_pd(reinterpret_cast(ptr));
+
+
+    __at_align__ double tmp_values[size()];
+    // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502
+    // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two
+    // instructions while a loop would be compiled to one instruction.
+    for (const auto i : c10::irange(size())) {
+      tmp_values[i] = 0.0;
+    }
+    std::memcpy(
+        tmp_values,
+        reinterpret_cast(ptr),
+        count * sizeof(double));
+    return _mm256_load_pd(tmp_values);
+  }
+  void store(void* ptr, int count = size()) const {
+    if (count == size()) {
+      _mm256_storeu_pd(reinterpret_cast(ptr), values);
+    } else if (count > 0) {
+      double tmp_values[size()];
+      _mm256_storeu_pd(reinterpret_cast(tmp_values), values);
+      std::memcpy(ptr, tmp_values, count * sizeof(double));
+    }
+  }
+  const double& operator[](int idx) const  = delete;
+  double& operator[](int idx) = delete;
+  int zero_mask() const {
+    // returns an integer mask where all zero elements are translated to 1-bit and others are translated to 0-bit
+    __m256d cmp = _mm256_cmp_pd(values, _mm256_set1_pd(0.0), _CMP_EQ_OQ);
+    return _mm256_movemask_pd(cmp);
+  }
+  Vectorized isnan() const {
+    return _mm256_cmp_pd(values, _mm256_set1_pd(0.0), _CMP_UNORD_Q);
+  }
+  bool has_inf_nan() const {
+    __m256d self_sub  = _mm256_sub_pd(values, values);
+    return (_mm256_movemask_epi8(_mm256_castpd_si256(self_sub)) & 0x77777777) != 0;
+  }
+  Vectorized map(double (*const f)(double)) const {
+    __at_align__ double tmp[size()];
+    store(tmp);
+    for (const auto i : c10::irange(size())) {
+      tmp[i] = f(tmp[i]);
+    }
+    return loadu(tmp);
+  }
+  Vectorized abs() const {
+    auto mask = _mm256_set1_pd(-0.f);
+    return _mm256_andnot_pd(mask, values);
+  }
+  Vectorized angle() const {
+    const auto zero_vec = _mm256_set1_pd(0.f);
+    const auto nan_vec = _mm256_set1_pd(NAN);
+    const auto not_nan_mask = _mm256_cmp_pd(values, values, _CMP_EQ_OQ);
+    const auto nan_mask = _mm256_cmp_pd(not_nan_mask, zero_vec, _CMP_EQ_OQ);
+    const auto pi = _mm256_set1_pd(c10::pi);
+
+    const auto neg_mask = _mm256_cmp_pd(values, zero_vec, _CMP_LT_OQ);
+    auto angle = _mm256_blendv_pd(zero_vec, pi, neg_mask);
+    angle = _mm256_blendv_pd(angle, nan_vec, nan_mask);
+    return angle;
+  }
+  Vectorized real() const {
+    return *this;
+  }
+  Vectorized imag() const {
+    return _mm256_set1_pd(0);
+  }
+  Vectorized conj() const {
+    return *this;
+  }
+  Vectorized acos() const {
+    return Vectorized(Sleef_acosd4_u10(values));
+  }
+  Vectorized acosh() const {
+    return Vectorized(Sleef_acoshd4_u10(values));
+  }
+  Vectorized asin() const {
+    return Vectorized(Sleef_asind4_u10(values));
+  }
+  Vectorized asinh() const {
+    return Vectorized(Sleef_asinhd4_u10(values));
+  }
+  Vectorized atan() const {
+    return Vectorized(Sleef_atand4_u10(values));
+  }
+  Vectorized atanh() const {
+    return Vectorized(Sleef_atanhd4_u10(values));
+  }
+  Vectorized atan2(const Vectorized &b) const {
+    return Vectorized(Sleef_atan2d4_u10(values, b));
+  }
+  Vectorized copysign(const Vectorized &sign) const {
+    return Vectorized(Sleef_copysignd4(values, sign));
+  }
+  Vectorized erf() const {
+    return Vectorized(Sleef_erfd4_u10(values));
+  }
+  Vectorized erfc() const {
+    return Vectorized(Sleef_erfcd4_u15(values));
+  }
+  Vectorized erfinv() const {
+    return map(calc_erfinv);
+  }
+  Vectorized exp() const {
+    return Vectorized(Sleef_expd4_u10(values));
+  }
+  Vectorized exp2() const {
+    return Vectorized(Sleef_exp2d4_u10(values));
+  }
+  Vectorized expm1() const {
+    return Vectorized(Sleef_expm1d4_u10(values));
+  }
+  Vectorized exp_u20() const {
+    return exp();
+  }
+  Vectorized fmod(const Vectorized& q) const {
+    return Vectorized(Sleef_fmodd4(values, q));
+  }
+  Vectorized hypot(const Vectorized &b) const {
+    return Vectorized(Sleef_hypotd4_u05(values, b));
+  }
+  Vectorized i0() const {
+    return map(calc_i0);
+  }
+  Vectorized i0e() const {
+    return map(calc_i0e);
+  }
+  Vectorized digamma() const {
+    return map(calc_digamma);
+  }
+  Vectorized igamma(const Vectorized &x) const {
+    __at_align__ double tmp[size()];
+    __at_align__ double tmp_x[size()];
+    store(tmp);
+    x.store(tmp_x);
+    for (const auto i : c10::irange(size())) {
+      tmp[i] = calc_igamma(tmp[i], tmp_x[i]);
+    }
+    return loadu(tmp);
+  }
+  Vectorized igammac(const Vectorized &x) const {
+    __at_align__ double tmp[size()];
+    __at_align__ double tmp_x[size()];
+    store(tmp);
+    x.store(tmp_x);
+    for (const auto i : c10::irange(size())) {
+      tmp[i] = calc_igammac(tmp[i], tmp_x[i]);
+    }
+    return loadu(tmp);
+  }
+  Vectorized log() const {
+    return Vectorized(Sleef_logd4_u10(values));
+  }
+  Vectorized log2() const {
+    return Vectorized(Sleef_log2d4_u10(values));
+  }
+  Vectorized log10() const {
+    return Vectorized(Sleef_log10d4_u10(values));
+  }
+  Vectorized log1p() const {
+    return Vectorized(Sleef_log1pd4_u10(values));
+  }
+  Vectorized sin() const {
+    return Vectorized(Sleef_sind4_u10(values));
+  }
+  Vectorized sinh() const {
+    return Vectorized(Sleef_sinhd4_u10(values));
+  }
+  Vectorized cos() const {
+    return Vectorized(Sleef_cosd4_u10(values));
+  }
+  Vectorized cosh() const {
+    return Vectorized(Sleef_coshd4_u10(values));
+  }
+  Vectorized ceil() const {
+    return _mm256_ceil_pd(values);
+  }
+  Vectorized floor() const {
+    return _mm256_floor_pd(values);
+  }
+  Vectorized frac() const;
+  Vectorized neg() const {
+    return _mm256_xor_pd(_mm256_set1_pd(-0.), values);
+  }
+  Vectorized nextafter(const Vectorized &b) const {
+    return Vectorized(Sleef_nextafterd4(values, b));
+  }
+  Vectorized round() const {
+    return _mm256_round_pd(values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
+  }
+  Vectorized tan() const {
+    return Vectorized(Sleef_tand4_u10(values));
+  }
+  Vectorized tanh() const {
+    return Vectorized(Sleef_tanhd4_u10(values));
+  }
+  Vectorized trunc() const {
+    return _mm256_round_pd(values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC));
+  }
+  Vectorized lgamma() const {
+    return Vectorized(Sleef_lgammad4_u10(values));
+  }
+  Vectorized sqrt() const {
+    return _mm256_sqrt_pd(values);
+  }
+  Vectorized reciprocal() const {
+    return _mm256_div_pd(_mm256_set1_pd(1), values);
+  }
+  Vectorized rsqrt() const {
+    return _mm256_div_pd(_mm256_set1_pd(1), _mm256_sqrt_pd(values));
+  }
+  Vectorized pow(const Vectorized &b) const {
+    return Vectorized(Sleef_powd4_u10(values, b));
+  }
+  // Comparison using the _CMP_**_OQ predicate.
+  //   `O`: get false if an operand is NaN
+  //   `Q`: do not raise if an operand is NaN
+  Vectorized operator==(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_EQ_OQ);
+  }
+
+  Vectorized operator!=(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_NEQ_UQ);
+  }
+
+  Vectorized operator<(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_LT_OQ);
+  }
+
+  Vectorized operator<=(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_LE_OQ);
+  }
+
+  Vectorized operator>(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_GT_OQ);
+  }
+
+  Vectorized operator>=(const Vectorized& other) const {
+    return _mm256_cmp_pd(values, other.values, _CMP_GE_OQ);
+  }
+
+  Vectorized eq(const Vectorized& other) const;
+  Vectorized ne(const Vectorized& other) const;
+  Vectorized lt(const Vectorized& other) const;
+  Vectorized le(const Vectorized& other) const;
+  Vectorized gt(const Vectorized& other) const;
+  Vectorized ge(const Vectorized& other) const;
+};
+
+template <>
+Vectorized inline operator+(const Vectorized& a, const Vectorized& b) {
+  return _mm256_add_pd(a, b);
+}
+
+template <>
+Vectorized inline operator-(const Vectorized& a, const Vectorized& b) {
+  return _mm256_sub_pd(a, b);
+}
+
+template <>
+Vectorized inline operator*(const Vectorized& a, const Vectorized& b) {
+  return _mm256_mul_pd(a, b);
+}
+
+template <>
+Vectorized inline operator/(const Vectorized& a, const Vectorized& b) {
+  return _mm256_div_pd(a, b);
+}
+
+// frac. Implement this here so we can use subtraction.
+inline Vectorized Vectorized::frac() const {
+  return *this - this->trunc();
+}
+
+// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if
+// either input is a NaN.
+template <>
+Vectorized inline maximum(const Vectorized& a, const Vectorized& b) {
+  Vectorized max = _mm256_max_pd(a, b);
+  Vectorized isnan = _mm256_cmp_pd(a, b, _CMP_UNORD_Q);
+  // Exploit the fact that all-ones is a NaN.
+  return _mm256_or_pd(max, isnan);
+}
+
+// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if
+// either input is a NaN.
+template <>
+Vectorized inline minimum(const Vectorized& a, const Vectorized& b) {
+  Vectorized min = _mm256_min_pd(a, b);
+  Vectorized isnan = _mm256_cmp_pd(a, b, _CMP_UNORD_Q);
+  // Exploit the fact that all-ones is a NaN.
+  return _mm256_or_pd(min, isnan);
+}
+
+template <>
+Vectorized inline clamp(const Vectorized& a, const Vectorized& min, const Vectorized& max) {
+  return _mm256_min_pd(max, _mm256_max_pd(min, a));
+}
+
+template <>
+Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min) {
+  return _mm256_max_pd(min, a);
+}
+
+template <>
+Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max) {
+  return _mm256_min_pd(max, a);
+}
+
+template <>
+Vectorized inline operator&(const Vectorized& a, const Vectorized& b) {
+  return _mm256_and_pd(a, b);
+}
+
+template <>
+Vectorized inline operator|(const Vectorized& a, const Vectorized& b) {
+  return _mm256_or_pd(a, b);
+}
+
+template <>
+Vectorized inline operator^(const Vectorized& a, const Vectorized& b) {
+  return _mm256_xor_pd(a, b);
+}
+
+inline Vectorized Vectorized::eq(const Vectorized& other) const {
+  return (*this == other) & Vectorized(1.0);
+}
+
+inline Vectorized Vectorized::ne(const Vectorized& other) const {
+  return (*this != other) & Vectorized(1.0);
+}
+
+inline Vectorized Vectorized::gt(const Vectorized& other) const {
+  return (*this > other) & Vectorized(1.0);
+}
+
+inline Vectorized Vectorized::ge(const Vectorized& other) const {
+  return (*this >= other) & Vectorized(1.0);
+}
+
+inline Vectorized Vectorized::lt(const Vectorized& other) const {
+  return (*this < other) & Vectorized(1.0);
+}
+
+inline Vectorized Vectorized::le(const Vectorized& other) const {
+  return (*this <= other) & Vectorized(1.0);
+}
+
+template <>
+inline void convert(const double* src, double* dst, int64_t n) {
+  int64_t i;
+#ifndef __msvc_cl__
+#pragma unroll
+#endif
+  for (i = 0; i <= (n - Vectorized::size()); i += Vectorized::size()) {
+    _mm256_storeu_pd(dst + i, _mm256_loadu_pd(src + i));
+  }
+#ifndef __msvc_cl__
+#pragma unroll
+#endif
+  for (; i < n; i++) {
+    dst[i] = src[i];
+  }
+}
+
+#ifdef CPU_CAPABILITY_AVX2
+template <>
+Vectorized inline fmadd(const Vectorized& a, const Vectorized& b, const Vectorized& c) {
+  return _mm256_fmadd_pd(a, b, c);
+}
+
+template <>
+Vectorized inline fmsub(const Vectorized& a, const Vectorized& b, const Vectorized& c) {
+  return _mm256_fmsub_pd(a, b, c);
+}
+#endif
+
+#endif
+
+}} // namespace at::vec::CPU_CAPABILITY
diff --git a/shared/package-files/56/560c6f0ae2927160bea1b3417a67a4228f1b7129a90bd882916f91d8674d1cc7/model_report_visualizer.py b/shared/package-files/56/560c6f0ae2927160bea1b3417a67a4228f1b7129a90bd882916f91d8674d1cc7/model_report_visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8699813f2d1815e4d44f788b6b29848b817b1be
--- /dev/null
+++ b/shared/package-files/56/560c6f0ae2927160bea1b3417a67a4228f1b7129a90bd882916f91d8674d1cc7/model_report_visualizer.py
@@ -0,0 +1,714 @@
+# mypy: allow-untyped-defs
+from collections import OrderedDict, OrderedDict as OrdDict
+from typing import Any
+
+import torch
+
+
+# try to import tablate
+got_tabulate = True
+try:
+    from tabulate import tabulate
+except ImportError:
+    got_tabulate = False
+
+
+# var to see if we could import matplotlib
+got_matplotlib = True
+try:
+    import matplotlib.pyplot as plt
+except ImportError:
+    got_matplotlib = False
+
+
+class ModelReportVisualizer:
+    r"""
+    The ModelReportVisualizer class aims to provide users a way to visualize some of the statistics
+    that were generated by the ModelReport API. However, at a higher level, the class aims to provide
+    some level of visualization of statistics to PyTorch in order to make it easier to parse data and
+    diagnose any potential issues with data or a specific model. With respect to the visualizations,
+    the ModelReportVisualizer class currently supports several methods of visualizing data.
+
+    Supported Visualization Methods Include:
+    - Table format
+    - Plot format (line graph)
+    - Histogram format
+
+    For all of the existing visualization methods, there is the option to filter data based on:
+    - A module fqn prefix
+    - Feature [required for the plot and histogram]
+
+    * :attr:`generated_reports` The reports generated by the ModelReport class in the structure below
+        Ensure sure that features that are the same across different report contain the same name
+        Ensure that objects representing the same features are the same type / dimension (where applicable)
+
+    Note:
+        Currently, the ModelReportVisualizer class supports visualization of data generated by the
+        ModelReport class. However, this structure is extensible and should allow the visualization of
+        other information as long as the information is structured in the following general format:
+
+        Report Structure
+        -- module_fqn [module with attached detectors]
+            |
+            -- feature keys [not every detector extracts same information]
+                                    [same collected info has same keys, unless can be specific to detector]
+
+
+    The goal behind the class is that the generated visualizations can be used in conjunction with the generated
+    report for people to get a better understanding of issues and what the fix might be. It is also just to provide
+    a good visualization platform, since it might be hard to parse through the ModelReport returned dictionary as
+    that grows in size.
+
+    General Use Flow Expected
+    1.) Initialize ModelReport object with reports of interest by passing in initialized detector objects
+    2.) Prepare your model with prepare_fx
+    3.) Call model_report.prepare_detailed_calibration on your model to add relevant observers
+    4.) Callibrate your model with data
+    5.) Call model_report.generate_report on your model to generate report and optionally remove added observers
+    6.) Use output of model_report.generate_report to initialize ModelReportVisualizer instance
+    7.) Use instance to view different views of data as desired, applying filters as needed
+        8.) Either see the super detailed information or just the actual printed or shown table / plot / histogram
+
+    """
+
+    # keys for table dict
+    TABLE_TENSOR_KEY = "tensor_level_info"
+    TABLE_CHANNEL_KEY = "channel_level_info"
+
+    # Constants for header vals
+    NUM_NON_FEATURE_TENSOR_HEADERS = 2
+    NUM_NON_FEATURE_CHANNEL_HEADERS = 3
+
+    # Constants for row index in header
+    CHANNEL_NUM_INDEX = 2
+
+    def __init__(self, generated_reports: OrderedDict[str, Any]):
+        r"""
+        Initializes the ModelReportVisualizer instance with the necessary reports.
+
+        Args:
+            generated_reports (Dict[str, Any]): The reports generated by the ModelReport class
+                can also be a dictionary generated in another manner, as long as format is same
+        """
+        self.generated_reports = generated_reports
+
+    def get_all_unique_module_fqns(self) -> set[str]:
+        r"""
+        The purpose of this method is to provide a user the set of all module_fqns so that if
+        they wish to use some of the filtering capabilities of the ModelReportVisualizer class,
+        they don't need to manually parse the generated_reports dictionary to get this information.
+
+        Returns all the unique module fqns present in the reports the ModelReportVisualizer
+        instance was initialized with.
+        """
+        # returns the keys of the ordered dict
+        return set(self.generated_reports.keys())
+
+    def get_all_unique_feature_names(
+        self, plottable_features_only: bool = True
+    ) -> set[str]:
+        r"""
+        The purpose of this method is to provide a user the set of all feature names so that if
+        they wish to use the filtering capabilities of the generate_table_view(), or use either of
+        the generate_plot_view() or generate_histogram_view(), they don't need to manually parse
+        the generated_reports dictionary to get this information.
+
+        Args:
+            plottable_features_only (bool): True if the user is only looking for plottable features,
+                False otherwise
+                plottable features are those that are tensor values
+                Default: True (only return those feature names that are plottable)
+
+        Returns all the unique module fqns present in the reports the ModelReportVisualizer
+        instance was initialized with.
+        """
+        unique_feature_names = set()
+        for module_fqn in self.generated_reports:
+            # get dict of the features
+            feature_dict: dict[str, Any] = self.generated_reports[module_fqn]
+
+            # loop through features
+            for feature_name in feature_dict:
+                # if we need plottable, ensure type of val is tensor
+                if (
+                    not plottable_features_only
+                    or type(feature_dict[feature_name]) == torch.Tensor
+                ):
+                    unique_feature_names.add(feature_name)
+
+        # return our compiled set of unique feature names
+        return unique_feature_names
+
+    def _get_filtered_data(
+        self, feature_filter: str, module_fqn_filter: str
+    ) -> OrderedDict[str, Any]:
+        r"""
+        Filters the data and returns it in the same ordered dictionary format so the relevant views can be displayed.
+
+        Args:
+            feature_filter (str): The feature filter, if we want to filter the set of data to only include
+                a certain set of features that include feature_filter
+                If feature = "", then we do not filter based on any features
+            module_fqn_filter (str): The filter on prefix for the module fqn. All modules that have fqn with
+                this prefix will be included
+                If module_fqn_filter = "" we do not filter based on module fqn, and include all modules
+
+        First, the data is filtered based on module_fqn, and then filtered based on feature
+        Returns an OrderedDict (sorted in order of model) mapping:
+            module_fqns -> feature_names -> values
+        """
+        # create return dict
+        filtered_dict: OrderedDict[str, Any] = OrdDict()
+
+        for module_fqn in self.generated_reports:
+            # first filter based on module
+            if module_fqn_filter == "" or module_fqn_filter in module_fqn:
+                # create entry for module and loop through features
+                filtered_dict[module_fqn] = {}
+                module_reports = self.generated_reports[module_fqn]
+                for feature_name in module_reports:
+                    # check if filtering on features and do so if desired
+                    if feature_filter == "" or feature_filter in feature_name:
+                        filtered_dict[module_fqn][feature_name] = module_reports[
+                            feature_name
+                        ]
+
+        # we have populated the filtered dict, and must return it
+
+        return filtered_dict
+
+    def _generate_tensor_table(
+        self,
+        filtered_data: OrderedDict[str, dict[str, Any]],
+        tensor_features: list[str],
+    ) -> tuple[list, list]:
+        r"""
+        Takes in the filtered data and features list and generates the tensor headers and table
+
+        Currently meant to generate the headers and table for both the tensor information.
+
+        Args:
+            filtered_data (OrderedDict[str, Dict[str, Any]]): An OrderedDict (sorted in order of model) mapping:
+                module_fqns -> feature_names -> values
+            tensor_features (List[str]): A list of the tensor level features
+
+        Returns a tuple with:
+            A list of the headers of the tensor table
+            A list of lists containing the table information row by row
+            The 0th index row will contain the headers of the columns
+            The rest of the rows will contain data
+        """
+        # now we compose the tensor information table
+        tensor_table: list[list[Any]] = []
+        tensor_headers: list[str] = []
+
+        # append the table row to the table only if we have features
+        if len(tensor_features) > 0:
+            # now we add all the data
+            for index, module_fqn in enumerate(filtered_data):
+                # we make a new row for the tensor table
+                tensor_table_row = [index, module_fqn]
+                for feature in tensor_features:
+                    # we iterate in same order of added features
+
+                    if feature in filtered_data[module_fqn]:
+                        # add value if applicable to module
+                        feature_val = filtered_data[module_fqn][feature]
+                    else:
+                        # add that it is not applicable
+                        feature_val = "Not Applicable"
+
+                    # if it's a tensor we want to extract val
+                    if isinstance(feature_val, torch.Tensor):
+                        feature_val = feature_val.item()
+
+                    # we add to our list of values
+                    tensor_table_row.append(feature_val)
+
+                tensor_table.append(tensor_table_row)
+
+        # add row of headers of we actually have something, otherwise just empty
+        if len(tensor_table) != 0:
+            tensor_headers = ["idx", "layer_fqn"] + tensor_features
+
+        return (tensor_headers, tensor_table)
+
+    def _generate_channels_table(
+        self,
+        filtered_data: OrderedDict[str, Any],
+        channel_features: list[str],
+        num_channels: int,
+    ) -> tuple[list, list]:
+        r"""
+        Takes in the filtered data and features list and generates the channels headers and table
+
+        Currently meant to generate the headers and table for both the channels information.
+
+        Args:
+            filtered_data (OrderedDict[str, Any]): An OrderedDict (sorted in order of model) mapping:
+                module_fqns -> feature_names -> values
+            channel_features (List[str]): A list of the channel level features
+            num_channels (int): Number of channels in the channel data
+
+        Returns a tuple with:
+            A list of the headers of the channel table
+            A list of lists containing the table information row by row
+            The 0th index row will contain the headers of the columns
+            The rest of the rows will contain data
+        """
+        # now we compose the table for the channel information table
+        channel_table: list[list[Any]] = []
+        channel_headers: list[str] = []
+
+        # counter to keep track of number of entries in
+        channel_table_entry_counter: int = 0
+
+        if len(channel_features) > 0:
+            # now we add all channel data
+            for module_fqn in filtered_data:
+                # we iterate over all channels
+                for channel in range(num_channels):
+                    # we make a new row for the channel
+                    new_channel_row = [channel_table_entry_counter, module_fqn, channel]
+                    for feature in channel_features:
+                        if feature in filtered_data[module_fqn]:
+                            # add value if applicable to module
+                            feature_val = filtered_data[module_fqn][feature][channel]
+                        else:
+                            # add that it is not applicable
+                            feature_val = "Not Applicable"
+
+                        # if it's a tensor we want to extract val
+                        if type(feature_val) is torch.Tensor:
+                            feature_val = feature_val.item()
+
+                        # add value to channel specific row
+                        new_channel_row.append(feature_val)
+
+                    # add to table and increment row index counter
+                    channel_table.append(new_channel_row)
+                    channel_table_entry_counter += 1
+
+        # add row of headers of we actually have something, otherwise just empty
+        if len(channel_table) != 0:
+            channel_headers = ["idx", "layer_fqn", "channel"] + channel_features
+
+        return (channel_headers, channel_table)
+
+    def generate_filtered_tables(
+        self, feature_filter: str = "", module_fqn_filter: str = ""
+    ) -> dict[str, tuple[list, list]]:
+        r"""
+        Takes in optional filter values and generates two tables with desired information.
+
+        The generated tables are presented in both a list-of-lists format
+
+        The reason for the two tables are that they handle different things:
+        1.) the first table handles all tensor level information
+        2.) the second table handles and displays all channel based information
+
+        The reasoning for this is that having all the info in one table can make it ambiguous which collected
+            statistics are global, and which are actually per-channel, so it's better to split it up into two
+            tables. This also makes the information much easier to digest given the plethora of statistics collected
+
+        Tensor table columns:
+            idx  layer_fqn  feature_1   feature_2   feature_3   .... feature_n
+            ----  ---------  ---------   ---------   ---------        ---------
+
+        Per-Channel table columns:
+            idx  layer_fqn  channel  feature_1   feature_2   feature_3   .... feature_n
+            ----  ---------  -------  ---------   ---------   ---------        ---------
+
+        Args:
+            feature_filter (str, optional): Filters the features presented to only those that
+                contain this filter substring
+                Default = "", results in all the features being printed
+            module_fqn_filter (str, optional): Only includes modules that contains this string
+                Default = "", results in all the modules in the reports to be visible in the table
+
+        Returns a dictionary with two keys:
+            (Dict[str, Tuple[List, List]]) A dict containing two keys:
+            "tensor_level_info", "channel_level_info"
+                Each key maps to a tuple with:
+                    A list of the headers of each table
+                    A list of lists containing the table information row by row
+                    The 0th index row will contain the headers of the columns
+                    The rest of the rows will contain data
+
+        Example Use:
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> mod_report_visualizer.generate_filtered_tables(
+            ...     feature_filter = "per_channel_min",
+            ...     module_fqn_filter = "block1"
+            ... ) # generates table with per_channel_min info for all modules in block 1 of the model
+        """
+        # first get the filtered data
+        filtered_data: OrderedDict[str, Any] = self._get_filtered_data(
+            feature_filter, module_fqn_filter
+        )
+
+        # now we split into tensor and per-channel data
+        tensor_features: set[str] = set()
+        channel_features: set[str] = set()
+
+        # keep track of the number of channels we have
+        num_channels: int = 0
+
+        for module_fqn in filtered_data:
+            for feature_name in filtered_data[module_fqn]:
+                # get the data for that specific feature
+                feature_data = filtered_data[module_fqn][feature_name]
+
+                # check if not zero dim tensor
+                is_tensor: bool = isinstance(feature_data, torch.Tensor)
+                is_not_zero_dim: bool = is_tensor and len(feature_data.shape) != 0
+
+                if is_not_zero_dim or isinstance(feature_data, list):
+                    # works means per channel
+                    channel_features.add(feature_name)
+                    num_channels = len(feature_data)
+                else:
+                    # means is per-tensor
+                    tensor_features.add(feature_name)
+
+        # we make them lists for iteration purposes
+        tensor_features_list: list[str] = sorted(tensor_features)
+        channel_features_list: list[str] = sorted(channel_features)
+
+        # get the tensor info
+        tensor_headers, tensor_table = self._generate_tensor_table(
+            filtered_data, tensor_features_list
+        )
+
+        # get the channel info
+        channel_headers, channel_table = self._generate_channels_table(
+            filtered_data, channel_features_list, num_channels
+        )
+
+        # let's now create the dictionary to return
+        table_dict = {
+            self.TABLE_TENSOR_KEY: (tensor_headers, tensor_table),
+            self.TABLE_CHANNEL_KEY: (channel_headers, channel_table),
+        }
+
+        # return the two tables
+        return table_dict
+
+    def generate_table_visualization(
+        self, feature_filter: str = "", module_fqn_filter: str = ""
+    ):
+        r"""
+        Takes in optional filter values and prints out formatted tables of the information.
+
+        The reason for the two tables printed out instead of one large one are that they handle different things:
+        1.) the first table handles all tensor level information
+        2.) the second table handles and displays all channel based information
+
+        The reasoning for this is that having all the info in one table can make it ambiguous which collected
+            statistics are global, and which are actually per-channel, so it's better to split it up into two
+            tables. This also makes the information much easier to digest given the plethora of statistics collected
+
+        Tensor table columns:
+         idx  layer_fqn  feature_1   feature_2   feature_3   .... feature_n
+        ----  ---------  ---------   ---------   ---------        ---------
+
+        Per-Channel table columns:
+
+         idx  layer_fqn  channel  feature_1   feature_2   feature_3   .... feature_n
+        ----  ---------  -------  ---------   ---------   ---------        ---------
+
+        Args:
+            feature_filter (str, optional): Filters the features presented to only those that
+                contain this filter substring
+                Default = "", results in all the features being printed
+            module_fqn_filter (str, optional): Only includes modules that contains this string
+                Default = "", results in all the modules in the reports to be visible in the table
+
+        Example Use:
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> mod_report_visualizer.generate_table_visualization(
+            ...     feature_filter = "per_channel_min",
+            ...     module_fqn_filter = "block1"
+            ... )
+            >>> # prints out neatly formatted table with per_channel_min info
+            >>> # for all modules in block 1 of the model
+        """
+        # see if we got tabulate
+        if not got_tabulate:
+            print("Make sure to install tabulate and try again.")
+            return None
+
+        # get the table dict and the specific tables of interest
+        table_dict = self.generate_filtered_tables(feature_filter, module_fqn_filter)
+        tensor_headers, tensor_table = table_dict[self.TABLE_TENSOR_KEY]
+        channel_headers, channel_table = table_dict[self.TABLE_CHANNEL_KEY]
+
+        # get the table string and print it out
+        # now we have populated the tables for each one
+        # let's create the strings to be returned
+        table_str = ""
+        # the tables will have some headers columns that are non-feature
+        # ex. table index, module name, channel index, etc.
+        # we want to look at header columns for features, that come after those headers
+        if len(tensor_headers) > self.NUM_NON_FEATURE_TENSOR_HEADERS:
+            # if we have at least one tensor level feature to be added we add tensor table
+            table_str += "Tensor Level Information \n"
+            table_str += tabulate(tensor_table, headers=tensor_headers)
+        if len(channel_headers) > self.NUM_NON_FEATURE_CHANNEL_HEADERS:
+            # if we have at least one channel level feature to be added we add tensor table
+            table_str += "\n\n Channel Level Information \n"
+            table_str += tabulate(channel_table, headers=channel_headers)
+
+        # if no features at all, let user know
+        if table_str == "":
+            table_str = "No data points to generate table with."
+
+        print(table_str)
+
+    def _get_plottable_data(
+        self, feature_filter: str, module_fqn_filter: str
+    ) -> tuple[list, list[list], bool]:
+        r"""
+        Takes in the feature filters and module filters and outputs the x and y data for plotting
+
+        Args:
+            feature_filter (str): Filters the features presented to only those that
+                contain this filter substring
+            module_fqn_filter (str): Only includes modules that contains this string
+
+        Returns a tuple of three elements
+            The first is a list containing relevant x-axis data
+            The second is a list containing the corresponding y-axis data
+            If the data is per channel
+        """
+        # get the table dict and the specific tables of interest
+        table_dict = self.generate_filtered_tables(feature_filter, module_fqn_filter)
+        tensor_headers, tensor_table = table_dict[self.TABLE_TENSOR_KEY]
+        channel_headers, channel_table = table_dict[self.TABLE_CHANNEL_KEY]
+
+        # make sure it is only 1 feature that is being plotted
+        # get the number of features in each of these
+        tensor_info_features_count = (
+            len(tensor_headers) - ModelReportVisualizer.NUM_NON_FEATURE_TENSOR_HEADERS
+        )
+        channel_info_features_count = (
+            len(channel_headers) - ModelReportVisualizer.NUM_NON_FEATURE_CHANNEL_HEADERS
+        )
+
+        # see if valid tensor or channel plot
+        is_valid_per_tensor_plot: bool = tensor_info_features_count == 1
+        is_valid_per_channel_plot: bool = channel_info_features_count == 1
+
+        # offset should either be one of tensor or channel table or neither
+        feature_column_offset = ModelReportVisualizer.NUM_NON_FEATURE_TENSOR_HEADERS
+        table = tensor_table
+
+        # if a per_channel plot, we have different offset and table
+        if is_valid_per_channel_plot:
+            feature_column_offset = (
+                ModelReportVisualizer.NUM_NON_FEATURE_CHANNEL_HEADERS
+            )
+            table = channel_table
+
+        x_data: list = []
+        y_data: list[list] = []
+        # the feature will either be a tensor feature or channel feature
+        if is_valid_per_tensor_plot:
+            for table_row_num, row in enumerate(table):
+                # get x_value to append
+                x_val_to_append = table_row_num
+                # the index of the feature will the 0 + num non feature columns
+                tensor_feature_index = feature_column_offset
+                row_value = row[tensor_feature_index]
+                if not type(row_value) == str:
+                    x_data.append(x_val_to_append)
+                    y_data.append(row_value)
+        elif is_valid_per_channel_plot:
+            # gather the x_data and multiple y_data
+            # calculate the number of channels
+            num_channels: int = max(row[self.CHANNEL_NUM_INDEX] for row in table) + 1
+
+            # separate data list per channel
+            y_data.extend([] for _ in range(num_channels))
+
+            for table_row_num, row in enumerate(table):
+                # get x_value to append
+                x_val_to_append = table_row_num
+                current_channel = row[
+                    self.CHANNEL_NUM_INDEX
+                ]  # initially chose current channel
+                new_module_index: int = table_row_num // num_channels
+                x_val_to_append = new_module_index
+
+                # the index of the feature will the 0 + num non feature columns
+                tensor_feature_index = feature_column_offset
+                row_value = row[tensor_feature_index]
+                if not type(row_value) == str:
+                    # only append if new index we are appending
+                    if len(x_data) == 0 or x_data[-1] != x_val_to_append:
+                        x_data.append(x_val_to_append)
+
+                    # append value for that channel
+                    y_data[current_channel].append(row_value)
+        else:
+            # more than one feature was chosen
+            error_str = "Make sure to pick only a single feature with your filter to plot a graph."
+            error_str += " We recommend calling get_all_unique_feature_names() to find unique feature names."
+            error_str += " Pick one of those features to plot."
+            raise ValueError(error_str)
+
+        # return x, y values, and if data is per-channel
+        return (x_data, y_data, is_valid_per_channel_plot)
+
+    def generate_plot_visualization(
+        self, feature_filter: str, module_fqn_filter: str = ""
+    ):
+        r"""
+        Takes in a feature and optional module_filter and plots of the desired data.
+
+        For per channel features, it averages the value across the channels and plots a point
+        per module. The reason for this is that for models with hundreds of channels, it can
+        be hard to differentiate one channel line from another, and so the point of generating
+        a single average point per module is to give a sense of general trends that encourage
+        further deep dives.
+
+        Note:
+            Only features in the report that have tensor value data are plottable by this class
+            When the tensor information is plotted, it will plot:
+                idx as the x val, feature value as the y_val
+            When the channel information is plotted, it will plot:
+                the first idx of each module as the x val, feature value as the y_val [for each channel]
+                The reason for this is that we want to be able to compare values across the
+                channels for same layer, and it will be hard if values are staggered by idx
+                This means each module is represented by only 1 x value
+        Args:
+            feature_filter (str): Filters the features presented to only those that
+                contain this filter substring
+            module_fqn_filter (str, optional): Only includes modules that contains this string
+                Default = "", results in all the modules in the reports to be visible in the table
+
+        Example Use:
+            >>> # xdoctest: +SKIP("undefined variables")
+            >>> mod_report_visualizer.generate_plot_visualization(
+            ...     feature_filter = "per_channel_min",
+            ...     module_fqn_filter = "block1"
+            ... )
+            >>> # outputs line plot of per_channel_min information for all
+            >>> # modules in block1 of model each channel gets it's own line,
+            >>> # and it's plotted across the in-order modules on the x-axis
+        """
+        # checks if we have matplotlib and let's user know to install it if don't
+        if not got_matplotlib:
+            print("make sure to install matplotlib and try again.")
+            return None
+
+        # get the x and y data and if per channel
+        x_data, y_data, data_per_channel = self._get_plottable_data(
+            feature_filter, module_fqn_filter
+        )
+
+        # plot based on whether data is per channel or not
+        ax = plt.subplot()
+        ax.set_ylabel(feature_filter)
+        ax.set_title(feature_filter + " Plot")
+        plt.xticks(x_data)  # only show ticks for actual points
+
+        if data_per_channel:
+            ax.set_xlabel("First idx of module")
+            # set the legend as well
+            # plot a single line that is average of the channel values
+            num_modules = len(
+                y_data[0]
+            )  # all y_data have same length, so get num modules
+            num_channels = len(
+                y_data
+            )  # we want num channels to be able to calculate average later
+
+            avg_vals = [
+                sum(y_data[:][index]) / num_channels for index in range(num_modules)
+            ]
+
+            # plot the three things we measured
+            ax.plot(
+                x_data, avg_vals, label=f"Average Value Across {num_channels} Channels"
+            )
+            ax.legend(loc="upper right")
+        else:
+            ax.set_xlabel("idx")
+            ax.plot(x_data, y_data)
+
+        # actually show the plot
+        plt.show()
+
+    def generate_histogram_visualization(
+        self, feature_filter: str, module_fqn_filter: str = "", num_bins: int = 10
+    ):
+        r"""
+        Takes in a feature and optional module_filter and plots the histogram of desired data.
+
+        Note:
+            Only features in the report that have tensor value data can be viewed as a histogram
+            If you want to plot a histogram from all the channel values of a specific feature for
+                a specific model, make sure to specify both the model and the feature properly
+                in the filters and you should be able to see a distribution of the channel data
+
+        Args:
+            feature_filter (str, optional): Filters the features presented to only those that
+                contain this filter substring
+                Default = "", results in all the features being printed
+            module_fqn_filter (str, optional): Only includes modules that contains this string
+                Default = "", results in all the modules in the reports to be visible in the table
+            num_bins (int, optional): The number of bins to create the histogram with
+                Default = 10, the values will be split into 10 equal sized bins
+
+        Example Use:
+            >>> # xdoctest: +SKIP
+            >>> mod_report_visualizer.generategenerate_histogram_visualization_plot_visualization(
+            ...     feature_filter = "per_channel_min",
+            ...     module_fqn_filter = "block1"
+            ... )
+            # outputs histogram of per_channel_min information for all modules in block1 of model
+                information is gathered across all channels for all modules in block 1 for the
+                per_channel_min and is displayed in a histogram of equally sized bins
+        """
+        # checks if we have matplotlib and let's user know to install it if don't
+        if not got_matplotlib:
+            print("make sure to install matplotlib and try again.")
+            return None
+
+        # get the x and y data and if per channel
+        _x_data, y_data, data_per_channel = self._get_plottable_data(
+            feature_filter, module_fqn_filter
+        )
+
+        # for histogram, we just care about plotting the y data
+        # plot based on whether data is per channel or not
+        ax = plt.subplot()
+        ax.set_xlabel(feature_filter)
+        ax.set_ylabel("Frequency")
+        ax.set_title(feature_filter + " Histogram")
+
+        if data_per_channel:
+            # set the legend as well
+            # combine all the data
+            all_data = []
+            for channel_info in y_data:
+                all_data.extend(channel_info)
+
+            _val, bins, _ = plt.hist(
+                all_data,
+                bins=num_bins,
+                stacked=True,
+                rwidth=0.8,
+            )
+            plt.xticks(bins)
+        else:
+            _val, bins, _ = plt.hist(
+                y_data,
+                bins=num_bins,
+                stacked=False,
+                rwidth=0.8,
+            )
+            plt.xticks(bins)
+
+        plt.show()
diff --git a/shared/package-files/56/561b4079ddeed0db2f683b21940753e274d9396c0edb6ca2c476196d149fb4d0/_foreach_norm.h b/shared/package-files/56/561b4079ddeed0db2f683b21940753e274d9396c0edb6ca2c476196d149fb4d0/_foreach_norm.h
new file mode 100644
index 0000000000000000000000000000000000000000..98a3ad79330682dead49ca3e5e2b83293a9b9d1e
--- /dev/null
+++ b/shared/package-files/56/561b4079ddeed0db2f683b21940753e274d9396c0edb6ca2c476196d149fb4d0/_foreach_norm.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[]
+inline ::std::vector _foreach_norm(at::TensorList self, const at::Scalar & ord=2, ::std::optional dtype=::std::nullopt) {
+    return at::_ops::_foreach_norm_Scalar::call(self, ord, dtype);
+}
+
+// aten::_foreach_norm.Scalar_out(Tensor[] self, Scalar ord=2, ScalarType? dtype=None, *, Tensor(a!)[] out) -> ()
+inline void _foreach_norm_out(at::TensorList out, at::TensorList self, const at::Scalar & ord=2, ::std::optional dtype=::std::nullopt) {
+    return at::_ops::_foreach_norm_Scalar_out::call(self, ord, dtype, out);
+}
+// aten::_foreach_norm.Scalar_out(Tensor[] self, Scalar ord=2, ScalarType? dtype=None, *, Tensor(a!)[] out) -> ()
+inline void _foreach_norm_outf(at::TensorList self, const at::Scalar & ord, ::std::optional dtype, at::TensorList out) {
+    return at::_ops::_foreach_norm_Scalar_out::call(self, ord, dtype, out);
+}
+
+}
diff --git a/shared/package-files/56/561db2227eacb921144724d216a3e3559b98e2d4757620e737ab4eb3df574b49/_linalg_solve_ex.h b/shared/package-files/56/561db2227eacb921144724d216a3e3559b98e2d4757620e737ab4eb3df574b49/_linalg_solve_ex.h
new file mode 100644
index 0000000000000000000000000000000000000000..ca5152aa439f7e06dc1853a07cbe6433e6f2e063
--- /dev/null
+++ b/shared/package-files/56/561db2227eacb921144724d216a3e3559b98e2d4757620e737ab4eb3df574b49/_linalg_solve_ex.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info)
+inline ::std::tuple _linalg_solve_ex(const at::Tensor & A, const at::Tensor & B, bool left=true, bool check_errors=false) {
+    return at::_ops::_linalg_solve_ex::call(A, B, left, check_errors);
+}
+
+// aten::_linalg_solve_ex.result(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info)
+inline ::std::tuple _linalg_solve_ex_out(at::Tensor & result, at::Tensor & LU, at::Tensor & pivots, at::Tensor & info, const at::Tensor & A, const at::Tensor & B, bool left=true, bool check_errors=false) {
+    return at::_ops::_linalg_solve_ex_result::call(A, B, left, check_errors, result, LU, pivots, info);
+}
+// aten::_linalg_solve_ex.result(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info)
+inline ::std::tuple _linalg_solve_ex_outf(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors, at::Tensor & result, at::Tensor & LU, at::Tensor & pivots, at::Tensor & info) {
+    return at::_ops::_linalg_solve_ex_result::call(A, B, left, check_errors, result, LU, pivots, info);
+}
+
+}
diff --git a/shared/package-files/56/562042078c2752549f6d8a7c86dbc5dd708088a7be6d80672ec7b07100b72468/METADATA b/shared/package-files/56/562042078c2752549f6d8a7c86dbc5dd708088a7be6d80672ec7b07100b72468/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..cfde03c2631c5c1d5cdc0949d0ee3379e7110f0e
--- /dev/null
+++ b/shared/package-files/56/562042078c2752549f6d8a7c86dbc5dd708088a7be6d80672ec7b07100b72468/METADATA
@@ -0,0 +1,43 @@
+Metadata-Version: 2.1
+Name: six
+Version: 1.17.0
+Summary: Python 2 and 3 compatibility utilities
+Home-page: https://github.com/benjaminp/six
+Author: Benjamin Peterson
+Author-email: benjamin@python.org
+License: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Utilities
+Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*
+License-File: LICENSE
+
+.. image:: https://img.shields.io/pypi/v/six.svg
+   :target: https://pypi.org/project/six/
+   :alt: six on PyPI
+
+.. image:: https://readthedocs.org/projects/six/badge/?version=latest
+   :target: https://six.readthedocs.io/
+   :alt: six's documentation on Read the Docs
+
+.. image:: https://img.shields.io/badge/license-MIT-green.svg
+   :target: https://github.com/benjaminp/six/blob/master/LICENSE
+   :alt: MIT License badge
+
+Six is a Python 2 and 3 compatibility library.  It provides utility functions
+for smoothing over the differences between the Python versions with the goal of
+writing Python code that is compatible on both Python versions.  See the
+documentation for more information on what is provided.
+
+Six supports Python 2.7 and 3.3+.  It is contained in only one Python
+file, so it can be easily copied into your project. (The copyright and license
+notice must be retained.)
+
+Online documentation is at https://six.readthedocs.io/.
+
+Bugs can be reported to https://github.com/benjaminp/six.  The code can also
+be found there.
diff --git a/shared/package-files/56/5625120a3f4ab117dac4aa3e761eeb6a0e67ab8eb2bc353d055596575a74a85d/vcfsom.c.pysam.c b/shared/package-files/56/5625120a3f4ab117dac4aa3e761eeb6a0e67ab8eb2bc353d055596575a74a85d/vcfsom.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..4e56158cc4cb41a456ec9e69f32c39569f6ac15a
--- /dev/null
+++ b/shared/package-files/56/5625120a3f4ab117dac4aa3e761eeb6a0e67ab8eb2bc353d055596575a74a85d/vcfsom.c.pysam.c
@@ -0,0 +1,720 @@
+#include "bcftools.pysam.h"
+
+/*  vcfsom.c -- SOM (Self-Organizing Map) filtering.
+
+    Copyright (C) 2013-2014, 2020 Genome Research Ltd.
+
+    Author: Petr Danecek 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.  */
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include "bcftools.h"
+
+#define SOM_TRAIN    1
+#define SOM_CLASSIFY 2
+
+typedef struct
+{
+    int ndim;       // dimension of the map (2D, 3D, ...)
+    int nbin;       // number of bins in th map
+    int size;       // pow(nbin,ndim)
+    int kdim;       // dimension of the input vectors
+    int nt, t;      // total number of learning cycles and the current cycle
+    double *w, *c;  // weights and counts (sum of learning influence)
+    double learn;   // learning rate
+    double bmu_th;  // best-matching unit threshold
+    int *a_idx, *b_idx; // temp arrays for traversing variable number of nested loops
+    double *div;        // dtto
+}
+som_t;
+
+typedef struct
+{
+    // SOM parameters
+    double bmu_th, learn;
+    int ndim, nbin, ntrain, t;
+    int nfold;                  // n-fold cross validation = the number of SOMs
+    som_t **som;
+
+    // annots reader's data
+    htsFile *file;              // reader
+    kstring_t str;              // temporary string for the reader
+    int dclass, mvals;
+    double *vals;
+
+    // training data
+    double *train_dat;
+    int *train_class, mtrain_class, mtrain_dat;
+
+    int rand_seed, good_class, bad_class;
+    char **argv, *fname, *prefix;
+    int argc, action, train_bad, merge;
+}
+args_t;
+
+static void usage(void);
+FILE *open_file(char **fname, const char *mode, const char *fmt, ...) HTS_FORMAT(HTS_PRINTF_FMT, 3, 4);
+
+char * HTS_FORMAT(HTS_PRINTF_FMT, 1, 2) msprintf(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+    int n = vsnprintf(NULL, 0, fmt, ap) + 2;
+    va_end(ap);
+
+    char *str = (char*)malloc(n);
+    va_start(ap, fmt);
+    vsnprintf(str, n, fmt, ap);
+    va_end(ap);
+
+    return str;
+}
+
+/*
+ *  char *t, *p = str;
+ *  t = column_next(p, '\t');
+ *  if ( strlen("")==t-p && !strncmp(p,"",t-p) ) fprintf(bcftools_stdout, "found!\n");
+ *
+ *  char *t;
+ *  t = column_next(str, '\t'); if ( !*t ) error("expected field\n", str);
+ *  t = column_next(t+1, '\t'); if ( !*t ) error("expected field\n", str);
+ */
+static inline char *column_next(char *start, char delim)
+{
+    char *end = start;
+    while (*end && *end!=delim) end++;
+    return end;
+}
+/**
+ *  annots_reader_next() - reads next line from annots.tab.gz and sets: class, vals
+ *   Returns 1 on successful read or 0 if no further record could be read.
+ */
+int annots_reader_next(args_t *args)
+{
+    args->str.l = 0;
+    if ( hts_getline(args->file,'\n',&args->str)<=0 ) return 0;
+
+    char *t, *line = args->str.s;
+
+    if ( !args->mvals )
+    {
+        t = line;
+        while ( *t )
+        {
+            if ( *t=='\t' ) args->mvals++;
+            t++;
+        }
+        args->vals = (double*) malloc(args->mvals*sizeof(double));
+    }
+
+    // class
+    args->dclass = atoi(line);
+    t = column_next(line, '\t');
+
+    // values
+    int i;
+    for (i=0; imvals; i++)
+    {
+        if ( !*t ) error("Could not parse %d-th data field: is the line truncated?\nThe line was: [%s]\n",i+2,line);
+        args->vals[i] = atof(++t);
+        t = column_next(t,'\t');
+    }
+    return 1;
+}
+void annots_reader_reset(args_t *args)
+{
+    if ( args->file ) hts_close(args->file);
+    if ( !args->fname ) error("annots_reader_reset: no fname\n");
+    args->file = hts_open(args->fname, "r");
+}
+void annots_reader_close(args_t *args)
+{
+    hts_close(args->file);
+}
+
+static void som_write_map(char *prefix, som_t **som, int nsom)
+{
+    FILE *fp = open_file(NULL,"w","%s.som",prefix);
+    size_t nw;
+    if ( (nw=fwrite("SOMv1",5,1,fp))!=5 ) error("Failed to write 5 bytes\n");
+    if ( (nw=fwrite(&nsom,sizeof(int),1,fp))!=sizeof(int) ) error("Failed to write %zu bytes\n",sizeof(int));
+    int i;
+    for (i=0; isize,sizeof(int),1,fp))!=sizeof(int) ) error("Failed to write %zu bytes\n",sizeof(int));
+        if ( (nw=fwrite(&som[i]->kdim,sizeof(int),1,fp))!=sizeof(int) ) error("Failed to write %zu bytes\n",sizeof(int));
+        if ( (nw=fwrite(som[i]->w,sizeof(double),som[i]->size*som[i]->kdim,fp))!=sizeof(double)*som[i]->size*som[i]->kdim ) error("Failed to write %zu bytes\n",sizeof(double)*som[i]->size*som[i]->kdim);
+        if ( (nw=fwrite(som[i]->c,sizeof(double),som[i]->size,fp))!=sizeof(double)*som[i]->size ) error("Failed to write %zu bytes\n",sizeof(double)*som[i]->size);
+    }
+    if ( fclose(fp) ) error("%s.som: fclose failed\n",prefix);
+}
+static som_t** som_load_map(char *prefix, int *nsom)
+{
+    FILE *fp = open_file(NULL,"r","%s.som",prefix);
+    char buf[5];
+    if ( fread(buf,5,1,fp)!=1 || strncmp(buf,"SOMv1",5) ) error("Could not parse %s.som\n", prefix);
+
+    if ( fread(nsom,sizeof(int),1,fp)!=1 ) error("Could not read %s.som\n", prefix);
+    som_t **som = (som_t**)malloc(*nsom*sizeof(som_t*));
+
+    int i;
+    for (i=0; i<*nsom; i++)
+    {
+        som[i] = (som_t*) calloc(1,sizeof(som_t));
+        if ( fread(&som[i]->size,sizeof(int),1,fp) != 1 ) error("Could not read %s.som\n", prefix);
+        if ( fread(&som[i]->kdim,sizeof(int),1,fp) != 1 ) error("Could not read %s.som\n", prefix);
+        som[i]->w = (double*) malloc(sizeof(double)*som[i]->size*som[i]->kdim);
+        som[i]->c = (double*) malloc(sizeof(double)*som[i]->size);
+        if ( fread(som[i]->w,sizeof(double),som[i]->size*som[i]->kdim,fp) != som[i]->size*som[i]->kdim ) error("Could not read from %s.som\n", prefix);
+        if ( fread(som[i]->c,sizeof(double),som[i]->size,fp) != som[i]->size ) error("Could not read from %s.som\n", prefix);
+    }
+    if ( fclose(fp) ) error("%s.som: fclose failed\n",prefix);
+    return som;
+}
+static void som_create_plot(som_t *som, char *prefix)
+{
+    if ( som->ndim!=2 ) return;
+
+    char *fname;
+    FILE *fp = open_file(&fname,"w","%s.py",prefix);
+    fprintf(fp,
+            "import matplotlib as mpl\n"
+            "mpl.use('Agg')\n"
+            "import matplotlib.pyplot as plt\n"
+            "\n"
+            "dat = [\n"
+           );
+    int i,j;
+    double *val = som->c;
+    for (i=0; inbin; i++)
+    {
+        fprintf(fp,"[");
+        for (j=0; jnbin; j++)
+        {
+            if ( j>0 ) fprintf(fp,",");
+            fprintf(fp,"%e", *val);
+            val++;
+        }
+        fprintf(fp,"],\n");
+    }
+    fprintf(fp,
+            "]\n"
+            "fig = plt.figure()\n"
+            "ax1 = plt.subplot(111)\n"
+            "im1 = ax1.imshow(dat)\n"
+            "fig.colorbar(im1)\n"
+            "plt.savefig('%s.png')\n"
+            "plt.close()\n"
+            "\n", prefix
+           );
+    fclose(fp);
+    free(fname);
+}
+// Find the best matching unit: the node with minimum distance from the input vector
+static inline int som_find_bmu(som_t *som, double *vec, double *dist)
+{
+    double *ptr = som->w;
+    double min_dist = HUGE_VAL;
+    int min_idx = 0;
+
+    int i, k;
+    for (i=0; isize; i++)
+    {
+        double dist = 0;
+        for (k=0; kkdim; k++)
+            dist += (vec[k] - ptr[k]) * (vec[k] - ptr[k]);
+        if ( dist < min_dist )
+        {
+            min_dist = dist;
+            min_idx  = i;
+        }
+        ptr += som->kdim;
+    }
+
+    if ( dist ) *dist = min_dist;
+    return min_idx;
+}
+static inline double som_get_score(som_t *som, double *vec, double bmu_th)
+{
+    double *ptr = som->w;
+    double min_dist = HUGE_VAL;
+
+    int i, k;
+    for (i=0; isize; i++)
+    {
+        if ( som->c[i] >= bmu_th )
+        {
+            double dist = 0;
+            for (k=0; kkdim; k++)
+                dist += (vec[k] - ptr[k]) * (vec[k] - ptr[k]);
+            if ( dist < min_dist ) min_dist = dist;
+        }
+        ptr += som->kdim;
+    }
+    return sqrt(min_dist);
+}
+// Convert flat index to that of a k-dimensional cube
+static inline void som_idx_to_ndim(som_t *som, int idx, int *ndim)
+{
+    int i;
+    double sub = 0;
+
+    ndim[0] = idx/som->div[0];
+    for (i=1; indim; i++)
+    {
+        sub += ndim[i-1] * som->div[i-1];
+        ndim[i] = (idx - sub)/som->div[i];
+    }
+}
+static void som_train_site(som_t *som, double *vec, int update_counts)
+{
+    // update learning rate and learning radius
+    som->t++;
+    double dt = exp(-som->t/som->nt);
+    double learning_rate = som->learn * dt;
+    double radius = som->nbin * dt; radius *= radius;
+
+    // find the best matching unit and its indexes
+    int min_idx = som_find_bmu(som, vec, NULL);
+    som_idx_to_ndim(som, min_idx, som->a_idx);
+
+    // update the weights: traverse the map and make all nodes within the
+    // radius more similar to the input vector
+    double *ptr = som->w;
+    double *cnt = som->c;
+    int i, j, k;
+    for (i=0; isize; i++)
+    {
+        som_idx_to_ndim(som, i, som->b_idx);
+        double dist = 0;
+        for (j=0; jndim; j++)
+            dist += (som->a_idx[j] - som->b_idx[j]) * (som->a_idx[j] - som->b_idx[j]);
+        if ( dist <= radius )
+        {
+            double influence = exp(-dist*dist*0.5/radius) * learning_rate;
+            for (k=0; kkdim; k++)
+                ptr[k] += influence * (vec[k] - ptr[k]);
+
+            // Bad sites may help to shape the map, but only nodes with big enough
+            // influence will be used for classification.
+            if ( update_counts ) *cnt += influence;
+        }
+        ptr += som->kdim;
+        cnt++;
+    }
+}
+static void som_norm_counts(som_t *som)
+{
+    int i;
+    double max = 0;
+    for (i=0; isize; i++)
+        if ( max < som->c[i] ) max = som->c[i];
+    for (i=0; isize; i++)
+        som->c[i] /= max;
+}
+static som_t *som_init(args_t *args)
+{
+    som_t *som  = (som_t*) calloc(1,sizeof(som_t));
+    som->ndim   = args->ndim;
+    som->nbin   = args->nbin;
+    som->kdim   = args->mvals;
+    som->nt     = args->ntrain;
+    som->learn  = args->learn;
+    som->bmu_th = args->bmu_th;
+    som->size   = pow(som->nbin,som->ndim);
+    som->w = (double*) malloc(sizeof(double)*som->size*som->kdim);
+    if ( !som->w ) error("Could not alloc %"PRIu64" bytes [nbin=%d ndim=%d kdim=%d]\n", (uint64_t)(sizeof(double)*som->size*som->kdim),som->nbin,som->ndim,som->kdim);
+    som->c = (double*) calloc(som->size,sizeof(double));
+    if ( !som->w ) error("Could not alloc %"PRIu64" bytes [nbin=%d ndim=%d]\n", (uint64_t)(sizeof(double)*som->size),som->nbin,som->ndim);
+    int i;
+    for (i=0; isize*som->kdim; i++)
+        som->w[i] = random();
+    som->a_idx = (int*) malloc(sizeof(int)*som->ndim);
+    som->b_idx = (int*) malloc(sizeof(int)*som->ndim);
+    som->div   = (double*) malloc(sizeof(double)*som->ndim);
+    for (i=0; indim; i++)
+        som->div[i] = pow(som->nbin,som->ndim-i-1);
+    return som;
+}
+static void som_destroy(som_t *som)
+{
+    free(som->a_idx); free(som->b_idx); free(som->div);
+    free(som->w); free(som->c);
+    free(som);
+}
+
+static void init_data(args_t *args)
+{
+    // Get first line to learn the vector size
+    annots_reader_reset(args);
+    annots_reader_next(args);
+
+    if ( args->action==SOM_CLASSIFY )
+        args->som = som_load_map(args->prefix,&args->nfold);
+}
+static void destroy_data(args_t *args)
+{
+    int i;
+    if ( args->som )
+    {
+        for (i=0; infold; i++) som_destroy(args->som[i]);
+    }
+    free(args->train_dat);
+    free(args->train_class);
+    free(args->som);
+    free(args->vals);
+    free(args->str.s);
+}
+
+#define MERGE_MIN 0
+#define MERGE_MAX 1
+#define MERGE_AVG 2
+static double get_min_score(args_t *args, int iskip)
+{
+    int i;
+    double score, min_score = HUGE_VAL;
+    for (i=0; infold; i++)
+    {
+        if ( i==iskip ) continue;
+        score = som_get_score(args->som[i], args->vals, args->bmu_th);
+        if ( i==0 || score < min_score ) min_score = score;
+    }
+    return min_score;
+}
+static double get_max_score(args_t *args, int iskip)
+{
+    int i;
+    double score, max_score = -HUGE_VAL;
+    for (i=0; infold; i++)
+    {
+        if ( i==iskip ) continue;
+        score = som_get_score(args->som[i], args->vals, args->bmu_th);
+        if ( i==0 || max_score < score ) max_score = score;
+    }
+    return max_score;
+}
+static double get_avg_score(args_t *args, int iskip)
+{
+    int i, n = 0;
+    double score = 0;
+    for (i=0; infold; i++)
+    {
+        if ( i==iskip ) continue;
+        score += som_get_score(args->som[i], args->vals, args->bmu_th);
+        n++;
+    }
+    return score/n;
+}
+static int cmpfloat_desc(const void *a, const void *b)
+{
+    float fa = *((float*)a);
+    float fb = *((float*)b);
+    if ( fafb ) return -1;
+    return 0;
+}
+
+static void create_eval_plot(args_t *args)
+{
+    FILE *fp = open_file(NULL,"w","%s.eval.py", args->prefix);
+    fprintf(fp,
+            "import matplotlib as mpl\n"
+            "mpl.use('Agg')\n"
+            "import matplotlib.pyplot as plt\n"
+            "\n"
+            "import csv\n"
+            "csv.register_dialect('tab', delimiter='\\t', quoting=csv.QUOTE_NONE)\n"
+            "dat = []\n"
+            "with open('%s.eval', 'r') as f:\n"
+            "\treader = csv.reader(f, 'tab')\n"
+            "\tfor row in reader:\n"
+            "\t\tif row[0][0]!='#': dat.append(row)\n"
+            "\n"
+            "fig = plt.figure()\n"
+            "ax1 = plt.subplot(111)\n"
+            "ax1.plot([x[0] for x in dat],[x[1] for x in dat],'g',label='Good')\n"
+            "ax1.plot([x[0] for x in dat],[x[2] for x in dat],'r',label='Bad')\n"
+            "ax1.set_xlabel('SOM score')\n"
+            "ax1.set_ylabel('Number of training sites')\n"
+            "ax1.legend(loc='best',prop={'size':8},frameon=False)\n"
+            "plt.savefig('%s.eval.png')\n"
+            "plt.close()\n"
+            "\n", args->prefix,args->prefix
+           );
+    fclose(fp);
+}
+
+static void do_train(args_t *args)
+{
+    // read training sites
+    int i, igood = 0, ibad = 0, ngood = 0, nbad = 0, ntrain = 0;
+    annots_reader_reset(args);
+    while ( annots_reader_next(args) )
+    {
+        // determine which of the nfold's SOMs to train
+        int isom = 0;
+        if ( args->dclass == args->good_class )
+        {
+            if ( ++igood >= args->nfold ) igood = 0;
+            isom = igood;
+            ngood++;
+        }
+        else if ( args->dclass == args->bad_class )
+        {
+            if ( ++ibad >= args->nfold ) ibad = 0;
+            isom = ibad;
+            nbad++;
+        }
+        else
+            error("Could not determine the class: %d (vs %d and %d)\n", args->dclass,args->good_class,args->bad_class);
+
+        // save the values for evaluation
+        ntrain++;
+        hts_expand(double, ntrain*args->mvals, args->mtrain_dat, args->train_dat);
+        hts_expand(int, ntrain, args->mtrain_class, args->train_class);
+        memcpy(args->train_dat+(ntrain-1)*args->mvals, args->vals, args->mvals*sizeof(double));
+        args->train_class[ntrain-1] = (args->dclass==args->good_class ? 1 : 0) | isom<<1;  // store class + chunk used for training
+    }
+    annots_reader_close(args);
+
+    // init maps
+    if ( !args->ntrain ) args->ntrain = ngood/args->nfold;
+    srandom(args->rand_seed);
+    args->som = (som_t**) malloc(sizeof(som_t*)*args->nfold);
+    for (i=0; infold; i++) args->som[i] = som_init(args);
+
+    // train
+    for (i=0; itrain_class[i] & 1;
+        int isom    = args->train_class[i] >> 1;
+        if ( is_good || args->train_bad )
+            som_train_site(args->som[isom], args->train_dat+i*args->mvals, is_good);
+    }
+
+    // norm and create plots
+    for (i=0; infold; i++)
+    {
+        som_norm_counts(args->som[i]);
+        if ( args->prefix )
+        {
+            char *bname = msprintf("%s.som.%d", args->prefix,i);
+            som_create_plot(args->som[i], bname);
+            free(bname);
+        }
+    }
+
+    // evaluate
+    float *good = (float*) malloc(sizeof(float)*ngood); assert(good);
+    float *bad  = (float*) malloc(sizeof(float)*nbad); assert(bad);
+    igood = ibad = 0;
+    double max_score = sqrt(args->som[0]->kdim);
+    for (i=0; itrain_class[i] & 1;
+        int isom    = args->train_class[i] >> 1;    // this vector was used for training isom-th SOM, skip
+        if ( args->nfold==1 ) isom = -1;
+        memcpy(args->vals, args->train_dat+i*args->mvals, args->mvals*sizeof(double));
+        switch (args->merge)
+        {
+            case MERGE_MIN: score = get_min_score(args, isom); break;
+            case MERGE_MAX: score = get_max_score(args, isom); break;
+            case MERGE_AVG: score = get_avg_score(args, isom); break;
+        }
+        score = 1.0 - score/max_score;
+        if ( is_good )
+            good[igood++] = score;
+        else
+            bad[ibad++] = score;
+    }
+    qsort(good, ngood, sizeof(float), cmpfloat_desc);
+    qsort(bad, nbad, sizeof(float), cmpfloat_desc);
+    FILE *fp = NULL;
+    if ( args->prefix ) fp = open_file(NULL,"w","%s.eval", args->prefix);
+    igood = 0;
+    ibad  = 0;
+    float prev_score = good[0]>bad[0] ? good[0] : bad[0];
+    int printed = 0;
+    while ( igood 0.9 )
+        {
+            fprintf(bcftools_stdout, "%.2f\t%.2f\t%e\t# %% of bad [1] and good [2] sites at a cutoff [3]\n", 100.*ibad/nbad,100.*igood/ngood,prev_score);
+            printed = 1;
+        }
+
+        if ( igoodbad[ibad] ? good[igood] : bad[ibad];
+        else if ( igoodprefix,strerror(errno));
+        create_eval_plot(args);
+        som_write_map(args->prefix, args->som, args->nfold);
+    }
+
+    free(good);
+    free(bad);
+}
+
+static void do_classify(args_t *args)
+{
+    annots_reader_reset(args);
+    double max_score = sqrt(args->som[0]->kdim);
+    while ( annots_reader_next(args) )
+    {
+        double score = 0;
+        switch (args->merge)
+        {
+            case MERGE_MIN: score = get_min_score(args, -1); break;
+            case MERGE_MAX: score = get_max_score(args, -1); break;
+            case MERGE_AVG: score = get_avg_score(args, -1); break;
+        }
+        fprintf(bcftools_stdout, "%e\n", 1.0 - score/max_score);
+    }
+    annots_reader_close(args);
+}
+
+static void usage(void)
+{
+    fprintf(bcftools_stderr, "\n");
+    fprintf(bcftools_stderr, "About:   SOM (Self-Organizing Map) filtering.\n");
+    fprintf(bcftools_stderr, "Usage:   bcftools som --train    [options] \n");
+    fprintf(bcftools_stderr, "         bcftools som --classify [options]\n");
+    fprintf(bcftools_stderr, "\n");
+    fprintf(bcftools_stderr, "Model training options:\n");
+    fprintf(bcftools_stderr, "    -f, --nfold                   n-fold cross-validation (number of maps) [5]\n");
+    fprintf(bcftools_stderr, "    -p, --prefix               prefix of output files\n");
+    fprintf(bcftools_stderr, "    -s, --size                    map size [20]\n");
+    fprintf(bcftools_stderr, "    -t, --train                        \n");
+    fprintf(bcftools_stderr, "\n");
+    fprintf(bcftools_stderr, "Classifying options:\n");
+    fprintf(bcftools_stderr, "    -c, --classify                     \n");
+    fprintf(bcftools_stderr, "\n");
+    fprintf(bcftools_stderr, "Experimental training options (no reason to change):\n");
+    fprintf(bcftools_stderr, "    -b, --bmu-threshold         threshold for selection of best-matching unit [0.9]\n");
+    fprintf(bcftools_stderr, "    -d, --som-dimension           SOM dimension [2]\n");
+    fprintf(bcftools_stderr, "    -e, --exclude-bad                  exclude bad sites from training, use for evaluation only\n");
+    fprintf(bcftools_stderr, "    -l, --learning-rate         learning rate [1.0]\n");
+    fprintf(bcftools_stderr, "    -m, --merge           -f merge algorithm [avg]\n");
+    fprintf(bcftools_stderr, "    -n, --ntrain-sites            effective number of training sites [number of good sites]\n");
+    fprintf(bcftools_stderr, "    -r, --random-seed             random seed, 0 for time() [1]\n");
+    fprintf(bcftools_stderr, "\n");
+    bcftools_exit(1);
+}
+
+int main_vcfsom(int argc, char *argv[])
+{
+    int c;
+    args_t *args     = (args_t*) calloc(1,sizeof(args_t));
+    args->argc       = argc; args->argv = argv;
+    args->nbin       = 20;
+    args->learn      = 1.0;
+    args->bmu_th     = 0.9;
+    args->nfold      = 5;
+    args->rand_seed  = 1;
+    args->ndim       = 2;
+    args->bad_class  = 1;
+    args->good_class = 2;
+    args->merge      = MERGE_AVG;
+    args->train_bad  = 1;
+
+    static struct option loptions[] =
+    {
+        {"help",0,0,'h'},
+        {"prefix",1,0,'p'},
+        {"ntrain-sites",1,0,'n'},
+        {"random-seed",1,0,'r'},
+        {"bmu-threshold",1,0,'b'},
+        {"exclude-bad",0,0,'e'},
+        {"learning-rate",1,0,'l'},
+        {"size",1,0,'s'},
+        {"som-dimension",1,0,'d'},
+        {"nfold",1,0,'f'},
+        {"merge",1,0,'m'},
+        {"train",0,0,'t'},
+        {"classify",0,0,'c'},
+        {0,0,0,0}
+    };
+    while ((c = getopt_long(argc, argv, "htcp:n:r:b:l:s:f:d:m:e",loptions,NULL)) >= 0) {
+        switch (c) {
+            case 'e': args->train_bad = 0; break;
+            case 'm':
+                if ( !strcmp(optarg,"min") ) args->merge = MERGE_MIN;
+                else if ( !strcmp(optarg,"max") ) args->merge = MERGE_MAX;
+                else if ( !strcmp(optarg,"avg") ) args->merge = MERGE_AVG;
+                else error("The -m method not recognised: %s\n", optarg);
+                break;
+            case 'p': args->prefix = optarg; break;
+            case 'n': args->ntrain = atoi(optarg); break;
+            case 'r': args->rand_seed = atoi(optarg); break;
+            case 'b': args->bmu_th = atof(optarg); break;
+            case 'l': args->learn = atof(optarg); break;
+            case 's': args->nbin = atoi(optarg); break;
+            case 'f': args->nfold = atoi(optarg); break;
+            case 'd':
+                args->ndim = atoi(optarg);
+                if ( args->ndim<2 ) error("Expected -d >=2, got %d\n", args->ndim);
+                if ( args->ndim>3 ) fprintf(bcftools_stderr,"Warning: This will take a long time and is not going to make the results better: -d %d\n", args->ndim);
+                break;
+            case 't': args->action = SOM_TRAIN; break;
+            case 'c': args->action = SOM_CLASSIFY; break;
+            case 'h':
+            case '?': usage(); break;
+            default: error("Unknown argument: %s\n", optarg);
+        }
+    }
+
+    if ( !args->rand_seed ) args->rand_seed = time(NULL);
+    if ( argc!=optind+1 ) usage();
+    args->fname = argv[optind];
+    init_data(args);
+
+    if ( args->action == SOM_TRAIN ) do_train(args);
+    else if ( args->action == SOM_CLASSIFY ) do_classify(args);
+
+    destroy_data(args);
+    free(args);
+    return 0;
+}
+
diff --git a/shared/package-files/56/5627d1a0e0ad2fabf400456d8121547d0c43ee0d15efd8ff767fba93498a0f12/_nested_dict.cpython-311.pyc b/shared/package-files/56/5627d1a0e0ad2fabf400456d8121547d0c43ee0d15efd8ff767fba93498a0f12/_nested_dict.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f76a97f5e7058b195c7e00374e97be000a1c1c07
Binary files /dev/null and b/shared/package-files/56/5627d1a0e0ad2fabf400456d8121547d0c43ee0d15efd8ff767fba93498a0f12/_nested_dict.cpython-311.pyc differ
diff --git a/shared/package-files/56/562a9c88be2421121d82748b3b2c1d5b735099ac875537cd324c748722e7db27/_fsdp_param.py b/shared/package-files/56/562a9c88be2421121d82748b3b2c1d5b735099ac875537cd324c748722e7db27/_fsdp_param.py
new file mode 100644
index 0000000000000000000000000000000000000000..274bb9d1cc10e30de1e049385c9d69c39729b789
--- /dev/null
+++ b/shared/package-files/56/562a9c88be2421121d82748b3b2c1d5b735099ac875537cd324c748722e7db27/_fsdp_param.py
@@ -0,0 +1,906 @@
+# mypy: allow-untyped-defs
+import inspect
+import itertools
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from enum import auto, Enum
+from typing import Any, Callable, cast, Optional
+
+import torch
+import torch.nn as nn
+from torch._prims_common import make_contiguous_strides_for
+from torch.distributed._functional_collectives import AsyncCollectiveTensor
+from torch.distributed.tensor import DTensor, Replicate, Shard
+from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
+from torch.distributed.tensor.device_mesh import _mesh_resources
+from torch.distributed.tensor.placement_types import _StridedShard, Placement
+
+from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
+from ._fsdp_common import (
+    _chunk_with_empty,
+    _from_local_no_grad,
+    _get_dim_chunked_size,
+    _raise_assert_with_print,
+    _to_dtype_if_needed,
+    compiled_autograd_enabled,
+    FSDPMeshInfo,
+    HSDPMeshInfo,
+)
+
+
+"""
+[Note: FSDP tensors]
+FSDP considers the following tensors:
+- Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
+  on the module when applying FSDP
+- Sharded parameter: sharding the original parameter on dim-0 (or a
+  user-specified dim) as a DTensor over the main mesh
+- All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
+  derived from the sharded parameter
+- All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
+  all-gathering the all-gather inputs
+- Unsharded parameter: parameter used for forward/backward computation, derived
+  from the all-gather output; autograd leaf
+
+We define these tensors to describe the general framework that can accomodate
+extensions, where:
+- all-gather-inputs = pre-all-gather-transform(sharded-parameter)
+- unsharded-parameter = post-all-gather-transform(all-gather-outputs)
+
+For the default ``torch.Tensor`` case, there is only one all-gather input, and
+it shares the same underlying tensor data as the sharded parameter, meaning
+that they can be thought of as the same tensors. The same applies for the
+all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
+these equivalences may no longer hold due to the pre/post-all-gather
+transforms, and some may have multiple all-gather inputs/outputs (e.g.
+quantized data and scales).
+
+[Note: FSDP and autograd]
+FSDP dynamically frees and allocates the unsharded parameter. Since autograd
+can pack a reference to it or a view to save for backward, we use storage
+resizing to implement the freeing/allocation since that preserves the aliasing.
+This implies that we construct the unsharded parameter object once and write to
+it in-place thereafter. For the default ``torch.Tensor` original parameter
+case, the all-gather output and unsharded parameter share the same
+data, so we use storage resizing on the all-gather output.
+"""
+
+lib = torch.library.Library("fsdp", "FRAGMENT")  # noqa: TOR901
+
+lib.define("copy_(Tensor(a!) tensor, Tensor data) -> ()")
+
+
+@torch.library.impl(lib, "copy_", "Meta")
+@torch.library.impl(lib, "copy_", "CUDA")
+@torch.library.impl(lib, "copy_", "XPU")
+@torch.library.impl(lib, "copy_", "HPU")
+@torch.library.impl(lib, "copy_", "CPU")
+@torch.library.impl(lib, "copy_", "MTIA")
+def copy_(tensor, data):
+    tensor.copy_(data)
+
+
+"""
+[Note: Avoiding functionalization for fsdp.copy_ and inductor.resize_storage_bytes_]
+
+Currently we don't functionalize `fsdp.copy_` op or `inductor.resize_storage_bytes_` op
+(i.e. they show up as a mutation op in the middle of the AOT joint graph).
+
+Reason:
+Traceable FSDP2 compiled autograd BWD graph have the following traits:
+(1) Two inputs of the graph were aliased to each other (one from hook closed-over tensors, one from FWD saved tensors).
+(2) One of them is mutated (copy_ and resize_ to handle the all-gathered param).
+(3) They are both subclasses.
+The combination of these traits is not supported by AOTAutograd (it's difficult to reason about subclass aliasing).
+So this doesn't work at all for Traceable FSDP2.
+
+The compromise we use is to avoid functionalization for the FSDP2 copy_ and resize_ ops.
+This avoids the problem above, because from AOTAutograd point-of-view there are no mutations
+that functionalization needs to handle. (Although we need to be careful not to DCE those mutable ops.)
+
+We can avoid this functionalization because:
+(1) The nn.Parameter is never used before its .copy_() is called in eager code (i.e. no alias of it is created),
+so it's safe to call .copy_() in the middle of the graph to update its content and start using the nn.Parameter downstream.
+(2) We always re-allocate the buffer for nn.Parameter to store the AllGather output and to be used in downstream user ops.
+So calling resize-to-0 in the middle of the graph to free nn.Parameter memory after use should always be okay
+(since we always allocate anew next time we need it, we strictly don't need to keep the old tensor storage around anymore).
+
+Q: Wouldn't the extra resize_ and copy_ ops hurt both memory usage and performance?
+A: Yes it would. As an optimization, we have an Inductor post-grad FX pass to remove those resize_ and copy_ ops
+for unsharded params that have this pattern: resize_(full) -> copy_ -> resize_(0).
+
+TODO:
+Now that we are maintaining the invariant of "no aliased + mutated graph inputs" in both the forward and backward,
+it is now more feasible to functionalize all of the mutable FSDP ops. Some of the pros and cons are:
+
+Cons (of functionalizing those ops):
+(1) By not functionalizing them as we are today, we are making it more likely that they will run at the "correct" time
+in the generated code. If we start to functionalize them, we will need to make sure that Inductor reinplaces them
+in a way where it properly moves the mutations back to exactly where they should have run, or we risk suffering worse
+peak memory than eager. (We probably already need to do something similar in Inductor's reinplacing for copy_:
+https://github.com/pytorch/pytorch/issues/135305#issuecomment-2334888089)
+
+Pros (of functionalizing):
+(1) Better safety, we don't need to worry about the graph passes in inductor/partitioning handling input mutations
+mid-graph quite as much (to be fair we've already done some amount of auditing, but we might have to do some more).
+(2) Better perf: each mutation midway through the graph prevents Inductor from pattern matching across it.
+But maybe there are few enough mutations induced by FSDP for this to matter.
+"""
+
+
+@torch.library.impl(lib, "copy_", "Functionalize")
+def copy__functionalize(tensor, data):
+    torch._sync(tensor)
+    torch._sync(data)
+    tensor_inner = torch._from_functional_tensor(tensor)
+    data_inner = torch._from_functional_tensor(data)
+    with torch._C._ExcludeDispatchKeyGuard(
+        torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
+    ):
+        torch.ops.fsdp.copy_.default(tensor_inner, data_inner)
+
+
+if not torch._running_with_deploy():
+    torch.fx.node.has_side_effect(torch.ops.fsdp.copy_.default)
+
+
+class ShardedState(Enum):
+    """
+    - ``SHARDED``: The sharded parameter is registered to the module. It is the
+      only contributor to parameter memory.
+    - ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
+      smaller world size. Since this data should not be used for computation,
+      we do not register it to the module. Users should reshard the module
+      before any in-place modifications. Both it and the sharded parameter
+      contribute to parameter memory.
+    - ``UNSHARDED``: The unsharded parameter is registered to the module. Both
+      it and the sharded parameter contribute to parameter memory.
+    """
+
+    SHARDED = auto()
+    SHARDED_POST_FORWARD = auto()
+    UNSHARDED = auto()
+
+
+@dataclass
+class ParamModuleInfo:
+    """
+    For a parameter, this stores the module and the parameter name to be able
+    to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
+    the parameter via ``getattr(module, param_name)``. We additionally save
+    shared modules and shared parameter names to update them accordingly.
+    """
+
+    # Parameter names are unprefixed, e.g. "weight", not "lin.weight"
+    module: nn.Module
+    param_name: str
+    shared_modules: list[nn.Module] = field(default_factory=list)
+    shared_param_names: list[str] = field(default_factory=list)
+
+
+@dataclass
+class ExtensionsData:
+    # User-defined metadata passed from pre to post-all-gather
+    all_gather_metadata: Optional[Any] = None
+    # Save the all-gather input sizes to unflatten the all-gather outputs to ND
+    all_gather_input_sizes: Sequence[torch.Size] = ()  # ND
+
+    def clear(self):
+        self.all_gather_metadata = None
+        self.all_gather_input_sizes = ()
+
+
+class FSDPParam:
+    """
+    This class manages a parameter with FSDP or FSDP variants applied,
+    implementing dim-0 per-parameter sharding.
+    """
+
+    orig_dtype: torch.dtype
+    param_dtype: Optional[torch.dtype]
+    reduce_dtype: Optional[torch.dtype]
+    _orig_size: torch.Size  # ND
+    sharded_size: torch.Size  # ND
+    contiguous_sharded_stride: tuple[int, ...]
+    padded_sharded_param_size: torch.Size  # ND
+    sharded_post_forward_size: torch.Size  # ND
+    contiguous_sharded_post_forward_stride: tuple[int, ...]
+    _sharded_param_data: torch.Tensor  # 1D
+    sharded_param: nn.Parameter  # ND
+    _sharded_post_forward_param_data: Optional[torch.Tensor]  # 1D
+    _sharded_post_forward_param: Optional[nn.Parameter]  # ND
+    _unsharded_param: nn.Parameter  # ND
+    unsharded_accumulated_grad: Optional[torch.Tensor]  # ND
+    _sharding_spec: DTensorSpec
+    # DTensor attributes (only defined for DTensor `param`):
+    _tp_spec: DTensorSpec
+    all_gather_outputs: list[torch.Tensor]  # 1D
+    # All-gather extension attributes
+    _extensions_data: ExtensionsData
+    _unsharded_inner_tensors: list[torch.Tensor]
+
+    def __init__(
+        self,
+        param: nn.Parameter,
+        module_info: ParamModuleInfo,
+        mesh_info: FSDPMeshInfo,
+        post_forward_mesh_info: Optional[FSDPMeshInfo],
+        device: torch.device,
+        shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
+        mp_policy: MixedPrecisionPolicy,
+        offload_policy: OffloadPolicy,
+    ):
+        self._module_info: ParamModuleInfo = module_info
+        self.mesh_info = mesh_info
+        self.post_forward_mesh_info = post_forward_mesh_info
+        self.device = device
+        self.mp_policy = mp_policy
+        self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
+        self.pin_memory = (
+            self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
+        )
+        self.grad_offload_event: Optional[torch.Event] = None
+        self._init_sharded_param(param, device, shard_placement_fn)
+        if self.post_forward_mesh_info:
+            self._init_sharded_post_forward_param_metadata(param)
+        self._init_extensions()
+        self.all_gather_outputs: list[torch.Tensor] = []
+        self.unsharded_accumulated_grad = None
+        self._param_fqn: Optional[str] = None  # prefixed from root module
+        # TODO: Remove this padding logic once DTensor pads the local tensor:
+        # https://github.com/pytorch/pytorch/issues/113045
+        self._post_load_hook_handle = (
+            module_info.module.register_load_state_dict_post_hook(
+                lambda *args, **kwargs: self.reset_sharded_param()
+            )
+        )
+
+    @torch.no_grad()
+    def _init_sharded_param(
+        self,
+        param: nn.Parameter,
+        device: torch.device,
+        shard_placement_fn: Optional[Callable],
+    ):
+        if param.device != device and param.device.type != "meta":
+            raise AssertionError(
+                f"Expects the parameter to already be moved to device {device} but got {param.device}"
+            )
+        if not param.is_contiguous():
+            raise NotImplementedError(
+                f"FSDP does not support non-contiguous parameters yet: {param.shape=} {param.stride()=}"
+            )
+        fsdp_placement = shard_placement_fn(param) if shard_placement_fn else None
+        if fsdp_placement is None:
+            fsdp_placement = Shard(0)
+        elif fsdp_placement.dim < 0:
+            fsdp_placement = Shard(fsdp_placement.dim + param.ndim)
+        assert isinstance(fsdp_placement, Shard), f"{fsdp_placement}"
+        self.fsdp_placement = fsdp_placement
+        shard_dim = fsdp_placement.dim
+        # TODO: Replace the sharded DTensor parameter construction logic with
+        # `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
+        # TODO: Simplify the following sharded parameter padding logic after
+        # https://github.com/pytorch/pytorch/issues/113045
+        self.is_dtensor = isinstance(param, DTensor)
+        if self.is_dtensor:
+            self._tp_spec = cast(DTensor, param)._spec
+            dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
+            dp_global_mesh = _mesh_resources.get_root_mesh(dp_mesh)
+            tp_global_mesh = _mesh_resources.get_root_mesh(tp_mesh)
+            if dp_global_mesh != tp_global_mesh or (
+                dp_global_mesh is None or tp_global_mesh is None
+            ):
+                raise AssertionError(
+                    "FSDP requires the DP and TP mesh to have the same parent mesh but got: \n"
+                    f"DP's global mesh: {dp_global_mesh}\nTP's global mesh: {tp_global_mesh}"
+                )
+            name_dims_error = "FSDP requires named DeviceMesh dims for ND parallelism"
+            assert dp_mesh.mesh_dim_names is not None, name_dims_error
+            assert tp_mesh.mesh_dim_names is not None, name_dims_error
+            submesh_names = dp_mesh.mesh_dim_names + tp_mesh.mesh_dim_names
+            self._spmd_mesh = dp_global_mesh[submesh_names]
+            if len(self._tp_spec.placements) != 1:
+                raise NotImplementedError(
+                    f"FSDP only supports 1D TP, not {self._tp_spec.placements}"
+                )
+            split_factor = self._tp_spec.num_shards_map[shard_dim]
+            assert 2 <= self._spmd_mesh.ndim <= 3, (
+                f"_spmd_mesh.ndim can only be 2 or 3 but got {self._spmd_mesh.ndim}."
+            )
+            self._spmd_placements: tuple[Placement, ...]
+            dp_shard_tp_placement = (
+                (
+                    _StridedShard(shard_dim, split_factor=split_factor)
+                    if split_factor > 1
+                    else fsdp_placement
+                ),
+                self._tp_spec.placements[0],
+            )
+            if self._spmd_mesh.ndim == 2:
+                self._spmd_placements = dp_shard_tp_placement
+            else:
+                assert self.mesh_info.replicate_mesh_dim == 0
+                self._spmd_placements = (Replicate(),) + dp_shard_tp_placement
+            self._sharding_spec = DTensorSpec(
+                self._spmd_mesh,
+                self._spmd_placements,
+                tensor_meta=self._tp_spec.tensor_meta,
+            )
+            # TODO: Enable uneven sharding for FSDP+TP.
+            if split_factor > 1:  # FSDP has strided sharding on tensor dim 0
+                num_shards = self._sharding_spec.num_shards_map[0]
+                tensor_size_dim_0 = self._sharding_spec.shape[0]
+                if tensor_size_dim_0 % num_shards != 0:
+                    raise NotImplementedError(
+                        "FSDP+TP sharding does not support uneven sharding for now: "
+                        f"tensor dim 0 has size {tensor_size_dim_0} which cannot be "
+                        f"evenly sharded into {num_shards} shards."
+                    )
+            param_data = cast(DTensor, param)._local_tensor
+        else:
+            self._spmd_mesh = self.mesh_info.mesh
+            if isinstance(self.mesh_info, HSDPMeshInfo):
+                self._spmd_placements = (Replicate(), fsdp_placement)
+            else:
+                self._spmd_placements = (fsdp_placement,)
+            self._sharding_spec = DTensorSpec(
+                self._spmd_mesh,
+                self._spmd_placements,
+                tensor_meta=TensorMeta(param.size(), param.stride(), param.dtype),
+            )
+            param_data = param
+        assert param_data.is_contiguous(), f"{param_data.shape=} {param_data.stride()=}"
+        shard_dim = fsdp_placement.dim
+        if shard_dim >= param_data.ndim:
+            raise AssertionError(
+                f"Shard dim {shard_dim} is invalid for {param_data.ndim}D tensor: {param.shape}"
+            )
+        self._orig_size = param_data.size()
+        self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
+        shard_rank = self.mesh_info.shard_mesh_rank
+        shard_world_size = self.mesh_info.shard_mesh_size
+        if shard_dim > 0 and param_data.size(shard_dim) % shard_world_size != 0:
+            # If sharding on nonzero dim, require even sharding for now because
+            # the uneven sharding (1) requires extra copies before/after FSDP
+            # collectives and (2) introduces extra complexity to handle padding
+            # and unpadding
+            raise NotImplementedError(
+                f"FSDP does not support uneven sharding on dim {shard_dim}: "
+                f"{param_data.size()} (world size: {shard_world_size})"
+            )
+        chunks = _chunk_with_empty(param_data, shard_world_size, dim=shard_dim)
+        sharded_param = chunks[shard_rank]
+        self.sharded_size = _get_dim_chunked_size(
+            sharded_param, param_data.size(), dim=shard_dim
+        )
+        self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
+        padded_sharded_size = chunks[0].size()  # 0th always padded
+        self.padded_sharded_param_size = padded_sharded_size
+        # Pre-pad the sharded parameter to avoid padding before all-gather
+        padded_sharded_param = param_data.new_zeros(padded_sharded_size)
+        if sharded_param.numel() > 0:
+            padded_sharded_param.narrow(
+                dim=shard_dim, start=0, length=sharded_param.size(shard_dim)
+            ).copy_(sharded_param)
+        if self.offload_to_cpu and not padded_sharded_param.is_meta:
+            padded_sharded_param = padded_sharded_param.cpu()
+            if self.pin_memory:
+                padded_sharded_param = padded_sharded_param.pin_memory(
+                    device=self.device
+                )
+        self._sharded_param_data = padded_sharded_param.view(-1)
+        length = sharded_param.size(shard_dim) if sharded_param.numel() > 0 else 0
+        sharded_param = padded_sharded_param.narrow(
+            dim=shard_dim, start=0, length=length
+        )
+        assert sharded_param.is_contiguous(), f"{self.fsdp_placement=}"
+        self.sharded_param = nn.Parameter(self.to_sharded_dtensor(sharded_param))
+        self.sharded_param.requires_grad_(param.requires_grad)
+        # Let `param_data` be freed normally when its ref count reaches 0 when
+        # the `fully_shard` call returns to allow provided parameters to alias
+        self._setattr_on_modules(self.sharded_param)
+        self.sharded_state = ShardedState.SHARDED
+
+    def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
+        mesh_info = self.post_forward_mesh_info
+        assert mesh_info is not None  # mypy
+        param_data = param._local_tensor if isinstance(param, DTensor) else param
+        chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
+        self.sharded_post_forward_size = _get_dim_chunked_size(
+            chunks[mesh_info.shard_mesh_rank],
+            param_data.size(),
+            dim=self.fsdp_placement.dim,
+        )
+        self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
+            self.sharded_post_forward_size
+        )
+
+    def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
+        param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
+        self.orig_dtype = self.sharded_param.dtype
+        # Clamp `reduce_dtype` to `None` if no casting is required: since
+        # gradients are computed in `param_dtype`, if `reduce_dtype` matches,
+        # then we do not need extra casting
+        if reduce_dtype == param_dtype:
+            reduce_dtype = None
+        # Clamp `param_dtype` to `None` if no casting is required
+        if param_dtype == self.orig_dtype:
+            param_dtype = None
+        self.param_dtype = param_dtype
+        self.reduce_dtype = reduce_dtype
+        # None indicates that the mixed precision is not enabled
+
+    def _init_extensions(self) -> None:
+        inner_tensor = self._sharded_local_tensor
+        has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
+        has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
+        if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
+            raise AssertionError(
+                "Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
+                f"if using all-gather extensions: {inner_tensor}"
+            )
+        if has_fsdp_pre_all_gather:
+            self._extensions_data = ExtensionsData()
+        self._unsharded_inner_tensors: list[torch.Tensor] = []
+
+    def init_all_gather_outputs(
+        self,
+        all_gather_input_numels: list[int],
+        all_gather_input_dtypes: list[torch.dtype],
+        world_size: int,
+        device: torch.device,
+        force_recreate: bool = False,
+    ):
+        if not force_recreate and len(self.all_gather_outputs) > 0:
+            return  # already initialized
+        self.all_gather_outputs = [
+            torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
+            for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
+        ]
+
+    def init_unsharded_param(self):
+        """
+        [Note: Invariants for torch.compile Traceable FSDP2]
+        1. Under compile, we always re-populate the content of `self._unsharded_param`
+           per AllGather using the slow path.
+        2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
+           This is to ensure the buffer creation is internal to the graph and
+           avoid `self.all_gather_outputs` being captured as a graph input.
+        3. Under compile, at the end of `free_unsharded_param()`, we always clean up
+           `self.all_gather_outputs` and `self._unsharded_inner_tensors`,
+           to avoid them being captured as graph output.
+
+        With these invariants, only these tensors will be inputs to the graph:
+        - Sharded parameters
+        - Placeholders for the `self._unsharded_param` nn.Parameter
+        """
+        if not compiled_autograd_enabled() and hasattr(
+            self, "_unsharded_param"
+        ):  # after the 1st all-gather
+            inner_tensor = self._sharded_local_tensor
+            if not hasattr(inner_tensor, "fsdp_post_all_gather"):
+                return  # already initialized
+            for tensor in self._unsharded_inner_tensors:
+                alloc_storage(tensor)
+            all_gather_outputs = self._unflatten_all_gather_outputs()
+            inner_tensor.fsdp_post_all_gather(
+                all_gather_outputs,
+                self._extensions_data.all_gather_metadata,
+                self.param_dtype or self.orig_dtype,
+                out=self._unsharded_param,
+            )
+            self._extensions_data.clear()
+            return
+        inner_tensor = self._sharded_local_tensor
+        if not compiled_autograd_enabled() and hasattr(
+            inner_tensor, "fsdp_post_all_gather"
+        ):
+            all_gather_outputs = self._unflatten_all_gather_outputs()
+            (
+                unsharded_tensor,
+                self._unsharded_inner_tensors,
+            ) = inner_tensor.fsdp_post_all_gather(
+                all_gather_outputs,
+                self._extensions_data.all_gather_metadata,
+                self.param_dtype or self.orig_dtype,
+            )
+            self._extensions_data.clear()
+        else:
+            # For the default path (no post-all-gather), the all-gather output
+            # gives the unsharded parameter data directly
+            assert len(self.all_gather_outputs) == 1, f"{len(self.all_gather_outputs)}"
+            unsharded_tensor = self.all_gather_outputs[0]
+        unsharded_param = torch.as_strided(
+            unsharded_tensor,
+            self._orig_size,
+            self._contiguous_orig_stride,
+            storage_offset=0,
+        )
+        if self.is_dtensor:
+            unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
+        if hasattr(self, "_unsharded_param"):
+            assert compiled_autograd_enabled()
+            with (
+                torch.no_grad(),
+                torch.autograd._unsafe_preserve_version_counter(self._unsharded_param),
+            ):
+                # NOTE: Under compile, if an unsharded param goes through
+                # resize_(full) -> copy_ -> resize_(0) pattern, we will remove those
+                # resize_ and copy_ ops in a compiler graph pass
+                # `remove_fsdp2_unsharded_param_graph_input_usage` to recover performance.
+                self._unsharded_param.untyped_storage().resize_(
+                    self._unsharded_param.numel() * self._unsharded_param.itemsize
+                )
+                torch.ops.fsdp.copy_(self._unsharded_param, unsharded_param)
+        else:
+            self._unsharded_param = nn.Parameter(
+                unsharded_param, requires_grad=self.sharded_param.requires_grad
+            )
+
+    def _unflatten_all_gather_outputs(self) -> tuple[torch.Tensor, ...]:
+        return tuple(
+            t.view(-1, *s[1:])
+            for t, s in zip(
+                self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
+            )
+        )
+
+    def to_sharded(self) -> None:
+        self._setattr_on_modules(self.sharded_param)
+        self.free_unsharded_param()
+        self.sharded_state = ShardedState.SHARDED
+
+    def to_sharded_post_forward(self) -> None:
+        if self.is_dtensor:
+            raise NotImplementedError(
+                "Resharding to smaller mesh with TP is not supported yet"
+            )
+        self._assert_in_states(ShardedState.UNSHARDED)
+        assert self.post_forward_mesh_info is not None  # mypy
+        assert len(self.all_gather_outputs) == 1
+        shard_world_size = self.post_forward_mesh_info.shard_mesh_size
+        if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
+            _raise_assert_with_print(
+                f"All-gather output size ({numel}) must be divisible by the shard "
+                f"world size ({shard_world_size})"
+            )
+        shard_rank = self.post_forward_mesh_info.shard_mesh_rank
+        sharded_numel = numel // shard_world_size
+        self._sharded_post_forward_param_data = (
+            self.all_gather_outputs[0].narrow(
+                0, sharded_numel * shard_rank, sharded_numel
+            )
+        ).clone()  # clone to be able to free all-gather output
+        sharded_post_forward_tensor = torch.as_strided(
+            self._sharded_post_forward_param_data,
+            size=self.sharded_post_forward_size,
+            stride=self.contiguous_sharded_post_forward_stride,
+            storage_offset=0,
+        )
+        self._sharded_post_forward_param = nn.Parameter(
+            self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
+        )
+        self._setattr_on_modules(self._sharded_post_forward_param)
+        self.free_unsharded_param()
+        self.sharded_state = ShardedState.SHARDED_POST_FORWARD
+
+    def to_unsharded(self) -> None:
+        # Assume that the data has been allocated and all-gathered
+        set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
+        self._setattr_on_modules(self._unsharded_param)
+        if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
+            # The data is allocated in the default stream via the post-forward
+            # reshard and must be kept alive for the next all-gather copy-in.
+            # Since we call this method after the copy-out, the data's lifetime
+            # is ensured without further synchronization.
+            self._sharded_post_forward_param = None
+            self._sharded_post_forward_param_data = None  # free
+        self.sharded_state = ShardedState.UNSHARDED
+
+    def _setattr_on_modules(self, param: nn.Parameter) -> None:
+        unsafe_setattr_param(
+            self._module_info.module, self._module_info.param_name, param
+        )
+        for shared_module, shared_param_name in zip(
+            self._module_info.shared_modules, self._module_info.shared_param_names
+        ):
+            unsafe_setattr_param(shared_module, shared_param_name, param)
+
+    def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
+        """
+        Converts a local tensor representing either the sharded parameter or
+        sharded gradient to DTensor.
+        """
+        if tensor.shape != self.sharded_size:
+            _raise_assert_with_print(
+                f"Expects size {self.sharded_size} but got {tensor.shape}"
+            )
+        return _from_local_no_grad(
+            tensor,
+            self._sharding_spec,
+        )
+
+    def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
+        if tensor.shape != self.sharded_post_forward_size:
+            _raise_assert_with_print(
+                f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
+            )
+        assert isinstance(self.post_forward_mesh_info, HSDPMeshInfo)
+        # TODO: Prefer this DTensor to be read-only and generalize the
+        # placement once we support TP.
+        post_forward_sharding_spec = DTensorSpec(
+            self.post_forward_mesh_info.mesh,
+            (Replicate(), Shard(0)),
+            tensor_meta=self._sharding_spec.tensor_meta,
+        )
+        return _from_local_no_grad(tensor, post_forward_sharding_spec)
+
+    def to_accumulated_grad_if_needed(self) -> None:
+        # Access `_unsharded_param` to bypass the sharded state check since we
+        # prefer to reshard before upcasting the gradient to save memory
+        if (
+            self.reduce_dtype is None
+            or self._unsharded_param.grad is None
+            or self._unsharded_param.grad.dtype == self.reduce_dtype
+        ):
+            return
+        unsharded_grad = self._unsharded_param.grad
+        self._unsharded_param.grad = None
+        self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
+
+    def accumulate_unsharded_grad_if_needed(self) -> None:
+        if (
+            self.unsharded_accumulated_grad is not None
+            and self.unsharded_param.grad is not None
+        ):
+            self.unsharded_accumulated_grad += self.unsharded_param.grad
+            self.unsharded_param.grad = None
+
+    def alloc_all_gather_outputs(self) -> None:
+        for tensor in self.all_gather_outputs:
+            alloc_storage(tensor)
+
+    def free_unsharded_param(self) -> None:
+        if compiled_autograd_enabled():
+            """
+            Assumptions under compile:
+            - `self._unsharded_param` is NOT an alias of `self.all_gather_outputs`.
+            Instead, we resize `self._unsharded_param` storage size to full and then
+            explicitly *copy* the data from `self.all_gather_outputs` to `self._unsharded_param`
+            in `init_unsharded_param()`. (For full-graph FSDP2 case, we will then remove
+            the resize_ and copy_ ops in a compiler graph pass to recover performance.)
+            - `self.all_gather_outputs` and `self._unsharded_inner_tensors` are NOT
+            graph inputs. They are created within the graph and is guaranteed to be freed
+            by the end of the graph. They don't leak outside of the graph.
+            """
+            self._unsharded_param.untyped_storage().resize_(0)
+            self.all_gather_outputs = []
+            self._unsharded_inner_tensors = []
+        else:
+            for tensor in itertools.chain(
+                self.all_gather_outputs, self._unsharded_inner_tensors
+            ):
+                free_storage(tensor)
+
+    @property
+    def all_gather_inputs(self) -> list[torch.Tensor]:  # 1D
+        self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
+        if self.sharded_state == ShardedState.SHARDED:
+            if not compiled_autograd_enabled() and hasattr(
+                self._sharded_local_tensor, "fsdp_pre_all_gather"
+            ):
+                sharded_local_tensor = self._sharded_local_tensor
+                if self.offload_to_cpu:
+                    sharded_local_tensor = sharded_local_tensor.to(
+                        self.device, non_blocking=True
+                    )
+                pre_all_gather_signature = inspect.signature(
+                    sharded_local_tensor.fsdp_pre_all_gather
+                )
+                num_fn_params = len(pre_all_gather_signature.parameters)
+                # Old signature only passes mesh; keep for BC for now
+                assert num_fn_params in (
+                    1,
+                    5,
+                ), (
+                    f"Invalid fsdp_pre_all_gather: {pre_all_gather_signature}\n"
+                    "Expects fsdp_pre_all_gather(self, mesh: DeviceMesh, "
+                    "module: nn.Module, mp_policy: MixedPrecisionPolicy)"
+                )
+                if num_fn_params == 1:
+                    (
+                        all_gather_inputs,
+                        self._extensions_data.all_gather_metadata,
+                    ) = sharded_local_tensor.fsdp_pre_all_gather(
+                        self.shard_mesh_from_root
+                    )
+                else:
+                    (
+                        all_gather_inputs,
+                        self._extensions_data.all_gather_metadata,
+                    ) = sharded_local_tensor.fsdp_pre_all_gather(
+                        self.shard_mesh_from_root,
+                        self._orig_size,
+                        self._contiguous_orig_stride,
+                        self._module_info.module,
+                        self.mp_policy,
+                    )
+                    if (
+                        sharded_local_tensor.size() != self.padded_sharded_param_size
+                        and any(
+                            all_gather_input.size() != self.padded_sharded_param_size
+                            for all_gather_input in all_gather_inputs
+                        )
+                    ):
+                        # NOTE: Since this error can only be raised on the
+                        # ranks that have padding, this can manifest as a NCCL
+                        # watchdog timeout, as the other ranks will not error.
+                        raise AssertionError(
+                            "When a parameter is unevenly sharded by FSDP "
+                            f"(orig size={self._orig_size}, FSDP world size={self.mesh_info.mesh.size()}), "
+                            "fsdp_pre_all_gather must return all-gather inputs with the padded sharded size "
+                            f"{self.padded_sharded_param_size} but got {[t.size() for t in all_gather_inputs]}"
+                        )
+                self._extensions_data.all_gather_input_sizes = [
+                    t.size() for t in all_gather_inputs
+                ]
+                return [t.view(-1) for t in all_gather_inputs]
+            sharded_param_data = self._sharded_param_data
+            if self.offload_to_cpu:
+                sharded_param_data = sharded_param_data.to(
+                    self.device, non_blocking=True
+                )
+            return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
+        elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
+            if not compiled_autograd_enabled() and hasattr(
+                self._sharded_local_tensor, "fsdp_pre_all_gather"
+            ):
+                raise NotImplementedError
+            all_gather_input = _to_dtype_if_needed(
+                cast(torch.Tensor, self._sharded_post_forward_param_data),
+                self.param_dtype,
+            )
+            return [all_gather_input]
+        return [torch.empty(0)]  # mypy
+
+    @property
+    def unsharded_param(self) -> nn.Parameter:  # ND
+        return self._unsharded_param
+
+    @property
+    def unsharded_grad_data(self) -> torch.Tensor:
+        grad = self.unsharded_param.grad
+        assert grad is not None, "Expects unsharded_param.grad to not be None"
+        return self._get_grad_inner_tensor(grad)
+
+    @property
+    def unsharded_accumulated_grad_data(self) -> torch.Tensor:
+        grad = self.unsharded_accumulated_grad
+        assert grad is not None, "Expects unsharded_accumulated_grad to not be None"
+        return self._get_grad_inner_tensor(grad)
+
+    def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
+        if self.is_dtensor:
+            if isinstance(grad, AsyncCollectiveTensor):
+                grad = grad.wait()
+            assert isinstance(grad, DTensor), f"{type(grad)}"
+            placements = self._tp_spec.placements
+            if placements != grad.placements:
+                assert len(self._tp_spec.placements) == len(grad.placements), (
+                    f"{self._tp_spec=} {grad.placements=}"
+                )
+                grad = grad.redistribute(placements=placements)
+            grad = grad._local_tensor
+        return grad
+
+    @property
+    def _sharded_local_tensor(self) -> torch.Tensor:
+        return cast(DTensor, self.sharded_param)._local_tensor
+
+    @property
+    def shard_mesh(self):
+        mesh = self.mesh_info.mesh
+        if mesh.ndim == 1:
+            return mesh
+        elif mesh.ndim == 2:
+            assert mesh.mesh_dim_names is not None
+            return mesh[mesh.mesh_dim_names[-1]]
+        raise ValueError(f"Invalid mesh: {mesh}")
+
+    @property
+    def shard_mesh_from_root(self):
+        mesh = self.mesh_info.mesh
+
+        if mesh.ndim == 1:
+            return mesh
+        else:
+            assert mesh.mesh_dim_names is not None
+            shard_dim_name = mesh.mesh_dim_names[-1]
+
+            root_mesh = _mesh_resources.get_root_mesh(mesh)
+            return root_mesh[shard_dim_name]
+
+    def _assert_in_states(self, *states: ShardedState) -> None:
+        if self.sharded_state not in states:
+            _raise_assert_with_print(
+                f"Expects to be in one of {states}, not {self.sharded_state}"
+            )
+
+    def reset_sharded_param(self):
+        # For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
+        # that change the sharded parameter tensor, we may need to re-pad the
+        # sharded local tensor and re-save the reference.
+        module_info = self._module_info
+        new_param = getattr(module_info.module, module_info.param_name)
+        if new_param is not self.sharded_param:
+            if torch.__future__.get_swap_module_params_on_conversion():
+                raise AssertionError(
+                    f"Expects swap_tensors to preserve object but got {new_param} "
+                    f"instead of {self.sharded_param}"
+                )
+            self.sharded_param = new_param
+        local_tensor = new_param._local_tensor
+        if local_tensor.is_meta:
+            return
+        updated_local_tensor = False
+        padded_sharded_size = self.padded_sharded_param_size
+        shard_dim = self.fsdp_placement.dim
+        length = local_tensor.size(shard_dim) if local_tensor.numel() > 0 else 0
+        if local_tensor.size() != padded_sharded_size:
+            assert shard_dim == 0, (
+                f"Shard({shard_dim}) requires even sharding: {local_tensor.size()=}"
+            )
+            padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
+            padded_local_tensor.narrow(dim=shard_dim, start=0, length=length).copy_(
+                local_tensor
+            )
+            local_tensor = padded_local_tensor
+            updated_local_tensor = True
+        if self.pin_memory and not local_tensor.is_pinned():
+            local_tensor = local_tensor.cpu().pin_memory(device=self.device)
+            updated_local_tensor = True
+        self._sharded_param_data = local_tensor.view(-1)
+        assert isinstance(self.sharded_param, DTensor)  # mypy
+        if updated_local_tensor:
+            # Only change the local tensor object if needed
+            self.sharded_param._local_tensor = local_tensor.narrow(
+                dim=shard_dim, start=0, length=length
+            )
+            assert self.sharded_param._local_tensor.is_contiguous()
+        self._sharding_spec = self.sharded_param._spec
+
+    def __repr__(self):
+        return f"FSDPParam(fqn={self._param_fqn}, orig_size={self._orig_size})"
+
+
+def alloc_storage(tensor: torch.Tensor) -> None:
+    size = tensor.numel() * tensor.itemsize
+    if (storage := tensor.untyped_storage()).size() != size:
+        storage.resize_(size)
+
+
+def free_storage(tensor: torch.Tensor) -> None:
+    if (storage := tensor.untyped_storage()).size() != 0:
+        storage.resize_(0)
+
+
+# NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
+# CPU overhead, if the module did not override it. For FSDP, we know we do not
+# need those checks when transitioning between sharded/unsharded parameters.
+def unsafe_setattr_param(
+    module: nn.Module, param_name: str, param: nn.Parameter
+) -> None:
+    if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
+        module._parameters[param_name] = param
+    else:  # slow path
+        setattr(module, param_name, param)
+
+
+def set_requires_grad_if_needed(
+    src_tensor: torch.Tensor, dst_tensor: torch.Tensor
+) -> None:
+    # Only call `requires_grad_` if needed to avoid the Python <> C++ context
+    # switch overhead
+    if src_tensor.requires_grad != dst_tensor.requires_grad:
+        dst_tensor.requires_grad_(src_tensor.requires_grad)
diff --git a/shared/package-files/56/56309fc7c33601c0f79bc4c751b204622749c880a568dc3d8cc6ddfc5cdfa35b/matrix.h b/shared/package-files/56/56309fc7c33601c0f79bc4c751b204622749c880a568dc3d8cc6ddfc5cdfa35b/matrix.h
new file mode 100644
index 0000000000000000000000000000000000000000..5cf1f0a2a0566a8155ef7bcc10806883286615ff
--- /dev/null
+++ b/shared/package-files/56/56309fc7c33601c0f79bc4c751b204622749c880a568dc3d8cc6ddfc5cdfa35b/matrix.h
@@ -0,0 +1,715 @@
+/*
+    pybind11/eigen/matrix.h: Transparent conversion for dense and sparse Eigen matrices
+
+    Copyright (c) 2016 Wenzel Jakob 
+
+    All rights reserved. Use of this source code is governed by a
+    BSD-style license that can be found in the LICENSE file.
+*/
+
+#pragma once
+
+#include 
+
+#include "common.h"
+
+/* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
+   See also:
+       https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
+       https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
+*/
+PYBIND11_WARNING_PUSH
+PYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741
+//       C5054: operator '&': deprecated between enumerations of different types
+#if defined(__MINGW32__)
+PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
+#endif
+
+#include 
+#include 
+
+PYBIND11_WARNING_POP
+
+// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
+// move constructors that break things.  We could detect this an explicitly copy, but an extra copy
+// of matrices seems highly undesirable.
+static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
+              "Eigen matrix support in pybind11 requires Eigen >= 3.2.7");
+
+PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
+
+PYBIND11_WARNING_DISABLE_MSVC(4127)
+
+// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
+using EigenDStride = Eigen::Stride;
+template 
+using EigenDRef = Eigen::Ref;
+template 
+using EigenDMap = Eigen::Map;
+
+PYBIND11_NAMESPACE_BEGIN(detail)
+
+#if EIGEN_VERSION_AT_LEAST(3, 3, 0)
+using EigenIndex = Eigen::Index;
+template 
+using EigenMapSparseMatrix = Eigen::Map>;
+#else
+using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
+template 
+using EigenMapSparseMatrix = Eigen::MappedSparseMatrix;
+#endif
+
+// Matches Eigen::Map, Eigen::Ref, blocks, etc:
+template 
+using is_eigen_dense_map = all_of,
+                                  std::is_base_of, T>>;
+template 
+using is_eigen_mutable_map = std::is_base_of, T>;
+template 
+using is_eigen_dense_plain
+    = all_of>, is_template_base_of>;
+template 
+using is_eigen_sparse = is_template_base_of;
+// Test for objects inheriting from EigenBase that aren't captured by the above.  This
+// basically covers anything that can be assigned to a dense matrix but that don't have a typical
+// matrix data layout that can be copied from their .data().  For example, DiagonalMatrix and
+// SelfAdjointView fall into this category.
+template 
+using is_eigen_other
+    = all_of,
+             negation, is_eigen_dense_plain, is_eigen_sparse>>>;
+
+// Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
+template 
+struct EigenConformable {
+    bool conformable = false;
+    EigenIndex rows = 0, cols = 0;
+    EigenDStride stride{0, 0};    // Only valid if negativestrides is false!
+    bool negativestrides = false; // If true, do not use stride!
+
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    EigenConformable(bool fits = false) : conformable{fits} {}
+    // Matrix type:
+    EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
+        : conformable{true}, rows{r}, cols{c},
+          // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
+          // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
+          stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
+                               : (cstride > 0 ? cstride : 0) /* outer stride */,
+                 EigenRowMajor ? (cstride > 0 ? cstride : 0)
+                               : (rstride > 0 ? rstride : 0) /* inner stride */},
+          negativestrides{rstride < 0 || cstride < 0} {}
+    // Vector type:
+    EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
+        : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
+
+    template 
+    bool stride_compatible() const {
+        // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
+        // matching strides, or a dimension size of 1 (in which case the stride value is
+        // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
+        // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
+        if (negativestrides) {
+            return false;
+        }
+        if (rows == 0 || cols == 0) {
+            return true;
+        }
+        return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
+                || (EigenRowMajor ? cols : rows) == 1)
+               && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
+                   || (EigenRowMajor ? rows : cols) == 1);
+    }
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator bool() const { return conformable; }
+};
+
+template 
+struct eigen_extract_stride {
+    using type = Type;
+};
+template 
+struct eigen_extract_stride> {
+    using type = StrideType;
+};
+template 
+struct eigen_extract_stride> {
+    using type = StrideType;
+};
+
+// Helper struct for extracting information from an Eigen type
+template 
+struct EigenProps {
+    using Type = Type_;
+    using Scalar = typename Type::Scalar;
+    using StrideType = typename eigen_extract_stride::type;
+    static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
+                                size = Type::SizeAtCompileTime;
+    static constexpr bool row_major = Type::IsRowMajor,
+                          vector
+                          = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
+        fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
+                          fixed = size != Eigen::Dynamic, // Fully-fixed size
+        dynamic = !fixed_rows && !fixed_cols;             // Fully-dynamic size
+
+    template 
+    using if_zero = std::integral_constant;
+    static constexpr EigenIndex inner_stride
+        = if_zero::value,
+        outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
+        vector      ? size
+        : row_major ? cols
+                    : rows > ::value;
+    static constexpr bool dynamic_stride
+        = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
+    static constexpr bool requires_row_major
+        = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
+    static constexpr bool requires_col_major
+        = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
+
+    // Takes an input array and determines whether we can make it fit into the Eigen type.  If
+    // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
+    // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
+    static EigenConformable conformable(const array &a) {
+        const auto dims = a.ndim();
+        if (dims < 1 || dims > 2) {
+            return false;
+        }
+
+        if (dims == 2) { // Matrix type: require exact match (or dynamic)
+
+            EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
+                       np_rstride = a.strides(0) / static_cast(sizeof(Scalar)),
+                       np_cstride = a.strides(1) / static_cast(sizeof(Scalar));
+            if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {
+                return false;
+            }
+
+            return {np_rows, np_cols, np_rstride, np_cstride};
+        }
+
+        // Otherwise we're storing an n-vector.  Only one of the strides will be used, but
+        // whichever is used, we want the (single) numpy stride value.
+        const EigenIndex n = a.shape(0),
+                         stride = a.strides(0) / static_cast(sizeof(Scalar));
+
+        if (vector) { // Eigen type is a compile-time vector
+            if (fixed && size != n) {
+                return false; // Vector size mismatch
+            }
+            return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
+        }
+        if (fixed) {
+            // The type has a fixed size, but is not a vector: abort
+            return false;
+        }
+        if (fixed_cols) {
+            // Since this isn't a vector, cols must be != 1.  We allow this only if it exactly
+            // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
+            if (cols != n) {
+                return false;
+            }
+            return {1, n, stride};
+        } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
+        if (fixed_rows && rows != n) {
+            return false;
+        }
+        return {n, 1, stride};
+    }
+
+    static constexpr bool show_writeable
+        = is_eigen_dense_map::value && is_eigen_mutable_map::value;
+    static constexpr bool show_order = is_eigen_dense_map::value;
+    static constexpr bool show_c_contiguous = show_order && requires_row_major;
+    static constexpr bool show_f_contiguous
+        = !show_c_contiguous && show_order && requires_col_major;
+
+    static constexpr auto descriptor
+        = const_name("numpy.ndarray[") + npy_format_descriptor::name + const_name("[")
+          + const_name(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
+          + const_name(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
+          +
+          // For a reference type (e.g. Ref) we have other constraints that might need to
+          // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
+          // stride options, possibly f_contiguous or c_contiguous.  We include them in the
+          // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
+          // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
+          // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
+          const_name(", flags.writeable", "")
+          + const_name(", flags.c_contiguous", "")
+          + const_name(", flags.f_contiguous", "") + const_name("]");
+};
+
+// Casts an Eigen type to numpy array.  If given a base, the numpy array references the src data,
+// otherwise it'll make a copy.  writeable lets you turn off the writeable flag for the array.
+template 
+handle
+eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
+    constexpr ssize_t elem_size = sizeof(typename props::Scalar);
+    array a;
+    if (props::vector) {
+        a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
+    } else {
+        a = array({src.rows(), src.cols()},
+                  {elem_size * src.rowStride(), elem_size * src.colStride()},
+                  src.data(),
+                  base);
+    }
+
+    if (!writeable) {
+        array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
+    }
+
+    return a.release();
+}
+
+// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
+// reference the Eigen object's data with `base` as the python-registered base class (if omitted,
+// the base will be set to None, and lifetime management is up to the caller).  The numpy array is
+// non-writeable if the given type is const.
+template 
+handle eigen_ref_array(Type &src, handle parent = none()) {
+    // none here is to get past array's should-we-copy detection, which currently always
+    // copies when there is no base.  Setting the base to None should be harmless.
+    return eigen_array_cast(src, parent, !std::is_const::value);
+}
+
+// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
+// numpy array that references the encapsulated data with a python-side reference to the capsule to
+// tie its destruction to that of any dependent python objects.  Const-ness is determined by
+// whether or not the Type of the pointer given is const.
+template ::value>>
+handle eigen_encapsulate(Type *src) {
+    capsule base(src, [](void *o) { delete static_cast(o); });
+    return eigen_ref_array(*src, base);
+}
+
+// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
+// types.
+template 
+struct type_caster::value>> {
+    using Scalar = typename Type::Scalar;
+    static_assert(!std::is_pointer::value,
+                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
+    using props = EigenProps;
+
+    bool load(handle src, bool convert) {
+        // If we're in no-convert mode, only load if given an array of the correct type
+        if (!convert && !isinstance>(src)) {
+            return false;
+        }
+
+        // Coerce into an array, but don't do type conversion yet; the copy below handles it.
+        auto buf = array::ensure(src);
+
+        if (!buf) {
+            return false;
+        }
+
+        auto dims = buf.ndim();
+        if (dims < 1 || dims > 2) {
+            return false;
+        }
+
+        auto fits = props::conformable(buf);
+        if (!fits) {
+            return false;
+        }
+
+        // Allocate the new type, then build a numpy reference into it
+        value = Type(fits.rows, fits.cols);
+        auto ref = reinterpret_steal(eigen_ref_array(value));
+        if (dims == 1) {
+            ref = ref.squeeze();
+        } else if (ref.ndim() == 1) {
+            buf = buf.squeeze();
+        }
+
+        int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
+
+        if (result < 0) { // Copy failed!
+            PyErr_Clear();
+            return false;
+        }
+
+        return true;
+    }
+
+private:
+    // Cast implementation
+    template 
+    static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
+        switch (policy) {
+            case return_value_policy::take_ownership:
+            case return_value_policy::automatic:
+                return eigen_encapsulate(src);
+            case return_value_policy::move:
+                return eigen_encapsulate(new CType(std::move(*src)));
+            case return_value_policy::copy:
+                return eigen_array_cast(*src);
+            case return_value_policy::reference:
+            case return_value_policy::automatic_reference:
+                return eigen_ref_array(*src);
+            case return_value_policy::reference_internal:
+                return eigen_ref_array(*src, parent);
+            default:
+                throw cast_error("unhandled return_value_policy: should not happen!");
+        };
+    }
+
+public:
+    // Normal returned non-reference, non-const value:
+    static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
+        return cast_impl(&src, return_value_policy::move, parent);
+    }
+    // If you return a non-reference const, we mark the numpy array readonly:
+    static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
+        return cast_impl(&src, return_value_policy::move, parent);
+    }
+    // lvalue reference return; default (automatic) becomes copy
+    static handle cast(Type &src, return_value_policy policy, handle parent) {
+        if (policy == return_value_policy::automatic
+            || policy == return_value_policy::automatic_reference) {
+            policy = return_value_policy::copy;
+        }
+        return cast_impl(&src, policy, parent);
+    }
+    // const lvalue reference return; default (automatic) becomes copy
+    static handle cast(const Type &src, return_value_policy policy, handle parent) {
+        if (policy == return_value_policy::automatic
+            || policy == return_value_policy::automatic_reference) {
+            policy = return_value_policy::copy;
+        }
+        return cast(&src, policy, parent);
+    }
+    // non-const pointer return
+    static handle cast(Type *src, return_value_policy policy, handle parent) {
+        return cast_impl(src, policy, parent);
+    }
+    // const pointer return
+    static handle cast(const Type *src, return_value_policy policy, handle parent) {
+        return cast_impl(src, policy, parent);
+    }
+
+    static constexpr auto name = props::descriptor;
+
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator Type *() { return &value; }
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator Type &() { return value; }
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator Type &&() && { return std::move(value); }
+    template 
+    using cast_op_type = movable_cast_op_type;
+
+private:
+    Type value;
+};
+
+// Base class for casting reference/map/block/etc. objects back to python.
+template 
+struct eigen_map_caster {
+    static_assert(!std::is_pointer::value,
+                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
+
+private:
+    using props = EigenProps;
+
+public:
+    // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
+    // to stay around), but we'll allow it under the assumption that you know what you're doing
+    // (and have an appropriate keep_alive in place).  We return a numpy array pointing directly at
+    // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
+    // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
+    // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
+    static handle cast(const MapType &src, return_value_policy policy, handle parent) {
+        switch (policy) {
+            case return_value_policy::copy:
+                return eigen_array_cast(src);
+            case return_value_policy::reference_internal:
+                return eigen_array_cast(src, parent, is_eigen_mutable_map::value);
+            case return_value_policy::reference:
+            case return_value_policy::automatic:
+            case return_value_policy::automatic_reference:
+                return eigen_array_cast(src, none(), is_eigen_mutable_map::value);
+            default:
+                // move, take_ownership don't make any sense for a ref/map:
+                pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
+        }
+    }
+
+    static constexpr auto name = props::descriptor;
+
+    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
+    // types but not bound arguments).  We still provide them (with an explicitly delete) so that
+    // you end up here if you try anyway.
+    bool load(handle, bool) = delete;
+    operator MapType() = delete;
+    template 
+    using cast_op_type = MapType;
+};
+
+// We can return any map-like object (but can only load Refs, specialized next):
+template 
+struct type_caster::value>> : eigen_map_caster {};
+
+// Loader for Ref<...> arguments.  See the documentation for info on how to make this work without
+// copying (it requires some extra effort in many cases).
+template 
+struct type_caster<
+    Eigen::Ref,
+    enable_if_t>::value>>
+    : public eigen_map_caster> {
+private:
+    using Type = Eigen::Ref;
+    using props = EigenProps;
+    using Scalar = typename props::Scalar;
+    static_assert(!std::is_pointer::value,
+                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
+    using MapType = Eigen::Map;
+    using Array
+        = array_t;
+    static constexpr bool need_writeable = is_eigen_mutable_map::value;
+    // Delay construction (these have no default constructor)
+    std::unique_ptr map;
+    std::unique_ptr ref;
+    // Our array.  When possible, this is just a numpy array pointing to the source data, but
+    // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
+    // incompatible layout, or is an array of a type that needs to be converted).  Using a numpy
+    // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
+    // conversion and storage order conversion.  (Note that we refuse to use this temporary copy
+    // when loading an argument for a Ref with M non-const, i.e. a read-write reference).
+    Array copy_or_ref;
+
+public:
+    bool load(handle src, bool convert) {
+        // First check whether what we have is already an array of the right type.  If not, we
+        // can't avoid a copy (because the copy is also going to do type conversion).
+        bool need_copy = !isinstance(src);
+
+        EigenConformable fits;
+        if (!need_copy) {
+            // We don't need a converting copy, but we also need to check whether the strides are
+            // compatible with the Ref's stride requirements
+            auto aref = reinterpret_borrow(src);
+
+            if (aref && (!need_writeable || aref.writeable())) {
+                fits = props::conformable(aref);
+                if (!fits) {
+                    return false; // Incompatible dimensions
+                }
+                if (!fits.template stride_compatible()) {
+                    need_copy = true;
+                } else {
+                    copy_or_ref = std::move(aref);
+                }
+            } else {
+                need_copy = true;
+            }
+        }
+
+        if (need_copy) {
+            // We need to copy: If we need a mutable reference, or we're not supposed to convert
+            // (either because we're in the no-convert overload pass, or because we're explicitly
+            // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
+            if (!convert || need_writeable) {
+                return false;
+            }
+
+            Array copy = Array::ensure(src);
+            if (!copy) {
+                return false;
+            }
+            fits = props::conformable(copy);
+            if (!fits || !fits.template stride_compatible()) {
+                return false;
+            }
+            copy_or_ref = std::move(copy);
+            loader_life_support::add_patient(copy_or_ref);
+        }
+
+        ref.reset();
+        map.reset(new MapType(data(copy_or_ref),
+                              fits.rows,
+                              fits.cols,
+                              make_stride(fits.stride.outer(), fits.stride.inner())));
+        ref.reset(new Type(*map));
+
+        return true;
+    }
+
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator Type *() { return ref.get(); }
+    // NOLINTNEXTLINE(google-explicit-constructor)
+    operator Type &() { return *ref; }
+    template 
+    using cast_op_type = pybind11::detail::cast_op_type<_T>;
+
+private:
+    template ::value, int> = 0>
+    Scalar *data(Array &a) {
+        return a.mutable_data();
+    }
+
+    template ::value, int> = 0>
+    const Scalar *data(Array &a) {
+        return a.data();
+    }
+
+    // Attempt to figure out a constructor of `Stride` that will work.
+    // If both strides are fixed, use a default constructor:
+    template 
+    using stride_ctor_default = bool_constant::value>;
+    // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
+    // Eigen::Stride, and use it:
+    template 
+    using stride_ctor_dual
+        = bool_constant::value
+                        && std::is_constructible::value>;
+    // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
+    // it (passing whichever stride is dynamic).
+    template 
+    using stride_ctor_outer
+        = bool_constant, stride_ctor_dual>::value
+                        && S::OuterStrideAtCompileTime == Eigen::Dynamic
+                        && S::InnerStrideAtCompileTime != Eigen::Dynamic
+                        && std::is_constructible::value>;
+    template 
+    using stride_ctor_inner
+        = bool_constant, stride_ctor_dual>::value
+                        && S::InnerStrideAtCompileTime == Eigen::Dynamic
+                        && S::OuterStrideAtCompileTime != Eigen::Dynamic
+                        && std::is_constructible::value>;
+
+    template ::value, int> = 0>
+    static S make_stride(EigenIndex, EigenIndex) {
+        return S();
+    }
+    template ::value, int> = 0>
+    static S make_stride(EigenIndex outer, EigenIndex inner) {
+        return S(outer, inner);
+    }
+    template ::value, int> = 0>
+    static S make_stride(EigenIndex outer, EigenIndex) {
+        return S(outer);
+    }
+    template ::value, int> = 0>
+    static S make_stride(EigenIndex, EigenIndex inner) {
+        return S(inner);
+    }
+};
+
+// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
+// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
+// load() is not supported, but we can cast them into the python domain by first copying to a
+// regular Eigen::Matrix, then casting that.
+template 
+struct type_caster::value>> {
+    static_assert(!std::is_pointer::value,
+                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
+
+protected:
+    using Matrix
+        = Eigen::Matrix;
+    using props = EigenProps;
+
+public:
+    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
+        handle h = eigen_encapsulate(new Matrix(src));
+        return h;
+    }
+    static handle cast(const Type *src, return_value_policy policy, handle parent) {
+        return cast(*src, policy, parent);
+    }
+
+    static constexpr auto name = props::descriptor;
+
+    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
+    // types but not bound arguments).  We still provide them (with an explicitly delete) so that
+    // you end up here if you try anyway.
+    bool load(handle, bool) = delete;
+    operator Type() = delete;
+    template 
+    using cast_op_type = Type;
+};
+
+template 
+struct type_caster::value>> {
+    using Scalar = typename Type::Scalar;
+    static_assert(!std::is_pointer::value,
+                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
+    using StorageIndex = remove_reference_t().outerIndexPtr())>;
+    using Index = typename Type::Index;
+    static constexpr bool rowMajor = Type::IsRowMajor;
+
+    bool load(handle src, bool) {
+        if (!src) {
+            return false;
+        }
+
+        auto obj = reinterpret_borrow(src);
+        object sparse_module = module_::import("scipy.sparse");
+        object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
+
+        if (!type::handle_of(obj).is(matrix_type)) {
+            try {
+                obj = matrix_type(obj);
+            } catch (const error_already_set &) {
+                return false;
+            }
+        }
+
+        auto values = array_t((object) obj.attr("data"));
+        auto innerIndices = array_t((object) obj.attr("indices"));
+        auto outerIndices = array_t((object) obj.attr("indptr"));
+        auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
+        auto nnz = obj.attr("nnz").cast();
+
+        if (!values || !innerIndices || !outerIndices) {
+            return false;
+        }
+
+        value = EigenMapSparseMatrix(shape[0].cast(),
+                                                   shape[1].cast(),
+                                                   std::move(nnz),
+                                                   outerIndices.mutable_data(),
+                                                   innerIndices.mutable_data(),
+                                                   values.mutable_data());
+
+        return true;
+    }
+
+    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
+        const_cast(src).makeCompressed();
+
+        object matrix_type
+            = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
+
+        array data(src.nonZeros(), src.valuePtr());
+        array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
+        array innerIndices(src.nonZeros(), src.innerIndexPtr());
+
+        return matrix_type(pybind11::make_tuple(
+                               std::move(data), std::move(innerIndices), std::move(outerIndices)),
+                           pybind11::make_tuple(src.rows(), src.cols()))
+            .release();
+    }
+
+    PYBIND11_TYPE_CASTER(Type,
+                         const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
+                                                             "scipy.sparse.csc_matrix[")
+                             + npy_format_descriptor::name + const_name("]"));
+};
+
+PYBIND11_NAMESPACE_END(detail)
+PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
diff --git a/shared/package-files/56/563555a322a20735aae1bb3966bb10ae95f0db8fcf9db7678030b25aa1153cba/unique_dim_ops.h b/shared/package-files/56/563555a322a20735aae1bb3966bb10ae95f0db8fcf9db7678030b25aa1153cba/unique_dim_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b3c784a9a955d592b50b116ca3cd3175def570b
--- /dev/null
+++ b/shared/package-files/56/563555a322a20735aae1bb3966bb10ae95f0db8fcf9db7678030b25aa1153cba/unique_dim_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API unique_dim {
+  using schema = ::std::tuple (const at::Tensor &, int64_t, bool, bool, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::unique_dim";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)";
+  static ::std::tuple call(const at::Tensor & self, int64_t dim, bool sorted, bool return_inverse, bool return_counts);
+  static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool sorted, bool return_inverse, bool return_counts);
+};
+
+struct TORCH_API unique_dim_out {
+  using schema = ::std::tuple (const at::Tensor &, int64_t, bool, bool, bool, at::Tensor &, at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::unique_dim";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "unique_dim.out(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))";
+  static ::std::tuple call(const at::Tensor & self, int64_t dim, bool sorted, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
+  static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool sorted, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/56/5635fc87b6c4b90ce781fa686a21e8c4ce93746ffe1358d75fe4edbf336fd5a7/function.cpython-311.pyc b/shared/package-files/56/5635fc87b6c4b90ce781fa686a21e8c4ce93746ffe1358d75fe4edbf336fd5a7/function.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0449f6244bee3323c6e62afadaada8cb210174c
Binary files /dev/null and b/shared/package-files/56/5635fc87b6c4b90ce781fa686a21e8c4ce93746ffe1358d75fe4edbf336fd5a7/function.cpython-311.pyc differ
diff --git a/shared/package-files/56/56361977d890ffc4e39a7b344eca87da49b4b788a7bd8d037dae5286b0d18a21/cram_codecs.h b/shared/package-files/56/56361977d890ffc4e39a7b344eca87da49b4b788a7bd8d037dae5286b0d18a21/cram_codecs.h
new file mode 100644
index 0000000000000000000000000000000000000000..d93d9955cb195fa3843c17462313a7e4926c916f
--- /dev/null
+++ b/shared/package-files/56/56361977d890ffc4e39a7b344eca87da49b4b788a7bd8d037dae5286b0d18a21/cram_codecs.h
@@ -0,0 +1,264 @@
+/*
+Copyright (c) 2012-2015, 2018, 2020, 2023 Genome Research Ltd.
+Author: James Bonfield 
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+   1. Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.
+
+   2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+   3. Neither the names Genome Research Ltd and Wellcome Trust Sanger
+Institute nor the names of its contributors may be used to endorse or promote
+products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH LTD OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef CRAM_CODECS_H
+#define CRAM_CODECS_H
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct cram_codec;
+
+/*
+ * Slow but simple huffman decoder to start with.
+ * Read a bit at a time, keeping track of {length, value}
+ * eg. 1 1 0 1 => {1,1},  {2,3}, {3,6}, {4,13}
+ *
+ * Keep track of this through the huffman code table.
+ * For fast scanning we have an index of where the first code of length X
+ * appears.
+ */
+typedef struct {
+    int64_t symbol;
+    int32_t p; // next code start value, minus index to codes[]
+    int32_t code;
+    int32_t len;
+} cram_huffman_code;
+
+typedef struct {
+    int ncodes;
+    cram_huffman_code *codes;
+    int option;
+} cram_huffman_decoder;
+
+#define MAX_HUFF 128
+typedef struct {
+    cram_huffman_code *codes;
+    int nvals;
+    int val2code[MAX_HUFF+1]; // value to code lookup for small values
+    int option;
+} cram_huffman_encoder;
+
+typedef struct {
+    int32_t offset;
+    int32_t nbits;
+} cram_beta_decoder;
+
+// A PACK transform, packing multiple values into a single byte
+typedef struct {
+    int32_t nbits;
+    enum cram_encoding sub_encoding;
+    void *sub_codec_dat;
+    struct cram_codec *sub_codec;
+    int nval;  // number of items in maps
+    uint32_t rmap[256]; // 0,1,2,3 -> P,A,C,K
+    int map[256];       // P,A,C,K -> 0,1,2,3 // NB: max input is uint8_tb? Or use hash?
+} cram_xpack_decoder;
+typedef cram_xpack_decoder cram_xpack_encoder;
+
+// Transforms symbols X,Y,Z to bytes 0,1,2.
+typedef struct {
+    enum cram_encoding len_encoding;
+    enum cram_encoding lit_encoding;
+    void *len_dat;
+    void *lit_dat;
+    struct cram_codec *len_codec;
+    struct cram_codec *lit_codec;
+    int cur_len;
+    int cur_lit;
+    int rep_score[256];
+    char *to_flush;
+    size_t to_flush_size;
+} cram_xrle_decoder;
+typedef cram_xrle_decoder cram_xrle_encoder;
+
+// DELTA + zigzag + varint encoding
+typedef struct {
+    // FIXME: define endian here too.  Require little endian?
+    int64_t last;
+    uint8_t word_size; // 1, 2, 4, 8
+    //uint8_t sign;      // true if input data is already signed
+    enum cram_encoding sub_encoding;
+    void *sub_codec_dat;
+    struct cram_codec *sub_codec;
+} cram_xdelta_decoder;
+typedef cram_xdelta_decoder cram_xdelta_encoder;
+
+typedef struct {
+    int32_t offset;
+} cram_gamma_decoder;
+
+typedef struct {
+    int32_t offset;
+    int32_t k;
+} cram_subexp_decoder;
+
+typedef struct {
+    int32_t content_id;
+    enum cram_external_type type;
+} cram_external_decoder;
+
+typedef struct {
+    int32_t content_id;
+    int64_t offset;
+    enum cram_external_type type;
+} cram_varint_decoder;
+
+typedef struct {
+    struct cram_codec *len_codec;
+    struct cram_codec *val_codec;
+} cram_byte_array_len_decoder;
+
+typedef struct {
+    unsigned char stop;
+    int32_t content_id;
+} cram_byte_array_stop_decoder;
+
+typedef struct {
+    enum cram_encoding len_encoding;
+    enum cram_encoding val_encoding;
+    void *len_dat;
+    void *val_dat;
+    struct cram_codec *len_codec;
+    struct cram_codec *val_codec;
+} cram_byte_array_len_encoder;
+
+typedef struct {
+    int64_t val;
+} cram_const_codec;
+
+/*
+ * A generic codec structure.
+ */
+struct cram_codec {
+    enum cram_encoding codec;
+    cram_block *out;
+    varint_vec *vv;
+    int codec_id;
+    void (*free)(struct cram_codec *codec);
+    int (*decode)(cram_slice *slice, struct cram_codec *codec,
+                  cram_block *in, char *out, int *out_size);
+    int (*encode)(cram_slice *slice, struct cram_codec *codec,
+                  char *in, int in_size);
+    int (*store)(struct cram_codec *codec, cram_block *b, char *prefix,
+                 int version);
+    int (*size)(cram_slice *slice, struct cram_codec *codec);
+    int (*flush)(struct cram_codec *codec);
+    cram_block *(*get_block)(cram_slice *slice, struct cram_codec *codec);
+    int (*describe)(struct cram_codec *codec, kstring_t *ks);
+
+    union {
+        cram_huffman_decoder         huffman;
+        cram_external_decoder        external;
+        cram_beta_decoder            beta;
+        cram_gamma_decoder           gamma;
+        cram_subexp_decoder          subexp;
+        cram_byte_array_len_decoder  byte_array_len;
+        cram_byte_array_stop_decoder byte_array_stop;
+        cram_xpack_decoder           xpack;
+        cram_xrle_decoder            xrle;
+        cram_xdelta_decoder          xdelta;
+        cram_const_codec             xconst;
+        cram_varint_decoder          varint;
+
+        cram_huffman_encoder         e_huffman;
+        cram_external_decoder        e_external;
+        cram_byte_array_stop_decoder e_byte_array_stop;
+        cram_byte_array_len_encoder  e_byte_array_len;
+        cram_beta_decoder            e_beta;
+        cram_xpack_decoder           e_xpack;
+        cram_xrle_decoder            e_xrle;
+        cram_xdelta_decoder          e_xdelta;
+        cram_const_codec             e_xconst;
+        cram_varint_decoder          e_varint;
+    } u;
+};
+
+const char *cram_encoding2str(enum cram_encoding t);
+
+cram_codec *cram_decoder_init(cram_block_compression_hdr *hdr,
+                              enum cram_encoding codec, char *data, int size,
+                              enum cram_external_type option,
+                              int version, varint_vec *vv);
+cram_codec *cram_encoder_init(enum cram_encoding codec, cram_stats *st,
+                              enum cram_external_type option, void *dat,
+                              int version, varint_vec *vv);
+
+//int cram_decode(void *codes, char *in, int in_size, char *out, int *out_size);
+//void cram_decoder_free(void *codes);
+
+//#define GET_BIT_MSB(b,v) (void)(v<<=1, v|=(b->data[b->byte] >> b->bit)&1, (--b->bit == -1) && (b->bit = 7, b->byte++))
+
+#define GET_BIT_MSB(b,v) (void)(v<<=1, v|=(b->data[b->byte] >> b->bit)&1, b->byte += (--b->bit<0), b->bit&=7)
+
+/*
+ * Check that enough bits are left in a block to satisy a bit-based decoder.
+ * Return  0 if there are enough
+ *         1 if not.
+ */
+
+static inline int cram_not_enough_bits(cram_block *blk, int nbits) {
+    if (nbits < 0 ||
+        (blk->byte >= blk->uncomp_size && nbits > 0) ||
+        (blk->uncomp_size - blk->byte <= INT32_MAX / 8 + 1 &&
+         (blk->uncomp_size - blk->byte) * 8 + blk->bit - 7 < nbits)) {
+        return 1;
+    }
+    return 0;
+}
+
+/*
+ * Returns the content_id used by this codec, also in id2 if byte_array_len.
+ * Returns -1 for the CORE block and -2 for unneeded.
+ * id2 is only filled out for BYTE_ARRAY_LEN which uses 2 codecs.
+ */
+int cram_codec_to_id(cram_codec *c, int *id2);
+
+/*
+ * cram_codec structures are specialised for decoding or encoding.
+ * Unfortunately this makes turning a decoder into an encoder (such as
+ * when transcoding files) problematic.
+ *
+ * This function converts a cram decoder codec into an encoder version
+ * in-place (ie it modifiers the codec itself).
+ *
+ * Returns 0 on success;
+ *        -1 on failure.
+ */
+int cram_codec_decoder2encoder(cram_fd *fd, cram_codec *c);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CRAM_CODECS_H */
diff --git a/shared/package-files/56/5637e79abdbfec666609c063f2afab53df60836786ac93dba898eafdd4add6e5/test_apply_pyprojecttoml.py b/shared/package-files/56/5637e79abdbfec666609c063f2afab53df60836786ac93dba898eafdd4add6e5/test_apply_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..20146b4a89f567b6038bcba9c36d40cbb933ef51
--- /dev/null
+++ b/shared/package-files/56/5637e79abdbfec666609c063f2afab53df60836786ac93dba898eafdd4add6e5/test_apply_pyprojecttoml.py
@@ -0,0 +1,539 @@
+"""Make sure that applying the configuration from pyproject.toml is equivalent to
+applying a similar configuration from setup.cfg
+
+To run these tests offline, please have a look on ``./downloads/preload.py``
+"""
+
+from __future__ import annotations
+
+import io
+import re
+import tarfile
+from inspect import cleandoc
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+from ini2toml.api import LiteTranslator
+from packaging.metadata import Metadata
+
+import setuptools  # noqa: F401 # ensure monkey patch to metadata
+from setuptools._static import is_static
+from setuptools.command.egg_info import write_requirements
+from setuptools.config import expand, pyprojecttoml, setupcfg
+from setuptools.config._apply_pyprojecttoml import _MissingDynamic, _some_attrgetter
+from setuptools.dist import Distribution
+from setuptools.errors import RemovedConfigError
+
+from .downloads import retrieve_file, urls_from_file
+
+HERE = Path(__file__).parent
+EXAMPLES_FILE = "setupcfg_examples.txt"
+
+
+def makedist(path, **attrs):
+    return Distribution({"src_root": path, **attrs})
+
+
+@pytest.mark.parametrize("url", urls_from_file(HERE / EXAMPLES_FILE))
+@pytest.mark.filterwarnings("ignore")
+@pytest.mark.uses_network
+def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
+    monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.0.1"))
+    setupcfg_example = retrieve_file(url)
+    pyproject_example = Path(tmp_path, "pyproject.toml")
+    setupcfg_text = setupcfg_example.read_text(encoding="utf-8")
+    toml_config = LiteTranslator().translate(setupcfg_text, "setup.cfg")
+    pyproject_example.write_text(toml_config, encoding="utf-8")
+
+    dist_toml = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject_example)
+    dist_cfg = setupcfg.apply_configuration(makedist(tmp_path), setupcfg_example)
+
+    pkg_info_toml = core_metadata(dist_toml)
+    pkg_info_cfg = core_metadata(dist_cfg)
+    assert pkg_info_toml == pkg_info_cfg
+
+    if any(getattr(d, "license_files", None) for d in (dist_toml, dist_cfg)):
+        assert set(dist_toml.license_files) == set(dist_cfg.license_files)
+
+    if any(getattr(d, "entry_points", None) for d in (dist_toml, dist_cfg)):
+        print(dist_cfg.entry_points)
+        ep_toml = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_toml.entry_points.items()
+        }
+        ep_cfg = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_cfg.entry_points.items()
+        }
+        assert ep_toml == ep_cfg
+
+    if any(getattr(d, "package_data", None) for d in (dist_toml, dist_cfg)):
+        pkg_data_toml = {(k, *sorted(v)) for k, v in dist_toml.package_data.items()}
+        pkg_data_cfg = {(k, *sorted(v)) for k, v in dist_cfg.package_data.items()}
+        assert pkg_data_toml == pkg_data_cfg
+
+    if any(getattr(d, "data_files", None) for d in (dist_toml, dist_cfg)):
+        data_files_toml = {(k, *sorted(v)) for k, v in dist_toml.data_files}
+        data_files_cfg = {(k, *sorted(v)) for k, v in dist_cfg.data_files}
+        assert data_files_toml == data_files_cfg
+
+    assert set(dist_toml.install_requires) == set(dist_cfg.install_requires)
+    if any(getattr(d, "extras_require", None) for d in (dist_toml, dist_cfg)):
+        extra_req_toml = {(k, *sorted(v)) for k, v in dist_toml.extras_require.items()}
+        extra_req_cfg = {(k, *sorted(v)) for k, v in dist_cfg.extras_require.items()}
+        assert extra_req_toml == extra_req_cfg
+
+
+PEP621_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+description = "Lovely Spam! Wonderful Spam!"
+readme = "README.rst"
+requires-python = ">=3.8"
+license = {file = "LICENSE.txt"}
+keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"]
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Brett Cannon", email = "brett@python.org"},
+  {name = "John X. Ãørçeč", email = "john@utf8.org"},
+  {name = "Γαμα קּ 東", email = "gama@utf8.org"},
+]
+classifiers = [
+  "Development Status :: 4 - Beta",
+  "Programming Language :: Python"
+]
+
+dependencies = [
+  "httpx",
+  "gidgethub[httpx]>4.0.0",
+  "django>2.1; os_name != 'nt'",
+  "django>2.0; os_name == 'nt'"
+]
+
+[project.optional-dependencies]
+test = [
+  "pytest < 5.0.0",
+  "pytest-cov[all]"
+]
+
+[project.urls]
+homepage = "http://example.com"
+documentation = "http://readthedocs.org"
+repository = "http://github.com"
+changelog = "http://github.com/me/spam/blob/master/CHANGELOG.md"
+
+[project.scripts]
+spam-cli = "spam:main_cli"
+
+[project.gui-scripts]
+spam-gui = "spam:main_gui"
+
+[project.entry-points."spam.magical"]
+tomatoes = "spam:main_tomatoes"
+"""
+
+PEP621_INTERNATIONAL_EMAIL_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Степан Бандера", email = "криївка@оун-упа.укр"},
+]
+"""
+
+PEP621_EXAMPLE_SCRIPT = """
+def main_cli(): pass
+def main_gui(): pass
+def main_tomatoes(): pass
+"""
+
+
+def _pep621_example_project(
+    tmp_path,
+    readme="README.rst",
+    pyproject_text=PEP621_EXAMPLE,
+):
+    pyproject = tmp_path / "pyproject.toml"
+    text = pyproject_text
+    replacements = {'readme = "README.rst"': f'readme = "{readme}"'}
+    for orig, subst in replacements.items():
+        text = text.replace(orig, subst)
+    pyproject.write_text(text, encoding="utf-8")
+
+    (tmp_path / readme).write_text("hello world", encoding="utf-8")
+    (tmp_path / "LICENSE.txt").write_text("--- LICENSE stub ---", encoding="utf-8")
+    (tmp_path / "spam.py").write_text(PEP621_EXAMPLE_SCRIPT, encoding="utf-8")
+    return pyproject
+
+
+def test_pep621_example(tmp_path):
+    """Make sure the example in PEP 621 works"""
+    pyproject = _pep621_example_project(tmp_path)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.license == "--- LICENSE stub ---"
+    assert set(dist.metadata.license_files) == {"LICENSE.txt"}
+
+
+@pytest.mark.parametrize(
+    ("readme", "ctype"),
+    [
+        ("Readme.txt", "text/plain"),
+        ("readme.md", "text/markdown"),
+        ("text.rst", "text/x-rst"),
+    ],
+)
+def test_readme_content_type(tmp_path, readme, ctype):
+    pyproject = _pep621_example_project(tmp_path, readme)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type == ctype
+
+
+def test_undefined_content_type(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README.tex")
+    with pytest.raises(ValueError, match="Undefined content type for README.tex"):
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+def test_no_explicit_content_type_for_missing_extension(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README")
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type is None
+
+
+@pytest.mark.parametrize(
+    ("pyproject_text", "expected_maintainers_meta_value"),
+    (
+        pytest.param(
+            PEP621_EXAMPLE,
+            (
+                'Brett Cannon , "John X. Ãørçeč" , '
+                'Γαμα קּ 東 '
+            ),
+            id='non-international-emails',
+        ),
+        pytest.param(
+            PEP621_INTERNATIONAL_EMAIL_EXAMPLE,
+            'Степан Бандера <криївка@оун-упа.укр>',
+            marks=pytest.mark.xfail(
+                reason="CPython's `email.headerregistry.Address` only supports "
+                'RFC 5322, as of Nov 10, 2022 and latest Python 3.11.0',
+                strict=True,
+            ),
+            id='international-email',
+        ),
+    ),
+)
+def test_utf8_maintainer_in_metadata(  # issue-3663
+    expected_maintainers_meta_value,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.maintainer_email == expected_maintainers_meta_value
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert f"Maintainer-email: {expected_maintainers_meta_value}" in content
+
+
+class TestLicenseFiles:
+    # TODO: After PEP 639 is accepted, we have to move the license-files
+    #       to the `project` table instead of `tool.setuptools`
+
+    def base_pyproject(self, tmp_path, additional_text):
+        pyproject = _pep621_example_project(tmp_path, "README")
+        text = pyproject.read_text(encoding="utf-8")
+
+        # Sanity-check
+        assert 'license = {file = "LICENSE.txt"}' in text
+        assert "[tool.setuptools]" not in text
+
+        text = f"{text}\n{additional_text}\n"
+        pyproject.write_text(text, encoding="utf-8")
+        return pyproject
+
+    def test_both_license_and_license_files_defined(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject(tmp_path, setuptools_config)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        # Would normally match the `license_files` patterns, but we want to exclude it
+        # by being explicit. On the other hand, contents should be added to `license`
+        license = tmp_path / "LICENSE.txt"
+        license.write_text("LicenseRef-Proprietary\n", encoding="utf-8")
+
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license == "LicenseRef-Proprietary\n"
+
+    def test_default_patterns(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nzip-safe = false'
+        # ^ used just to trigger section validation
+        pyproject = self.base_pyproject(tmp_path, setuptools_config)
+
+        license_files = "LICENCE-a.html COPYING-abc.txt AUTHORS-xyz NOTICE,def".split()
+
+        for fname in license_files:
+            (tmp_path / fname).write_text(f"{fname}\n", encoding="utf-8")
+
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+        assert (tmp_path / "LICENSE.txt").exists()  # from base example
+        assert set(dist.metadata.license_files) == {*license_files, "LICENSE.txt"}
+
+
+class TestPyModules:
+    # https://github.com/pypa/setuptools/issues/4316
+
+    def dist(self, name):
+        toml_config = f"""
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        py-modules = [{name!r}]
+        """
+        pyproject = Path("pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        return pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+
+    @pytest.mark.parametrize("module", ["pip-run", "abc-d.λ-xyz-e"])
+    def test_valid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        assert module in self.dist(module).py_modules
+
+    @pytest.mark.parametrize("module", ["pip run", "-pip-run", "pip-run-stubs"])
+    def test_invalid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        with pytest.raises(ValueError, match="py-modules"):
+            self.dist(module).py_modules
+
+
+class TestExtModules:
+    def test_pyproject_sets_attribute(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        pyproject = Path("pyproject.toml")
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        ext-modules = [
+          {name = "my.ext", sources = ["hello.c", "world.c"]}
+        ]
+        """
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        with pytest.warns(pyprojecttoml._ExperimentalConfiguration):
+            dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert len(dist.ext_modules) == 1
+        assert dist.ext_modules[0].name == "my.ext"
+        assert set(dist.ext_modules[0].sources) == {"hello.c", "world.c"}
+
+
+class TestDeprecatedFields:
+    def test_namespace_packages(self, tmp_path):
+        pyproject = tmp_path / "pyproject.toml"
+        config = """
+        [project]
+        name = "myproj"
+        version = "42"
+        [tool.setuptools]
+        namespace-packages = ["myproj.pkg"]
+        """
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.raises(RemovedConfigError, match="namespace-packages"):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+class TestPresetField:
+    def pyproject(self, tmp_path, dynamic, extra_content=""):
+        content = f"[project]\nname = 'proj'\ndynamic = {dynamic!r}\n"
+        if "version" not in dynamic:
+            content += "version = '42'\n"
+        file = tmp_path / "pyproject.toml"
+        file.write_text(content + extra_content, encoding="utf-8")
+        return file
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+            ("entry_points", "scripts", {"console_scripts": ["foobar=foobar:main"]}),
+            ("entry_points", "gui-scripts", {"gui_scripts": ["bazquux=bazquux:main"]}),
+            pytest.param(
+                *("install_requires", "dependencies", ["six"]),
+                marks=[
+                    pytest.mark.filterwarnings("ignore:.*install_requires. overwritten")
+                ],
+            ),
+        ],
+    )
+    def test_not_listed_in_dynamic(self, tmp_path, attr, field, value):
+        """Setuptools cannot set a field if not listed in ``dynamic``"""
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, **{attr: value})
+        msg = re.compile(f"defined outside of `pyproject.toml`:.*{field}", re.S)
+        with pytest.warns(_MissingDynamic, match=msg):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert not dist_value
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("install_requires", "dependencies", []),
+            ("extras_require", "optional-dependencies", {}),
+            ("install_requires", "dependencies", ["six"]),
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+        ],
+    )
+    def test_listed_in_dynamic(self, tmp_path, attr, field, value):
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, **{attr: value})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert dist_value == value
+
+    def test_warning_overwritten_dependencies(self, tmp_path):
+        src = "[project]\nname='pkg'\nversion='0.1'\ndependencies=['click']\n"
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(src, encoding="utf-8")
+        dist = makedist(tmp_path, install_requires=["wheel"])
+        with pytest.warns(match="`install_requires` overwritten"):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "wheel" not in dist.install_requires
+
+    def test_optional_dependencies_dont_remove_env_markers(self, tmp_path):
+        """
+        Internally setuptools converts dependencies with markers to "extras".
+        If ``install_requires`` is given by ``setup.py``, we have to ensure that
+        applying ``optional-dependencies`` does not overwrite the mandatory
+        dependencies with markers (see #3204).
+        """
+        # If setuptools replace its internal mechanism that uses `requires.txt`
+        # this test has to be rewritten to adapt accordingly
+        extra = "\n[project.optional-dependencies]\nfoo = ['bar>1']\n"
+        pyproject = self.pyproject(tmp_path, ["dependencies"], extra)
+        install_req = ['importlib-resources (>=3.0.0) ; python_version < "3.7"']
+        dist = makedist(tmp_path, install_requires=install_req)
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "foo" in dist.extras_require
+        egg_info = dist.get_command_obj("egg_info")
+        write_requirements(egg_info, tmp_path, tmp_path / "requires.txt")
+        reqs = (tmp_path / "requires.txt").read_text(encoding="utf-8")
+        assert "importlib-resources" in reqs
+        assert "bar" in reqs
+        assert ':python_version < "3.7"' in reqs
+
+    @pytest.mark.parametrize(
+        ("field", "group"),
+        [("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")],
+    )
+    @pytest.mark.filterwarnings("error")
+    def test_scripts_dont_require_dynamic_entry_points(self, tmp_path, field, group):
+        # Issue 3862
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, entry_points={group: ["foobar=foobar:main"]})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert group in dist.entry_points
+
+
+class TestMeta:
+    def test_example_file_in_sdist(self, setuptools_sdist):
+        """Meta test to ensure tests can run from sdist"""
+        with tarfile.open(setuptools_sdist) as tar:
+            assert any(name.endswith(EXAMPLES_FILE) for name in tar.getnames())
+
+
+class TestInteropCommandLineParsing:
+    def test_version(self, tmp_path, monkeypatch, capsys):
+        # See pypa/setuptools#4047
+        # This test can be removed once the CLI interface of setup.py is removed
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        opts = {"script_args": ["--version"]}
+        dist = pyprojecttoml.apply_configuration(Distribution(opts), pyproject)
+        dist.parse_command_line()  # <-- there should be no exception here.
+        captured = capsys.readouterr()
+        assert "42.0" in captured.out
+
+
+class TestStaticConfig:
+    def test_mark_static_fields(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        dependencies = ["hello"]
+        keywords = ["world"]
+        classifiers = ["private :: hello world"]
+        [tool.setuptools]
+        obsoletes = ["abcd"]
+        provides = ["abcd"]
+        platforms = ["abcd"]
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert is_static(dist.install_requires)
+        assert is_static(dist.metadata.keywords)
+        assert is_static(dist.metadata.classifiers)
+        assert is_static(dist.metadata.obsoletes)
+        assert is_static(dist.metadata.provides)
+        assert is_static(dist.metadata.platforms)
+
+
+# --- Auxiliary Functions ---
+
+
+def core_metadata(dist) -> str:
+    with io.StringIO() as buffer:
+        dist.metadata.write_pkg_file(buffer)
+        pkg_file_txt = buffer.getvalue()
+
+    # Make sure core metadata is valid
+    Metadata.from_email(pkg_file_txt, validate=True)  # can raise exceptions
+
+    skip_prefixes: tuple[str, ...] = ()
+    skip_lines = set()
+    # ---- DIFF NORMALISATION ----
+    # PEP 621 is very particular about author/maintainer metadata conversion, so skip
+    skip_prefixes += ("Author:", "Author-email:", "Maintainer:", "Maintainer-email:")
+    # May be redundant with Home-page
+    skip_prefixes += ("Project-URL: Homepage,", "Home-page:")
+    # May be missing in original (relying on default) but backfilled in the TOML
+    skip_prefixes += ("Description-Content-Type:",)
+    # Remove empty lines
+    skip_lines.add("")
+
+    result = []
+    for line in pkg_file_txt.splitlines():
+        if line.startswith(skip_prefixes) or line in skip_lines:
+            continue
+        result.append(line + "\n")
+
+    return "".join(result)
diff --git a/shared/package-files/56/563e9a8267c8240260a3d4b84645e130f9923aad0415af2a8a1294dcd38ee8b8/test_getlimits.cpython-311.pyc b/shared/package-files/56/563e9a8267c8240260a3d4b84645e130f9923aad0415af2a8a1294dcd38ee8b8/test_getlimits.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f1249b630957fa8f4060bb58330abefc7f4b50c
Binary files /dev/null and b/shared/package-files/56/563e9a8267c8240260a3d4b84645e130f9923aad0415af2a8a1294dcd38ee8b8/test_getlimits.cpython-311.pyc differ
diff --git a/shared/package-files/56/564630df94a4e79cdfb9f1b3d50b3dbcd87c0b87534e74e9479876eab62938ab/msvc.cpython-311.pyc b/shared/package-files/56/564630df94a4e79cdfb9f1b3d50b3dbcd87c0b87534e74e9479876eab62938ab/msvc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a23d6bfcb9701d0b2c2a790461cb0a59ba66461a
Binary files /dev/null and b/shared/package-files/56/564630df94a4e79cdfb9f1b3d50b3dbcd87c0b87534e74e9479876eab62938ab/msvc.cpython-311.pyc differ
diff --git a/shared/package-files/56/564ad6ea7c1d633ed11f86ffecf510052a703190341490d0c45067f79bbaf6f2/__init__.cpython-311.pyc b/shared/package-files/56/564ad6ea7c1d633ed11f86ffecf510052a703190341490d0c45067f79bbaf6f2/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85ec063dfbbacd5d01fe34ccc47310138bae50d9
Binary files /dev/null and b/shared/package-files/56/564ad6ea7c1d633ed11f86ffecf510052a703190341490d0c45067f79bbaf6f2/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/564aec0287b5e4ce14f601017683727b6a1770ae731073568c4f64b00b85df68/diagflat_ops.h b/shared/package-files/56/564aec0287b5e4ce14f601017683727b6a1770ae731073568c4f64b00b85df68/diagflat_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..ed009d207579a948cc95083c372b350a4ac30c6f
--- /dev/null
+++ b/shared/package-files/56/564aec0287b5e4ce14f601017683727b6a1770ae731073568c4f64b00b85df68/diagflat_ops.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API diagflat {
+  using schema = at::Tensor (const at::Tensor &, int64_t);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::diagflat";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "diagflat(Tensor self, int offset=0) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, int64_t offset);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t offset);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/56/564b4da0a6419b781a37a74f6cbf7bf8e57262edc93caa8e7894c3faf54607a6/__init__.cpython-311.pyc b/shared/package-files/56/564b4da0a6419b781a37a74f6cbf7bf8e57262edc93caa8e7894c3faf54607a6/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10bc00a99165ccd4f27b37029ae85556d75a70f4
Binary files /dev/null and b/shared/package-files/56/564b4da0a6419b781a37a74f6cbf7bf8e57262edc93caa8e7894c3faf54607a6/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/564baef963c01d6987522d43d0f07f44ed7fcfe60ddb514fe2bb6f61fdb849a2/container.cpython-311.pyc b/shared/package-files/56/564baef963c01d6987522d43d0f07f44ed7fcfe60ddb514fe2bb6f61fdb849a2/container.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5850032ad2f15c629a57afd232fd6cde2fa5a130
Binary files /dev/null and b/shared/package-files/56/564baef963c01d6987522d43d0f07f44ed7fcfe60ddb514fe2bb6f61fdb849a2/container.cpython-311.pyc differ
diff --git a/shared/package-files/56/565251f93ac651431878491b1c0f69da8c61022134c169777310093c66df5554/model_container_runner_xpu.h b/shared/package-files/56/565251f93ac651431878491b1c0f69da8c61022134c169777310093c66df5554/model_container_runner_xpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..e93d98d49abd87f5e7acb1aa6d843b67b6d81779
--- /dev/null
+++ b/shared/package-files/56/565251f93ac651431878491b1c0f69da8c61022134c169777310093c66df5554/model_container_runner_xpu.h
@@ -0,0 +1,37 @@
+#if !defined(C10_MOBILE) && !defined(ANDROID)
+#pragma once
+
+#include 
+#include 
+
+namespace torch::inductor {
+
+// NOTICE: Following APIs are subject to change due to active development
+// We provide NO BC guarantee for these APIs
+
+// HERE we use C10_EXPORT because libtorch_python needs this Symbol be exported.
+// And `TORCH_API and `TORCH_XPU_API`` do not export the symbol in Windows
+// build.
+class C10_EXPORT AOTIModelContainerRunnerXpu : public AOTIModelContainerRunner {
+ public:
+  // @param device_str: xpu device string, e.g. "xpu", "xpu:0"
+  AOTIModelContainerRunnerXpu(
+      const std::string& model_so_path,
+      size_t num_models = 1,
+      const std::string& device_str = "xpu",
+      const std::string& kernel_bin_dir = "",
+      const bool run_single_threaded = false);
+
+  ~AOTIModelContainerRunnerXpu() override;
+
+  std::vector run_impl(
+      std::vector& input_handles,
+      void* stream_handle) override;
+
+  std::vector run_with_xpu_stream(
+      const std::vector& inputs,
+      const at::xpu::XPUStream& xpu_stream);
+};
+
+} // namespace torch::inductor
+#endif
diff --git a/shared/package-files/56/565e42d528737c6350974471967db288d9a90771752e6b6ce863eaaac1de502f/StackKernel.h b/shared/package-files/56/565e42d528737c6350974471967db288d9a90771752e6b6ce863eaaac1de502f/StackKernel.h
new file mode 100644
index 0000000000000000000000000000000000000000..3ff30c4bc6310f2899856e6d7032ded1662f1271
--- /dev/null
+++ b/shared/package-files/56/565e42d528737c6350974471967db288d9a90771752e6b6ce863eaaac1de502f/StackKernel.h
@@ -0,0 +1,12 @@
+// Copyright 2004-present Facebook. All Rights Reserved.
+#pragma once
+
+#include 
+#include 
+
+namespace at::native {
+
+using stack_serial_fn = void(*)(Tensor &, TensorList, int64_t);
+DECLARE_DISPATCH(stack_serial_fn, stack_serial_stub)
+
+} // namespace at::native
diff --git a/shared/package-files/56/565e8aca1aaf7788bdd04889f96038f8836f6e9c150c203e6909fa7c3364592f/__init__.cpython-311.pyc b/shared/package-files/56/565e8aca1aaf7788bdd04889f96038f8836f6e9c150c203e6909fa7c3364592f/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7a86fdbe0e4fd7fc41106950cc8bf026f11f780
Binary files /dev/null and b/shared/package-files/56/565e8aca1aaf7788bdd04889f96038f8836f6e9c150c203e6909fa7c3364592f/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/5667a6718c863f632cad3675f5bfad1498cb5fb79872a62ea591a473bfa4298c/structuralholes.cpython-311.pyc b/shared/package-files/56/5667a6718c863f632cad3675f5bfad1498cb5fb79872a62ea591a473bfa4298c/structuralholes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6546d7d38891f7f12d27ad0b75ec7a5513f5c3b5
Binary files /dev/null and b/shared/package-files/56/5667a6718c863f632cad3675f5bfad1498cb5fb79872a62ea591a473bfa4298c/structuralholes.cpython-311.pyc differ
diff --git a/shared/package-files/56/56685b99d406c974ffce84260b08b06476b1e98f701d0675c378d86c8f19f579/test_configdialog.py b/shared/package-files/56/56685b99d406c974ffce84260b08b06476b1e98f701d0675c378d86c8f19f579/test_configdialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..5099d0933824453c32ca0ec9582721db840db566
--- /dev/null
+++ b/shared/package-files/56/56685b99d406c974ffce84260b08b06476b1e98f701d0675c378d86c8f19f579/test_configdialog.py
@@ -0,0 +1,1580 @@
+"""Test configdialog, coverage 94%.
+
+Half the class creates dialog, half works with user customizations.
+"""
+from idlelib import configdialog
+from test.support import requires
+requires('gui')
+import unittest
+from unittest import mock
+from idlelib.idle_test.mock_idle import Func
+from tkinter import (Tk, StringVar, IntVar, BooleanVar, DISABLED, NORMAL)
+from idlelib import config
+from idlelib.configdialog import idleConf, changes, tracers
+
+# Tests should not depend on fortuitous user configurations.
+# They must not affect actual user .cfg files.
+# Use solution from test_config: empty parsers with no filename.
+usercfg = idleConf.userCfg
+testcfg = {
+    'main': config.IdleUserConfParser(''),
+    'highlight': config.IdleUserConfParser(''),
+    'keys': config.IdleUserConfParser(''),
+    'extensions': config.IdleUserConfParser(''),
+}
+
+root = None
+dialog = None
+mainpage = changes['main']
+highpage = changes['highlight']
+keyspage = changes['keys']
+extpage = changes['extensions']
+
+
+def setUpModule():
+    global root, dialog
+    idleConf.userCfg = testcfg
+    root = Tk()
+    # root.withdraw()    # Comment out, see issue 30870
+    dialog = configdialog.ConfigDialog(root, 'Test', _utest=True)
+
+
+def tearDownModule():
+    global root, dialog
+    idleConf.userCfg = usercfg
+    tracers.detach()
+    tracers.clear()
+    changes.clear()
+    root.update_idletasks()
+    root.destroy()
+    root = dialog = None
+
+
+class ConfigDialogTest(unittest.TestCase):
+
+    def test_deactivate_current_config(self):
+        pass
+
+    def activate_config_changes(self):
+        pass
+
+
+class ButtonTest(unittest.TestCase):
+
+    def test_click_ok(self):
+        d = dialog
+        apply = d.apply = mock.Mock()
+        destroy = d.destroy = mock.Mock()
+        d.buttons['Ok'].invoke()
+        apply.assert_called_once()
+        destroy.assert_called_once()
+        del d.destroy, d.apply
+
+    def test_click_apply(self):
+        d = dialog
+        deactivate = d.deactivate_current_config = mock.Mock()
+        save_ext = d.extpage.save_all_changed_extensions = mock.Mock()
+        activate = d.activate_config_changes = mock.Mock()
+        d.buttons['Apply'].invoke()
+        deactivate.assert_called_once()
+        save_ext.assert_called_once()
+        activate.assert_called_once()
+        del d.extpage.save_all_changed_extensions
+        del d.activate_config_changes, d.deactivate_current_config
+
+    def test_click_cancel(self):
+        d = dialog
+        d.destroy = Func()
+        changes['main']['something'] = 1
+        d.buttons['Cancel'].invoke()
+        self.assertEqual(changes['main'], {})
+        self.assertEqual(d.destroy.called, 1)
+        del d.destroy
+
+    def test_click_help(self):
+        dialog.note.select(dialog.keyspage)
+        with mock.patch.object(configdialog, 'view_text',
+                               new_callable=Func) as view:
+            dialog.buttons['Help'].invoke()
+            title, contents = view.kwds['title'], view.kwds['contents']
+        self.assertEqual(title, 'Help for IDLE preferences')
+        self.assertTrue(contents.startswith('When you click') and
+                        contents.endswith('a different name.\n'))
+
+
+class FontPageTest(unittest.TestCase):
+    """Test that font widgets enable users to make font changes.
+
+    Test that widget actions set vars, that var changes add three
+    options to changes and call set_samples, and that set_samples
+    changes the font of both sample boxes.
+    """
+    @classmethod
+    def setUpClass(cls):
+        page = cls.page = dialog.fontpage
+        dialog.note.select(page)
+        page.set_samples = Func()  # Mask instance method.
+        page.update()
+
+    @classmethod
+    def tearDownClass(cls):
+        del cls.page.set_samples  # Unmask instance method.
+
+    def setUp(self):
+        changes.clear()
+
+    def test_load_font_cfg(self):
+        # Leave widget load test to human visual check.
+        # TODO Improve checks when add IdleConf.get_font_values.
+        tracers.detach()
+        d = self.page
+        d.font_name.set('Fake')
+        d.font_size.set('1')
+        d.font_bold.set(True)
+        d.set_samples.called = 0
+        d.load_font_cfg()
+        self.assertNotEqual(d.font_name.get(), 'Fake')
+        self.assertNotEqual(d.font_size.get(), '1')
+        self.assertFalse(d.font_bold.get())
+        self.assertEqual(d.set_samples.called, 1)
+        tracers.attach()
+
+    def test_fontlist_key(self):
+        # Up and Down keys should select a new font.
+        d = self.page
+        if d.fontlist.size() < 2:
+            self.skipTest('need at least 2 fonts')
+        fontlist = d.fontlist
+        fontlist.activate(0)
+        font = d.fontlist.get('active')
+
+        # Test Down key.
+        fontlist.focus_force()
+        fontlist.update()
+        fontlist.event_generate('')
+        fontlist.event_generate('')
+
+        down_font = fontlist.get('active')
+        self.assertNotEqual(down_font, font)
+        self.assertIn(d.font_name.get(), down_font.lower())
+
+        # Test Up key.
+        fontlist.focus_force()
+        fontlist.update()
+        fontlist.event_generate('')
+        fontlist.event_generate('')
+
+        up_font = fontlist.get('active')
+        self.assertEqual(up_font, font)
+        self.assertIn(d.font_name.get(), up_font.lower())
+
+    def test_fontlist_mouse(self):
+        # Click on item should select that item.
+        d = self.page
+        if d.fontlist.size() < 2:
+            self.skipTest('need at least 2 fonts')
+        fontlist = d.fontlist
+        fontlist.activate(0)
+
+        # Select next item in listbox
+        fontlist.focus_force()
+        fontlist.see(1)
+        fontlist.update()
+        x, y, dx, dy = fontlist.bbox(1)
+        x += dx // 2
+        y += dy // 2
+        fontlist.event_generate('', x=x, y=y)
+        fontlist.event_generate('', x=x, y=y)
+
+        font1 = fontlist.get(1)
+        select_font = fontlist.get('anchor')
+        self.assertEqual(select_font, font1)
+        self.assertIn(d.font_name.get(), font1.lower())
+
+    def test_sizelist(self):
+        # Click on number should select that number
+        d = self.page
+        d.sizelist.variable.set(40)
+        self.assertEqual(d.font_size.get(), '40')
+
+    def test_bold_toggle(self):
+        # Click on checkbutton should invert it.
+        d = self.page
+        d.font_bold.set(False)
+        d.bold_toggle.invoke()
+        self.assertTrue(d.font_bold.get())
+        d.bold_toggle.invoke()
+        self.assertFalse(d.font_bold.get())
+
+    def test_font_set(self):
+        # Test that setting a font Variable results in 3 provisional
+        # change entries and a call to set_samples. Use values sure to
+        # not be defaults.
+
+        default_font = idleConf.GetFont(root, 'main', 'EditorWindow')
+        default_size = str(default_font[1])
+        default_bold = default_font[2] == 'bold'
+        d = self.page
+        d.font_size.set(default_size)
+        d.font_bold.set(default_bold)
+        d.set_samples.called = 0
+
+        d.font_name.set('Test Font')
+        expected = {'EditorWindow': {'font': 'Test Font',
+                                     'font-size': default_size,
+                                     'font-bold': str(default_bold)}}
+        self.assertEqual(mainpage, expected)
+        self.assertEqual(d.set_samples.called, 1)
+        changes.clear()
+
+        d.font_size.set('20')
+        expected = {'EditorWindow': {'font': 'Test Font',
+                                     'font-size': '20',
+                                     'font-bold': str(default_bold)}}
+        self.assertEqual(mainpage, expected)
+        self.assertEqual(d.set_samples.called, 2)
+        changes.clear()
+
+        d.font_bold.set(not default_bold)
+        expected = {'EditorWindow': {'font': 'Test Font',
+                                     'font-size': '20',
+                                     'font-bold': str(not default_bold)}}
+        self.assertEqual(mainpage, expected)
+        self.assertEqual(d.set_samples.called, 3)
+
+    def test_set_samples(self):
+        d = self.page
+        del d.set_samples  # Unmask method for test
+        orig_samples = d.font_sample, d.highlight_sample
+        d.font_sample, d.highlight_sample = {}, {}
+        d.font_name.set('test')
+        d.font_size.set('5')
+        d.font_bold.set(1)
+        expected = {'font': ('test', '5', 'bold')}
+
+        # Test set_samples.
+        d.set_samples()
+        self.assertTrue(d.font_sample == d.highlight_sample == expected)
+
+        d.font_sample, d.highlight_sample = orig_samples
+        d.set_samples = Func()  # Re-mask for other tests.
+
+
+class HighPageTest(unittest.TestCase):
+    """Test that highlight tab widgets enable users to make changes.
+
+    Test that widget actions set vars, that var changes add
+    options to changes and that themes work correctly.
+    """
+
+    @classmethod
+    def setUpClass(cls):
+        page = cls.page = dialog.highpage
+        dialog.note.select(page)
+        page.set_theme_type = Func()
+        page.paint_theme_sample = Func()
+        page.set_highlight_target = Func()
+        page.set_color_sample = Func()
+        page.update()
+
+    @classmethod
+    def tearDownClass(cls):
+        d = cls.page
+        del d.set_theme_type, d.paint_theme_sample
+        del d.set_highlight_target, d.set_color_sample
+
+    def setUp(self):
+        d = self.page
+        # The following is needed for test_load_key_cfg, _delete_custom_keys.
+        # This may indicate a defect in some test or function.
+        for section in idleConf.GetSectionList('user', 'highlight'):
+            idleConf.userCfg['highlight'].remove_section(section)
+        changes.clear()
+        d.set_theme_type.called = 0
+        d.paint_theme_sample.called = 0
+        d.set_highlight_target.called = 0
+        d.set_color_sample.called = 0
+
+    def test_load_theme_cfg(self):
+        tracers.detach()
+        d = self.page
+        eq = self.assertEqual
+
+        # Use builtin theme with no user themes created.
+        idleConf.CurrentTheme = mock.Mock(return_value='IDLE Classic')
+        d.load_theme_cfg()
+        self.assertTrue(d.theme_source.get())
+        # builtinlist sets variable builtin_name to the CurrentTheme default.
+        eq(d.builtin_name.get(), 'IDLE Classic')
+        eq(d.custom_name.get(), '- no custom themes -')
+        eq(d.custom_theme_on.state(), ('disabled',))
+        eq(d.set_theme_type.called, 1)
+        eq(d.paint_theme_sample.called, 1)
+        eq(d.set_highlight_target.called, 1)
+
+        # Builtin theme with non-empty user theme list.
+        idleConf.SetOption('highlight', 'test1', 'option', 'value')
+        idleConf.SetOption('highlight', 'test2', 'option2', 'value2')
+        d.load_theme_cfg()
+        eq(d.builtin_name.get(), 'IDLE Classic')
+        eq(d.custom_name.get(), 'test1')
+        eq(d.set_theme_type.called, 2)
+        eq(d.paint_theme_sample.called, 2)
+        eq(d.set_highlight_target.called, 2)
+
+        # Use custom theme.
+        idleConf.CurrentTheme = mock.Mock(return_value='test2')
+        idleConf.SetOption('main', 'Theme', 'default', '0')
+        d.load_theme_cfg()
+        self.assertFalse(d.theme_source.get())
+        eq(d.builtin_name.get(), 'IDLE Classic')
+        eq(d.custom_name.get(), 'test2')
+        eq(d.set_theme_type.called, 3)
+        eq(d.paint_theme_sample.called, 3)
+        eq(d.set_highlight_target.called, 3)
+
+        del idleConf.CurrentTheme
+        tracers.attach()
+
+    def test_theme_source(self):
+        eq = self.assertEqual
+        d = self.page
+        # Test these separately.
+        d.var_changed_builtin_name = Func()
+        d.var_changed_custom_name = Func()
+        # Builtin selected.
+        d.builtin_theme_on.invoke()
+        eq(mainpage, {'Theme': {'default': 'True'}})
+        eq(d.var_changed_builtin_name.called, 1)
+        eq(d.var_changed_custom_name.called, 0)
+        changes.clear()
+
+        # Custom selected.
+        d.custom_theme_on.state(('!disabled',))
+        d.custom_theme_on.invoke()
+        self.assertEqual(mainpage, {'Theme': {'default': 'False'}})
+        eq(d.var_changed_builtin_name.called, 1)
+        eq(d.var_changed_custom_name.called, 1)
+        del d.var_changed_builtin_name, d.var_changed_custom_name
+
+    def test_builtin_name(self):
+        eq = self.assertEqual
+        d = self.page
+        item_list = ['IDLE Classic', 'IDLE Dark', 'IDLE New']
+
+        # Not in old_themes, defaults name to first item.
+        idleConf.SetOption('main', 'Theme', 'name', 'spam')
+        d.builtinlist.SetMenu(item_list, 'IDLE Dark')
+        eq(mainpage, {'Theme': {'name': 'IDLE Classic',
+                                'name2': 'IDLE Dark'}})
+        eq(d.theme_message['text'], 'New theme, see Help')
+        eq(d.paint_theme_sample.called, 1)
+
+        # Not in old themes - uses name2.
+        changes.clear()
+        idleConf.SetOption('main', 'Theme', 'name', 'IDLE New')
+        d.builtinlist.SetMenu(item_list, 'IDLE Dark')
+        eq(mainpage, {'Theme': {'name2': 'IDLE Dark'}})
+        eq(d.theme_message['text'], 'New theme, see Help')
+        eq(d.paint_theme_sample.called, 2)
+
+        # Builtin name in old_themes.
+        changes.clear()
+        d.builtinlist.SetMenu(item_list, 'IDLE Classic')
+        eq(mainpage, {'Theme': {'name': 'IDLE Classic', 'name2': ''}})
+        eq(d.theme_message['text'], '')
+        eq(d.paint_theme_sample.called, 3)
+
+    def test_custom_name(self):
+        d = self.page
+
+        # If no selections, doesn't get added.
+        d.customlist.SetMenu([], '- no custom themes -')
+        self.assertNotIn('Theme', mainpage)
+        self.assertEqual(d.paint_theme_sample.called, 0)
+
+        # Custom name selected.
+        changes.clear()
+        d.customlist.SetMenu(['a', 'b', 'c'], 'c')
+        self.assertEqual(mainpage, {'Theme': {'name': 'c'}})
+        self.assertEqual(d.paint_theme_sample.called, 1)
+
+    def test_color(self):
+        d = self.page
+        d.on_new_color_set = Func()
+        # self.color is only set in get_color through colorchooser.
+        d.color.set('green')
+        self.assertEqual(d.on_new_color_set.called, 1)
+        del d.on_new_color_set
+
+    def test_highlight_target_list_mouse(self):
+        # Set highlight_target through targetlist.
+        eq = self.assertEqual
+        d = self.page
+
+        d.targetlist.SetMenu(['a', 'b', 'c'], 'c')
+        eq(d.highlight_target.get(), 'c')
+        eq(d.set_highlight_target.called, 1)
+
+    def test_highlight_target_text_mouse(self):
+        # Set highlight_target through clicking highlight_sample.
+        eq = self.assertEqual
+        d = self.page
+        hs = d.highlight_sample
+        hs.focus_force()
+
+        def click_char(index):
+            "Simulate click on character at *index*."
+            hs.see(index)
+            hs.update_idletasks()
+            x, y, dx, dy = hs.bbox(index)
+            x += dx // 2
+            y += dy // 2
+            hs.event_generate('', x=0, y=0)
+            hs.event_generate('', x=x, y=y)
+            hs.event_generate('', x=x, y=y)
+            hs.event_generate('', x=x, y=y)
+
+        # Reverse theme_elements to make the tag the key.
+        elem = {tag: element for element, tag in d.theme_elements.items()}
+
+        # If highlight_sample has a tag that isn't in theme_elements, there
+        # will be a KeyError in the test run.
+        count = 0
+        for tag in hs.tag_names():
+            try:
+                click_char(hs.tag_nextrange(tag, "1.0")[0])
+                eq(d.highlight_target.get(), elem[tag])
+                count += 1
+                eq(d.set_highlight_target.called, count)
+            except IndexError:
+                pass  # Skip unused theme_elements tag, like 'sel'.
+
+    def test_highlight_sample_double_click(self):
+        # Test double click on highlight_sample.
+        eq = self.assertEqual
+        d = self.page
+
+        hs = d.highlight_sample
+        hs.focus_force()
+        hs.see(1.0)
+        hs.update_idletasks()
+
+        # Test binding from configdialog.
+        hs.event_generate('', x=0, y=0)
+        hs.event_generate('', x=0, y=0)
+        # Double click is a sequence of two clicks in a row.
+        for _ in range(2):
+            hs.event_generate('', x=0, y=0)
+            hs.event_generate('', x=0, y=0)
+
+        eq(hs.tag_ranges('sel'), ())
+
+    def test_highlight_sample_b1_motion(self):
+        # Test button motion on highlight_sample.
+        eq = self.assertEqual
+        d = self.page
+
+        hs = d.highlight_sample
+        hs.focus_force()
+        hs.see(1.0)
+        hs.update_idletasks()
+
+        x, y, dx, dy, offset = hs.dlineinfo('1.0')
+
+        # Test binding from configdialog.
+        hs.event_generate('')
+        hs.event_generate('')
+        hs.event_generate('', x=x, y=y)
+        hs.event_generate('', x=x, y=y)
+        hs.event_generate('', x=dx, y=dy)
+        hs.event_generate('', x=dx, y=dy)
+
+        eq(hs.tag_ranges('sel'), ())
+
+    def test_set_theme_type(self):
+        eq = self.assertEqual
+        d = self.page
+        del d.set_theme_type
+
+        # Builtin theme selected.
+        d.theme_source.set(True)
+        d.set_theme_type()
+        eq(d.builtinlist['state'], NORMAL)
+        eq(d.customlist['state'], DISABLED)
+        eq(d.button_delete_custom.state(), ('disabled',))
+
+        # Custom theme selected.
+        d.theme_source.set(False)
+        d.set_theme_type()
+        eq(d.builtinlist['state'], DISABLED)
+        eq(d.custom_theme_on.state(), ('selected',))
+        eq(d.customlist['state'], NORMAL)
+        eq(d.button_delete_custom.state(), ())
+        d.set_theme_type = Func()
+
+    def test_get_color(self):
+        eq = self.assertEqual
+        d = self.page
+        orig_chooser = configdialog.colorchooser.askcolor
+        chooser = configdialog.colorchooser.askcolor = Func()
+        gntn = d.get_new_theme_name = Func()
+
+        d.highlight_target.set('Editor Breakpoint')
+        d.color.set('#ffffff')
+
+        # Nothing selected.
+        chooser.result = (None, None)
+        d.button_set_color.invoke()
+        eq(d.color.get(), '#ffffff')
+
+        # Selection same as previous color.
+        chooser.result = ('', d.style.lookup(d.frame_color_set['style'], 'background'))
+        d.button_set_color.invoke()
+        eq(d.color.get(), '#ffffff')
+
+        # Select different color.
+        chooser.result = ((222.8671875, 0.0, 0.0), '#de0000')
+
+        # Default theme.
+        d.color.set('#ffffff')
+        d.theme_source.set(True)
+
+        # No theme name selected therefore color not saved.
+        gntn.result = ''
+        d.button_set_color.invoke()
+        eq(gntn.called, 1)
+        eq(d.color.get(), '#ffffff')
+        # Theme name selected.
+        gntn.result = 'My New Theme'
+        d.button_set_color.invoke()
+        eq(d.custom_name.get(), gntn.result)
+        eq(d.color.get(), '#de0000')
+
+        # Custom theme.
+        d.color.set('#ffffff')
+        d.theme_source.set(False)
+        d.button_set_color.invoke()
+        eq(d.color.get(), '#de0000')
+
+        del d.get_new_theme_name
+        configdialog.colorchooser.askcolor = orig_chooser
+
+    def test_on_new_color_set(self):
+        d = self.page
+        color = '#3f7cae'
+        d.custom_name.set('Python')
+        d.highlight_target.set('Selected Text')
+        d.fg_bg_toggle.set(True)
+
+        d.color.set(color)
+        self.assertEqual(d.style.lookup(d.frame_color_set['style'], 'background'), color)
+        self.assertEqual(d.highlight_sample.tag_cget('hilite', 'foreground'), color)
+        self.assertEqual(highpage,
+                         {'Python': {'hilite-foreground': color}})
+
+    def test_get_new_theme_name(self):
+        orig_sectionname = configdialog.SectionName
+        sn = configdialog.SectionName = Func(return_self=True)
+        d = self.page
+
+        sn.result = 'New Theme'
+        self.assertEqual(d.get_new_theme_name(''), 'New Theme')
+
+        configdialog.SectionName = orig_sectionname
+
+    def test_save_as_new_theme(self):
+        d = self.page
+        gntn = d.get_new_theme_name = Func()
+        d.theme_source.set(True)
+
+        # No name entered.
+        gntn.result = ''
+        d.button_save_custom.invoke()
+        self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])
+
+        # Name entered.
+        gntn.result = 'my new theme'
+        gntn.called = 0
+        self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])
+        d.button_save_custom.invoke()
+        self.assertIn(gntn.result, idleConf.userCfg['highlight'])
+
+        del d.get_new_theme_name
+
+    def test_create_new_and_save_new(self):
+        eq = self.assertEqual
+        d = self.page
+
+        # Use default as previously active theme.
+        d.theme_source.set(True)
+        d.builtin_name.set('IDLE Classic')
+        first_new = 'my new custom theme'
+        second_new = 'my second custom theme'
+
+        # No changes, so themes are an exact copy.
+        self.assertNotIn(first_new, idleConf.userCfg)
+        d.create_new(first_new)
+        eq(idleConf.GetSectionList('user', 'highlight'), [first_new])
+        eq(idleConf.GetThemeDict('default', 'IDLE Classic'),
+           idleConf.GetThemeDict('user', first_new))
+        eq(d.custom_name.get(), first_new)
+        self.assertFalse(d.theme_source.get())  # Use custom set.
+        eq(d.set_theme_type.called, 1)
+
+        # Test that changed targets are in new theme.
+        changes.add_option('highlight', first_new, 'hit-background', 'yellow')
+        self.assertNotIn(second_new, idleConf.userCfg)
+        d.create_new(second_new)
+        eq(idleConf.GetSectionList('user', 'highlight'), [first_new, second_new])
+        self.assertNotEqual(idleConf.GetThemeDict('user', first_new),
+                            idleConf.GetThemeDict('user', second_new))
+        # Check that difference in themes was in `hit-background` from `changes`.
+        idleConf.SetOption('highlight', first_new, 'hit-background', 'yellow')
+        eq(idleConf.GetThemeDict('user', first_new),
+           idleConf.GetThemeDict('user', second_new))
+
+    def test_set_highlight_target(self):
+        eq = self.assertEqual
+        d = self.page
+        del d.set_highlight_target
+
+        # Target is cursor.
+        d.highlight_target.set('Cursor')
+        eq(d.fg_on.state(), ('disabled', 'selected'))
+        eq(d.bg_on.state(), ('disabled',))
+        self.assertTrue(d.fg_bg_toggle)
+        eq(d.set_color_sample.called, 1)
+
+        # Target is not cursor.
+        d.highlight_target.set('Comment')
+        eq(d.fg_on.state(), ('selected',))
+        eq(d.bg_on.state(), ())
+        self.assertTrue(d.fg_bg_toggle)
+        eq(d.set_color_sample.called, 2)
+
+        d.set_highlight_target = Func()
+
+    def test_set_color_sample_binding(self):
+        d = self.page
+        scs = d.set_color_sample
+
+        d.fg_on.invoke()
+        self.assertEqual(scs.called, 1)
+
+        d.bg_on.invoke()
+        self.assertEqual(scs.called, 2)
+
+    def test_set_color_sample(self):
+        d = self.page
+        del d.set_color_sample
+        d.highlight_target.set('Selected Text')
+        d.fg_bg_toggle.set(True)
+        d.set_color_sample()
+        self.assertEqual(
+                d.style.lookup(d.frame_color_set['style'], 'background'),
+                d.highlight_sample.tag_cget('hilite', 'foreground'))
+        d.set_color_sample = Func()
+
+    def test_paint_theme_sample(self):
+        eq = self.assertEqual
+        page = self.page
+        del page.paint_theme_sample  # Delete masking mock.
+        hs_tag = page.highlight_sample.tag_cget
+        gh = idleConf.GetHighlight
+
+        # Create custom theme based on IDLE Dark.
+        page.theme_source.set(True)
+        page.builtin_name.set('IDLE Dark')
+        theme = 'IDLE Test'
+        page.create_new(theme)
+        page.set_color_sample.called = 0
+
+        # Base theme with nothing in `changes`.
+        page.paint_theme_sample()
+        new_console = {'foreground': 'blue',
+                       'background': 'yellow',}
+        for key, value in new_console.items():
+            self.assertNotEqual(hs_tag('console', key), value)
+        eq(page.set_color_sample.called, 1)
+
+        # Apply changes.
+        for key, value in new_console.items():
+            changes.add_option('highlight', theme, 'console-'+key, value)
+        page.paint_theme_sample()
+        for key, value in new_console.items():
+            eq(hs_tag('console', key), value)
+        eq(page.set_color_sample.called, 2)
+
+        page.paint_theme_sample = Func()
+
+    def test_delete_custom(self):
+        eq = self.assertEqual
+        d = self.page
+        d.button_delete_custom.state(('!disabled',))
+        yesno = d.askyesno = Func()
+        dialog.deactivate_current_config = Func()
+        dialog.activate_config_changes = Func()
+
+        theme_name = 'spam theme'
+        idleConf.userCfg['highlight'].SetOption(theme_name, 'name', 'value')
+        highpage[theme_name] = {'option': 'True'}
+
+        theme_name2 = 'other theme'
+        idleConf.userCfg['highlight'].SetOption(theme_name2, 'name', 'value')
+        highpage[theme_name2] = {'option': 'False'}
+
+        # Force custom theme.
+        d.custom_theme_on.state(('!disabled',))
+        d.custom_theme_on.invoke()
+        d.custom_name.set(theme_name)
+
+        # Cancel deletion.
+        yesno.result = False
+        d.button_delete_custom.invoke()
+        eq(yesno.called, 1)
+        eq(highpage[theme_name], {'option': 'True'})
+        eq(idleConf.GetSectionList('user', 'highlight'), [theme_name, theme_name2])
+        eq(dialog.deactivate_current_config.called, 0)
+        eq(dialog.activate_config_changes.called, 0)
+        eq(d.set_theme_type.called, 0)
+
+        # Confirm deletion.
+        yesno.result = True
+        d.button_delete_custom.invoke()
+        eq(yesno.called, 2)
+        self.assertNotIn(theme_name, highpage)
+        eq(idleConf.GetSectionList('user', 'highlight'), [theme_name2])
+        eq(d.custom_theme_on.state(), ())
+        eq(d.custom_name.get(), theme_name2)
+        eq(dialog.deactivate_current_config.called, 1)
+        eq(dialog.activate_config_changes.called, 1)
+        eq(d.set_theme_type.called, 1)
+
+        # Confirm deletion of second theme - empties list.
+        d.custom_name.set(theme_name2)
+        yesno.result = True
+        d.button_delete_custom.invoke()
+        eq(yesno.called, 3)
+        self.assertNotIn(theme_name, highpage)
+        eq(idleConf.GetSectionList('user', 'highlight'), [])
+        eq(d.custom_theme_on.state(), ('disabled',))
+        eq(d.custom_name.get(), '- no custom themes -')
+        eq(dialog.deactivate_current_config.called, 2)
+        eq(dialog.activate_config_changes.called, 2)
+        eq(d.set_theme_type.called, 2)
+
+        del dialog.activate_config_changes, dialog.deactivate_current_config
+        del d.askyesno
+
+
+class KeysPageTest(unittest.TestCase):
+    """Test that keys tab widgets enable users to make changes.
+
+    Test that widget actions set vars, that var changes add
+    options to changes and that key sets works correctly.
+    """
+
+    @classmethod
+    def setUpClass(cls):
+        page = cls.page = dialog.keyspage
+        dialog.note.select(page)
+        page.set_keys_type = Func()
+        page.load_keys_list = Func()
+
+    @classmethod
+    def tearDownClass(cls):
+        page = cls.page
+        del page.set_keys_type, page.load_keys_list
+
+    def setUp(self):
+        d = self.page
+        # The following is needed for test_load_key_cfg, _delete_custom_keys.
+        # This may indicate a defect in some test or function.
+        for section in idleConf.GetSectionList('user', 'keys'):
+            idleConf.userCfg['keys'].remove_section(section)
+        changes.clear()
+        d.set_keys_type.called = 0
+        d.load_keys_list.called = 0
+
+    def test_load_key_cfg(self):
+        tracers.detach()
+        d = self.page
+        eq = self.assertEqual
+
+        # Use builtin keyset with no user keysets created.
+        idleConf.CurrentKeys = mock.Mock(return_value='IDLE Classic OSX')
+        d.load_key_cfg()
+        self.assertTrue(d.keyset_source.get())
+        # builtinlist sets variable builtin_name to the CurrentKeys default.
+        eq(d.builtin_name.get(), 'IDLE Classic OSX')
+        eq(d.custom_name.get(), '- no custom keys -')
+        eq(d.custom_keyset_on.state(), ('disabled',))
+        eq(d.set_keys_type.called, 1)
+        eq(d.load_keys_list.called, 1)
+        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
+
+        # Builtin keyset with non-empty user keyset list.
+        idleConf.SetOption('keys', 'test1', 'option', 'value')
+        idleConf.SetOption('keys', 'test2', 'option2', 'value2')
+        d.load_key_cfg()
+        eq(d.builtin_name.get(), 'IDLE Classic OSX')
+        eq(d.custom_name.get(), 'test1')
+        eq(d.set_keys_type.called, 2)
+        eq(d.load_keys_list.called, 2)
+        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
+
+        # Use custom keyset.
+        idleConf.CurrentKeys = mock.Mock(return_value='test2')
+        idleConf.default_keys = mock.Mock(return_value='IDLE Modern Unix')
+        idleConf.SetOption('main', 'Keys', 'default', '0')
+        d.load_key_cfg()
+        self.assertFalse(d.keyset_source.get())
+        eq(d.builtin_name.get(), 'IDLE Modern Unix')
+        eq(d.custom_name.get(), 'test2')
+        eq(d.set_keys_type.called, 3)
+        eq(d.load_keys_list.called, 3)
+        eq(d.load_keys_list.args, ('test2', ))
+
+        del idleConf.CurrentKeys, idleConf.default_keys
+        tracers.attach()
+
+    def test_keyset_source(self):
+        eq = self.assertEqual
+        d = self.page
+        # Test these separately.
+        d.var_changed_builtin_name = Func()
+        d.var_changed_custom_name = Func()
+        # Builtin selected.
+        d.builtin_keyset_on.invoke()
+        eq(mainpage, {'Keys': {'default': 'True'}})
+        eq(d.var_changed_builtin_name.called, 1)
+        eq(d.var_changed_custom_name.called, 0)
+        changes.clear()
+
+        # Custom selected.
+        d.custom_keyset_on.state(('!disabled',))
+        d.custom_keyset_on.invoke()
+        self.assertEqual(mainpage, {'Keys': {'default': 'False'}})
+        eq(d.var_changed_builtin_name.called, 1)
+        eq(d.var_changed_custom_name.called, 1)
+        del d.var_changed_builtin_name, d.var_changed_custom_name
+
+    def test_builtin_name(self):
+        eq = self.assertEqual
+        d = self.page
+        idleConf.userCfg['main'].remove_section('Keys')
+        item_list = ['IDLE Classic Windows', 'IDLE Classic OSX',
+                     'IDLE Modern UNIX']
+
+        # Not in old_keys, defaults name to first item.
+        d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
+        eq(mainpage, {'Keys': {'name': 'IDLE Classic Windows',
+                               'name2': 'IDLE Modern UNIX'}})
+        eq(d.keys_message['text'], 'New key set, see Help')
+        eq(d.load_keys_list.called, 1)
+        eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))
+
+        # Not in old keys - uses name2.
+        changes.clear()
+        idleConf.SetOption('main', 'Keys', 'name', 'IDLE Classic Unix')
+        d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
+        eq(mainpage, {'Keys': {'name2': 'IDLE Modern UNIX'}})
+        eq(d.keys_message['text'], 'New key set, see Help')
+        eq(d.load_keys_list.called, 2)
+        eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))
+
+        # Builtin name in old_keys.
+        changes.clear()
+        d.builtinlist.SetMenu(item_list, 'IDLE Classic OSX')
+        eq(mainpage, {'Keys': {'name': 'IDLE Classic OSX', 'name2': ''}})
+        eq(d.keys_message['text'], '')
+        eq(d.load_keys_list.called, 3)
+        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
+
+    def test_custom_name(self):
+        d = self.page
+
+        # If no selections, doesn't get added.
+        d.customlist.SetMenu([], '- no custom keys -')
+        self.assertNotIn('Keys', mainpage)
+        self.assertEqual(d.load_keys_list.called, 0)
+
+        # Custom name selected.
+        changes.clear()
+        d.customlist.SetMenu(['a', 'b', 'c'], 'c')
+        self.assertEqual(mainpage, {'Keys': {'name': 'c'}})
+        self.assertEqual(d.load_keys_list.called, 1)
+
+    def test_keybinding(self):
+        idleConf.SetOption('extensions', 'ZzDummy', 'enable', 'True')
+        d = self.page
+        d.custom_name.set('my custom keys')
+        d.bindingslist.delete(0, 'end')
+        d.bindingslist.insert(0, 'copy')
+        d.bindingslist.insert(1, 'z-in')
+        d.bindingslist.selection_set(0)
+        d.bindingslist.selection_anchor(0)
+        # Core binding - adds to keys.
+        d.keybinding.set('')
+        self.assertEqual(keyspage,
+                         {'my custom keys': {'copy': ''}})
+
+        # Not a core binding - adds to extensions.
+        d.bindingslist.selection_set(1)
+        d.bindingslist.selection_anchor(1)
+        d.keybinding.set('')
+        self.assertEqual(extpage,
+                         {'ZzDummy_cfgBindings': {'z-in': ''}})
+
+    def test_set_keys_type(self):
+        eq = self.assertEqual
+        d = self.page
+        del d.set_keys_type
+
+        # Builtin keyset selected.
+        d.keyset_source.set(True)
+        d.set_keys_type()
+        eq(d.builtinlist['state'], NORMAL)
+        eq(d.customlist['state'], DISABLED)
+        eq(d.button_delete_custom_keys.state(), ('disabled',))
+
+        # Custom keyset selected.
+        d.keyset_source.set(False)
+        d.set_keys_type()
+        eq(d.builtinlist['state'], DISABLED)
+        eq(d.custom_keyset_on.state(), ('selected',))
+        eq(d.customlist['state'], NORMAL)
+        eq(d.button_delete_custom_keys.state(), ())
+        d.set_keys_type = Func()
+
+    def test_get_new_keys(self):
+        eq = self.assertEqual
+        d = self.page
+        orig_getkeysdialog = configdialog.GetKeysWindow
+        gkd = configdialog.GetKeysWindow = Func(return_self=True)
+        gnkn = d.get_new_keys_name = Func()
+
+        d.button_new_keys.state(('!disabled',))
+        d.bindingslist.delete(0, 'end')
+        d.bindingslist.insert(0, 'copy - ')
+        d.bindingslist.selection_set(0)
+        d.bindingslist.selection_anchor(0)
+        d.keybinding.set('Key-a')
+        d.keyset_source.set(True)  # Default keyset.
+
+        # Default keyset; no change to binding.
+        gkd.result = ''
+        d.button_new_keys.invoke()
+        eq(d.bindingslist.get('anchor'), 'copy - ')
+        # Keybinding isn't changed when there isn't a change entered.
+        eq(d.keybinding.get(), 'Key-a')
+
+        # Default keyset; binding changed.
+        gkd.result = ''
+        # No keyset name selected therefore binding not saved.
+        gnkn.result = ''
+        d.button_new_keys.invoke()
+        eq(gnkn.called, 1)
+        eq(d.bindingslist.get('anchor'), 'copy - ')
+        # Keyset name selected.
+        gnkn.result = 'My New Key Set'
+        d.button_new_keys.invoke()
+        eq(d.custom_name.get(), gnkn.result)
+        eq(d.bindingslist.get('anchor'), 'copy - ')
+        eq(d.keybinding.get(), '')
+
+        # User keyset; binding changed.
+        d.keyset_source.set(False)  # Custom keyset.
+        gnkn.called = 0
+        gkd.result = ''
+        d.button_new_keys.invoke()
+        eq(gnkn.called, 0)
+        eq(d.bindingslist.get('anchor'), 'copy - ')
+        eq(d.keybinding.get(), '')
+
+        del d.get_new_keys_name
+        configdialog.GetKeysWindow = orig_getkeysdialog
+
+    def test_get_new_keys_name(self):
+        orig_sectionname = configdialog.SectionName
+        sn = configdialog.SectionName = Func(return_self=True)
+        d = self.page
+
+        sn.result = 'New Keys'
+        self.assertEqual(d.get_new_keys_name(''), 'New Keys')
+
+        configdialog.SectionName = orig_sectionname
+
+    def test_save_as_new_key_set(self):
+        d = self.page
+        gnkn = d.get_new_keys_name = Func()
+        d.keyset_source.set(True)
+
+        # No name entered.
+        gnkn.result = ''
+        d.button_save_custom_keys.invoke()
+
+        # Name entered.
+        gnkn.result = 'my new key set'
+        gnkn.called = 0
+        self.assertNotIn(gnkn.result, idleConf.userCfg['keys'])
+        d.button_save_custom_keys.invoke()
+        self.assertIn(gnkn.result, idleConf.userCfg['keys'])
+
+        del d.get_new_keys_name
+
+    def test_on_bindingslist_select(self):
+        d = self.page
+        b = d.bindingslist
+        b.delete(0, 'end')
+        b.insert(0, 'copy')
+        b.insert(1, 'find')
+        b.activate(0)
+
+        b.focus_force()
+        b.see(1)
+        b.update()
+        x, y, dx, dy = b.bbox(1)
+        x += dx // 2
+        y += dy // 2
+        b.event_generate('', x=0, y=0)
+        b.event_generate('', x=x, y=y)
+        b.event_generate('', x=x, y=y)
+        b.event_generate('', x=x, y=y)
+        self.assertEqual(b.get('anchor'), 'find')
+        self.assertEqual(d.button_new_keys.state(), ())
+
+    def test_create_new_key_set_and_save_new_key_set(self):
+        eq = self.assertEqual
+        d = self.page
+
+        # Use default as previously active keyset.
+        d.keyset_source.set(True)
+        d.builtin_name.set('IDLE Classic Windows')
+        first_new = 'my new custom key set'
+        second_new = 'my second custom keyset'
+
+        # No changes, so keysets are an exact copy.
+        self.assertNotIn(first_new, idleConf.userCfg)
+        d.create_new_key_set(first_new)
+        eq(idleConf.GetSectionList('user', 'keys'), [first_new])
+        eq(idleConf.GetKeySet('IDLE Classic Windows'),
+           idleConf.GetKeySet(first_new))
+        eq(d.custom_name.get(), first_new)
+        self.assertFalse(d.keyset_source.get())  # Use custom set.
+        eq(d.set_keys_type.called, 1)
+
+        # Test that changed keybindings are in new keyset.
+        changes.add_option('keys', first_new, 'copy', '')
+        self.assertNotIn(second_new, idleConf.userCfg)
+        d.create_new_key_set(second_new)
+        eq(idleConf.GetSectionList('user', 'keys'), [first_new, second_new])
+        self.assertNotEqual(idleConf.GetKeySet(first_new),
+                            idleConf.GetKeySet(second_new))
+        # Check that difference in keysets was in option `copy` from `changes`.
+        idleConf.SetOption('keys', first_new, 'copy', '')
+        eq(idleConf.GetKeySet(first_new), idleConf.GetKeySet(second_new))
+
+    def test_load_keys_list(self):
+        eq = self.assertEqual
+        d = self.page
+        gks = idleConf.GetKeySet = Func()
+        del d.load_keys_list
+        b = d.bindingslist
+
+        b.delete(0, 'end')
+        b.insert(0, '<>')
+        b.insert(1, '<>')
+        gks.result = {'<>': ['', ''],
+                      '<>': [''],
+                      '<>': ['']}
+        changes.add_option('keys', 'my keys', 'spam', '')
+        expected = ('copy -  ',
+                    'force-open-completions - ',
+                    'spam - ')
+
+        # No current selection.
+        d.load_keys_list('my keys')
+        eq(b.get(0, 'end'), expected)
+        eq(b.get('anchor'), '')
+        eq(b.curselection(), ())
+
+        # Check selection.
+        b.selection_set(1)
+        b.selection_anchor(1)
+        d.load_keys_list('my keys')
+        eq(b.get(0, 'end'), expected)
+        eq(b.get('anchor'), 'force-open-completions - ')
+        eq(b.curselection(), (1, ))
+
+        # Change selection.
+        b.selection_set(2)
+        b.selection_anchor(2)
+        d.load_keys_list('my keys')
+        eq(b.get(0, 'end'), expected)
+        eq(b.get('anchor'), 'spam - ')
+        eq(b.curselection(), (2, ))
+        d.load_keys_list = Func()
+
+        del idleConf.GetKeySet
+
+    def test_delete_custom_keys(self):
+        eq = self.assertEqual
+        d = self.page
+        d.button_delete_custom_keys.state(('!disabled',))
+        yesno = d.askyesno = Func()
+        dialog.deactivate_current_config = Func()
+        dialog.activate_config_changes = Func()
+
+        keyset_name = 'spam key set'
+        idleConf.userCfg['keys'].SetOption(keyset_name, 'name', 'value')
+        keyspage[keyset_name] = {'option': 'True'}
+
+        keyset_name2 = 'other key set'
+        idleConf.userCfg['keys'].SetOption(keyset_name2, 'name', 'value')
+        keyspage[keyset_name2] = {'option': 'False'}
+
+        # Force custom keyset.
+        d.custom_keyset_on.state(('!disabled',))
+        d.custom_keyset_on.invoke()
+        d.custom_name.set(keyset_name)
+
+        # Cancel deletion.
+        yesno.result = False
+        d.button_delete_custom_keys.invoke()
+        eq(yesno.called, 1)
+        eq(keyspage[keyset_name], {'option': 'True'})
+        eq(idleConf.GetSectionList('user', 'keys'), [keyset_name, keyset_name2])
+        eq(dialog.deactivate_current_config.called, 0)
+        eq(dialog.activate_config_changes.called, 0)
+        eq(d.set_keys_type.called, 0)
+
+        # Confirm deletion.
+        yesno.result = True
+        d.button_delete_custom_keys.invoke()
+        eq(yesno.called, 2)
+        self.assertNotIn(keyset_name, keyspage)
+        eq(idleConf.GetSectionList('user', 'keys'), [keyset_name2])
+        eq(d.custom_keyset_on.state(), ())
+        eq(d.custom_name.get(), keyset_name2)
+        eq(dialog.deactivate_current_config.called, 1)
+        eq(dialog.activate_config_changes.called, 1)
+        eq(d.set_keys_type.called, 1)
+
+        # Confirm deletion of second keyset - empties list.
+        d.custom_name.set(keyset_name2)
+        yesno.result = True
+        d.button_delete_custom_keys.invoke()
+        eq(yesno.called, 3)
+        self.assertNotIn(keyset_name, keyspage)
+        eq(idleConf.GetSectionList('user', 'keys'), [])
+        eq(d.custom_keyset_on.state(), ('disabled',))
+        eq(d.custom_name.get(), '- no custom keys -')
+        eq(dialog.deactivate_current_config.called, 2)
+        eq(dialog.activate_config_changes.called, 2)
+        eq(d.set_keys_type.called, 2)
+
+        del dialog.activate_config_changes, dialog.deactivate_current_config
+        del d.askyesno
+
+
+class WinPageTest(unittest.TestCase):
+    """Test that general tab widgets enable users to make changes.
+
+    Test that widget actions set vars, that var changes add
+    options to changes.
+    """
+    @classmethod
+    def setUpClass(cls):
+        page = cls.page = dialog.winpage
+        dialog.note.select(page)
+        page.update()
+
+    def setUp(self):
+        changes.clear()
+
+    def test_load_windows_cfg(self):
+        # Set to wrong values, load, check right values.
+        eq = self.assertEqual
+        d = self.page
+        d.startup_edit.set(1)
+        d.win_width.set(1)
+        d.win_height.set(1)
+        d.load_windows_cfg()
+        eq(d.startup_edit.get(), 0)
+        eq(d.win_width.get(), '80')
+        eq(d.win_height.get(), '40')
+
+    def test_startup(self):
+        d = self.page
+        d.startup_editor_on.invoke()
+        self.assertEqual(mainpage,
+                         {'General': {'editor-on-startup': '1'}})
+        changes.clear()
+        d.startup_shell_on.invoke()
+        self.assertEqual(mainpage,
+                         {'General': {'editor-on-startup': '0'}})
+
+    def test_editor_size(self):
+        d = self.page
+        d.win_height_int.delete(0, 'end')
+        d.win_height_int.insert(0, '11')
+        self.assertEqual(mainpage, {'EditorWindow': {'height': '11'}})
+        changes.clear()
+        d.win_width_int.delete(0, 'end')
+        d.win_width_int.insert(0, '11')
+        self.assertEqual(mainpage, {'EditorWindow': {'width': '11'}})
+
+    def test_indent_spaces(self):
+        d = self.page
+        d.indent_chooser.set(6)
+        self.assertEqual(d.indent_spaces.get(), '6')
+        self.assertEqual(mainpage, {'Indent': {'num-spaces': '6'}})
+
+    def test_cursor_blink(self):
+        self.page.cursor_blink_bool.invoke()
+        self.assertEqual(mainpage, {'EditorWindow': {'cursor-blink': 'False'}})
+
+    def test_autocomplete_wait(self):
+        self.page.auto_wait_int.delete(0, 'end')
+        self.page.auto_wait_int.insert(0, '11')
+        self.assertEqual(extpage, {'AutoComplete': {'popupwait': '11'}})
+
+    def test_parenmatch(self):
+        d = self.page
+        eq = self.assertEqual
+        d.paren_style_type['menu'].invoke(0)
+        eq(extpage, {'ParenMatch': {'style': 'opener'}})
+        changes.clear()
+        d.paren_flash_time.delete(0, 'end')
+        d.paren_flash_time.insert(0, '11')
+        eq(extpage, {'ParenMatch': {'flash-delay': '11'}})
+        changes.clear()
+        d.bell_on.invoke()
+        eq(extpage, {'ParenMatch': {'bell': 'False'}})
+
+    def test_paragraph(self):
+        self.page.format_width_int.delete(0, 'end')
+        self.page.format_width_int.insert(0, '11')
+        self.assertEqual(extpage, {'FormatParagraph': {'max-width': '11'}})
+
+
+class ShedPageTest(unittest.TestCase):
+    """Test that shed tab widgets enable users to make changes.
+
+    Test that widget actions set vars, that var changes add
+    options to changes.
+    """
+    @classmethod
+    def setUpClass(cls):
+        page = cls.page = dialog.shedpage
+        dialog.note.select(page)
+        page.update()
+
+    def setUp(self):
+        changes.clear()
+
+    def test_load_shelled_cfg(self):
+        # Set to wrong values, load, check right values.
+        eq = self.assertEqual
+        d = self.page
+        d.autosave.set(1)
+        d.load_shelled_cfg()
+        eq(d.autosave.get(), 0)
+
+    def test_autosave(self):
+        d = self.page
+        d.save_auto_on.invoke()
+        self.assertEqual(mainpage, {'General': {'autosave': '1'}})
+        d.save_ask_on.invoke()
+        self.assertEqual(mainpage, {'General': {'autosave': '0'}})
+
+    def test_context(self):
+        self.page.context_int.delete(0, 'end')
+        self.page.context_int.insert(0, '1')
+        self.assertEqual(extpage, {'CodeContext': {'maxlines': '1'}})
+
+
+#unittest.skip("Nothing here yet TODO")
+class ExtPageTest(unittest.TestCase):
+    """Test that the help source list works correctly."""
+    @classmethod
+    def setUpClass(cls):
+        page = dialog.extpage
+        dialog.note.select(page)
+
+
+class HelpSourceTest(unittest.TestCase):
+    """Test that the help source list works correctly."""
+    @classmethod
+    def setUpClass(cls):
+        page = dialog.extpage
+        dialog.note.select(page)
+        frame = cls.frame = page.frame_help
+        frame.set = frame.set_add_delete_state = Func()
+        frame.upc = frame.update_help_changes = Func()
+        frame.update()
+
+    @classmethod
+    def tearDownClass(cls):
+        frame = cls.frame
+        del frame.set, frame.set_add_delete_state
+        del frame.upc, frame.update_help_changes
+        frame.helplist.delete(0, 'end')
+        frame.user_helplist.clear()
+
+    def setUp(self):
+        changes.clear()
+
+    def test_load_helplist(self):
+        eq = self.assertEqual
+        fr = self.frame
+        fr.helplist.insert('end', 'bad')
+        fr.user_helplist = ['bad', 'worse']
+        idleConf.SetOption('main', 'HelpFiles', '1', 'name;file')
+        fr.load_helplist()
+        eq(fr.helplist.get(0, 'end'), ('name',))
+        eq(fr.user_helplist, [('name', 'file', '1')])
+
+    def test_source_selected(self):
+        fr = self.frame
+        fr.set = fr.set_add_delete_state
+        fr.upc = fr.update_help_changes
+        helplist = fr.helplist
+        dex = 'end'
+        helplist.insert(dex, 'source')
+        helplist.activate(dex)
+
+        helplist.focus_force()
+        helplist.see(dex)
+        helplist.update()
+        x, y, dx, dy = helplist.bbox(dex)
+        x += dx // 2
+        y += dy // 2
+        fr.set.called = fr.upc.called = 0
+        helplist.event_generate('', x=0, y=0)
+        helplist.event_generate('', x=x, y=y)
+        helplist.event_generate('', x=x, y=y)
+        helplist.event_generate('', x=x, y=y)
+        self.assertEqual(helplist.get('anchor'), 'source')
+        self.assertTrue(fr.set.called)
+        self.assertFalse(fr.upc.called)
+
+    def test_set_add_delete_state(self):
+        # Call with 0 items, 1 unselected item, 1 selected item.
+        eq = self.assertEqual
+        fr = self.frame
+        del fr.set_add_delete_state  # Unmask method.
+        sad = fr.set_add_delete_state
+        h = fr.helplist
+
+        h.delete(0, 'end')
+        sad()
+        eq(fr.button_helplist_edit.state(), ('disabled',))
+        eq(fr.button_helplist_remove.state(), ('disabled',))
+
+        h.insert(0, 'source')
+        sad()
+        eq(fr.button_helplist_edit.state(), ('disabled',))
+        eq(fr.button_helplist_remove.state(), ('disabled',))
+
+        h.selection_set(0)
+        sad()
+        eq(fr.button_helplist_edit.state(), ())
+        eq(fr.button_helplist_remove.state(), ())
+        fr.set_add_delete_state = Func()  # Mask method.
+
+    def test_helplist_item_add(self):
+        # Call without and twice with HelpSource result.
+        # Double call enables check on order.
+        eq = self.assertEqual
+        orig_helpsource = configdialog.HelpSource
+        hs = configdialog.HelpSource = Func(return_self=True)
+        fr = self.frame
+        fr.helplist.delete(0, 'end')
+        fr.user_helplist.clear()
+        fr.set.called = fr.upc.called = 0
+
+        hs.result = ''
+        fr.helplist_item_add()
+        self.assertTrue(list(fr.helplist.get(0, 'end')) ==
+                        fr.user_helplist == [])
+        self.assertFalse(fr.upc.called)
+
+        hs.result = ('name1', 'file1')
+        fr.helplist_item_add()
+        hs.result = ('name2', 'file2')
+        fr.helplist_item_add()
+        eq(fr.helplist.get(0, 'end'), ('name1', 'name2'))
+        eq(fr.user_helplist, [('name1', 'file1'), ('name2', 'file2')])
+        eq(fr.upc.called, 2)
+        self.assertFalse(fr.set.called)
+
+        configdialog.HelpSource = orig_helpsource
+
+    def test_helplist_item_edit(self):
+        # Call without and with HelpSource change.
+        eq = self.assertEqual
+        orig_helpsource = configdialog.HelpSource
+        hs = configdialog.HelpSource = Func(return_self=True)
+        fr = self.frame
+        fr.helplist.delete(0, 'end')
+        fr.helplist.insert(0, 'name1')
+        fr.helplist.selection_set(0)
+        fr.helplist.selection_anchor(0)
+        fr.user_helplist.clear()
+        fr.user_helplist.append(('name1', 'file1'))
+        fr.set.called = fr.upc.called = 0
+
+        hs.result = ''
+        fr.helplist_item_edit()
+        hs.result = ('name1', 'file1')
+        fr.helplist_item_edit()
+        eq(fr.helplist.get(0, 'end'), ('name1',))
+        eq(fr.user_helplist, [('name1', 'file1')])
+        self.assertFalse(fr.upc.called)
+
+        hs.result = ('name2', 'file2')
+        fr.helplist_item_edit()
+        eq(fr.helplist.get(0, 'end'), ('name2',))
+        eq(fr.user_helplist, [('name2', 'file2')])
+        self.assertTrue(fr.upc.called == fr.set.called == 1)
+
+        configdialog.HelpSource = orig_helpsource
+
+    def test_helplist_item_remove(self):
+        eq = self.assertEqual
+        fr = self.frame
+        fr.helplist.delete(0, 'end')
+        fr.helplist.insert(0, 'name1')
+        fr.helplist.selection_set(0)
+        fr.helplist.selection_anchor(0)
+        fr.user_helplist.clear()
+        fr.user_helplist.append(('name1', 'file1'))
+        fr.set.called = fr.upc.called = 0
+
+        fr.helplist_item_remove()
+        eq(fr.helplist.get(0, 'end'), ())
+        eq(fr.user_helplist, [])
+        self.assertTrue(fr.upc.called == fr.set.called == 1)
+
+    def test_update_help_changes(self):
+        fr = self.frame
+        del fr.update_help_changes
+        fr.user_helplist.clear()
+        fr.user_helplist.append(('name1', 'file1'))
+        fr.user_helplist.append(('name2', 'file2'))
+
+        fr.update_help_changes()
+        self.assertEqual(mainpage['HelpFiles'],
+                         {'1': 'name1;file1', '2': 'name2;file2'})
+        fr.update_help_changes = Func()
+
+
+class VarTraceTest(unittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        cls.tracers = configdialog.VarTrace()
+        cls.iv = IntVar(root)
+        cls.bv = BooleanVar(root)
+
+    @classmethod
+    def tearDownClass(cls):
+        del cls.tracers, cls.iv, cls.bv
+
+    def setUp(self):
+        self.tracers.clear()
+        self.called = 0
+
+    def var_changed_increment(self, *params):
+        self.called += 13
+
+    def var_changed_boolean(self, *params):
+        pass
+
+    def test_init(self):
+        tr = self.tracers
+        tr.__init__()
+        self.assertEqual(tr.untraced, [])
+        self.assertEqual(tr.traced, [])
+
+    def test_clear(self):
+        tr = self.tracers
+        tr.untraced.append(0)
+        tr.traced.append(1)
+        tr.clear()
+        self.assertEqual(tr.untraced, [])
+        self.assertEqual(tr.traced, [])
+
+    def test_add(self):
+        tr = self.tracers
+        func = Func()
+        cb = tr.make_callback = mock.Mock(return_value=func)
+
+        iv = tr.add(self.iv, self.var_changed_increment)
+        self.assertIs(iv, self.iv)
+        bv = tr.add(self.bv, self.var_changed_boolean)
+        self.assertIs(bv, self.bv)
+
+        sv = StringVar(root)
+        sv2 = tr.add(sv, ('main', 'section', 'option'))
+        self.assertIs(sv2, sv)
+        cb.assert_called_once()
+        cb.assert_called_with(sv, ('main', 'section', 'option'))
+
+        expected = [(iv, self.var_changed_increment),
+                    (bv, self.var_changed_boolean),
+                    (sv, func)]
+        self.assertEqual(tr.traced, [])
+        self.assertEqual(tr.untraced, expected)
+
+        del tr.make_callback
+
+    def test_make_callback(self):
+        cb = self.tracers.make_callback(self.iv, ('main', 'section', 'option'))
+        self.assertTrue(callable(cb))
+        self.iv.set(42)
+        # Not attached, so set didn't invoke the callback.
+        self.assertNotIn('section', changes['main'])
+        # Invoke callback manually.
+        cb()
+        self.assertIn('section', changes['main'])
+        self.assertEqual(changes['main']['section']['option'], '42')
+        changes.clear()
+
+    def test_attach_detach(self):
+        tr = self.tracers
+        iv = tr.add(self.iv, self.var_changed_increment)
+        bv = tr.add(self.bv, self.var_changed_boolean)
+        expected = [(iv, self.var_changed_increment),
+                    (bv, self.var_changed_boolean)]
+
+        # Attach callbacks and test call increment.
+        tr.attach()
+        self.assertEqual(tr.untraced, [])
+        self.assertCountEqual(tr.traced, expected)
+        iv.set(1)
+        self.assertEqual(iv.get(), 1)
+        self.assertEqual(self.called, 13)
+
+        # Check that only one callback is attached to a variable.
+        # If more than one callback were attached, then var_changed_increment
+        # would be called twice and the counter would be 2.
+        self.called = 0
+        tr.attach()
+        iv.set(1)
+        self.assertEqual(self.called, 13)
+
+        # Detach callbacks.
+        self.called = 0
+        tr.detach()
+        self.assertEqual(tr.traced, [])
+        self.assertCountEqual(tr.untraced, expected)
+        iv.set(1)
+        self.assertEqual(self.called, 0)
+
+
+if __name__ == '__main__':
+    unittest.main(verbosity=2)
diff --git a/shared/package-files/56/56748ba2ad7a0d9af693785bd79cb9929f8b684ca9662813710884ecc4bda175/special_bessel_j0_native.h b/shared/package-files/56/56748ba2ad7a0d9af693785bd79cb9929f8b684ca9662813710884ecc4bda175/special_bessel_j0_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..bee8a9f0205a61da5600919819ada99e68a866bd
--- /dev/null
+++ b/shared/package-files/56/56748ba2ad7a0d9af693785bd79cb9929f8b684ca9662813710884ecc4bda175/special_bessel_j0_native.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_special_bessel_j0_out : public at::meta::structured_special_bessel_j0 {
+void impl(const at::Tensor & self, const at::Tensor & out);
+};
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/5674c39ad83231b5f424a219d836af97bd3d22fa7424afa1c4952dd06ad4b0b5/test_astype.cpython-311.pyc b/shared/package-files/56/5674c39ad83231b5f424a219d836af97bd3d22fa7424afa1c4952dd06ad4b0b5/test_astype.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d7ec5403d825b1069052744d7e02477a33b3933
Binary files /dev/null and b/shared/package-files/56/5674c39ad83231b5f424a219d836af97bd3d22fa7424afa1c4952dd06ad4b0b5/test_astype.cpython-311.pyc differ
diff --git a/shared/package-files/56/5677abdfc5cddc7b8f48d17d42f72ebf41e086e7d0470a82e6a043d238bb1aab/group_norm_compositeimplicitautograd_dispatch.h b/shared/package-files/56/5677abdfc5cddc7b8f48d17d42f72ebf41e086e7d0470a82e6a043d238bb1aab/group_norm_compositeimplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5722d88243346058ae366b70e7f3aadbf9e8e18
--- /dev/null
+++ b/shared/package-files/56/5677abdfc5cddc7b8f48d17d42f72ebf41e086e7d0470a82e6a043d238bb1aab/group_norm_compositeimplicitautograd_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeimplicitautograd {
+
+TORCH_API at::Tensor group_norm(const at::Tensor & input, int64_t num_groups, const ::std::optional & weight={}, const ::std::optional & bias={}, double eps=1e-05, bool cudnn_enabled=true);
+
+} // namespace compositeimplicitautograd
+} // namespace at
diff --git a/shared/package-files/56/5679656a716cec5968f7d1188b8e26134d970f1a676e29788088c429b907e41e/coreerrors.cpython-311.pyc b/shared/package-files/56/5679656a716cec5968f7d1188b8e26134d970f1a676e29788088c429b907e41e/coreerrors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dddb111f9428ab245f1604f41e8bdfad076ba0c7
Binary files /dev/null and b/shared/package-files/56/5679656a716cec5968f7d1188b8e26134d970f1a676e29788088c429b907e41e/coreerrors.cpython-311.pyc differ
diff --git a/shared/package-files/56/567bf794fd8c9088cbbda8f92d3b0fbd937f193b1a18397b7387737476c46412/test_at.py b/shared/package-files/56/567bf794fd8c9088cbbda8f92d3b0fbd937f193b1a18397b7387737476c46412/test_at.py
new file mode 100644
index 0000000000000000000000000000000000000000..d78694018749c80824fac7b7a55c86ebee28be19
--- /dev/null
+++ b/shared/package-files/56/567bf794fd8c9088cbbda8f92d3b0fbd937f193b1a18397b7387737476c46412/test_at.py
@@ -0,0 +1,257 @@
+from datetime import (
+    datetime,
+    timezone,
+)
+
+import numpy as np
+import pytest
+
+from pandas.errors import InvalidIndexError
+
+from pandas import (
+    CategoricalDtype,
+    CategoricalIndex,
+    DataFrame,
+    DatetimeIndex,
+    Index,
+    MultiIndex,
+    Series,
+    Timestamp,
+)
+import pandas._testing as tm
+
+
+def test_at_timezone():
+    # https://github.com/pandas-dev/pandas/issues/33544
+    result = DataFrame({"foo": [datetime(2000, 1, 1)]})
+    with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
+        result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=timezone.utc)
+    expected = DataFrame(
+        {"foo": [datetime(2000, 1, 2, tzinfo=timezone.utc)]}, dtype=object
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_selection_methods_of_assigned_col():
+    # GH 29282
+    df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
+    df2 = DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0])
+    df["c"] = df2["c"]
+    df.at[1, "c"] = 11
+    result = df
+    expected = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [9, 11, 7]})
+    tm.assert_frame_equal(result, expected)
+    result = df.at[1, "c"]
+    assert result == 11
+
+    result = df["c"]
+    expected = Series([9, 11, 7], name="c")
+    tm.assert_series_equal(result, expected)
+
+    result = df[["c"]]
+    expected = DataFrame({"c": [9, 11, 7]})
+    tm.assert_frame_equal(result, expected)
+
+
+class TestAtSetItem:
+    def test_at_setitem_item_cache_cleared(self):
+        # GH#22372 Note the multi-step construction is necessary to trigger
+        #  the original bug. pandas/issues/22372#issuecomment-413345309
+        df = DataFrame(index=[0])
+        df["x"] = 1
+        df["cost"] = 2
+
+        # accessing df["cost"] adds "cost" to the _item_cache
+        df["cost"]
+
+        # This loc[[0]] lookup used to call _consolidate_inplace at the
+        #  BlockManager level, which failed to clear the _item_cache
+        df.loc[[0]]
+
+        df.at[0, "x"] = 4
+        df.at[0, "cost"] = 789
+
+        expected = DataFrame(
+            {"x": [4], "cost": 789},
+            index=[0],
+            columns=Index(["x", "cost"], dtype=object),
+        )
+        tm.assert_frame_equal(df, expected)
+
+        # And in particular, check that the _item_cache has updated correctly.
+        tm.assert_series_equal(df["cost"], expected["cost"])
+
+    def test_at_setitem_mixed_index_assignment(self):
+        # GH#19860
+        ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
+        ser.at["a"] = 11
+        assert ser.iat[0] == 11
+        ser.at[1] = 22
+        assert ser.iat[3] == 22
+
+    def test_at_setitem_categorical_missing(self):
+        df = DataFrame(
+            index=range(3), columns=range(3), dtype=CategoricalDtype(["foo", "bar"])
+        )
+        df.at[1, 1] = "foo"
+
+        expected = DataFrame(
+            [
+                [np.nan, np.nan, np.nan],
+                [np.nan, "foo", np.nan],
+                [np.nan, np.nan, np.nan],
+            ],
+            dtype=CategoricalDtype(["foo", "bar"]),
+        )
+
+        tm.assert_frame_equal(df, expected)
+
+    def test_at_setitem_multiindex(self):
+        df = DataFrame(
+            np.zeros((3, 2), dtype="int64"),
+            columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
+        )
+        df.at[0, "a"] = 10
+        expected = DataFrame(
+            [[10, 10], [0, 0], [0, 0]],
+            columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
+        )
+        tm.assert_frame_equal(df, expected)
+
+    @pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01"))
+    def test_at_datetime_index(self, row):
+        # Set float64 dtype to avoid upcast when setting .5
+        df = DataFrame(
+            data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"])
+        ).astype({0: "float64"})
+        expected = DataFrame(
+            data=[[0.5, 1], [1.0, 1]],
+            index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]),
+        )
+
+        df.at[row, 0] = 0.5
+        tm.assert_frame_equal(df, expected)
+
+
+class TestAtSetItemWithExpansion:
+    def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture):
+        # GH#25506
+        ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture)
+        result = Series(ts)
+        result.at[1] = ts
+        expected = Series([ts, ts])
+        tm.assert_series_equal(result, expected)
+
+
+class TestAtWithDuplicates:
+    def test_at_with_duplicate_axes_requires_scalar_lookup(self):
+        # GH#33041 check that falling back to loc doesn't allow non-scalar
+        #  args to slip in
+
+        arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2)
+        df = DataFrame(arr, columns=["A", "A"])
+
+        msg = "Invalid call for scalar access"
+        with pytest.raises(ValueError, match=msg):
+            df.at[[1, 2]]
+        with pytest.raises(ValueError, match=msg):
+            df.at[1, ["A"]]
+        with pytest.raises(ValueError, match=msg):
+            df.at[:, "A"]
+
+        with pytest.raises(ValueError, match=msg):
+            df.at[[1, 2]] = 1
+        with pytest.raises(ValueError, match=msg):
+            df.at[1, ["A"]] = 1
+        with pytest.raises(ValueError, match=msg):
+            df.at[:, "A"] = 1
+
+
+class TestAtErrors:
+    # TODO: De-duplicate/parametrize
+    #  test_at_series_raises_key_error2, test_at_frame_raises_key_error2
+
+    def test_at_series_raises_key_error(self, indexer_al):
+        # GH#31724 .at should match .loc
+
+        ser = Series([1, 2, 3], index=[3, 2, 1])
+        result = indexer_al(ser)[1]
+        assert result == 3
+
+        with pytest.raises(KeyError, match="a"):
+            indexer_al(ser)["a"]
+
+    def test_at_frame_raises_key_error(self, indexer_al):
+        # GH#31724 .at should match .loc
+
+        df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])
+
+        result = indexer_al(df)[1, 0]
+        assert result == 3
+
+        with pytest.raises(KeyError, match="a"):
+            indexer_al(df)["a", 0]
+
+        with pytest.raises(KeyError, match="a"):
+            indexer_al(df)[1, "a"]
+
+    def test_at_series_raises_key_error2(self, indexer_al):
+        # at should not fallback
+        # GH#7814
+        # GH#31724 .at should match .loc
+        ser = Series([1, 2, 3], index=list("abc"))
+        result = indexer_al(ser)["a"]
+        assert result == 1
+
+        with pytest.raises(KeyError, match="^0$"):
+            indexer_al(ser)[0]
+
+    def test_at_frame_raises_key_error2(self, indexer_al):
+        # GH#31724 .at should match .loc
+        df = DataFrame({"A": [1, 2, 3]}, index=list("abc"))
+        result = indexer_al(df)["a", "A"]
+        assert result == 1
+
+        with pytest.raises(KeyError, match="^0$"):
+            indexer_al(df)["a", 0]
+
+    def test_at_frame_multiple_columns(self):
+        # GH#48296 - at shouldn't modify multiple columns
+        df = DataFrame({"a": [1, 2], "b": [3, 4]})
+        new_row = [6, 7]
+        with pytest.raises(
+            InvalidIndexError,
+            match=f"You can only assign a scalar value not a \\{type(new_row)}",
+        ):
+            df.at[5] = new_row
+
+    def test_at_getitem_mixed_index_no_fallback(self):
+        # GH#19860
+        ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
+        with pytest.raises(KeyError, match="^0$"):
+            ser.at[0]
+        with pytest.raises(KeyError, match="^4$"):
+            ser.at[4]
+
+    def test_at_categorical_integers(self):
+        # CategoricalIndex with integer categories that don't happen to match
+        #  the Categorical's codes
+        ci = CategoricalIndex([3, 4])
+
+        arr = np.arange(4).reshape(2, 2)
+        frame = DataFrame(arr, index=ci)
+
+        for df in [frame, frame.T]:
+            for key in [0, 1]:
+                with pytest.raises(KeyError, match=str(key)):
+                    df.at[key, key]
+
+    def test_at_applied_for_rows(self):
+        # GH#48729 .at should raise InvalidIndexError when assigning rows
+        df = DataFrame(index=["a"], columns=["col1", "col2"])
+        new_row = [123, 15]
+        with pytest.raises(
+            InvalidIndexError,
+            match=f"You can only assign a scalar value not a \\{type(new_row)}",
+        ):
+            df.at["a"] = new_row
diff --git a/shared/package-files/56/567d1314ee27ff0b3bd22e7c4d1157246469de25e7a3183d96debe167b193615/instantiator.py b/shared/package-files/56/567d1314ee27ff0b3bd22e7c4d1157246469de25e7a3183d96debe167b193615/instantiator.py
new file mode 100644
index 0000000000000000000000000000000000000000..9465eb036daab4b81c82abee1eb38f92ac4d037c
--- /dev/null
+++ b/shared/package-files/56/567d1314ee27ff0b3bd22e7c4d1157246469de25e7a3183d96debe167b193615/instantiator.py
@@ -0,0 +1,156 @@
+#!/usr/bin/python3
+# mypy: allow-untyped-defs
+import atexit
+import importlib
+import logging
+import os
+import sys
+import tempfile
+from typing import Optional
+
+import torch
+from torch.distributed.nn.jit.templates.remote_module_template import (
+    get_remote_module_template,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+_FILE_PREFIX = "_remote_module_"
+_TEMP_DIR = tempfile.TemporaryDirectory()
+INSTANTIATED_TEMPLATE_DIR_PATH = _TEMP_DIR.name
+atexit.register(_TEMP_DIR.cleanup)
+logger.info("Created a temporary directory at %s", INSTANTIATED_TEMPLATE_DIR_PATH)
+sys.path.append(INSTANTIATED_TEMPLATE_DIR_PATH)
+
+
+def get_arg_return_types_from_interface(module_interface):
+    assert getattr(module_interface, "__torch_script_interface__", False), (
+        "Expect a TorchScript class interface decorated by @torch.jit.interface."
+    )
+    qualified_name = torch._jit_internal._qualified_name(module_interface)
+    cu = torch.jit._state._python_cu
+    module_interface_c = cu.get_interface(qualified_name)
+    assert "forward" in module_interface_c.getMethodNames(), (
+        f"Expect forward in interface methods, while it has {module_interface_c.getMethodNames()}"
+    )
+    method_schema = module_interface_c.getMethod("forward")
+
+    arg_str_list = []
+    arg_type_str_list = []
+    assert method_schema is not None
+    for argument in method_schema.arguments:
+        arg_str_list.append(argument.name)
+
+        if argument.has_default_value():
+            default_value_str = f" = {argument.default_value}"
+        else:
+            default_value_str = ""
+        arg_type_str = f"{argument.name}: {argument.type}{default_value_str}"
+        arg_type_str_list.append(arg_type_str)
+
+    arg_str_list = arg_str_list[1:]  # Remove "self".
+    args_str = ", ".join(arg_str_list)
+
+    arg_type_str_list = arg_type_str_list[1:]  # Remove "self".
+    arg_types_str = ", ".join(arg_type_str_list)
+
+    assert len(method_schema.returns) == 1
+    argument = method_schema.returns[0]
+    return_type_str = str(argument.type)
+
+    return args_str, arg_types_str, return_type_str
+
+
+def _write(out_path, text):
+    old_text: Optional[str]
+    try:
+        with open(out_path) as f:
+            old_text = f.read()
+    except OSError:
+        old_text = None
+    if old_text != text:
+        with open(out_path, "w") as f:
+            logger.info("Writing %s", out_path)
+            f.write(text)
+    else:
+        logger.info("Skipped writing %s", out_path)
+
+
+def _do_instantiate_remote_module_template(
+    generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
+):
+    generated_code_text = get_remote_module_template(
+        enable_moving_cpu_tensors_to_cuda
+    ).format(**str_dict)
+    out_path = os.path.join(
+        INSTANTIATED_TEMPLATE_DIR_PATH, f"{generated_module_name}.py"
+    )
+    _write(out_path, generated_code_text)
+
+    # From importlib doc,
+    # > If you are dynamically importing a module that was created since
+    # the interpreter began execution (e.g., created a Python source file),
+    # you may need to call invalidate_caches() in order for the new module
+    # to be noticed by the import system.
+    importlib.invalidate_caches()
+    generated_module = importlib.import_module(f"{generated_module_name}")
+    return generated_module
+
+
+def instantiate_scriptable_remote_module_template(
+    module_interface_cls, enable_moving_cpu_tensors_to_cuda=True
+):
+    if not getattr(module_interface_cls, "__torch_script_interface__", False):
+        raise ValueError(
+            f"module_interface_cls {module_interface_cls} must be a type object decorated by "
+            "@torch.jit.interface"
+        )
+
+    # Generate the template instance name.
+    module_interface_cls_name = torch._jit_internal._qualified_name(
+        module_interface_cls
+    ).replace(".", "_")
+    generated_module_name = f"{_FILE_PREFIX}{module_interface_cls_name}"
+
+    # Generate type annotation strs.
+    assign_module_interface_cls_str = (
+        f"from {module_interface_cls.__module__} import "
+        f"{module_interface_cls.__name__} as module_interface_cls"
+    )
+    args_str, arg_types_str, return_type_str = get_arg_return_types_from_interface(
+        module_interface_cls
+    )
+    kwargs_str = ""
+    arrow_and_return_type_str = f" -> {return_type_str}"
+    arrow_and_future_return_type_str = f" -> Future[{return_type_str}]"
+
+    str_dict = dict(
+        assign_module_interface_cls=assign_module_interface_cls_str,
+        arg_types=arg_types_str,
+        arrow_and_return_type=arrow_and_return_type_str,
+        arrow_and_future_return_type=arrow_and_future_return_type_str,
+        args=args_str,
+        kwargs=kwargs_str,
+        jit_script_decorator="@torch.jit.script",
+    )
+    return _do_instantiate_remote_module_template(
+        generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
+    )
+
+
+def instantiate_non_scriptable_remote_module_template():
+    generated_module_name = f"{_FILE_PREFIX}non_scriptable"
+    str_dict = dict(
+        assign_module_interface_cls="module_interface_cls = None",
+        args="*args",
+        kwargs="**kwargs",
+        arg_types="*args, **kwargs",
+        arrow_and_return_type="",
+        arrow_and_future_return_type="",
+        jit_script_decorator="",
+    )
+    # For a non-scriptable template, always enable moving CPU tensors to a cuda device,
+    # because there is no syntax limitation on the extra handling caused by the script.
+    return _do_instantiate_remote_module_template(generated_module_name, str_dict, True)
diff --git a/shared/package-files/56/567d14e16724f08092848006820bf7b55b505955b4001133fe1701b06aea97aa/beamsearch.py b/shared/package-files/56/567d14e16724f08092848006820bf7b55b505955b4001133fe1701b06aea97aa/beamsearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..23fbe7bbb3f037eca4f7ede25b7edf6305356587
--- /dev/null
+++ b/shared/package-files/56/567d14e16724f08092848006820bf7b55b505955b4001133fe1701b06aea97aa/beamsearch.py
@@ -0,0 +1,90 @@
+"""Basic algorithms for breadth-first searching the nodes of a graph."""
+
+import networkx as nx
+
+__all__ = ["bfs_beam_edges"]
+
+
+@nx._dispatchable
+def bfs_beam_edges(G, source, value, width=None):
+    """Iterates over edges in a beam search.
+
+    The beam search is a generalized breadth-first search in which only
+    the "best" *w* neighbors of the current node are enqueued, where *w*
+    is the beam width and "best" is an application-specific
+    heuristic. In general, a beam search with a small beam width might
+    not visit each node in the graph.
+
+    .. note::
+
+       With the default value of ``width=None`` or `width` greater than the
+       maximum degree of the graph, this function equates to a slower
+       version of `~networkx.algorithms.traversal.breadth_first_search.bfs_edges`.
+       All nodes will be visited, though the order of the reported edges may
+       vary. In such cases, `value` has no effect - consider using `bfs_edges`
+       directly instead.
+
+    Parameters
+    ----------
+    G : NetworkX graph
+
+    source : node
+        Starting node for the breadth-first search; this function
+        iterates over only those edges in the component reachable from
+        this node.
+
+    value : function
+        A function that takes a node of the graph as input and returns a
+        real number indicating how "good" it is. A higher value means it
+        is more likely to be visited sooner during the search. When
+        visiting a new node, only the `width` neighbors with the highest
+        `value` are enqueued (in decreasing order of `value`).
+
+    width : int (default = None)
+        The beam width for the search. This is the number of neighbors
+        (ordered by `value`) to enqueue when visiting each new node.
+
+    Yields
+    ------
+    edge
+        Edges in the beam search starting from `source`, given as a pair
+        of nodes.
+
+    Examples
+    --------
+    To give nodes with, for example, a higher centrality precedence
+    during the search, set the `value` function to return the centrality
+    value of the node:
+
+    >>> G = nx.karate_club_graph()
+    >>> centrality = nx.eigenvector_centrality(G)
+    >>> list(nx.bfs_beam_edges(G, source=0, value=centrality.get, width=3))
+    [(0, 2), (0, 1), (0, 8), (2, 32), (1, 13), (8, 33)]
+    """
+
+    if width is None:
+        width = len(G)
+
+    def successors(v):
+        """Returns a list of the best neighbors of a node.
+
+        `v` is a node in the graph `G`.
+
+        The "best" neighbors are chosen according to the `value`
+        function (higher is better). Only the `width` best neighbors of
+        `v` are returned.
+        """
+        # TODO The Python documentation states that for small values, it
+        # is better to use `heapq.nlargest`. We should determine the
+        # threshold at which its better to use `heapq.nlargest()`
+        # instead of `sorted()[:]` and apply that optimization here.
+        #
+        # If `width` is greater than the number of neighbors of `v`, all
+        # neighbors are returned by the semantics of slicing in
+        # Python. This occurs in the special case that the user did not
+        # specify a `width`: in this case all neighbors are always
+        # returned, so this is just a (slower) implementation of
+        # `bfs_edges(G, source)` but with a sorted enqueue step.
+        return iter(sorted(G.neighbors(v), key=value, reverse=True)[:width])
+
+    yield from nx.generic_bfs_edges(G, source, successors)
diff --git a/shared/package-files/56/567e3dcac61f9874534e7f24df8f6620e5150365674edc3296f6c0e099093389/constants.cpython-311.pyc b/shared/package-files/56/567e3dcac61f9874534e7f24df8f6620e5150365674edc3296f6c0e099093389/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55bca2d05126c19748d2b4c59c50ee03b6c2ddd4
Binary files /dev/null and b/shared/package-files/56/567e3dcac61f9874534e7f24df8f6620e5150365674edc3296f6c0e099093389/constants.cpython-311.pyc differ
diff --git a/shared/package-files/56/5692a7f45c84357e9184a6b606c4d06a67683ec47ed75aa17fa1c79940a2525f/_rules.cpython-311.pyc b/shared/package-files/56/5692a7f45c84357e9184a6b606c4d06a67683ec47ed75aa17fa1c79940a2525f/_rules.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..249968e2d843ea979098152eef8da08ce599b76d
Binary files /dev/null and b/shared/package-files/56/5692a7f45c84357e9184a6b606c4d06a67683ec47ed75aa17fa1c79940a2525f/_rules.cpython-311.pyc differ
diff --git a/shared/package-files/56/5693ee54729713159b2dc3b8bc25efe30151f93d45fa77bb89a4675f6d8d6a0f/graph_passes.cpython-311.pyc b/shared/package-files/56/5693ee54729713159b2dc3b8bc25efe30151f93d45fa77bb89a4675f6d8d6a0f/graph_passes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffa49dbc23f5fbcb12c8be52330c089043cb593a
Binary files /dev/null and b/shared/package-files/56/5693ee54729713159b2dc3b8bc25efe30151f93d45fa77bb89a4675f6d8d6a0f/graph_passes.cpython-311.pyc differ
diff --git a/shared/package-files/56/569848fa8b2fb9f887e33159e6188ae396a5c98472820f8e1d46e4b959162f8e/reflection_pad3d_meta.h b/shared/package-files/56/569848fa8b2fb9f887e33159e6188ae396a5c98472820f8e1d46e4b959162f8e/reflection_pad3d_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..847d8525881b68ee68795da89da763edfdbc8e34
--- /dev/null
+++ b/shared/package-files/56/569848fa8b2fb9f887e33159e6188ae396a5c98472820f8e1d46e4b959162f8e/reflection_pad3d_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_reflection_pad3d : public at::impl::MetaBase {
+    
+    
+    void meta(const at::Tensor & self, at::ArrayRef padding);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/569c77dcfa3a8c56fc632b2a5396fae0ffb563a1c12afbae85d811673f5d0fd0/strtod.h b/shared/package-files/56/569c77dcfa3a8c56fc632b2a5396fae0ffb563a1c12afbae85d811673f5d0fd0/strtod.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb704a3e689ef79cb5977f59fe28a4b68b6eec72
--- /dev/null
+++ b/shared/package-files/56/569c77dcfa3a8c56fc632b2a5396fae0ffb563a1c12afbae85d811673f5d0fd0/strtod.h
@@ -0,0 +1,10 @@
+#pragma once
+
+#include 
+
+namespace torch::jit {
+
+TORCH_API double strtod_c(const char* nptr, char** endptr);
+TORCH_API float strtof_c(const char* nptr, char** endptr);
+
+} // namespace torch::jit
diff --git a/shared/package-files/56/569e01479368a69a7efb60ff4d7ed5e12d5c0ef6d1dac9c32ac52b0e0e9ab7bb/_utils.cpython-311.pyc b/shared/package-files/56/569e01479368a69a7efb60ff4d7ed5e12d5c0ef6d1dac9c32ac52b0e0e9ab7bb/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8524e5945fdc4dd05bab7cea8db9b7f9fbd17d2
Binary files /dev/null and b/shared/package-files/56/569e01479368a69a7efb60ff4d7ed5e12d5c0ef6d1dac9c32ac52b0e0e9ab7bb/_utils.cpython-311.pyc differ
diff --git a/shared/package-files/56/569e4a486503398004e7834c5d11d722663b32311fa5f80edd7651727b49b142/compare.py b/shared/package-files/56/569e4a486503398004e7834c5d11d722663b32311fa5f80edd7651727b49b142/compare.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d797a5b0a2bfc7be3cecd13d4d1ad2ac4e52686
--- /dev/null
+++ b/shared/package-files/56/569e4a486503398004e7834c5d11d722663b32311fa5f80edd7651727b49b142/compare.py
@@ -0,0 +1,99 @@
+# mypy: allow-untyped-defs
+"""Example of Timer and Compare APIs:
+
+$ python -m examples.compare
+"""
+
+import pickle
+import sys
+import time
+
+import torch
+
+import torch.utils.benchmark as benchmark_utils
+
+
+class FauxTorch:
+    """Emulate different versions of pytorch.
+
+    In normal circumstances this would be done with multiple processes
+    writing serialized measurements, but this simplifies that model to
+    make the example clearer.
+    """
+    def __init__(self, real_torch, extra_ns_per_element):
+        self._real_torch = real_torch
+        self._extra_ns_per_element = extra_ns_per_element
+
+    def extra_overhead(self, result):
+        # time.sleep has a ~65 us overhead, so only fake a
+        # per-element overhead if numel is large enough.
+        numel = int(result.numel())
+        if numel > 5000:
+            time.sleep(numel * self._extra_ns_per_element * 1e-9)
+        return result
+
+    def add(self, *args, **kwargs):
+        return self.extra_overhead(self._real_torch.add(*args, **kwargs))
+
+    def mul(self, *args, **kwargs):
+        return self.extra_overhead(self._real_torch.mul(*args, **kwargs))
+
+    def cat(self, *args, **kwargs):
+        return self.extra_overhead(self._real_torch.cat(*args, **kwargs))
+
+    def matmul(self, *args, **kwargs):
+        return self.extra_overhead(self._real_torch.matmul(*args, **kwargs))
+
+
+def main():
+    tasks = [
+        ("add", "add", "torch.add(x, y)"),
+        ("add", "add (extra +0)", "torch.add(x, y + zero)"),
+    ]
+
+    serialized_results = []
+    repeats = 2
+    timers = [
+        benchmark_utils.Timer(
+            stmt=stmt,
+            globals={
+                "torch": torch if branch == "master" else FauxTorch(torch, overhead_ns),
+                "x": torch.ones((size, 4)),
+                "y": torch.ones((1, 4)),
+                "zero": torch.zeros(()),
+            },
+            label=label,
+            sub_label=sub_label,
+            description=f"size: {size}",
+            env=branch,
+            num_threads=num_threads,
+        )
+        for branch, overhead_ns in [("master", None), ("my_branch", 1), ("severe_regression", 5)]
+        for label, sub_label, stmt in tasks
+        for size in [1, 10, 100, 1000, 10000, 50000]
+        for num_threads in [1, 4]
+    ]
+
+    for i, timer in enumerate(timers * repeats):
+        serialized_results.append(pickle.dumps(
+            timer.blocked_autorange(min_run_time=0.05)
+        ))
+        print(f"\r{i + 1} / {len(timers) * repeats}", end="")
+        sys.stdout.flush()
+    print()
+
+    comparison = benchmark_utils.Compare([
+        pickle.loads(i) for i in serialized_results
+    ])
+
+    print("== Unformatted " + "=" * 80 + "\n" + "/" * 95 + "\n")
+    comparison.print()
+
+    print("== Formatted " + "=" * 80 + "\n" + "/" * 93 + "\n")
+    comparison.trim_significant_figures()
+    comparison.colorize()
+    comparison.print()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/shared/package-files/56/569ee22fe8dd13778f8a9873889ceb015491e84836bd0da0586b6011f6112dbe/as_strided_scatter_compositeexplicitautograd_dispatch.h b/shared/package-files/56/569ee22fe8dd13778f8a9873889ceb015491e84836bd0da0586b6011f6112dbe/as_strided_scatter_compositeexplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..cc0962f4b8c45771696c1b5854b85778575781d7
--- /dev/null
+++ b/shared/package-files/56/569ee22fe8dd13778f8a9873889ceb015491e84836bd0da0586b6011f6112dbe/as_strided_scatter_compositeexplicitautograd_dispatch.h
@@ -0,0 +1,26 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautograd {
+
+TORCH_API at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset=::std::nullopt);
+TORCH_API at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset, at::Tensor & out);
+TORCH_API at::Tensor & as_strided_scatter_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset=::std::nullopt);
+TORCH_API at::Tensor & as_strided_scatter_symint_outf(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset, at::Tensor & out);
+
+} // namespace compositeexplicitautograd
+} // namespace at
diff --git a/shared/package-files/56/56a2a90d973c06668f6f113d67f26cf348af10b33eece2a6b812e34da45258d8/policy.py b/shared/package-files/56/56a2a90d973c06668f6f113d67f26cf348af10b33eece2a6b812e34da45258d8/policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..8816c84ed175a709cef85329461185b40efa610a
--- /dev/null
+++ b/shared/package-files/56/56a2a90d973c06668f6f113d67f26cf348af10b33eece2a6b812e34da45258d8/policy.py
@@ -0,0 +1,231 @@
+"""This will be the home for the policy that hooks in the new
+code that adds all the email6 features.
+"""
+
+import re
+import sys
+from email._policybase import Policy, Compat32, compat32, _extend_docstrings
+from email.utils import _has_surrogates
+from email.headerregistry import HeaderRegistry as HeaderRegistry
+from email.contentmanager import raw_data_manager
+from email.message import EmailMessage
+
+__all__ = [
+    'Compat32',
+    'compat32',
+    'Policy',
+    'EmailPolicy',
+    'default',
+    'strict',
+    'SMTP',
+    'HTTP',
+    ]
+
+linesep_splitter = re.compile(r'\n|\r')
+
+@_extend_docstrings
+class EmailPolicy(Policy):
+
+    """+
+    PROVISIONAL
+
+    The API extensions enabled by this policy are currently provisional.
+    Refer to the documentation for details.
+
+    This policy adds new header parsing and folding algorithms.  Instead of
+    simple strings, headers are custom objects with custom attributes
+    depending on the type of the field.  The folding algorithm fully
+    implements RFCs 2047 and 5322.
+
+    In addition to the settable attributes listed above that apply to
+    all Policies, this policy adds the following additional attributes:
+
+    utf8                -- if False (the default) message headers will be
+                           serialized as ASCII, using encoded words to encode
+                           any non-ASCII characters in the source strings.  If
+                           True, the message headers will be serialized using
+                           utf8 and will not contain encoded words (see RFC
+                           6532 for more on this serialization format).
+
+    refold_source       -- if the value for a header in the Message object
+                           came from the parsing of some source, this attribute
+                           indicates whether or not a generator should refold
+                           that value when transforming the message back into
+                           stream form.  The possible values are:
+
+                           none  -- all source values use original folding
+                           long  -- source values that have any line that is
+                                    longer than max_line_length will be
+                                    refolded
+                           all  -- all values are refolded.
+
+                           The default is 'long'.
+
+    header_factory      -- a callable that takes two arguments, 'name' and
+                           'value', where 'name' is a header field name and
+                           'value' is an unfolded header field value, and
+                           returns a string-like object that represents that
+                           header.  A default header_factory is provided that
+                           understands some of the RFC5322 header field types.
+                           (Currently address fields and date fields have
+                           special treatment, while all other fields are
+                           treated as unstructured.  This list will be
+                           completed before the extension is marked stable.)
+
+    content_manager     -- an object with at least two methods: get_content
+                           and set_content.  When the get_content or
+                           set_content method of a Message object is called,
+                           it calls the corresponding method of this object,
+                           passing it the message object as its first argument,
+                           and any arguments or keywords that were passed to
+                           it as additional arguments.  The default
+                           content_manager is
+                           :data:`~email.contentmanager.raw_data_manager`.
+
+    """
+
+    message_factory = EmailMessage
+    utf8 = False
+    refold_source = 'long'
+    header_factory = HeaderRegistry()
+    content_manager = raw_data_manager
+
+    def __init__(self, **kw):
+        # Ensure that each new instance gets a unique header factory
+        # (as opposed to clones, which share the factory).
+        if 'header_factory' not in kw:
+            object.__setattr__(self, 'header_factory', HeaderRegistry())
+        super().__init__(**kw)
+
+    def header_max_count(self, name):
+        """+
+        The implementation for this class returns the max_count attribute from
+        the specialized header class that would be used to construct a header
+        of type 'name'.
+        """
+        return self.header_factory[name].max_count
+
+    # The logic of the next three methods is chosen such that it is possible to
+    # switch a Message object between a Compat32 policy and a policy derived
+    # from this class and have the results stay consistent.  This allows a
+    # Message object constructed with this policy to be passed to a library
+    # that only handles Compat32 objects, or to receive such an object and
+    # convert it to use the newer style by just changing its policy.  It is
+    # also chosen because it postpones the relatively expensive full rfc5322
+    # parse until as late as possible when parsing from source, since in many
+    # applications only a few headers will actually be inspected.
+
+    def header_source_parse(self, sourcelines):
+        """+
+        The name is parsed as everything up to the ':' and returned unmodified.
+        The value is determined by stripping leading whitespace off the
+        remainder of the first line, joining all subsequent lines together, and
+        stripping any trailing carriage return or linefeed characters.  (This
+        is the same as Compat32).
+
+        """
+        name, value = sourcelines[0].split(':', 1)
+        value = value.lstrip(' \t') + ''.join(sourcelines[1:])
+        return (name, value.rstrip('\r\n'))
+
+    def header_store_parse(self, name, value):
+        """+
+        The name is returned unchanged.  If the input value has a 'name'
+        attribute and it matches the name ignoring case, the value is returned
+        unchanged.  Otherwise the name and value are passed to header_factory
+        method, and the resulting custom header object is returned as the
+        value.  In this case a ValueError is raised if the input value contains
+        CR or LF characters.
+
+        """
+        if hasattr(value, 'name') and value.name.lower() == name.lower():
+            return (name, value)
+        if isinstance(value, str) and len(value.splitlines())>1:
+            # XXX this error message isn't quite right when we use splitlines
+            # (see issue 22233), but I'm not sure what should happen here.
+            raise ValueError("Header values may not contain linefeed "
+                             "or carriage return characters")
+        return (name, self.header_factory(name, value))
+
+    def header_fetch_parse(self, name, value):
+        """+
+        If the value has a 'name' attribute, it is returned to unmodified.
+        Otherwise the name and the value with any linesep characters removed
+        are passed to the header_factory method, and the resulting custom
+        header object is returned.  Any surrogateescaped bytes get turned
+        into the unicode unknown-character glyph.
+
+        """
+        if hasattr(value, 'name'):
+            return value
+        # We can't use splitlines here because it splits on more than \r and \n.
+        value = ''.join(linesep_splitter.split(value))
+        return self.header_factory(name, value)
+
+    def fold(self, name, value):
+        """+
+        Header folding is controlled by the refold_source policy setting.  A
+        value is considered to be a 'source value' if and only if it does not
+        have a 'name' attribute (having a 'name' attribute means it is a header
+        object of some sort).  If a source value needs to be refolded according
+        to the policy, it is converted into a custom header object by passing
+        the name and the value with any linesep characters removed to the
+        header_factory method.  Folding of a custom header object is done by
+        calling its fold method with the current policy.
+
+        Source values are split into lines using splitlines.  If the value is
+        not to be refolded, the lines are rejoined using the linesep from the
+        policy and returned.  The exception is lines containing non-ascii
+        binary data.  In that case the value is refolded regardless of the
+        refold_source setting, which causes the binary data to be CTE encoded
+        using the unknown-8bit charset.
+
+        """
+        return self._fold(name, value, refold_binary=True)
+
+    def fold_binary(self, name, value):
+        """+
+        The same as fold if cte_type is 7bit, except that the returned value is
+        bytes.
+
+        If cte_type is 8bit, non-ASCII binary data is converted back into
+        bytes.  Headers with binary data are not refolded, regardless of the
+        refold_header setting, since there is no way to know whether the binary
+        data consists of single byte characters or multibyte characters.
+
+        If utf8 is true, headers are encoded to utf8, otherwise to ascii with
+        non-ASCII unicode rendered as encoded words.
+
+        """
+        folded = self._fold(name, value, refold_binary=self.cte_type=='7bit')
+        charset = 'utf8' if self.utf8 else 'ascii'
+        return folded.encode(charset, 'surrogateescape')
+
+    def _fold(self, name, value, refold_binary=False):
+        if hasattr(value, 'name'):
+            return value.fold(policy=self)
+        maxlen = self.max_line_length if self.max_line_length else sys.maxsize
+        lines = value.splitlines()
+        refold = (self.refold_source == 'all' or
+                  self.refold_source == 'long' and
+                    (lines and len(lines[0])+len(name)+2 > maxlen or
+                     any(len(x) > maxlen for x in lines[1:])))
+
+        if not refold:
+            if not self.utf8:
+                refold = not value.isascii()
+            elif refold_binary:
+                refold = _has_surrogates(value)
+        if refold:
+            return self.header_factory(name, ''.join(lines)).fold(policy=self)
+
+        return name + ': ' + self.linesep.join(lines) + self.linesep
+
+
+default = EmailPolicy()
+# Make the default policy use the class default header_factory
+del default.header_factory
+strict = default.clone(raise_on_defect=True)
+SMTP = default.clone(linesep='\r\n')
+HTTP = default.clone(linesep='\r\n', max_line_length=None)
+SMTPUTF8 = SMTP.clone(utf8=True)
diff --git a/shared/package-files/56/56a7c0636bb33c55453be0b9be85f1525e63722924ed5b1ccc1607eb2f15b09e/DistributionTemplates.h b/shared/package-files/56/56a7c0636bb33c55453be0b9be85f1525e63722924ed5b1ccc1607eb2f15b09e/DistributionTemplates.h
new file mode 100644
index 0000000000000000000000000000000000000000..8171ae8e79ad2a1311f4a8600decd202c66649d5
--- /dev/null
+++ b/shared/package-files/56/56a7c0636bb33c55453be0b9be85f1525e63722924ed5b1ccc1607eb2f15b09e/DistributionTemplates.h
@@ -0,0 +1,425 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef CPU_CAPABILITY_AVX2
+#include 
+#include 
+#endif
+
+
+
+
+namespace at::native::templates::cpu {
+namespace {
+
+// ==================================================== Random ========================================================
+
+template
+void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG generator) {
+  AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cpu", AT_WRAP([&] {
+    std::lock_guard lock(generator->mutex_);
+    cpu_serial_kernel(iter, [range, base, generator]() -> scalar_t {
+      uniform_int_from_to_distribution random(range, base);
+      return random(generator);
+    });
+  }), kBool, kHalf, kBFloat16, AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES));
+}
+
+// This is the special kernel to handle single specific case:
+// from(inclusive) = std::numeric_limits::lowest()
+// to(exclusive) = None (= std::numeric_limits::max() + 1)
+template
+void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG generator) {
+  AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cpu", [&] {
+    if constexpr (std::is_same_v ||
+        std::is_same_v ||
+        std::is_same_v ||
+        std::is_same_v) {
+      std::lock_guard lock(generator->mutex_);
+      cpu_serial_kernel(iter, [generator]() -> scalar_t {
+        uniform_int_full_range_distribution random;
+        return random(generator);
+      });
+    } else {
+      TORCH_CHECK(false, "random_full_64_bits_range_kernel_cpu handles only int64, double, float and bfloat16");
+    }
+  });
+}
+
+template
+struct RandomFromToKernel {
+  void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional gen) {
+    random_from_to_kernel(iter, range, base, check_generator(gen));
+  }
+  void operator()(TensorIteratorBase& iter, std::optional gen) {
+    random_full_64_bits_range_kernel(iter, check_generator(gen));
+  }
+};
+
+template
+void random_kernel(TensorIteratorBase& iter, RNG generator) {
+  std::lock_guard lock(generator->mutex_);
+  AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cpu", [&] {
+    cpu_serial_kernel(iter, [generator]() -> scalar_t {
+      uniform_int_distribution random;
+      return random(generator);
+    });
+  });
+}
+
+template
+struct RandomKernel {
+  void operator()(TensorIteratorBase& iter, std::optional gen) {
+    random_kernel(iter, check_generator(gen));
+  }
+};
+
+// ==================================================== Normal ========================================================
+
+#ifdef CPU_CAPABILITY_AVX2
+static void normal_fill_16_AVX2(float *data,
+                         const __m256* two_pi,
+                         const __m256* one,
+                         const __m256* minus_two,
+                         const __m256* mean,
+                         const __m256* std_v) {
+  const __m256 u1 = _mm256_sub_ps(*one, _mm256_loadu_ps(data));
+  const __m256 u2 = _mm256_loadu_ps(data + 8);
+  // sincos256_ps and log256_ps are from avx_mathfun.h
+  const __m256 radius = _mm256_sqrt_ps(_mm256_mul_ps(*minus_two, log256_ps(u1)));
+  const __m256 theta = _mm256_mul_ps(*two_pi, u2);
+  __m256 sintheta, costheta;
+  sincos256_ps(theta, &sintheta, &costheta);
+  const __m256 n1 = _mm256_mul_ps(radius, costheta);
+  const __m256 n2 = _mm256_mul_ps(radius, sintheta);
+  _mm256_storeu_ps(data, _mm256_fmadd_ps(n1, *std_v, *mean));
+  _mm256_storeu_ps(data + 8, _mm256_fmadd_ps(n2, *std_v, *mean));
+}
+
+template
+void normal_fill_AVX2(const TensorBase &self, const float mean, const float std, RNG generator) {
+  float *data = self.data_ptr();
+  auto size = self.numel();
+  std::lock_guard lock(generator->mutex_);
+  for (const auto i : c10::irange(size)) {
+    at::uniform_real_distribution uniform(0, 1);
+    data[i] = uniform(generator);
+  }
+  const __m256 two_pi = _mm256_set1_ps(2.0f * c10::pi);
+  const __m256 one = _mm256_set1_ps(1.0f);
+  const __m256 minus_two = _mm256_set1_ps(-2.0f);
+  const __m256 mean_v = _mm256_set1_ps(mean);
+  const __m256 std_v = _mm256_set1_ps(std);
+
+  for (int64_t i = 0; i < size - 15; i += 16) {
+    normal_fill_16_AVX2(data + i, &two_pi, &one, &minus_two, &mean_v, &std_v);
+  }
+
+  if (size % 16 != 0) {
+    // Recompute the last 16 values.
+    data = data + size - 16;
+    for (const auto i : c10::irange(16)) {
+      at::uniform_real_distribution uniform(0, 1);
+      data[i] = uniform(generator);
+    }
+    normal_fill_16_AVX2(data, &two_pi, &one, &minus_two, &mean_v, &std_v);
+  }
+}
+#endif
+
+template 
+static void normal_fill_16(scalar_t *data, const scalar_t mean, const scalar_t std) {
+  for (const auto j : c10::irange(8)) {
+    const scalar_t u1 = 1 - data[j]; // [0, 1) -> (0, 1] for log.
+    const scalar_t u2 = data[j + 8];
+    const scalar_t radius = std::sqrt(-2 * std::log(u1));
+    const scalar_t theta = 2.0f * c10::pi * u2;
+    data[j] = radius * std::cos(theta) * std + mean;
+    data[j + 8] = radius * std::sin(theta) * std + mean;
+  }
+}
+
+#if defined(__VSX__)  || defined(CPU_CAPABILITY_VSX)
+static void normal_fill_16_VSX(float *data,const Vectorized &two_pi,const Vectorized &one,const Vectorized &minus_two,const Vectorized &mean,const Vectorized &std) {
+  using Vec = Vectorized;
+  Vec u1=one-Vec::loadu(data);
+  Vec u2=Vec::loadu(data+8);
+  Vec radius=(minus_two * u1.log());
+  radius=radius.sqrt();
+  Vec theta=two_pi * u2;
+  Vec output_vec=radius * theta.cos() * std + mean;
+  Vec output_vec2=radius * theta.sin() * std + mean;
+  output_vec.store(data);
+  output_vec2.store(data+8);
+}
+
+template 
+void normal_fill_VSX(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
+  float *data = self.data_ptr();
+  auto size = self.numel();
+  std::lock_guard lock(generator->mutex_);
+  for (const auto i : c10::irange(size)) {
+    at::uniform_real_distribution uniform(0, 1);
+    data[i] = uniform(generator);
+  }
+
+  using Vec = Vectorized;
+  const Vec two_pi = Vec(2.0f * c10::pi);
+  const Vec one = Vec(1.0f);
+  const Vec minus_two = Vec(-2.0f);
+  const Vec var_vec  = Vec(std);
+  const Vec mean_vec = Vec(mean);
+
+  for (int64_t i = 0; i < size - 15; i += 16) {
+    if(Vec::size()==8) {
+      normal_fill_16_VSX(data + i, two_pi, one, minus_two, mean_vec, var_vec);
+    }
+    else{
+      normal_fill_16(data + i, mean, std);
+    }
+  }
+  if (size % 16 != 0) {
+    // Recompute the last 16 values.
+    data = data + size - 16;
+    for (const auto i : c10::irange(16)) {
+      at::uniform_real_distribution uniform(0, 1);
+      data[i] = uniform(generator);
+    }
+    if(Vec::size()==8){
+      normal_fill_16_VSX(data, two_pi, one, minus_two, mean_vec, var_vec);
+    }
+    else{
+      normal_fill_16(data, mean, std);
+    }
+  }
+}
+#endif //VSX
+
+template 
+void normal_fill(const TensorBase &self, const scalar_t mean, const scalar_t std, RNG generator) {
+  scalar_t *data = self.data_ptr();
+  auto size = self.numel();
+  std::lock_guard lock(generator->mutex_);
+  for (const auto i : c10::irange(size)) {
+    at::uniform_real_distribution uniform(0, 1);
+    data[i] = uniform(generator);
+  }
+
+  for (int64_t i = 0; i < size - 15; i += 16) {
+    normal_fill_16(data + i, mean, std);
+  }
+  if (size % 16 != 0) {
+    // Recompute the last 16 values.
+    data = data + size - 16;
+    for (const auto i : c10::irange(16)) {
+      at::uniform_real_distribution uniform(0, 1);
+      data[i] = uniform(generator);
+    }
+    normal_fill_16(data, mean, std);
+  }
+}
+
+template
+void normal_kernel(const TensorBase &self, double mean, double std, RNG generator) {
+  auto size = self.numel();
+  if (self.scalar_type() == ScalarType::Float && size >= 16 && self.is_contiguous()) {
+#ifdef CPU_CAPABILITY_AVX2
+    normal_fill_AVX2(self, static_cast(mean), static_cast(std), generator);
+#elif defined(__VSX__)  || defined(CPU_CAPABILITY_VSX)
+    normal_fill_VSX(self, static_cast(mean), static_cast(std), generator);
+#else
+    normal_fill(self, static_cast(mean), static_cast(std), generator);
+#endif
+  } else {
+    AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, self.scalar_type(), "normal_kernel_cpu", [&] {
+      if (size >= 16 && self.is_contiguous()) {
+        normal_fill(self, static_cast(mean), static_cast(std), generator);
+      } else {
+        auto iter = TensorIterator::borrowing_nullary_op(self);
+        std::lock_guard lock(generator->mutex_);
+        cpu_serial_kernel(iter, [mean, std, generator]() -> scalar_t {
+          at::normal_distribution normal(mean, std);
+          return static_cast(normal(generator));
+        });
+      }
+    });
+  }
+}
+
+template
+struct NormalKernel {
+  void operator()(Tensor& self, double mean, double std, std::optional gen) {
+    normal_kernel(self, mean, std, check_generator(gen));
+  }
+};
+
+// ==================================================== Uniform =======================================================
+
+template
+void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG generator) {
+  AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "uniform_kernel_cpu", [&]() {
+    std::lock_guard lock(generator->mutex_);
+    auto from = static_cast(from_);
+    auto to = static_cast(to_);
+    at::uniform_real_distribution uniform(from, to);
+    cpu_serial_kernel(iter, [&uniform, generator]() -> scalar_t {
+      return static_cast(uniform(generator));
+    });
+  });
+}
+
+template
+struct UniformKernel {
+  void operator()(TensorIteratorBase& iter, double from, double to, std::optional gen) {
+    uniform_kernel(iter, from, to, check_generator(gen));
+  }
+};
+
+// ==================================================== Cauchy ========================================================
+
+template
+void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, RNG generator) {
+  AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "cauchy_cpu", [&]() {
+    std::lock_guard lock(generator->mutex_);
+    at::cauchy_distribution cauchy(median, sigma);
+    cpu_serial_kernel(iter, [&cauchy, generator]() -> scalar_t {
+      return static_cast(cauchy(generator));
+    });
+  });
+}
+
+template
+struct CauchyKernel {
+  void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional gen) {
+    cauchy_kernel(iter, median, sigma, check_generator(gen));
+  }
+};
+
+// ================================================== LogNormal =======================================================
+
+template
+void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, RNG generator) {
+  AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cpu", [&]() {
+    std::lock_guard lock(generator->mutex_);
+    at::lognormal_distribution logNormal(mean, std);
+    cpu_serial_kernel(iter, [&logNormal, generator]() -> scalar_t {
+      return static_cast(logNormal(generator));
+    });
+  });
+}
+
+template
+struct LogNormalKernel {
+  void operator()(TensorIteratorBase& iter, double mean, double std, std::optional gen) {
+    log_normal_kernel(iter, mean, std, check_generator(gen));
+  }
+};
+
+// =================================================== Geometric ======================================================
+
+template
+void geometric_kernel(TensorIteratorBase& iter, double p, RNG generator) {
+  AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cpu", [&]() {
+    std::lock_guard lock(generator->mutex_);
+    at::geometric_distribution geometric(p);
+    cpu_serial_kernel(iter, [&geometric, generator]() -> scalar_t {
+      return static_cast(geometric(generator));
+    });
+  });
+}
+
+template
+struct GeometricKernel {
+  void operator()(TensorIteratorBase& iter, double p, std::optional gen) {
+    geometric_kernel(iter, p, check_generator(gen));
+  }
+};
+
+// ================================================== Exponential =====================================================
+
+template
+void exponential_kernel(TensorIteratorBase& iter, double lambda, RNG generator) {
+  TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype());
+  AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cpu", [&]() {
+    std::lock_guard lock(generator->mutex_);
+    at::exponential_distribution exponential(lambda);
+    cpu_serial_kernel(iter, [&exponential, generator]() -> scalar_t {
+      return static_cast(exponential(generator));
+    });
+  });
+}
+
+template
+struct ExponentialKernel {
+  void operator()(TensorIteratorBase& iter, double lambda, std::optional gen) {
+    exponential_kernel(iter, lambda, check_generator(gen));
+  }
+};
+
+// ================================================== Bernoulli =======================================================
+
+template
+void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG generator) {
+  AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
+  self.scalar_type(), "bernoulli_tensor_cpu_self_", [&] {
+    // See Note [Acquire lock when using random generators]
+    std::lock_guard lock(generator->mutex_);
+    using self_t = scalar_t;
+    auto p_cpu = p_.to(kCPU);
+    auto p = expand_inplace(self, p_cpu);
+    auto iter = TensorIteratorConfig()
+        .add_output(self)
+        .add_const_input(*p)
+        .check_all_same_dtype(false)
+        .build();
+    if (p->scalar_type() == kDouble) {
+      cpu_serial_kernel(iter, [&](const double p_val) -> self_t {
+        at::bernoulli_distribution bernoulli(p_val);
+        return static_cast(bernoulli(generator));
+      });
+    } else {
+      AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half,
+      p->scalar_type(), "bernoulli_tensor_cpu_p_", [&] {
+        using p_t = scalar_t;
+        cpu_serial_kernel(iter, [&](const p_t p_val) -> self_t {
+          at::bernoulli_distribution bernoulli(p_val);
+          return static_cast(bernoulli(generator));
+        });
+      });
+    }
+  });
+}
+
+template
+void bernoulli_kernel(const TensorBase &self, double p, RNG generator) {
+  AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half,
+  self.scalar_type(), "bernoulli_scalar_cpu_", [&] {
+    // See Note [Acquire lock when using random generators]
+    std::lock_guard lock(generator->mutex_);
+    auto iter = TensorIterator::borrowing_nullary_op(self);
+    cpu_serial_kernel(iter, [p, generator]() -> scalar_t {
+      at::bernoulli_distribution bernoulli(p);
+      return static_cast(bernoulli(generator));
+    });
+  });
+}
+
+template
+struct BernoulliKernel {
+  void operator()(const TensorBase &self, double p, std::optional gen) {
+    bernoulli_kernel(self, p, check_generator(gen));
+  }
+  void operator()(const TensorBase &self, const TensorBase &p_, std::optional gen) {
+    bernoulli_kernel(self, p_, check_generator(gen));
+  }
+};
+
+}}
diff --git a/shared/package-files/56/56ab690ca131b5388f0e1aba6e5727435770acb9a40b3d2e7464db2126024a21/base.h b/shared/package-files/56/56ab690ca131b5388f0e1aba6e5727435770acb9a40b3d2e7464db2126024a21/base.h
new file mode 100644
index 0000000000000000000000000000000000000000..c64f4e5a6c9e932cde6edb6a4851bc0789ce2544
--- /dev/null
+++ b/shared/package-files/56/56ab690ca131b5388f0e1aba6e5727435770acb9a40b3d2e7464db2126024a21/base.h
@@ -0,0 +1,53 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+struct CUevent_st;
+
+namespace torch::profiler::impl {
+
+// ----------------------------------------------------------------------------
+// -- Annotation --------------------------------------------------------------
+// ----------------------------------------------------------------------------
+using ProfilerEventStub = std::shared_ptr;
+using ProfilerVoidEventStub = std::shared_ptr;
+
+struct TORCH_API ProfilerStubs {
+  virtual void record(
+      c10::DeviceIndex* device,
+      ProfilerVoidEventStub* event,
+      int64_t* cpu_ns) const = 0;
+  virtual float elapsed(
+      const ProfilerVoidEventStub* event,
+      const ProfilerVoidEventStub* event2) const = 0;
+  virtual void mark(const char* name) const = 0;
+  virtual void rangePush(const char* name) const = 0;
+  virtual void rangePop() const = 0;
+  virtual bool enabled() const {
+    return false;
+  }
+  virtual void onEachDevice(std::function op) const = 0;
+  virtual void synchronize() const = 0;
+  virtual ~ProfilerStubs() = default;
+};
+
+TORCH_API void registerCUDAMethods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* cudaStubs();
+TORCH_API void registerITTMethods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* ittStubs();
+TORCH_API void registerPrivateUse1Methods(ProfilerStubs* stubs);
+TORCH_API const ProfilerStubs* privateuse1Stubs();
+
+using vulkan_id_t = strong::type<
+    int64_t,
+    struct _VulkanID,
+    strong::regular,
+    strong::convertible_to,
+    strong::hashable>;
+
+} // namespace torch::profiler::impl
diff --git a/shared/package-files/56/56ac62c0e9f06d80d06dcdb2583839970fe482d2655d6ba1cd285402c38dcce4/test_astype.cpython-311.pyc b/shared/package-files/56/56ac62c0e9f06d80d06dcdb2583839970fe482d2655d6ba1cd285402c38dcce4/test_astype.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a60e57977ee0743f315406a14efa3497b39c4da0
Binary files /dev/null and b/shared/package-files/56/56ac62c0e9f06d80d06dcdb2583839970fe482d2655d6ba1cd285402c38dcce4/test_astype.cpython-311.pyc differ
diff --git a/shared/package-files/56/56ad71247ae36ad40452280cb3194093caa8652ca9fd9ff41a2279cb90083088/beam.py b/shared/package-files/56/56ad71247ae36ad40452280cb3194093caa8652ca9fd9ff41a2279cb90083088/beam.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfdfc6d3594da6de44c7c42def3e3f5539cb988e
--- /dev/null
+++ b/shared/package-files/56/56ad71247ae36ad40452280cb3194093caa8652ca9fd9ff41a2279cb90083088/beam.py
@@ -0,0 +1,3903 @@
+"""
+This module can be used to solve 2D beam bending problems with
+singularity functions in mechanics.
+"""
+
+from sympy.core import S, Symbol, diff, symbols
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.function import (Derivative, Function)
+from sympy.core.mul import Mul
+from sympy.core.relational import Eq
+from sympy.core.sympify import sympify
+from sympy.solvers import linsolve
+from sympy.solvers.ode.ode import dsolve
+from sympy.solvers.solvers import solve
+from sympy.printing import sstr
+from sympy.functions import SingularityFunction, Piecewise, factorial
+from sympy.integrals import integrate
+from sympy.series import limit
+from sympy.plotting import plot, PlotGrid
+from sympy.geometry.entity import GeometryEntity
+from sympy.external import import_module
+from sympy.sets.sets import Interval
+from sympy.utilities.lambdify import lambdify
+from sympy.utilities.decorator import doctest_depends_on
+from sympy.utilities.iterables import iterable
+import warnings
+
+
+__doctest_requires__ = {
+    ('Beam.draw',
+     'Beam.plot_bending_moment',
+     'Beam.plot_deflection',
+     'Beam.plot_ild_moment',
+     'Beam.plot_ild_shear',
+     'Beam.plot_shear_force',
+     'Beam.plot_shear_stress',
+     'Beam.plot_slope'): ['matplotlib'],
+}
+
+
+numpy = import_module('numpy', import_kwargs={'fromlist':['arange']})
+
+
+class Beam:
+    """
+    A Beam is a structural element that is capable of withstanding load
+    primarily by resisting against bending. Beams are characterized by
+    their cross sectional profile(Second moment of area), their length
+    and their material.
+
+    .. note::
+       A consistent sign convention must be used while solving a beam
+       bending problem; the results will
+       automatically follow the chosen sign convention. However, the
+       chosen sign convention must respect the rule that, on the positive
+       side of beam's axis (in respect to current section), a loading force
+       giving positive shear yields a negative moment, as below (the
+       curved arrow shows the positive moment and rotation):
+
+    .. image:: allowed-sign-conventions.png
+
+    Examples
+    ========
+    There is a beam of length 4 meters. A constant distributed load of 6 N/m
+    is applied from half of the beam till the end. There are two simple supports
+    below the beam, one at the starting point and another at the ending point
+    of the beam. The deflection of the beam at the end is restricted.
+
+    Using the sign convention of downwards forces being positive.
+
+    >>> from sympy.physics.continuum_mechanics.beam import Beam
+    >>> from sympy import symbols, Piecewise
+    >>> E, I = symbols('E, I')
+    >>> R1, R2 = symbols('R1, R2')
+    >>> b = Beam(4, E, I)
+    >>> b.apply_load(R1, 0, -1)
+    >>> b.apply_load(6, 2, 0)
+    >>> b.apply_load(R2, 4, -1)
+    >>> b.bc_deflection = [(0, 0), (4, 0)]
+    >>> b.boundary_conditions
+    {'bending_moment': [], 'deflection': [(0, 0), (4, 0)], 'shear_force': [], 'slope': []}
+    >>> b.load
+    R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0)
+    >>> b.solve_for_reaction_loads(R1, R2)
+    >>> b.load
+    -3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1)
+    >>> b.shear_force()
+    3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0)
+    >>> b.bending_moment()
+    3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1)
+    >>> b.slope()
+    (-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I)
+    >>> b.deflection()
+    (7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I)
+    >>> b.deflection().rewrite(Piecewise)
+    (7*x - Piecewise((x**3, x >= 0), (0, True))/2
+         - 3*Piecewise(((x - 4)**3, x >= 4), (0, True))/2
+         + Piecewise(((x - 2)**4, x >= 2), (0, True))/4)/(E*I)
+
+    Calculate the support reactions for a fully symbolic beam of length L.
+    There are two simple supports below the beam, one at the starting point
+    and another at the ending point of the beam. The deflection of the beam
+    at the end is restricted. The beam is loaded with:
+
+    * a downward point load P1 applied at L/4
+    * an upward point load P2 applied at L/8
+    * a counterclockwise moment M1 applied at L/2
+    * a clockwise moment M2 applied at 3*L/4
+    * a distributed constant load q1, applied downward, starting from L/2
+      up to 3*L/4
+    * a distributed constant load q2, applied upward, starting from 3*L/4
+      up to L
+
+    No assumptions are needed for symbolic loads. However, defining a positive
+    length will help the algorithm to compute the solution.
+
+    >>> E, I = symbols('E, I')
+    >>> L = symbols("L", positive=True)
+    >>> P1, P2, M1, M2, q1, q2 = symbols("P1, P2, M1, M2, q1, q2")
+    >>> R1, R2 = symbols('R1, R2')
+    >>> b = Beam(L, E, I)
+    >>> b.apply_load(R1, 0, -1)
+    >>> b.apply_load(R2, L, -1)
+    >>> b.apply_load(P1, L/4, -1)
+    >>> b.apply_load(-P2, L/8, -1)
+    >>> b.apply_load(M1, L/2, -2)
+    >>> b.apply_load(-M2, 3*L/4, -2)
+    >>> b.apply_load(q1, L/2, 0, 3*L/4)
+    >>> b.apply_load(-q2, 3*L/4, 0, L)
+    >>> b.bc_deflection = [(0, 0), (L, 0)]
+    >>> b.solve_for_reaction_loads(R1, R2)
+    >>> print(b.reaction_loads[R1])
+    (-3*L**2*q1 + L**2*q2 - 24*L*P1 + 28*L*P2 - 32*M1 + 32*M2)/(32*L)
+    >>> print(b.reaction_loads[R2])
+    (-5*L**2*q1 + 7*L**2*q2 - 8*L*P1 + 4*L*P2 + 32*M1 - 32*M2)/(32*L)
+    """
+
+    def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C', ild_variable=Symbol('a')):
+        """Initializes the class.
+
+        Parameters
+        ==========
+
+        length : Sympifyable
+            A Symbol or value representing the Beam's length.
+
+        elastic_modulus : Sympifyable
+            A SymPy expression representing the Beam's Modulus of Elasticity.
+            It is a measure of the stiffness of the Beam material. It can
+            also be a continuous function of position along the beam.
+
+        second_moment : Sympifyable or Geometry object
+            Describes the cross-section of the beam via a SymPy expression
+            representing the Beam's second moment of area. It is a geometrical
+            property of an area which reflects how its points are distributed
+            with respect to its neutral axis. It can also be a continuous
+            function of position along the beam. Alternatively ``second_moment``
+            can be a shape object such as a ``Polygon`` from the geometry module
+            representing the shape of the cross-section of the beam. In such cases,
+            it is assumed that the x-axis of the shape object is aligned with the
+            bending axis of the beam. The second moment of area will be computed
+            from the shape object internally.
+
+        area : Symbol/float
+            Represents the cross-section area of beam
+
+        variable : Symbol, optional
+            A Symbol object that will be used as the variable along the beam
+            while representing the load, shear, moment, slope and deflection
+            curve. By default, it is set to ``Symbol('x')``.
+
+        base_char : String, optional
+            A String that will be used as base character to generate sequential
+            symbols for integration constants in cases where boundary conditions
+            are not sufficient to solve them.
+
+        ild_variable : Symbol, optional
+            A Symbol object that will be used as the variable specifying the
+            location of the moving load in ILD calculations. By default, it
+            is set to ``Symbol('a')``.
+        """
+        self.length = length
+        self.elastic_modulus = elastic_modulus
+        if isinstance(second_moment, GeometryEntity):
+            self.cross_section = second_moment
+        else:
+            self.cross_section = None
+            self.second_moment = second_moment
+        self.variable = variable
+        self.ild_variable = ild_variable
+        self._base_char = base_char
+        self._boundary_conditions = {'deflection': [], 'slope': [], 'bending_moment': [], 'shear_force': []}
+        self._load = 0
+        self.area = area
+        self._applied_supports = []
+        self._applied_rotation_hinges = []
+        self._applied_sliding_hinges = []
+        self._rotation_hinge_symbols = []
+        self._sliding_hinge_symbols = []
+        self._support_as_loads = []
+        self._applied_loads = []
+        self._reaction_loads = {}
+        self._ild_reactions = {}
+        self._ild_shear = 0
+        self._ild_moment = 0
+        # _original_load is a copy of _load equations with unsubstituted reaction
+        # forces. It is used for calculating reaction forces in case of I.L.D.
+        self._original_load = 0
+        self._joined_beam = False
+
+    def __str__(self):
+        shape_description = self._cross_section if self._cross_section else self._second_moment
+        str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description))
+        return str_sol
+
+    @property
+    def reaction_loads(self):
+        """ Returns the reaction forces in a dictionary."""
+        return self._reaction_loads
+
+    @property
+    def rotation_jumps(self):
+        """
+        Returns the value for the rotation jumps in rotation hinges in a dictionary.
+        The rotation jump is the rotation (in radian) in a rotation hinge. This can
+        be seen as a jump in the slope plot.
+        """
+        return self._rotation_jumps
+
+    @property
+    def deflection_jumps(self):
+        """
+        Returns the deflection jumps in sliding hinges in a dictionary.
+        The deflection jump is the deflection (in meters) in a sliding hinge.
+        This can be seen as a jump in the deflection plot.
+        """
+        return self._deflection_jumps
+
+    @property
+    def ild_shear(self):
+        """ Returns the I.L.D. shear equation."""
+        return self._ild_shear
+
+    @property
+    def ild_reactions(self):
+        """ Returns the I.L.D. reaction forces in a dictionary."""
+        return self._ild_reactions
+
+    @property
+    def ild_rotation_jumps(self):
+        """
+        Returns the I.L.D. rotation jumps in rotation hinges in a dictionary.
+        The rotation jump is the rotation (in radian) in a rotation hinge. This can
+        be seen as a jump in the slope plot.
+        """
+        return self._ild_rotations_jumps
+
+    @property
+    def ild_deflection_jumps(self):
+        """
+        Returns the I.L.D. deflection jumps in sliding hinges in a dictionary.
+        The deflection jump is the deflection (in meters) in a sliding hinge.
+        This can be seen as a jump in the deflection plot.
+        """
+        return self._ild_deflection_jumps
+
+    @property
+    def ild_moment(self):
+        """ Returns the I.L.D. moment equation."""
+        return self._ild_moment
+
+    @property
+    def length(self):
+        """Length of the Beam."""
+        return self._length
+
+    @length.setter
+    def length(self, l):
+        self._length = sympify(l)
+
+    @property
+    def area(self):
+        """Cross-sectional area of the Beam. """
+        return self._area
+
+    @area.setter
+    def area(self, a):
+        self._area = sympify(a)
+
+    @property
+    def variable(self):
+        """
+        A symbol that can be used as a variable along the length of the beam
+        while representing load distribution, shear force curve, bending
+        moment, slope curve and the deflection curve. By default, it is set
+        to ``Symbol('x')``, but this property is mutable.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I, A = symbols('E, I, A')
+        >>> x, y, z = symbols('x, y, z')
+        >>> b = Beam(4, E, I)
+        >>> b.variable
+        x
+        >>> b.variable = y
+        >>> b.variable
+        y
+        >>> b = Beam(4, E, I, A, z)
+        >>> b.variable
+        z
+        """
+        return self._variable
+
+    @variable.setter
+    def variable(self, v):
+        if isinstance(v, Symbol):
+            self._variable = v
+        else:
+            raise TypeError("""The variable should be a Symbol object.""")
+
+    @property
+    def elastic_modulus(self):
+        """Young's Modulus of the Beam. """
+        return self._elastic_modulus
+
+    @elastic_modulus.setter
+    def elastic_modulus(self, e):
+        self._elastic_modulus = sympify(e)
+
+    @property
+    def second_moment(self):
+        """Second moment of area of the Beam. """
+        return self._second_moment
+
+    @second_moment.setter
+    def second_moment(self, i):
+        self._cross_section = None
+        if isinstance(i, GeometryEntity):
+            raise ValueError("To update cross-section geometry use `cross_section` attribute")
+        else:
+            self._second_moment = sympify(i)
+
+    @property
+    def cross_section(self):
+        """Cross-section of the beam"""
+        return self._cross_section
+
+    @cross_section.setter
+    def cross_section(self, s):
+        if s:
+            self._second_moment = s.second_moment_of_area()[0]
+        self._cross_section = s
+
+    @property
+    def boundary_conditions(self):
+        """
+        Returns a dictionary of boundary conditions applied on the beam.
+        The dictionary has three keywords namely moment, slope and deflection.
+        The value of each keyword is a list of tuple, where each tuple
+        contains location and value of a boundary condition in the format
+        (location, value).
+
+        Examples
+        ========
+        There is a beam of length 4 meters. The bending moment at 0 should be 4
+        and at 4 it should be 0. The slope of the beam should be 1 at 0. The
+        deflection should be 2 at 0.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(4, E, I)
+        >>> b.bc_deflection = [(0, 2)]
+        >>> b.bc_slope = [(0, 1)]
+        >>> b.boundary_conditions
+        {'bending_moment': [], 'deflection': [(0, 2)], 'shear_force': [], 'slope': [(0, 1)]}
+
+        Here the deflection of the beam should be ``2`` at ``0``.
+        Similarly, the slope of the beam should be ``1`` at ``0``.
+        """
+        return self._boundary_conditions
+
+    @property
+    def bc_shear_force(self):
+        return self._boundary_conditions['shear_force']
+
+    @bc_shear_force.setter
+    def bc_shear_force(self, sf_bcs):
+        self._boundary_conditions['shear_force'] = sf_bcs
+
+    @property
+    def bc_bending_moment(self):
+        return self._boundary_conditions['bending_moment']
+
+    @bc_bending_moment.setter
+    def bc_bending_moment(self, bm_bcs):
+        self._boundary_conditions['bending_moment'] = bm_bcs
+
+    @property
+    def bc_slope(self):
+        return self._boundary_conditions['slope']
+
+    @bc_slope.setter
+    def bc_slope(self, s_bcs):
+        self._boundary_conditions['slope'] = s_bcs
+
+    @property
+    def bc_deflection(self):
+        return self._boundary_conditions['deflection']
+
+    @bc_deflection.setter
+    def bc_deflection(self, d_bcs):
+        self._boundary_conditions['deflection'] = d_bcs
+
+    def join(self, beam, via="fixed"):
+        """
+        This method joins two beams to make a new composite beam system.
+        Passed Beam class instance is attached to the right end of calling
+        object. This method can be used to form beams having Discontinuous
+        values of Elastic modulus or Second moment.
+
+        Parameters
+        ==========
+        beam : Beam class object
+            The Beam object which would be connected to the right of calling
+            object.
+        via : String
+            States the way two Beam object would get connected
+            - For axially fixed Beams, via="fixed"
+            - For Beams connected via rotation hinge, via="hinge"
+
+        Examples
+        ========
+        There is a cantilever beam of length 4 meters. For first 2 meters
+        its moment of inertia is `1.5*I` and `I` for the other end.
+        A pointload of magnitude 4 N is applied from the top at its free end.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b1 = Beam(2, E, 1.5*I)
+        >>> b2 = Beam(2, E, I)
+        >>> b = b1.join(b2, "fixed")
+        >>> b.apply_load(20, 4, -1)
+        >>> b.apply_load(R1, 0, -1)
+        >>> b.apply_load(R2, 0, -2)
+        >>> b.bc_slope = [(0, 0)]
+        >>> b.bc_deflection = [(0, 0)]
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.load
+        80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1)
+        >>> b.slope()
+        (-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0)
+        - 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I)
+        + 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I)
+        """
+        x = self.variable
+        E = self.elastic_modulus
+        new_length = self.length + beam.length
+        if self.elastic_modulus != beam.elastic_modulus:
+            raise NotImplementedError('Joining beams with different Elastic modulus is not implemented.')
+
+        if self.second_moment != beam.second_moment:
+            new_second_moment = Piecewise((self.second_moment, x<=self.length),
+                                    (beam.second_moment, x<=new_length))
+        else:
+            new_second_moment = self.second_moment
+
+        if via == "fixed":
+            new_beam = Beam(new_length, E, new_second_moment, x)
+            new_beam._joined_beam = True
+            return new_beam
+
+        if via == "hinge":
+            new_beam = Beam(new_length, E, new_second_moment, x)
+            new_beam._joined_beam = True
+            new_beam.apply_rotation_hinge(self.length)
+            return new_beam
+
+    def apply_support(self, loc, type="fixed"):
+        """
+        This method applies support to a particular beam object and returns
+        the symbol of the unknown reaction load(s).
+
+        Parameters
+        ==========
+        loc : Sympifyable
+            Location of point at which support is applied.
+        type : String
+            Determines type of Beam support applied. To apply support structure
+            with
+            - zero degree of freedom, type = "fixed"
+            - one degree of freedom, type = "pin"
+            - two degrees of freedom, type = "roller"
+
+        Returns
+        =======
+        Symbol or tuple of Symbol
+            The unknown reaction load as a symbol.
+            - Symbol(reaction_force) if type = "pin" or "roller"
+            - Symbol(reaction_force), Symbol(reaction_moment) if type = "fixed"
+
+        Examples
+        ========
+        There is a beam of length 20 meters. A moment of magnitude 100 Nm is
+        applied in the clockwise direction at the end of the beam. A pointload
+        of magnitude 8 N is applied from the top of the beam at a distance of 10 meters.
+        There is one fixed support at the start of the beam and a roller at the end.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(20, E, I)
+        >>> p0, m0 = b.apply_support(0, 'fixed')
+        >>> p1 = b.apply_support(20, 'roller')
+        >>> b.apply_load(-8, 10, -1)
+        >>> b.apply_load(100, 20, -2)
+        >>> b.solve_for_reaction_loads(p0, m0, p1)
+        >>> b.reaction_loads
+        {M_0: 20, R_0: -2, R_20: 10}
+        >>> b.reaction_loads[p0]
+        -2
+        >>> b.load
+        20*SingularityFunction(x, 0, -2) - 2*SingularityFunction(x, 0, -1)
+        - 8*SingularityFunction(x, 10, -1) + 100*SingularityFunction(x, 20, -2)
+        + 10*SingularityFunction(x, 20, -1)
+        """
+        loc = sympify(loc)
+
+        self._applied_supports.append((loc, type))
+        if type in ("pin", "roller"):
+            reaction_load = Symbol('R_'+str(loc))
+            self.apply_load(reaction_load, loc, -1)
+            self.bc_deflection.append((loc, 0))
+        else:
+            reaction_load = Symbol('R_'+str(loc))
+            reaction_moment = Symbol('M_'+str(loc))
+            self.apply_load(reaction_load, loc, -1)
+            self.apply_load(reaction_moment, loc, -2)
+            self.bc_deflection.append((loc, 0))
+            self.bc_slope.append((loc, 0))
+            self._support_as_loads.append((reaction_moment, loc, -2, None))
+
+        self._support_as_loads.append((reaction_load, loc, -1, None))
+
+        if type in ("pin", "roller"):
+            return reaction_load
+        else:
+            return reaction_load, reaction_moment
+
+    def _get_I(self, loc):
+        """
+        Helper function that returns the Second moment (I) at a location in the beam.
+        """
+        I = self.second_moment
+        if not isinstance(I, Piecewise):
+            return I
+        else:
+            for i in range(len(I.args)):
+                if loc <= I.args[i][1].args[1]:
+                    return I.args[i][0]
+
+    def apply_rotation_hinge(self, loc):
+        """
+        This method applies a rotation hinge at a single location on the beam.
+
+        Parameters
+        ----------
+        loc : Sympifyable
+            Location of point at which hinge is applied.
+
+        Returns
+        =======
+        Symbol
+            The unknown rotation jump multiplied by the elastic modulus and second moment as a symbol.
+
+        Examples
+        ========
+        There is a beam of length 15 meters. Pin supports are placed at distances
+        of 0 and 10 meters. There is a fixed support at the end. There are two rotation hinges
+        in the structure, one at 5 meters and one at 10 meters. A pointload of magnitude
+        10 kN is applied on the hinge at 5 meters. A distributed load of 5 kN works on
+        the structure from 10 meters to the end.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import Symbol
+        >>> E = Symbol('E')
+        >>> I = Symbol('I')
+        >>> b = Beam(15, E, I)
+        >>> r0 = b.apply_support(0, type='pin')
+        >>> r10 = b.apply_support(10, type='pin')
+        >>> r15, m15 = b.apply_support(15, type='fixed')
+        >>> p5 = b.apply_rotation_hinge(5)
+        >>> p12 = b.apply_rotation_hinge(12)
+        >>> b.apply_load(-10, 5, -1)
+        >>> b.apply_load(-5, 10, 0, 15)
+        >>> b.solve_for_reaction_loads(r0, r10, r15, m15)
+        >>> b.reaction_loads
+        {M_15: -75/2, R_0: 0, R_10: 40, R_15: -5}
+        >>> b.rotation_jumps
+        {P_12: -1875/(16*E*I), P_5: 9625/(24*E*I)}
+        >>> b.rotation_jumps[p12]
+        -1875/(16*E*I)
+        >>> b.bending_moment()
+        -9625*SingularityFunction(x, 5, -1)/24 + 10*SingularityFunction(x, 5, 1)
+        - 40*SingularityFunction(x, 10, 1) + 5*SingularityFunction(x, 10, 2)/2
+        + 1875*SingularityFunction(x, 12, -1)/16 + 75*SingularityFunction(x, 15, 0)/2
+        + 5*SingularityFunction(x, 15, 1) - 5*SingularityFunction(x, 15, 2)/2
+        """
+        loc = sympify(loc)
+        E = self.elastic_modulus
+        I = self._get_I(loc)
+
+        rotation_jump = Symbol('P_'+str(loc))
+        self._applied_rotation_hinges.append(loc)
+        self._rotation_hinge_symbols.append(rotation_jump)
+        self.apply_load(E * I * rotation_jump, loc, -3)
+        self.bc_bending_moment.append((loc, 0))
+        return rotation_jump
+
+    def apply_sliding_hinge(self, loc):
+        """
+        This method applies a sliding hinge at a single location on the beam.
+
+        Parameters
+        ----------
+        loc : Sympifyable
+            Location of point at which hinge is applied.
+
+        Returns
+        =======
+        Symbol
+            The unknown deflection jump multiplied by the elastic modulus and second moment as a symbol.
+
+        Examples
+        ========
+        There is a beam of length 13 meters. A fixed support is placed at the beginning.
+        There is a pin support at the end. There is a sliding hinge at a location of 8 meters.
+        A pointload of magnitude 10 kN is applied on the hinge at 5 meters.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> b = Beam(13, 20, 20)
+        >>> r0, m0 = b.apply_support(0, type="fixed")
+        >>> s8 = b.apply_sliding_hinge(8)
+        >>> r13 = b.apply_support(13, type="pin")
+        >>> b.apply_load(-10, 5, -1)
+        >>> b.solve_for_reaction_loads(r0, m0, r13)
+        >>> b.reaction_loads
+        {M_0: -50, R_0: 10, R_13: 0}
+        >>> b.deflection_jumps
+        {W_8: 85/24}
+        >>> b.deflection_jumps[s8]
+        85/24
+        >>> b.bending_moment()
+        50*SingularityFunction(x, 0, 0) - 10*SingularityFunction(x, 0, 1)
+        + 10*SingularityFunction(x, 5, 1) - 4250*SingularityFunction(x, 8, -2)/3
+        >>> b.deflection()
+        -SingularityFunction(x, 0, 2)/16 + SingularityFunction(x, 0, 3)/240
+        - SingularityFunction(x, 5, 3)/240 + 85*SingularityFunction(x, 8, 0)/24
+        """
+        loc = sympify(loc)
+        E = self.elastic_modulus
+        I = self._get_I(loc)
+
+        deflection_jump = Symbol('W_' + str(loc))
+        self._applied_sliding_hinges.append(loc)
+        self._sliding_hinge_symbols.append(deflection_jump)
+        self.apply_load(E * I * deflection_jump, loc, -4)
+        self.bc_shear_force.append((loc, 0))
+        return deflection_jump
+
+    def apply_load(self, value, start, order, end=None):
+        """
+        This method adds up the loads given to a particular beam object.
+
+        Parameters
+        ==========
+        value : Sympifyable
+            The value inserted should have the units [Force/(Distance**(n+1)]
+            where n is the order of applied load.
+            Units for applied loads:
+
+               - For moments, unit = kN*m
+               - For point loads, unit = kN
+               - For constant distributed load, unit = kN/m
+               - For ramp loads, unit = kN/m/m
+               - For parabolic ramp loads, unit = kN/m/m/m
+               - ... so on.
+
+        start : Sympifyable
+            The starting point of the applied load. For point moments and
+            point forces this is the location of application.
+        order : Integer
+            The order of the applied load.
+
+               - For moments, order = -2
+               - For point loads, order =-1
+               - For constant distributed load, order = 0
+               - For ramp loads, order = 1
+               - For parabolic ramp loads, order = 2
+               - ... so on.
+
+        end : Sympifyable, optional
+            An optional argument that can be used if the load has an end point
+            within the length of the beam.
+
+        Examples
+        ========
+        There is a beam of length 4 meters. A moment of magnitude 3 Nm is
+        applied in the clockwise direction at the starting point of the beam.
+        A point load of magnitude 4 N is applied from the top of the beam at
+        2 meters from the starting point and a parabolic ramp load of magnitude
+        2 N/m is applied below the beam starting from 2 meters to 3 meters
+        away from the starting point of the beam.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(4, E, I)
+        >>> b.apply_load(-3, 0, -2)
+        >>> b.apply_load(4, 2, -1)
+        >>> b.apply_load(-2, 2, 2, end=3)
+        >>> b.load
+        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
+
+        """
+        x = self.variable
+        value = sympify(value)
+        start = sympify(start)
+        order = sympify(order)
+
+        self._applied_loads.append((value, start, order, end))
+        self._load += value*SingularityFunction(x, start, order)
+        self._original_load += value*SingularityFunction(x, start, order)
+
+        if end:
+            # load has an end point within the length of the beam.
+            self._handle_end(x, value, start, order, end, type="apply")
+
+    def remove_load(self, value, start, order, end=None):
+        """
+        This method removes a particular load present on the beam object.
+        Returns a ValueError if the load passed as an argument is not
+        present on the beam.
+
+        Parameters
+        ==========
+        value : Sympifyable
+            The magnitude of an applied load.
+        start : Sympifyable
+            The starting point of the applied load. For point moments and
+            point forces this is the location of application.
+        order : Integer
+            The order of the applied load.
+            - For moments, order= -2
+            - For point loads, order=-1
+            - For constant distributed load, order=0
+            - For ramp loads, order=1
+            - For parabolic ramp loads, order=2
+            - ... so on.
+        end : Sympifyable, optional
+            An optional argument that can be used if the load has an end point
+            within the length of the beam.
+
+        Examples
+        ========
+        There is a beam of length 4 meters. A moment of magnitude 3 Nm is
+        applied in the clockwise direction at the starting point of the beam.
+        A pointload of magnitude 4 N is applied from the top of the beam at
+        2 meters from the starting point and a parabolic ramp load of magnitude
+        2 N/m is applied below the beam starting from 2 meters to 3 meters
+        away from the starting point of the beam.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(4, E, I)
+        >>> b.apply_load(-3, 0, -2)
+        >>> b.apply_load(4, 2, -1)
+        >>> b.apply_load(-2, 2, 2, end=3)
+        >>> b.load
+        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
+        >>> b.remove_load(-2, 2, 2, end = 3)
+        >>> b.load
+        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
+        """
+        x = self.variable
+        value = sympify(value)
+        start = sympify(start)
+        order = sympify(order)
+
+        if (value, start, order, end) in self._applied_loads:
+            self._load -= value*SingularityFunction(x, start, order)
+            self._original_load -= value*SingularityFunction(x, start, order)
+            self._applied_loads.remove((value, start, order, end))
+        else:
+            msg = "No such load distribution exists on the beam object."
+            raise ValueError(msg)
+
+        if end:
+            # load has an end point within the length of the beam.
+            self._handle_end(x, value, start, order, end, type="remove")
+
+    def _handle_end(self, x, value, start, order, end, type):
+        """
+        This functions handles the optional `end` value in the
+        `apply_load` and `remove_load` functions. When the value
+        of end is not NULL, this function will be executed.
+        """
+        if order.is_negative:
+            msg = ("If 'end' is provided the 'order' of the load cannot "
+                    "be negative, i.e. 'end' is only valid for distributed "
+                    "loads.")
+            raise ValueError(msg)
+        # NOTE : A Taylor series can be used to define the summation of
+        # singularity functions that subtract from the load past the end
+        # point such that it evaluates to zero past 'end'.
+        f = value*x**order
+
+        if type == "apply":
+            # iterating for "apply_load" method
+            for i in range(0, order + 1):
+                self._load -= (f.diff(x, i).subs(x, end - start) *
+                                SingularityFunction(x, end, i)/factorial(i))
+                self._original_load -= (f.diff(x, i).subs(x, end - start) *
+                                SingularityFunction(x, end, i)/factorial(i))
+        elif type == "remove":
+            # iterating for "remove_load" method
+            for i in range(0, order + 1):
+                self._load += (f.diff(x, i).subs(x, end - start) *
+                                SingularityFunction(x, end, i)/factorial(i))
+                self._original_load += (f.diff(x, i).subs(x, end - start) *
+                                SingularityFunction(x, end, i)/factorial(i))
+
+
+    @property
+    def load(self):
+        """
+        Returns a Singularity Function expression which represents
+        the load distribution curve of the Beam object.
+
+        Examples
+        ========
+        There is a beam of length 4 meters. A moment of magnitude 3 Nm is
+        applied in the clockwise direction at the starting point of the beam.
+        A point load of magnitude 4 N is applied from the top of the beam at
+        2 meters from the starting point and a parabolic ramp load of magnitude
+        2 N/m is applied below the beam starting from 3 meters away from the
+        starting point of the beam.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(4, E, I)
+        >>> b.apply_load(-3, 0, -2)
+        >>> b.apply_load(4, 2, -1)
+        >>> b.apply_load(-2, 3, 2)
+        >>> b.load
+        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2)
+        """
+        return self._load
+
+    @property
+    def applied_loads(self):
+        """
+        Returns a list of all loads applied on the beam object.
+        Each load in the list is a tuple of form (value, start, order, end).
+
+        Examples
+        ========
+        There is a beam of length 4 meters. A moment of magnitude 3 Nm is
+        applied in the clockwise direction at the starting point of the beam.
+        A pointload of magnitude 4 N is applied from the top of the beam at
+        2 meters from the starting point. Another pointload of magnitude 5 N
+        is applied at same position.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(4, E, I)
+        >>> b.apply_load(-3, 0, -2)
+        >>> b.apply_load(4, 2, -1)
+        >>> b.apply_load(5, 2, -1)
+        >>> b.load
+        -3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1)
+        >>> b.applied_loads
+        [(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)]
+        """
+        return self._applied_loads
+
+    def solve_for_reaction_loads(self, *reactions):
+        """
+        Solves for the reaction forces.
+
+        Examples
+        ========
+        There is a beam of length 30 meters. A moment of magnitude 120 Nm is
+        applied in the clockwise direction at the end of the beam. A pointload
+        of magnitude 8 N is applied from the top of the beam at the starting
+        point. There are two simple supports below the beam. One at the end
+        and another one at a distance of 10 meters from the start. The
+        deflection is restricted at both the supports.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b = Beam(30, E, I)
+        >>> b.apply_load(-8, 0, -1)
+        >>> b.apply_load(R1, 10, -1)  # Reaction force at x = 10
+        >>> b.apply_load(R2, 30, -1)  # Reaction force at x = 30
+        >>> b.apply_load(120, 30, -2)
+        >>> b.bc_deflection = [(10, 0), (30, 0)]
+        >>> b.load
+        R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1)
+            - 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2)
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.reaction_loads
+        {R1: 6, R2: 2}
+        >>> b.load
+        -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1)
+            + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
+        """
+
+        x = self.variable
+        l = self.length
+        C3 = Symbol('C3')
+        C4 = Symbol('C4')
+        rotation_jumps = tuple(self._rotation_hinge_symbols)
+        deflection_jumps = tuple(self._sliding_hinge_symbols)
+
+        shear_curve = limit(self.shear_force(), x, l)
+        moment_curve = limit(self.bending_moment(), x, l)
+
+        shear_force_eqs = []
+        bending_moment_eqs = []
+        slope_eqs = []
+        deflection_eqs = []
+
+        for position, value in self._boundary_conditions['shear_force']:
+            eqs = self.shear_force().subs(x, position) - value
+            new_eqs = sum(arg for arg in eqs.args if not any(num.is_infinite for num in arg.args))
+            shear_force_eqs.append(new_eqs)
+
+        for position, value in self._boundary_conditions['bending_moment']:
+            eqs = self.bending_moment().subs(x, position) - value
+            new_eqs = sum(arg for arg in eqs.args if not any(num.is_infinite for num in arg.args))
+            bending_moment_eqs.append(new_eqs)
+
+        slope_curve = integrate(self.bending_moment(), x) + C3
+        for position, value in self._boundary_conditions['slope']:
+            eqs = slope_curve.subs(x, position) - value
+            slope_eqs.append(eqs)
+
+        deflection_curve = integrate(slope_curve, x) + C4
+        for position, value in self._boundary_conditions['deflection']:
+            eqs = deflection_curve.subs(x, position) - value
+            deflection_eqs.append(eqs)
+
+        solution = list((linsolve([shear_curve, moment_curve] + shear_force_eqs + bending_moment_eqs + slope_eqs
+                            + deflection_eqs, (C3, C4) + reactions + rotation_jumps + deflection_jumps).args)[0])
+        reaction_index = 2+len(reactions)
+        rotation_index = reaction_index + len(rotation_jumps)
+        reaction_solution = solution[2:reaction_index]
+        rotation_solution = solution[reaction_index:rotation_index]
+        deflection_solution = solution[rotation_index:]
+
+        self._reaction_loads = dict(zip(reactions, reaction_solution))
+        self._rotation_jumps = dict(zip(rotation_jumps, rotation_solution))
+        self._deflection_jumps = dict(zip(deflection_jumps, deflection_solution))
+        self._load = self._load.subs(self._reaction_loads)
+        self._load = self._load.subs(self._rotation_jumps)
+        self._load = self._load.subs(self._deflection_jumps)
+
+    def shear_force(self):
+        """
+        Returns a Singularity Function expression which represents
+        the shear force curve of the Beam object.
+
+        Examples
+        ========
+        There is a beam of length 30 meters. A moment of magnitude 120 Nm is
+        applied in the clockwise direction at the end of the beam. A pointload
+        of magnitude 8 N is applied from the top of the beam at the starting
+        point. There are two simple supports below the beam. One at the end
+        and another one at a distance of 10 meters from the start. The
+        deflection is restricted at both the supports.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b = Beam(30, E, I)
+        >>> b.apply_load(-8, 0, -1)
+        >>> b.apply_load(R1, 10, -1)
+        >>> b.apply_load(R2, 30, -1)
+        >>> b.apply_load(120, 30, -2)
+        >>> b.bc_deflection = [(10, 0), (30, 0)]
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.shear_force()
+        8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
+        """
+        x = self.variable
+        return -integrate(self.load, x)
+
+    def max_shear_force(self):
+        """Returns maximum Shear force and its coordinate
+        in the Beam object."""
+        shear_curve = self.shear_force()
+        x = self.variable
+
+        terms = shear_curve.args
+        singularity = []        # Points at which shear function changes
+        for term in terms:
+            if isinstance(term, Mul):
+                term = term.args[-1]    # SingularityFunction in the term
+            singularity.append(term.args[1])
+        singularity = list(set(singularity))
+        singularity.sort()
+
+        intervals = []    # List of Intervals with discrete value of shear force
+        shear_values = []   # List of values of shear force in each interval
+        for i, s in enumerate(singularity):
+            if s == 0:
+                continue
+            try:
+                shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b = Beam(30, E, I)
+        >>> b.apply_load(-8, 0, -1)
+        >>> b.apply_load(R1, 10, -1)
+        >>> b.apply_load(R2, 30, -1)
+        >>> b.apply_load(120, 30, -2)
+        >>> b.bc_deflection = [(10, 0), (30, 0)]
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.bending_moment()
+        8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
+        """
+        x = self.variable
+        return integrate(self.shear_force(), x)
+
+    def max_bmoment(self):
+        """Returns maximum Shear force and its coordinate
+        in the Beam object."""
+        bending_curve = self.bending_moment()
+        x = self.variable
+
+        terms = bending_curve.args
+        singularity = []        # Points at which bending moment changes
+        for term in terms:
+            if isinstance(term, Mul):
+                term = term.args[-1]    # SingularityFunction in the term
+            singularity.append(term.args[1])
+        singularity = list(set(singularity))
+        singularity.sort()
+
+        intervals = []    # List of Intervals with discrete value of bending moment
+        moment_values = []   # List of values of bending moment in each interval
+        for i, s in enumerate(singularity):
+            if s == 0:
+                continue
+            try:
+                moment_slope = Piecewise(
+                    (float("nan"), x <= singularity[i - 1]),
+                    (self.shear_force().rewrite(Piecewise), x < s),
+                    (float("nan"), True))
+                points = solve(moment_slope, x)
+                val = []
+                for point in points:
+                    val.append(abs(bending_curve.subs(x, point)))
+                points.extend([singularity[i-1], s])
+                val += [abs(limit(bending_curve, x, singularity[i-1], '+')), abs(limit(bending_curve, x, s, '-'))]
+                max_moment = max(val)
+                moment_values.append(max_moment)
+                intervals.append(points[val.index(max_moment)])
+
+            # If bending moment in a particular Interval has zero or constant
+            # slope, then above block gives NotImplementedError as solve
+            # can't represent Interval solutions.
+            except NotImplementedError:
+                initial_moment = limit(bending_curve, x, singularity[i-1], '+')
+                final_moment = limit(bending_curve, x, s, '-')
+                # If bending_curve has a constant slope(it is a line).
+                if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment:
+                    moment_values.extend([initial_moment, final_moment])
+                    intervals.extend([singularity[i-1], s])
+                else:    # bending_curve has same value in whole Interval
+                    moment_values.append(final_moment)
+                    intervals.append(Interval(singularity[i-1], s))
+
+        moment_values = list(map(abs, moment_values))
+        maximum_moment = max(moment_values)
+        point = intervals[moment_values.index(maximum_moment)]
+        return (point, maximum_moment)
+
+    def point_cflexure(self):
+        """
+        Returns a Set of point(s) with zero bending moment and
+        where bending moment curve of the beam object changes
+        its sign from negative to positive or vice versa.
+
+        Examples
+        ========
+        There is is 10 meter long overhanging beam. There are
+        two simple supports below the beam. One at the start
+        and another one at a distance of 6 meters from the start.
+        Point loads of magnitude 10KN and 20KN are applied at
+        2 meters and 4 meters from start respectively. A Uniformly
+        distribute load of magnitude of magnitude 3KN/m is also
+        applied on top starting from 6 meters away from starting
+        point till end.
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> b = Beam(10, E, I)
+        >>> b.apply_load(-4, 0, -1)
+        >>> b.apply_load(-46, 6, -1)
+        >>> b.apply_load(10, 2, -1)
+        >>> b.apply_load(20, 4, -1)
+        >>> b.apply_load(3, 6, 0)
+        >>> b.point_cflexure()
+        [10/3]
+        """
+        #Removes the singularity functions of order < 0 from the bending moment equation used in this method
+        non_singular_bending_moment = sum(arg for arg in self.bending_moment().args if not arg.args[1].args[2] < 0)
+
+        # To restrict the range within length of the Beam
+        moment_curve = Piecewise((float("nan"), self.variable<=0),
+                (non_singular_bending_moment, self.variable>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b = Beam(30, E, I)
+        >>> b.apply_load(-8, 0, -1)
+        >>> b.apply_load(R1, 10, -1)
+        >>> b.apply_load(R2, 30, -1)
+        >>> b.apply_load(120, 30, -2)
+        >>> b.bc_deflection = [(10, 0), (30, 0)]
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.slope()
+        (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+            + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I)
+        """
+        x = self.variable
+        E = self.elastic_modulus
+        I = self.second_moment
+
+        if not self._boundary_conditions['slope']:
+            return diff(self.deflection(), x)
+        if isinstance(I, Piecewise) and self._joined_beam:
+            args = I.args
+            slope = 0
+            prev_slope = 0
+            prev_end = 0
+            for i in range(len(args)):
+                if i != 0:
+                    prev_end = args[i-1][1].args[1]
+                slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
+                if i != len(args) - 1:
+                    slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \
+                        (prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0)
+                else:
+                    slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0)
+                prev_slope = slope_value.subs(x, args[i][1].args[1])
+            return slope
+
+        C3 = Symbol('C3')
+        slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3
+
+        bc_eqs = []
+        for position, value in self._boundary_conditions['slope']:
+            eqs = slope_curve.subs(x, position) - value
+            bc_eqs.append(eqs)
+        constants = list(linsolve(bc_eqs, C3))
+        slope_curve = slope_curve.subs({C3: constants[0][0]})
+        return slope_curve
+
+    def deflection(self):
+        """
+        Returns a Singularity Function expression which represents
+        the elastic curve or deflection of the Beam object.
+
+        Examples
+        ========
+        There is a beam of length 30 meters. A moment of magnitude 120 Nm is
+        applied in the clockwise direction at the end of the beam. A pointload
+        of magnitude 8 N is applied from the top of the beam at the starting
+        point. There are two simple supports below the beam. One at the end
+        and another one at a distance of 10 meters from the start. The
+        deflection is restricted at both the supports.
+
+        Using the sign convention of upward forces and clockwise moment
+        being positive.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam
+        >>> from sympy import symbols
+        >>> E, I = symbols('E, I')
+        >>> R1, R2 = symbols('R1, R2')
+        >>> b = Beam(30, E, I)
+        >>> b.apply_load(-8, 0, -1)
+        >>> b.apply_load(R1, 10, -1)
+        >>> b.apply_load(R2, 30, -1)
+        >>> b.apply_load(120, 30, -2)
+        >>> b.bc_deflection = [(10, 0), (30, 0)]
+        >>> b.solve_for_reaction_loads(R1, R2)
+        >>> b.deflection()
+        (4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
+            + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
+        """
+        x = self.variable
+        E = self.elastic_modulus
+        I = self.second_moment
+        if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']:
+            if isinstance(I, Piecewise) and self._joined_beam:
+                args = I.args
+                prev_slope = 0
+                prev_def = 0
+                prev_end = 0
+                deflection = 0
+                for i in range(len(args)):
+                    if i != 0:
+                        prev_end = args[i-1][1].args[1]
+                    slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
+                    recent_segment_slope = prev_slope + slope_value
+                    deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
+                    if i != len(args) - 1:
+                        deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
+                            - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
+                    else:
+                        deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
+                    prev_slope = slope_value.subs(x, args[i][1].args[1])
+                    prev_def = deflection_value.subs(x, args[i][1].args[1])
+                return deflection
+            base_char = self._base_char
+            constants = symbols(base_char + '3:5')
+            return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1]
+        elif not self._boundary_conditions['deflection']:
+            base_char = self._base_char
+            constant = symbols(base_char + '4')
+            return integrate(self.slope(), x) + constant
+        elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']:
+            if isinstance(I, Piecewise) and self._joined_beam:
+                args = I.args
+                prev_slope = 0
+                prev_def = 0
+                prev_end = 0
+                deflection = 0
+                for i in range(len(args)):
+                    if i != 0:
+                        prev_end = args[i-1][1].args[1]
+                    slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
+                    recent_segment_slope = prev_slope + slope_value
+                    deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
+                    if i != len(args) - 1:
+                        deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
+                            - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
+                    else:
+                        deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
+                    prev_slope = slope_value.subs(x, args[i][1].args[1])
+                    prev_def = deflection_value.subs(x, args[i][1].args[1])
+                return deflection
+            base_char = self._base_char
+            C3, C4 = symbols(base_char + '3:5')    # Integration constants
+            slope_curve = -integrate(self.bending_moment(), x) + C3
+            deflection_curve = integrate(slope_curve, x) + C4
+            bc_eqs = []
+            for position, value in self._boundary_conditions['deflection']:
+                eqs = deflection_curve.subs(x, position) - value
+                bc_eqs.append(eqs)
+            constants = list(linsolve(bc_eqs, (C3, C4)))
+            deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]})
+            return S.One/(E*I)*deflection_curve
+
+        if isinstance(I, Piecewise) and self._joined_beam:
+            args = I.args
+            prev_slope = 0
+            prev_def = 0
+            prev_end = 0
+            deflection = 0
+            for i in range(len(args)):
+                if i != 0:
+                    prev_end = args[i-1][1].args[1]
+                slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
+                recent_segment_slope = prev_slope + slope_value
+                deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
+                if i != len(args) - 1:
+                    deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
+                        - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
+                else:
+                    deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
+                prev_slope = slope_value.subs(x, args[i][1].args[1])
+                prev_def = deflection_value.subs(x, args[i][1].args[1])
+            return deflection
+
+        C4 = Symbol('C4')
+        deflection_curve = integrate(self.slope(), x) + C4
+
+        bc_eqs = []
+        for position, value in self._boundary_conditions['deflection']:
+            eqs = deflection_curve.subs(x, position) - value
+            bc_eqs.append(eqs)
+
+        constants = list(linsolve(bc_eqs, C4))
+        deflection_curve = deflection_curve.subs({C4: constants[0][0]})
+        return deflection_curve
+
+    def max_deflection(self):
+        """
+        Returns point of max deflection and its corresponding deflection value
+        in a Beam object.
+        """
+
+        # To restrict the range within length of the Beam
+        slope_curve = Piecewise((float("nan"), self.variable<=0),
+                (self.slope(), self.variable>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6), 2)
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> b.plot_shear_stress()
+            Plot object containing:
+            [0]: cartesian line: 6875*SingularityFunction(x, 0, 0) - 2500*SingularityFunction(x, 2, 0)
+            - 5000*SingularityFunction(x, 4, 1) + 15625*SingularityFunction(x, 8, 0)
+            + 5000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
+        """
+
+        shear_stress = self.shear_stress()
+        x = self.variable
+        length = self.length
+
+        if subs is None:
+            subs = {}
+        for sym in shear_stress.atoms(Symbol):
+            if sym != x and sym not in subs:
+                raise ValueError('value of %s was not passed.' %sym)
+
+        if length in subs:
+            length = subs[length]
+
+        # Returns Plot of Shear Stress
+        return plot (shear_stress.subs(subs), (x, 0, length),
+        title='Shear Stress', xlabel=r'$\mathrm{x}$', ylabel=r'$\tau$',
+        line_color='r')
+
+
+    def plot_shear_force(self, subs=None):
+        """
+
+        Returns a plot for Shear force present in the Beam object.
+
+        Parameters
+        ==========
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 8 meters. A constant distributed load of 10 KN/m
+        is applied from half of the beam till the end. There are two simple supports
+        below the beam, one at the starting point and another at the ending point
+        of the beam. A pointload of magnitude 5 KN is also applied from top of the
+        beam, at a distance of 4 meters from the starting point.
+        Take E = 200 GPa and I = 400*(10**-6) meter**4.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6))
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> b.plot_shear_force()
+            Plot object containing:
+            [0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0)
+            - 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0)
+            + 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
+        """
+        shear_force = self.shear_force()
+        if subs is None:
+            subs = {}
+        for sym in shear_force.atoms(Symbol):
+            if sym == self.variable:
+                continue
+            if sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+        return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force',
+                xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g')
+
+    def plot_bending_moment(self, subs=None):
+        """
+
+        Returns a plot for Bending moment present in the Beam object.
+
+        Parameters
+        ==========
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 8 meters. A constant distributed load of 10 KN/m
+        is applied from half of the beam till the end. There are two simple supports
+        below the beam, one at the starting point and another at the ending point
+        of the beam. A pointload of magnitude 5 KN is also applied from top of the
+        beam, at a distance of 4 meters from the starting point.
+        Take E = 200 GPa and I = 400*(10**-6) meter**4.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6))
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> b.plot_bending_moment()
+            Plot object containing:
+            [0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1)
+            - 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1)
+            + 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0)
+        """
+        bending_moment = self.bending_moment()
+        if subs is None:
+            subs = {}
+        for sym in bending_moment.atoms(Symbol):
+            if sym == self.variable:
+                continue
+            if sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+        return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment',
+                xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b')
+
+    def plot_slope(self, subs=None):
+        """
+
+        Returns a plot for slope of deflection curve of the Beam object.
+
+        Parameters
+        ==========
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 8 meters. A constant distributed load of 10 KN/m
+        is applied from half of the beam till the end. There are two simple supports
+        below the beam, one at the starting point and another at the ending point
+        of the beam. A pointload of magnitude 5 KN is also applied from top of the
+        beam, at a distance of 4 meters from the starting point.
+        Take E = 200 GPa and I = 400*(10**-6) meter**4.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6))
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> b.plot_slope()
+            Plot object containing:
+            [0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2)
+            + 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2)
+            - 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0)
+        """
+        slope = self.slope()
+        if subs is None:
+            subs = {}
+        for sym in slope.atoms(Symbol):
+            if sym == self.variable:
+                continue
+            if sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+        return plot(slope.subs(subs), (self.variable, 0, length), title='Slope',
+                xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m')
+
+    def plot_deflection(self, subs=None):
+        """
+
+        Returns a plot for deflection curve of the Beam object.
+
+        Parameters
+        ==========
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 8 meters. A constant distributed load of 10 KN/m
+        is applied from half of the beam till the end. There are two simple supports
+        below the beam, one at the starting point and another at the ending point
+        of the beam. A pointload of magnitude 5 KN is also applied from top of the
+        beam, at a distance of 4 meters from the starting point.
+        Take E = 200 GPa and I = 400*(10**-6) meter**4.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6))
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> b.plot_deflection()
+            Plot object containing:
+            [0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3)
+            + 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4)
+            - 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4)
+            for x over (0.0, 8.0)
+        """
+        deflection = self.deflection()
+        if subs is None:
+            subs = {}
+        for sym in deflection.atoms(Symbol):
+            if sym == self.variable:
+                continue
+            if sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+        return plot(deflection.subs(subs), (self.variable, 0, length),
+                    title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
+                    line_color='r')
+
+
+    def plot_loading_results(self, subs=None):
+        """
+        Returns a subplot of Shear Force, Bending Moment,
+        Slope and Deflection of the Beam object.
+
+        Parameters
+        ==========
+
+        subs : dictionary
+               Python dictionary containing Symbols as key and their
+               corresponding values.
+
+        Examples
+        ========
+
+        There is a beam of length 8 meters. A constant distributed load of 10 KN/m
+        is applied from half of the beam till the end. There are two simple supports
+        below the beam, one at the starting point and another at the ending point
+        of the beam. A pointload of magnitude 5 KN is also applied from top of the
+        beam, at a distance of 4 meters from the starting point.
+        Take E = 200 GPa and I = 400*(10**-6) meter**4.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> R1, R2 = symbols('R1, R2')
+            >>> b = Beam(8, 200*(10**9), 400*(10**-6))
+            >>> b.apply_load(5000, 2, -1)
+            >>> b.apply_load(R1, 0, -1)
+            >>> b.apply_load(R2, 8, -1)
+            >>> b.apply_load(10000, 4, 0, end=8)
+            >>> b.bc_deflection = [(0, 0), (8, 0)]
+            >>> b.solve_for_reaction_loads(R1, R2)
+            >>> axes = b.plot_loading_results()
+        """
+        length = self.length
+        variable = self.variable
+        if subs is None:
+            subs = {}
+        for sym in self.deflection().atoms(Symbol):
+            if sym == self.variable:
+                continue
+            if sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if length in subs:
+            length = subs[length]
+        ax1 = plot(self.shear_force().subs(subs), (variable, 0, length),
+                   title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$',
+                   line_color='g', show=False)
+        ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length),
+                   title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$',
+                   line_color='b', show=False)
+        ax3 = plot(self.slope().subs(subs), (variable, 0, length),
+                   title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$',
+                   line_color='m', show=False)
+        ax4 = plot(self.deflection().subs(subs), (variable, 0, length),
+                   title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
+                   line_color='r', show=False)
+
+        return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
+
+    def _solve_for_ild_equations(self, value):
+        """
+
+        Helper function for I.L.D. It takes the unsubstituted
+        copy of the load equation and uses it to calculate shear force and bending
+        moment equations.
+        """
+        x = self.variable
+        a = self.ild_variable
+        load = self._load + value * SingularityFunction(x, a, -1)
+        shear_force = -integrate(load, x)
+        bending_moment = integrate(shear_force, x)
+
+        return shear_force, bending_moment
+
+    def solve_for_ild_reactions(self, value, *reactions):
+        """
+
+        Determines the Influence Line Diagram equations for reaction
+        forces under the effect of a moving load.
+
+        Parameters
+        ==========
+        value : Integer
+            Magnitude of moving load
+        reactions :
+            The reaction forces applied on the beam.
+
+        Warning
+        =======
+        This method creates equations that can give incorrect results when
+        substituting a = 0 or a = l, with l the length of the beam.
+
+        Examples
+        ========
+
+        There is a beam of length 10 meters. There are two simple supports
+        below the beam, one at the starting point and another at the ending
+        point of the beam. Calculate the I.L.D. equations for reaction forces
+        under the effect of a moving load of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_10 = symbols('R_0, R_10')
+            >>> b = Beam(10, E, I)
+            >>> p0 = b.apply_support(0, 'pin')
+            >>> p10 = b.apply_support(10, 'roller')
+            >>> b.solve_for_ild_reactions(1,R_0,R_10)
+            >>> b.ild_reactions
+            {R_0: -SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/10 - SingularityFunction(a, 10, 1)/10,
+            R_10: -SingularityFunction(a, 0, 1)/10 + SingularityFunction(a, 10, 0) + SingularityFunction(a, 10, 1)/10}
+
+        """
+        shear_force, bending_moment = self._solve_for_ild_equations(value)
+        x = self.variable
+        l = self.length
+        a = self.ild_variable
+
+        rotation_jumps = tuple(self._rotation_hinge_symbols)
+        deflection_jumps = tuple(self._sliding_hinge_symbols)
+
+        C3 = Symbol('C3')
+        C4 = Symbol('C4')
+
+        shear_curve = limit(shear_force, x, l) - value*(SingularityFunction(a, 0, 0) - SingularityFunction(a, l, 0))
+        moment_curve = (limit(bending_moment, x, l) - value * (l * SingularityFunction(a, 0, 0)
+                                                               - SingularityFunction(a, 0, 1)
+                                                               + SingularityFunction(a, l, 1)))
+
+        shear_force_eqs = []
+        bending_moment_eqs = []
+        slope_eqs = []
+        deflection_eqs = []
+
+        for position, val in self._boundary_conditions['shear_force']:
+            eqs = self.shear_force().subs(x, position) - val
+            eqs_without_inf = sum(arg for arg in eqs.args if not any(num.is_infinite for num in arg.args))
+            shear_sinc = value * (SingularityFunction(- a, - position, 0) - SingularityFunction(-a, 0, 0))
+            eqs_with_shear_sinc = eqs_without_inf - shear_sinc
+            shear_force_eqs.append(eqs_with_shear_sinc)
+
+        for position, val in self._boundary_conditions['bending_moment']:
+            eqs = self.bending_moment().subs(x, position) - val
+            eqs_without_inf = sum(arg for arg in eqs.args if not any(num.is_infinite for num in arg.args))
+            moment_sinc = value * (position * SingularityFunction(a, 0, 0)
+                                   - SingularityFunction(a, 0, 1) + SingularityFunction(a, position, 1))
+            eqs_with_moment_sinc = eqs_without_inf - moment_sinc
+            bending_moment_eqs.append(eqs_with_moment_sinc)
+
+        slope_curve = integrate(bending_moment, x) + C3
+        for position, val in self._boundary_conditions['slope']:
+            eqs = slope_curve.subs(x, position) - val + value * (SingularityFunction(-a, 0, 1) + position * SingularityFunction(-a, 0, 0))**2 / 2
+            slope_eqs.append(eqs)
+
+        deflection_curve = integrate(slope_curve, x) + C4
+        for position, val in self._boundary_conditions['deflection']:
+            eqs = deflection_curve.subs(x, position) - val + value * (SingularityFunction(-a, 0, 1) + position * SingularityFunction(-a, 0, 0)) ** 3 / 6
+            deflection_eqs.append(eqs)
+
+        solution = list((linsolve([shear_curve, moment_curve] + shear_force_eqs + bending_moment_eqs + slope_eqs
+                                  + deflection_eqs, (C3, C4) + reactions + rotation_jumps + deflection_jumps).args)[0])
+
+        reaction_index = 2 + len(reactions)
+        rotation_index = reaction_index + len(rotation_jumps)
+        reaction_solution = solution[2:reaction_index]
+        rotation_solution = solution[reaction_index:rotation_index]
+        deflection_solution = solution[rotation_index:]
+
+        self._ild_reactions = dict(zip(reactions, reaction_solution))
+        self._ild_rotations_jumps = dict(zip(rotation_jumps, rotation_solution))
+        self._ild_deflection_jumps = dict(zip(deflection_jumps, deflection_solution))
+
+    def plot_ild_reactions(self, subs=None):
+        """
+
+        Plots the Influence Line Diagram of Reaction Forces
+        under the effect of a moving load. This function
+        should be called after calling solve_for_ild_reactions().
+
+        Parameters
+        ==========
+
+        subs : dictionary
+               Python dictionary containing Symbols as key and their
+               corresponding values.
+
+        Warning
+        =======
+        The values for a = 0 and a = l, with l the length of the beam, in
+        the plot can be incorrect.
+
+        Examples
+        ========
+
+        There is a beam of length 10 meters. A point load of magnitude 5KN
+        is also applied from top of the beam, at a distance of 4 meters
+        from the starting point. There are two simple supports below the
+        beam, located at the starting point and at a distance of 7 meters
+        from the starting point. Plot the I.L.D. equations for reactions
+        at both support points under the effect of a moving load
+        of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_7 = symbols('R_0, R_7')
+            >>> b = Beam(10, E, I)
+            >>> p0 = b.apply_support(0, 'roller')
+            >>> p7 = b.apply_support(7, 'roller')
+            >>> b.apply_load(5,4,-1)
+            >>> b.solve_for_ild_reactions(1,R_0,R_7)
+            >>> b.ild_reactions
+            {R_0: -SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/7
+            - 3*SingularityFunction(a, 10, 0)/7  - SingularityFunction(a, 10, 1)/7 - 15/7,
+            R_7: -SingularityFunction(a, 0, 1)/7 + 10*SingularityFunction(a, 10, 0)/7 + SingularityFunction(a, 10, 1)/7 - 20/7}
+            >>> b.plot_ild_reactions()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: -SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/7
+            - 3*SingularityFunction(a, 10, 0)/7 - SingularityFunction(a, 10, 1)/7 - 15/7 for a over (0.0, 10.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -SingularityFunction(a, 0, 1)/7 + 10*SingularityFunction(a, 10, 0)/7
+            + SingularityFunction(a, 10, 1)/7 - 20/7 for a over (0.0, 10.0)
+
+        """
+        if not self._ild_reactions:
+            raise ValueError("I.L.D. reaction equations not found. Please use solve_for_ild_reactions() to generate the I.L.D. reaction equations.")
+
+        a = self.ild_variable
+        ildplots = []
+
+        if subs is None:
+            subs = {}
+
+        for reaction in self._ild_reactions:
+            for sym in self._ild_reactions[reaction].atoms(Symbol):
+                if sym != a and sym not in subs:
+                    raise ValueError('Value of %s was not passed.' %sym)
+
+        for sym in self._length.atoms(Symbol):
+            if sym != a and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+
+        for reaction in self._ild_reactions:
+            ildplots.append(plot(self._ild_reactions[reaction].subs(subs),
+            (a, 0, self._length.subs(subs)), title='I.L.D. for Reactions',
+            xlabel=a, ylabel=reaction, line_color='blue', show=False))
+
+        return PlotGrid(len(ildplots), 1, *ildplots)
+
+    def solve_for_ild_shear(self, distance, value, *reactions):
+        """
+
+        Determines the Influence Line Diagram equations for shear at a
+        specified point under the effect of a moving load.
+
+        Parameters
+        ==========
+        distance : Integer
+            Distance of the point from the start of the beam
+            for which equations are to be determined
+        value : Integer
+            Magnitude of moving load
+        reactions :
+            The reaction forces applied on the beam.
+
+        Warning
+        =======
+        This method creates equations that can give incorrect results when
+        substituting a = 0 or a = l, with l the length of the beam.
+
+        Examples
+        ========
+
+        There is a beam of length 12 meters. There are two simple supports
+        below the beam, one at the starting point and another at a distance
+        of 8 meters. Calculate the I.L.D. equations for Shear at a distance
+        of 4 meters under the effect of a moving load of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_8 = symbols('R_0, R_8')
+            >>> b = Beam(12, E, I)
+            >>> p0 = b.apply_support(0, 'roller')
+            >>> p8 = b.apply_support(8, 'roller')
+            >>> b.solve_for_ild_reactions(1, R_0, R_8)
+            >>> b.solve_for_ild_shear(4, 1, R_0, R_8)
+            >>> b.ild_shear
+            -(-SingularityFunction(a, 0, 0) + SingularityFunction(a, 12, 0) + 2)*SingularityFunction(a, 4, 0)
+            - SingularityFunction(-a, 0, 0) - SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/8
+            + SingularityFunction(a, 12, 0)/2 - SingularityFunction(a, 12, 1)/8 + 1
+
+        """
+
+        x = self.variable
+        l = self.length
+        a = self.ild_variable
+
+        shear_force, _ = self._solve_for_ild_equations(value)
+
+        shear_curve1 = value - limit(shear_force, x, distance)
+        shear_curve2 = (limit(shear_force, x, l) - limit(shear_force, x, distance)) - value
+
+        for reaction in reactions:
+            shear_curve1 = shear_curve1.subs(reaction,self._ild_reactions[reaction])
+            shear_curve2 = shear_curve2.subs(reaction,self._ild_reactions[reaction])
+
+        shear_eq = (shear_curve1 - (shear_curve1 - shear_curve2) * SingularityFunction(a, distance, 0)
+                    - value * SingularityFunction(-a, 0, 0) + value * SingularityFunction(a, l, 0))
+
+        self._ild_shear = shear_eq
+
+    def plot_ild_shear(self,subs=None):
+        """
+
+        Plots the Influence Line Diagram for Shear under the effect
+        of a moving load. This function should be called after
+        calling solve_for_ild_shear().
+
+        Parameters
+        ==========
+
+        subs : dictionary
+               Python dictionary containing Symbols as key and their
+               corresponding values.
+
+        Warning
+        =======
+        The values for a = 0 and a = l, with l the length of the beam, in
+        the plot can be incorrect.
+
+        Examples
+        ========
+
+        There is a beam of length 12 meters. There are two simple supports
+        below the beam, one at the starting point and another at a distance
+        of 8 meters. Plot the I.L.D. for Shear at a distance
+        of 4 meters under the effect of a moving load of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_8 = symbols('R_0, R_8')
+            >>> b = Beam(12, E, I)
+            >>> p0 = b.apply_support(0, 'roller')
+            >>> p8 = b.apply_support(8, 'roller')
+            >>> b.solve_for_ild_reactions(1, R_0, R_8)
+            >>> b.solve_for_ild_shear(4, 1, R_0, R_8)
+            >>> b.ild_shear
+            -(-SingularityFunction(a, 0, 0) + SingularityFunction(a, 12, 0) + 2)*SingularityFunction(a, 4, 0)
+            - SingularityFunction(-a, 0, 0) - SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/8
+            + SingularityFunction(a, 12, 0)/2 - SingularityFunction(a, 12, 1)/8 + 1
+            >>> b.plot_ild_shear()
+            Plot object containing:
+            [0]: cartesian line: -(-SingularityFunction(a, 0, 0) + SingularityFunction(a, 12, 0) + 2)*SingularityFunction(a, 4, 0)
+            - SingularityFunction(-a, 0, 0) - SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/8
+            + SingularityFunction(a, 12, 0)/2 - SingularityFunction(a, 12, 1)/8 + 1 for a over (0.0, 12.0)
+
+        """
+
+        if not self._ild_shear:
+            raise ValueError("I.L.D. shear equation not found. Please use solve_for_ild_shear() to generate the I.L.D. shear equations.")
+
+        l = self._length
+        a = self.ild_variable
+
+        if subs is None:
+            subs = {}
+
+        for sym in self._ild_shear.atoms(Symbol):
+            if sym != a and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+
+        for sym in self._length.atoms(Symbol):
+            if sym != a and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+
+        return plot(self._ild_shear.subs(subs), (a, 0, l),  title='I.L.D. for Shear',
+               xlabel=r'$\mathrm{a}$', ylabel=r'$\mathrm{V}$', line_color='blue',show=True)
+
+    def solve_for_ild_moment(self, distance, value, *reactions):
+        """
+
+        Determines the Influence Line Diagram equations for moment at a
+        specified point under the effect of a moving load.
+
+        Parameters
+        ==========
+        distance : Integer
+            Distance of the point from the start of the beam
+            for which equations are to be determined
+        value : Integer
+            Magnitude of moving load
+        reactions :
+            The reaction forces applied on the beam.
+
+        Warning
+        =======
+        This method creates equations that can give incorrect results when
+        substituting a = 0 or a = l, with l the length of the beam.
+
+        Examples
+        ========
+
+        There is a beam of length 12 meters. There are two simple supports
+        below the beam, one at the starting point and another at a distance
+        of 8 meters. Calculate the I.L.D. equations for Moment at a distance
+        of 4 meters under the effect of a moving load of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_8 = symbols('R_0, R_8')
+            >>> b = Beam(12, E, I)
+            >>> p0 = b.apply_support(0, 'roller')
+            >>> p8 = b.apply_support(8, 'roller')
+            >>> b.solve_for_ild_reactions(1, R_0, R_8)
+            >>> b.solve_for_ild_moment(4, 1, R_0, R_8)
+            >>> b.ild_moment
+            -(4*SingularityFunction(a, 0, 0) - SingularityFunction(a, 0, 1) + SingularityFunction(a, 4, 1))*SingularityFunction(a, 4, 0)
+            - SingularityFunction(a, 0, 1)/2 + SingularityFunction(a, 4, 1) - 2*SingularityFunction(a, 12, 0)
+            - SingularityFunction(a, 12, 1)/2
+
+        """
+
+        x = self.variable
+        l = self.length
+        a = self.ild_variable
+
+        _, moment = self._solve_for_ild_equations(value)
+
+        moment_curve1 = value*(distance * SingularityFunction(a, 0, 0) - SingularityFunction(a, 0, 1)
+                               + SingularityFunction(a, distance, 1)) - limit(moment, x, distance)
+        moment_curve2 = (limit(moment, x, l)-limit(moment, x, distance)
+                         - value * (l * SingularityFunction(a, 0, 0) - SingularityFunction(a, 0, 1)
+                                    + SingularityFunction(a, l, 1)))
+
+        for reaction in reactions:
+            moment_curve1 = moment_curve1.subs(reaction, self._ild_reactions[reaction])
+            moment_curve2 = moment_curve2.subs(reaction, self._ild_reactions[reaction])
+
+        moment_eq = moment_curve1 - (moment_curve1 - moment_curve2) * SingularityFunction(a, distance, 0)
+
+        self._ild_moment = moment_eq
+
+    def plot_ild_moment(self,subs=None):
+        """
+
+        Plots the Influence Line Diagram for Moment under the effect
+        of a moving load. This function should be called after
+        calling solve_for_ild_moment().
+
+        Parameters
+        ==========
+
+        subs : dictionary
+               Python dictionary containing Symbols as key and their
+               corresponding values.
+
+        Warning
+        =======
+        The values for a = 0 and a = l, with l the length of the beam, in
+        the plot can be incorrect.
+
+        Examples
+        ========
+
+        There is a beam of length 12 meters. There are two simple supports
+        below the beam, one at the starting point and another at a distance
+        of 8 meters. Plot the I.L.D. for Moment at a distance
+        of 4 meters under the effect of a moving load of magnitude 1kN.
+
+        Using the sign convention of downwards forces being positive.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy import symbols
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> E, I = symbols('E, I')
+            >>> R_0, R_8 = symbols('R_0, R_8')
+            >>> b = Beam(12, E, I)
+            >>> p0 = b.apply_support(0, 'roller')
+            >>> p8 = b.apply_support(8, 'roller')
+            >>> b.solve_for_ild_reactions(1, R_0, R_8)
+            >>> b.solve_for_ild_moment(4, 1, R_0, R_8)
+            >>> b.ild_moment
+            -(4*SingularityFunction(a, 0, 0) - SingularityFunction(a, 0, 1) + SingularityFunction(a, 4, 1))*SingularityFunction(a, 4, 0)
+            - SingularityFunction(a, 0, 1)/2 + SingularityFunction(a, 4, 1) - 2*SingularityFunction(a, 12, 0)
+            - SingularityFunction(a, 12, 1)/2
+            >>> b.plot_ild_moment()
+            Plot object containing:
+            [0]: cartesian line: -(4*SingularityFunction(a, 0, 0) - SingularityFunction(a, 0, 1)
+            + SingularityFunction(a, 4, 1))*SingularityFunction(a, 4, 0) - SingularityFunction(a, 0, 1)/2
+            + SingularityFunction(a, 4, 1) - 2*SingularityFunction(a, 12, 0) - SingularityFunction(a, 12, 1)/2 for a over (0.0, 12.0)
+
+        """
+
+        if not self._ild_moment:
+            raise ValueError("I.L.D. moment equation not found. Please use solve_for_ild_moment() to generate the I.L.D. moment equations.")
+
+        a = self.ild_variable
+
+        if subs is None:
+            subs = {}
+
+        for sym in self._ild_moment.atoms(Symbol):
+            if sym != a and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+
+        for sym in self._length.atoms(Symbol):
+            if sym != a and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        return plot(self._ild_moment.subs(subs), (a, 0, self._length), title='I.L.D. for Moment',
+               xlabel=r'$\mathrm{a}$', ylabel=r'$\mathrm{M}$', line_color='blue', show=True)
+
+    @doctest_depends_on(modules=('numpy',))
+    def draw(self, pictorial=True):
+        """
+        Returns a plot object representing the beam diagram of the beam.
+        In particular, the diagram might include:
+
+        * the beam.
+        * vertical black arrows represent point loads and support reaction
+          forces (the latter if they have been added with the ``apply_load``
+          method).
+        * circular arrows represent moments.
+        * shaded areas represent distributed loads.
+        * the support, if ``apply_support`` has been executed.
+        * if a composite beam has been created with the ``join`` method and
+          a hinge has been specified, it will be shown with a white disc.
+
+        The diagram shows positive loads on the upper side of the beam,
+        and negative loads on the lower side. If two or more distributed
+        loads acts along the same direction over the same region, the
+        function will add them up together.
+
+        .. note::
+            The user must be careful while entering load values.
+            The draw function assumes a sign convention which is used
+            for plotting loads.
+            Given a right handed coordinate system with XYZ coordinates,
+            the beam's length is assumed to be along the positive X axis.
+            The draw function recognizes positive loads(with n>-2) as loads
+            acting along negative Y direction and positive moments acting
+            along positive Z direction.
+
+        Parameters
+        ==========
+
+        pictorial: Boolean (default=True)
+            Setting ``pictorial=True`` would simply create a pictorial (scaled)
+            view of the beam diagram. On the other hand, ``pictorial=False``
+            would create a beam diagram with the exact dimensions on the plot.
+
+        Examples
+        ========
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam
+            >>> from sympy import symbols
+            >>> P1, P2, M = symbols('P1, P2, M')
+            >>> E, I = symbols('E, I')
+            >>> b = Beam(50, 20, 30)
+            >>> b.apply_load(-10, 2, -1)
+            >>> b.apply_load(15, 26, -1)
+            >>> b.apply_load(P1, 10, -1)
+            >>> b.apply_load(-P2, 40, -1)
+            >>> b.apply_load(90, 5, 0, 23)
+            >>> b.apply_load(10, 30, 1, 50)
+            >>> b.apply_load(M, 15, -2)
+            >>> b.apply_load(-M, 30, -2)
+            >>> p50 = b.apply_support(50, "pin")
+            >>> p0, m0 = b.apply_support(0, "fixed")
+            >>> p20 = b.apply_support(20, "roller")
+            >>> p = b.draw()  # doctest: +SKIP
+            >>> p  # doctest: +ELLIPSIS,+SKIP
+            Plot object containing:
+            [0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0)
+            + SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0)
+            - SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0)
+            [1]: cartesian line: 5 for x over (0.0, 50.0)
+            ...
+            >>> p.show() # doctest: +SKIP
+
+        """
+        if not numpy:
+            raise ImportError("To use this function numpy module is required")
+
+        loads = list(set(self.applied_loads) - set(self._support_as_loads))
+        if (not pictorial) and any((len(l[0].free_symbols) > 0) and (l[2] >= 0) for l in loads):
+            raise ValueError("`pictorial=False` requires numerical "
+                "distributed loads. Instead, symbolic loads were found. "
+                "Cannot continue.")
+
+        x = self.variable
+
+        # checking whether length is an expression in terms of any Symbol.
+        if isinstance(self.length, Expr):
+            l = list(self.length.atoms(Symbol))
+            # assigning every Symbol a default value of 10
+            l = dict.fromkeys(l, 10)
+            length = self.length.subs(l)
+        else:
+            l = {}
+            length = self.length
+        height = length/10
+
+        rectangles = []
+        rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"})
+        annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l)
+        support_markers, support_rectangles = self._draw_supports(length, l)
+
+        rectangles += support_rectangles
+        markers += support_markers
+
+        for loc in self._applied_rotation_hinges:
+            ratio = loc / self.length
+            x_pos = float(ratio) * length
+            markers += [{'args':[[x_pos], [height / 2]], 'marker':'o', 'markersize':6, 'color':"white"}]
+
+        for loc in self._applied_sliding_hinges:
+            ratio = loc / self.length
+            x_pos = float(ratio) * length
+            markers += [{'args': [[x_pos], [height / 2]], 'marker':'|', 'markersize':12, 'color':"white"}]
+
+        ylim = (-length, 1.25*length)
+        if fill:
+            # when distributed loads are presents, they might get clipped out
+            # in the figure by the ylim settings.
+            # It might be necessary to compute new limits.
+            _min = min(min(fill["y2"]), min(r["xy"][1] for r in rectangles))
+            _max = max(max(fill["y1"]), max(r["xy"][1] for r in rectangles))
+            if (_min < ylim[0]) or (_max > ylim[1]):
+                offset = abs(_max - _min) * 0.1
+                ylim = (_min - offset, _max + offset)
+
+        sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length),
+            xlim=(-height, length + height), ylim=ylim,
+            annotations=annotations, markers=markers, rectangles=rectangles,
+            line_color='brown', fill=fill, axis=False, show=False)
+
+        return sing_plot
+
+
+    def _is_load_negative(self, load):
+        """Try to determine if a load is negative or positive, using
+        expansion and doit if necessary.
+
+        Returns
+        =======
+        True: if the load is negative
+        False: if the load is positive
+        None: if it is indeterminate
+
+        """
+        rv = load.is_negative
+        if load.is_Atom or rv is not None:
+            return rv
+        return load.doit().expand().is_negative
+
+    def _draw_load(self, pictorial, length, l):
+        loads = list(set(self.applied_loads) - set(self._support_as_loads))
+        height = length/10
+        x = self.variable
+
+        annotations = []
+        markers = []
+        load_args = []
+        scaled_load = 0
+        load_args1 = []
+        scaled_load1 = 0
+        load_eq = S.Zero     # For positive valued higher order loads
+        load_eq1 = S.Zero    # For negative valued higher order loads
+        fill = None
+
+        # schematic view should use the class convention as much as possible.
+        # However, users can add expressions as symbolic loads, for example
+        # P1 - P2: is this load positive or negative? We can't say.
+        # On these occasions it is better to inform users about the
+        # indeterminate state of those loads.
+        warning_head = "Please, note that this schematic view might not be " \
+            "in agreement with the sign convention used by the Beam class " \
+            "for load-related computations, because it was not possible " \
+            "to determine the sign (hence, the direction) of the " \
+            "following loads:\n"
+        warning_body = ""
+
+        for load in loads:
+            # check if the position of load is in terms of the beam length.
+            if l:
+                pos =  load[1].subs(l)
+            else:
+                pos = load[1]
+
+            # point loads
+            if load[2] == -1:
+                iln = self._is_load_negative(load[0])
+                if iln is None:
+                    warning_body += "* Point load %s located at %s\n" % (load[0], load[1])
+                if iln:
+                    annotations.append({'text':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':{'width': 1.5, 'headlength': 5, 'headwidth': 5, 'facecolor': 'black'}})
+                else:
+                    annotations.append({'text':'', 'xy':(pos, height),  'xytext':(pos, height*4), 'arrowprops':{"width": 1.5, "headlength": 4, "headwidth": 4, "facecolor": 'black'}})
+            # moment loads
+            elif load[2] == -2:
+                iln = self._is_load_negative(load[0])
+                if iln is None:
+                    warning_body += "* Moment %s located at %s\n" % (load[0], load[1])
+                if self._is_load_negative(load[0]):
+                    markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15})
+                else:
+                    markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15})
+            # higher order loads
+            elif load[2] >= 0:
+                # `fill` will be assigned only when higher order loads are present
+                value, start, order, end = load
+
+                iln = self._is_load_negative(value)
+                if iln is None:
+                    warning_body += "* Distributed load %s from %s to %s\n" % (value, start, end)
+
+                # Positive loads have their separate equations
+                if not iln:
+                    # if pictorial is True we remake the load equation again with
+                    # some constant magnitude values.
+                    if pictorial:
+                        # remake the load equation again with some constant
+                        # magnitude values.
+                        value = 10**(1-order) if order > 0 else length/2
+                    scaled_load += value*SingularityFunction(x, start, order)
+                    if end:
+                        f2 = value*x**order if order >= 0 else length/2*x**order
+                        for i in range(0, order + 1):
+                            scaled_load -= (f2.diff(x, i).subs(x, end - start)*
+                                            SingularityFunction(x, end, i)/factorial(i))
+
+                    if isinstance(scaled_load, Add):
+                        load_args = scaled_load.args
+                    else:
+                        # when the load equation consists of only a single term
+                        load_args = (scaled_load,)
+                    load_eq = Add(*[i.subs(l) for i in load_args])
+
+                # For loads with negative value
+                else:
+                    if pictorial:
+                        # remake the load equation again with some constant
+                        # magnitude values.
+                        value = 10**(1-order) if order > 0 else length/2
+                    scaled_load1 += abs(value)*SingularityFunction(x, start, order)
+                    if end:
+                        f2 = abs(value)*x**order if order >= 0 else length/2*x**order
+                        for i in range(0, order + 1):
+                            scaled_load1 -= (f2.diff(x, i).subs(x, end - start)*
+                                            SingularityFunction(x, end, i)/factorial(i))
+
+                    if isinstance(scaled_load1, Add):
+                        load_args1 = scaled_load1.args
+                    else:
+                        # when the load equation consists of only a single term
+                        load_args1 = (scaled_load1,)
+                    load_eq1 = [i.subs(l) for i in load_args1]
+                    load_eq1 = -Add(*load_eq1) - height
+
+        if len(warning_body) > 0:
+            warnings.warn(warning_head + warning_body)
+
+        xx = numpy.arange(0, float(length), 0.001)
+        yy1 = lambdify([x], height + load_eq.rewrite(Piecewise))(xx)
+        yy2 = lambdify([x], height + load_eq1.rewrite(Piecewise))(xx)
+        if not isinstance(yy1, numpy.ndarray):
+            yy1 *= numpy.ones_like(xx)
+        if not isinstance(yy2, numpy.ndarray):
+            yy2 *= numpy.ones_like(xx)
+        fill = {'x': xx, 'y1': yy1, 'y2': yy2,
+            'color':'darkkhaki', "zorder": -1}
+        return annotations, markers, load_eq, load_eq1, fill
+
+
+    def _draw_supports(self, length, l):
+        height = float(length/10)
+
+        support_markers = []
+        support_rectangles = []
+        for support in self._applied_supports:
+            if l:
+                pos =  support[0].subs(l)
+            else:
+                pos = support[0]
+
+            if support[1] == "pin":
+                support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"})
+
+            elif support[1] == "roller":
+                support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"})
+
+            elif support[1] == "fixed":
+                if pos == 0:
+                    support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'})
+                else:
+                    support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'})
+
+        return support_markers, support_rectangles
+
+
+class Beam3D(Beam):
+    """
+    This class handles loads applied in any direction of a 3D space along
+    with unequal values of Second moment along different axes.
+
+    .. note::
+       A consistent sign convention must be used while solving a beam
+       bending problem; the results will
+       automatically follow the chosen sign convention.
+       This class assumes that any kind of distributed load/moment is
+       applied through out the span of a beam.
+
+    Examples
+    ========
+    There is a beam of l meters long. A constant distributed load of magnitude q
+    is applied along y-axis from start till the end of beam. A constant distributed
+    moment of magnitude m is also applied along z-axis from start till the end of beam.
+    Beam is fixed at both of its end. So, deflection of the beam at the both ends
+    is restricted.
+
+    >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+    >>> from sympy import symbols, simplify, collect, factor
+    >>> l, E, G, I, A = symbols('l, E, G, I, A')
+    >>> b = Beam3D(l, E, G, I, A)
+    >>> x, q, m = symbols('x, q, m')
+    >>> b.apply_load(q, 0, 0, dir="y")
+    >>> b.apply_moment_load(m, 0, -1, dir="z")
+    >>> b.shear_force()
+    [0, -q*x, 0]
+    >>> b.bending_moment()
+    [0, 0, -m*x + q*x**2/2]
+    >>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
+    >>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
+    >>> b.solve_slope_deflection()
+    >>> factor(b.slope())
+    [0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q
+        - 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))]
+    >>> dx, dy, dz = b.deflection()
+    >>> dy = collect(simplify(dy), x)
+    >>> dx == dz == 0
+    True
+    >>> dy == (x*(12*E*I*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q)
+    ... + x*(A*G*l*(3*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) + x*(-2*A*G*l**2*q + 4*A*G*l*m - 24*E*I*q))
+    ... + A*G*(A*G*l**2 + 12*E*I)*(-2*l**2*q + 6*l*m - 4*m*x + q*x**2)
+    ... - 12*E*I*q*(A*G*l**2 + 12*E*I)))/(24*A*E*G*I*(A*G*l**2 + 12*E*I)))
+    True
+
+    References
+    ==========
+
+    .. [1] https://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf
+
+    """
+
+    def __init__(self, length, elastic_modulus, shear_modulus, second_moment,
+                 area, variable=Symbol('x')):
+        """Initializes the class.
+
+        Parameters
+        ==========
+        length : Sympifyable
+            A Symbol or value representing the Beam's length.
+        elastic_modulus : Sympifyable
+            A SymPy expression representing the Beam's Modulus of Elasticity.
+            It is a measure of the stiffness of the Beam material.
+        shear_modulus : Sympifyable
+            A SymPy expression representing the Beam's Modulus of rigidity.
+            It is a measure of rigidity of the Beam material.
+        second_moment : Sympifyable or list
+            A list of two elements having SymPy expression representing the
+            Beam's Second moment of area. First value represent Second moment
+            across y-axis and second across z-axis.
+            Single SymPy expression can be passed if both values are same
+        area : Sympifyable
+            A SymPy expression representing the Beam's cross-sectional area
+            in a plane perpendicular to length of the Beam.
+        variable : Symbol, optional
+            A Symbol object that will be used as the variable along the beam
+            while representing the load, shear, moment, slope and deflection
+            curve. By default, it is set to ``Symbol('x')``.
+        """
+        super().__init__(length, elastic_modulus, second_moment, variable)
+        self.shear_modulus = shear_modulus
+        self.area = area
+        self._load_vector = [0, 0, 0]
+        self._moment_load_vector = [0, 0, 0]
+        self._torsion_moment = {}
+        self._load_Singularity = [0, 0, 0]
+        self._slope = [0, 0, 0]
+        self._deflection = [0, 0, 0]
+        self._angular_deflection = 0
+
+    @property
+    def shear_modulus(self):
+        """Young's Modulus of the Beam. """
+        return self._shear_modulus
+
+    @shear_modulus.setter
+    def shear_modulus(self, e):
+        self._shear_modulus = sympify(e)
+
+    @property
+    def second_moment(self):
+        """Second moment of area of the Beam. """
+        return self._second_moment
+
+    @second_moment.setter
+    def second_moment(self, i):
+        if isinstance(i, list):
+            i = [sympify(x) for x in i]
+            self._second_moment = i
+        else:
+            self._second_moment = sympify(i)
+
+    @property
+    def area(self):
+        """Cross-sectional area of the Beam. """
+        return self._area
+
+    @area.setter
+    def area(self, a):
+        self._area = sympify(a)
+
+    @property
+    def load_vector(self):
+        """
+        Returns a three element list representing the load vector.
+        """
+        return self._load_vector
+
+    @property
+    def moment_load_vector(self):
+        """
+        Returns a three element list representing moment loads on Beam.
+        """
+        return self._moment_load_vector
+
+    @property
+    def boundary_conditions(self):
+        """
+        Returns a dictionary of boundary conditions applied on the beam.
+        The dictionary has two keywords namely slope and deflection.
+        The value of each keyword is a list of tuple, where each tuple
+        contains location and value of a boundary condition in the format
+        (location, value). Further each value is a list corresponding to
+        slope or deflection(s) values along three axes at that location.
+
+        Examples
+        ========
+        There is a beam of length 4 meters. The slope at 0 should be 4 along
+        the x-axis and 0 along others. At the other end of beam, deflection
+        along all the three axes should be zero.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+        >>> from sympy import symbols
+        >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+        >>> b = Beam3D(30, E, G, I, A, x)
+        >>> b.bc_slope = [(0, (4, 0, 0))]
+        >>> b.bc_deflection = [(4, [0, 0, 0])]
+        >>> b.boundary_conditions
+        {'bending_moment': [], 'deflection': [(4, [0, 0, 0])], 'shear_force': [], 'slope': [(0, (4, 0, 0))]}
+
+        Here the deflection of the beam should be ``0`` along all the three axes at ``4``.
+        Similarly, the slope of the beam should be ``4`` along x-axis and ``0``
+        along y and z axis at ``0``.
+        """
+        return self._boundary_conditions
+
+    def polar_moment(self):
+        """
+        Returns the polar moment of area of the beam
+        about the X axis with respect to the centroid.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+        >>> from sympy import symbols
+        >>> l, E, G, I, A = symbols('l, E, G, I, A')
+        >>> b = Beam3D(l, E, G, I, A)
+        >>> b.polar_moment()
+        2*I
+        >>> I1 = [9, 15]
+        >>> b = Beam3D(l, E, G, I1, A)
+        >>> b.polar_moment()
+        24
+        """
+        if not iterable(self.second_moment):
+            return 2*self.second_moment
+        return sum(self.second_moment)
+
+    def apply_load(self, value, start, order, dir="y"):
+        """
+        This method adds up the force load to a particular beam object.
+
+        Parameters
+        ==========
+        value : Sympifyable
+            The magnitude of an applied load.
+        dir : String
+            Axis along which load is applied.
+        order : Integer
+            The order of the applied load.
+            - For point loads, order=-1
+            - For constant distributed load, order=0
+            - For ramp loads, order=1
+            - For parabolic ramp loads, order=2
+            - ... so on.
+        """
+        x = self.variable
+        value = sympify(value)
+        start = sympify(start)
+        order = sympify(order)
+
+        if dir == "x":
+            if not order == -1:
+                self._load_vector[0] += value
+            self._load_Singularity[0] += value*SingularityFunction(x, start, order)
+
+        elif dir == "y":
+            if not order == -1:
+                self._load_vector[1] += value
+            self._load_Singularity[1] += value*SingularityFunction(x, start, order)
+
+        else:
+            if not order == -1:
+                self._load_vector[2] += value
+            self._load_Singularity[2] += value*SingularityFunction(x, start, order)
+
+    def apply_moment_load(self, value, start, order, dir="y"):
+        """
+        This method adds up the moment loads to a particular beam object.
+
+        Parameters
+        ==========
+        value : Sympifyable
+            The magnitude of an applied moment.
+        dir : String
+            Axis along which moment is applied.
+        order : Integer
+            The order of the applied load.
+            - For point moments, order=-2
+            - For constant distributed moment, order=-1
+            - For ramp moments, order=0
+            - For parabolic ramp moments, order=1
+            - ... so on.
+        """
+        x = self.variable
+        value = sympify(value)
+        start = sympify(start)
+        order = sympify(order)
+
+        if dir == "x":
+            if not order == -2:
+                self._moment_load_vector[0] += value
+            else:
+                if start in list(self._torsion_moment):
+                    self._torsion_moment[start] += value
+                else:
+                    self._torsion_moment[start] = value
+            self._load_Singularity[0] += value*SingularityFunction(x, start, order)
+        elif dir == "y":
+            if not order == -2:
+                self._moment_load_vector[1] += value
+            self._load_Singularity[0] += value*SingularityFunction(x, start, order)
+        else:
+            if not order == -2:
+                self._moment_load_vector[2] += value
+            self._load_Singularity[0] += value*SingularityFunction(x, start, order)
+
+    def apply_support(self, loc, type="fixed"):
+        if type in ("pin", "roller"):
+            reaction_load = Symbol('R_'+str(loc))
+            self._reaction_loads[reaction_load] = reaction_load
+            self.bc_deflection.append((loc, [0, 0, 0]))
+        else:
+            reaction_load = Symbol('R_'+str(loc))
+            reaction_moment = Symbol('M_'+str(loc))
+            self._reaction_loads[reaction_load] = [reaction_load, reaction_moment]
+            self.bc_deflection.append((loc, [0, 0, 0]))
+            self.bc_slope.append((loc, [0, 0, 0]))
+
+    def solve_for_reaction_loads(self, *reaction):
+        """
+        Solves for the reaction forces.
+
+        Examples
+        ========
+        There is a beam of length 30 meters. It it supported by rollers at
+        of its end. A constant distributed load of magnitude 8 N is applied
+        from start till its end along y-axis. Another linear load having
+        slope equal to 9 is applied along z-axis.
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+        >>> from sympy import symbols
+        >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+        >>> b = Beam3D(30, E, G, I, A, x)
+        >>> b.apply_load(8, start=0, order=0, dir="y")
+        >>> b.apply_load(9*x, start=0, order=0, dir="z")
+        >>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
+        >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+        >>> b.apply_load(R1, start=0, order=-1, dir="y")
+        >>> b.apply_load(R2, start=30, order=-1, dir="y")
+        >>> b.apply_load(R3, start=0, order=-1, dir="z")
+        >>> b.apply_load(R4, start=30, order=-1, dir="z")
+        >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+        >>> b.reaction_loads
+        {R1: -120, R2: -120, R3: -1350, R4: -2700}
+        """
+        x = self.variable
+        l = self.length
+        q = self._load_Singularity
+        shear_curves = [integrate(load, x) for load in q]
+        moment_curves = [integrate(shear, x) for shear in shear_curves]
+        for i in range(3):
+            react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))]
+            if len(react) == 0:
+                continue
+            shear_curve = limit(shear_curves[i], x, l)
+            moment_curve = limit(moment_curves[i], x, l)
+            sol = list((linsolve([shear_curve, moment_curve], react).args)[0])
+            sol_dict = dict(zip(react, sol))
+            reaction_loads = self._reaction_loads
+            # Check if any of the evaluated reaction exists in another direction
+            # and if it exists then it should have same value.
+            for key in sol_dict:
+                if key in reaction_loads and sol_dict[key] != reaction_loads[key]:
+                    raise ValueError("Ambiguous solution for %s in different directions." % key)
+            self._reaction_loads.update(sol_dict)
+
+    def shear_force(self):
+        """
+        Returns a list of three expressions which represents the shear force
+        curve of the Beam object along all three axes.
+        """
+        x = self.variable
+        q = self._load_vector
+        return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)]
+
+    def axial_force(self):
+        """
+        Returns expression of Axial shear force present inside the Beam object.
+        """
+        return self.shear_force()[0]
+
+    def shear_stress(self):
+        """
+        Returns a list of three expressions which represents the shear stress
+        curve of the Beam object along all three axes.
+        """
+        return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area]
+
+    def axial_stress(self):
+        """
+        Returns expression of Axial stress present inside the Beam object.
+        """
+        return self.axial_force()/self._area
+
+    def bending_moment(self):
+        """
+        Returns a list of three expressions which represents the bending moment
+        curve of the Beam object along all three axes.
+        """
+        x = self.variable
+        m = self._moment_load_vector
+        shear = self.shear_force()
+
+        return [integrate(-m[0], x), integrate(-m[1] + shear[2], x),
+                integrate(-m[2] - shear[1], x) ]
+
+    def torsional_moment(self):
+        """
+        Returns expression of Torsional moment present inside the Beam object.
+        """
+        return self.bending_moment()[0]
+
+    def solve_for_torsion(self):
+        """
+        Solves for the angular deflection due to the torsional effects of
+        moments being applied in the x-direction i.e. out of or into the beam.
+
+        Here, a positive torque means the direction of the torque is positive
+        i.e. out of the beam along the beam-axis. Likewise, a negative torque
+        signifies a torque into the beam cross-section.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+        >>> from sympy import symbols
+        >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+        >>> b = Beam3D(20, E, G, I, A, x)
+        >>> b.apply_moment_load(4, 4, -2, dir='x')
+        >>> b.apply_moment_load(4, 8, -2, dir='x')
+        >>> b.apply_moment_load(4, 8, -2, dir='x')
+        >>> b.solve_for_torsion()
+        >>> b.angular_deflection().subs(x, 3)
+        18/(G*I)
+        """
+        x = self.variable
+        sum_moments = 0
+        for point in list(self._torsion_moment):
+            sum_moments += self._torsion_moment[point]
+        list(self._torsion_moment).sort()
+        pointsList = list(self._torsion_moment)
+        torque_diagram = Piecewise((sum_moments, x<=pointsList[0]), (0, x>=pointsList[0]))
+        for i in range(len(pointsList))[1:]:
+            sum_moments -= self._torsion_moment[pointsList[i-1]]
+            torque_diagram += Piecewise((0, x<=pointsList[i-1]), (sum_moments, x<=pointsList[i]), (0, x>=pointsList[i]))
+        integrated_torque_diagram = integrate(torque_diagram)
+        self._angular_deflection =  integrated_torque_diagram/(self.shear_modulus*self.polar_moment())
+
+    def solve_slope_deflection(self):
+        x = self.variable
+        l = self.length
+        E = self.elastic_modulus
+        G = self.shear_modulus
+        I = self.second_moment
+        if isinstance(I, list):
+            I_y, I_z = I[0], I[1]
+        else:
+            I_y = I_z = I
+        A = self._area
+        load = self._load_vector
+        moment = self._moment_load_vector
+        defl = Function('defl')
+        theta = Function('theta')
+
+        # Finding deflection along x-axis(and corresponding slope value by differentiating it)
+        # Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0
+        eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0]
+        def_x = dsolve(Eq(eq, 0), defl(x)).args[1]
+        # Solving constants originated from dsolve
+        C1 = Symbol('C1')
+        C2 = Symbol('C2')
+        constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0])
+        def_x = def_x.subs({C1:constants[0], C2:constants[1]})
+        slope_x = def_x.diff(x)
+        self._deflection[0] = def_x
+        self._slope[0] = slope_x
+
+        # Finding deflection along y-axis and slope across z-axis. System of equation involved:
+        # 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0
+        # 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0
+        C_i = Symbol('C_i')
+        # Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1)
+        eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2]
+        slope_z = dsolve(Eq(eq1, 0)).args[1]
+
+        # Solve for constants originated from using dsolve on eq1
+        constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0])
+        slope_z = slope_z.subs({C1:constants[0], C2:constants[1]})
+
+        # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis
+        eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z
+        def_y = dsolve(Eq(eq2, 0), defl(x)).args[1]
+        # Solve for constants originated from using dsolve on eq2
+        constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0])
+        self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]})
+        self._slope[2] = slope_z.subs(C_i, constants[1])
+
+        # Finding deflection along z-axis and slope across y-axis. System of equation involved:
+        # 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0
+        # 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0
+
+        # Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1)
+        eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1]
+        slope_y = dsolve(Eq(eq1, 0)).args[1]
+        # Solve for constants originated from using dsolve on eq1
+        constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0])
+        slope_y = slope_y.subs({C1:constants[0], C2:constants[1]})
+
+        # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis
+        eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y
+        def_z = dsolve(Eq(eq2,0)).args[1]
+        # Solve for constants originated from using dsolve on eq2
+        constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0])
+        self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]})
+        self._slope[1] = slope_y.subs(C_i, constants[1])
+
+    def slope(self):
+        """
+        Returns a three element list representing slope of deflection curve
+        along all the three axes.
+        """
+        return self._slope
+
+    def deflection(self):
+        """
+        Returns a three element list representing deflection curve along all
+        the three axes.
+        """
+        return self._deflection
+
+    def angular_deflection(self):
+        """
+        Returns a function in x depicting how the angular deflection, due to moments
+        in the x-axis on the beam, varies with x.
+        """
+        return self._angular_deflection
+
+    def _plot_shear_force(self, dir, subs=None):
+
+        shear_force = self.shear_force()
+
+        if dir == 'x':
+            dir_num = 0
+            color = 'r'
+
+        elif dir == 'y':
+            dir_num = 1
+            color = 'g'
+
+        elif dir == 'z':
+            dir_num = 2
+            color = 'b'
+
+        if subs is None:
+            subs = {}
+
+        for sym in shear_force[dir_num].atoms(Symbol):
+            if sym != self.variable and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+
+        return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir,
+                xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V(%c)}$'%dir, line_color=color)
+
+    def plot_shear_force(self, dir="all", subs=None):
+
+        """
+
+        Returns a plot for Shear force along all three directions
+        present in the Beam object.
+
+        Parameters
+        ==========
+        dir : string (default : "all")
+            Direction along which shear force plot is required.
+            If no direction is specified, all plots are displayed.
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters. It is supported by rollers
+        at both of its ends. A linear load having slope equal to 12 is applied
+        along y-axis. A constant distributed load of magnitude 15 N is
+        applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, E, G, I, A, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.plot_shear_force()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: 0 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: -15*x for x over (0.0, 20.0)
+
+        """
+
+        dir = dir.lower()
+        # For shear force along x direction
+        if dir == "x":
+            Px = self._plot_shear_force('x', subs)
+            return Px.show()
+        # For shear force along y direction
+        elif dir == "y":
+            Py = self._plot_shear_force('y', subs)
+            return Py.show()
+        # For shear force along z direction
+        elif dir == "z":
+            Pz = self._plot_shear_force('z', subs)
+            return Pz.show()
+        # For shear force along all direction
+        else:
+            Px = self._plot_shear_force('x', subs)
+            Py = self._plot_shear_force('y', subs)
+            Pz = self._plot_shear_force('z', subs)
+            return PlotGrid(3, 1, Px, Py, Pz)
+
+    def _plot_bending_moment(self, dir, subs=None):
+
+        bending_moment = self.bending_moment()
+
+        if dir == 'x':
+            dir_num = 0
+            color = 'g'
+
+        elif dir == 'y':
+            dir_num = 1
+            color = 'c'
+
+        elif dir == 'z':
+            dir_num = 2
+            color = 'm'
+
+        if subs is None:
+            subs = {}
+
+        for sym in bending_moment[dir_num].atoms(Symbol):
+            if sym != self.variable and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+
+        return plot(bending_moment[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Bending Moment along %c direction'%dir,
+                xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M(%c)}$'%dir, line_color=color)
+
+    def plot_bending_moment(self, dir="all", subs=None):
+
+        """
+
+        Returns a plot for bending moment along all three directions
+        present in the Beam object.
+
+        Parameters
+        ==========
+        dir : string (default : "all")
+            Direction along which bending moment plot is required.
+            If no direction is specified, all plots are displayed.
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters. It is supported by rollers
+        at both of its ends. A linear load having slope equal to 12 is applied
+        along y-axis. A constant distributed load of magnitude 15 N is
+        applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, E, G, I, A, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.plot_bending_moment()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: 0 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: 2*x**3 for x over (0.0, 20.0)
+
+        """
+
+        dir = dir.lower()
+        # For bending moment along x direction
+        if dir == "x":
+            Px = self._plot_bending_moment('x', subs)
+            return Px.show()
+        # For bending moment along y direction
+        elif dir == "y":
+            Py = self._plot_bending_moment('y', subs)
+            return Py.show()
+        # For bending moment along z direction
+        elif dir == "z":
+            Pz = self._plot_bending_moment('z', subs)
+            return Pz.show()
+        # For bending moment along all direction
+        else:
+            Px = self._plot_bending_moment('x', subs)
+            Py = self._plot_bending_moment('y', subs)
+            Pz = self._plot_bending_moment('z', subs)
+            return PlotGrid(3, 1, Px, Py, Pz)
+
+    def _plot_slope(self, dir, subs=None):
+
+        slope = self.slope()
+
+        if dir == 'x':
+            dir_num = 0
+            color = 'b'
+
+        elif dir == 'y':
+            dir_num = 1
+            color = 'm'
+
+        elif dir == 'z':
+            dir_num = 2
+            color = 'g'
+
+        if subs is None:
+            subs = {}
+
+        for sym in slope[dir_num].atoms(Symbol):
+            if sym != self.variable and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+
+
+        return plot(slope[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Slope along %c direction'%dir,
+                xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\theta(%c)}$'%dir, line_color=color)
+
+    def plot_slope(self, dir="all", subs=None):
+
+        """
+
+        Returns a plot for Slope along all three directions
+        present in the Beam object.
+
+        Parameters
+        ==========
+        dir : string (default : "all")
+            Direction along which Slope plot is required.
+            If no direction is specified, all plots are displayed.
+        subs : dictionary
+            Python dictionary containing Symbols as keys and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters. It is supported by rollers
+        at both of its ends. A linear load having slope equal to 12 is applied
+        along y-axis. A constant distributed load of magnitude 15 N is
+        applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, 40, 21, 100, 25, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.solve_slope_deflection()
+            >>> b.plot_slope()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: 0 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: x**4/8000 - 19*x**2/172 + 52*x/43 for x over (0.0, 20.0)
+
+        """
+
+        dir = dir.lower()
+        # For Slope along x direction
+        if dir == "x":
+            Px = self._plot_slope('x', subs)
+            return Px.show()
+        # For Slope along y direction
+        elif dir == "y":
+            Py = self._plot_slope('y', subs)
+            return Py.show()
+        # For Slope along z direction
+        elif dir == "z":
+            Pz = self._plot_slope('z', subs)
+            return Pz.show()
+        # For Slope along all direction
+        else:
+            Px = self._plot_slope('x', subs)
+            Py = self._plot_slope('y', subs)
+            Pz = self._plot_slope('z', subs)
+            return PlotGrid(3, 1, Px, Py, Pz)
+
+    def _plot_deflection(self, dir, subs=None):
+
+        deflection = self.deflection()
+
+        if dir == 'x':
+            dir_num = 0
+            color = 'm'
+
+        elif dir == 'y':
+            dir_num = 1
+            color = 'r'
+
+        elif dir == 'z':
+            dir_num = 2
+            color = 'c'
+
+        if subs is None:
+            subs = {}
+
+        for sym in deflection[dir_num].atoms(Symbol):
+            if sym != self.variable and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+
+        return plot(deflection[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Deflection along %c direction'%dir,
+                xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\delta(%c)}$'%dir, line_color=color)
+
+    def plot_deflection(self, dir="all", subs=None):
+
+        """
+
+        Returns a plot for Deflection along all three directions
+        present in the Beam object.
+
+        Parameters
+        ==========
+        dir : string (default : "all")
+            Direction along which deflection plot is required.
+            If no direction is specified, all plots are displayed.
+        subs : dictionary
+            Python dictionary containing Symbols as keys and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters. It is supported by rollers
+        at both of its ends. A linear load having slope equal to 12 is applied
+        along y-axis. A constant distributed load of magnitude 15 N is
+        applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, 40, 21, 100, 25, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.solve_slope_deflection()
+            >>> b.plot_deflection()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: 0 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: x**4/6400 - x**3/160 + 27*x**2/560 + 2*x/7 for x over (0.0, 20.0)
+
+
+        """
+
+        dir = dir.lower()
+        # For deflection along x direction
+        if dir == "x":
+            Px = self._plot_deflection('x', subs)
+            return Px.show()
+        # For deflection along y direction
+        elif dir == "y":
+            Py = self._plot_deflection('y', subs)
+            return Py.show()
+        # For deflection along z direction
+        elif dir == "z":
+            Pz = self._plot_deflection('z', subs)
+            return Pz.show()
+        # For deflection along all direction
+        else:
+            Px = self._plot_deflection('x', subs)
+            Py = self._plot_deflection('y', subs)
+            Pz = self._plot_deflection('z', subs)
+            return PlotGrid(3, 1, Px, Py, Pz)
+
+    def plot_loading_results(self, dir='x', subs=None):
+
+        """
+
+        Returns a subplot of Shear Force, Bending Moment,
+        Slope and Deflection of the Beam object along the direction specified.
+
+        Parameters
+        ==========
+
+        dir : string (default : "x")
+               Direction along which plots are required.
+               If no direction is specified, plots along x-axis are displayed.
+        subs : dictionary
+               Python dictionary containing Symbols as key and their
+               corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters. It is supported by rollers
+        at both of its ends. A linear load having slope equal to 12 is applied
+        along y-axis. A constant distributed load of magnitude 15 N is
+        applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, E, G, I, A, x)
+            >>> subs = {E:40, G:21, I:100, A:25}
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.solve_slope_deflection()
+            >>> b.plot_loading_results('y',subs)
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
+            Plot[3]:Plot object containing:
+            [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
+
+        """
+
+        dir = dir.lower()
+        if subs is None:
+            subs = {}
+
+        ax1 = self._plot_shear_force(dir, subs)
+        ax2 = self._plot_bending_moment(dir, subs)
+        ax3 = self._plot_slope(dir, subs)
+        ax4 = self._plot_deflection(dir, subs)
+
+        return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
+
+    def _plot_shear_stress(self, dir, subs=None):
+
+        shear_stress = self.shear_stress()
+
+        if dir == 'x':
+            dir_num = 0
+            color = 'r'
+
+        elif dir == 'y':
+            dir_num = 1
+            color = 'g'
+
+        elif dir == 'z':
+            dir_num = 2
+            color = 'b'
+
+        if subs is None:
+            subs = {}
+
+        for sym in shear_stress[dir_num].atoms(Symbol):
+            if sym != self.variable and sym not in subs:
+                raise ValueError('Value of %s was not passed.' %sym)
+        if self.length in subs:
+            length = subs[self.length]
+        else:
+            length = self.length
+
+        return plot(shear_stress[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear stress along %c direction'%dir,
+                xlabel=r'$\mathrm{X}$', ylabel=r'$\tau(%c)$'%dir, line_color=color)
+
+    def plot_shear_stress(self, dir="all", subs=None):
+
+        """
+
+        Returns a plot for Shear Stress along all three directions
+        present in the Beam object.
+
+        Parameters
+        ==========
+        dir : string (default : "all")
+            Direction along which shear stress plot is required.
+            If no direction is specified, all plots are displayed.
+        subs : dictionary
+            Python dictionary containing Symbols as key and their
+            corresponding values.
+
+        Examples
+        ========
+        There is a beam of length 20 meters and area of cross section 2 square
+        meters. It is supported by rollers at both of its ends. A linear load having
+        slope equal to 12 is applied along y-axis. A constant distributed load
+        of magnitude 15 N is applied from start till its end along z-axis.
+
+        .. plot::
+            :context: close-figs
+            :format: doctest
+            :include-source: True
+
+            >>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, E, G, I, 2, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.plot_shear_stress()
+            PlotGrid object containing:
+            Plot[0]:Plot object containing:
+            [0]: cartesian line: 0 for x over (0.0, 20.0)
+            Plot[1]:Plot object containing:
+            [0]: cartesian line: -3*x**2 for x over (0.0, 20.0)
+            Plot[2]:Plot object containing:
+            [0]: cartesian line: -15*x/2 for x over (0.0, 20.0)
+
+        """
+
+        dir = dir.lower()
+        # For shear stress along x direction
+        if dir == "x":
+            Px = self._plot_shear_stress('x', subs)
+            return Px.show()
+        # For shear stress along y direction
+        elif dir == "y":
+            Py = self._plot_shear_stress('y', subs)
+            return Py.show()
+        # For shear stress along z direction
+        elif dir == "z":
+            Pz = self._plot_shear_stress('z', subs)
+            return Pz.show()
+        # For shear stress along all direction
+        else:
+            Px = self._plot_shear_stress('x', subs)
+            Py = self._plot_shear_stress('y', subs)
+            Pz = self._plot_shear_stress('z', subs)
+            return PlotGrid(3, 1, Px, Py, Pz)
+
+    def _max_shear_force(self, dir):
+        """
+        Helper function for max_shear_force().
+        """
+
+        dir = dir.lower()
+
+        if dir == 'x':
+            dir_num = 0
+
+        elif dir == 'y':
+            dir_num = 1
+
+        elif dir == 'z':
+            dir_num = 2
+
+        if not self.shear_force()[dir_num]:
+            return (0,0)
+        # To restrict the range within length of the Beam
+        load_curve = Piecewise((float("nan"), self.variable<=0),
+                (self._load_vector[dir_num], self.variable>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, 40, 21, 100, 25, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.max_shear_force()
+            [(0, 0), (20, 2400), (20, 300)]
+        """
+
+        max_shear = []
+        max_shear.append(self._max_shear_force('x'))
+        max_shear.append(self._max_shear_force('y'))
+        max_shear.append(self._max_shear_force('z'))
+        return max_shear
+
+    def _max_bending_moment(self, dir):
+        """
+        Helper function for max_bending_moment().
+        """
+
+        dir = dir.lower()
+
+        if dir == 'x':
+            dir_num = 0
+
+        elif dir == 'y':
+            dir_num = 1
+
+        elif dir == 'z':
+            dir_num = 2
+
+        if not self.bending_moment()[dir_num]:
+            return (0,0)
+        # To restrict the range within length of the Beam
+        shear_curve = Piecewise((float("nan"), self.variable<=0),
+                (self.shear_force()[dir_num], self.variable>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, 40, 21, 100, 25, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.max_bending_moment()
+            [(0, 0), (20, 3000), (20, 16000)]
+        """
+
+        max_bmoment = []
+        max_bmoment.append(self._max_bending_moment('x'))
+        max_bmoment.append(self._max_bending_moment('y'))
+        max_bmoment.append(self._max_bending_moment('z'))
+        return max_bmoment
+
+    max_bmoment = max_bending_moment
+
+    def _max_deflection(self, dir):
+        """
+        Helper function for max_Deflection()
+        """
+
+        dir = dir.lower()
+
+        if dir == 'x':
+            dir_num = 0
+
+        elif dir == 'y':
+            dir_num = 1
+
+        elif dir == 'z':
+            dir_num = 2
+
+        if not self.deflection()[dir_num]:
+            return (0,0)
+        # To restrict the range within length of the Beam
+        slope_curve = Piecewise((float("nan"), self.variable<=0),
+                (self.slope()[dir_num], self.variable>> from sympy.physics.continuum_mechanics.beam import Beam3D
+            >>> from sympy import symbols
+            >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
+            >>> b = Beam3D(20, 40, 21, 100, 25, x)
+            >>> b.apply_load(15, start=0, order=0, dir="z")
+            >>> b.apply_load(12*x, start=0, order=0, dir="y")
+            >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
+            >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
+            >>> b.apply_load(R1, start=0, order=-1, dir="z")
+            >>> b.apply_load(R2, start=20, order=-1, dir="z")
+            >>> b.apply_load(R3, start=0, order=-1, dir="y")
+            >>> b.apply_load(R4, start=20, order=-1, dir="y")
+            >>> b.solve_for_reaction_loads(R1, R2, R3, R4)
+            >>> b.solve_slope_deflection()
+            >>> b.max_deflection()
+            [(0, 0), (10, 495/14), (-10 + 10*sqrt(10793)/43, (10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560)]
+        """
+
+        max_def = []
+        max_def.append(self._max_deflection('x'))
+        max_def.append(self._max_deflection('y'))
+        max_def.append(self._max_deflection('z'))
+        return max_def
diff --git a/shared/package-files/56/56ae4fc73ebe2615360f6bed6c23f4ddb44a9ac57e7a8cfd36c79c0d7961ba82/Backend.hpp b/shared/package-files/56/56ae4fc73ebe2615360f6bed6c23f4ddb44a9ac57e7a8cfd36c79c0d7961ba82/Backend.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..3d498627efa3eab7898c1d8a02b88956414eb838
--- /dev/null
+++ b/shared/package-files/56/56ae4fc73ebe2615360f6bed6c23f4ddb44a9ac57e7a8cfd36c79c0d7961ba82/Backend.hpp
@@ -0,0 +1,467 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+constexpr auto kBackendDefaultTimeout =
+    std::chrono::milliseconds(30 * 60 * 1000);
+
+namespace c10d {
+
+enum class ErrorType {
+  SUCCESS = 0,
+  TIMEOUT = 1,
+  // e.g., NCCL error, etc
+  COMM_ERROR = 2,
+  // TODO, do we need to distinguish between remote timeout or remote COMM
+  // errors?
+  REMOTE_ERROR = 3
+};
+
+class TORCH_API Backend : public torch::CustomClassHolder {
+ public:
+  // Backend Options is a base struct that defines the basic options
+  // when constructing a Backend. Each Backend subclass should
+  // extend this struct and define its options if it wants to provide more
+  // config options (beyond basic ones defined here) to end user.
+  struct TORCH_API Options : torch::CustomClassHolder {
+    explicit Options(
+        std::string backend,
+        std::chrono::milliseconds timeout = kBackendDefaultTimeout)
+        : timeout(timeout), backend(std::move(backend)) {}
+    ~Options() override = default;
+
+    std::chrono::milliseconds timeout;
+
+    // backend name
+    // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+    const std::string backend;
+  };
+
+  explicit Backend(int rank, int size);
+  ~Backend() override = 0;
+
+  int getRank() const {
+    return rank_;
+  }
+
+  int getSize() const {
+    return size_;
+  }
+
+  // Returns an unique opaque ID of this backend that can be used to correlate
+  // with its collectives.
+  int64_t getID() const {
+    return reinterpret_cast(this);
+  }
+
+  virtual bool supportsSplitting() const {
+    return false;
+  }
+
+  virtual bool supportsCoalescing() const {
+    return false;
+  }
+
+  virtual void startCoalescing() {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not implement startCoalescing"));
+  }
+
+  virtual c10::intrusive_ptr endCoalescing() {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not implement endCoalescing"));
+  }
+
+  // Subclasses must override this method to return the backend name
+  virtual const std::string getBackendName() const {
+    TORCH_INTERNAL_ASSERT(false, "getBackendName is not implemented.");
+  }
+
+  virtual c10::intrusive_ptr broadcast(
+      std::vector& /* tensors */,
+      const BroadcastOptions& /* opts */ = BroadcastOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support broadcast"));
+  }
+
+  virtual c10::intrusive_ptr allreduce(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support allreduce"));
+  }
+
+  virtual c10::intrusive_ptr allreduce_sparse(
+      std::vector& /* tensors */,
+      const AllreduceOptions& /* opts */ = AllreduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allreduce sparse"));
+  }
+
+  virtual c10::intrusive_ptr allreduce_coalesced(
+      std::vector& /* tensors */,
+      const AllreduceCoalescedOptions& /* opts */ =
+          AllreduceCoalescedOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allreduce_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr reduce(
+      std::vector& /* tensors */,
+      const ReduceOptions& /* opts */ = ReduceOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support reduce"));
+  }
+
+  virtual c10::intrusive_ptr allgather(
+      std::vector>& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support allgather"));
+  }
+
+  // Gathers a single tensor inputBuffer into a single buffer outputBuffer that
+  // is interpreted as a contiguous collection of size inputBuffer * WORLD_SIZE.
+  // For implementers of ProcessGroup API and advanced users only.
+  // Note: this function will be deprecated in near future.
+  virtual c10::intrusive_ptr _allgather_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support _allgather_base"));
+  }
+
+  // This function is deprecated and will be moved out of Backend to comms:
+  // * do not add dependencies on this function,
+  // * do not implement it in your Backend, implement _allgather_base
+  //   instead.
+  virtual c10::intrusive_ptr allgather_coalesced(
+      std::vector>& /* outputTensorLists */,
+      std::vector& /* inputTensors */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allgather_coalesced"));
+  }
+
+  // This function is a coalesced version of `allgather_into_tensor` (currently
+  // still named as `_allgather_base`). Each tensor in the vector corresponds to
+  // an input/output of one `allgather_into_tensor` operation.
+  virtual c10::intrusive_ptr allgather_into_tensor_coalesced(
+      std::vector& /* outputs */,
+      std::vector& /* inputs */,
+      const AllgatherOptions& /* opts */ = AllgatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support allgather_into_tensor_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr gather(
+      std::vector>& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const GatherOptions& /* opts */ = GatherOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support gather"));
+  }
+
+  virtual c10::intrusive_ptr scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ScatterOptions& /* opts */ = ScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support scatter"));
+  }
+
+  virtual c10::intrusive_ptr reduce_scatter(
+      std::vector& /* outputTensors */,
+      std::vector>& /* inputTensors */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support reduce_scatter"));
+  }
+
+  virtual c10::intrusive_ptr _reduce_scatter_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support _reduce_scatter_base"));
+  }
+
+  // This function is a coalesced version of `reduce_scatter_tensor` (currently
+  // still named as `_reduce_scatter_base`). Each tensor in the vector
+  // corresponds to an input/output of one `reduce_scatter_tensor` operation.
+  virtual c10::intrusive_ptr reduce_scatter_tensor_coalesced(
+      std::vector& /* outputs */,
+      std::vector& /* inputs */,
+      const ReduceScatterOptions& /* opts */ = ReduceScatterOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            getBackendName(),
+            " does not support reduce_scatter_tensor_coalesced"));
+  }
+
+  virtual c10::intrusive_ptr alltoall_base(
+      at::Tensor& /* outputBuffer */,
+      at::Tensor& /* inputBuffer */,
+      std::vector& /* outputSplitSizes */,
+      std::vector& /* inputSplitSizes */,
+      const AllToAllOptions& /* opts */ = AllToAllOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support alltoall_base"));
+  }
+
+  virtual c10::intrusive_ptr alltoall(
+      std::vector& /* outputTensors */,
+      std::vector& /* inputTensors */,
+      const AllToAllOptions& opts = AllToAllOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support alltoall"));
+  }
+
+  virtual void monitoredBarrier(
+      const BarrierOptions& /* unused */,
+      bool /* unused */ = false) {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not support monitoredBarrier, only GLOO supports monitored barrier."));
+  }
+
+  // Agrees on an initial sequence number for the whole group by having rank 0
+  // create it and broadcast it to other ranks using the store. Only implemented
+  // for GLOO and NCCL backends currently.
+  virtual void setSequenceNumberForGroup() {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not yet support sequence numbers."));
+  }
+
+  // Retrieves the current sequence number for the whole group, which should be
+  // in sync. If the returned number is not consistent across the group, it
+  // may indicate that there is some sort of collective desynchronization.
+  virtual uint64_t getSequenceNumberForGroup() {
+    auto backendName = getBackendName();
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ",
+            backendName,
+            " does not yet support sequence numbers."));
+  }
+
+  virtual c10::intrusive_ptr send(
+      std::vector& /* tensors */,
+      int /* dstRank */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support send"));
+  }
+
+  virtual c10::intrusive_ptr recv(
+      std::vector& /* tensors */,
+      int /* srcRank */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support recv"));
+  }
+
+  virtual c10::intrusive_ptr recvAnysource(
+      std::vector& /* tensors */,
+      int /* tag */) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support recvAnysource"));
+  }
+
+  virtual c10::intrusive_ptr barrier(
+      const BarrierOptions& /* opts */ = BarrierOptions()) {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support barrier"));
+  }
+
+  virtual void registerOnCompletionHook(
+      std::function)>&& hook) {
+    TORCH_CHECK(
+        false,
+        "Only ProcessGrouppNCCL supports onCompletion hook, but got ",
+        getBackendName(),
+        " backend.");
+  }
+
+  virtual void waitForPendingWorks() {
+    TORCH_CHECK(
+        false,
+        "Only ProcessGrouppNCCL supports waitForPendingWorks, but got ",
+        getBackendName(),
+        " backend.");
+  }
+
+  virtual void enableCollectivesTiming() {
+    TORCH_CHECK(
+        false,
+        "Backend ",
+        getBackendName(),
+        " is missing implementation of enableCollectivesTiming.");
+  }
+
+  bool hasHooks() const {
+    return onCompletionHook_ != nullptr;
+  }
+
+  // Do not call this directly, use ProcessGroup::setGroupName instead.
+  void setGroupUid(const std::string& pg_uid) {
+    pg_uid_ = pg_uid;
+  }
+
+  const std::string& getGroupUid() const {
+    return pg_uid_;
+  }
+
+  void setGroupDesc(const std::string& desc) {
+    pg_desc_ = desc;
+  }
+
+  const std::string& getGroupDesc() const {
+    return pg_desc_;
+  }
+
+  // See similar functions in ProcessGroup.hpp for context.
+  std::optional getBoundDeviceId() const {
+    return bound_device_id_;
+  }
+
+  // Perform an eager connect to the specified device if the backend supports
+  // it.
+  virtual void eagerConnectSingleDevice(at::Device device) {
+    // no-op in the default case; this is an optimization some
+    // backends may perform
+  }
+
+  void setBoundDeviceId(std::optional device) {
+    if (device) {
+      TORCH_CHECK(device->has_index(), "setBoundDeviceId must have an index");
+    }
+    bound_device_id_ = device;
+  }
+
+  virtual ErrorType getError() {
+    TORCH_CHECK(
+        false,
+        c10::str("Backend ", getBackendName(), " does not support getError"));
+  }
+
+  virtual std::shared_ptr getMemAllocator() {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support getMemAllocator"));
+  }
+
+  // Allocate tensor (aten::empty) from backend's communication-optimized memory
+  // pool
+  virtual at::Tensor allocateTensor(long size, at::TensorOptions options = {}) {
+    TORCH_CHECK(
+        false,
+        c10::str(
+            "Backend ", getBackendName(), " does not support allocateTensor"));
+  }
+
+  // Returns true if backend supports tensor allocation
+  virtual bool supportsTensorAlloc(c10::DeviceIndex deviceIdx) {
+    // Change to true in concrete backend if supported
+    return false;
+  }
+
+  // Aborts all pending operations and connections in the backend if the backend
+  // supports it.
+  virtual void abort() {}
+
+  // Shutdown the backend if the backend supports it. This should be used for
+  // normal shutdown.
+  virtual void shutdown() {}
+
+ protected:
+  // Implementations of this interface need to call this to setup
+  // appropriate logging etc.
+  void init();
+
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int rank_;
+  // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
+  const int size_;
+  // Debug level setting. It is parsed once when ProcessGroup is constructed and
+  // remains the same across use of this process group.
+  DebugLevel dist_debug_level_;
+  std::string pg_uid_;
+  std::string pg_desc_;
+
+  std::function)> onCompletionHook_;
+
+  std::optional bound_device_id_;
+};
+
+} // namespace c10d
diff --git a/shared/package-files/56/56b59987a173bf2bc08bbe388a21417186ab057dc0927ea44daad8cc4217d3fc/__init__.py b/shared/package-files/56/56b59987a173bf2bc08bbe388a21417186ab057dc0927ea44daad8cc4217d3fc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..61faa90bd95cc7e255be2df82c617b5bab46b044
--- /dev/null
+++ b/shared/package-files/56/56b59987a173bf2bc08bbe388a21417186ab057dc0927ea44daad8cc4217d3fc/__init__.py
@@ -0,0 +1 @@
+from torch.nn.quantized._reference.modules import *  # noqa: F403
diff --git a/shared/package-files/56/56b63c03153d9822b908762354fce12566f8a33b6e47813c827f4de3abc4a6e7/_shape_as_tensor_native.h b/shared/package-files/56/56b63c03153d9822b908762354fce12566f8a33b6e47813c827f4de3abc4a6e7/_shape_as_tensor_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..1b3544b63ac14b8f0ff43d5c411368396736097d
--- /dev/null
+++ b/shared/package-files/56/56b63c03153d9822b908762354fce12566f8a33b6e47813c827f4de3abc4a6e7/_shape_as_tensor_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor _shape_as_tensor(const at::Tensor & self);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/56be0996c6b8b24fb36c3ed50b57bfa0dc3c840c2edf74a67aeeb9dacfd2f181/test_count_ops.cpython-311.pyc b/shared/package-files/56/56be0996c6b8b24fb36c3ed50b57bfa0dc3c840c2edf74a67aeeb9dacfd2f181/test_count_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35ada722abdd79ef72d20e3756bdc5b12b298923
Binary files /dev/null and b/shared/package-files/56/56be0996c6b8b24fb36c3ed50b57bfa0dc3c840c2edf74a67aeeb9dacfd2f181/test_count_ops.cpython-311.pyc differ
diff --git a/shared/package-files/56/56c0c7ed354cb1991a264c0ede6de80813d9d0984b72aa2c5b6f3764d65b7957/_foreach_clamp_max_native.h b/shared/package-files/56/56c0c7ed354cb1991a264c0ede6de80813d9d0984b72aa2c5b6f3764d65b7957/_foreach_clamp_max_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..e0047c01c3ef3b1d504ff616f09494bee060c775
--- /dev/null
+++ b/shared/package-files/56/56c0c7ed354cb1991a264c0ede6de80813d9d0984b72aa2c5b6f3764d65b7957/_foreach_clamp_max_native.h
@@ -0,0 +1,35 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API ::std::vector foreach_tensor_clamp_max_scalar_kernel_slow(at::TensorList self, const at::Scalar & scalar);
+TORCH_API void _foreach_clamp_max_Scalar_out(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
+TORCH_API void foreach_tensor_clamp_max_scalar_kernel_slow_(at::TensorList self, const at::Scalar & scalar);
+TORCH_API ::std::vector foreach_tensor_clamp_max_scalar_kernel_cuda(at::TensorList self, const at::Scalar & scalar);
+TORCH_API void foreach_tensor_clamp_max_scalar_kernel_cuda_(at::TensorList self, const at::Scalar & scalar);
+TORCH_API ::std::vector foreach_tensor_clamp_max_list_kernel_slow(at::TensorList self, at::TensorList other);
+TORCH_API void _foreach_clamp_max_List_out(at::TensorList self, at::TensorList other, at::TensorList out);
+TORCH_API void foreach_tensor_clamp_max_list_kernel_slow_(at::TensorList self, at::TensorList other);
+TORCH_API ::std::vector foreach_tensor_clamp_max_list_kernel_cuda(at::TensorList self, at::TensorList other);
+TORCH_API void foreach_tensor_clamp_max_list_kernel_cuda_(at::TensorList self, at::TensorList other);
+TORCH_API ::std::vector foreach_tensor_clamp_max_scalarlist_kernel_slow(at::TensorList self, at::ArrayRef scalars);
+TORCH_API void _foreach_clamp_max_ScalarList_out(at::TensorList self, at::ArrayRef scalars, at::TensorList out);
+TORCH_API void foreach_tensor_clamp_max_scalarlist_kernel_slow_(at::TensorList self, at::ArrayRef scalars);
+TORCH_API ::std::vector foreach_tensor_clamp_max_scalarlist_kernel_cuda(at::TensorList self, at::ArrayRef scalars);
+TORCH_API void foreach_tensor_clamp_max_scalarlist_kernel_cuda_(at::TensorList self, at::ArrayRef scalars);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/56c3cf41f26cd2004b28960d43664b983f7c2562ddd48672d10191c08db5fd33/system.py b/shared/package-files/56/56c3cf41f26cd2004b28960d43664b983f7c2562ddd48672d10191c08db5fd33/system.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8e0657d7da54ca5aaad9b37b816235641968470
--- /dev/null
+++ b/shared/package-files/56/56c3cf41f26cd2004b28960d43664b983f7c2562ddd48672d10191c08db5fd33/system.py
@@ -0,0 +1,1553 @@
+from functools import wraps
+
+from sympy.core.basic import Basic
+from sympy.matrices.immutable import ImmutableMatrix
+from sympy.matrices.dense import Matrix, eye, zeros
+from sympy.core.containers import OrderedSet
+from sympy.physics.mechanics.actuator import ActuatorBase
+from sympy.physics.mechanics.body_base import BodyBase
+from sympy.physics.mechanics.functions import (
+    Lagrangian, _validate_coordinates, find_dynamicsymbols)
+from sympy.physics.mechanics.joint import Joint
+from sympy.physics.mechanics.kane import KanesMethod
+from sympy.physics.mechanics.lagrange import LagrangesMethod
+from sympy.physics.mechanics.loads import _parse_load, gravity
+from sympy.physics.mechanics.method import _Methods
+from sympy.physics.mechanics.particle import Particle
+from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
+from sympy.utilities.iterables import iterable
+from sympy.utilities.misc import filldedent
+
+__all__ = ['SymbolicSystem', 'System']
+
+
+def _reset_eom_method(method):
+    """Decorator to reset the eom_method if a property is changed."""
+
+    @wraps(method)
+    def wrapper(self, *args, **kwargs):
+        self._eom_method = None
+        return method(self, *args, **kwargs)
+
+    return wrapper
+
+
+class System(_Methods):
+    """Class to define a multibody system and form its equations of motion.
+
+    Explanation
+    ===========
+
+    A ``System`` instance stores the different objects associated with a model,
+    including bodies, joints, constraints, and other relevant information. With
+    all the relationships between components defined, the ``System`` can be used
+    to form the equations of motion using a backend, such as ``KanesMethod``.
+    The ``System`` has been designed to be compatible with third-party
+    libraries for greater flexibility and integration with other tools.
+
+    Attributes
+    ==========
+
+    frame : ReferenceFrame
+        Inertial reference frame of the system.
+    fixed_point : Point
+        A fixed point in the inertial reference frame.
+    x : Vector
+        Unit vector fixed in the inertial reference frame.
+    y : Vector
+        Unit vector fixed in the inertial reference frame.
+    z : Vector
+        Unit vector fixed in the inertial reference frame.
+    q : ImmutableMatrix
+        Matrix of all the generalized coordinates, i.e. the independent
+        generalized coordinates stacked upon the dependent.
+    u : ImmutableMatrix
+        Matrix of all the generalized speeds, i.e. the independent generealized
+        speeds stacked upon the dependent.
+    q_ind : ImmutableMatrix
+        Matrix of the independent generalized coordinates.
+    q_dep : ImmutableMatrix
+        Matrix of the dependent generalized coordinates.
+    u_ind : ImmutableMatrix
+        Matrix of the independent generalized speeds.
+    u_dep : ImmutableMatrix
+        Matrix of the dependent generalized speeds.
+    u_aux : ImmutableMatrix
+        Matrix of auxiliary generalized speeds.
+    kdes : ImmutableMatrix
+        Matrix of the kinematical differential equations as expressions equated
+        to the zero matrix.
+    bodies : tuple of BodyBase subclasses
+        Tuple of all bodies that make up the system.
+    joints : tuple of Joint
+        Tuple of all joints that connect bodies in the system.
+    loads : tuple of LoadBase subclasses
+        Tuple of all loads that have been applied to the system.
+    actuators : tuple of ActuatorBase subclasses
+        Tuple of all actuators present in the system.
+    holonomic_constraints : ImmutableMatrix
+        Matrix with the holonomic constraints as expressions equated to the zero
+        matrix.
+    nonholonomic_constraints : ImmutableMatrix
+        Matrix with the nonholonomic constraints as expressions equated to the
+        zero matrix.
+    velocity_constraints : ImmutableMatrix
+        Matrix with the velocity constraints as expressions equated to the zero
+        matrix. These are by default derived as the time derivatives of the
+        holonomic constraints extended with the nonholonomic constraints.
+    eom_method : subclass of KanesMethod or LagrangesMethod
+        Backend for forming the equations of motion.
+
+    Examples
+    ========
+
+    In the example below a cart with a pendulum is created. The cart moves along
+    the x axis of the rail and the pendulum rotates about the z axis. The length
+    of the pendulum is ``l`` with the pendulum represented as a particle. To
+    move the cart a time dependent force ``F`` is applied to the cart.
+
+    We first need to import some functions and create some of our variables.
+
+    >>> from sympy import symbols, simplify
+    >>> from sympy.physics.mechanics import (
+    ...     mechanics_printing, dynamicsymbols, RigidBody, Particle,
+    ...     ReferenceFrame, PrismaticJoint, PinJoint, System)
+    >>> mechanics_printing(pretty_print=False)
+    >>> g, l = symbols('g l')
+    >>> F = dynamicsymbols('F')
+
+    The next step is to create bodies. It is also useful to create a frame for
+    locating the particle with respect to the pin joint later on, as a particle
+    does not have a body-fixed frame.
+
+    >>> rail = RigidBody('rail')
+    >>> cart = RigidBody('cart')
+    >>> bob = Particle('bob')
+    >>> bob_frame = ReferenceFrame('bob_frame')
+
+    Initialize the system, with the rail as the Newtonian reference. The body is
+    also automatically added to the system.
+
+    >>> system = System.from_newtonian(rail)
+    >>> print(system.bodies[0])
+    rail
+
+    Create the joints, while immediately also adding them to the system.
+
+    >>> system.add_joints(
+    ...     PrismaticJoint('slider', rail, cart, joint_axis=rail.x),
+    ...     PinJoint('pin', cart, bob, joint_axis=cart.z,
+    ...              child_interframe=bob_frame,
+    ...              child_point=l * bob_frame.y)
+    ... )
+    >>> system.joints
+    (PrismaticJoint: slider  parent: rail  child: cart,
+    PinJoint: pin  parent: cart  child: bob)
+
+    While adding the joints, the associated generalized coordinates, generalized
+    speeds, kinematic differential equations and bodies are also added to the
+    system.
+
+    >>> system.q
+    Matrix([
+    [q_slider],
+    [   q_pin]])
+    >>> system.u
+    Matrix([
+    [u_slider],
+    [   u_pin]])
+    >>> system.kdes
+    Matrix([
+    [u_slider - q_slider'],
+    [      u_pin - q_pin']])
+    >>> [body.name for body in system.bodies]
+    ['rail', 'cart', 'bob']
+
+    With the kinematics established, we can now apply gravity and the cart force
+    ``F``.
+
+    >>> system.apply_uniform_gravity(-g * system.y)
+    >>> system.add_loads((cart.masscenter, F * rail.x))
+    >>> system.loads
+    ((rail_masscenter, - g*rail_mass*rail_frame.y),
+     (cart_masscenter, - cart_mass*g*rail_frame.y),
+     (bob_masscenter, - bob_mass*g*rail_frame.y),
+     (cart_masscenter, F*rail_frame.x))
+
+    With the entire system defined, we can now form the equations of motion.
+    Before forming the equations of motion, one can also run some checks that
+    will try to identify some common errors.
+
+    >>> system.validate_system()
+    >>> system.form_eoms()
+    Matrix([
+    [bob_mass*l*u_pin**2*sin(q_pin) - bob_mass*l*cos(q_pin)*u_pin'
+     - (bob_mass + cart_mass)*u_slider' + F],
+    [                   -bob_mass*g*l*sin(q_pin) - bob_mass*l**2*u_pin'
+     - bob_mass*l*cos(q_pin)*u_slider']])
+    >>> simplify(system.mass_matrix)
+    Matrix([
+    [ bob_mass + cart_mass, bob_mass*l*cos(q_pin)],
+    [bob_mass*l*cos(q_pin),         bob_mass*l**2]])
+    >>> system.forcing
+    Matrix([
+    [bob_mass*l*u_pin**2*sin(q_pin) + F],
+    [          -bob_mass*g*l*sin(q_pin)]])
+
+    The complexity of the above example can be increased if we add a constraint
+    to prevent the particle from moving in the horizontal (x) direction. This
+    can be done by adding a holonomic constraint. After which we should also
+    redefine what our (in)dependent generalized coordinates and speeds are.
+
+    >>> system.add_holonomic_constraints(
+    ...     bob.masscenter.pos_from(rail.masscenter).dot(system.x)
+    ... )
+    >>> system.q_ind = system.get_joint('pin').coordinates
+    >>> system.q_dep = system.get_joint('slider').coordinates
+    >>> system.u_ind = system.get_joint('pin').speeds
+    >>> system.u_dep = system.get_joint('slider').speeds
+
+    With the updated system the equations of motion can be formed again.
+
+    >>> system.validate_system()
+    >>> system.form_eoms()
+    Matrix([[-bob_mass*g*l*sin(q_pin)
+             - bob_mass*l**2*u_pin'
+             - bob_mass*l*cos(q_pin)*u_slider'
+             - l*(bob_mass*l*u_pin**2*sin(q_pin)
+             - bob_mass*l*cos(q_pin)*u_pin'
+             - (bob_mass + cart_mass)*u_slider')*cos(q_pin)
+             - l*F*cos(q_pin)]])
+    >>> simplify(system.mass_matrix)
+    Matrix([
+    [bob_mass*l**2*sin(q_pin)**2, -cart_mass*l*cos(q_pin)],
+    [               l*cos(q_pin),                       1]])
+    >>> simplify(system.forcing)
+    Matrix([
+    [-l*(bob_mass*g*sin(q_pin) + bob_mass*l*u_pin**2*sin(2*q_pin)/2
+     + F*cos(q_pin))],
+    [
+    l*u_pin**2*sin(q_pin)]])
+
+    """
+
+    def __init__(self, frame=None, fixed_point=None):
+        """Initialize the system.
+
+        Parameters
+        ==========
+
+        frame : ReferenceFrame, optional
+            The inertial frame of the system. If none is supplied, a new frame
+            will be created.
+        fixed_point : Point, optional
+            A fixed point in the inertial reference frame. If none is supplied,
+            a new fixed_point will be created.
+
+        """
+        if frame is None:
+            frame = ReferenceFrame('inertial_frame')
+        elif not isinstance(frame, ReferenceFrame):
+            raise TypeError('Frame must be an instance of ReferenceFrame.')
+        self._frame = frame
+        if fixed_point is None:
+            fixed_point = Point('inertial_point')
+        elif not isinstance(fixed_point, Point):
+            raise TypeError('Fixed point must be an instance of Point.')
+        self._fixed_point = fixed_point
+        self._fixed_point.set_vel(self._frame, 0)
+        self._q_ind = ImmutableMatrix(1, 0, []).T
+        self._q_dep = ImmutableMatrix(1, 0, []).T
+        self._u_ind = ImmutableMatrix(1, 0, []).T
+        self._u_dep = ImmutableMatrix(1, 0, []).T
+        self._u_aux = ImmutableMatrix(1, 0, []).T
+        self._kdes = ImmutableMatrix(1, 0, []).T
+        self._hol_coneqs = ImmutableMatrix(1, 0, []).T
+        self._nonhol_coneqs = ImmutableMatrix(1, 0, []).T
+        self._vel_constrs = None
+        self._bodies = []
+        self._joints = []
+        self._loads = []
+        self._actuators = []
+        self._eom_method = None
+
+    @classmethod
+    def from_newtonian(cls, newtonian):
+        """Constructs the system with respect to a Newtonian body."""
+        if isinstance(newtonian, Particle):
+            raise TypeError('A Particle has no frame so cannot act as '
+                            'the Newtonian.')
+        system = cls(frame=newtonian.frame, fixed_point=newtonian.masscenter)
+        system.add_bodies(newtonian)
+        return system
+
+    @property
+    def fixed_point(self):
+        """Fixed point in the inertial reference frame."""
+        return self._fixed_point
+
+    @property
+    def frame(self):
+        """Inertial reference frame of the system."""
+        return self._frame
+
+    @property
+    def x(self):
+        """Unit vector fixed in the inertial reference frame."""
+        return self._frame.x
+
+    @property
+    def y(self):
+        """Unit vector fixed in the inertial reference frame."""
+        return self._frame.y
+
+    @property
+    def z(self):
+        """Unit vector fixed in the inertial reference frame."""
+        return self._frame.z
+
+    @property
+    def bodies(self):
+        """Tuple of all bodies that have been added to the system."""
+        return tuple(self._bodies)
+
+    @bodies.setter
+    @_reset_eom_method
+    def bodies(self, bodies):
+        bodies = self._objects_to_list(bodies)
+        self._check_objects(bodies, [], BodyBase, 'Bodies', 'bodies')
+        self._bodies = bodies
+
+    @property
+    def joints(self):
+        """Tuple of all joints that have been added to the system."""
+        return tuple(self._joints)
+
+    @joints.setter
+    @_reset_eom_method
+    def joints(self, joints):
+        joints = self._objects_to_list(joints)
+        self._check_objects(joints, [], Joint, 'Joints', 'joints')
+        self._joints = []
+        self.add_joints(*joints)
+
+    @property
+    def loads(self):
+        """Tuple of loads that have been applied on the system."""
+        return tuple(self._loads)
+
+    @loads.setter
+    @_reset_eom_method
+    def loads(self, loads):
+        loads = self._objects_to_list(loads)
+        self._loads = [_parse_load(load) for load in loads]
+
+    @property
+    def actuators(self):
+        """Tuple of actuators present in the system."""
+        return tuple(self._actuators)
+
+    @actuators.setter
+    @_reset_eom_method
+    def actuators(self, actuators):
+        actuators = self._objects_to_list(actuators)
+        self._check_objects(actuators, [], ActuatorBase, 'Actuators',
+                            'actuators')
+        self._actuators = actuators
+
+    @property
+    def q(self):
+        """Matrix of all the generalized coordinates with the independent
+        stacked upon the dependent."""
+        return self._q_ind.col_join(self._q_dep)
+
+    @property
+    def u(self):
+        """Matrix of all the generalized speeds with the independent stacked
+        upon the dependent."""
+        return self._u_ind.col_join(self._u_dep)
+
+    @property
+    def q_ind(self):
+        """Matrix of the independent generalized coordinates."""
+        return self._q_ind
+
+    @q_ind.setter
+    @_reset_eom_method
+    def q_ind(self, q_ind):
+        self._q_ind, self._q_dep = self._parse_coordinates(
+            self._objects_to_list(q_ind), True, [], self.q_dep, 'coordinates')
+
+    @property
+    def q_dep(self):
+        """Matrix of the dependent generalized coordinates."""
+        return self._q_dep
+
+    @q_dep.setter
+    @_reset_eom_method
+    def q_dep(self, q_dep):
+        self._q_ind, self._q_dep = self._parse_coordinates(
+            self._objects_to_list(q_dep), False, self.q_ind, [], 'coordinates')
+
+    @property
+    def u_ind(self):
+        """Matrix of the independent generalized speeds."""
+        return self._u_ind
+
+    @u_ind.setter
+    @_reset_eom_method
+    def u_ind(self, u_ind):
+        self._u_ind, self._u_dep = self._parse_coordinates(
+            self._objects_to_list(u_ind), True, [], self.u_dep, 'speeds')
+
+    @property
+    def u_dep(self):
+        """Matrix of the dependent generalized speeds."""
+        return self._u_dep
+
+    @u_dep.setter
+    @_reset_eom_method
+    def u_dep(self, u_dep):
+        self._u_ind, self._u_dep = self._parse_coordinates(
+            self._objects_to_list(u_dep), False, self.u_ind, [], 'speeds')
+
+    @property
+    def u_aux(self):
+        """Matrix of auxiliary generalized speeds."""
+        return self._u_aux
+
+    @u_aux.setter
+    @_reset_eom_method
+    def u_aux(self, u_aux):
+        self._u_aux = self._parse_coordinates(
+            self._objects_to_list(u_aux), True, [], [], 'u_auxiliary')[0]
+
+    @property
+    def kdes(self):
+        """Kinematical differential equations as expressions equated to the zero
+        matrix. These equations describe the coupling between the generalized
+        coordinates and the generalized speeds."""
+        return self._kdes
+
+    @kdes.setter
+    @_reset_eom_method
+    def kdes(self, kdes):
+        kdes = self._objects_to_list(kdes)
+        self._kdes = self._parse_expressions(
+            kdes, [], 'kinematic differential equations')
+
+    @property
+    def holonomic_constraints(self):
+        """Matrix with the holonomic constraints as expressions equated to the
+        zero matrix."""
+        return self._hol_coneqs
+
+    @holonomic_constraints.setter
+    @_reset_eom_method
+    def holonomic_constraints(self, constraints):
+        constraints = self._objects_to_list(constraints)
+        self._hol_coneqs = self._parse_expressions(
+            constraints, [], 'holonomic constraints')
+
+    @property
+    def nonholonomic_constraints(self):
+        """Matrix with the nonholonomic constraints as expressions equated to
+        the zero matrix."""
+        return self._nonhol_coneqs
+
+    @nonholonomic_constraints.setter
+    @_reset_eom_method
+    def nonholonomic_constraints(self, constraints):
+        constraints = self._objects_to_list(constraints)
+        self._nonhol_coneqs = self._parse_expressions(
+            constraints, [], 'nonholonomic constraints')
+
+    @property
+    def velocity_constraints(self):
+        """Matrix with the velocity constraints as expressions equated to the
+        zero matrix. The velocity constraints are by default derived from the
+        holonomic and nonholonomic constraints unless they are explicitly set.
+        """
+        if self._vel_constrs is None:
+            return self.holonomic_constraints.diff(dynamicsymbols._t).col_join(
+                self.nonholonomic_constraints)
+        return self._vel_constrs
+
+    @velocity_constraints.setter
+    @_reset_eom_method
+    def velocity_constraints(self, constraints):
+        if constraints is None:
+            self._vel_constrs = None
+            return
+        constraints = self._objects_to_list(constraints)
+        self._vel_constrs = self._parse_expressions(
+            constraints, [], 'velocity constraints')
+
+    @property
+    def eom_method(self):
+        """Backend for forming the equations of motion."""
+        return self._eom_method
+
+    @staticmethod
+    def _objects_to_list(lst):
+        """Helper to convert passed objects to a list."""
+        if not iterable(lst):  # Only one object
+            return [lst]
+        return list(lst[:])  # converts Matrix and tuple to flattened list
+
+    @staticmethod
+    def _check_objects(objects, obj_lst, expected_type, obj_name, type_name):
+        """Helper to check the objects that are being added to the system.
+
+        Explanation
+        ===========
+        This method checks that the objects that are being added to the system
+        are of the correct type and have not already been added. If any of the
+        objects are not of the correct type or have already been added, then
+        an error is raised.
+
+        Parameters
+        ==========
+        objects : iterable
+            The objects that would be added to the system.
+        obj_lst : list
+            The list of objects that are already in the system.
+        expected_type : type
+            The type that the objects should be.
+        obj_name : str
+            The name of the category of objects. This string is used to
+            formulate the error message for the user.
+        type_name : str
+            The name of the type that the objects should be. This string is used
+            to formulate the error message for the user.
+
+        """
+        seen = set(obj_lst)
+        duplicates = set()
+        wrong_types = set()
+        for obj in objects:
+            if not isinstance(obj, expected_type):
+                wrong_types.add(obj)
+            if obj in seen:
+                duplicates.add(obj)
+            else:
+                seen.add(obj)
+        if wrong_types:
+            raise TypeError(f'{obj_name} {wrong_types} are not {type_name}.')
+        if duplicates:
+            raise ValueError(f'{obj_name} {duplicates} have already been added '
+                             f'to the system.')
+
+    def _parse_coordinates(self, new_coords, independent, old_coords_ind,
+                           old_coords_dep, coord_type='coordinates'):
+        """Helper to parse coordinates and speeds."""
+        # Construct lists of the independent and dependent coordinates
+        coords_ind, coords_dep = old_coords_ind[:], old_coords_dep[:]
+        if not iterable(independent):
+            independent = [independent] * len(new_coords)
+        for coord, indep in zip(new_coords, independent):
+            if indep:
+                coords_ind.append(coord)
+            else:
+                coords_dep.append(coord)
+        # Check types and duplicates
+        current = {'coordinates': self.q_ind[:] + self.q_dep[:],
+                   'speeds': self.u_ind[:] + self.u_dep[:],
+                   'u_auxiliary': self._u_aux[:],
+                   coord_type: coords_ind + coords_dep}
+        _validate_coordinates(**current)
+        return (ImmutableMatrix(1, len(coords_ind), coords_ind).T,
+                ImmutableMatrix(1, len(coords_dep), coords_dep).T)
+
+    @staticmethod
+    def _parse_expressions(new_expressions, old_expressions, name,
+                           check_negatives=False):
+        """Helper to parse expressions like constraints."""
+        old_expressions = old_expressions[:]
+        new_expressions = list(new_expressions)  # Converts a possible tuple
+        if check_negatives:
+            check_exprs = old_expressions + [-expr for expr in old_expressions]
+        else:
+            check_exprs = old_expressions
+        System._check_objects(new_expressions, check_exprs, Basic, name,
+                              'expressions')
+        for expr in new_expressions:
+            if expr == 0:
+                raise ValueError(f'Parsed {name} are zero.')
+        return ImmutableMatrix(1, len(old_expressions) + len(new_expressions),
+                               old_expressions + new_expressions).T
+
+    @_reset_eom_method
+    def add_coordinates(self, *coordinates, independent=True):
+        """Add generalized coordinate(s) to the system.
+
+        Parameters
+        ==========
+
+        *coordinates : dynamicsymbols
+            One or more generalized coordinates to be added to the system.
+        independent : bool or list of bool, optional
+            Boolean whether a coordinate is dependent or independent. The
+            default is True, so the coordinates are added as independent by
+            default.
+
+        """
+        self._q_ind, self._q_dep = self._parse_coordinates(
+            coordinates, independent, self.q_ind, self.q_dep, 'coordinates')
+
+    @_reset_eom_method
+    def add_speeds(self, *speeds, independent=True):
+        """Add generalized speed(s) to the system.
+
+        Parameters
+        ==========
+
+        *speeds : dynamicsymbols
+            One or more generalized speeds to be added to the system.
+        independent : bool or list of bool, optional
+            Boolean whether a speed is dependent or independent. The default is
+            True, so the speeds are added as independent by default.
+
+        """
+        self._u_ind, self._u_dep = self._parse_coordinates(
+            speeds, independent, self.u_ind, self.u_dep, 'speeds')
+
+    @_reset_eom_method
+    def add_auxiliary_speeds(self, *speeds):
+        """Add auxiliary speed(s) to the system.
+
+        Parameters
+        ==========
+
+        *speeds : dynamicsymbols
+            One or more auxiliary speeds to be added to the system.
+
+        """
+        self._u_aux = self._parse_coordinates(
+            speeds, True, self._u_aux, [], 'u_auxiliary')[0]
+
+    @_reset_eom_method
+    def add_kdes(self, *kdes):
+        """Add kinematic differential equation(s) to the system.
+
+        Parameters
+        ==========
+
+        *kdes : Expr
+            One or more kinematic differential equations.
+
+        """
+        self._kdes = self._parse_expressions(
+            kdes, self.kdes, 'kinematic differential equations',
+            check_negatives=True)
+
+    @_reset_eom_method
+    def add_holonomic_constraints(self, *constraints):
+        """Add holonomic constraint(s) to the system.
+
+        Parameters
+        ==========
+
+        *constraints : Expr
+            One or more holonomic constraints, which are expressions that should
+            be zero.
+
+        """
+        self._hol_coneqs = self._parse_expressions(
+            constraints, self._hol_coneqs, 'holonomic constraints',
+            check_negatives=True)
+
+    @_reset_eom_method
+    def add_nonholonomic_constraints(self, *constraints):
+        """Add nonholonomic constraint(s) to the system.
+
+        Parameters
+        ==========
+
+        *constraints : Expr
+            One or more nonholonomic constraints, which are expressions that
+            should be zero.
+
+        """
+        self._nonhol_coneqs = self._parse_expressions(
+            constraints, self._nonhol_coneqs, 'nonholonomic constraints',
+            check_negatives=True)
+
+    @_reset_eom_method
+    def add_bodies(self, *bodies):
+        """Add body(ies) to the system.
+
+        Parameters
+        ==========
+
+        bodies : Particle or RigidBody
+            One or more bodies.
+
+        """
+        self._check_objects(bodies, self.bodies, BodyBase, 'Bodies', 'bodies')
+        self._bodies.extend(bodies)
+
+    @_reset_eom_method
+    def add_loads(self, *loads):
+        """Add load(s) to the system.
+
+        Parameters
+        ==========
+
+        *loads : Force or Torque
+            One or more loads.
+
+        """
+        loads = [_parse_load(load) for load in loads]  # Checks the loads
+        self._loads.extend(loads)
+
+    @_reset_eom_method
+    def apply_uniform_gravity(self, acceleration):
+        """Apply uniform gravity to all bodies in the system by adding loads.
+
+        Parameters
+        ==========
+
+        acceleration : Vector
+            The acceleration due to gravity.
+
+        """
+        self.add_loads(*gravity(acceleration, *self.bodies))
+
+    @_reset_eom_method
+    def add_actuators(self, *actuators):
+        """Add actuator(s) to the system.
+
+        Parameters
+        ==========
+
+        *actuators : subclass of ActuatorBase
+            One or more actuators.
+
+        """
+        self._check_objects(actuators, self.actuators, ActuatorBase,
+                            'Actuators', 'actuators')
+        self._actuators.extend(actuators)
+
+    @_reset_eom_method
+    def add_joints(self, *joints):
+        """Add joint(s) to the system.
+
+        Explanation
+        ===========
+
+        This methods adds one or more joints to the system including its
+        associated objects, i.e. generalized coordinates, generalized speeds,
+        kinematic differential equations and the bodies.
+
+        Parameters
+        ==========
+
+        *joints : subclass of Joint
+            One or more joints.
+
+        Notes
+        =====
+
+        For the generalized coordinates, generalized speeds and bodies it is
+        checked whether they are already known by the system instance. If they
+        are, then they are not added. The kinematic differential equations are
+        however always added to the system, so you should not also manually add
+        those on beforehand.
+
+        """
+        self._check_objects(joints, self.joints, Joint, 'Joints', 'joints')
+        self._joints.extend(joints)
+        coordinates, speeds, kdes, bodies = (OrderedSet() for _ in range(4))
+        for joint in joints:
+            coordinates.update(joint.coordinates)
+            speeds.update(joint.speeds)
+            kdes.update(joint.kdes)
+            bodies.update((joint.parent, joint.child))
+        coordinates = coordinates.difference(self.q)
+        speeds = speeds.difference(self.u)
+        kdes = kdes.difference(self.kdes[:] + (-self.kdes)[:])
+        bodies = bodies.difference(self.bodies)
+        self.add_coordinates(*tuple(coordinates))
+        self.add_speeds(*tuple(speeds))
+        self.add_kdes(*(kde for kde in tuple(kdes) if not kde == 0))
+        self.add_bodies(*tuple(bodies))
+
+    def get_body(self, name):
+        """Retrieve a body from the system by name.
+
+        Parameters
+        ==========
+
+        name : str
+            The name of the body to retrieve.
+
+        Returns
+        =======
+
+        RigidBody or Particle
+            The body with the given name, or None if no such body exists.
+
+        """
+        for body in self._bodies:
+            if body.name == name:
+                return body
+
+    def get_joint(self, name):
+        """Retrieve a joint from the system by name.
+
+        Parameters
+        ==========
+
+        name : str
+            The name of the joint to retrieve.
+
+        Returns
+        =======
+
+        subclass of Joint
+            The joint with the given name, or None if no such joint exists.
+
+        """
+        for joint in self._joints:
+            if joint.name == name:
+                return joint
+
+    def _form_eoms(self):
+        return self.form_eoms()
+
+    def form_eoms(self, eom_method=KanesMethod, **kwargs):
+        """Form the equations of motion of the system.
+
+        Parameters
+        ==========
+
+        eom_method : subclass of KanesMethod or LagrangesMethod
+            Backend class to be used for forming the equations of motion. The
+            default is ``KanesMethod``.
+
+        Returns
+        ========
+
+        ImmutableMatrix
+            Vector of equations of motions.
+
+        Examples
+        ========
+
+        This is a simple example for a one degree of freedom translational
+        spring-mass-damper.
+
+        >>> from sympy import S, symbols
+        >>> from sympy.physics.mechanics import (
+        ...     LagrangesMethod, dynamicsymbols, PrismaticJoint, Particle,
+        ...     RigidBody, System)
+        >>> q = dynamicsymbols('q')
+        >>> qd = dynamicsymbols('q', 1)
+        >>> m, k, b = symbols('m k b')
+        >>> wall = RigidBody('W')
+        >>> system = System.from_newtonian(wall)
+        >>> bob = Particle('P', mass=m)
+        >>> bob.potential_energy = S.Half * k * q**2
+        >>> system.add_joints(PrismaticJoint('J', wall, bob, q, qd))
+        >>> system.add_loads((bob.masscenter, b * qd * system.x))
+        >>> system.form_eoms(LagrangesMethod)
+        Matrix([[-b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
+
+        We can also solve for the states using the 'rhs' method.
+
+        >>> system.rhs()
+        Matrix([
+        [               Derivative(q(t), t)],
+        [(b*Derivative(q(t), t) - k*q(t))/m]])
+
+        """
+        # KanesMethod does not accept empty iterables
+        loads = self.loads + tuple(
+            load for act in self.actuators for load in act.to_loads())
+        loads = loads if loads else None
+        if issubclass(eom_method, KanesMethod):
+            disallowed_kwargs = {
+                "frame", "q_ind", "u_ind", "kd_eqs", "q_dependent",
+                "u_dependent", "u_auxiliary", "configuration_constraints",
+                "velocity_constraints", "forcelist", "bodies"}
+            wrong_kwargs = disallowed_kwargs.intersection(kwargs)
+            if wrong_kwargs:
+                raise ValueError(
+                    f"The following keyword arguments are not allowed to be "
+                    f"overwritten in {eom_method.__name__}: {wrong_kwargs}.")
+            kwargs = {"frame": self.frame, "q_ind": self.q_ind,
+                      "u_ind": self.u_ind, "kd_eqs": self.kdes,
+                      "q_dependent": self.q_dep, "u_dependent": self.u_dep,
+                      "configuration_constraints": self.holonomic_constraints,
+                      "velocity_constraints": self.velocity_constraints,
+                      "u_auxiliary": self.u_aux,
+                      "forcelist": loads, "bodies": self.bodies,
+                      "explicit_kinematics": False, **kwargs}
+            self._eom_method = eom_method(**kwargs)
+        elif issubclass(eom_method, LagrangesMethod):
+            disallowed_kwargs = {
+                "frame", "qs", "forcelist", "bodies", "hol_coneqs",
+                "nonhol_coneqs", "Lagrangian"}
+            wrong_kwargs = disallowed_kwargs.intersection(kwargs)
+            if wrong_kwargs:
+                raise ValueError(
+                    f"The following keyword arguments are not allowed to be "
+                    f"overwritten in {eom_method.__name__}: {wrong_kwargs}.")
+            kwargs = {"frame": self.frame, "qs": self.q, "forcelist": loads,
+                      "bodies": self.bodies,
+                      "hol_coneqs": self.holonomic_constraints,
+                      "nonhol_coneqs": self.nonholonomic_constraints, **kwargs}
+            if "Lagrangian" not in kwargs:
+                kwargs["Lagrangian"] = Lagrangian(kwargs["frame"],
+                                                  *kwargs["bodies"])
+            self._eom_method = eom_method(**kwargs)
+        else:
+            raise NotImplementedError(f'{eom_method} has not been implemented.')
+        return self.eom_method._form_eoms()
+
+    def rhs(self, inv_method=None):
+        """Compute the equations of motion in the explicit form.
+
+        Parameters
+        ==========
+
+        inv_method : str
+            The specific sympy inverse matrix calculation method to use. For a
+            list of valid methods, see
+            :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
+
+        Returns
+        ========
+
+        ImmutableMatrix
+            Equations of motion in the explicit form.
+
+        See Also
+        ========
+
+        sympy.physics.mechanics.kane.KanesMethod.rhs:
+            KanesMethod's ``rhs`` function.
+        sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
+            LagrangesMethod's ``rhs`` function.
+
+        """
+        return self.eom_method.rhs(inv_method=inv_method)
+
+    @property
+    def mass_matrix(self):
+        r"""The mass matrix of the system.
+
+        Explanation
+        ===========
+
+        The mass matrix $M_d$ and the forcing vector $f_d$ of a system describe
+        the system's dynamics according to the following equations:
+
+        .. math::
+            M_d \dot{u} = f_d
+
+        where $\dot{u}$ is the time derivative of the generalized speeds.
+
+        """
+        return self.eom_method.mass_matrix
+
+    @property
+    def mass_matrix_full(self):
+        r"""The mass matrix of the system, augmented by the kinematic
+        differential equations in explicit or implicit form.
+
+        Explanation
+        ===========
+
+        The full mass matrix $M_m$ and the full forcing vector $f_m$ of a system
+        describe the dynamics and kinematics according to the following
+        equation:
+
+        .. math::
+            M_m \dot{x} = f_m
+
+        where $x$ is the state vector stacking $q$ and $u$.
+
+        """
+        return self.eom_method.mass_matrix_full
+
+    @property
+    def forcing(self):
+        """The forcing vector of the system."""
+        return self.eom_method.forcing
+
+    @property
+    def forcing_full(self):
+        """The forcing vector of the system, augmented by the kinematic
+        differential equations in explicit or implicit form."""
+        return self.eom_method.forcing_full
+
+    def validate_system(self, eom_method=KanesMethod, check_duplicates=False):
+        """Validates the system using some basic checks.
+
+        Explanation
+        ===========
+
+        This method validates the system based on the following checks:
+
+        - The number of dependent generalized coordinates should equal the
+          number of holonomic constraints.
+        - All generalized coordinates defined by the joints should also be known
+          to the system.
+        - If ``KanesMethod`` is used as a ``eom_method``:
+            - All generalized speeds and kinematic differential equations
+              defined by the joints should also be known to the system.
+            - The number of dependent generalized speeds should equal the number
+              of velocity constraints.
+            - The number of generalized coordinates should be less than or equal
+              to the number of generalized speeds.
+            - The number of generalized coordinates should equal the number of
+              kinematic differential equations.
+        - If ``LagrangesMethod`` is used as ``eom_method``:
+            - There should not be any generalized speeds that are not
+              derivatives of the generalized coordinates (this includes the
+              generalized speeds defined by the joints).
+
+        Parameters
+        ==========
+
+        eom_method : subclass of KanesMethod or LagrangesMethod
+            Backend class that will be used for forming the equations of motion.
+            There are different checks for the different backends. The default
+            is ``KanesMethod``.
+        check_duplicates : bool
+            Boolean whether the system should be checked for duplicate
+            definitions. The default is False, because duplicates are already
+            checked when adding objects to the system.
+
+        Notes
+        =====
+
+        This method is not guaranteed to be backwards compatible as it may
+        improve over time. The method can become both more and less strict in
+        certain areas. However a well-defined system should always pass all
+        these tests.
+
+        """
+        msgs = []
+        # Save some data in variables
+        n_hc = self.holonomic_constraints.shape[0]
+        n_vc = self.velocity_constraints.shape[0]
+        n_q_dep, n_u_dep = self.q_dep.shape[0], self.u_dep.shape[0]
+        q_set, u_set = set(self.q), set(self.u)
+        n_q, n_u = len(q_set), len(u_set)
+        # Check number of holonomic constraints
+        if n_q_dep != n_hc:
+            msgs.append(filldedent(f"""
+            The number of dependent generalized coordinates {n_q_dep} should be
+            equal to the number of holonomic constraints {n_hc}."""))
+        # Check if all joint coordinates and speeds are present
+        missing_q = set()
+        for joint in self.joints:
+            missing_q.update(set(joint.coordinates).difference(q_set))
+        if missing_q:
+            msgs.append(filldedent(f"""
+            The generalized coordinates {missing_q} used in joints are not added
+            to the system."""))
+        # Method dependent checks
+        if issubclass(eom_method, KanesMethod):
+            n_kdes = len(self.kdes)
+            missing_kdes, missing_u = set(), set()
+            for joint in self.joints:
+                missing_u.update(set(joint.speeds).difference(u_set))
+                missing_kdes.update(set(joint.kdes).difference(
+                    self.kdes[:] + (-self.kdes)[:]))
+            if missing_u:
+                msgs.append(filldedent(f"""
+                The generalized speeds {missing_u} used in joints are not added
+                to the system."""))
+            if missing_kdes:
+                msgs.append(filldedent(f"""
+                The kinematic differential equations {missing_kdes} used in
+                joints are not added to the system."""))
+            if n_u_dep != n_vc:
+                msgs.append(filldedent(f"""
+                The number of dependent generalized speeds {n_u_dep} should be
+                equal to the number of velocity constraints {n_vc}."""))
+            if n_q > n_u:
+                msgs.append(filldedent(f"""
+                The number of generalized coordinates {n_q} should be less than
+                or equal to the number of generalized speeds {n_u}."""))
+            if n_u != n_kdes:
+                msgs.append(filldedent(f"""
+                The number of generalized speeds {n_u} should be equal to the
+                number of kinematic differential equations {n_kdes}."""))
+        elif issubclass(eom_method, LagrangesMethod):
+            not_qdots = set(self.u).difference(self.q.diff(dynamicsymbols._t))
+            for joint in self.joints:
+                not_qdots.update(set(
+                    joint.speeds).difference(self.q.diff(dynamicsymbols._t)))
+            if not_qdots:
+                msgs.append(filldedent(f"""
+                The generalized speeds {not_qdots} are not supported by this
+                method. Only derivatives of the generalized coordinates are
+                supported. If these symbols are used in your expressions, then
+                this will result in wrong equations of motion."""))
+            if self.u_aux:
+                msgs.append(filldedent(f"""
+                This method does not support auxiliary speeds. If these symbols
+                are used in your expressions, then this will result in wrong
+                equations of motion. The auxiliary speeds are {self.u_aux}."""))
+        else:
+            raise NotImplementedError(f'{eom_method} has not been implemented.')
+        if check_duplicates:  # Should be redundant
+            duplicates_to_check = [('generalized coordinates', self.q),
+                                   ('generalized speeds', self.u),
+                                   ('auxiliary speeds', self.u_aux),
+                                   ('bodies', self.bodies),
+                                   ('joints', self.joints)]
+            for name, lst in duplicates_to_check:
+                seen = set()
+                duplicates = {x for x in lst if x in seen or seen.add(x)}
+                if duplicates:
+                    msgs.append(filldedent(f"""
+                    The {name} {duplicates} exist multiple times within the
+                    system."""))
+        if msgs:
+            raise ValueError('\n'.join(msgs))
+
+
+class SymbolicSystem:
+    """SymbolicSystem is a class that contains all the information about a
+    system in a symbolic format such as the equations of motions and the bodies
+    and loads in the system.
+
+    There are three ways that the equations of motion can be described for
+    Symbolic System:
+
+
+        [1] Explicit form where the kinematics and dynamics are combined
+            x' = F_1(x, t, r, p)
+
+        [2] Implicit form where the kinematics and dynamics are combined
+            M_2(x, p) x' = F_2(x, t, r, p)
+
+        [3] Implicit form where the kinematics and dynamics are separate
+            M_3(q, p) u' = F_3(q, u, t, r, p)
+            q' = G(q, u, t, r, p)
+
+    where
+
+    x : states, e.g. [q, u]
+    t : time
+    r : specified (exogenous) inputs
+    p : constants
+    q : generalized coordinates
+    u : generalized speeds
+    F_1 : right hand side of the combined equations in explicit form
+    F_2 : right hand side of the combined equations in implicit form
+    F_3 : right hand side of the dynamical equations in implicit form
+    M_2 : mass matrix of the combined equations in implicit form
+    M_3 : mass matrix of the dynamical equations in implicit form
+    G : right hand side of the kinematical differential equations
+
+        Parameters
+        ==========
+
+        coord_states : ordered iterable of functions of time
+            This input will either be a collection of the coordinates or states
+            of the system depending on whether or not the speeds are also
+            given. If speeds are specified this input will be assumed to
+            be the coordinates otherwise this input will be assumed to
+            be the states.
+
+        right_hand_side : Matrix
+            This variable is the right hand side of the equations of motion in
+            any of the forms. The specific form will be assumed depending on
+            whether a mass matrix or coordinate derivatives are given.
+
+        speeds : ordered iterable of functions of time, optional
+            This is a collection of the generalized speeds of the system. If
+            given it will be assumed that the first argument (coord_states)
+            will represent the generalized coordinates of the system.
+
+        mass_matrix : Matrix, optional
+            The matrix of the implicit forms of the equations of motion (forms
+            [2] and [3]). The distinction between the forms is determined by
+            whether or not the coordinate derivatives are passed in. If
+            they are given form [3] will be assumed otherwise form [2] is
+            assumed.
+
+        coordinate_derivatives : Matrix, optional
+            The right hand side of the kinematical equations in explicit form.
+            If given it will be assumed that the equations of motion are being
+            entered in form [3].
+
+        alg_con : Iterable, optional
+            The indexes of the rows in the equations of motion that contain
+            algebraic constraints instead of differential equations. If the
+            equations are input in form [3], it will be assumed the indexes are
+            referencing the mass_matrix/right_hand_side combination and not the
+            coordinate_derivatives.
+
+        output_eqns : Dictionary, optional
+            Any output equations that are desired to be tracked are stored in a
+            dictionary where the key corresponds to the name given for the
+            specific equation and the value is the equation itself in symbolic
+            form
+
+        coord_idxs : Iterable, optional
+            If coord_states corresponds to the states rather than the
+            coordinates this variable will tell SymbolicSystem which indexes of
+            the states correspond to generalized coordinates.
+
+        speed_idxs : Iterable, optional
+            If coord_states corresponds to the states rather than the
+            coordinates this variable will tell SymbolicSystem which indexes of
+            the states correspond to generalized speeds.
+
+        bodies : iterable of Body/Rigidbody objects, optional
+            Iterable containing the bodies of the system
+
+        loads : iterable of load instances (described below), optional
+            Iterable containing the loads of the system where forces are given
+            by (point of application, force vector) and torques are given by
+            (reference frame acting upon, torque vector). Ex [(point, force),
+            (ref_frame, torque)]
+
+    Attributes
+    ==========
+
+    coordinates : Matrix, shape(n, 1)
+        This is a matrix containing the generalized coordinates of the system
+
+    speeds : Matrix, shape(m, 1)
+        This is a matrix containing the generalized speeds of the system
+
+    states : Matrix, shape(o, 1)
+        This is a matrix containing the state variables of the system
+
+    alg_con : List
+        This list contains the indices of the algebraic constraints in the
+        combined equations of motion. The presence of these constraints
+        requires that a DAE solver be used instead of an ODE solver.
+        If the system is given in form [3] the alg_con variable will be
+        adjusted such that it is a representation of the combined kinematics
+        and dynamics thus make sure it always matches the mass matrix
+        entered.
+
+    dyn_implicit_mat : Matrix, shape(m, m)
+        This is the M matrix in form [3] of the equations of motion (the mass
+        matrix or generalized inertia matrix of the dynamical equations of
+        motion in implicit form).
+
+    dyn_implicit_rhs : Matrix, shape(m, 1)
+        This is the F vector in form [3] of the equations of motion (the right
+        hand side of the dynamical equations of motion in implicit form).
+
+    comb_implicit_mat : Matrix, shape(o, o)
+        This is the M matrix in form [2] of the equations of motion.
+        This matrix contains a block diagonal structure where the top
+        left block (the first rows) represent the matrix in the
+        implicit form of the kinematical equations and the bottom right
+        block (the last rows) represent the matrix in the implicit form
+        of the dynamical equations.
+
+    comb_implicit_rhs : Matrix, shape(o, 1)
+        This is the F vector in form [2] of the equations of motion. The top
+        part of the vector represents the right hand side of the implicit form
+        of the kinemaical equations and the bottom of the vector represents the
+        right hand side of the implicit form of the dynamical equations of
+        motion.
+
+    comb_explicit_rhs : Matrix, shape(o, 1)
+        This vector represents the right hand side of the combined equations of
+        motion in explicit form (form [1] from above).
+
+    kin_explicit_rhs : Matrix, shape(m, 1)
+        This is the right hand side of the explicit form of the kinematical
+        equations of motion as can be seen in form [3] (the G matrix).
+
+    output_eqns : Dictionary
+        If output equations were given they are stored in a dictionary where
+        the key corresponds to the name given for the specific equation and
+        the value is the equation itself in symbolic form
+
+    bodies : Tuple
+        If the bodies in the system were given they are stored in a tuple for
+        future access
+
+    loads : Tuple
+        If the loads in the system were given they are stored in a tuple for
+        future access. This includes forces and torques where forces are given
+        by (point of application, force vector) and torques are given by
+        (reference frame acted upon, torque vector).
+
+    Example
+    =======
+
+    As a simple example, the dynamics of a simple pendulum will be input into a
+    SymbolicSystem object manually. First some imports will be needed and then
+    symbols will be set up for the length of the pendulum (l), mass at the end
+    of the pendulum (m), and a constant for gravity (g). ::
+
+        >>> from sympy import Matrix, sin, symbols
+        >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem
+        >>> l, m, g = symbols('l m g')
+
+    The system will be defined by an angle of theta from the vertical and a
+    generalized speed of omega will be used where omega = theta_dot. ::
+
+        >>> theta, omega = dynamicsymbols('theta omega')
+
+    Now the equations of motion are ready to be formed and passed to the
+    SymbolicSystem object. ::
+
+        >>> kin_explicit_rhs = Matrix([omega])
+        >>> dyn_implicit_mat = Matrix([l**2 * m])
+        >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)])
+        >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega],
+        ...                            dyn_implicit_mat)
+
+    Notes
+    =====
+
+    m : number of generalized speeds
+    n : number of generalized coordinates
+    o : number of states
+
+    """
+
+    def __init__(self, coord_states, right_hand_side, speeds=None,
+                 mass_matrix=None, coordinate_derivatives=None, alg_con=None,
+                 output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None,
+                 loads=None):
+        """Initializes a SymbolicSystem object"""
+
+        # Extract information on speeds, coordinates and states
+        if speeds is None:
+            self._states = Matrix(coord_states)
+
+            if coord_idxs is None:
+                self._coordinates = None
+            else:
+                coords = [coord_states[i] for i in coord_idxs]
+                self._coordinates = Matrix(coords)
+
+            if speed_idxs is None:
+                self._speeds = None
+            else:
+                speeds_inter = [coord_states[i] for i in speed_idxs]
+                self._speeds = Matrix(speeds_inter)
+        else:
+            self._coordinates = Matrix(coord_states)
+            self._speeds = Matrix(speeds)
+            self._states = self._coordinates.col_join(self._speeds)
+
+        # Extract equations of motion form
+        if coordinate_derivatives is not None:
+            self._kin_explicit_rhs = coordinate_derivatives
+            self._dyn_implicit_rhs = right_hand_side
+            self._dyn_implicit_mat = mass_matrix
+            self._comb_implicit_rhs = None
+            self._comb_implicit_mat = None
+            self._comb_explicit_rhs = None
+        elif mass_matrix is not None:
+            self._kin_explicit_rhs = None
+            self._dyn_implicit_rhs = None
+            self._dyn_implicit_mat = None
+            self._comb_implicit_rhs = right_hand_side
+            self._comb_implicit_mat = mass_matrix
+            self._comb_explicit_rhs = None
+        else:
+            self._kin_explicit_rhs = None
+            self._dyn_implicit_rhs = None
+            self._dyn_implicit_mat = None
+            self._comb_implicit_rhs = None
+            self._comb_implicit_mat = None
+            self._comb_explicit_rhs = right_hand_side
+
+        # Set the remainder of the inputs as instance attributes
+        if alg_con is not None and coordinate_derivatives is not None:
+            alg_con = [i + len(coordinate_derivatives) for i in alg_con]
+        self._alg_con = alg_con
+        self.output_eqns = output_eqns
+
+        # Change the body and loads iterables to tuples if they are not tuples
+        # already
+        if not isinstance(bodies, tuple) and bodies is not None:
+            bodies = tuple(bodies)
+        if not isinstance(loads, tuple) and loads is not None:
+            loads = tuple(loads)
+        self._bodies = bodies
+        self._loads = loads
+
+    @property
+    def coordinates(self):
+        """Returns the column matrix of the generalized coordinates"""
+        if self._coordinates is None:
+            raise AttributeError("The coordinates were not specified.")
+        else:
+            return self._coordinates
+
+    @property
+    def speeds(self):
+        """Returns the column matrix of generalized speeds"""
+        if self._speeds is None:
+            raise AttributeError("The speeds were not specified.")
+        else:
+            return self._speeds
+
+    @property
+    def states(self):
+        """Returns the column matrix of the state variables"""
+        return self._states
+
+    @property
+    def alg_con(self):
+        """Returns a list with the indices of the rows containing algebraic
+        constraints in the combined form of the equations of motion"""
+        return self._alg_con
+
+    @property
+    def dyn_implicit_mat(self):
+        """Returns the matrix, M, corresponding to the dynamic equations in
+        implicit form, M x' = F, where the kinematical equations are not
+        included"""
+        if self._dyn_implicit_mat is None:
+            raise AttributeError("dyn_implicit_mat is not specified for "
+                                 "equations of motion form [1] or [2].")
+        else:
+            return self._dyn_implicit_mat
+
+    @property
+    def dyn_implicit_rhs(self):
+        """Returns the column matrix, F, corresponding to the dynamic equations
+        in implicit form, M x' = F, where the kinematical equations are not
+        included"""
+        if self._dyn_implicit_rhs is None:
+            raise AttributeError("dyn_implicit_rhs is not specified for "
+                                 "equations of motion form [1] or [2].")
+        else:
+            return self._dyn_implicit_rhs
+
+    @property
+    def comb_implicit_mat(self):
+        """Returns the matrix, M, corresponding to the equations of motion in
+        implicit form (form [2]), M x' = F, where the kinematical equations are
+        included"""
+        if self._comb_implicit_mat is None:
+            if self._dyn_implicit_mat is not None:
+                num_kin_eqns = len(self._kin_explicit_rhs)
+                num_dyn_eqns = len(self._dyn_implicit_rhs)
+                zeros1 = zeros(num_kin_eqns, num_dyn_eqns)
+                zeros2 = zeros(num_dyn_eqns, num_kin_eqns)
+                inter1 = eye(num_kin_eqns).row_join(zeros1)
+                inter2 = zeros2.row_join(self._dyn_implicit_mat)
+                self._comb_implicit_mat = inter1.col_join(inter2)
+                return self._comb_implicit_mat
+            else:
+                raise AttributeError("comb_implicit_mat is not specified for "
+                                     "equations of motion form [1].")
+        else:
+            return self._comb_implicit_mat
+
+    @property
+    def comb_implicit_rhs(self):
+        """Returns the column matrix, F, corresponding to the equations of
+        motion in implicit form (form [2]), M x' = F, where the kinematical
+        equations are included"""
+        if self._comb_implicit_rhs is None:
+            if self._dyn_implicit_rhs is not None:
+                kin_inter = self._kin_explicit_rhs
+                dyn_inter = self._dyn_implicit_rhs
+                self._comb_implicit_rhs = kin_inter.col_join(dyn_inter)
+                return self._comb_implicit_rhs
+            else:
+                raise AttributeError("comb_implicit_mat is not specified for "
+                                     "equations of motion in form [1].")
+        else:
+            return self._comb_implicit_rhs
+
+    def compute_explicit_form(self):
+        """If the explicit right hand side of the combined equations of motion
+        is to provided upon initialization, this method will calculate it. This
+        calculation can potentially take awhile to compute."""
+        if self._comb_explicit_rhs is not None:
+            raise AttributeError("comb_explicit_rhs is already formed.")
+
+        inter1 = getattr(self, 'kin_explicit_rhs', None)
+        if inter1 is not None:
+            inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs)
+            out = inter1.col_join(inter2)
+        else:
+            out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs)
+
+        self._comb_explicit_rhs = out
+
+    @property
+    def comb_explicit_rhs(self):
+        """Returns the right hand side of the equations of motion in explicit
+        form, x' = F, where the kinematical equations are included"""
+        if self._comb_explicit_rhs is None:
+            raise AttributeError("Please run .combute_explicit_form before "
+                                 "attempting to access comb_explicit_rhs.")
+        else:
+            return self._comb_explicit_rhs
+
+    @property
+    def kin_explicit_rhs(self):
+        """Returns the right hand side of the kinematical equations in explicit
+        form, q' = G"""
+        if self._kin_explicit_rhs is None:
+            raise AttributeError("kin_explicit_rhs is not specified for "
+                                 "equations of motion form [1] or [2].")
+        else:
+            return self._kin_explicit_rhs
+
+    def dynamic_symbols(self):
+        """Returns a column matrix containing all of the symbols in the system
+        that depend on time"""
+        # Create a list of all of the expressions in the equations of motion
+        if self._comb_explicit_rhs is None:
+            eom_expressions = (self.comb_implicit_mat[:] +
+                               self.comb_implicit_rhs[:])
+        else:
+            eom_expressions = (self._comb_explicit_rhs[:])
+
+        functions_of_time = set()
+        for expr in eom_expressions:
+            functions_of_time = functions_of_time.union(
+                find_dynamicsymbols(expr))
+        functions_of_time = functions_of_time.union(self._states)
+
+        return tuple(functions_of_time)
+
+    def constant_symbols(self):
+        """Returns a column matrix containing all of the symbols in the system
+        that do not depend on time"""
+        # Create a list of all of the expressions in the equations of motion
+        if self._comb_explicit_rhs is None:
+            eom_expressions = (self.comb_implicit_mat[:] +
+                               self.comb_implicit_rhs[:])
+        else:
+            eom_expressions = (self._comb_explicit_rhs[:])
+
+        constants = set()
+        for expr in eom_expressions:
+            constants = constants.union(expr.free_symbols)
+        constants.remove(dynamicsymbols._t)
+
+        return tuple(constants)
+
+    @property
+    def bodies(self):
+        """Returns the bodies in the system"""
+        if self._bodies is None:
+            raise AttributeError("bodies were not specified for the system.")
+        else:
+            return self._bodies
+
+    @property
+    def loads(self):
+        """Returns the loads in the system"""
+        if self._loads is None:
+            raise AttributeError("loads were not specified for the system.")
+        else:
+            return self._loads
diff --git a/shared/package-files/56/56c4db62be83c8a1620aa503818fd6ce542e7fe0e27714ad8200fe7b8741edfa/flipud_ops.h b/shared/package-files/56/56c4db62be83c8a1620aa503818fd6ce542e7fe0e27714ad8200fe7b8741edfa/flipud_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..a77b3e7f91e0c6484283274080d28b1a728460a9
--- /dev/null
+++ b/shared/package-files/56/56c4db62be83c8a1620aa503818fd6ce542e7fe0e27714ad8200fe7b8741edfa/flipud_ops.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API flipud {
+  using schema = at::Tensor (const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::flipud";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "flipud(Tensor self) -> Tensor";
+  static at::Tensor call(const at::Tensor & self);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/56/56cc0a6b45d0edf65e999d187bfd1a4ec71affc210b9c022a6dfad2f1e94abf4/__init__.cpython-311.pyc b/shared/package-files/56/56cc0a6b45d0edf65e999d187bfd1a4ec71affc210b9c022a6dfad2f1e94abf4/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7026d9651960ccbeff106148ad7c49d5780dc932
Binary files /dev/null and b/shared/package-files/56/56cc0a6b45d0edf65e999d187bfd1a4ec71affc210b9c022a6dfad2f1e94abf4/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/56cc5da6c930508219bd040f9167dc2d903945f39c4ba1943f73a6a98d0ee5b9/upsample_trilinear3d_backward_native.h b/shared/package-files/56/56cc5da6c930508219bd040f9167dc2d903945f39c4ba1943f73a6a98d0ee5b9/upsample_trilinear3d_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..30f6bc43a3b2ee2ec4f10a4f102cd8c981d508f8
--- /dev/null
+++ b/shared/package-files/56/56cc5da6c930508219bd040f9167dc2d903945f39c4ba1943f73a6a98d0ee5b9/upsample_trilinear3d_backward_native.h
@@ -0,0 +1,26 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_upsample_trilinear3d_backward_out_cpu : public at::meta::structured_upsample_trilinear3d_backward {
+void impl(const at::Tensor & grad_output, at::ArrayRef output_size, at::ArrayRef input_size, bool align_corners, ::std::optional scales_d, ::std::optional scales_h, ::std::optional scales_w, const at::Tensor & grad_input);
+};
+struct TORCH_API structured_upsample_trilinear3d_backward_out_cuda : public at::meta::structured_upsample_trilinear3d_backward {
+void impl(const at::Tensor & grad_output, at::ArrayRef output_size, at::ArrayRef input_size, bool align_corners, ::std::optional scales_d, ::std::optional scales_h, ::std::optional scales_w, const at::Tensor & grad_input);
+};
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/56cf65e0379184a5f207e85f0c1ae9e6ff3938eeaf9245d31d356367bceed318/cache.py b/shared/package-files/56/56cf65e0379184a5f207e85f0c1ae9e6ff3938eeaf9245d31d356367bceed318/cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..62895508b019aa76743a43e8237172ffe8e3fec7
--- /dev/null
+++ b/shared/package-files/56/56cf65e0379184a5f207e85f0c1ae9e6ff3938eeaf9245d31d356367bceed318/cache.py
@@ -0,0 +1,295 @@
+import importlib
+import json
+import os
+import uuid
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Dict, List, Optional
+import base64
+import hashlib
+
+
+def get_home_dir():
+    return os.getenv("TRITON_HOME", Path.home())
+
+
+def default_cache_dir():
+    return os.path.join(get_home_dir(), ".triton", "cache")
+
+
+def default_override_dir():
+    return os.path.join(get_home_dir(), ".triton", "override")
+
+
+def default_dump_dir():
+    return os.path.join(get_home_dir(), ".triton", "dump")
+
+
+class CacheManager(ABC):
+
+    def __init__(self, key):
+        pass
+
+    @abstractmethod
+    def get_file(self, filename) -> Optional[str]:
+        pass
+
+    @abstractmethod
+    def put(self, data, filename, binary=True) -> str:
+        pass
+
+    @abstractmethod
+    def get_group(self, filename: str) -> Optional[Dict[str, str]]:
+        pass
+
+    @abstractmethod
+    def put_group(self, filename: str, group: Dict[str, str]):
+        pass
+
+
+class FileCacheManager(CacheManager):
+
+    def __init__(self, key, override=False, dump=False):
+        self.key = key
+        self.lock_path = None
+        if dump:
+            self.cache_dir = os.getenv("TRITON_DUMP_DIR", "").strip() or default_dump_dir()
+            self.cache_dir = os.path.join(self.cache_dir, self.key)
+            self.lock_path = os.path.join(self.cache_dir, "lock")
+            os.makedirs(self.cache_dir, exist_ok=True)
+        elif override:
+            self.cache_dir = os.getenv("TRITON_OVERRIDE_DIR", "").strip() or default_override_dir()
+            self.cache_dir = os.path.join(self.cache_dir, self.key)
+        else:
+            # create cache directory if it doesn't exist
+            self.cache_dir = os.getenv("TRITON_CACHE_DIR", "").strip() or default_cache_dir()
+            if self.cache_dir:
+                self.cache_dir = os.path.join(self.cache_dir, self.key)
+                self.lock_path = os.path.join(self.cache_dir, "lock")
+                os.makedirs(self.cache_dir, exist_ok=True)
+            else:
+                raise RuntimeError("Could not create or locate cache dir")
+
+    def _make_path(self, filename) -> str:
+        return os.path.join(self.cache_dir, filename)
+
+    def has_file(self, filename) -> bool:
+        if not self.cache_dir:
+            raise RuntimeError("Could not create or locate cache dir")
+        return os.path.exists(self._make_path(filename))
+
+    def get_file(self, filename) -> Optional[str]:
+        if self.has_file(filename):
+            return self._make_path(filename)
+        else:
+            return None
+
+    def get_group(self, filename: str) -> Optional[Dict[str, str]]:
+        grp_filename = f"__grp__{filename}"
+        if not self.has_file(grp_filename):
+            return None
+        grp_filepath = self._make_path(grp_filename)
+        with open(grp_filepath) as f:
+            grp_data = json.load(f)
+        child_paths = grp_data.get("child_paths", None)
+        # Invalid group data.
+        if child_paths is None:
+            return None
+        result = {}
+        for c, p in child_paths.items():
+            if os.path.exists(p):
+                result[c] = p
+        return result
+
+    # Note a group of pushed files as being part of a group
+    def put_group(self, filename: str, group: Dict[str, str]) -> str:
+        if not self.cache_dir:
+            raise RuntimeError("Could not create or locate cache dir")
+        grp_contents = json.dumps({"child_paths": group})
+        grp_filename = f"__grp__{filename}"
+        return self.put(grp_contents, grp_filename, binary=False)
+
+    def put(self, data, filename, binary=True) -> str:
+        if not self.cache_dir:
+            raise RuntimeError("Could not create or locate cache dir")
+        binary = isinstance(data, bytes)
+        if not binary:
+            data = str(data)
+        assert self.lock_path is not None
+        filepath = self._make_path(filename)
+        # Random ID to avoid any collisions
+        rnd_id = str(uuid.uuid4())
+        # we use the PID in case a bunch of these around so we can see what PID made it
+        pid = os.getpid()
+        # use temp dir to be robust against program interruptions
+        temp_dir = os.path.join(self.cache_dir, f"tmp.pid_{pid}_{rnd_id}")
+        os.makedirs(temp_dir, exist_ok=True)
+        temp_path = os.path.join(temp_dir, filename)
+
+        mode = "wb" if binary else "w"
+        with open(temp_path, mode) as f:
+            f.write(data)
+        # Replace is guaranteed to be atomic on POSIX systems if it succeeds
+        # so filepath cannot see a partial write
+        os.replace(temp_path, filepath)
+        os.removedirs(temp_dir)
+        return filepath
+
+
+class RemoteCacheBackend:
+    """
+    A backend implementation for accessing a remote/distributed cache.
+    """
+
+    def __init__(self, key: str):
+        pass
+
+    @abstractmethod
+    def get(self, filenames: List[str]) -> Dict[str, bytes]:
+        pass
+
+    @abstractmethod
+    def put(self, filename: str, data: bytes):
+        pass
+
+
+class RedisRemoteCacheBackend(RemoteCacheBackend):
+
+    def __init__(self, key):
+        import redis
+        self._key = key
+        self._key_fmt = os.environ.get("TRITON_REDIS_KEY_FORMAT", "triton:{key}:{filename}")
+        self._redis = redis.Redis(
+            host=os.environ.get("TRITON_REDIS_HOST", "localhost"),
+            port=int(os.environ.get("TRITON_REDIS_PORT", 6379)),
+        )
+
+    def _get_key(self, filename: str) -> str:
+        return self._key_fmt.format(key=self._key, filename=filename)
+
+    def get(self, filenames: List[str]) -> Dict[str, str]:
+        results = self._redis.mget([self._get_key(f) for f in filenames])
+        return {filename: result for filename, result in zip(filenames, results) if result is not None}
+
+    def put(self, filename: str, data: bytes) -> Dict[str, bytes]:
+        self._redis.set(self._get_key(filename), data)
+
+
+class RemoteCacheManager(CacheManager):
+
+    def __init__(self, key, override=False, dump=False):
+        # Setup backend pointed too by `TRITON_REMOTE_CACHE_BACKEND`.
+        remote_cache_manager = os.environ["TRITON_REMOTE_CACHE_BACKEND"]
+        module_path, clz_nme = remote_cache_manager.split(":")
+        module = importlib.import_module(module_path)
+        remote_cache_cls = getattr(module, clz_nme)
+        self._backend = remote_cache_cls(key)
+
+        self._override = override
+        self._dump = dump
+
+        # Use a `FileCacheManager` to materialize remote cache paths locally.
+        self._file_cache_manager = FileCacheManager(key, override=override, dump=dump)
+
+    def _materialize(self, filename: str, data: bytes):
+        # We use a backing `FileCacheManager` to provide the materialized data.
+        return self._file_cache_manager.put(data, filename, binary=True)
+
+    def get_file(self, filename: str) -> Optional[str]:
+        # We don't handle the dump/override cases.
+        if self._dump or self._override:
+            return self._file_cache_manager.get_file(filename)
+
+        # We always check the remote cache backend -- even if our internal file-
+        # based cache has the item -- to make sure LRU accounting works as
+        # expected.
+        results = self._backend.get([filename])
+        if len(results) == 0:
+            return None
+        (_, data), = results.items()
+        return self._materialize(filename, data)
+
+    def put(self, data, filename: str, binary=True) -> str:
+        # We don't handle the dump/override cases.
+        if self._dump or self._override:
+            return self._file_cache_manager.put(data, filename, binary=binary)
+
+        if not isinstance(data, bytes):
+            data = str(data).encode("utf-8")
+        self._backend.put(filename, data)
+        return self._materialize(filename, data)
+
+    def get_group(self, filename: str) -> Optional[Dict[str, str]]:
+        # We don't handle the dump/override cases.
+        if self._dump or self._override:
+            return self._file_cache_manager.get_group(filename)
+
+        grp_filename = f"__grp__{filename}"
+        grp_filepath = self.get_file(grp_filename)
+        if grp_filepath is None:
+            return None
+        with open(grp_filepath) as f:
+            grp_data = json.load(f)
+        child_paths = grp_data.get("child_paths", None)
+
+        result = None
+
+        # Found group data.
+        if child_paths is not None:
+            result = {}
+            for child_path, data in self._backend.get(child_paths).items():
+                result[child_path] = self._materialize(child_path, data)
+
+        return result
+
+    def put_group(self, filename: str, group: Dict[str, str]):
+        # We don't handle the dump/override cases.
+        if self._dump or self._override:
+            return self._file_cache_manager.put_group(filename, group)
+
+        grp_contents = json.dumps({"child_paths": sorted(list(group.keys()))})
+        grp_filename = f"__grp__{filename}"
+        return self.put(grp_contents, grp_filename)
+
+
+__cache_cls = FileCacheManager
+__cache_cls_nme = "DEFAULT"
+
+
+def _base32(key):
+    # Assume key is a hex string.
+    return base64.b32encode(bytes.fromhex(key)).decode("utf-8").rstrip("=")
+
+
+def get_cache_manager(key) -> CacheManager:
+    import os
+
+    user_cache_manager = os.environ.get("TRITON_CACHE_MANAGER", None)
+    global __cache_cls
+    global __cache_cls_nme
+
+    if user_cache_manager is not None and user_cache_manager != __cache_cls_nme:
+        module_path, clz_nme = user_cache_manager.split(":")
+        module = importlib.import_module(module_path)
+        __cache_cls = getattr(module, clz_nme)
+        __cache_cls_nme = user_cache_manager
+
+    return __cache_cls(_base32(key))
+
+
+def get_override_manager(key) -> CacheManager:
+    return __cache_cls(_base32(key), override=True)
+
+
+def get_dump_manager(key) -> CacheManager:
+    return __cache_cls(_base32(key), dump=True)
+
+
+def make_so_cache_key(version_hash, signature, constants, ids, **kwargs):
+    # Get unique key for the compiled code
+    signature = {k: 'ptr' if v[0] == '*' else v for k, v in signature.items()}
+    key = f"{version_hash}-{''.join(signature.values())}-{constants}-{ids}"
+    for kw in kwargs:
+        key = f"{key}-{kwargs.get(kw)}"
+    key = hashlib.sha256(key.encode("utf-8")).hexdigest()
+    return _base32(key)
diff --git a/shared/package-files/56/56d2a6093635b4efe655a4590540670ef114147cc3fc1137ab7a748d20c075d7/cuda_occupancy.h b/shared/package-files/56/56d2a6093635b4efe655a4590540670ef114147cc3fc1137ab7a748d20c075d7/cuda_occupancy.h
new file mode 100644
index 0000000000000000000000000000000000000000..d0769a3d4a82eb1553b7e494ff48ab9cd7868610
--- /dev/null
+++ b/shared/package-files/56/56d2a6093635b4efe655a4590540670ef114147cc3fc1137ab7a748d20c075d7/cuda_occupancy.h
@@ -0,0 +1,1981 @@
+/*
+ * Copyright 1993-2017 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+/**
+ * CUDA Occupancy Calculator
+ *
+ * NAME
+ *
+ *   cudaOccMaxActiveBlocksPerMultiprocessor,
+ *   cudaOccMaxPotentialOccupancyBlockSize,
+ *   cudaOccMaxPotentialOccupancyBlockSizeVariableSMem
+ *   cudaOccAvailableDynamicSMemPerBlock
+ *
+ * DESCRIPTION
+ *
+ *   The CUDA occupancy calculator provides a standalone, programmatical
+ *   interface to compute the occupancy of a function on a device. It can also
+ *   provide occupancy-oriented launch configuration suggestions.
+ *
+ *   The function and device are defined by the user through
+ *   cudaOccFuncAttributes, cudaOccDeviceProp, and cudaOccDeviceState
+ *   structures. All APIs require all 3 of them.
+ *
+ *   See the structure definition for more details about the device / function
+ *   descriptors.
+ *
+ *   See each API's prototype for API usage.
+ *
+ * COMPATIBILITY
+ *
+ *   The occupancy calculator will be updated on each major CUDA toolkit
+ *   release. It does not provide forward compatibility, i.e. new hardwares
+ *   released after this implementation's release will not be supported.
+ *
+ * NOTE
+ *
+ *   If there is access to CUDA runtime, and the sole intent is to calculate
+ *   occupancy related values on one of the accessible CUDA devices, using CUDA
+ *   runtime's occupancy calculation APIs is recommended.
+ *
+ */
+
+#ifndef __cuda_occupancy_h__
+#define __cuda_occupancy_h__
+
+#include 
+#include 
+#include 
+
+
+// __OCC_INLINE will be undefined at the end of this header
+//
+#ifdef __CUDACC__
+#define __OCC_INLINE inline __host__ __device__
+#elif defined _MSC_VER
+#define __OCC_INLINE __inline
+#else // GNUCC assumed
+#define __OCC_INLINE inline
+#endif
+
+enum cudaOccError_enum {
+    CUDA_OCC_SUCCESS              = 0,  // no error encountered
+    CUDA_OCC_ERROR_INVALID_INPUT  = 1,  // input parameter is invalid
+    CUDA_OCC_ERROR_UNKNOWN_DEVICE = 2,  // requested device is not supported in
+                                        // current implementation or device is
+                                        // invalid
+};
+typedef enum cudaOccError_enum       cudaOccError;
+
+typedef struct cudaOccResult         cudaOccResult;
+typedef struct cudaOccDeviceProp     cudaOccDeviceProp;
+typedef struct cudaOccFuncAttributes cudaOccFuncAttributes;
+typedef struct cudaOccDeviceState    cudaOccDeviceState;
+
+/**
+ * The CUDA occupancy calculator computes the occupancy of the function
+ * described by attributes with the given block size (blockSize), static device
+ * properties (properties), dynamic device states (states) and per-block dynamic
+ * shared memory allocation (dynamicSMemSize) in bytes, and output it through
+ * result along with other useful information. The occupancy is computed in
+ * terms of the maximum number of active blocks per multiprocessor. The user can
+ * then convert it to other metrics, such as number of active warps.
+ *
+ * RETURN VALUE
+ *
+ * The occupancy and related information is returned through result.
+ *
+ * If result->activeBlocksPerMultiprocessor is 0, then the given parameter
+ * combination cannot run on the device.
+ *
+ * ERRORS
+ *
+ *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
+ *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
+ *     current implementation or device is invalid
+ */
+static __OCC_INLINE
+cudaOccError cudaOccMaxActiveBlocksPerMultiprocessor(
+    cudaOccResult               *result,           // out
+    const cudaOccDeviceProp     *properties,       // in
+    const cudaOccFuncAttributes *attributes,       // in
+    const cudaOccDeviceState    *state,            // in
+    int                          blockSize,        // in
+    size_t                       dynamicSmemSize); // in
+
+/**
+ * The CUDA launch configurator C API suggests a grid / block size pair (in
+ * minGridSize and blockSize) that achieves the best potential occupancy
+ * (i.e. maximum number of active warps with the smallest number of blocks) for
+ * the given function described by attributes, on a device described by
+ * properties with settings in state.
+ *
+ * If per-block dynamic shared memory allocation is not needed, the user should
+ * leave both blockSizeToDynamicSMemSize and dynamicSMemSize as 0.
+ *
+ * If per-block dynamic shared memory allocation is needed, then if the dynamic
+ * shared memory size is constant regardless of block size, the size should be
+ * passed through dynamicSMemSize, and blockSizeToDynamicSMemSize should be
+ * NULL.
+ *
+ * Otherwise, if the per-block dynamic shared memory size varies with different
+ * block sizes, the user needs to provide a pointer to an unary function through
+ * blockSizeToDynamicSMemSize that computes the dynamic shared memory needed by
+ * a block of the function for any given block size. dynamicSMemSize is
+ * ignored. An example signature is:
+ *
+ *    // Take block size, returns dynamic shared memory needed
+ *    size_t blockToSmem(int blockSize);
+ *
+ * RETURN VALUE
+ *
+ * The suggested block size and the minimum number of blocks needed to achieve
+ * the maximum occupancy are returned through blockSize and minGridSize.
+ *
+ * If *blockSize is 0, then the given combination cannot run on the device.
+ *
+ * ERRORS
+ *
+ *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
+ *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
+ *     current implementation or device is invalid
+ *
+ */
+static __OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
+    int                         *minGridSize,      // out
+    int                         *blockSize,        // out
+    const cudaOccDeviceProp     *properties,       // in
+    const cudaOccFuncAttributes *attributes,       // in
+    const cudaOccDeviceState    *state,            // in
+    size_t                     (*blockSizeToDynamicSMemSize)(int), // in
+    size_t                       dynamicSMemSize); // in
+
+/**
+ * The CUDA launch configurator C++ API suggests a grid / block size pair (in
+ * minGridSize and blockSize) that achieves the best potential occupancy
+ * (i.e. the maximum number of active warps with the smallest number of blocks)
+ * for the given function described by attributes, on a device described by
+ * properties with settings in state.
+ *
+ * If per-block dynamic shared memory allocation is 0 or constant regardless of
+ * block size, the user can use cudaOccMaxPotentialOccupancyBlockSize to
+ * configure the launch. A constant dynamic shared memory allocation size in
+ * bytes can be passed through dynamicSMemSize.
+ *
+ * Otherwise, if the per-block dynamic shared memory size varies with different
+ * block sizes, the user needs to use
+ * cudaOccMaxPotentialOccupancyBlockSizeVariableSmem instead, and provide a
+ * functor / pointer to an unary function (blockSizeToDynamicSMemSize) that
+ * computes the dynamic shared memory needed by func for any given block
+ * size. An example signature is:
+ *
+ *  // Take block size, returns per-block dynamic shared memory needed
+ *  size_t blockToSmem(int blockSize);
+ *
+ * RETURN VALUE
+ *
+ * The suggested block size and the minimum number of blocks needed to achieve
+ * the maximum occupancy are returned through blockSize and minGridSize.
+ *
+ * If *blockSize is 0, then the given combination cannot run on the device.
+ *
+ * ERRORS
+ *
+ *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
+ *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
+ *     current implementation or device is invalid
+ *
+ */
+
+#if defined(__cplusplus)
+namespace {
+
+__OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
+    int                         *minGridSize,          // out
+    int                         *blockSize,            // out
+    const cudaOccDeviceProp     *properties,           // in
+    const cudaOccFuncAttributes *attributes,           // in
+    const cudaOccDeviceState    *state,                // in
+    size_t                       dynamicSMemSize = 0); // in
+
+template 
+__OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSizeVariableSMem(
+    int                         *minGridSize,          // out
+    int                         *blockSize,            // out
+    const cudaOccDeviceProp     *properties,           // in
+    const cudaOccFuncAttributes *attributes,           // in
+    const cudaOccDeviceState    *state,                // in
+    UnaryFunction                blockSizeToDynamicSMemSize); // in
+
+} // namespace anonymous
+#endif // defined(__cplusplus)
+
+/**
+ *
+ * The CUDA dynamic shared memory calculator computes the maximum size of 
+ * per-block dynamic shared memory if we want to place numBlocks blocks
+ * on an SM.
+ *
+ * RETURN VALUE
+ *
+ * Returns in *dynamicSmemSize the maximum size of dynamic shared memory to allow 
+ * numBlocks blocks per SM.
+ *
+ * ERRORS
+ *
+ *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
+ *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
+ *     current implementation or device is invalid
+ *
+ */
+static __OCC_INLINE
+cudaOccError cudaOccAvailableDynamicSMemPerBlock(
+    size_t                      *dynamicSmemSize,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    int                         numBlocks,
+    int                         blockSize);
+
+/**
+ * Data structures
+ *
+ * These structures are subject to change for future architecture and CUDA
+ * releases. C users should initialize the structure as {0}.
+ *
+ */
+
+/**
+ * Device descriptor
+ *
+ * This structure describes a device.
+ */
+struct cudaOccDeviceProp {
+    int    computeMajor;                // Compute capability major version
+    int    computeMinor;                // Compute capability minor
+                                        // version. None supported minor version
+                                        // may cause error
+    int    maxThreadsPerBlock;          // Maximum number of threads per block
+    int    maxThreadsPerMultiprocessor; // Maximum number of threads per SM
+                                        // i.e. (Max. number of warps) x (warp
+                                        // size)
+    int    regsPerBlock;                // Maximum number of registers per block
+    int    regsPerMultiprocessor;       // Maximum number of registers per SM
+    int    warpSize;                    // Warp size
+    size_t sharedMemPerBlock;           // Maximum shared memory size per block
+    size_t sharedMemPerMultiprocessor;  // Maximum shared memory size per SM
+    int    numSms;                      // Number of SMs available
+    size_t sharedMemPerBlockOptin;      // Maximum optin shared memory size per block
+    size_t reservedSharedMemPerBlock;   // Shared memory per block reserved by driver
+
+#ifdef __cplusplus
+    // This structure can be converted from a cudaDeviceProp structure for users
+    // that use this header in their CUDA applications.
+    //
+    // If the application have access to the CUDA Runtime API, the application
+    // can obtain the device properties of a CUDA device through
+    // cudaGetDeviceProperties, and initialize a cudaOccDeviceProp with the
+    // cudaDeviceProp structure.
+    //
+    // Example:
+    /*
+     {
+         cudaDeviceProp prop;
+
+         cudaGetDeviceProperties(&prop, ...);
+
+         cudaOccDeviceProp occProp = prop;
+
+         ...
+
+         cudaOccMaxPotentialOccupancyBlockSize(..., &occProp, ...);
+     }
+     */
+    //
+    template
+    __OCC_INLINE
+    cudaOccDeviceProp(const DeviceProp &props)
+    :   computeMajor                (props.major),
+        computeMinor                (props.minor),
+        maxThreadsPerBlock          (props.maxThreadsPerBlock),
+        maxThreadsPerMultiprocessor (props.maxThreadsPerMultiProcessor),
+        regsPerBlock                (props.regsPerBlock),
+        regsPerMultiprocessor       (props.regsPerMultiprocessor),
+        warpSize                    (props.warpSize),
+        sharedMemPerBlock           (props.sharedMemPerBlock),
+        sharedMemPerMultiprocessor  (props.sharedMemPerMultiprocessor),
+        numSms                      (props.multiProcessorCount),
+        sharedMemPerBlockOptin      (props.sharedMemPerBlockOptin),
+        reservedSharedMemPerBlock   (props.reservedSharedMemPerBlock)
+    {}
+
+    __OCC_INLINE
+    cudaOccDeviceProp()
+    :   computeMajor                (0),
+        computeMinor                (0),
+        maxThreadsPerBlock          (0),
+        maxThreadsPerMultiprocessor (0),
+        regsPerBlock                (0),
+        regsPerMultiprocessor       (0),
+        warpSize                    (0),
+        sharedMemPerBlock           (0),
+        sharedMemPerMultiprocessor  (0),
+        numSms                      (0),
+        sharedMemPerBlockOptin      (0),
+        reservedSharedMemPerBlock   (0)
+    {}
+#endif // __cplusplus
+};
+
+/**
+ * Partitioned global caching option
+ */
+typedef enum cudaOccPartitionedGCConfig_enum {
+    PARTITIONED_GC_OFF,        // Disable partitioned global caching
+    PARTITIONED_GC_ON,         // Prefer partitioned global caching
+    PARTITIONED_GC_ON_STRICT   // Force partitioned global caching
+} cudaOccPartitionedGCConfig;
+
+/**
+ * Per function opt in maximum dynamic shared memory limit
+ */
+typedef enum cudaOccFuncShmemConfig_enum {
+    FUNC_SHMEM_LIMIT_DEFAULT,   // Default shmem limit
+    FUNC_SHMEM_LIMIT_OPTIN,     // Use the optin shmem limit
+} cudaOccFuncShmemConfig;
+
+/**
+ * Function descriptor
+ *
+ * This structure describes a CUDA function.
+ */
+struct cudaOccFuncAttributes {
+    int maxThreadsPerBlock; // Maximum block size the function can work with. If
+                            // unlimited, use INT_MAX or any value greater than
+                            // or equal to maxThreadsPerBlock of the device
+    int numRegs;            // Number of registers used. When the function is
+                            // launched on device, the register count may change
+                            // due to internal tools requirements.
+    size_t sharedSizeBytes; // Number of static shared memory used
+
+    cudaOccPartitionedGCConfig partitionedGCConfig; 
+                            // Partitioned global caching is required to enable
+                            // caching on certain chips, such as sm_52
+                            // devices. Partitioned global caching can be
+                            // automatically disabled if the occupancy
+                            // requirement of the launch cannot support caching.
+                            //
+                            // To override this behavior with caching on and
+                            // calculate occupancy strictly according to the
+                            // preference, set partitionedGCConfig to
+                            // PARTITIONED_GC_ON_STRICT. This is especially
+                            // useful for experimenting and finding launch
+                            // configurations (MaxPotentialOccupancyBlockSize)
+                            // that allow global caching to take effect.
+                            //
+                            // This flag only affects the occupancy calculation.
+
+    cudaOccFuncShmemConfig shmemLimitConfig;
+                            // Certain chips like sm_70 allow a user to opt into
+                            // a higher per block limit of dynamic shared memory
+                            // This optin is performed on a per function basis
+                            // using the cuFuncSetAttribute function
+
+    size_t maxDynamicSharedSizeBytes;
+                            // User set limit on maximum dynamic shared memory
+                            // usable by the kernel
+                            // This limit is set using the cuFuncSetAttribute
+                            // function.
+
+    int numBlockBarriers;   // Number of block barriers used (default to 1)
+#ifdef __cplusplus
+    // This structure can be converted from a cudaFuncAttributes structure for
+    // users that use this header in their CUDA applications.
+    //
+    // If the application have access to the CUDA Runtime API, the application
+    // can obtain the function attributes of a CUDA kernel function through
+    // cudaFuncGetAttributes, and initialize a cudaOccFuncAttributes with the
+    // cudaFuncAttributes structure.
+    //
+    // Example:
+    /*
+      __global__ void foo() {...}
+
+      ...
+
+      {
+          cudaFuncAttributes attr;
+
+          cudaFuncGetAttributes(&attr, foo);
+
+          cudaOccFuncAttributes occAttr = attr;
+
+          ...
+
+          cudaOccMaxPotentialOccupancyBlockSize(..., &occAttr, ...);
+      }
+     */
+    //
+    template
+    __OCC_INLINE
+    cudaOccFuncAttributes(const FuncAttributes &attr)
+    :   maxThreadsPerBlock  (attr.maxThreadsPerBlock),
+        numRegs             (attr.numRegs),
+        sharedSizeBytes     (attr.sharedSizeBytes),
+        partitionedGCConfig (PARTITIONED_GC_OFF),
+        shmemLimitConfig    (FUNC_SHMEM_LIMIT_OPTIN),
+        maxDynamicSharedSizeBytes (attr.maxDynamicSharedSizeBytes),
+        numBlockBarriers    (1)
+    {}
+
+    __OCC_INLINE
+    cudaOccFuncAttributes()
+    :   maxThreadsPerBlock  (0),
+        numRegs             (0),
+        sharedSizeBytes     (0),
+        partitionedGCConfig (PARTITIONED_GC_OFF),
+        shmemLimitConfig    (FUNC_SHMEM_LIMIT_DEFAULT),
+        maxDynamicSharedSizeBytes (0),
+        numBlockBarriers    (0)
+    {}
+#endif
+};
+
+typedef enum cudaOccCacheConfig_enum {
+    CACHE_PREFER_NONE   = 0x00, // no preference for shared memory or L1 (default)
+    CACHE_PREFER_SHARED = 0x01, // prefer larger shared memory and smaller L1 cache
+    CACHE_PREFER_L1     = 0x02, // prefer larger L1 cache and smaller shared memory
+    CACHE_PREFER_EQUAL  = 0x03  // prefer equal sized L1 cache and shared memory
+} cudaOccCacheConfig;
+
+typedef enum cudaOccCarveoutConfig_enum {
+    SHAREDMEM_CARVEOUT_DEFAULT       = -1,  // no preference for shared memory or L1 (default)
+    SHAREDMEM_CARVEOUT_MAX_SHARED    = 100, // prefer maximum available shared memory, minimum L1 cache
+    SHAREDMEM_CARVEOUT_MAX_L1        = 0,    // prefer maximum available L1 cache, minimum shared memory
+    SHAREDMEM_CARVEOUT_HALF          = 50   // prefer half of maximum available shared memory, with the rest as L1 cache
+} cudaOccCarveoutConfig;
+
+/**
+ * Device state descriptor
+ *
+ * This structure describes device settings that affect occupancy calculation.
+ */
+struct cudaOccDeviceState
+{
+    // Cache / shared memory split preference. Deprecated on Volta 
+    cudaOccCacheConfig cacheConfig; 
+    // Shared memory / L1 split preference. Supported on only Volta
+    int carveoutConfig;
+
+#ifdef __cplusplus
+    __OCC_INLINE
+    cudaOccDeviceState()
+    :   cacheConfig     (CACHE_PREFER_NONE),
+        carveoutConfig  (SHAREDMEM_CARVEOUT_DEFAULT)
+    {}
+#endif
+};
+
+typedef enum cudaOccLimitingFactor_enum {
+                                    // Occupancy limited due to:
+    OCC_LIMIT_WARPS         = 0x01, // - warps available
+    OCC_LIMIT_REGISTERS     = 0x02, // - registers available
+    OCC_LIMIT_SHARED_MEMORY = 0x04, // - shared memory available
+    OCC_LIMIT_BLOCKS        = 0x08, // - blocks available
+    OCC_LIMIT_BARRIERS      = 0x10  // - barrier available
+} cudaOccLimitingFactor;
+
+/**
+ * Occupancy output
+ *
+ * This structure contains occupancy calculator's output.
+ */
+struct cudaOccResult {
+    int activeBlocksPerMultiprocessor; // Occupancy
+    unsigned int limitingFactors;      // Factors that limited occupancy. A bit
+                                       // field that counts the limiting
+                                       // factors, see cudaOccLimitingFactor
+    int blockLimitRegs;                // Occupancy due to register
+                                       // usage, INT_MAX if the kernel does not
+                                       // use any register.
+    int blockLimitSharedMem;           // Occupancy due to shared memory
+                                       // usage, INT_MAX if the kernel does not
+                                       // use shared memory.
+    int blockLimitWarps;               // Occupancy due to block size limit
+    int blockLimitBlocks;              // Occupancy due to maximum number of blocks
+                                       // managable per SM
+    int blockLimitBarriers;            // Occupancy due to block barrier usage
+    int allocatedRegistersPerBlock;    // Actual number of registers allocated per
+                                       // block
+    size_t allocatedSharedMemPerBlock; // Actual size of shared memory allocated
+                                       // per block
+    cudaOccPartitionedGCConfig partitionedGCConfig;
+                                       // Report if partitioned global caching
+                                       // is actually enabled.
+};
+
+/**
+ * Partitioned global caching support
+ *
+ * See cudaOccPartitionedGlobalCachingModeSupport
+ */
+typedef enum cudaOccPartitionedGCSupport_enum {
+    PARTITIONED_GC_NOT_SUPPORTED,  // Partitioned global caching is not supported
+    PARTITIONED_GC_SUPPORTED,      // Partitioned global caching is supported
+} cudaOccPartitionedGCSupport;
+
+/**
+ * Implementation
+ */
+
+/**
+ * Max compute capability supported
+ */
+
+#define __CUDA_OCC_MAJOR__ 9
+#define __CUDA_OCC_MINOR__ 0
+
+//////////////////////////////////////////
+//    Mathematical Helper Functions     //
+//////////////////////////////////////////
+
+static __OCC_INLINE int __occMin(int lhs, int rhs)
+{
+    return rhs < lhs ? rhs : lhs;
+}
+
+static __OCC_INLINE int __occDivideRoundUp(int x, int y)
+{
+    return (x + (y - 1)) / y;
+}
+
+static __OCC_INLINE int __occRoundUp(int x, int y)
+{
+    return y * __occDivideRoundUp(x, y);
+}
+
+//////////////////////////////////////////
+//      Architectural Properties        //
+//////////////////////////////////////////
+
+/**
+ * Granularity of shared memory allocation
+ */
+static __OCC_INLINE cudaOccError cudaOccSMemAllocationGranularity(int *limit, const cudaOccDeviceProp *properties)
+{
+    int value;
+
+    switch(properties->computeMajor) {
+        case 3:
+        case 5:
+        case 6:
+        case 7:
+            value = 256;
+            break;
+        case 8:
+        case 9:
+            value = 128;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = value;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Maximum number of registers per thread
+ */
+static __OCC_INLINE cudaOccError cudaOccRegAllocationMaxPerThread(int *limit, const cudaOccDeviceProp *properties)
+{
+    int value;
+
+    switch(properties->computeMajor) {
+        case 3:
+        case 5:
+        case 6:
+            value = 255;
+            break;
+        case 7:
+        case 8:
+        case 9:
+            value = 256;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = value;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Granularity of register allocation
+ */
+static __OCC_INLINE cudaOccError cudaOccRegAllocationGranularity(int *limit, const cudaOccDeviceProp *properties)
+{
+    int value;
+
+    switch(properties->computeMajor) {
+        case 3:
+        case 5:
+        case 6:
+        case 7:
+        case 8:
+        case 9:
+            value = 256;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = value;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Number of sub-partitions
+ */
+static __OCC_INLINE cudaOccError cudaOccSubPartitionsPerMultiprocessor(int *limit, const cudaOccDeviceProp *properties)
+{
+    int value;
+
+    switch(properties->computeMajor) {
+        case 3:
+        case 5:
+        case 7:
+        case 8:
+        case 9:
+            value = 4;
+            break;
+        case 6:
+            value = properties->computeMinor ? 4 : 2;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = value;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+
+/**
+ * Maximum number of blocks that can run simultaneously on a multiprocessor
+ */
+static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerMultiprocessor(int* limit, const cudaOccDeviceProp *properties)
+{
+    int value;
+
+    switch(properties->computeMajor) {
+        case 3:
+            value = 16;
+            break;
+        case 5:
+        case 6:
+            value = 32;
+            break;
+        case 7: {
+            int isTuring = properties->computeMinor == 5;
+            value = (isTuring) ? 16 : 32;
+            break;
+        }
+        case 8:
+            if (properties->computeMinor == 0) {
+                value = 32;
+            }
+            else if (properties->computeMinor == 9) {
+                value = 24;
+            }
+            else {
+                value = 16;
+            }
+            break;
+        case 9:
+            value = 32;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = value;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/** 
+ * Align up shared memory based on compute major configurations
+ */
+static __OCC_INLINE cudaOccError cudaOccAlignUpShmemSizeVoltaPlus(size_t *shMemSize, const cudaOccDeviceProp *properties)
+{
+    // Volta and Turing have shared L1 cache / shared memory, and support cache
+    // configuration to trade one for the other. These values are needed to
+    // map carveout config ratio to the next available architecture size
+    size_t size = *shMemSize;
+
+    switch (properties->computeMajor) {
+    case 7: {
+        // Turing supports 32KB and 64KB shared mem.
+        int isTuring = properties->computeMinor == 5;
+        if (isTuring) {
+            if      (size <= 32 * 1024) {
+                *shMemSize = 32 * 1024;
+            }
+            else if (size <= 64 * 1024) {
+                *shMemSize = 64 * 1024;
+            }
+            else {
+                return CUDA_OCC_ERROR_INVALID_INPUT;
+            }
+        }
+        // Volta supports 0KB, 8KB, 16KB, 32KB, 64KB, and 96KB shared mem.
+        else {
+            if      (size == 0) {
+                *shMemSize = 0;
+            }
+            else if (size <= 8 * 1024) {
+                *shMemSize = 8 * 1024;
+            }
+            else if (size <= 16 * 1024) {
+                *shMemSize = 16 * 1024;
+            }
+            else if (size <= 32 * 1024) {
+                *shMemSize = 32 * 1024;
+            }
+            else if (size <= 64 * 1024) {
+                *shMemSize = 64 * 1024;
+            }
+            else if (size <= 96 * 1024) {
+                *shMemSize = 96 * 1024;
+            }
+            else {
+                return CUDA_OCC_ERROR_INVALID_INPUT;
+            }
+        }
+        break;
+    }
+    case 8:
+        if (properties->computeMinor == 0 || properties->computeMinor == 7) {
+            if      (size == 0) {
+                *shMemSize = 0;
+            }
+            else if (size <= 8 * 1024) {
+                *shMemSize = 8 * 1024;
+            }
+            else if (size <= 16 * 1024) {
+                *shMemSize = 16 * 1024;
+            }
+            else if (size <= 32 * 1024) {
+                *shMemSize = 32 * 1024;
+            }
+            else if (size <= 64 * 1024) {
+                *shMemSize = 64 * 1024;
+            }
+            else if (size <= 100 * 1024) {
+                *shMemSize = 100 * 1024;
+            }
+            else if (size <= 132 * 1024) {
+                *shMemSize = 132 * 1024;
+            }
+            else if (size <= 164 * 1024) {
+                *shMemSize = 164 * 1024;
+            }
+            else {
+                return CUDA_OCC_ERROR_INVALID_INPUT;
+            }
+        }
+        else {
+            if      (size == 0) {
+                *shMemSize = 0;
+            }
+            else if (size <= 8 * 1024) {
+                *shMemSize = 8 * 1024;
+            }
+            else if (size <= 16 * 1024) {
+                *shMemSize = 16 * 1024;
+            }
+            else if (size <= 32 * 1024) {
+                *shMemSize = 32 * 1024;
+            }
+            else if (size <= 64 * 1024) {
+                *shMemSize = 64 * 1024;
+            }
+            else if (size <= 100 * 1024) {
+                *shMemSize = 100 * 1024;
+            }
+            else {
+                return CUDA_OCC_ERROR_INVALID_INPUT;
+            }
+        }
+        break;
+    case 9: {
+        if      (size == 0) {
+            *shMemSize = 0;
+        }
+        else if (size <= 8 * 1024) {
+            *shMemSize = 8 * 1024;
+        }
+        else if (size <= 16 * 1024) {
+            *shMemSize = 16 * 1024;
+        }
+        else if (size <= 32 * 1024) {
+            *shMemSize = 32 * 1024;
+        }
+        else if (size <= 64 * 1024) {
+            *shMemSize = 64 * 1024;
+        }
+        else if (size <= 100 * 1024) {
+            *shMemSize = 100 * 1024;
+        }
+        else if (size <= 132 * 1024) {
+            *shMemSize = 132 * 1024;
+        }
+        else if (size <= 164 * 1024) {
+            *shMemSize = 164 * 1024;
+        }
+        else if (size <= 196 * 1024) {
+            *shMemSize = 196 * 1024;
+        }
+        else if (size <= 228 * 1024) {
+            *shMemSize = 228 * 1024;
+        }
+        else {
+            return CUDA_OCC_ERROR_INVALID_INPUT;
+        }
+        break;
+    }
+    default:
+        return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Shared memory based on the new carveoutConfig API introduced with Volta
+ */
+static __OCC_INLINE cudaOccError cudaOccSMemPreferenceVoltaPlus(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+    size_t preferenceShmemSize;
+
+    // CUDA 9.0 introduces a new API to set shared memory - L1 configuration on supported
+    // devices. This preference will take precedence over the older cacheConfig setting.
+    // Map cacheConfig to its effective preference value.
+    int effectivePreference = state->carveoutConfig;
+    if ((effectivePreference < SHAREDMEM_CARVEOUT_DEFAULT) || (effectivePreference > SHAREDMEM_CARVEOUT_MAX_SHARED)) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+    
+    if (effectivePreference == SHAREDMEM_CARVEOUT_DEFAULT) {
+        switch (state->cacheConfig)
+        {
+        case CACHE_PREFER_L1:
+            effectivePreference = SHAREDMEM_CARVEOUT_MAX_L1;
+            break;
+        case CACHE_PREFER_SHARED:
+            effectivePreference = SHAREDMEM_CARVEOUT_MAX_SHARED;
+            break;
+        case CACHE_PREFER_EQUAL:
+            effectivePreference = SHAREDMEM_CARVEOUT_HALF;
+            break;
+        default:
+            effectivePreference = SHAREDMEM_CARVEOUT_DEFAULT;
+            break;
+        }
+    }
+
+    if (effectivePreference == SHAREDMEM_CARVEOUT_DEFAULT) {
+        preferenceShmemSize = properties->sharedMemPerMultiprocessor;
+    }
+    else {
+        preferenceShmemSize = (size_t) (effectivePreference * properties->sharedMemPerMultiprocessor) / 100;
+    }
+
+    status = cudaOccAlignUpShmemSizeVoltaPlus(&preferenceShmemSize, properties);
+    *limit = preferenceShmemSize;
+    return status;
+}
+
+/**
+ * Shared memory based on the cacheConfig
+ */
+static __OCC_INLINE cudaOccError cudaOccSMemPreference(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
+{
+    size_t bytes                          = 0;
+    size_t sharedMemPerMultiprocessorHigh = properties->sharedMemPerMultiprocessor;
+    cudaOccCacheConfig cacheConfig        = state->cacheConfig;
+
+    // Kepler has shared L1 cache / shared memory, and support cache
+    // configuration to trade one for the other. These values are needed to
+    // calculate the correct shared memory size for user requested cache
+    // configuration.
+    //
+    size_t minCacheSize                   = 16384;
+    size_t maxCacheSize                   = 49152;
+    size_t cacheAndSharedTotal            = sharedMemPerMultiprocessorHigh + minCacheSize;
+    size_t sharedMemPerMultiprocessorLow  = cacheAndSharedTotal - maxCacheSize;
+
+    switch (properties->computeMajor) {
+        case 3:
+            // Kepler supports 16KB, 32KB, or 48KB partitions for L1. The rest
+            // is shared memory.
+            //
+            switch (cacheConfig) {
+                default :
+                case CACHE_PREFER_NONE:
+                case CACHE_PREFER_SHARED:
+                    bytes = sharedMemPerMultiprocessorHigh;
+                    break;
+                case CACHE_PREFER_L1:
+                    bytes = sharedMemPerMultiprocessorLow;
+                    break;
+                case CACHE_PREFER_EQUAL:
+                    // Equal is the mid-point between high and low. It should be
+                    // equivalent to low + 16KB.
+                    //
+                    bytes = (sharedMemPerMultiprocessorHigh + sharedMemPerMultiprocessorLow) / 2;
+                    break;
+            }
+            break;
+        case 5:
+        case 6:
+            // Maxwell and Pascal have dedicated shared memory.
+            //
+            bytes = sharedMemPerMultiprocessorHigh;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    *limit = bytes;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Shared memory based on config requested by User
+ */
+static __OCC_INLINE cudaOccError cudaOccSMemPerMultiprocessor(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
+{
+    // Volta introduces a new API that allows for shared memory carveout preference. Because it is a shared memory preference,
+    // it is handled separately from the cache config preference.
+    if (properties->computeMajor >= 7) {
+        return cudaOccSMemPreferenceVoltaPlus(limit, properties, state);
+    }
+    return cudaOccSMemPreference(limit, properties, state);
+}
+
+/**
+ * Return the per block shared memory limit based on function config
+ */
+static __OCC_INLINE cudaOccError cudaOccSMemPerBlock(size_t *limit, const cudaOccDeviceProp *properties, cudaOccFuncShmemConfig shmemLimitConfig, size_t smemPerCta)
+{
+    switch (properties->computeMajor) {
+        case 2:
+        case 3:
+        case 4:
+        case 5:
+        case 6:
+            *limit = properties->sharedMemPerBlock;
+            break;
+        case 7:
+        case 8:
+        case 9:
+            switch (shmemLimitConfig) {
+                default:
+                case FUNC_SHMEM_LIMIT_DEFAULT:
+                    *limit = properties->sharedMemPerBlock;
+                    break;
+                case FUNC_SHMEM_LIMIT_OPTIN:
+                    if (smemPerCta > properties->sharedMemPerBlock) {
+                        *limit = properties->sharedMemPerBlockOptin;
+                    }
+                    else {
+                        *limit = properties->sharedMemPerBlock;
+                    }
+                    break;
+            }
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    // Starting Ampere, CUDA driver reserves additional shared memory per block
+    if (properties->computeMajor >= 8) {
+        *limit += properties->reservedSharedMemPerBlock;
+    }
+
+    return CUDA_OCC_SUCCESS;
+}
+
+/**
+ * Partitioned global caching mode support
+ */
+static __OCC_INLINE cudaOccError cudaOccPartitionedGlobalCachingModeSupport(cudaOccPartitionedGCSupport *limit, const cudaOccDeviceProp *properties)
+{
+    *limit = PARTITIONED_GC_NOT_SUPPORTED;
+
+    if ((properties->computeMajor == 5 && (properties->computeMinor == 2 || properties->computeMinor == 3)) ||
+        properties->computeMajor == 6) {
+        *limit = PARTITIONED_GC_SUPPORTED;
+    }
+
+    if (properties->computeMajor == 6 && properties->computeMinor == 0) {
+        *limit = PARTITIONED_GC_NOT_SUPPORTED;
+    }
+
+    return CUDA_OCC_SUCCESS;
+}
+
+///////////////////////////////////////////////
+//            User Input Sanity              //
+///////////////////////////////////////////////
+
+static __OCC_INLINE cudaOccError cudaOccDevicePropCheck(const cudaOccDeviceProp *properties)
+{
+    // Verify device properties
+    //
+    // Each of these limits must be a positive number.
+    //
+    // Compute capacity is checked during the occupancy calculation
+    //
+    if (properties->maxThreadsPerBlock          <= 0 ||
+        properties->maxThreadsPerMultiprocessor <= 0 ||
+        properties->regsPerBlock                <= 0 ||
+        properties->regsPerMultiprocessor       <= 0 ||
+        properties->warpSize                    <= 0 ||
+        properties->sharedMemPerBlock           <= 0 ||
+        properties->sharedMemPerMultiprocessor  <= 0 ||
+        properties->numSms                      <= 0) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    return CUDA_OCC_SUCCESS;
+}
+
+static __OCC_INLINE cudaOccError cudaOccFuncAttributesCheck(const cudaOccFuncAttributes *attributes)
+{
+    // Verify function attributes
+    //
+    if (attributes->maxThreadsPerBlock <= 0 ||
+        attributes->numRegs < 0) {            // Compiler may choose not to use
+                                              // any register (empty kernels,
+                                              // etc.)
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    return CUDA_OCC_SUCCESS;
+}
+
+static __OCC_INLINE cudaOccError cudaOccDeviceStateCheck(const cudaOccDeviceState *state)
+{
+    (void)state;   // silence unused-variable warning
+    // Placeholder
+    //
+
+    return CUDA_OCC_SUCCESS;
+}
+
+static __OCC_INLINE cudaOccError cudaOccInputCheck(
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+
+    status = cudaOccDevicePropCheck(properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    status = cudaOccFuncAttributesCheck(attributes);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    status = cudaOccDeviceStateCheck(state);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    return status;
+}
+
+///////////////////////////////////////////////
+//    Occupancy calculation Functions        //
+///////////////////////////////////////////////
+
+static __OCC_INLINE cudaOccPartitionedGCConfig cudaOccPartitionedGCExpected(
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes)
+{
+    cudaOccPartitionedGCSupport gcSupport;
+    cudaOccPartitionedGCConfig gcConfig;
+
+    cudaOccPartitionedGlobalCachingModeSupport(&gcSupport, properties);
+
+    gcConfig = attributes->partitionedGCConfig;
+
+    if (gcSupport == PARTITIONED_GC_NOT_SUPPORTED) {
+        gcConfig = PARTITIONED_GC_OFF;
+    }
+
+    return gcConfig;
+}
+
+// Warp limit
+//
+static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMWarpsLimit(
+    int                         *limit,
+    cudaOccPartitionedGCConfig   gcConfig,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    int                          blockSize)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+    int maxWarpsPerSm;
+    int warpsAllocatedPerCTA;
+    int maxBlocks;
+    (void)attributes;   // silence unused-variable warning
+
+    if (blockSize > properties->maxThreadsPerBlock) {
+        maxBlocks = 0;
+    }
+    else {
+        maxWarpsPerSm = properties->maxThreadsPerMultiprocessor / properties->warpSize;
+        warpsAllocatedPerCTA = __occDivideRoundUp(blockSize, properties->warpSize);
+        maxBlocks = 0;
+
+        if (gcConfig != PARTITIONED_GC_OFF) {
+            int maxBlocksPerSmPartition;
+            int maxWarpsPerSmPartition;
+
+            // If partitioned global caching is on, then a CTA can only use a SM
+            // partition (a half SM), and thus a half of the warp slots
+            // available per SM
+            //
+            maxWarpsPerSmPartition  = maxWarpsPerSm / 2;
+            maxBlocksPerSmPartition = maxWarpsPerSmPartition / warpsAllocatedPerCTA;
+            maxBlocks               = maxBlocksPerSmPartition * 2;
+        }
+        // On hardware that supports partitioned global caching, each half SM is
+        // guaranteed to support at least 32 warps (maximum number of warps of a
+        // CTA), so caching will not cause 0 occupancy due to insufficient warp
+        // allocation slots.
+        //
+        else {
+            maxBlocks = maxWarpsPerSm / warpsAllocatedPerCTA;
+        }
+    }
+
+    *limit = maxBlocks;
+
+    return status;
+}
+
+// Shared memory limit
+//
+static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMSmemLimit(
+    int                         *limit,
+    cudaOccResult               *result,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    int                          blockSize,
+    size_t                       dynamicSmemSize)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+    int allocationGranularity;
+    size_t userSmemPreference = 0;
+    size_t totalSmemUsagePerCTA;
+    size_t maxSmemUsagePerCTA;
+    size_t smemAllocatedPerCTA;
+    size_t staticSmemSize;
+    size_t sharedMemPerMultiprocessor;
+    size_t smemLimitPerCTA;
+    int maxBlocks;
+    int dynamicSmemSizeExceeded = 0;
+    int totalSmemSizeExceeded = 0;
+    (void)blockSize;   // silence unused-variable warning
+
+    status = cudaOccSMemAllocationGranularity(&allocationGranularity, properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // Obtain the user preferred shared memory size. This setting is ignored if
+    // user requests more shared memory than preferred.
+    //
+    status = cudaOccSMemPerMultiprocessor(&userSmemPreference, properties, state);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    staticSmemSize = attributes->sharedSizeBytes + properties->reservedSharedMemPerBlock;
+    totalSmemUsagePerCTA = staticSmemSize + dynamicSmemSize;
+    smemAllocatedPerCTA = __occRoundUp((int)totalSmemUsagePerCTA, (int)allocationGranularity);
+
+    maxSmemUsagePerCTA = staticSmemSize + attributes->maxDynamicSharedSizeBytes;
+
+    dynamicSmemSizeExceeded = 0;
+    totalSmemSizeExceeded   = 0;
+
+    // Obtain the user set maximum dynamic size if it exists
+    // If so, the current launch dynamic shared memory must not
+    // exceed the set limit
+    if (attributes->shmemLimitConfig != FUNC_SHMEM_LIMIT_DEFAULT &&
+        dynamicSmemSize > attributes->maxDynamicSharedSizeBytes) {
+        dynamicSmemSizeExceeded = 1;
+    }
+
+    status = cudaOccSMemPerBlock(&smemLimitPerCTA, properties, attributes->shmemLimitConfig, maxSmemUsagePerCTA);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    if (smemAllocatedPerCTA > smemLimitPerCTA) {
+        totalSmemSizeExceeded = 1;
+    }
+
+    if (dynamicSmemSizeExceeded || totalSmemSizeExceeded) {
+        maxBlocks = 0;
+    }
+    else {
+        // User requested shared memory limit is used as long as it is greater
+        // than the total shared memory used per CTA, i.e. as long as at least
+        // one CTA can be launched.
+        if (userSmemPreference >= smemAllocatedPerCTA) {
+            sharedMemPerMultiprocessor = userSmemPreference;
+        }
+        else {
+            // On Volta+, user requested shared memory will limit occupancy
+            // if it's less than shared memory per CTA. Otherwise, the
+            // maximum shared memory limit is used.
+            if (properties->computeMajor >= 7) {
+                sharedMemPerMultiprocessor = smemAllocatedPerCTA;
+                status = cudaOccAlignUpShmemSizeVoltaPlus(&sharedMemPerMultiprocessor, properties);
+                if (status != CUDA_OCC_SUCCESS) {
+                    return status;
+                }
+            }
+            else {
+                sharedMemPerMultiprocessor = properties->sharedMemPerMultiprocessor;
+            }
+        }
+
+        if (smemAllocatedPerCTA > 0) {
+            maxBlocks = (int)(sharedMemPerMultiprocessor / smemAllocatedPerCTA);
+        }
+        else {
+            maxBlocks = INT_MAX;
+        }
+    }
+
+    result->allocatedSharedMemPerBlock = smemAllocatedPerCTA;
+
+    *limit = maxBlocks;
+
+    return status;
+}
+
+static __OCC_INLINE
+cudaOccError cudaOccMaxBlocksPerSMRegsLimit(
+    int                         *limit,
+    cudaOccPartitionedGCConfig  *gcConfig,
+    cudaOccResult               *result,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    int                          blockSize)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+    int allocationGranularity;
+    int warpsAllocatedPerCTA;
+    int regsAllocatedPerCTA;
+    int regsAssumedPerCTA;
+    int regsPerWarp;
+    int regsAllocatedPerWarp;
+    int numSubPartitions;
+    int numRegsPerSubPartition;
+    int numWarpsPerSubPartition;
+    int numWarpsPerSM;
+    int maxBlocks;
+    int maxRegsPerThread;
+
+    status = cudaOccRegAllocationGranularity(
+        &allocationGranularity,
+        properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    status = cudaOccRegAllocationMaxPerThread(
+        &maxRegsPerThread,
+        properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    status = cudaOccSubPartitionsPerMultiprocessor(&numSubPartitions, properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    warpsAllocatedPerCTA = __occDivideRoundUp(blockSize, properties->warpSize);
+
+    // GPUs of compute capability 2.x and higher allocate registers to warps
+    //
+    // Number of regs per warp is regs per thread x warp size, rounded up to
+    // register allocation granularity
+    //
+    regsPerWarp          = attributes->numRegs * properties->warpSize;
+    regsAllocatedPerWarp = __occRoundUp(regsPerWarp, allocationGranularity);
+    regsAllocatedPerCTA  = regsAllocatedPerWarp * warpsAllocatedPerCTA;
+
+    // Hardware verifies if a launch fits the per-CTA register limit. For
+    // historical reasons, the verification logic assumes register
+    // allocations are made to all partitions simultaneously. Therefore, to
+    // simulate the hardware check, the warp allocation needs to be rounded
+    // up to the number of partitions.
+    //
+    regsAssumedPerCTA = regsAllocatedPerWarp * __occRoundUp(warpsAllocatedPerCTA, numSubPartitions);
+
+    if (properties->regsPerBlock < regsAssumedPerCTA ||   // Hardware check
+        properties->regsPerBlock < regsAllocatedPerCTA || // Software check
+        attributes->numRegs > maxRegsPerThread) {         // Per thread limit check
+        maxBlocks = 0;
+    }
+    else {
+        if (regsAllocatedPerWarp > 0) {
+            // Registers are allocated in each sub-partition. The max number
+            // of warps that can fit on an SM is equal to the max number of
+            // warps per sub-partition x number of sub-partitions.
+            //
+            numRegsPerSubPartition  = properties->regsPerMultiprocessor / numSubPartitions;
+            numWarpsPerSubPartition = numRegsPerSubPartition / regsAllocatedPerWarp;
+
+            maxBlocks = 0;
+
+            if (*gcConfig != PARTITIONED_GC_OFF) {
+                int numSubPartitionsPerSmPartition;
+                int numWarpsPerSmPartition;
+                int maxBlocksPerSmPartition;
+
+                // If partitioned global caching is on, then a CTA can only
+                // use a half SM, and thus a half of the registers available
+                // per SM
+                //
+                numSubPartitionsPerSmPartition = numSubPartitions / 2;
+                numWarpsPerSmPartition         = numWarpsPerSubPartition * numSubPartitionsPerSmPartition;
+                maxBlocksPerSmPartition        = numWarpsPerSmPartition / warpsAllocatedPerCTA;
+                maxBlocks                      = maxBlocksPerSmPartition * 2;
+            }
+
+            // Try again if partitioned global caching is not enabled, or if
+            // the CTA cannot fit on the SM with caching on (maxBlocks == 0).  In the latter
+            // case, the device will automatically turn off caching, except
+            // if the user forces enablement via PARTITIONED_GC_ON_STRICT to calculate
+            // occupancy and launch configuration.
+            //
+            if (maxBlocks == 0 && *gcConfig != PARTITIONED_GC_ON_STRICT) {
+               // In case *gcConfig was PARTITIONED_GC_ON flip it OFF since
+               // this is what it will be if we spread CTA across partitions.
+               //
+               *gcConfig = PARTITIONED_GC_OFF;
+               numWarpsPerSM = numWarpsPerSubPartition * numSubPartitions;
+               maxBlocks     = numWarpsPerSM / warpsAllocatedPerCTA;
+            }
+        }
+        else {
+            maxBlocks = INT_MAX;
+        }
+    }
+
+
+    result->allocatedRegistersPerBlock = regsAllocatedPerCTA;
+
+    *limit = maxBlocks;
+
+    return status;
+}
+
+// Barrier limit
+//
+static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMBlockBarrierLimit(
+    int                         *limit,
+    int                          ctaLimitBlocks,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes)
+{
+    cudaOccError status = CUDA_OCC_SUCCESS;
+    int numBarriersAvailable = 0;
+    int numBarriersUsed = attributes->numBlockBarriers;
+    int maxBlocks = INT_MAX;
+
+    switch(properties->computeMajor) {
+        case 5:
+        case 6:
+        case 7:
+            numBarriersAvailable = ctaLimitBlocks * 2;
+            break;
+        case 8:
+            if (properties->computeMinor == 0) {
+                numBarriersAvailable = ctaLimitBlocks * 2;
+            }
+            else {
+                numBarriersAvailable = ctaLimitBlocks;
+            }
+            break;
+        case 9:
+            numBarriersAvailable = ctaLimitBlocks * 2;
+            break;
+        default:
+            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
+    }
+
+    if (numBarriersUsed) {
+        maxBlocks = numBarriersAvailable / numBarriersUsed;
+    }
+
+    *limit = maxBlocks;
+
+    return status;
+}
+
+///////////////////////////////////
+//      API Implementations      //
+///////////////////////////////////
+
+static __OCC_INLINE
+cudaOccError cudaOccMaxActiveBlocksPerMultiprocessor(
+    cudaOccResult               *result,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    int                          blockSize,
+    size_t                       dynamicSmemSize)
+{
+    cudaOccError status          = CUDA_OCC_SUCCESS;
+    int          ctaLimitWarps   = 0;
+    int          ctaLimitBlocks  = 0;
+    int          ctaLimitSMem    = 0;
+    int          ctaLimitRegs    = 0;
+    int          ctaLimitBars    = 0;
+    int          ctaLimit        = 0;
+    unsigned int limitingFactors = 0;
+    
+    cudaOccPartitionedGCConfig gcConfig = PARTITIONED_GC_OFF;
+
+    if (!result || !properties || !attributes || !state || blockSize <= 0) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    ///////////////////////////
+    // Check user input
+    ///////////////////////////
+
+    status = cudaOccInputCheck(properties, attributes, state);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    ///////////////////////////
+    // Initialization
+    ///////////////////////////
+
+    gcConfig = cudaOccPartitionedGCExpected(properties, attributes);
+
+    ///////////////////////////
+    // Compute occupancy
+    ///////////////////////////
+
+    // Limits due to registers/SM
+    // Also compute if partitioned global caching has to be turned off
+    //
+    status = cudaOccMaxBlocksPerSMRegsLimit(&ctaLimitRegs, &gcConfig, result, properties, attributes, blockSize);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // SMs on GP100 (6.0) have 2 subpartitions, while those on GP10x have 4.
+    // As a result, an SM on GP100 may be able to run more CTAs than the one on GP10x.
+    // For forward compatibility within Pascal family, if a function cannot run on GP10x (maxBlock == 0),
+    // we do not let it run on any Pascal processor, even though it may be able to run on GP100.
+    // Therefore, we check the occupancy on GP10x when it can run on GP100
+    //
+    if (properties->computeMajor == 6 && properties->computeMinor == 0 && ctaLimitRegs) {
+        cudaOccDeviceProp propertiesGP10x;
+        cudaOccPartitionedGCConfig gcConfigGP10x = gcConfig;
+        int ctaLimitRegsGP10x = 0;
+
+        // Set up properties for GP10x
+        memcpy(&propertiesGP10x, properties, sizeof(propertiesGP10x));
+        propertiesGP10x.computeMinor = 1;
+
+        status = cudaOccMaxBlocksPerSMRegsLimit(&ctaLimitRegsGP10x, &gcConfigGP10x, result, &propertiesGP10x, attributes, blockSize);
+        if (status != CUDA_OCC_SUCCESS) {
+            return status;
+        }
+
+        if (ctaLimitRegsGP10x == 0) {
+            ctaLimitRegs = 0;
+        }
+    }
+
+    // Limits due to warps/SM
+    //
+    status = cudaOccMaxBlocksPerSMWarpsLimit(&ctaLimitWarps, gcConfig, properties, attributes, blockSize);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // Limits due to blocks/SM
+    //
+    status = cudaOccMaxBlocksPerMultiprocessor(&ctaLimitBlocks, properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // Limits due to shared memory/SM
+    //
+    status = cudaOccMaxBlocksPerSMSmemLimit(&ctaLimitSMem, result, properties, attributes, state, blockSize, dynamicSmemSize);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    ///////////////////////////
+    // Overall occupancy
+    ///////////////////////////
+
+    // Overall limit is min() of limits due to above reasons
+    //
+    ctaLimit = __occMin(ctaLimitRegs, __occMin(ctaLimitSMem, __occMin(ctaLimitWarps, ctaLimitBlocks)));
+
+    // Determine occupancy limiting factors
+    //
+    if (ctaLimit == ctaLimitWarps) {
+        limitingFactors |= OCC_LIMIT_WARPS;
+    }
+    if (ctaLimit == ctaLimitRegs) {
+        limitingFactors |= OCC_LIMIT_REGISTERS;
+    }
+    if (ctaLimit == ctaLimitSMem) {
+        limitingFactors |= OCC_LIMIT_SHARED_MEMORY;
+    }
+    if (ctaLimit == ctaLimitBlocks) {
+        limitingFactors |= OCC_LIMIT_BLOCKS;
+    }
+
+    // For Hopper onwards compute the limits to occupancy based on block barrier count
+    //
+    if (properties->computeMajor >= 9 && attributes->numBlockBarriers > 0) {
+        // Limits due to barrier/SM
+        //
+        status = cudaOccMaxBlocksPerSMBlockBarrierLimit(&ctaLimitBars, ctaLimitBlocks, properties, attributes);
+        if (status != CUDA_OCC_SUCCESS) {
+            return status;
+        }
+
+        // Recompute overall limit based on barrier/SM
+        //
+        ctaLimit = __occMin(ctaLimitBars, ctaLimit);
+
+        // Determine if this is occupancy limiting factor
+        //
+        if (ctaLimit == ctaLimitBars) {
+            limitingFactors |= OCC_LIMIT_BARRIERS;
+        }
+    }
+    else {
+        ctaLimitBars = INT_MAX;
+    }
+
+    // Fill in the return values
+    //
+    result->limitingFactors = limitingFactors;
+
+    result->blockLimitRegs      = ctaLimitRegs;
+    result->blockLimitSharedMem = ctaLimitSMem;
+    result->blockLimitWarps     = ctaLimitWarps;
+    result->blockLimitBlocks    = ctaLimitBlocks;
+    result->blockLimitBarriers  = ctaLimitBars;
+    result->partitionedGCConfig = gcConfig;
+
+    // Final occupancy
+    result->activeBlocksPerMultiprocessor = ctaLimit;
+
+    return CUDA_OCC_SUCCESS;
+}
+
+static __OCC_INLINE
+cudaOccError cudaOccAvailableDynamicSMemPerBlock(
+    size_t                      *bytesAvailable,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    int                         numBlocks,
+    int                         blockSize)
+{
+    int allocationGranularity;
+    size_t smemLimitPerBlock;
+    size_t smemAvailableForDynamic;
+    size_t userSmemPreference = 0;
+    size_t sharedMemPerMultiprocessor;
+    cudaOccResult result;
+    cudaOccError status = CUDA_OCC_SUCCESS;
+
+    if (numBlocks <= 0)
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+
+    // First compute occupancy of potential kernel launch.
+    //
+    status = cudaOccMaxActiveBlocksPerMultiprocessor(&result, properties, attributes, state, blockSize, 0);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+    // Check if occupancy is achievable given user requested number of blocks. 
+    //
+    if (result.activeBlocksPerMultiprocessor < numBlocks) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    status = cudaOccSMemAllocationGranularity(&allocationGranularity, properties);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // Return the per block shared memory limit based on function config.
+    //
+    status = cudaOccSMemPerBlock(&smemLimitPerBlock, properties, attributes->shmemLimitConfig, properties->sharedMemPerMultiprocessor);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    // If there is only a single block needed per SM, then the user preference can be ignored and the fully SW
+    // limit is allowed to be used as shared memory otherwise if more than one block is needed, then the user
+    // preference sets the total limit of available shared memory.
+    //
+    cudaOccSMemPerMultiprocessor(&userSmemPreference, properties, state);
+    if (numBlocks == 1) {
+        sharedMemPerMultiprocessor = smemLimitPerBlock;
+    }
+    else {
+        if (!userSmemPreference) {
+            userSmemPreference = 1 ;
+            status = cudaOccAlignUpShmemSizeVoltaPlus(&userSmemPreference, properties);
+            if (status != CUDA_OCC_SUCCESS) {
+                return status;
+            }
+        }
+        sharedMemPerMultiprocessor = userSmemPreference;
+    }
+
+    // Compute total shared memory available per SM
+    //
+    smemAvailableForDynamic =  sharedMemPerMultiprocessor / numBlocks;
+    smemAvailableForDynamic = (smemAvailableForDynamic / allocationGranularity) * allocationGranularity;
+
+    // Cap shared memory
+    //
+    if (smemAvailableForDynamic > smemLimitPerBlock) {
+        smemAvailableForDynamic = smemLimitPerBlock;
+    }
+
+    // Now compute dynamic shared memory size
+    smemAvailableForDynamic = smemAvailableForDynamic - attributes->sharedSizeBytes; 
+
+    // Cap computed dynamic SM by user requested limit specified via cuFuncSetAttribute()
+    //
+    if (smemAvailableForDynamic > attributes->maxDynamicSharedSizeBytes)
+        smemAvailableForDynamic = attributes->maxDynamicSharedSizeBytes;
+
+    *bytesAvailable = smemAvailableForDynamic;
+    return CUDA_OCC_SUCCESS;
+}
+
+static __OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
+    int                         *minGridSize,
+    int                         *blockSize,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    size_t                     (*blockSizeToDynamicSMemSize)(int),
+    size_t                       dynamicSMemSize)
+{
+    cudaOccError  status = CUDA_OCC_SUCCESS;
+    cudaOccResult result;
+
+    // Limits
+    int occupancyLimit;
+    int granularity;
+    int blockSizeLimit;
+
+    // Recorded maximum
+    int maxBlockSize = 0;
+    int numBlocks    = 0;
+    int maxOccupancy = 0;
+
+    // Temporary
+    int blockSizeToTryAligned;
+    int blockSizeToTry;
+    int blockSizeLimitAligned;
+    int occupancyInBlocks;
+    int occupancyInThreads;
+
+    ///////////////////////////
+    // Check user input
+    ///////////////////////////
+
+    if (!minGridSize || !blockSize || !properties || !attributes || !state) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    status = cudaOccInputCheck(properties, attributes, state);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////
+    // Try each block size, and pick the block size with maximum occupancy
+    /////////////////////////////////////////////////////////////////////////////////
+
+    occupancyLimit = properties->maxThreadsPerMultiprocessor;
+    granularity    = properties->warpSize;
+
+    blockSizeLimit        = __occMin(properties->maxThreadsPerBlock, attributes->maxThreadsPerBlock);
+    blockSizeLimitAligned = __occRoundUp(blockSizeLimit, granularity);
+
+    for (blockSizeToTryAligned = blockSizeLimitAligned; blockSizeToTryAligned > 0; blockSizeToTryAligned -= granularity) {
+        blockSizeToTry = __occMin(blockSizeLimit, blockSizeToTryAligned);
+
+        // Ignore dynamicSMemSize if the user provides a mapping
+        //
+        if (blockSizeToDynamicSMemSize) {
+            dynamicSMemSize = (*blockSizeToDynamicSMemSize)(blockSizeToTry);
+        }
+
+        status = cudaOccMaxActiveBlocksPerMultiprocessor(
+            &result,
+            properties,
+            attributes,
+            state,
+            blockSizeToTry,
+            dynamicSMemSize);
+
+        if (status != CUDA_OCC_SUCCESS) {
+            return status;
+        }
+
+        occupancyInBlocks = result.activeBlocksPerMultiprocessor;
+        occupancyInThreads = blockSizeToTry * occupancyInBlocks;
+
+        if (occupancyInThreads > maxOccupancy) {
+            maxBlockSize = blockSizeToTry;
+            numBlocks    = occupancyInBlocks;
+            maxOccupancy = occupancyInThreads;
+        }
+
+        // Early out if we have reached the maximum
+        //
+        if (occupancyLimit == maxOccupancy) {
+            break;
+        }
+    }
+
+    ///////////////////////////
+    // Return best available
+    ///////////////////////////
+
+    // Suggested min grid size to achieve a full machine launch
+    //
+    *minGridSize = numBlocks * properties->numSms;
+    *blockSize = maxBlockSize;
+
+    return status;
+}
+
+
+#if defined(__cplusplus)
+
+namespace {
+
+__OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
+    int                         *minGridSize,
+    int                         *blockSize,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    size_t                       dynamicSMemSize)
+{
+    return cudaOccMaxPotentialOccupancyBlockSize(
+        minGridSize,
+        blockSize,
+        properties,
+        attributes,
+        state,
+        NULL,
+        dynamicSMemSize);
+}
+
+template 
+__OCC_INLINE
+cudaOccError cudaOccMaxPotentialOccupancyBlockSizeVariableSMem(
+    int                         *minGridSize,
+    int                         *blockSize,
+    const cudaOccDeviceProp     *properties,
+    const cudaOccFuncAttributes *attributes,
+    const cudaOccDeviceState    *state,
+    UnaryFunction                blockSizeToDynamicSMemSize)
+{
+    cudaOccError  status = CUDA_OCC_SUCCESS;
+    cudaOccResult result;
+
+    // Limits
+    int occupancyLimit;
+    int granularity;
+    int blockSizeLimit;
+
+    // Recorded maximum
+    int maxBlockSize = 0;
+    int numBlocks    = 0;
+    int maxOccupancy = 0;
+
+    // Temporary
+    int blockSizeToTryAligned;
+    int blockSizeToTry;
+    int blockSizeLimitAligned;
+    int occupancyInBlocks;
+    int occupancyInThreads;
+    size_t dynamicSMemSize;
+
+    ///////////////////////////
+    // Check user input
+    ///////////////////////////
+
+    if (!minGridSize || !blockSize || !properties || !attributes || !state) {
+        return CUDA_OCC_ERROR_INVALID_INPUT;
+    }
+
+    status = cudaOccInputCheck(properties, attributes, state);
+    if (status != CUDA_OCC_SUCCESS) {
+        return status;
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////
+    // Try each block size, and pick the block size with maximum occupancy
+    /////////////////////////////////////////////////////////////////////////////////
+
+    occupancyLimit = properties->maxThreadsPerMultiprocessor;
+    granularity    = properties->warpSize;
+    blockSizeLimit        = __occMin(properties->maxThreadsPerBlock, attributes->maxThreadsPerBlock);
+    blockSizeLimitAligned = __occRoundUp(blockSizeLimit, granularity);
+
+    for (blockSizeToTryAligned = blockSizeLimitAligned; blockSizeToTryAligned > 0; blockSizeToTryAligned -= granularity) {
+        blockSizeToTry = __occMin(blockSizeLimit, blockSizeToTryAligned);
+
+        dynamicSMemSize = blockSizeToDynamicSMemSize(blockSizeToTry);
+
+        status = cudaOccMaxActiveBlocksPerMultiprocessor(
+            &result,
+            properties,
+            attributes,
+            state,
+            blockSizeToTry,
+            dynamicSMemSize);
+
+        if (status != CUDA_OCC_SUCCESS) {
+            return status;
+        }
+
+        occupancyInBlocks = result.activeBlocksPerMultiprocessor;
+
+        occupancyInThreads = blockSizeToTry * occupancyInBlocks;
+
+        if (occupancyInThreads > maxOccupancy) {
+            maxBlockSize = blockSizeToTry;
+            numBlocks    = occupancyInBlocks;
+            maxOccupancy = occupancyInThreads;
+        }
+
+        // Early out if we have reached the maximum
+        //
+        if (occupancyLimit == maxOccupancy) {
+            break;
+        }
+    }
+
+    ///////////////////////////
+    // Return best available
+    ///////////////////////////
+
+    // Suggested min grid size to achieve a full machine launch
+    //
+    *minGridSize = numBlocks * properties->numSms;
+    *blockSize = maxBlockSize;
+
+    return status;
+}
+
+} // namespace anonymous
+
+#endif /*__cplusplus */
+
+#undef __OCC_INLINE
+
+#endif /*__cuda_occupancy_h__*/
diff --git a/shared/package-files/56/56d6fffc127faab0b2ed3062b06e0133ca8d5f30d8ae5fb134354b6c70ac6086/_data_sparstity_utils.py b/shared/package-files/56/56d6fffc127faab0b2ed3062b06e0133ca8d5f30d8ae5fb134354b6c70ac6086/_data_sparstity_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..50d5684961bc807d5ae1b02615ade168416c9b3d
--- /dev/null
+++ b/shared/package-files/56/56d6fffc127faab0b2ed3062b06e0133ca8d5f30d8ae5fb134354b6c70ac6086/_data_sparstity_utils.py
@@ -0,0 +1,44 @@
+# mypy: allow-untyped-defs
+import logging
+
+from torch.ao.pruning._experimental.data_sparsifier.base_data_sparsifier import (
+    SUPPORTED_TYPES,
+)
+
+
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+def _attach_model_to_data_sparsifier(module, data_sparsifier, config=None):
+    """Attaches a data sparsifier to all the layers of the module.
+    Essentially, loop over all the weight parameters in the module and
+    attach it to the data sparsifier.
+    Note::
+        The '.' in the layer names are replaced with '_' (refer to _get_valid_name() below)
+        before attaching to the sparsifier. This is because, the data
+        sparsifier uses a dummy model inside to store the weight parameters.
+    """
+    if config is None:
+        config = {}
+    for name, parameter in module.named_parameters():
+        if type(parameter) in SUPPORTED_TYPES:
+            valid_name = _get_valid_name(name)
+            # will be defaulted to default configs
+            data_sparsifier.add_data(
+                name=valid_name, data=parameter, **config.get(valid_name, {})
+            )
+
+
+def _get_valid_name(name):
+    return name.replace(".", "_")  # . is not allowed as a name
+
+
+def _log_sparsified_level(model, data_sparsifier) -> None:
+    # Show the level of sparsity AFTER step:
+    for name, parameter in model.named_parameters():
+        if type(parameter) not in SUPPORTED_TYPES:
+            continue
+        valid_name = _get_valid_name(name)
+        mask = data_sparsifier.get_mask(name=valid_name)
+        sparsity_level = 1.0 - mask.float().mean()
+        logger.info("Sparsity in layer %s = % .2%", name, sparsity_level)
diff --git a/shared/package-files/56/56defbf3d56bb7a938c302b877e5c69e6031075cd16af14b9b11edd28a79f5b0/__init__.cpython-311.pyc b/shared/package-files/56/56defbf3d56bb7a938c302b877e5c69e6031075cd16af14b9b11edd28a79f5b0/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41cc62c968de2569d227e724c931d71389ddabed
Binary files /dev/null and b/shared/package-files/56/56defbf3d56bb7a938c302b877e5c69e6031075cd16af14b9b11edd28a79f5b0/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/56dfa4b7e96c6e2b86c6049b16bb21249fc5b7b69a27d44c55892ba5848bc9f2/__init__.cpython-311.pyc b/shared/package-files/56/56dfa4b7e96c6e2b86c6049b16bb21249fc5b7b69a27d44c55892ba5848bc9f2/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83b5c19dd2aec00dfc6ef22e134b4b258890475a
Binary files /dev/null and b/shared/package-files/56/56dfa4b7e96c6e2b86c6049b16bb21249fc5b7b69a27d44c55892ba5848bc9f2/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/56/56e23ce1e13f7a4677cae6943218ebf7d30034905b1844b3da6f5cd8c9bb5ed6/setup.cpython-311.pyc b/shared/package-files/56/56e23ce1e13f7a4677cae6943218ebf7d30034905b1844b3da6f5cd8c9bb5ed6/setup.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c3054eef0b59a1d6633039c0534b4f0036ee2ba
Binary files /dev/null and b/shared/package-files/56/56e23ce1e13f7a4677cae6943218ebf7d30034905b1844b3da6f5cd8c9bb5ed6/setup.cpython-311.pyc differ
diff --git a/shared/package-files/56/56e3f375d878fa419d4d983b1b17408a114389cee51eb1f103181e902dac729c/object_ptr.h b/shared/package-files/56/56e3f375d878fa419d4d983b1b17408a114389cee51eb1f103181e902dac729c/object_ptr.h
new file mode 100644
index 0000000000000000000000000000000000000000..b5b2ac98e0741018856f7fd4e63cf33aa6efe90d
--- /dev/null
+++ b/shared/package-files/56/56e3f375d878fa419d4d983b1b17408a114389cee51eb1f103181e902dac729c/object_ptr.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+template 
+class TORCH_PYTHON_API THPPointer {
+ public:
+  THPPointer() : ptr(nullptr) {}
+  explicit THPPointer(T* ptr) noexcept : ptr(ptr) {}
+  THPPointer(THPPointer&& p) noexcept : ptr(std::exchange(p.ptr, nullptr)) {}
+  THPPointer(const THPPointer& p) = delete;
+  THPPointer& operator=(const THPPointer&) = delete;
+
+  ~THPPointer() {
+    free();
+  }
+  T* get() {
+    return ptr;
+  }
+  const T* get() const {
+    return ptr;
+  }
+  THPPointer dup() const {
+    return dup(ptr);
+  }
+  static THPPointer dup(const T* ptr) {
+    Py_XINCREF(ptr);
+    return THPPointer(
+        const_cast(ptr)); // NOLINT(cppcoreguidelines-pro-type-const-cast)
+  }
+  static THPPointer none() {
+    Py_INCREF(Py_None);
+    return THPPointer(reinterpret_cast(Py_None));
+  }
+  T* release() {
+    T* tmp = ptr;
+    ptr = nullptr;
+    return tmp;
+  }
+  operator T*() {
+    return ptr;
+  }
+  THPPointer& operator=(T* new_ptr) noexcept {
+    free();
+    ptr = new_ptr;
+    return *this;
+  }
+  THPPointer& operator=(THPPointer&& p) noexcept {
+    free();
+    ptr = p.ptr;
+    p.ptr = nullptr;
+    return *this;
+  }
+  T* operator->() {
+    return ptr;
+  }
+  explicit operator bool() const {
+    return ptr != nullptr;
+  }
+
+ private:
+  void free();
+  T* ptr = nullptr;
+};
+
+/**
+ * An RAII-style, owning pointer to a PyObject.  You must protect
+ * destruction of this object with the GIL.
+ *
+ * WARNING: Think twice before putting this as a field in a C++
+ * struct.  This class does NOT take out the GIL on destruction,
+ * so if you will need to ensure that the destructor of your struct
+ * is either (a) always invoked when the GIL is taken or (b) takes
+ * out the GIL itself.  Easiest way to avoid this problem is to
+ * not use THPPointer in this situation.
+ */
+using THPObjectPtr = THPPointer;
+using THPCodeObjectPtr = THPPointer;
+using THPFrameObjectPtr = THPPointer;
diff --git a/shared/package-files/56/56ec7680faeeaa18980a317309cd2222ee5f924d3c0fb0c40dd5bdadee3f7957/_modified.cpython-311.pyc b/shared/package-files/56/56ec7680faeeaa18980a317309cd2222ee5f924d3c0fb0c40dd5bdadee3f7957/_modified.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21e83c286a2c2bdc60a30993695d3e1a0c452584
Binary files /dev/null and b/shared/package-files/56/56ec7680faeeaa18980a317309cd2222ee5f924d3c0fb0c40dd5bdadee3f7957/_modified.cpython-311.pyc differ
diff --git a/shared/package-files/56/56f0206329b4f5606cf96f9974ed535051ab185b0057357b746111d62d78edd8/functional.py b/shared/package-files/56/56f0206329b4f5606cf96f9974ed535051ab185b0057357b746111d62d78edd8/functional.py
new file mode 100644
index 0000000000000000000000000000000000000000..eeff877260bcc083051c6622a2894677cb6324e4
--- /dev/null
+++ b/shared/package-files/56/56f0206329b4f5606cf96f9974ed535051ab185b0057357b746111d62d78edd8/functional.py
@@ -0,0 +1,452 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.distributed as dist
+from torch.autograd import Function
+
+# The two imports below are not always available depending on the
+# USE_DISTRIBUTED compile flag. Make sure they raise import error
+# if we're trying to use them.
+from torch.distributed import group, ReduceOp
+
+
+def broadcast(tensor, src, group=group.WORLD):
+    """
+    Broadcasts the tensor to the whole group.
+
+    ``tensor`` must have the same number of elements in all processes
+    participating in the collective.
+
+    Arguments:
+        tensor (Tensor): Data to be sent if ``src`` is the rank of current
+            process.
+        src (int): Source rank.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Received tensor from the broadcast op.
+
+    """
+    return _Broadcast.apply(src, group, tensor)
+
+
+def gather(tensor, dst=0, group=group.WORLD):
+    """
+    Gathers a list of tensors in a single process.
+
+    Arguments:
+        tensor (Tensor): Input tensor.
+        dst (int, optional): Destination rank (default is 0).
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple[Tensor]: List of appropriately-sized tensors with the gathered data.
+    """
+    return _Gather.apply(dst, group, tensor)
+
+
+def scatter(tensors, src=0, group=group.WORLD):
+    """
+    Scatters a list of tensors to all processes in a group.
+
+    Each process will receive exactly one tensor and store its data in the
+    ``tensor`` argument.
+
+    Arguments:
+        tensors (list[Tensor]): List of tensors to scatter on the source rank.
+            Receivers must pass ``None`.
+        src (int, optional): Source rank (default is 0).
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output tensor from the scatter operation.
+
+    """
+    return _Scatter.apply(src, group, *tensors)
+
+
+def reduce(tensor, dst, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces the tensor data across all machines.
+
+    Only the process with rank ``dst`` is going to receive the final result.
+
+    Arguments:
+        tensor (Tensor): Input of the collective.
+        dst (int): Destination rank.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _Reduce.apply(dst, op, group, tensor)
+
+
+def reduce_scatter(output, input_list, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces, then scatters a list of tensors to all processes in a group.
+
+    Arguments:
+        output (Tensor): Output tensor.
+        input_list (list[Tensor]): List of tensors to reduce and scatter.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _Reduce_Scatter.apply(op, group, output, *input_list)
+
+
+def all_gather(tensor, group=group.WORLD):
+    """
+    Gathers tensors from the whole group in a list.
+
+    Arguments:
+        tensor (Tensor): Tensor to be broadcast from current process.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple([Tensor]): Output of the collective.
+
+    """
+    return _AllGather.apply(group, tensor)
+
+
+def _all_gather_base(output_tensor, input_tensor, group=group.WORLD):
+    """
+    Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
+
+    Args:
+        output_tensor (Tensor): Output tensor. It should contain
+            correctly-sized tensors to be used for output of the collective.
+        input_tensor (Tensor): Tensor to be broadcast from current process.
+        group (ProcessGroup, optional): The process group to work on. If None,
+            the default process group will be used.
+
+    Examples:
+        >>> # All tensors below are of torch.int64 dtype.
+        >>> # We have 2 process groups, 2 ranks.
+        >>> # xdoctest: +SKIP("incorrect want text")
+        >>> output_tensor = torch.zeros(2, dtype=torch.int64)
+        >>> output_tensor
+        [tensor([0, 0])] # Rank 0 and 1
+        >>> tensor = torch.arange(1, dtype=torch.int64) + 1 + rank
+        >>> tensor
+        tensor([1]) # Rank 0
+        tensor([2]) # Rank 1
+        >>> dist.all_gather_base(output_tensor, tensor)
+        >>> output_tensor
+        tensor([1,2]) # Rank 0
+        tensor([1,2]) # Rank 1
+
+    .. warning::
+        `_all_gather_base` is experimental and subject to change.
+        It is the caller's responsibility to ensure the output_tensor
+        is correctly sized.
+
+    """
+    return _AllGatherBase.apply(output_tensor, input_tensor, group)
+
+
+def all_to_all(output_tensor_list, input_tensor_list, group=group.WORLD):
+    """
+    Each process scatters list of input tensors to all processes in a group and return gathered list of tensors in output list.
+
+    Arguments:
+        output_tensor_list (list[Tensor]): list of tensors to gather one per rank.
+        input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        tuple([Tensor]): Output of the collective.
+
+    """
+    return _AlltoAll.apply(group, output_tensor_list, *input_tensor_list)
+
+
+def all_to_all_single(
+    output,
+    input,
+    output_split_sizes=None,
+    input_split_sizes=None,
+    group=group.WORLD,
+):
+    """
+    Each process splits input tensor and then scatters the split list to all processes in a group.
+
+    Then concatenate the received tensors from all the processes in the group and return single output tensor.
+
+    Arguments:
+        output (Tensor): Gathered concatenated output tensor.
+        input (Tensor): Input tensor to scatter.
+        output_split_sizes: (list[Int], optional): Output split sizes for dim 0
+            if specified None or empty, dim 0 of ``output`` tensor must divide
+            equally by ``world_size``.
+        input_split_sizes: (list[Int], optional): Input split sizes for dim 0
+            if specified None or empty, dim 0 of ``input`` tensor must divide
+            equally by ``world_size``.
+
+    Returns:
+        Tensor: Output of the collective.
+
+    """
+    return _AlltoAllSingle.apply(
+        group, output, output_split_sizes, input_split_sizes, input
+    )
+
+
+def all_reduce(tensor, op=ReduceOp.SUM, group=group.WORLD):
+    """
+    Reduces the tensor data across all machines in such a way that all get the final result.
+
+    After the call the returned tensor is going to be bitwise
+    identical in all processes.
+
+    Arguments:
+        tensor (Tensor): Input of the collective.
+        op (optional): One of the values from
+            ``torch.distributed.ReduceOp``
+            enum.  Specifies an operation used for element-wise reductions.
+        group (ProcessGroup, optional): The process group to work on.
+
+    Returns:
+        Tensor: Output of the collective
+
+    """
+    return _AllReduce.apply(op, group, tensor)
+
+
+class _Broadcast(Function):
+    @staticmethod
+    def forward(ctx, src, group, tensor):
+        ctx.src = src
+        ctx.group = group
+        ctx.rank = dist.get_rank(group=group)
+        # torch.distributed makes all the calls in place
+        # we allocate new tensors to avoid this
+        tensor = tensor.clone()
+        dist.broadcast(tensor, src, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        gx = _Reduce.apply(ctx.src, ReduceOp.SUM, ctx.group, grad_output)
+        if ctx.src != ctx.rank:
+            gx.zero_()
+        return (None, None, gx)
+
+
+class _Gather(Function):
+    @staticmethod
+    def forward(ctx, dst, group, tensor):
+        ctx.dst = dst
+        ctx.group = group
+        # Need to create a list of tensors here to do the
+        # aggregation, get it from the group size
+        # tensor should be correctly sized for the method
+        # gathering
+        tensor_list = [
+            torch.zeros_like(tensor) for i in range(dist.get_world_size(group=group))
+        ]
+
+        tensor = tensor.contiguous()
+        if dist.get_rank(group=group) == dst:
+            dist.gather(tensor, tensor_list, dst, group=group)
+        else:
+            dist.gather(tensor, None, dst, group=group)
+        return tuple(tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        return (None, None) + (_Scatter.apply(ctx.dst, ctx.group, *grad_outputs),)
+
+
+class _Scatter(Function):
+    @staticmethod
+    def forward(ctx, src, group, *tensors):
+        ctx.src = src
+        ctx.group = group
+        assert all(t.size() == tensors[0].size() for t in tensors)
+        output = torch.zeros_like(tensors[0])
+        if dist.get_rank(group=group) == src:
+            dist.scatter(output, list(tensors), src, group=group)
+        else:
+            dist.scatter(output, None, src, group=group)
+        return output
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None) + _Gather.apply(ctx.src, ctx.group, grad_output)
+
+
+class _Reduce(Function):
+    @staticmethod
+    def forward(ctx, src, op, group, tensor):
+        ctx.src = src
+        ctx.group = group
+        tensor = tensor.clone()
+        dist.reduce(tensor, src, op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None, None) + (_Broadcast.apply(ctx.src, ctx.group, grad_output),)
+
+
+class _Reduce_Scatter(Function):
+    @staticmethod
+    def forward(ctx, op, group, tensor, *input_tensor_list):
+        ctx.group = group
+        # Need contiguous tensors for collectives.
+        tensor = tensor.contiguous()
+        input_tensor_list = tuple(t.contiguous() for t in input_tensor_list)
+        dist.reduce_scatter(tensor, list(input_tensor_list), op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None, None) + _AllGather.apply(ctx.group, grad_output)
+
+
+class _AllGather(Function):
+    @staticmethod
+    def forward(ctx, group, tensor):
+        # Need contiguous tensors for collectives.
+        tensor = tensor.contiguous()
+
+        ctx.group = group
+        out_tensor_list = [
+            torch.empty_like(tensor) for _ in range(dist.get_world_size(group=group))
+        ]
+
+        dist.all_gather(out_tensor_list, tensor, group=group)
+        return tuple(out_tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        if dist.get_backend(group=ctx.group) is dist.Backend.NCCL:
+            rank = dist.get_rank(group=ctx.group)
+            gx = torch.empty_like(grad_outputs[rank])
+            gx = _Reduce_Scatter.apply(ReduceOp.SUM, ctx.group, gx, *grad_outputs)
+        else:
+            # As many backends doesn't support ReduceScatter, we use AlltoAll with .sum()
+            # to emulate the ReduceScatter behavior
+            tensor_list = [torch.empty_like(tensor) for tensor in grad_outputs]
+            gxs = _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
+            gx = torch.sum(torch.stack(gxs), dim=0)
+        return (None, gx)
+
+
+class _AllGatherBase(Function):
+    @staticmethod
+    def forward(ctx, output_tensor, input_tensor, group):
+        ctx.group = group
+        dist._all_gather_base(output_tensor, input_tensor.contiguous(), group=group)
+        return output_tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        if dist.get_backend(group=ctx.group) is dist.Backend.NCCL:
+            world_size = dist.get_world_size(group=ctx.group)
+            out_size = list(grad_output.size())
+            if out_size[0] % world_size != 0:
+                raise RuntimeError(
+                    f"Tensor with dimensions: {out_size} does "
+                    f"not have first dimension divisible by world_size: {world_size}"
+                )
+            out_size[0] = out_size[0] // dist.get_world_size(group=ctx.group)
+            gx = torch.empty(
+                out_size, device=grad_output.device, dtype=grad_output.dtype
+            )
+            dist._reduce_scatter_base(gx, grad_output, ReduceOp.SUM, ctx.group)
+        else:
+            raise RuntimeError("Backend not supported!")
+        return (None, gx, None)
+
+
+class _AlltoAll(Function):
+    @staticmethod
+    def forward(ctx, group, out_tensor_list, *tensors):
+        ctx.group = group
+        ctx.input_tensor_size_list = [
+            tensors[i].size() for i in range(dist.get_world_size(group=group))
+        ]
+        my_rank = dist.get_rank(group=group)
+        tensors = tuple(t.contiguous() for t in tensors)
+        # Implement it on means of scatter/gather, send/recv async operations have issues
+        if dist.get_backend(group=group) is dist.Backend.GLOO:
+            for i in range(dist.get_world_size(group=group)):
+                to_send = None
+                if i == my_rank:
+                    to_send = list(tensors)
+                dist.scatter(out_tensor_list[i], to_send, i, group=group)
+        else:
+            dist.all_to_all(
+                out_tensor_list,
+                list(tensors),
+                group=group,
+            )
+        return tuple(out_tensor_list)
+
+    @staticmethod
+    def backward(ctx, *grad_outputs):
+        tensor_list = [
+            torch.empty(
+                size, device=grad_outputs[0].device, dtype=grad_outputs[0].dtype
+            )
+            for size in ctx.input_tensor_size_list
+        ]
+        return (None, None) + _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
+
+
+class _AlltoAllSingle(Function):
+    @staticmethod
+    def forward(ctx, group, output, output_split_sizes, input_split_sizes, input):
+        ctx.group = group
+        ctx.input_size = input.size()
+        ctx.output_split_sizes = input_split_sizes
+        ctx.input_split_sizes = output_split_sizes
+        dist.all_to_all_single(
+            output,
+            input,
+            output_split_sizes=output_split_sizes,
+            input_split_sizes=input_split_sizes,
+            group=group,
+        )
+        return output
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        tensor = torch.empty(
+            ctx.input_size, device=grad_output.device, dtype=grad_output.dtype
+        )
+        return (None, None, None, None) + (
+            _AlltoAllSingle.apply(
+                ctx.group,
+                tensor,
+                ctx.output_split_sizes,
+                ctx.input_split_sizes,
+                grad_output.contiguous(),
+            ),
+        )
+
+
+class _AllReduce(Function):
+    @staticmethod
+    def forward(ctx, op, group, tensor):
+        ctx.group = group
+        ctx.op = op
+        tensor = tensor.clone(memory_format=torch.contiguous_format)
+        dist.all_reduce(tensor, op=op, group=group)
+        return tensor
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        return (None, None) + (_AllReduce.apply(ctx.op, ctx.group, grad_output),)
diff --git a/shared/package-files/56/56f212e6d79c1e31b9838ac4e3a012a9afe1cda3c14094aee43fba4e5de491c3/METADATA b/shared/package-files/56/56f212e6d79c1e31b9838ac4e3a012a9afe1cda3c14094aee43fba4e5de491c3/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..de290023fbee3502d0d0953eeeb6149e6543f56c
--- /dev/null
+++ b/shared/package-files/56/56f212e6d79c1e31b9838ac4e3a012a9afe1cda3c14094aee43fba4e5de491c3/METADATA
@@ -0,0 +1,38 @@
+Metadata-Version: 2.1
+Name: nvidia-cusolver-cu12
+Version: 11.7.1.2
+Summary: CUDA solver native runtime libraries
+Home-page: https://developer.nvidia.com/cuda-zone
+Author: Nvidia CUDA Installer Team
+Author-email: compute_installer@nvidia.com
+License: NVIDIA Proprietary Software
+Keywords: cuda,nvidia,runtime,machine learning,deep learning
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Education
+Classifier: Intended Audience :: Science/Research
+Classifier: License :: Other/Proprietary License
+Classifier: Natural Language :: English
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: Scientific/Engineering :: Mathematics
+Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
+Classifier: Topic :: Software Development
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Requires-Python: >=3
+License-File: License.txt
+Requires-Dist: nvidia-cublas-cu12
+Requires-Dist: nvidia-nvjitlink-cu12
+Requires-Dist: nvidia-cusparse-cu12
+
+CUDA solver native runtime libraries
diff --git a/shared/package-files/56/56f52b4eb975a4039ebe6850cb52d3a4e4b0d4fa0e02f03810047a3367cf579f/inner_native.h b/shared/package-files/56/56f52b4eb975a4039ebe6850cb52d3a4e4b0d4fa0e02f03810047a3367cf579f/inner_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..a4343decb14b38c7d3b44043df77318367a6c0ca
--- /dev/null
+++ b/shared/package-files/56/56f52b4eb975a4039ebe6850cb52d3a4e4b0d4fa0e02f03810047a3367cf579f/inner_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor inner(const at::Tensor & self, const at::Tensor & other);
+TORCH_API at::Tensor & inner_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/56f63a0f8cc378efc132d205278bcc948f1c7d0fd6298e5536226b2788af8c12/rendezvous.cpython-311.pyc b/shared/package-files/56/56f63a0f8cc378efc132d205278bcc948f1c7d0fd6298e5536226b2788af8c12/rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06a3ea2018c2d0d1839ce52ff24d6fb187f68893
Binary files /dev/null and b/shared/package-files/56/56f63a0f8cc378efc132d205278bcc948f1c7d0fd6298e5536226b2788af8c12/rendezvous.cpython-311.pyc differ
diff --git a/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/__init__.py b/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d37bd2766ac1c6c50660afff724338ab696afbbd
--- /dev/null
+++ b/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/__init__.py
@@ -0,0 +1,7 @@
+initialized = True
+
+def main():
+    print("Hello world!")
+
+if __name__ == '__main__':
+    main()
diff --git a/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/spam.py b/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/spam.py
new file mode 100644
index 0000000000000000000000000000000000000000..d37bd2766ac1c6c50660afff724338ab696afbbd
--- /dev/null
+++ b/shared/package-files/56/56f7ed595e767c558ded05def14b682893105daf504500c3443b458ca2431bc6/spam.py
@@ -0,0 +1,7 @@
+initialized = True
+
+def main():
+    print("Hello world!")
+
+if __name__ == '__main__':
+    main()
diff --git a/shared/package-files/56/56f8d313fb74019e53eb9287400702fbce788b7fe30e097b0b6e06296f3f080c/weakref.py b/shared/package-files/56/56f8d313fb74019e53eb9287400702fbce788b7fe30e097b0b6e06296f3f080c/weakref.py
new file mode 100644
index 0000000000000000000000000000000000000000..25b70927e29c31d5fbe48beab554270c866c5829
--- /dev/null
+++ b/shared/package-files/56/56f8d313fb74019e53eb9287400702fbce788b7fe30e097b0b6e06296f3f080c/weakref.py
@@ -0,0 +1,674 @@
+"""Weak reference support for Python.
+
+This module is an implementation of PEP 205:
+
+https://peps.python.org/pep-0205/
+"""
+
+# Naming convention: Variables named "wr" are weak reference objects;
+# they are called this instead of "ref" to avoid name collisions with
+# the module-global ref() function imported from _weakref.
+
+from _weakref import (
+     getweakrefcount,
+     getweakrefs,
+     ref,
+     proxy,
+     CallableProxyType,
+     ProxyType,
+     ReferenceType,
+     _remove_dead_weakref)
+
+from _weakrefset import WeakSet, _IterationGuard
+
+import _collections_abc  # Import after _weakref to avoid circular import.
+import sys
+import itertools
+
+ProxyTypes = (ProxyType, CallableProxyType)
+
+__all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
+           "WeakKeyDictionary", "ReferenceType", "ProxyType",
+           "CallableProxyType", "ProxyTypes", "WeakValueDictionary",
+           "WeakSet", "WeakMethod", "finalize"]
+
+
+_collections_abc.MutableSet.register(WeakSet)
+
+class WeakMethod(ref):
+    """
+    A custom `weakref.ref` subclass which simulates a weak reference to
+    a bound method, working around the lifetime problem of bound methods.
+    """
+
+    __slots__ = "_func_ref", "_meth_type", "_alive", "__weakref__"
+
+    def __new__(cls, meth, callback=None):
+        try:
+            obj = meth.__self__
+            func = meth.__func__
+        except AttributeError:
+            raise TypeError("argument should be a bound method, not {}"
+                            .format(type(meth))) from None
+        def _cb(arg):
+            # The self-weakref trick is needed to avoid creating a reference
+            # cycle.
+            self = self_wr()
+            if self._alive:
+                self._alive = False
+                if callback is not None:
+                    callback(self)
+        self = ref.__new__(cls, obj, _cb)
+        self._func_ref = ref(func, _cb)
+        self._meth_type = type(meth)
+        self._alive = True
+        self_wr = ref(self)
+        return self
+
+    def __call__(self):
+        obj = super().__call__()
+        func = self._func_ref()
+        if obj is None or func is None:
+            return None
+        return self._meth_type(func, obj)
+
+    def __eq__(self, other):
+        if isinstance(other, WeakMethod):
+            if not self._alive or not other._alive:
+                return self is other
+            return ref.__eq__(self, other) and self._func_ref == other._func_ref
+        return NotImplemented
+
+    def __ne__(self, other):
+        if isinstance(other, WeakMethod):
+            if not self._alive or not other._alive:
+                return self is not other
+            return ref.__ne__(self, other) or self._func_ref != other._func_ref
+        return NotImplemented
+
+    __hash__ = ref.__hash__
+
+
+class WeakValueDictionary(_collections_abc.MutableMapping):
+    """Mapping class that references values weakly.
+
+    Entries in the dictionary will be discarded when no strong
+    reference to the value exists anymore
+    """
+    # We inherit the constructor without worrying about the input
+    # dictionary; since it uses our .update() method, we get the right
+    # checks (if the other dictionary is a WeakValueDictionary,
+    # objects are unwrapped on the way out, and we always wrap on the
+    # way in).
+
+    def __init__(self, other=(), /, **kw):
+        def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref):
+            self = selfref()
+            if self is not None:
+                if self._iterating:
+                    self._pending_removals.append(wr.key)
+                else:
+                    # Atomic removal is necessary since this function
+                    # can be called asynchronously by the GC
+                    _atomic_removal(self.data, wr.key)
+        self._remove = remove
+        # A list of keys to be removed
+        self._pending_removals = []
+        self._iterating = set()
+        self.data = {}
+        self.update(other, **kw)
+
+    def _commit_removals(self, _atomic_removal=_remove_dead_weakref):
+        pop = self._pending_removals.pop
+        d = self.data
+        # We shouldn't encounter any KeyError, because this method should
+        # always be called *before* mutating the dict.
+        while True:
+            try:
+                key = pop()
+            except IndexError:
+                return
+            _atomic_removal(d, key)
+
+    def __getitem__(self, key):
+        if self._pending_removals:
+            self._commit_removals()
+        o = self.data[key]()
+        if o is None:
+            raise KeyError(key)
+        else:
+            return o
+
+    def __delitem__(self, key):
+        if self._pending_removals:
+            self._commit_removals()
+        del self.data[key]
+
+    def __len__(self):
+        if self._pending_removals:
+            self._commit_removals()
+        return len(self.data)
+
+    def __contains__(self, key):
+        if self._pending_removals:
+            self._commit_removals()
+        try:
+            o = self.data[key]()
+        except KeyError:
+            return False
+        return o is not None
+
+    def __repr__(self):
+        return "<%s at %#x>" % (self.__class__.__name__, id(self))
+
+    def __setitem__(self, key, value):
+        if self._pending_removals:
+            self._commit_removals()
+        self.data[key] = KeyedRef(value, self._remove, key)
+
+    def copy(self):
+        if self._pending_removals:
+            self._commit_removals()
+        new = WeakValueDictionary()
+        with _IterationGuard(self):
+            for key, wr in self.data.items():
+                o = wr()
+                if o is not None:
+                    new[key] = o
+        return new
+
+    __copy__ = copy
+
+    def __deepcopy__(self, memo):
+        from copy import deepcopy
+        if self._pending_removals:
+            self._commit_removals()
+        new = self.__class__()
+        with _IterationGuard(self):
+            for key, wr in self.data.items():
+                o = wr()
+                if o is not None:
+                    new[deepcopy(key, memo)] = o
+        return new
+
+    def get(self, key, default=None):
+        if self._pending_removals:
+            self._commit_removals()
+        try:
+            wr = self.data[key]
+        except KeyError:
+            return default
+        else:
+            o = wr()
+            if o is None:
+                # This should only happen
+                return default
+            else:
+                return o
+
+    def items(self):
+        if self._pending_removals:
+            self._commit_removals()
+        with _IterationGuard(self):
+            for k, wr in self.data.items():
+                v = wr()
+                if v is not None:
+                    yield k, v
+
+    def keys(self):
+        if self._pending_removals:
+            self._commit_removals()
+        with _IterationGuard(self):
+            for k, wr in self.data.items():
+                if wr() is not None:
+                    yield k
+
+    __iter__ = keys
+
+    def itervaluerefs(self):
+        """Return an iterator that yields the weak references to the values.
+
+        The references are not guaranteed to be 'live' at the time
+        they are used, so the result of calling the references needs
+        to be checked before being used.  This can be used to avoid
+        creating references that will cause the garbage collector to
+        keep the values around longer than needed.
+
+        """
+        if self._pending_removals:
+            self._commit_removals()
+        with _IterationGuard(self):
+            yield from self.data.values()
+
+    def values(self):
+        if self._pending_removals:
+            self._commit_removals()
+        with _IterationGuard(self):
+            for wr in self.data.values():
+                obj = wr()
+                if obj is not None:
+                    yield obj
+
+    def popitem(self):
+        if self._pending_removals:
+            self._commit_removals()
+        while True:
+            key, wr = self.data.popitem()
+            o = wr()
+            if o is not None:
+                return key, o
+
+    def pop(self, key, *args):
+        if self._pending_removals:
+            self._commit_removals()
+        try:
+            o = self.data.pop(key)()
+        except KeyError:
+            o = None
+        if o is None:
+            if args:
+                return args[0]
+            else:
+                raise KeyError(key)
+        else:
+            return o
+
+    def setdefault(self, key, default=None):
+        try:
+            o = self.data[key]()
+        except KeyError:
+            o = None
+        if o is None:
+            if self._pending_removals:
+                self._commit_removals()
+            self.data[key] = KeyedRef(default, self._remove, key)
+            return default
+        else:
+            return o
+
+    def update(self, other=None, /, **kwargs):
+        if self._pending_removals:
+            self._commit_removals()
+        d = self.data
+        if other is not None:
+            if not hasattr(other, "items"):
+                other = dict(other)
+            for key, o in other.items():
+                d[key] = KeyedRef(o, self._remove, key)
+        for key, o in kwargs.items():
+            d[key] = KeyedRef(o, self._remove, key)
+
+    def valuerefs(self):
+        """Return a list of weak references to the values.
+
+        The references are not guaranteed to be 'live' at the time
+        they are used, so the result of calling the references needs
+        to be checked before being used.  This can be used to avoid
+        creating references that will cause the garbage collector to
+        keep the values around longer than needed.
+
+        """
+        if self._pending_removals:
+            self._commit_removals()
+        return list(self.data.values())
+
+    def __ior__(self, other):
+        self.update(other)
+        return self
+
+    def __or__(self, other):
+        if isinstance(other, _collections_abc.Mapping):
+            c = self.copy()
+            c.update(other)
+            return c
+        return NotImplemented
+
+    def __ror__(self, other):
+        if isinstance(other, _collections_abc.Mapping):
+            c = self.__class__()
+            c.update(other)
+            c.update(self)
+            return c
+        return NotImplemented
+
+
+class KeyedRef(ref):
+    """Specialized reference that includes a key corresponding to the value.
+
+    This is used in the WeakValueDictionary to avoid having to create
+    a function object for each key stored in the mapping.  A shared
+    callback object can use the 'key' attribute of a KeyedRef instead
+    of getting a reference to the key from an enclosing scope.
+
+    """
+
+    __slots__ = "key",
+
+    def __new__(type, ob, callback, key):
+        self = ref.__new__(type, ob, callback)
+        self.key = key
+        return self
+
+    def __init__(self, ob, callback, key):
+        super().__init__(ob, callback)
+
+
+class WeakKeyDictionary(_collections_abc.MutableMapping):
+    """ Mapping class that references keys weakly.
+
+    Entries in the dictionary will be discarded when there is no
+    longer a strong reference to the key. This can be used to
+    associate additional data with an object owned by other parts of
+    an application without adding attributes to those objects. This
+    can be especially useful with objects that override attribute
+    accesses.
+    """
+
+    def __init__(self, dict=None):
+        self.data = {}
+        def remove(k, selfref=ref(self)):
+            self = selfref()
+            if self is not None:
+                if self._iterating:
+                    self._pending_removals.append(k)
+                else:
+                    try:
+                        del self.data[k]
+                    except KeyError:
+                        pass
+        self._remove = remove
+        # A list of dead weakrefs (keys to be removed)
+        self._pending_removals = []
+        self._iterating = set()
+        self._dirty_len = False
+        if dict is not None:
+            self.update(dict)
+
+    def _commit_removals(self):
+        # NOTE: We don't need to call this method before mutating the dict,
+        # because a dead weakref never compares equal to a live weakref,
+        # even if they happened to refer to equal objects.
+        # However, it means keys may already have been removed.
+        pop = self._pending_removals.pop
+        d = self.data
+        while True:
+            try:
+                key = pop()
+            except IndexError:
+                return
+
+            try:
+                del d[key]
+            except KeyError:
+                pass
+
+    def _scrub_removals(self):
+        d = self.data
+        self._pending_removals = [k for k in self._pending_removals if k in d]
+        self._dirty_len = False
+
+    def __delitem__(self, key):
+        self._dirty_len = True
+        del self.data[ref(key)]
+
+    def __getitem__(self, key):
+        return self.data[ref(key)]
+
+    def __len__(self):
+        if self._dirty_len and self._pending_removals:
+            # self._pending_removals may still contain keys which were
+            # explicitly removed, we have to scrub them (see issue #21173).
+            self._scrub_removals()
+        return len(self.data) - len(self._pending_removals)
+
+    def __repr__(self):
+        return "<%s at %#x>" % (self.__class__.__name__, id(self))
+
+    def __setitem__(self, key, value):
+        self.data[ref(key, self._remove)] = value
+
+    def copy(self):
+        new = WeakKeyDictionary()
+        with _IterationGuard(self):
+            for key, value in self.data.items():
+                o = key()
+                if o is not None:
+                    new[o] = value
+        return new
+
+    __copy__ = copy
+
+    def __deepcopy__(self, memo):
+        from copy import deepcopy
+        new = self.__class__()
+        with _IterationGuard(self):
+            for key, value in self.data.items():
+                o = key()
+                if o is not None:
+                    new[o] = deepcopy(value, memo)
+        return new
+
+    def get(self, key, default=None):
+        return self.data.get(ref(key),default)
+
+    def __contains__(self, key):
+        try:
+            wr = ref(key)
+        except TypeError:
+            return False
+        return wr in self.data
+
+    def items(self):
+        with _IterationGuard(self):
+            for wr, value in self.data.items():
+                key = wr()
+                if key is not None:
+                    yield key, value
+
+    def keys(self):
+        with _IterationGuard(self):
+            for wr in self.data:
+                obj = wr()
+                if obj is not None:
+                    yield obj
+
+    __iter__ = keys
+
+    def values(self):
+        with _IterationGuard(self):
+            for wr, value in self.data.items():
+                if wr() is not None:
+                    yield value
+
+    def keyrefs(self):
+        """Return a list of weak references to the keys.
+
+        The references are not guaranteed to be 'live' at the time
+        they are used, so the result of calling the references needs
+        to be checked before being used.  This can be used to avoid
+        creating references that will cause the garbage collector to
+        keep the keys around longer than needed.
+
+        """
+        return list(self.data)
+
+    def popitem(self):
+        self._dirty_len = True
+        while True:
+            key, value = self.data.popitem()
+            o = key()
+            if o is not None:
+                return o, value
+
+    def pop(self, key, *args):
+        self._dirty_len = True
+        return self.data.pop(ref(key), *args)
+
+    def setdefault(self, key, default=None):
+        return self.data.setdefault(ref(key, self._remove),default)
+
+    def update(self, dict=None, /, **kwargs):
+        d = self.data
+        if dict is not None:
+            if not hasattr(dict, "items"):
+                dict = type({})(dict)
+            for key, value in dict.items():
+                d[ref(key, self._remove)] = value
+        if len(kwargs):
+            self.update(kwargs)
+
+    def __ior__(self, other):
+        self.update(other)
+        return self
+
+    def __or__(self, other):
+        if isinstance(other, _collections_abc.Mapping):
+            c = self.copy()
+            c.update(other)
+            return c
+        return NotImplemented
+
+    def __ror__(self, other):
+        if isinstance(other, _collections_abc.Mapping):
+            c = self.__class__()
+            c.update(other)
+            c.update(self)
+            return c
+        return NotImplemented
+
+
+class finalize:
+    """Class for finalization of weakrefable objects
+
+    finalize(obj, func, *args, **kwargs) returns a callable finalizer
+    object which will be called when obj is garbage collected. The
+    first time the finalizer is called it evaluates func(*arg, **kwargs)
+    and returns the result. After this the finalizer is dead, and
+    calling it just returns None.
+
+    When the program exits any remaining finalizers for which the
+    atexit attribute is true will be run in reverse order of creation.
+    By default atexit is true.
+    """
+
+    # Finalizer objects don't have any state of their own.  They are
+    # just used as keys to lookup _Info objects in the registry.  This
+    # ensures that they cannot be part of a ref-cycle.
+
+    __slots__ = ()
+    _registry = {}
+    _shutdown = False
+    _index_iter = itertools.count()
+    _dirty = False
+    _registered_with_atexit = False
+
+    class _Info:
+        __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index")
+
+    def __init__(self, obj, func, /, *args, **kwargs):
+        if not self._registered_with_atexit:
+            # We may register the exit function more than once because
+            # of a thread race, but that is harmless
+            import atexit
+            atexit.register(self._exitfunc)
+            finalize._registered_with_atexit = True
+        info = self._Info()
+        info.weakref = ref(obj, self)
+        info.func = func
+        info.args = args
+        info.kwargs = kwargs or None
+        info.atexit = True
+        info.index = next(self._index_iter)
+        self._registry[self] = info
+        finalize._dirty = True
+
+    def __call__(self, _=None):
+        """If alive then mark as dead and return func(*args, **kwargs);
+        otherwise return None"""
+        info = self._registry.pop(self, None)
+        if info and not self._shutdown:
+            return info.func(*info.args, **(info.kwargs or {}))
+
+    def detach(self):
+        """If alive then mark as dead and return (obj, func, args, kwargs);
+        otherwise return None"""
+        info = self._registry.get(self)
+        obj = info and info.weakref()
+        if obj is not None and self._registry.pop(self, None):
+            return (obj, info.func, info.args, info.kwargs or {})
+
+    def peek(self):
+        """If alive then return (obj, func, args, kwargs);
+        otherwise return None"""
+        info = self._registry.get(self)
+        obj = info and info.weakref()
+        if obj is not None:
+            return (obj, info.func, info.args, info.kwargs or {})
+
+    @property
+    def alive(self):
+        """Whether finalizer is alive"""
+        return self in self._registry
+
+    @property
+    def atexit(self):
+        """Whether finalizer should be called at exit"""
+        info = self._registry.get(self)
+        return bool(info) and info.atexit
+
+    @atexit.setter
+    def atexit(self, value):
+        info = self._registry.get(self)
+        if info:
+            info.atexit = bool(value)
+
+    def __repr__(self):
+        info = self._registry.get(self)
+        obj = info and info.weakref()
+        if obj is None:
+            return '<%s object at %#x; dead>' % (type(self).__name__, id(self))
+        else:
+            return '<%s object at %#x; for %r at %#x>' % \
+                (type(self).__name__, id(self), type(obj).__name__, id(obj))
+
+    @classmethod
+    def _select_for_exit(cls):
+        # Return live finalizers marked for exit, oldest first
+        L = [(f,i) for (f,i) in cls._registry.items() if i.atexit]
+        L.sort(key=lambda item:item[1].index)
+        return [f for (f,i) in L]
+
+    @classmethod
+    def _exitfunc(cls):
+        # At shutdown invoke finalizers for which atexit is true.
+        # This is called once all other non-daemonic threads have been
+        # joined.
+        reenable_gc = False
+        try:
+            if cls._registry:
+                import gc
+                if gc.isenabled():
+                    reenable_gc = True
+                    gc.disable()
+                pending = None
+                while True:
+                    if pending is None or finalize._dirty:
+                        pending = cls._select_for_exit()
+                        finalize._dirty = False
+                    if not pending:
+                        break
+                    f = pending.pop()
+                    try:
+                        # gc is disabled, so (assuming no daemonic
+                        # threads) the following is the only line in
+                        # this function which might trigger creation
+                        # of a new finalizer
+                        f()
+                    except Exception:
+                        sys.excepthook(*sys.exc_info())
+                    assert f not in cls._registry
+        finally:
+            # prevent any more finalizers from executing during shutdown
+            finalize._shutdown = True
+            if reenable_gc:
+                gc.enable()
diff --git a/shared/package-files/56/56f9428c2b4e73dcebeafa1c1fc2dcebf40e7418a60ace9a97cd27296ee82f34/_upsample_bilinear2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/56/56f9428c2b4e73dcebeafa1c1fc2dcebf40e7418a60ace9a97cd27296ee82f34/_upsample_bilinear2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..1bee5bc4c953e0197856c2168eccaad896f3ab9e
--- /dev/null
+++ b/shared/package-files/56/56f9428c2b4e73dcebeafa1c1fc2dcebf40e7418a60ace9a97cd27296ee82f34/_upsample_bilinear2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h
@@ -0,0 +1,24 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautogradnonfunctional {
+
+TORCH_API at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor _upsample_bilinear2d_aa_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+
+} // namespace compositeexplicitautogradnonfunctional
+} // namespace at
diff --git a/shared/package-files/56/56fb184a883b15a24ef6ba3bc0e5b2eebe310021276d160b2c143f9c13627174/_version_native.h b/shared/package-files/56/56fb184a883b15a24ef6ba3bc0e5b2eebe310021276d160b2c143f9c13627174/_version_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..17500bb111ddbb2594df4e585693f25afea8ed5e
--- /dev/null
+++ b/shared/package-files/56/56fb184a883b15a24ef6ba3bc0e5b2eebe310021276d160b2c143f9c13627174/_version_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API int64_t _version(const at::Tensor & self);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/56/56fdf3496f3d8842cdfbc28d6d47259a484e7b52f329d17b53fc37e27628bc8a/test_load_centrality.py b/shared/package-files/56/56fdf3496f3d8842cdfbc28d6d47259a484e7b52f329d17b53fc37e27628bc8a/test_load_centrality.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf096039cd76542cc4c963ab896ee8fc4b295224
--- /dev/null
+++ b/shared/package-files/56/56fdf3496f3d8842cdfbc28d6d47259a484e7b52f329d17b53fc37e27628bc8a/test_load_centrality.py
@@ -0,0 +1,344 @@
+import pytest
+
+import networkx as nx
+
+
+class TestLoadCentrality:
+    @classmethod
+    def setup_class(cls):
+        G = nx.Graph()
+        G.add_edge(0, 1, weight=3)
+        G.add_edge(0, 2, weight=2)
+        G.add_edge(0, 3, weight=6)
+        G.add_edge(0, 4, weight=4)
+        G.add_edge(1, 3, weight=5)
+        G.add_edge(1, 5, weight=5)
+        G.add_edge(2, 4, weight=1)
+        G.add_edge(3, 4, weight=2)
+        G.add_edge(3, 5, weight=1)
+        G.add_edge(4, 5, weight=4)
+        cls.G = G
+        cls.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0}
+        cls.K = nx.krackhardt_kite_graph()
+        cls.P3 = nx.path_graph(3)
+        cls.P4 = nx.path_graph(4)
+        cls.K5 = nx.complete_graph(5)
+        cls.P2 = nx.path_graph(2)
+
+        cls.C4 = nx.cycle_graph(4)
+        cls.T = nx.balanced_tree(r=2, h=2)
+        cls.Gb = nx.Graph()
+        cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
+        cls.F = nx.florentine_families_graph()
+        cls.LM = nx.les_miserables_graph()
+        cls.D = nx.cycle_graph(3, create_using=nx.DiGraph())
+        cls.D.add_edges_from([(3, 0), (4, 3)])
+
+    def test_not_strongly_connected(self):
+        b = nx.load_centrality(self.D)
+        result = {0: 5.0 / 12, 1: 1.0 / 4, 2: 1.0 / 12, 3: 1.0 / 4, 4: 0.000}
+        for n in sorted(self.D):
+            assert result[n] == pytest.approx(b[n], abs=1e-3)
+            assert result[n] == pytest.approx(nx.load_centrality(self.D, n), abs=1e-3)
+
+    def test_P2_normalized_load(self):
+        G = self.P2
+        c = nx.load_centrality(G, normalized=True)
+        d = {0: 0.000, 1: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_weighted_load(self):
+        b = nx.load_centrality(self.G, weight="weight", normalized=False)
+        for n in sorted(self.G):
+            assert b[n] == self.exact_weighted[n]
+
+    def test_k5_load(self):
+        G = self.K5
+        c = nx.load_centrality(G)
+        d = {0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_p3_load(self):
+        G = self.P3
+        c = nx.load_centrality(G)
+        d = {0: 0.000, 1: 1.000, 2: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+        c = nx.load_centrality(G, v=1)
+        assert c == pytest.approx(1.0, abs=1e-7)
+        c = nx.load_centrality(G, v=1, normalized=True)
+        assert c == pytest.approx(1.0, abs=1e-7)
+
+    def test_p2_load(self):
+        G = nx.path_graph(2)
+        c = nx.load_centrality(G)
+        d = {0: 0.000, 1: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_krackhardt_load(self):
+        G = self.K
+        c = nx.load_centrality(G)
+        d = {
+            0: 0.023,
+            1: 0.023,
+            2: 0.000,
+            3: 0.102,
+            4: 0.000,
+            5: 0.231,
+            6: 0.231,
+            7: 0.389,
+            8: 0.222,
+            9: 0.000,
+        }
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_florentine_families_load(self):
+        G = self.F
+        c = nx.load_centrality(G)
+        d = {
+            "Acciaiuoli": 0.000,
+            "Albizzi": 0.211,
+            "Barbadori": 0.093,
+            "Bischeri": 0.104,
+            "Castellani": 0.055,
+            "Ginori": 0.000,
+            "Guadagni": 0.251,
+            "Lamberteschi": 0.000,
+            "Medici": 0.522,
+            "Pazzi": 0.000,
+            "Peruzzi": 0.022,
+            "Ridolfi": 0.117,
+            "Salviati": 0.143,
+            "Strozzi": 0.106,
+            "Tornabuoni": 0.090,
+        }
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_les_miserables_load(self):
+        G = self.LM
+        c = nx.load_centrality(G)
+        d = {
+            "Napoleon": 0.000,
+            "Myriel": 0.177,
+            "MlleBaptistine": 0.000,
+            "MmeMagloire": 0.000,
+            "CountessDeLo": 0.000,
+            "Geborand": 0.000,
+            "Champtercier": 0.000,
+            "Cravatte": 0.000,
+            "Count": 0.000,
+            "OldMan": 0.000,
+            "Valjean": 0.567,
+            "Labarre": 0.000,
+            "Marguerite": 0.000,
+            "MmeDeR": 0.000,
+            "Isabeau": 0.000,
+            "Gervais": 0.000,
+            "Listolier": 0.000,
+            "Tholomyes": 0.043,
+            "Fameuil": 0.000,
+            "Blacheville": 0.000,
+            "Favourite": 0.000,
+            "Dahlia": 0.000,
+            "Zephine": 0.000,
+            "Fantine": 0.128,
+            "MmeThenardier": 0.029,
+            "Thenardier": 0.075,
+            "Cosette": 0.024,
+            "Javert": 0.054,
+            "Fauchelevent": 0.026,
+            "Bamatabois": 0.008,
+            "Perpetue": 0.000,
+            "Simplice": 0.009,
+            "Scaufflaire": 0.000,
+            "Woman1": 0.000,
+            "Judge": 0.000,
+            "Champmathieu": 0.000,
+            "Brevet": 0.000,
+            "Chenildieu": 0.000,
+            "Cochepaille": 0.000,
+            "Pontmercy": 0.007,
+            "Boulatruelle": 0.000,
+            "Eponine": 0.012,
+            "Anzelma": 0.000,
+            "Woman2": 0.000,
+            "MotherInnocent": 0.000,
+            "Gribier": 0.000,
+            "MmeBurgon": 0.026,
+            "Jondrette": 0.000,
+            "Gavroche": 0.164,
+            "Gillenormand": 0.021,
+            "Magnon": 0.000,
+            "MlleGillenormand": 0.047,
+            "MmePontmercy": 0.000,
+            "MlleVaubois": 0.000,
+            "LtGillenormand": 0.000,
+            "Marius": 0.133,
+            "BaronessT": 0.000,
+            "Mabeuf": 0.028,
+            "Enjolras": 0.041,
+            "Combeferre": 0.001,
+            "Prouvaire": 0.000,
+            "Feuilly": 0.001,
+            "Courfeyrac": 0.006,
+            "Bahorel": 0.002,
+            "Bossuet": 0.032,
+            "Joly": 0.002,
+            "Grantaire": 0.000,
+            "MotherPlutarch": 0.000,
+            "Gueulemer": 0.005,
+            "Babet": 0.005,
+            "Claquesous": 0.005,
+            "Montparnasse": 0.004,
+            "Toussaint": 0.000,
+            "Child1": 0.000,
+            "Child2": 0.000,
+            "Brujon": 0.000,
+            "MmeHucheloup": 0.000,
+        }
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_unnormalized_k5_load(self):
+        G = self.K5
+        c = nx.load_centrality(G, normalized=False)
+        d = {0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_unnormalized_p3_load(self):
+        G = self.P3
+        c = nx.load_centrality(G, normalized=False)
+        d = {0: 0.000, 1: 2.000, 2: 0.000}
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_unnormalized_krackhardt_load(self):
+        G = self.K
+        c = nx.load_centrality(G, normalized=False)
+        d = {
+            0: 1.667,
+            1: 1.667,
+            2: 0.000,
+            3: 7.333,
+            4: 0.000,
+            5: 16.667,
+            6: 16.667,
+            7: 28.000,
+            8: 16.000,
+            9: 0.000,
+        }
+
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_unnormalized_florentine_families_load(self):
+        G = self.F
+        c = nx.load_centrality(G, normalized=False)
+
+        d = {
+            "Acciaiuoli": 0.000,
+            "Albizzi": 38.333,
+            "Barbadori": 17.000,
+            "Bischeri": 19.000,
+            "Castellani": 10.000,
+            "Ginori": 0.000,
+            "Guadagni": 45.667,
+            "Lamberteschi": 0.000,
+            "Medici": 95.000,
+            "Pazzi": 0.000,
+            "Peruzzi": 4.000,
+            "Ridolfi": 21.333,
+            "Salviati": 26.000,
+            "Strozzi": 19.333,
+            "Tornabuoni": 16.333,
+        }
+        for n in sorted(G):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_load_betweenness_difference(self):
+        # Difference Between Load and Betweenness
+        # --------------------------------------- The smallest graph
+        # that shows the difference between load and betweenness is
+        # G=ladder_graph(3) (Graph B below)
+
+        # Graph A and B are from Tao Zhou, Jian-Guo Liu, Bing-Hong
+        # Wang: Comment on "Scientific collaboration
+        # networks. II. Shortest paths, weighted networks, and
+        # centrality". https://arxiv.org/pdf/physics/0511084
+
+        # Notice that unlike here, their calculation adds to 1 to the
+        # betweenness of every node i for every path from i to every
+        # other node.  This is exactly what it should be, based on
+        # Eqn. (1) in their paper: the eqn is B(v) = \sum_{s\neq t,
+        # s\neq v}{\frac{\sigma_{st}(v)}{\sigma_{st}}}, therefore,
+        # they allow v to be the target node.
+
+        # We follow Brandes 2001, who follows Freeman 1977 that make
+        # the sum for betweenness of v exclude paths where v is either
+        # the source or target node.  To agree with their numbers, we
+        # must additionally, remove edge (4,8) from the graph, see AC
+        # example following (there is a mistake in the figure in their
+        # paper - personal communication).
+
+        # A = nx.Graph()
+        # A.add_edges_from([(0,1), (1,2), (1,3), (2,4),
+        #                  (3,5), (4,6), (4,7), (4,8),
+        #                  (5,8), (6,9), (7,9), (8,9)])
+        B = nx.Graph()  # ladder_graph(3)
+        B.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
+        c = nx.load_centrality(B, normalized=False)
+        d = {0: 1.750, 1: 1.750, 2: 6.500, 3: 6.500, 4: 1.750, 5: 1.750}
+        for n in sorted(B):
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_c4_edge_load(self):
+        G = self.C4
+        c = nx.edge_load_centrality(G)
+        d = {(0, 1): 6.000, (0, 3): 6.000, (1, 2): 6.000, (2, 3): 6.000}
+        for n in G.edges():
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_p4_edge_load(self):
+        G = self.P4
+        c = nx.edge_load_centrality(G)
+        d = {(0, 1): 6.000, (1, 2): 8.000, (2, 3): 6.000}
+        for n in G.edges():
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_k5_edge_load(self):
+        G = self.K5
+        c = nx.edge_load_centrality(G)
+        d = {
+            (0, 1): 5.000,
+            (0, 2): 5.000,
+            (0, 3): 5.000,
+            (0, 4): 5.000,
+            (1, 2): 5.000,
+            (1, 3): 5.000,
+            (1, 4): 5.000,
+            (2, 3): 5.000,
+            (2, 4): 5.000,
+            (3, 4): 5.000,
+        }
+        for n in G.edges():
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
+
+    def test_tree_edge_load(self):
+        G = self.T
+        c = nx.edge_load_centrality(G)
+        d = {
+            (0, 1): 24.000,
+            (0, 2): 24.000,
+            (1, 3): 12.000,
+            (1, 4): 12.000,
+            (2, 5): 12.000,
+            (2, 6): 12.000,
+        }
+        for n in G.edges():
+            assert c[n] == pytest.approx(d[n], abs=1e-3)
diff --git a/shared/package-files/56/56fe9c409950e2aa0859d87423c4d8f0cc2f1fe3f7a64a149032d0afd51eb1c3/test_indexing.cpython-311.pyc b/shared/package-files/56/56fe9c409950e2aa0859d87423c4d8f0cc2f1fe3f7a64a149032d0afd51eb1c3/test_indexing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6183dc491a8615e35949f77cb6c066179eb28009
Binary files /dev/null and b/shared/package-files/56/56fe9c409950e2aa0859d87423c4d8f0cc2f1fe3f7a64a149032d0afd51eb1c3/test_indexing.cpython-311.pyc differ
diff --git a/shared/package-files/75/7504d79d810f6d4fb704a5ca5a6db5ff721056dd4bfbef05c6d9882f4b76fb0c/__init__.cpython-311.pyc b/shared/package-files/75/7504d79d810f6d4fb704a5ca5a6db5ff721056dd4bfbef05c6d9882f4b76fb0c/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81d3b431fb33538b0c5049fc34ed1054e8aa5cd7
Binary files /dev/null and b/shared/package-files/75/7504d79d810f6d4fb704a5ca5a6db5ff721056dd4bfbef05c6d9882f4b76fb0c/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/75/750f8ecdb2af2b3e1bd1a79de539ec463ff92296a10b0d301973f1d8bfbd5bfc/_cudnn_rnn_cuda_dispatch.h b/shared/package-files/75/750f8ecdb2af2b3e1bd1a79de539ec463ff92296a10b0d301973f1d8bfbd5bfc/_cudnn_rnn_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..03347a95c484d1a8b665444a2ce0c25810676472
--- /dev/null
+++ b/shared/package-files/75/750f8ecdb2af2b3e1bd1a79de539ec463ff92296a10b0d301973f1d8bfbd5bfc/_cudnn_rnn_cuda_dispatch.h
@@ -0,0 +1,24 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API ::std::tuple _cudnn_rnn(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional & weight_buf, const at::Tensor & hx, const ::std::optional & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional & dropout_state);
+TORCH_API ::std::tuple _cudnn_rnn_symint(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional & weight_buf, const at::Tensor & hx, const ::std::optional & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional & dropout_state);
+
+} // namespace cuda
+} // namespace at
diff --git a/shared/package-files/75/750f95d54085983d097346296771098008718f892f344e41313de620768974a1/__init__.cpython-311.pyc b/shared/package-files/75/750f95d54085983d097346296771098008718f892f344e41313de620768974a1/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8586693cb9552bb33e12cb464fff82f6f48dbab
Binary files /dev/null and b/shared/package-files/75/750f95d54085983d097346296771098008718f892f344e41313de620768974a1/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/75/75130ae2a115db7332e5b8acbfd106b839c186cf49c18a958de900b986c6aeb4/model_attr_mutation.py b/shared/package-files/75/75130ae2a115db7332e5b8acbfd106b839c186cf49c18a958de900b986c6aeb4/model_attr_mutation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aa623c7dc39efd94fecb8eb32caac3f7420f05d
--- /dev/null
+++ b/shared/package-files/75/75130ae2a115db7332e5b8acbfd106b839c186cf49c18a958de900b986c6aeb4/model_attr_mutation.py
@@ -0,0 +1,26 @@
+# mypy: allow-untyped-defs
+import torch
+from torch._export.db.case import SupportLevel
+
+
+class ModelAttrMutation(torch.nn.Module):
+    """
+    Attribute mutation is not supported.
+    """
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.attr_list = [torch.randn(3, 2), torch.randn(3, 2)]
+
+    def recreate_list(self):
+        return [torch.zeros(3, 2), torch.zeros(3, 2)]
+
+    def forward(self, x):
+        self.attr_list = self.recreate_list()
+        return x.sum() + self.attr_list[0].sum()
+
+
+example_args = (torch.randn(3, 2),)
+tags = {"python.object-model"}
+support_level = SupportLevel.NOT_SUPPORTED_YET
+model = ModelAttrMutation()
diff --git a/shared/package-files/75/75206028238a4bac19c3a8fd6177202d7e3c1b5fda835e81b5bbd04097dcdf5b/test_searchsorted.cpython-311.pyc b/shared/package-files/75/75206028238a4bac19c3a8fd6177202d7e3c1b5fda835e81b5bbd04097dcdf5b/test_searchsorted.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2d3e34c16cbf63b665afa34934db1cc3947f7bc
Binary files /dev/null and b/shared/package-files/75/75206028238a4bac19c3a8fd6177202d7e3c1b5fda835e81b5bbd04097dcdf5b/test_searchsorted.cpython-311.pyc differ
diff --git a/shared/package-files/75/75222ae6d9f32ef40dde7b43fe77e40d956f105c22aa941041970cf40d4d0190/silu_backward_meta.h b/shared/package-files/75/75222ae6d9f32ef40dde7b43fe77e40d956f105c22aa941041970cf40d4d0190/silu_backward_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..e059b4335d20b4cf6e2cff821a3ce3c0f0c820e4
--- /dev/null
+++ b/shared/package-files/75/75222ae6d9f32ef40dde7b43fe77e40d956f105c22aa941041970cf40d4d0190/silu_backward_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_silu_backward : public TensorIteratorBase {
+    
+    
+    void meta(const at::Tensor & grad_output, const at::Tensor & self);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/75/752c8dbcbff94818569719f1479ccd85405a54948480ef373caac83ab7a46370/is_set_to_ops.h b/shared/package-files/75/752c8dbcbff94818569719f1479ccd85405a54948480ef373caac83ab7a46370/is_set_to_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a52ea7b72d84bbd33e4a35be40ff6771c58cb11
--- /dev/null
+++ b/shared/package-files/75/752c8dbcbff94818569719f1479ccd85405a54948480ef373caac83ab7a46370/is_set_to_ops.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API is_set_to {
+  using schema = bool (const at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::is_set_to";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "is_set_to(Tensor self, Tensor tensor) -> bool";
+  static bool call(const at::Tensor & self, const at::Tensor & tensor);
+  static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & tensor);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/75/7530b95260fe0493bd77df51318c5b16e44f2612c51ec260460cadd484195403/sparse_unary.py b/shared/package-files/75/7530b95260fe0493bd77df51318c5b16e44f2612c51ec260460cadd484195403/sparse_unary.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6fe622183f68f02770507250d41f280e88a1d92
--- /dev/null
+++ b/shared/package-files/75/7530b95260fe0493bd77df51318c5b16e44f2612c51ec260460cadd484195403/sparse_unary.py
@@ -0,0 +1,83 @@
+# mypy: allow-untyped-defs
+
+import numpy as np
+import torch
+from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
+
+
+_MIN_DIM_SIZE = 16
+_MAX_DIM_SIZE = 16 * 1024 ** 2
+_POW_TWO_SIZES = tuple(2 ** i for i in range(
+    int(np.log2(_MIN_DIM_SIZE)),
+    int(np.log2(_MAX_DIM_SIZE)) + 1,
+))
+
+class UnaryOpSparseFuzzer(Fuzzer):
+    def __init__(self, seed, dtype=torch.float32, cuda=False):
+        super().__init__(
+            parameters=[
+                # Sparse dim parameter of x. (e.g. 1D, 2D, or 3D.)
+                FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
+                FuzzedParameter(
+                    name="sparse_dim",
+                    distribution={1: 0.4, 2: 0.4, 3: 0.2},
+                    strict=True
+                ),
+                # Shapes for `x`.
+                #   It is important to test all shapes, however
+                #   powers of two are especially important and therefore
+                #   warrant special attention. This is done by generating
+                #   both a value drawn from all integers between the min and
+                #   max allowed values, and another from only the powers of two
+                #   (both distributions are loguniform) and then randomly
+                #   selecting between the two.
+                [
+                    FuzzedParameter(
+                        name=f"k_any_{i}",
+                        minval=_MIN_DIM_SIZE,
+                        maxval=_MAX_DIM_SIZE,
+                        distribution="loguniform",
+                    ) for i in range(3)
+                ],
+                [
+                    FuzzedParameter(
+                        name=f"k_pow2_{i}",
+                        distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
+                    ) for i in range(3)
+                ],
+                [
+                    FuzzedParameter(
+                        name=f"k{i}",
+                        distribution={
+                            ParameterAlias(f"k_any_{i}"): 0.8,
+                            ParameterAlias(f"k_pow2_{i}"): 0.2,
+                        },
+                        strict=True,
+                    ) for i in range(3)
+                ],
+                FuzzedParameter(
+                    name="density",
+                    distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3},
+                ),
+                FuzzedParameter(
+                    name="coalesced",
+                    distribution={True: 0.5, False: 0.5},
+                ),
+                FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
+            ],
+            tensors=[
+                FuzzedSparseTensor(
+                    name="x",
+                    size=("k0", "k1", "k2"),
+                    dim_parameter="dim_parameter",
+                    sparse_dim="sparse_dim",
+                    min_elements=4 * 1024,
+                    max_elements=32 * 1024 ** 2,
+                    density="density",
+                    coalesced="coalesced",
+                    dtype=dtype,
+                    cuda=cuda,
+                ),
+            ],
+            seed=seed,
+        )
diff --git a/shared/package-files/75/7553babcb06d4caddf5e94f4957978133bc6a5072c74068fca1067fc39da38b7/miopen_depthwise_convolution.h b/shared/package-files/75/7553babcb06d4caddf5e94f4957978133bc6a5072c74068fca1067fc39da38b7/miopen_depthwise_convolution.h
new file mode 100644
index 0000000000000000000000000000000000000000..ca473c93faca40f64b5bdb4b1168301b55168326
--- /dev/null
+++ b/shared/package-files/75/7553babcb06d4caddf5e94f4957978133bc6a5072c74068fca1067fc39da38b7/miopen_depthwise_convolution.h
@@ -0,0 +1,92 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+inline at::Tensor miopen_depthwise_convolution(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic);
+}
+namespace symint {
+  template >>
+  at::Tensor miopen_depthwise_convolution(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic);
+  }
+}
+
+// aten::miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+inline at::Tensor miopen_depthwise_convolution_symint(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic);
+}
+namespace symint {
+  template >>
+  at::Tensor miopen_depthwise_convolution(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic);
+  }
+}
+
+// aten::miopen_depthwise_convolution.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & miopen_depthwise_convolution_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & miopen_depthwise_convolution_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic, out);
+  }
+}
+
+// aten::miopen_depthwise_convolution.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & miopen_depthwise_convolution_outf(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, at::Tensor & out) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & miopen_depthwise_convolution_outf(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, at::Tensor & out) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(dilation), groups, benchmark, deterministic, out);
+  }
+}
+
+// aten::miopen_depthwise_convolution.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & miopen_depthwise_convolution_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & miopen_depthwise_convolution_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic, out);
+  }
+}
+
+// aten::miopen_depthwise_convolution.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & miopen_depthwise_convolution_symint_outf(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, at::Tensor & out) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & miopen_depthwise_convolution_outf(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, at::Tensor & out) {
+    return at::_ops::miopen_depthwise_convolution_out::call(self, weight, bias, padding, stride, dilation, groups, benchmark, deterministic, out);
+  }
+}
+
+}
diff --git a/shared/package-files/75/755d9e383591811c588e53d34cd6aeff39f79df325c68655b2911221b11f898f/checksum32.cpython-311.pyc b/shared/package-files/75/755d9e383591811c588e53d34cd6aeff39f79df325c68655b2911221b11f898f/checksum32.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..359088818d2edb863b1a0031d6e7548c1c4380d4
Binary files /dev/null and b/shared/package-files/75/755d9e383591811c588e53d34cd6aeff39f79df325c68655b2911221b11f898f/checksum32.cpython-311.pyc differ
diff --git a/shared/package-files/75/7566f9ffc9326918227bb10457352207d5d9ea945fe958f1e9a842653ba9aa39/api.py b/shared/package-files/75/7566f9ffc9326918227bb10457352207d5d9ea945fe958f1e9a842653ba9aa39/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c899437346734dce799ddefeedbef8ef10c90ec
--- /dev/null
+++ b/shared/package-files/75/7566f9ffc9326918227bb10457352207d5d9ea945fe958f1e9a842653ba9aa39/api.py
@@ -0,0 +1,102 @@
+# mypy: allow-untyped-defs
+from collections.abc import Mapping
+from typing import Any, Union
+
+import torch.optim as optim
+from torch import Tensor
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+
+
+class ShardedOptimizer(optim.Optimizer):
+    def __init__(
+        self,
+        named_params: Mapping[str, Union[Tensor, ShardedTensor]],
+        optimizer_class,
+        *optimizer_args,
+        **optimizer_kwargs,
+    ):
+        """
+        ShardedOptimizer collects all tensors and local shard tensors of
+        ShardedTensor, then use these tensors as ``params`` for optimizers
+
+        Args:
+            named_params (Dict[str, Union[Tensor, ShardedTensor]]) : a Dict
+                of parameters, where key is the parameter key, value is either
+                Tensor or ShardedTensor parameter.
+            optimizer_class (torch.optim.Optimizer): the Optimizer to use
+                locally, i.e. torch.optim.SGD, torch.optim.Adagrad, etc.
+            *optimizer_args: the arguments to initialize the optimizer.
+            **optimizer_kwargs: the key-word arguments to initialize the optimizer.
+
+        """
+        tensors: list[Tensor] = []
+        for value in named_params.values():
+            if isinstance(value, ShardedTensor):
+                tensors.extend(
+                    local_shard.tensor for local_shard in value.local_shards()
+                )
+            else:
+                tensors.append(value)
+
+        self.named_params = named_params
+        self._optim = optimizer_class(tensors, *optimizer_args, **optimizer_kwargs)
+        self.param_groups = self._optim.param_groups
+        self.state = self._optim.state
+
+    def zero_grad(self, set_to_none: bool = True):  # type: ignore[override]
+        r"""Resets the gradients of all optimized :class:`torch.Tensor` s.
+
+        Args:
+            set_to_none (bool): instead of setting to zero, set the grads to None.
+                This will in general have lower memory footprint, and can modestly improve performance.
+                However, it changes certain behaviors. For example:
+                1. When the user tries to access a gradient and perform manual ops on it,
+                a None attribute or a Tensor full of 0s will behave differently.
+                2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
+                are guaranteed to be None for params that did not receive a gradient.
+                3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
+                (in one case it does the step with a gradient of 0 and in the other it skips
+                the step altogether).
+        """
+        self._optim.zero_grad(set_to_none)
+
+    def step(self, closure=None):
+        r"""Performs a single optimization step (parameter update).
+
+        Args:
+            closure (Callable): A closure that reevaluates the model and
+                returns the loss. Optional for most optimizers.
+
+        .. note::
+            Unless otherwise specified, this function should not modify the
+            ``.grad`` field of the parameters.
+        """
+        self._optim.step(closure)
+
+    def state_dict(self) -> dict[str, Any]:
+        """
+        Returned state and param_groups will contain parameter keys
+        instead of parameter indices like torch.optim.Optimizer.
+        This allows for advanced functionality like optimizer re-sharding to be implemented.
+        """
+        # TODO: implement state_dict
+        raise NotImplementedError("ShardedOptimizer state_dict not implemented yet!")
+
+    def load_state_dict(self, state_dict: Mapping[str, Any]):
+        r"""Loads the ShardedOptimizer state.
+
+        Args:
+            state_dict (dict): ShardedOptimizer state. Should be an object returned
+                from a call to :meth:`state_dict`.
+        """
+        # TODO: implement load_state_dict
+        raise NotImplementedError(
+            "ShardedOptimizer load_state_dict not implemented yet!"
+        )
+
+    def add_param_group(self, param_group: Any):
+        r"""Add a new param group"""
+        # TODO: implement add_param_group
+        raise NotImplementedError(
+            "ShardedOptimizer add_param_group not implemented yet!"
+        )
diff --git a/shared/package-files/75/75708b47eda8522245ccbb03b4800ad3d9b8d9cb781b41d6758cc152e0cf5e97/nvblas.h b/shared/package-files/75/75708b47eda8522245ccbb03b4800ad3d9b8d9cb781b41d6758cc152e0cf5e97/nvblas.h
new file mode 100644
index 0000000000000000000000000000000000000000..29ea9153faf7b3e62a6d53c0be1980ae79c49f51
--- /dev/null
+++ b/shared/package-files/75/75708b47eda8522245ccbb03b4800ad3d9b8d9cb781b41d6758cc152e0cf5e97/nvblas.h
@@ -0,0 +1,824 @@
+/*
+ * Copyright 1993-2019 NVIDIA Corporation. All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#if !defined(NVBLAS_H_)
+#define NVBLAS_H_
+
+#include "driver_types.h"
+#include "cuComplex.h" /* import complex data type */
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/* GEMM */
+void sgemm_(const char* transa,
+            const char* transb,
+            const int* m,
+            const int* n,
+            const int* k,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            const float* b,
+            const int* ldb,
+            const float* beta,
+            float* c,
+            const int* ldc);
+
+void dgemm_(const char* transa,
+            const char* transb,
+            const int* m,
+            const int* n,
+            const int* k,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            const double* b,
+            const int* ldb,
+            const double* beta,
+            double* c,
+            const int* ldc);
+
+void cgemm_(const char* transa,
+            const char* transb,
+            const int* m,
+            const int* n,
+            const int* k,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* b,
+            const int* ldb,
+            const cuComplex* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zgemm_(const char* transa,
+            const char* transb,
+            const int* m,
+            const int* n,
+            const int* k,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* b,
+            const int* ldb,
+            const cuDoubleComplex* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+void sgemm(const char* transa,
+           const char* transb,
+           const int* m,
+           const int* n,
+           const int* k,
+           const float* alpha,
+           const float* a,
+           const int* lda,
+           const float* b,
+           const int* ldb,
+           const float* beta,
+           float* c,
+           const int* ldc);
+
+void dgemm(const char* transa,
+           const char* transb,
+           const int* m,
+           const int* n,
+           const int* k,
+           const double* alpha,
+           const double* a,
+           const int* lda,
+           const double* b,
+           const int* ldb,
+           const double* beta,
+           double* c,
+           const int* ldc);
+
+void cgemm(const char* transa,
+           const char* transb,
+           const int* m,
+           const int* n,
+           const int* k,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           const cuComplex* b,
+           const int* ldb,
+           const cuComplex* beta,
+           cuComplex* c,
+           const int* ldc);
+
+void zgemm(const char* transa,
+           const char* transb,
+           const int* m,
+           const int* n,
+           const int* k,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           const cuDoubleComplex* b,
+           const int* ldb,
+           const cuDoubleComplex* beta,
+           cuDoubleComplex* c,
+           const int* ldc);
+
+/* SYRK */
+void ssyrk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            const float* beta,
+            float* c,
+            const int* ldc);
+
+void dsyrk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            const double* beta,
+            double* c,
+            const int* ldc);
+
+void csyrk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zsyrk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+void ssyrk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const float* alpha,
+           const float* a,
+           const int* lda,
+           const float* beta,
+           float* c,
+           const int* ldc);
+
+void dsyrk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const double* alpha,
+           const double* a,
+           const int* lda,
+           const double* beta,
+           double* c,
+           const int* ldc);
+
+void csyrk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           const cuComplex* beta,
+           cuComplex* c,
+           const int* ldc);
+
+void zsyrk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           const cuDoubleComplex* beta,
+           cuDoubleComplex* c,
+           const int* ldc);
+
+/* HERK */
+void cherk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const float* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const float* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zherk_(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const double* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const double* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+void cherk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const float* alpha,
+           const cuComplex* a,
+           const int* lda,
+           const float* beta,
+           cuComplex* c,
+           const int* ldc);
+
+void zherk(const char* uplo,
+           const char* trans,
+           const int* n,
+           const int* k,
+           const double* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           const double* beta,
+           cuDoubleComplex* c,
+           const int* ldc);
+
+/* TRSM */
+void strsm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            float* b,
+            const int* ldb);
+
+void dtrsm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            double* b,
+            const int* ldb);
+
+void ctrsm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            cuComplex* b,
+            const int* ldb);
+
+void ztrsm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            cuDoubleComplex* b,
+            const int* ldb);
+
+void strsm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const float* alpha,
+           const float* a,
+           const int* lda,
+           float* b,
+           const int* ldb);
+
+void dtrsm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const double* alpha,
+           const double* a,
+           const int* lda,
+           double* b,
+           const int* ldb);
+
+void ctrsm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           cuComplex* b,
+           const int* ldb);
+
+void ztrsm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           cuDoubleComplex* b,
+           const int* ldb);
+
+/* SYMM */
+void ssymm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            const float* b,
+            const int* ldb,
+            const float* beta,
+            float* c,
+            const int* ldc);
+
+void dsymm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            const double* b,
+            const int* ldb,
+            const double* beta,
+            double* c,
+            const int* ldc);
+
+void csymm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* b,
+            const int* ldb,
+            const cuComplex* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zsymm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* b,
+            const int* ldb,
+            const cuDoubleComplex* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+void ssymm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const float* alpha,
+           const float* a,
+           const int* lda,
+           const float* b,
+           const int* ldb,
+           const float* beta,
+           float* c,
+           const int* ldc);
+
+void dsymm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const double* alpha,
+           const double* a,
+           const int* lda,
+           const double* b,
+           const int* ldb,
+           const double* beta,
+           double* c,
+           const int* ldc);
+
+void csymm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           const cuComplex* b,
+           const int* ldb,
+           const cuComplex* beta,
+           cuComplex* c,
+           const int* ldc);
+
+void zsymm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           const cuDoubleComplex* b,
+           const int* ldb,
+           const cuDoubleComplex* beta,
+           cuDoubleComplex* c,
+           const int* ldc);
+
+/* HEMM */
+void chemm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* b,
+            const int* ldb,
+            const cuComplex* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zhemm_(const char* side,
+            const char* uplo,
+            const int* m,
+            const int* n,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* b,
+            const int* ldb,
+            const cuDoubleComplex* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+/* HEMM with no underscore*/
+void chemm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           const cuComplex* b,
+           const int* ldb,
+           const cuComplex* beta,
+           cuComplex* c,
+           const int* ldc);
+
+void zhemm(const char* side,
+           const char* uplo,
+           const int* m,
+           const int* n,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           const cuDoubleComplex* b,
+           const int* ldb,
+           const cuDoubleComplex* beta,
+           cuDoubleComplex* c,
+           const int* ldc);
+
+/* SYR2K */
+void ssyr2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const float* alpha,
+             const float* a,
+             const int* lda,
+             const float* b,
+             const int* ldb,
+             const float* beta,
+             float* c,
+             const int* ldc);
+
+void dsyr2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const double* alpha,
+             const double* a,
+             const int* lda,
+             const double* b,
+             const int* ldb,
+             const double* beta,
+             double* c,
+             const int* ldc);
+
+void csyr2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const cuComplex* alpha,
+             const cuComplex* a,
+             const int* lda,
+             const cuComplex* b,
+             const int* ldb,
+             const cuComplex* beta,
+             cuComplex* c,
+             const int* ldc);
+
+void zsyr2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const cuDoubleComplex* alpha,
+             const cuDoubleComplex* a,
+             const int* lda,
+             const cuDoubleComplex* b,
+             const int* ldb,
+             const cuDoubleComplex* beta,
+             cuDoubleComplex* c,
+             const int* ldc);
+
+/* SYR2K no_underscore*/
+void ssyr2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            const float* b,
+            const int* ldb,
+            const float* beta,
+            float* c,
+            const int* ldc);
+
+void dsyr2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            const double* b,
+            const int* ldb,
+            const double* beta,
+            double* c,
+            const int* ldc);
+
+void csyr2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* b,
+            const int* ldb,
+            const cuComplex* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zsyr2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* b,
+            const int* ldb,
+            const cuDoubleComplex* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+/* HERK */
+void cher2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const cuComplex* alpha,
+             const cuComplex* a,
+             const int* lda,
+             const cuComplex* b,
+             const int* ldb,
+             const float* beta,
+             cuComplex* c,
+             const int* ldc);
+
+void zher2k_(const char* uplo,
+             const char* trans,
+             const int* n,
+             const int* k,
+             const cuDoubleComplex* alpha,
+             const cuDoubleComplex* a,
+             const int* lda,
+             const cuDoubleComplex* b,
+             const int* ldb,
+             const double* beta,
+             cuDoubleComplex* c,
+             const int* ldc);
+
+/* HER2K with no underscore */
+void cher2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            const cuComplex* b,
+            const int* ldb,
+            const float* beta,
+            cuComplex* c,
+            const int* ldc);
+
+void zher2k(const char* uplo,
+            const char* trans,
+            const int* n,
+            const int* k,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            const cuDoubleComplex* b,
+            const int* ldb,
+            const double* beta,
+            cuDoubleComplex* c,
+            const int* ldc);
+
+/* TRMM */
+void strmm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const float* alpha,
+            const float* a,
+            const int* lda,
+            float* b,
+            const int* ldb);
+
+void dtrmm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const double* alpha,
+            const double* a,
+            const int* lda,
+            double* b,
+            const int* ldb);
+
+void ctrmm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const cuComplex* alpha,
+            const cuComplex* a,
+            const int* lda,
+            cuComplex* b,
+            const int* ldb);
+
+void ztrmm_(const char* side,
+            const char* uplo,
+            const char* transa,
+            const char* diag,
+            const int* m,
+            const int* n,
+            const cuDoubleComplex* alpha,
+            const cuDoubleComplex* a,
+            const int* lda,
+            cuDoubleComplex* b,
+            const int* ldb);
+
+void strmm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const float* alpha,
+           const float* a,
+           const int* lda,
+           float* b,
+           const int* ldb);
+
+void dtrmm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const double* alpha,
+           const double* a,
+           const int* lda,
+           double* b,
+           const int* ldb);
+
+void ctrmm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const cuComplex* alpha,
+           const cuComplex* a,
+           const int* lda,
+           cuComplex* b,
+           const int* ldb);
+
+void ztrmm(const char* side,
+           const char* uplo,
+           const char* transa,
+           const char* diag,
+           const int* m,
+           const int* n,
+           const cuDoubleComplex* alpha,
+           const cuDoubleComplex* a,
+           const int* lda,
+           cuDoubleComplex* b,
+           const int* ldb);
+
+#if defined(__cplusplus)
+}
+#endif /* __cplusplus */
+
+#endif /* !defined(NVBLAS_H_) */
diff --git a/shared/package-files/75/75765a494ebd6b12a722c827ef647db46d92d5e801acb4b8390266a7ae559181/reflection_pad1d_backward_ops.h b/shared/package-files/75/75765a494ebd6b12a722c827ef647db46d92d5e801acb4b8390266a7ae559181/reflection_pad1d_backward_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..8589986abd29fcf386f5f06b78b830e27d93f8cf
--- /dev/null
+++ b/shared/package-files/75/75765a494ebd6b12a722c827ef647db46d92d5e801acb4b8390266a7ae559181/reflection_pad1d_backward_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API reflection_pad1d_backward_grad_input {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::reflection_pad1d_backward";
+  static constexpr const char* overload_name = "grad_input";
+  static constexpr const char* schema_str = "reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input);
+};
+
+struct TORCH_API reflection_pad1d_backward {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::reflection_pad1d_backward";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor";
+  static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/75/75859aaeb3d6f2c2672ecc2b7ae18654855314853a798f3d8a59df1325be79cb/__init__.cpython-311.pyc b/shared/package-files/75/75859aaeb3d6f2c2672ecc2b7ae18654855314853a798f3d8a59df1325be79cb/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41c0effb433687bba2489cced841f2408b98dedb
Binary files /dev/null and b/shared/package-files/75/75859aaeb3d6f2c2672ecc2b7ae18654855314853a798f3d8a59df1325be79cb/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/75/7588384601828b307b17f11991303acac8666736b59f91e37b8adb618d477768/StorageImpl.h b/shared/package-files/75/7588384601828b307b17f11991303acac8666736b59f91e37b8adb618d477768/StorageImpl.h
new file mode 100644
index 0000000000000000000000000000000000000000..e45b4953b9c90ecc3d81163d370f49af652b1cb5
--- /dev/null
+++ b/shared/package-files/75/7588384601828b307b17f11991303acac8666736b59f91e37b8adb618d477768/StorageImpl.h
@@ -0,0 +1,368 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10 {
+
+[[noreturn]] C10_API void throwNullDataPtrError();
+C10_API void warnDeprecatedDataPtr();
+
+// Used in StorageImpl to store extra metadata.
+// Currently used only for storing a custom error message
+// used when throwing an exception when data_ptr is accessed.
+struct C10_API StorageExtraMeta {
+  std::optional custom_data_ptr_error_msg_ = std::nullopt;
+};
+
+// A storage represents the underlying backing data buffer for a
+// tensor.  This concept was inherited from the original Torch7
+// codebase; we'd kind of like to get rid of the concept
+// (see https://github.com/pytorch/pytorch/issues/14797) but
+// it's hard work and no one has gotten around to doing it.
+//
+// NB: storage is supposed to uniquely own a data pointer; e.g.,
+// two non-null data pointers alias if and only if they are from
+// the same storage.  Technically you can violate this invariant
+// (e.g., you can create a non-owning StorageImpl with at::from_blob)
+// but a lot of things won't work correctly, including:
+//
+// - An ordinary deleter on such a storage is wrong, because normal deleters
+//   assume unique ownership, but if you have two storages at the same data,
+//   that implies there is some sort of shared ownership. So your deleter would
+//   have to actually be internally doing some sort of refcount thing
+// - Deepcopy in Python side relies on storage equality and not data pointer
+//   equality; so if there are two separate storages pointing to the same data,
+//   the data will actually get duplicated in that case (one data ptr before,
+//   two data ptrs after)
+// - Version counts won't work correctly, because we do all VC tracking at the
+//   level of storages (unless you explicitly disconnect the VC with detach);
+//   mutation because data pointers are the same are totally untracked
+struct C10_API StorageImpl : public c10::intrusive_ptr_target {
+ public:
+  struct use_byte_size_t {};
+
+  StorageImpl(
+      use_byte_size_t /*use_byte_size*/,
+      SymInt size_bytes,
+      at::DataPtr data_ptr,
+      at::Allocator* allocator,
+      bool resizable)
+      : data_ptr_(std::move(data_ptr)),
+        size_bytes_(std::move(size_bytes)),
+        size_bytes_is_heap_allocated_(size_bytes_.is_heap_allocated()),
+        resizable_(resizable),
+        received_cuda_(false),
+        allocator_(allocator) {
+    if (resizable) {
+      TORCH_INTERNAL_ASSERT(
+          allocator_, "For resizable storage, allocator must be provided");
+    }
+    refresh_has_data_ptr_check();
+  }
+
+  StorageImpl(
+      use_byte_size_t /*use_byte_size*/,
+      const SymInt& size_bytes,
+      at::Allocator* allocator,
+      bool resizable)
+      : StorageImpl(
+            use_byte_size_t(),
+            size_bytes,
+            size_bytes.is_heap_allocated()
+                ? allocator->allocate(0)
+                : allocator->allocate(size_bytes.as_int_unchecked()),
+            allocator,
+            resizable) {}
+
+  StorageImpl& operator=(StorageImpl&& other) = delete;
+  StorageImpl& operator=(const StorageImpl&) = delete;
+  StorageImpl() = delete;
+  StorageImpl(StorageImpl&& other) = delete;
+  StorageImpl(const StorageImpl&) = delete;
+  ~StorageImpl() override = default;
+
+  void reset() {
+    data_ptr_.clear();
+    size_bytes_ = 0;
+    size_bytes_is_heap_allocated_ = false;
+  }
+
+  // Destructor doesn't call release_resources because it's
+  // unnecessary; don't forget to change that if needed!
+  void release_resources() override {
+    data_ptr_.clear();
+  }
+
+  size_t nbytes() const {
+    // OK to do this instead of maybe_as_int as nbytes is guaranteed positive
+    TORCH_CHECK(!size_bytes_is_heap_allocated_);
+    return size_bytes_.as_int_unchecked();
+  }
+
+  SymInt sym_nbytes() const {
+    return size_bytes_;
+  }
+
+  // TODO: remove later
+  void set_nbytes(size_t size_bytes) {
+    size_bytes_ = static_cast(size_bytes);
+    size_bytes_is_heap_allocated_ = false;
+  }
+
+  void set_nbytes(c10::SymInt size_bytes) {
+    size_bytes_ = std::move(size_bytes);
+  }
+
+  bool resizable() const {
+    return resizable_;
+  }
+
+  const at::DataPtr& data_ptr() const {
+    if (C10_UNLIKELY(throw_on_immutable_data_ptr_)) {
+      throw_data_ptr_access_error();
+    }
+    return data_ptr_;
+  }
+
+  at::DataPtr& mutable_data_ptr() {
+    if (C10_UNLIKELY(has_mutable_data_ptr_check_)) {
+      if (throw_on_immutable_data_ptr_) {
+        throw_data_ptr_access_error();
+      }
+      if (throw_on_mutable_data_ptr_) {
+        throwNullDataPtrError();
+      }
+      if (warn_deprecated_on_mutable_data_ptr_) {
+        warnDeprecatedDataPtr();
+      }
+      maybe_materialize_cow();
+    }
+    return data_ptr_;
+  }
+
+  // Returns the data_ptr. Bypasses all checks.
+  at::DataPtr& _mutable_data_ptr_no_checks() {
+    return data_ptr_;
+  }
+
+  // Returns the previous data_ptr
+  at::DataPtr set_data_ptr(at::DataPtr&& data_ptr) {
+    // We need to materialize the old COW DataPtr because it is
+    // being returned as mutable.
+    maybe_materialize_cow();
+    return set_data_ptr_no_materialize_cow(std::move(data_ptr));
+  }
+
+  void set_data_ptr_noswap(at::DataPtr&& data_ptr) {
+    data_ptr_ = std::move(data_ptr);
+    refresh_has_data_ptr_check();
+  }
+
+  const void* data() const {
+    if (C10_UNLIKELY(throw_on_immutable_data_ptr_)) {
+      throw_data_ptr_access_error();
+    }
+    return data_ptr_.get();
+  }
+
+  void* mutable_data() {
+    if (C10_UNLIKELY(has_mutable_data_ptr_check_)) {
+      if (throw_on_immutable_data_ptr_) {
+        throw_data_ptr_access_error();
+      }
+      if (throw_on_mutable_data_ptr_) {
+        throwNullDataPtrError();
+      }
+      if (warn_deprecated_on_mutable_data_ptr_) {
+        warnDeprecatedDataPtr();
+      }
+      maybe_materialize_cow();
+    }
+    return data_ptr_.mutable_get();
+  }
+
+  at::DeviceType device_type() const {
+    return data_ptr_.device().type();
+  }
+
+  at::Allocator* allocator() {
+    return allocator_;
+  }
+
+  const at::Allocator* allocator() const {
+    return allocator_;
+  }
+
+  // You generally shouldn't use this method, but it is occasionally
+  // useful if you want to override how a tensor will be reallocated,
+  // after it was already allocated (and its initial allocator was
+  // set)
+  void set_allocator(at::Allocator* allocator) {
+    allocator_ = allocator;
+  }
+
+  Device device() const {
+    return data_ptr_.device();
+  }
+
+  void set_resizable(bool resizable) {
+    if (resizable) {
+      // We need an allocator to be resizable
+      AT_ASSERT(allocator_);
+    }
+    resizable_ = resizable;
+  }
+
+  /**
+   * Can only be called when use_count is 1
+   */
+  void UniqueStorageShareExternalPointer(
+      void* src,
+      size_t size_bytes,
+      DeleterFnPtr d = nullptr) {
+    UniqueStorageShareExternalPointer(
+        at::DataPtr(src, src, d, data_ptr_.device()), size_bytes);
+  }
+
+  /**
+   * Can only be called when use_count is 1
+   */
+  void UniqueStorageShareExternalPointer(
+      at::DataPtr&& data_ptr,
+      size_t size_bytes) {
+    data_ptr_ = std::move(data_ptr);
+    size_bytes_ = static_cast(size_bytes);
+    size_bytes_is_heap_allocated_ = false;
+    allocator_ = nullptr;
+    resizable_ = false;
+  }
+
+  // This method can be used only after storage construction and cannot be used
+  // to modify storage status
+  void set_received_cuda(bool received_cuda) {
+    received_cuda_ = received_cuda;
+  }
+
+  bool received_cuda() {
+    return received_cuda_;
+  }
+
+  impl::PyObjectSlot* pyobj_slot() {
+    return &pyobj_slot_;
+  }
+
+  const impl::PyObjectSlot* pyobj_slot() const {
+    return &pyobj_slot_;
+  }
+
+  StorageExtraMeta& get_extra_meta() {
+    if (!extra_meta_) {
+      extra_meta_ = std::make_unique();
+    }
+    return *extra_meta_;
+  }
+
+  [[noreturn]] void throw_data_ptr_access_error() const;
+
+  void release_data_and_set_meta_custom_data_ptr_error_msg_(
+      std::optional s) {
+    throw_on_immutable_data_ptr_ = true;
+    get_extra_meta().custom_data_ptr_error_msg_ = std::move(s);
+    refresh_has_data_ptr_check();
+  }
+
+  void set_throw_on_mutable_data_ptr() {
+    throw_on_mutable_data_ptr_ = true;
+    refresh_has_data_ptr_check();
+  }
+
+  void set_warn_deprecated_on_mutable_data_ptr() {
+    warn_deprecated_on_mutable_data_ptr_ = true;
+    refresh_has_data_ptr_check();
+  }
+
+ protected:
+  // materialize_cow_storage needs to call set_data_ptr_no_materlize_cow
+  friend void c10::impl::cow::materialize_cow_storage(StorageImpl& storage);
+
+  // Returns the previous data_ptr. If the old data_ptr was COW,
+  // this avoids materializing it
+  at::DataPtr set_data_ptr_no_materialize_cow(at::DataPtr&& data_ptr) {
+    at::DataPtr old_data_ptr(std::move(data_ptr_));
+    data_ptr_ = std::move(data_ptr);
+    refresh_has_data_ptr_check();
+    return old_data_ptr;
+  }
+
+ private:
+  void refresh_has_data_ptr_check() {
+    has_mutable_data_ptr_check_ = is_cow() || throw_on_mutable_data_ptr_ ||
+        warn_deprecated_on_mutable_data_ptr_ || throw_on_immutable_data_ptr_;
+  }
+
+  inline bool is_cow() const {
+    return c10::impl::cow::is_cow_data_ptr(data_ptr_);
+  }
+
+  // Triggers a copy if this is a copy-on-write tensor.
+  void maybe_materialize_cow() {
+    if (is_cow()) {
+      impl::cow::materialize_cow_storage(*this);
+    }
+  }
+
+  DataPtr data_ptr_;
+  SymInt size_bytes_;
+  bool size_bytes_is_heap_allocated_;
+  bool resizable_;
+  // Identifies that Storage was received from another process and doesn't have
+  // local to process cuda memory allocation
+  bool received_cuda_;
+  // All special checks in data/data_ptr calls are guarded behind this single
+  // boolean. This is for performance: .data/.data_ptr calls are commonly in the
+  // hot-path.
+  bool has_mutable_data_ptr_check_ = false;
+  // If we should throw when mutable_data_ptr() or mutable_data() is called.
+  bool throw_on_mutable_data_ptr_ = false;
+  // If we should throw when data_ptr() or data() is called.
+  bool throw_on_immutable_data_ptr_ = false;
+  // If we warn when mutable_data_ptr() or mutable_data() is called.
+  bool warn_deprecated_on_mutable_data_ptr_ = false;
+  Allocator* allocator_;
+  impl::PyObjectSlot pyobj_slot_;
+  std::unique_ptr extra_meta_ = nullptr;
+};
+
+// Declare StorageImpl create function pointer types.
+using StorageImplCreateHelper = intrusive_ptr (*)(
+    StorageImpl::use_byte_size_t,
+    SymInt size_bytes,
+    DataPtr data_ptr,
+    Allocator* allocator,
+    bool resizable);
+
+C10_API void SetStorageImplCreate(DeviceType t, StorageImplCreateHelper fptr);
+
+C10_API StorageImplCreateHelper GetStorageImplCreate(DeviceType t);
+
+C10_API c10::intrusive_ptr make_storage_impl(
+    c10::StorageImpl::use_byte_size_t use_byte_size,
+    c10::SymInt size_bytes,
+    c10::DataPtr data_ptr,
+    c10::Allocator* allocator,
+    bool resizable,
+    std::optional device_opt);
+
+} // namespace c10
diff --git a/shared/package-files/75/7588ab7f093df6344ffd6d51db406f533f769abaa859ebe55b765d7eef5f4390/conftest.py b/shared/package-files/75/7588ab7f093df6344ffd6d51db406f533f769abaa859ebe55b765d7eef5f4390/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..10134c90f8eeb861ba6368e6677e0d2120a09290
--- /dev/null
+++ b/shared/package-files/75/7588ab7f093df6344ffd6d51db406f533f769abaa859ebe55b765d7eef5f4390/conftest.py
@@ -0,0 +1,1980 @@
+"""
+This file is very long and growing, but it was decided to not split it yet, as
+it's still manageable (2020-03-17, ~1.1k LoC). See gh-31989
+
+Instead of splitting it was decided to define sections here:
+- Configuration / Settings
+- Autouse fixtures
+- Common arguments
+- Missing values & co.
+- Classes
+- Indices
+- Series'
+- DataFrames
+- Operators & Operations
+- Data sets/files
+- Time zones
+- Dtypes
+- Misc
+"""
+from __future__ import annotations
+
+from collections import abc
+from datetime import (
+    date,
+    datetime,
+    time,
+    timedelta,
+    timezone,
+)
+from decimal import Decimal
+import operator
+import os
+from typing import (
+    TYPE_CHECKING,
+    Callable,
+)
+
+from dateutil.tz import (
+    tzlocal,
+    tzutc,
+)
+import hypothesis
+from hypothesis import strategies as st
+import numpy as np
+import pytest
+from pytz import (
+    FixedOffset,
+    utc,
+)
+
+from pandas._config.config import _get_option
+
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.dtypes import (
+    DatetimeTZDtype,
+    IntervalDtype,
+)
+
+import pandas as pd
+from pandas import (
+    CategoricalIndex,
+    DataFrame,
+    Interval,
+    IntervalIndex,
+    Period,
+    RangeIndex,
+    Series,
+    Timedelta,
+    Timestamp,
+    date_range,
+    period_range,
+    timedelta_range,
+)
+import pandas._testing as tm
+from pandas.core import ops
+from pandas.core.indexes.api import (
+    Index,
+    MultiIndex,
+)
+from pandas.util.version import Version
+
+if TYPE_CHECKING:
+    from collections.abc import (
+        Hashable,
+        Iterator,
+    )
+
+try:
+    import pyarrow as pa
+except ImportError:
+    has_pyarrow = False
+else:
+    del pa
+    has_pyarrow = True
+
+import zoneinfo
+
+try:
+    zoneinfo.ZoneInfo("UTC")
+except zoneinfo.ZoneInfoNotFoundError:
+    zoneinfo = None  # type: ignore[assignment]
+
+
+# ----------------------------------------------------------------
+# Configuration / Settings
+# ----------------------------------------------------------------
+# pytest
+
+
+def pytest_addoption(parser) -> None:
+    parser.addoption(
+        "--no-strict-data-files",
+        action="store_false",
+        help="Don't fail if a test is skipped for missing data file.",
+    )
+
+
+def ignore_doctest_warning(item: pytest.Item, path: str, message: str) -> None:
+    """Ignore doctest warning.
+
+    Parameters
+    ----------
+    item : pytest.Item
+        pytest test item.
+    path : str
+        Module path to Python object, e.g. "pandas.core.frame.DataFrame.append". A
+        warning will be filtered when item.name ends with in given path. So it is
+        sufficient to specify e.g. "DataFrame.append".
+    message : str
+        Message to be filtered.
+    """
+    if item.name.endswith(path):
+        item.add_marker(pytest.mark.filterwarnings(f"ignore:{message}"))
+
+
+def pytest_collection_modifyitems(items, config) -> None:
+    is_doctest = config.getoption("--doctest-modules") or config.getoption(
+        "--doctest-cython", default=False
+    )
+
+    # Warnings from doctests that can be ignored; place reason in comment above.
+    # Each entry specifies (path, message) - see the ignore_doctest_warning function
+    ignored_doctest_warnings = [
+        ("is_int64_dtype", "is_int64_dtype is deprecated"),
+        ("is_interval_dtype", "is_interval_dtype is deprecated"),
+        ("is_period_dtype", "is_period_dtype is deprecated"),
+        ("is_datetime64tz_dtype", "is_datetime64tz_dtype is deprecated"),
+        ("is_categorical_dtype", "is_categorical_dtype is deprecated"),
+        ("is_sparse", "is_sparse is deprecated"),
+        ("DataFrameGroupBy.fillna", "DataFrameGroupBy.fillna is deprecated"),
+        ("NDFrame.replace", "The 'method' keyword"),
+        ("NDFrame.replace", "Series.replace without 'value'"),
+        ("NDFrame.clip", "Downcasting behavior in Series and DataFrame methods"),
+        ("Series.idxmin", "The behavior of Series.idxmin"),
+        ("Series.idxmax", "The behavior of Series.idxmax"),
+        ("SeriesGroupBy.fillna", "SeriesGroupBy.fillna is deprecated"),
+        ("SeriesGroupBy.idxmin", "The behavior of Series.idxmin"),
+        ("SeriesGroupBy.idxmax", "The behavior of Series.idxmax"),
+        # Docstring divides by zero to show behavior difference
+        ("missing.mask_zero_div_zero", "divide by zero encountered"),
+        (
+            "to_pydatetime",
+            "The behavior of DatetimeProperties.to_pydatetime is deprecated",
+        ),
+        (
+            "pandas.core.generic.NDFrame.bool",
+            "(Series|DataFrame).bool is now deprecated and will be removed "
+            "in future version of pandas",
+        ),
+        (
+            "pandas.core.generic.NDFrame.first",
+            "first is deprecated and will be removed in a future version. "
+            "Please create a mask and filter using `.loc` instead",
+        ),
+        (
+            "Resampler.fillna",
+            "DatetimeIndexResampler.fillna is deprecated",
+        ),
+        (
+            "DataFrameGroupBy.fillna",
+            "DataFrameGroupBy.fillna with 'method' is deprecated",
+        ),
+        (
+            "DataFrameGroupBy.fillna",
+            "DataFrame.fillna with 'method' is deprecated",
+        ),
+        ("read_parquet", "Passing a BlockManager to DataFrame is deprecated"),
+    ]
+
+    if is_doctest:
+        for item in items:
+            for path, message in ignored_doctest_warnings:
+                ignore_doctest_warning(item, path, message)
+
+
+hypothesis_health_checks = [hypothesis.HealthCheck.too_slow]
+if Version(hypothesis.__version__) >= Version("6.83.2"):
+    hypothesis_health_checks.append(hypothesis.HealthCheck.differing_executors)
+
+# Hypothesis
+hypothesis.settings.register_profile(
+    "ci",
+    # Hypothesis timing checks are tuned for scalars by default, so we bump
+    # them from 200ms to 500ms per test case as the global default.  If this
+    # is too short for a specific test, (a) try to make it faster, and (b)
+    # if it really is slow add `@settings(deadline=...)` with a working value,
+    # or `deadline=None` to entirely disable timeouts for that test.
+    # 2022-02-09: Changed deadline from 500 -> None. Deadline leads to
+    # non-actionable, flaky CI failures (# GH 24641, 44969, 45118, 44969)
+    deadline=None,
+    suppress_health_check=tuple(hypothesis_health_checks),
+)
+hypothesis.settings.load_profile("ci")
+
+# Registering these strategies makes them globally available via st.from_type,
+# which is use for offsets in tests/tseries/offsets/test_offsets_properties.py
+for name in "MonthBegin MonthEnd BMonthBegin BMonthEnd".split():
+    cls = getattr(pd.tseries.offsets, name)
+    st.register_type_strategy(
+        cls, st.builds(cls, n=st.integers(-99, 99), normalize=st.booleans())
+    )
+
+for name in "YearBegin YearEnd BYearBegin BYearEnd".split():
+    cls = getattr(pd.tseries.offsets, name)
+    st.register_type_strategy(
+        cls,
+        st.builds(
+            cls,
+            n=st.integers(-5, 5),
+            normalize=st.booleans(),
+            month=st.integers(min_value=1, max_value=12),
+        ),
+    )
+
+for name in "QuarterBegin QuarterEnd BQuarterBegin BQuarterEnd".split():
+    cls = getattr(pd.tseries.offsets, name)
+    st.register_type_strategy(
+        cls,
+        st.builds(
+            cls,
+            n=st.integers(-24, 24),
+            normalize=st.booleans(),
+            startingMonth=st.integers(min_value=1, max_value=12),
+        ),
+    )
+
+
+# ----------------------------------------------------------------
+# Autouse fixtures
+# ----------------------------------------------------------------
+
+
+# https://github.com/pytest-dev/pytest/issues/11873
+# Would like to avoid autouse=True, but cannot as of pytest 8.0.0
+@pytest.fixture(autouse=True)
+def add_doctest_imports(doctest_namespace) -> None:
+    """
+    Make `np` and `pd` names available for doctests.
+    """
+    doctest_namespace["np"] = np
+    doctest_namespace["pd"] = pd
+
+
+@pytest.fixture(autouse=True)
+def configure_tests() -> None:
+    """
+    Configure settings for all tests and test modules.
+    """
+    pd.set_option("chained_assignment", "raise")
+
+
+# ----------------------------------------------------------------
+# Common arguments
+# ----------------------------------------------------------------
+@pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis={repr(x)}")
+def axis(request):
+    """
+    Fixture for returning the axis numbers of a DataFrame.
+    """
+    return request.param
+
+
+axis_frame = axis
+
+
+@pytest.fixture(params=[1, "columns"], ids=lambda x: f"axis={repr(x)}")
+def axis_1(request):
+    """
+    Fixture for returning aliases of axis 1 of a DataFrame.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[True, False, None])
+def observed(request):
+    """
+    Pass in the observed keyword to groupby for [True, False]
+    This indicates whether categoricals should return values for
+    values which are not in the grouper [False / None], or only values which
+    appear in the grouper [True]. [None] is supported for future compatibility
+    if we decide to change the default (and would need to warn if this
+    parameter is not passed).
+    """
+    return request.param
+
+
+@pytest.fixture(params=[True, False, None])
+def ordered(request):
+    """
+    Boolean 'ordered' parameter for Categorical.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[True, False])
+def skipna(request):
+    """
+    Boolean 'skipna' parameter.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["first", "last", False])
+def keep(request):
+    """
+    Valid values for the 'keep' parameter used in
+    .duplicated or .drop_duplicates
+    """
+    return request.param
+
+
+@pytest.fixture(params=["both", "neither", "left", "right"])
+def inclusive_endpoints_fixture(request):
+    """
+    Fixture for trying all interval 'inclusive' parameters.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["left", "right", "both", "neither"])
+def closed(request):
+    """
+    Fixture for trying all interval closed parameters.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["left", "right", "both", "neither"])
+def other_closed(request):
+    """
+    Secondary closed fixture to allow parametrizing over all pairs of closed.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        None,
+        "gzip",
+        "bz2",
+        "zip",
+        "xz",
+        "tar",
+        pytest.param("zstd", marks=td.skip_if_no("zstandard")),
+    ]
+)
+def compression(request):
+    """
+    Fixture for trying common compression types in compression tests.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        "gzip",
+        "bz2",
+        "zip",
+        "xz",
+        "tar",
+        pytest.param("zstd", marks=td.skip_if_no("zstandard")),
+    ]
+)
+def compression_only(request):
+    """
+    Fixture for trying common compression types in compression tests excluding
+    uncompressed case.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[True, False])
+def writable(request):
+    """
+    Fixture that an array is writable.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["inner", "outer", "left", "right"])
+def join_type(request):
+    """
+    Fixture for trying all types of join operations.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["nlargest", "nsmallest"])
+def nselect_method(request):
+    """
+    Fixture for trying all nselect methods.
+    """
+    return request.param
+
+
+# ----------------------------------------------------------------
+# Missing values & co.
+# ----------------------------------------------------------------
+@pytest.fixture(params=tm.NULL_OBJECTS, ids=lambda x: type(x).__name__)
+def nulls_fixture(request):
+    """
+    Fixture for each null type in pandas.
+    """
+    return request.param
+
+
+nulls_fixture2 = nulls_fixture  # Generate cartesian product of nulls_fixture
+
+
+@pytest.fixture(params=[None, np.nan, pd.NaT])
+def unique_nulls_fixture(request):
+    """
+    Fixture for each null type in pandas, each null type exactly once.
+    """
+    return request.param
+
+
+# Generate cartesian product of unique_nulls_fixture:
+unique_nulls_fixture2 = unique_nulls_fixture
+
+
+@pytest.fixture(params=tm.NP_NAT_OBJECTS, ids=lambda x: type(x).__name__)
+def np_nat_fixture(request):
+    """
+    Fixture for each NaT type in numpy.
+    """
+    return request.param
+
+
+# Generate cartesian product of np_nat_fixture:
+np_nat_fixture2 = np_nat_fixture
+
+
+# ----------------------------------------------------------------
+# Classes
+# ----------------------------------------------------------------
+
+
+@pytest.fixture(params=[DataFrame, Series])
+def frame_or_series(request):
+    """
+    Fixture to parametrize over DataFrame and Series.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[Index, Series], ids=["index", "series"])
+def index_or_series(request):
+    """
+    Fixture to parametrize over Index and Series, made necessary by a mypy
+    bug, giving an error:
+
+    List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]"
+
+    See GH#29725
+    """
+    return request.param
+
+
+# Generate cartesian product of index_or_series fixture:
+index_or_series2 = index_or_series
+
+
+@pytest.fixture(params=[Index, Series, pd.array], ids=["index", "series", "array"])
+def index_or_series_or_array(request):
+    """
+    Fixture to parametrize over Index, Series, and ExtensionArray
+    """
+    return request.param
+
+
+@pytest.fixture(params=[Index, Series, DataFrame, pd.array], ids=lambda x: x.__name__)
+def box_with_array(request):
+    """
+    Fixture to test behavior for Index, Series, DataFrame, and pandas Array
+    classes
+    """
+    return request.param
+
+
+box_with_array2 = box_with_array
+
+
+@pytest.fixture
+def dict_subclass() -> type[dict]:
+    """
+    Fixture for a dictionary subclass.
+    """
+
+    class TestSubDict(dict):
+        def __init__(self, *args, **kwargs) -> None:
+            dict.__init__(self, *args, **kwargs)
+
+    return TestSubDict
+
+
+@pytest.fixture
+def non_dict_mapping_subclass() -> type[abc.Mapping]:
+    """
+    Fixture for a non-mapping dictionary subclass.
+    """
+
+    class TestNonDictMapping(abc.Mapping):
+        def __init__(self, underlying_dict) -> None:
+            self._data = underlying_dict
+
+        def __getitem__(self, key):
+            return self._data.__getitem__(key)
+
+        def __iter__(self) -> Iterator:
+            return self._data.__iter__()
+
+        def __len__(self) -> int:
+            return self._data.__len__()
+
+    return TestNonDictMapping
+
+
+# ----------------------------------------------------------------
+# Indices
+# ----------------------------------------------------------------
+@pytest.fixture
+def multiindex_year_month_day_dataframe_random_data():
+    """
+    DataFrame with 3 level MultiIndex (year, month, day) covering
+    first 100 business days from 2000-01-01 with random data
+    """
+    tdf = DataFrame(
+        np.random.default_rng(2).standard_normal((100, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=date_range("2000-01-01", periods=100, freq="B"),
+    )
+    ymd = tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum()
+    # use int64 Index, to make sure things work
+    ymd.index = ymd.index.set_levels([lev.astype("i8") for lev in ymd.index.levels])
+    ymd.index.set_names(["year", "month", "day"], inplace=True)
+    return ymd
+
+
+@pytest.fixture
+def lexsorted_two_level_string_multiindex() -> MultiIndex:
+    """
+    2-level MultiIndex, lexsorted, with string names.
+    """
+    return MultiIndex(
+        levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]],
+        codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
+        names=["first", "second"],
+    )
+
+
+@pytest.fixture
+def multiindex_dataframe_random_data(
+    lexsorted_two_level_string_multiindex,
+) -> DataFrame:
+    """DataFrame with 2 level MultiIndex with random data"""
+    index = lexsorted_two_level_string_multiindex
+    return DataFrame(
+        np.random.default_rng(2).standard_normal((10, 3)),
+        index=index,
+        columns=Index(["A", "B", "C"], name="exp"),
+    )
+
+
+def _create_multiindex():
+    """
+    MultiIndex used to test the general functionality of this object
+    """
+
+    # See Also: tests.multi.conftest.idx
+    major_axis = Index(["foo", "bar", "baz", "qux"])
+    minor_axis = Index(["one", "two"])
+
+    major_codes = np.array([0, 0, 1, 2, 3, 3])
+    minor_codes = np.array([0, 1, 0, 1, 0, 1])
+    index_names = ["first", "second"]
+    return MultiIndex(
+        levels=[major_axis, minor_axis],
+        codes=[major_codes, minor_codes],
+        names=index_names,
+        verify_integrity=False,
+    )
+
+
+def _create_mi_with_dt64tz_level():
+    """
+    MultiIndex with a level that is a tzaware DatetimeIndex.
+    """
+    # GH#8367 round trip with pickle
+    return MultiIndex.from_product(
+        [[1, 2], ["a", "b"], date_range("20130101", periods=3, tz="US/Eastern")],
+        names=["one", "two", "three"],
+    )
+
+
+indices_dict = {
+    "string": Index([f"pandas_{i}" for i in range(100)]),
+    "datetime": date_range("2020-01-01", periods=100),
+    "datetime-tz": date_range("2020-01-01", periods=100, tz="US/Pacific"),
+    "period": period_range("2020-01-01", periods=100, freq="D"),
+    "timedelta": timedelta_range(start="1 day", periods=100, freq="D"),
+    "range": RangeIndex(100),
+    "int8": Index(np.arange(100), dtype="int8"),
+    "int16": Index(np.arange(100), dtype="int16"),
+    "int32": Index(np.arange(100), dtype="int32"),
+    "int64": Index(np.arange(100), dtype="int64"),
+    "uint8": Index(np.arange(100), dtype="uint8"),
+    "uint16": Index(np.arange(100), dtype="uint16"),
+    "uint32": Index(np.arange(100), dtype="uint32"),
+    "uint64": Index(np.arange(100), dtype="uint64"),
+    "float32": Index(np.arange(100), dtype="float32"),
+    "float64": Index(np.arange(100), dtype="float64"),
+    "bool-object": Index([True, False] * 5, dtype=object),
+    "bool-dtype": Index([True, False] * 5, dtype=bool),
+    "complex64": Index(
+        np.arange(100, dtype="complex64") + 1.0j * np.arange(100, dtype="complex64")
+    ),
+    "complex128": Index(
+        np.arange(100, dtype="complex128") + 1.0j * np.arange(100, dtype="complex128")
+    ),
+    "categorical": CategoricalIndex(list("abcd") * 25),
+    "interval": IntervalIndex.from_breaks(np.linspace(0, 100, num=101)),
+    "empty": Index([]),
+    "tuples": MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])),
+    "mi-with-dt64tz-level": _create_mi_with_dt64tz_level(),
+    "multi": _create_multiindex(),
+    "repeats": Index([0, 0, 1, 1, 2, 2]),
+    "nullable_int": Index(np.arange(100), dtype="Int64"),
+    "nullable_uint": Index(np.arange(100), dtype="UInt16"),
+    "nullable_float": Index(np.arange(100), dtype="Float32"),
+    "nullable_bool": Index(np.arange(100).astype(bool), dtype="boolean"),
+    "string-python": Index(
+        pd.array([f"pandas_{i}" for i in range(100)], dtype="string[python]")
+    ),
+}
+if has_pyarrow:
+    idx = Index(pd.array([f"pandas_{i}" for i in range(100)], dtype="string[pyarrow]"))
+    indices_dict["string-pyarrow"] = idx
+
+
+@pytest.fixture(params=indices_dict.keys())
+def index(request):
+    """
+    Fixture for many "simple" kinds of indices.
+
+    These indices are unlikely to cover corner cases, e.g.
+        - no names
+        - no NaTs/NaNs
+        - no values near implementation bounds
+        - ...
+    """
+    # copy to avoid mutation, e.g. setting .name
+    return indices_dict[request.param].copy()
+
+
+# Needed to generate cartesian product of indices
+index_fixture2 = index
+
+
+@pytest.fixture(
+    params=[
+        key for key, value in indices_dict.items() if not isinstance(value, MultiIndex)
+    ]
+)
+def index_flat(request):
+    """
+    index fixture, but excluding MultiIndex cases.
+    """
+    key = request.param
+    return indices_dict[key].copy()
+
+
+# Alias so we can test with cartesian product of index_flat
+index_flat2 = index_flat
+
+
+@pytest.fixture(
+    params=[
+        key
+        for key, value in indices_dict.items()
+        if not (
+            key.startswith(("int", "uint", "float"))
+            or key in ["range", "empty", "repeats", "bool-dtype"]
+        )
+        and not isinstance(value, MultiIndex)
+    ]
+)
+def index_with_missing(request):
+    """
+    Fixture for indices with missing values.
+
+    Integer-dtype and empty cases are excluded because they cannot hold missing
+    values.
+
+    MultiIndex is excluded because isna() is not defined for MultiIndex.
+    """
+
+    # GH 35538. Use deep copy to avoid illusive bug on np-dev
+    # GHA pipeline that writes into indices_dict despite copy
+    ind = indices_dict[request.param].copy(deep=True)
+    vals = ind.values.copy()
+    if request.param in ["tuples", "mi-with-dt64tz-level", "multi"]:
+        # For setting missing values in the top level of MultiIndex
+        vals = ind.tolist()
+        vals[0] = (None,) + vals[0][1:]
+        vals[-1] = (None,) + vals[-1][1:]
+        return MultiIndex.from_tuples(vals)
+    else:
+        vals[0] = None
+        vals[-1] = None
+        return type(ind)(vals)
+
+
+# ----------------------------------------------------------------
+# Series'
+# ----------------------------------------------------------------
+@pytest.fixture
+def string_series() -> Series:
+    """
+    Fixture for Series of floats with Index of unique strings
+    """
+    return Series(
+        np.arange(30, dtype=np.float64) * 1.1,
+        index=Index([f"i_{i}" for i in range(30)], dtype=object),
+        name="series",
+    )
+
+
+@pytest.fixture
+def object_series() -> Series:
+    """
+    Fixture for Series of dtype object with Index of unique strings
+    """
+    data = [f"foo_{i}" for i in range(30)]
+    index = Index([f"bar_{i}" for i in range(30)], dtype=object)
+    return Series(data, index=index, name="objects", dtype=object)
+
+
+@pytest.fixture
+def datetime_series() -> Series:
+    """
+    Fixture for Series of floats with DatetimeIndex
+    """
+    return Series(
+        np.random.default_rng(2).standard_normal(30),
+        index=date_range("2000-01-01", periods=30, freq="B"),
+        name="ts",
+    )
+
+
+def _create_series(index):
+    """Helper for the _series dict"""
+    size = len(index)
+    data = np.random.default_rng(2).standard_normal(size)
+    return Series(data, index=index, name="a", copy=False)
+
+
+_series = {
+    f"series-with-{index_id}-index": _create_series(index)
+    for index_id, index in indices_dict.items()
+}
+
+
+@pytest.fixture
+def series_with_simple_index(index) -> Series:
+    """
+    Fixture for tests on series with changing types of indices.
+    """
+    return _create_series(index)
+
+
+_narrow_series = {
+    f"{dtype.__name__}-series": Series(
+        range(30), index=[f"i-{i}" for i in range(30)], name="a", dtype=dtype
+    )
+    for dtype in tm.NARROW_NP_DTYPES
+}
+
+
+_index_or_series_objs = {**indices_dict, **_series, **_narrow_series}
+
+
+@pytest.fixture(params=_index_or_series_objs.keys())
+def index_or_series_obj(request):
+    """
+    Fixture for tests on indexes, series and series with a narrow dtype
+    copy to avoid mutation, e.g. setting .name
+    """
+    return _index_or_series_objs[request.param].copy(deep=True)
+
+
+_typ_objects_series = {
+    f"{dtype.__name__}-series": Series(dtype) for dtype in tm.PYTHON_DATA_TYPES
+}
+
+
+_index_or_series_memory_objs = {
+    **indices_dict,
+    **_series,
+    **_narrow_series,
+    **_typ_objects_series,
+}
+
+
+@pytest.fixture(params=_index_or_series_memory_objs.keys())
+def index_or_series_memory_obj(request):
+    """
+    Fixture for tests on indexes, series, series with a narrow dtype and
+    series with empty objects type
+    copy to avoid mutation, e.g. setting .name
+    """
+    return _index_or_series_memory_objs[request.param].copy(deep=True)
+
+
+# ----------------------------------------------------------------
+# DataFrames
+# ----------------------------------------------------------------
+@pytest.fixture
+def int_frame() -> DataFrame:
+    """
+    Fixture for DataFrame of ints with index of unique strings
+
+    Columns are ['A', 'B', 'C', 'D']
+    """
+    return DataFrame(
+        np.ones((30, 4), dtype=np.int64),
+        index=Index([f"foo_{i}" for i in range(30)], dtype=object),
+        columns=Index(list("ABCD"), dtype=object),
+    )
+
+
+@pytest.fixture
+def float_frame() -> DataFrame:
+    """
+    Fixture for DataFrame of floats with index of unique strings
+
+    Columns are ['A', 'B', 'C', 'D'].
+    """
+    return DataFrame(
+        np.random.default_rng(2).standard_normal((30, 4)),
+        index=Index([f"foo_{i}" for i in range(30)]),
+        columns=Index(list("ABCD")),
+    )
+
+
+@pytest.fixture
+def rand_series_with_duplicate_datetimeindex() -> Series:
+    """
+    Fixture for Series with a DatetimeIndex that has duplicates.
+    """
+    dates = [
+        datetime(2000, 1, 2),
+        datetime(2000, 1, 2),
+        datetime(2000, 1, 2),
+        datetime(2000, 1, 3),
+        datetime(2000, 1, 3),
+        datetime(2000, 1, 3),
+        datetime(2000, 1, 4),
+        datetime(2000, 1, 4),
+        datetime(2000, 1, 4),
+        datetime(2000, 1, 5),
+    ]
+
+    return Series(np.random.default_rng(2).standard_normal(len(dates)), index=dates)
+
+
+# ----------------------------------------------------------------
+# Scalars
+# ----------------------------------------------------------------
+@pytest.fixture(
+    params=[
+        (Interval(left=0, right=5), IntervalDtype("int64", "right")),
+        (Interval(left=0.1, right=0.5), IntervalDtype("float64", "right")),
+        (Period("2012-01", freq="M"), "period[M]"),
+        (Period("2012-02-01", freq="D"), "period[D]"),
+        (
+            Timestamp("2011-01-01", tz="US/Eastern"),
+            DatetimeTZDtype(unit="s", tz="US/Eastern"),
+        ),
+        (Timedelta(seconds=500), "timedelta64[ns]"),
+    ]
+)
+def ea_scalar_and_dtype(request):
+    return request.param
+
+
+# ----------------------------------------------------------------
+# Operators & Operations
+# ----------------------------------------------------------------
+
+
+@pytest.fixture(params=tm.arithmetic_dunder_methods)
+def all_arithmetic_operators(request):
+    """
+    Fixture for dunder names for common arithmetic operations.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        operator.add,
+        ops.radd,
+        operator.sub,
+        ops.rsub,
+        operator.mul,
+        ops.rmul,
+        operator.truediv,
+        ops.rtruediv,
+        operator.floordiv,
+        ops.rfloordiv,
+        operator.mod,
+        ops.rmod,
+        operator.pow,
+        ops.rpow,
+        operator.eq,
+        operator.ne,
+        operator.lt,
+        operator.le,
+        operator.gt,
+        operator.ge,
+        operator.and_,
+        ops.rand_,
+        operator.xor,
+        ops.rxor,
+        operator.or_,
+        ops.ror_,
+    ]
+)
+def all_binary_operators(request):
+    """
+    Fixture for operator and roperator arithmetic, comparison, and logical ops.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        operator.add,
+        ops.radd,
+        operator.sub,
+        ops.rsub,
+        operator.mul,
+        ops.rmul,
+        operator.truediv,
+        ops.rtruediv,
+        operator.floordiv,
+        ops.rfloordiv,
+        operator.mod,
+        ops.rmod,
+        operator.pow,
+        ops.rpow,
+    ]
+)
+def all_arithmetic_functions(request):
+    """
+    Fixture for operator and roperator arithmetic functions.
+
+    Notes
+    -----
+    This includes divmod and rdivmod, whereas all_arithmetic_operators
+    does not.
+    """
+    return request.param
+
+
+_all_numeric_reductions = [
+    "count",
+    "sum",
+    "max",
+    "min",
+    "mean",
+    "prod",
+    "std",
+    "var",
+    "median",
+    "kurt",
+    "skew",
+    "sem",
+]
+
+
+@pytest.fixture(params=_all_numeric_reductions)
+def all_numeric_reductions(request):
+    """
+    Fixture for numeric reduction names.
+    """
+    return request.param
+
+
+_all_boolean_reductions = ["all", "any"]
+
+
+@pytest.fixture(params=_all_boolean_reductions)
+def all_boolean_reductions(request):
+    """
+    Fixture for boolean reduction names.
+    """
+    return request.param
+
+
+_all_reductions = _all_numeric_reductions + _all_boolean_reductions
+
+
+@pytest.fixture(params=_all_reductions)
+def all_reductions(request):
+    """
+    Fixture for all (boolean + numeric) reduction names.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        operator.eq,
+        operator.ne,
+        operator.gt,
+        operator.ge,
+        operator.lt,
+        operator.le,
+    ]
+)
+def comparison_op(request):
+    """
+    Fixture for operator module comparison functions.
+    """
+    return request.param
+
+
+@pytest.fixture(params=["__le__", "__lt__", "__ge__", "__gt__"])
+def compare_operators_no_eq_ne(request):
+    """
+    Fixture for dunder names for compare operations except == and !=
+
+    * >=
+    * >
+    * <
+    * <=
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=["__and__", "__rand__", "__or__", "__ror__", "__xor__", "__rxor__"]
+)
+def all_logical_operators(request):
+    """
+    Fixture for dunder names for common logical operations
+
+    * |
+    * &
+    * ^
+    """
+    return request.param
+
+
+_all_numeric_accumulations = ["cumsum", "cumprod", "cummin", "cummax"]
+
+
+@pytest.fixture(params=_all_numeric_accumulations)
+def all_numeric_accumulations(request):
+    """
+    Fixture for numeric accumulation names
+    """
+    return request.param
+
+
+# ----------------------------------------------------------------
+# Data sets/files
+# ----------------------------------------------------------------
+@pytest.fixture
+def strict_data_files(pytestconfig):
+    """
+    Returns the configuration for the test setting `--no-strict-data-files`.
+    """
+    return pytestconfig.getoption("--no-strict-data-files")
+
+
+@pytest.fixture
+def datapath(strict_data_files: str) -> Callable[..., str]:
+    """
+    Get the path to a data file.
+
+    Parameters
+    ----------
+    path : str
+        Path to the file, relative to ``pandas/tests/``
+
+    Returns
+    -------
+    path including ``pandas/tests``.
+
+    Raises
+    ------
+    ValueError
+        If the path doesn't exist and the --no-strict-data-files option is not set.
+    """
+    BASE_PATH = os.path.join(os.path.dirname(__file__), "tests")
+
+    def deco(*args):
+        path = os.path.join(BASE_PATH, *args)
+        if not os.path.exists(path):
+            if strict_data_files:
+                raise ValueError(
+                    f"Could not find file {path} and --no-strict-data-files is not set."
+                )
+            pytest.skip(f"Could not find {path}.")
+        return path
+
+    return deco
+
+
+# ----------------------------------------------------------------
+# Time zones
+# ----------------------------------------------------------------
+TIMEZONES = [
+    None,
+    "UTC",
+    "US/Eastern",
+    "Asia/Tokyo",
+    "dateutil/US/Pacific",
+    "dateutil/Asia/Singapore",
+    "+01:15",
+    "-02:15",
+    "UTC+01:15",
+    "UTC-02:15",
+    tzutc(),
+    tzlocal(),
+    FixedOffset(300),
+    FixedOffset(0),
+    FixedOffset(-300),
+    timezone.utc,
+    timezone(timedelta(hours=1)),
+    timezone(timedelta(hours=-1), name="foo"),
+]
+if zoneinfo is not None:
+    TIMEZONES.extend(
+        [
+            zoneinfo.ZoneInfo("US/Pacific"),  # type: ignore[list-item]
+            zoneinfo.ZoneInfo("UTC"),  # type: ignore[list-item]
+        ]
+    )
+TIMEZONE_IDS = [repr(i) for i in TIMEZONES]
+
+
+@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
+@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
+def tz_naive_fixture(request):
+    """
+    Fixture for trying timezones including default (None): {0}
+    """
+    return request.param
+
+
+@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
+@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
+def tz_aware_fixture(request):
+    """
+    Fixture for trying explicit timezones: {0}
+    """
+    return request.param
+
+
+# Generate cartesian product of tz_aware_fixture:
+tz_aware_fixture2 = tz_aware_fixture
+
+
+_UTCS = ["utc", "dateutil/UTC", utc, tzutc(), timezone.utc]
+if zoneinfo is not None:
+    _UTCS.append(zoneinfo.ZoneInfo("UTC"))
+
+
+@pytest.fixture(params=_UTCS)
+def utc_fixture(request):
+    """
+    Fixture to provide variants of UTC timezone strings and tzinfo objects.
+    """
+    return request.param
+
+
+utc_fixture2 = utc_fixture
+
+
+@pytest.fixture(params=["s", "ms", "us", "ns"])
+def unit(request):
+    """
+    datetime64 units we support.
+    """
+    return request.param
+
+
+unit2 = unit
+
+
+# ----------------------------------------------------------------
+# Dtypes
+# ----------------------------------------------------------------
+@pytest.fixture(params=tm.STRING_DTYPES)
+def string_dtype(request):
+    """
+    Parametrized fixture for string dtypes.
+
+    * str
+    * 'str'
+    * 'U'
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        "string[python]",
+        pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
+    ]
+)
+def nullable_string_dtype(request):
+    """
+    Parametrized fixture for string dtypes.
+
+    * 'string[python]'
+    * 'string[pyarrow]'
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        "python",
+        pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
+        pytest.param("pyarrow_numpy", marks=td.skip_if_no("pyarrow")),
+    ]
+)
+def string_storage(request):
+    """
+    Parametrized fixture for pd.options.mode.string_storage.
+
+    * 'python'
+    * 'pyarrow'
+    * 'pyarrow_numpy'
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        "numpy_nullable",
+        pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
+    ]
+)
+def dtype_backend(request):
+    """
+    Parametrized fixture for pd.options.mode.string_storage.
+
+    * 'python'
+    * 'pyarrow'
+    """
+    return request.param
+
+
+# Alias so we can test with cartesian product of string_storage
+string_storage2 = string_storage
+
+
+@pytest.fixture(params=tm.BYTES_DTYPES)
+def bytes_dtype(request):
+    """
+    Parametrized fixture for bytes dtypes.
+
+    * bytes
+    * 'bytes'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.OBJECT_DTYPES)
+def object_dtype(request):
+    """
+    Parametrized fixture for object dtypes.
+
+    * object
+    * 'object'
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        "object",
+        "string[python]",
+        pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
+        pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
+    ]
+)
+def any_string_dtype(request):
+    """
+    Parametrized fixture for string dtypes.
+    * 'object'
+    * 'string[python]'
+    * 'string[pyarrow]'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.DATETIME64_DTYPES)
+def datetime64_dtype(request):
+    """
+    Parametrized fixture for datetime64 dtypes.
+
+    * 'datetime64[ns]'
+    * 'M8[ns]'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.TIMEDELTA64_DTYPES)
+def timedelta64_dtype(request):
+    """
+    Parametrized fixture for timedelta64 dtypes.
+
+    * 'timedelta64[ns]'
+    * 'm8[ns]'
+    """
+    return request.param
+
+
+@pytest.fixture
+def fixed_now_ts() -> Timestamp:
+    """
+    Fixture emits fixed Timestamp.now()
+    """
+    return Timestamp(  # pyright: ignore[reportGeneralTypeIssues]
+        year=2021, month=1, day=1, hour=12, minute=4, second=13, microsecond=22
+    )
+
+
+@pytest.fixture(params=tm.FLOAT_NUMPY_DTYPES)
+def float_numpy_dtype(request):
+    """
+    Parameterized fixture for float dtypes.
+
+    * float
+    * 'float32'
+    * 'float64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.FLOAT_EA_DTYPES)
+def float_ea_dtype(request):
+    """
+    Parameterized fixture for float dtypes.
+
+    * 'Float32'
+    * 'Float64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_FLOAT_DTYPES)
+def any_float_dtype(request):
+    """
+    Parameterized fixture for float dtypes.
+
+    * float
+    * 'float32'
+    * 'float64'
+    * 'Float32'
+    * 'Float64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.COMPLEX_DTYPES)
+def complex_dtype(request):
+    """
+    Parameterized fixture for complex dtypes.
+
+    * complex
+    * 'complex64'
+    * 'complex128'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.COMPLEX_FLOAT_DTYPES)
+def complex_or_float_dtype(request):
+    """
+    Parameterized fixture for complex and numpy float dtypes.
+
+    * complex
+    * 'complex64'
+    * 'complex128'
+    * float
+    * 'float32'
+    * 'float64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.SIGNED_INT_NUMPY_DTYPES)
+def any_signed_int_numpy_dtype(request):
+    """
+    Parameterized fixture for signed integer dtypes.
+
+    * int
+    * 'int8'
+    * 'int16'
+    * 'int32'
+    * 'int64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.UNSIGNED_INT_NUMPY_DTYPES)
+def any_unsigned_int_numpy_dtype(request):
+    """
+    Parameterized fixture for unsigned integer dtypes.
+
+    * 'uint8'
+    * 'uint16'
+    * 'uint32'
+    * 'uint64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_INT_NUMPY_DTYPES)
+def any_int_numpy_dtype(request):
+    """
+    Parameterized fixture for any integer dtype.
+
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_INT_EA_DTYPES)
+def any_int_ea_dtype(request):
+    """
+    Parameterized fixture for any nullable integer dtype.
+
+    * 'UInt8'
+    * 'Int8'
+    * 'UInt16'
+    * 'Int16'
+    * 'UInt32'
+    * 'Int32'
+    * 'UInt64'
+    * 'Int64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_INT_DTYPES)
+def any_int_dtype(request):
+    """
+    Parameterized fixture for any nullable integer dtype.
+
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    * 'UInt8'
+    * 'Int8'
+    * 'UInt16'
+    * 'Int16'
+    * 'UInt32'
+    * 'Int32'
+    * 'UInt64'
+    * 'Int64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES)
+def any_numeric_ea_dtype(request):
+    """
+    Parameterized fixture for any nullable integer dtype and
+    any float ea dtypes.
+
+    * 'UInt8'
+    * 'Int8'
+    * 'UInt16'
+    * 'Int16'
+    * 'UInt32'
+    * 'Int32'
+    * 'UInt64'
+    * 'Int64'
+    * 'Float32'
+    * 'Float64'
+    """
+    return request.param
+
+
+#  Unsupported operand types for + ("List[Union[str, ExtensionDtype, dtype[Any],
+#  Type[object]]]" and "List[str]")
+@pytest.fixture(
+    params=tm.ALL_INT_EA_DTYPES
+    + tm.FLOAT_EA_DTYPES
+    + tm.ALL_INT_PYARROW_DTYPES_STR_REPR
+    + tm.FLOAT_PYARROW_DTYPES_STR_REPR  # type: ignore[operator]
+)
+def any_numeric_ea_and_arrow_dtype(request):
+    """
+    Parameterized fixture for any nullable integer dtype and
+    any float ea dtypes.
+
+    * 'UInt8'
+    * 'Int8'
+    * 'UInt16'
+    * 'Int16'
+    * 'UInt32'
+    * 'Int32'
+    * 'UInt64'
+    * 'Int64'
+    * 'Float32'
+    * 'Float64'
+    * 'uint8[pyarrow]'
+    * 'int8[pyarrow]'
+    * 'uint16[pyarrow]'
+    * 'int16[pyarrow]'
+    * 'uint32[pyarrow]'
+    * 'int32[pyarrow]'
+    * 'uint64[pyarrow]'
+    * 'int64[pyarrow]'
+    * 'float32[pyarrow]'
+    * 'float64[pyarrow]'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.SIGNED_INT_EA_DTYPES)
+def any_signed_int_ea_dtype(request):
+    """
+    Parameterized fixture for any signed nullable integer dtype.
+
+    * 'Int8'
+    * 'Int16'
+    * 'Int32'
+    * 'Int64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_REAL_NUMPY_DTYPES)
+def any_real_numpy_dtype(request):
+    """
+    Parameterized fixture for any (purely) real numeric dtype.
+
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    * float
+    * 'float32'
+    * 'float64'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_REAL_DTYPES)
+def any_real_numeric_dtype(request):
+    """
+    Parameterized fixture for any (purely) real numeric dtype.
+
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    * float
+    * 'float32'
+    * 'float64'
+
+    and associated ea dtypes.
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_NUMPY_DTYPES)
+def any_numpy_dtype(request):
+    """
+    Parameterized fixture for all numpy dtypes.
+
+    * bool
+    * 'bool'
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    * float
+    * 'float32'
+    * 'float64'
+    * complex
+    * 'complex64'
+    * 'complex128'
+    * str
+    * 'str'
+    * 'U'
+    * bytes
+    * 'bytes'
+    * 'datetime64[ns]'
+    * 'M8[ns]'
+    * 'timedelta64[ns]'
+    * 'm8[ns]'
+    * object
+    * 'object'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_REAL_NULLABLE_DTYPES)
+def any_real_nullable_dtype(request):
+    """
+    Parameterized fixture for all real dtypes that can hold NA.
+
+    * float
+    * 'float32'
+    * 'float64'
+    * 'Float32'
+    * 'Float64'
+    * 'UInt8'
+    * 'UInt16'
+    * 'UInt32'
+    * 'UInt64'
+    * 'Int8'
+    * 'Int16'
+    * 'Int32'
+    * 'Int64'
+    * 'uint8[pyarrow]'
+    * 'uint16[pyarrow]'
+    * 'uint32[pyarrow]'
+    * 'uint64[pyarrow]'
+    * 'int8[pyarrow]'
+    * 'int16[pyarrow]'
+    * 'int32[pyarrow]'
+    * 'int64[pyarrow]'
+    * 'float[pyarrow]'
+    * 'double[pyarrow]'
+    """
+    return request.param
+
+
+@pytest.fixture(params=tm.ALL_NUMERIC_DTYPES)
+def any_numeric_dtype(request):
+    """
+    Parameterized fixture for all numeric dtypes.
+
+    * int
+    * 'int8'
+    * 'uint8'
+    * 'int16'
+    * 'uint16'
+    * 'int32'
+    * 'uint32'
+    * 'int64'
+    * 'uint64'
+    * float
+    * 'float32'
+    * 'float64'
+    * complex
+    * 'complex64'
+    * 'complex128'
+    * 'UInt8'
+    * 'Int8'
+    * 'UInt16'
+    * 'Int16'
+    * 'UInt32'
+    * 'Int32'
+    * 'UInt64'
+    * 'Int64'
+    * 'Float32'
+    * 'Float64'
+    """
+    return request.param
+
+
+# categoricals are handled separately
+_any_skipna_inferred_dtype = [
+    ("string", ["a", np.nan, "c"]),
+    ("string", ["a", pd.NA, "c"]),
+    ("mixed", ["a", pd.NaT, "c"]),  # pd.NaT not considered valid by is_string_array
+    ("bytes", [b"a", np.nan, b"c"]),
+    ("empty", [np.nan, np.nan, np.nan]),
+    ("empty", []),
+    ("mixed-integer", ["a", np.nan, 2]),
+    ("mixed", ["a", np.nan, 2.0]),
+    ("floating", [1.0, np.nan, 2.0]),
+    ("integer", [1, np.nan, 2]),
+    ("mixed-integer-float", [1, np.nan, 2.0]),
+    ("decimal", [Decimal(1), np.nan, Decimal(2)]),
+    ("boolean", [True, np.nan, False]),
+    ("boolean", [True, pd.NA, False]),
+    ("datetime64", [np.datetime64("2013-01-01"), np.nan, np.datetime64("2018-01-01")]),
+    ("datetime", [Timestamp("20130101"), np.nan, Timestamp("20180101")]),
+    ("date", [date(2013, 1, 1), np.nan, date(2018, 1, 1)]),
+    ("complex", [1 + 1j, np.nan, 2 + 2j]),
+    # The following dtype is commented out due to GH 23554
+    # ('timedelta64', [np.timedelta64(1, 'D'),
+    #                  np.nan, np.timedelta64(2, 'D')]),
+    ("timedelta", [timedelta(1), np.nan, timedelta(2)]),
+    ("time", [time(1), np.nan, time(2)]),
+    ("period", [Period(2013), pd.NaT, Period(2018)]),
+    ("interval", [Interval(0, 1), np.nan, Interval(0, 2)]),
+]
+ids, _ = zip(*_any_skipna_inferred_dtype)  # use inferred type as fixture-id
+
+
+@pytest.fixture(params=_any_skipna_inferred_dtype, ids=ids)
+def any_skipna_inferred_dtype(request):
+    """
+    Fixture for all inferred dtypes from _libs.lib.infer_dtype
+
+    The covered (inferred) types are:
+    * 'string'
+    * 'empty'
+    * 'bytes'
+    * 'mixed'
+    * 'mixed-integer'
+    * 'mixed-integer-float'
+    * 'floating'
+    * 'integer'
+    * 'decimal'
+    * 'boolean'
+    * 'datetime64'
+    * 'datetime'
+    * 'date'
+    * 'timedelta'
+    * 'time'
+    * 'period'
+    * 'interval'
+
+    Returns
+    -------
+    inferred_dtype : str
+        The string for the inferred dtype from _libs.lib.infer_dtype
+    values : np.ndarray
+        An array of object dtype that will be inferred to have
+        `inferred_dtype`
+
+    Examples
+    --------
+    >>> from pandas._libs import lib
+    >>>
+    >>> def test_something(any_skipna_inferred_dtype):
+    ...     inferred_dtype, values = any_skipna_inferred_dtype
+    ...     # will pass
+    ...     assert lib.infer_dtype(values, skipna=True) == inferred_dtype
+    """
+    inferred_dtype, values = request.param
+    values = np.array(values, dtype=object)  # object dtype to avoid casting
+
+    # correctness of inference tested in tests/dtypes/test_inference.py
+    return inferred_dtype, values
+
+
+# ----------------------------------------------------------------
+# Misc
+# ----------------------------------------------------------------
+@pytest.fixture
+def ip():
+    """
+    Get an instance of IPython.InteractiveShell.
+
+    Will raise a skip if IPython is not installed.
+    """
+    pytest.importorskip("IPython", minversion="6.0.0")
+    from IPython.core.interactiveshell import InteractiveShell
+
+    # GH#35711 make sure sqlite history file handle is not leaked
+    from traitlets.config import Config  # isort:skip
+
+    c = Config()
+    c.HistoryManager.hist_file = ":memory:"
+
+    return InteractiveShell(config=c)
+
+
+@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
+def spmatrix(request):
+    """
+    Yields scipy sparse matrix classes.
+    """
+    sparse = pytest.importorskip("scipy.sparse")
+
+    return getattr(sparse, request.param + "_matrix")
+
+
+@pytest.fixture(
+    params=[
+        getattr(pd.offsets, o)
+        for o in pd.offsets.__all__
+        if issubclass(getattr(pd.offsets, o), pd.offsets.Tick) and o != "Tick"
+    ]
+)
+def tick_classes(request):
+    """
+    Fixture for Tick based datetime offsets available for a time series.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[None, lambda x: x])
+def sort_by_key(request):
+    """
+    Simple fixture for testing keys in sorting methods.
+    Tests None (no key) and the identity key.
+    """
+    return request.param
+
+
+@pytest.fixture(
+    params=[
+        ("foo", None, None),
+        ("Egon", "Venkman", None),
+        ("NCC1701D", "NCC1701D", "NCC1701D"),
+        # possibly-matching NAs
+        (np.nan, np.nan, np.nan),
+        (np.nan, pd.NaT, None),
+        (np.nan, pd.NA, None),
+        (pd.NA, pd.NA, pd.NA),
+    ]
+)
+def names(request) -> tuple[Hashable, Hashable, Hashable]:
+    """
+    A 3-tuple of names, the first two for operands, the last for a result.
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.setitem, tm.loc, tm.iloc])
+def indexer_sli(request):
+    """
+    Parametrize over __setitem__, loc.__setitem__, iloc.__setitem__
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.loc, tm.iloc])
+def indexer_li(request):
+    """
+    Parametrize over loc.__getitem__, iloc.__getitem__
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.setitem, tm.iloc])
+def indexer_si(request):
+    """
+    Parametrize over __setitem__, iloc.__setitem__
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.setitem, tm.loc])
+def indexer_sl(request):
+    """
+    Parametrize over __setitem__, loc.__setitem__
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.at, tm.loc])
+def indexer_al(request):
+    """
+    Parametrize over at.__setitem__, loc.__setitem__
+    """
+    return request.param
+
+
+@pytest.fixture(params=[tm.iat, tm.iloc])
+def indexer_ial(request):
+    """
+    Parametrize over iat.__setitem__, iloc.__setitem__
+    """
+    return request.param
+
+
+@pytest.fixture
+def using_array_manager() -> bool:
+    """
+    Fixture to check if the array manager is being used.
+    """
+    return _get_option("mode.data_manager", silent=True) == "array"
+
+
+@pytest.fixture
+def using_copy_on_write() -> bool:
+    """
+    Fixture to check if Copy-on-Write is enabled.
+    """
+    return (
+        pd.options.mode.copy_on_write is True
+        and _get_option("mode.data_manager", silent=True) == "block"
+    )
+
+
+@pytest.fixture
+def warn_copy_on_write() -> bool:
+    """
+    Fixture to check if Copy-on-Write is in warning mode.
+    """
+    return (
+        pd.options.mode.copy_on_write == "warn"
+        and _get_option("mode.data_manager", silent=True) == "block"
+    )
+
+
+@pytest.fixture
+def using_infer_string() -> bool:
+    """
+    Fixture to check if infer string option is enabled.
+    """
+    return pd.options.future.infer_string is True
+
+
+warsaws = ["Europe/Warsaw", "dateutil/Europe/Warsaw"]
+if zoneinfo is not None:
+    warsaws.append(zoneinfo.ZoneInfo("Europe/Warsaw"))  # type: ignore[arg-type]
+
+
+@pytest.fixture(params=warsaws)
+def warsaw(request) -> str:
+    """
+    tzinfo for Europe/Warsaw using pytz, dateutil, or zoneinfo.
+    """
+    return request.param
+
+
+@pytest.fixture()
+def arrow_string_storage():
+    return ("pyarrow", "pyarrow_numpy")
diff --git a/shared/package-files/75/759051b921276646ada1596dd645701bca1c4de45d3bb043d31bce58a1f9e0f6/setuptools.schema.json b/shared/package-files/75/759051b921276646ada1596dd645701bca1c4de45d3bb043d31bce58a1f9e0f6/setuptools.schema.json
new file mode 100644
index 0000000000000000000000000000000000000000..ec887b35736e4ede6265e95e3a9e2520b43cc40f
--- /dev/null
+++ b/shared/package-files/75/759051b921276646ada1596dd645701bca1c4de45d3bb043d31bce58a1f9e0f6/setuptools.schema.json
@@ -0,0 +1,433 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+
+  "$id": "https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html",
+  "title": "``tool.setuptools`` table",
+  "$$description": [
+    "``setuptools``-specific configurations that can be set by users that require",
+    "customization.",
+    "These configurations are completely optional and probably can be skipped when",
+    "creating simple packages. They are equivalent to some of the `Keywords",
+    "`_",
+    "used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.",
+    "It considers only ``setuptools`` `parameters",
+    "`_",
+    "that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``",
+    "and ``setup_requires`` (incompatible with modern workflows/standards)."
+  ],
+
+  "type": "object",
+  "additionalProperties": false,
+  "properties": {
+    "platforms": {
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "provides": {
+      "$$description": [
+        "Package and virtual package names contained within this package",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "obsoletes": {
+      "$$description": [
+        "Packages which this package renders obsolete",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "zip-safe": {
+      "$$description": [
+        "Whether the project can be safely installed and run from a zip file.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "boolean"
+    },
+    "script-files": {
+      "$$description": [
+        "Legacy way of defining scripts (entry-points are preferred).",
+        "Equivalent to the ``script`` keyword in ``setup.py``",
+        "(it was renamed to avoid confusion with entry-point based ``project.scripts``",
+        "defined in :pep:`621`).",
+        "**DISCOURAGED**: generic script wrappers are tricky and may not work properly.",
+        "Whenever possible, please use ``project.scripts`` instead."
+      ],
+      "type": "array",
+      "items": {"type": "string"},
+      "$comment": "TODO: is this field deprecated/should be removed?"
+    },
+    "eager-resources": {
+      "$$description": [
+        "Resources that should be extracted together, if any of them is needed,",
+        "or if any C extensions included in the project are imported.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "packages": {
+      "$$description": [
+        "Packages that should be included in the distribution.",
+        "It can be given either as a list of package identifiers",
+        "or as a ``dict``-like structure with a single key ``find``",
+        "which corresponds to a dynamic call to",
+        "``setuptools.config.expand.find_packages`` function.",
+        "The ``find`` key is associated with a nested ``dict``-like structure that can",
+        "contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,",
+        "mimicking the keyword arguments of the associated function."
+      ],
+      "oneOf": [
+        {
+          "title": "Array of Python package identifiers",
+          "type": "array",
+          "items": {"$ref": "#/definitions/package-name"}
+        },
+        {"$ref": "#/definitions/find-directive"}
+      ]
+    },
+    "package-dir": {
+      "$$description": [
+        ":class:`dict`-like structure mapping from package names to directories where their",
+        "code can be found.",
+        "The empty string (as key) means that all packages are contained inside",
+        "the given directory will be included in the distribution."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"const": ""}, {"$ref": "#/definitions/package-name"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "string" }
+      }
+    },
+    "package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns.",
+        "Usually this option is not needed when using ``include-package-data = true``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "include-package-data": {
+      "$$description": [
+        "Automatically include any data files inside the package directories",
+        "that are specified by ``MANIFEST.in``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "boolean"
+    },
+    "exclude-package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns that should be excluded",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "namespace-packages": {
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "https://setuptools.pypa.io/en/latest/userguide/package_discovery.html",
+      "description": "**DEPRECATED**: use implicit namespaces instead (:pep:`420`)."
+    },
+    "py-modules": {
+      "description": "Modules that setuptools will manipulate",
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "TODO: clarify the relationship with ``packages``"
+    },
+    "ext-modules": {
+      "description": "Extension modules to be compiled by setuptools",
+      "type": "array",
+      "items": {"$ref": "#/definitions/ext-module"}
+    },
+    "data-files": {
+      "$$description": [
+        "``dict``-like structure where each key represents a directory and",
+        "the value is a list of glob patterns that should be installed in them.",
+        "**DISCOURAGED**: please notice this might not work as expected with wheels.",
+        "Whenever possible, consider using data files inside the package directories",
+        "(or create a new namespace package that only contains data files).",
+        "See `data files support",
+        "`_."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "cmdclass": {
+      "$$description": [
+        "Mapping of distutils-style command names to ``setuptools.Command`` subclasses",
+        "which in turn should be represented by strings with a qualified class name",
+        "(i.e., \"dotted\" form with module), e.g.::\n\n",
+        "    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\n\n",
+        "The command class should be a directly defined at the top-level of the",
+        "containing module (no class nesting)."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "string", "format": "python-qualified-identifier"}
+      }
+    },
+    "license-files": {
+      "type": "array",
+      "items": {"type": "string"},
+      "$$description": [
+        "**PROVISIONAL**: list of glob patterns for all license files being distributed.",
+        "(likely to become standard with :pep:`639`).",
+        "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"
+      ],
+      "$comment": "TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?"
+    },
+    "dynamic": {
+      "type": "object",
+      "description": "Instructions for loading :pep:`621`-related metadata dynamically",
+      "additionalProperties": false,
+      "properties": {
+        "version": {
+          "$$description": [
+            "A version dynamically loaded via either the ``attr:`` or ``file:``",
+            "directives. Please make sure the given file or attribute respects :pep:`440`.",
+            "Also ensure to set ``project.dynamic`` accordingly."
+          ],
+          "oneOf": [
+            {"$ref": "#/definitions/attr-directive"},
+            {"$ref": "#/definitions/file-directive"}
+          ]
+        },
+        "classifiers": {"$ref": "#/definitions/file-directive"},
+        "description": {"$ref": "#/definitions/file-directive"},
+        "entry-points": {"$ref": "#/definitions/file-directive"},
+        "dependencies": {"$ref": "#/definitions/file-directive-for-dependencies"},
+        "optional-dependencies": {
+          "type": "object",
+          "propertyNames": {"type": "string", "format": "pep508-identifier"},
+          "additionalProperties": false,
+          "patternProperties": {
+            ".+": {"$ref": "#/definitions/file-directive-for-dependencies"}
+          }
+        },
+        "readme": {
+          "type": "object",
+          "anyOf": [
+            {"$ref": "#/definitions/file-directive"},
+            {
+              "type": "object",
+              "properties": {
+                "content-type": {"type": "string"},
+                "file": { "$ref": "#/definitions/file-directive/properties/file" }
+              },
+              "additionalProperties": false}
+          ],
+          "required": ["file"]
+        }
+      }
+    }
+  },
+
+  "definitions": {
+    "package-name": {
+      "$id": "#/definitions/package-name",
+      "title": "Valid package name",
+      "description": "Valid package name (importable or :pep:`561`).",
+      "type": "string",
+      "anyOf": [
+        {"type": "string", "format": "python-module-name-relaxed"},
+        {"type": "string", "format": "pep561-stub-name"}
+      ]
+    },
+    "ext-module": {
+      "$id": "#/definitions/ext-module",
+      "title": "Extension module",
+      "description": "Parameters to construct a :class:`setuptools.Extension` object",
+      "type": "object",
+      "required": ["name", "sources"],
+      "additionalProperties": false,
+      "properties": {
+        "name": {
+          "type": "string",
+          "format": "python-module-name-relaxed"
+        },
+        "sources": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "include-dirs":{
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "define-macros": {
+          "type": "array",
+          "items": {
+            "type": "array",
+            "items": [
+              {"description": "macro name", "type": "string"},
+              {"description": "macro value", "oneOf": [{"type": "string"}, {"type": "null"}]}
+            ],
+            "additionalItems": false
+          }
+        },
+        "undef-macros": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "libraries": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "runtime-library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-objects": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-compile-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-link-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "export-symbols": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "swig-opts": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "depends": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "language": {"type": "string"},
+        "optional": {"type": "boolean"},
+        "py-limited-api": {"type": "boolean"}
+      }
+    },
+    "file-directive": {
+      "$id": "#/definitions/file-directive",
+      "title": "'file:' directive",
+      "description":
+        "Value is read from a file (or list of files and then concatenated)",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "file": {
+          "oneOf": [
+            {"type": "string"},
+            {"type": "array", "items": {"type": "string"}}
+          ]
+        }
+      },
+      "required": ["file"]
+    },
+    "file-directive-for-dependencies": {
+      "title": "'file:' directive for dependencies",
+      "allOf": [
+        {
+          "$$description": [
+            "**BETA**: subset of the ``requirements.txt`` format",
+            "without ``pip`` flags and options",
+            "(one :pep:`508`-compliant string per line,",
+            "lines that are blank or start with ``#`` are excluded).",
+            "See `dynamic metadata",
+            "`_."
+          ]
+        },
+        {"$ref": "#/definitions/file-directive"}
+      ]
+    },
+    "attr-directive": {
+      "title": "'attr:' directive",
+      "$id": "#/definitions/attr-directive",
+      "$$description": [
+        "Value is read from a module attribute. Supports callables and iterables;",
+        "unsupported types are cast via ``str()``"
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "attr": {"type": "string", "format": "python-qualified-identifier"}
+      },
+      "required": ["attr"]
+    },
+    "find-directive": {
+      "$id": "#/definitions/find-directive",
+      "title": "'find:' directive",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "find": {
+          "type": "object",
+          "$$description": [
+            "Dynamic `package discovery",
+            "`_."
+          ],
+          "additionalProperties": false,
+          "properties": {
+            "where": {
+              "description":
+                "Directories to be searched for packages (Unix-style relative path)",
+              "type": "array",
+              "items": {"type": "string"}
+            },
+            "exclude": {
+              "type": "array",
+              "$$description": [
+                "Exclude packages that match the values listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "include": {
+              "type": "array",
+              "$$description": [
+                "Restrict the found packages to just the ones listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "namespaces": {
+              "type": "boolean",
+              "$$description": [
+                "When ``True``, directories without a ``__init__.py`` file will also",
+                "be scanned for :pep:`420`-style implicit namespaces"
+              ]
+            }
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/shared/package-files/75/75a08d4a4a0c7b03558fbbc110070613cc63756b11d2eb7c4b1bab3405884408/missing.cpython-311.pyc b/shared/package-files/75/75a08d4a4a0c7b03558fbbc110070613cc63756b11d2eb7c4b1bab3405884408/missing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a2f8023bfdf9ca0e8401aad85a56740ef388e1a
Binary files /dev/null and b/shared/package-files/75/75a08d4a4a0c7b03558fbbc110070613cc63756b11d2eb7c4b1bab3405884408/missing.cpython-311.pyc differ
diff --git a/shared/package-files/75/75a7e514a1a96dd900615724faa8509cfcb3daa4cbdca2dd10f92e66f45b9318/_weight_norm.h b/shared/package-files/75/75a7e514a1a96dd900615724faa8509cfcb3daa4cbdca2dd10f92e66f45b9318/_weight_norm.h
new file mode 100644
index 0000000000000000000000000000000000000000..824e2f99e4f7242551e189ce5f1fdc18f5f576ee
--- /dev/null
+++ b/shared/package-files/75/75a7e514a1a96dd900615724faa8509cfcb3daa4cbdca2dd10f92e66f45b9318/_weight_norm.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_weight_norm(Tensor v, Tensor g, int dim=0) -> Tensor
+inline at::Tensor _weight_norm(const at::Tensor & v, const at::Tensor & g, int64_t dim=0) {
+    return at::_ops::_weight_norm::call(v, g, dim);
+}
+
+}
diff --git a/shared/package-files/75/75bfdce08acae848dcc79fb0c8d8ce588b306a6afb633931552bfd8fb17fa5ef/_trilinear.h b/shared/package-files/75/75bfdce08acae848dcc79fb0c8d8ce588b306a6afb633931552bfd8fb17fa5ef/_trilinear.h
new file mode 100644
index 0000000000000000000000000000000000000000..abcd6b056060e2ba991d49fb6d7e66cfaf7aad93
--- /dev/null
+++ b/shared/package-files/75/75bfdce08acae848dcc79fb0c8d8ce588b306a6afb633931552bfd8fb17fa5ef/_trilinear.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor
+inline at::Tensor _trilinear(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim=1) {
+    return at::_ops::_trilinear::call(i1, i2, i3, expand1, expand2, expand3, sumdim, unroll_dim);
+}
+
+// aten::_trilinear.out(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & _trilinear_out(at::Tensor & out, const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim=1) {
+    return at::_ops::_trilinear_out::call(i1, i2, i3, expand1, expand2, expand3, sumdim, unroll_dim, out);
+}
+// aten::_trilinear.out(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & _trilinear_outf(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim, at::Tensor & out) {
+    return at::_ops::_trilinear_out::call(i1, i2, i3, expand1, expand2, expand3, sumdim, unroll_dim, out);
+}
+
+}
diff --git a/shared/package-files/75/75d36a15feced3536456afdbeaba37705c52b8876b247b543cab3d15e09c6c52/ufuncs.cpython-311.pyc b/shared/package-files/75/75d36a15feced3536456afdbeaba37705c52b8876b247b543cab3d15e09c6c52/ufuncs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f7a2b05b7581a1a88209aff51266f87896f92c4
Binary files /dev/null and b/shared/package-files/75/75d36a15feced3536456afdbeaba37705c52b8876b247b543cab3d15e09c6c52/ufuncs.cpython-311.pyc differ
diff --git a/shared/package-files/75/75dc7ecaa9d570e7f1d5d29535417af79852dd0fb30a6166086ccaeb807b6121/test_correlation.py b/shared/package-files/75/75dc7ecaa9d570e7f1d5d29535417af79852dd0fb30a6166086ccaeb807b6121/test_correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..147c837459ae47c4133718615b492d1dee2f0674
--- /dev/null
+++ b/shared/package-files/75/75dc7ecaa9d570e7f1d5d29535417af79852dd0fb30a6166086ccaeb807b6121/test_correlation.py
@@ -0,0 +1,122 @@
+import pytest
+
+import networkx as nx
+from networkx.algorithms.assortativity.correlation import attribute_ac
+
+from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
+
+np = pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+
+
+class TestDegreeMixingCorrelation(BaseTestDegreeMixing):
+    def test_degree_assortativity_undirected(self):
+        r = nx.degree_assortativity_coefficient(self.P4)
+        np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
+
+    def test_degree_assortativity_node_kwargs(self):
+        G = nx.Graph()
+        edges = [(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (5, 9), (9, 0)]
+        G.add_edges_from(edges)
+        r = nx.degree_assortativity_coefficient(G, nodes=[1, 2, 4])
+        np.testing.assert_almost_equal(r, -1.0, decimal=4)
+
+    def test_degree_assortativity_directed(self):
+        r = nx.degree_assortativity_coefficient(self.D)
+        np.testing.assert_almost_equal(r, -0.57735, decimal=4)
+
+    def test_degree_assortativity_directed2(self):
+        """Test degree assortativity for a directed graph where the set of
+        in/out degree does not equal the total degree."""
+        r = nx.degree_assortativity_coefficient(self.D2)
+        np.testing.assert_almost_equal(r, 0.14852, decimal=4)
+
+    def test_degree_assortativity_multigraph(self):
+        r = nx.degree_assortativity_coefficient(self.M)
+        np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
+
+    def test_degree_pearson_assortativity_undirected(self):
+        r = nx.degree_pearson_correlation_coefficient(self.P4)
+        np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
+
+    def test_degree_pearson_assortativity_directed(self):
+        r = nx.degree_pearson_correlation_coefficient(self.D)
+        np.testing.assert_almost_equal(r, -0.57735, decimal=4)
+
+    def test_degree_pearson_assortativity_directed2(self):
+        """Test degree assortativity with Pearson for a directed graph where
+        the set of in/out degree does not equal the total degree."""
+        r = nx.degree_pearson_correlation_coefficient(self.D2)
+        np.testing.assert_almost_equal(r, 0.14852, decimal=4)
+
+    def test_degree_pearson_assortativity_multigraph(self):
+        r = nx.degree_pearson_correlation_coefficient(self.M)
+        np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
+
+    def test_degree_assortativity_weighted(self):
+        r = nx.degree_assortativity_coefficient(self.W, weight="weight")
+        np.testing.assert_almost_equal(r, -0.1429, decimal=4)
+
+    def test_degree_assortativity_double_star(self):
+        r = nx.degree_assortativity_coefficient(self.DS)
+        np.testing.assert_almost_equal(r, -0.9339, decimal=4)
+
+
+class TestAttributeMixingCorrelation(BaseTestAttributeMixing):
+    def test_attribute_assortativity_undirected(self):
+        r = nx.attribute_assortativity_coefficient(self.G, "fish")
+        assert r == 6.0 / 22.0
+
+    def test_attribute_assortativity_directed(self):
+        r = nx.attribute_assortativity_coefficient(self.D, "fish")
+        assert r == 1.0 / 3.0
+
+    def test_attribute_assortativity_multigraph(self):
+        r = nx.attribute_assortativity_coefficient(self.M, "fish")
+        assert r == 1.0
+
+    def test_attribute_assortativity_coefficient(self):
+        # from "Mixing patterns in networks"
+        # fmt: off
+        a = np.array([[0.258, 0.016, 0.035, 0.013],
+                      [0.012, 0.157, 0.058, 0.019],
+                      [0.013, 0.023, 0.306, 0.035],
+                      [0.005, 0.007, 0.024, 0.016]])
+        # fmt: on
+        r = attribute_ac(a)
+        np.testing.assert_almost_equal(r, 0.623, decimal=3)
+
+    def test_attribute_assortativity_coefficient2(self):
+        # fmt: off
+        a = np.array([[0.18, 0.02, 0.01, 0.03],
+                      [0.02, 0.20, 0.03, 0.02],
+                      [0.01, 0.03, 0.16, 0.01],
+                      [0.03, 0.02, 0.01, 0.22]])
+        # fmt: on
+        r = attribute_ac(a)
+        np.testing.assert_almost_equal(r, 0.68, decimal=2)
+
+    def test_attribute_assortativity(self):
+        a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]])
+        r = attribute_ac(a)
+        np.testing.assert_almost_equal(r, 0.029, decimal=3)
+
+    def test_attribute_assortativity_negative(self):
+        r = nx.numeric_assortativity_coefficient(self.N, "margin")
+        np.testing.assert_almost_equal(r, -0.2903, decimal=4)
+
+    def test_assortativity_node_kwargs(self):
+        G = nx.Graph()
+        G.add_nodes_from([0, 1], size=2)
+        G.add_nodes_from([2, 3], size=3)
+        G.add_edges_from([(0, 1), (2, 3)])
+        r = nx.numeric_assortativity_coefficient(G, "size", nodes=[0, 3])
+        np.testing.assert_almost_equal(r, 1.0, decimal=4)
+
+    def test_attribute_assortativity_float(self):
+        r = nx.numeric_assortativity_coefficient(self.F, "margin")
+        np.testing.assert_almost_equal(r, -0.1429, decimal=4)
+
+    def test_attribute_assortativity_mixed(self):
+        r = nx.numeric_assortativity_coefficient(self.K, "margin")
+        np.testing.assert_almost_equal(r, 0.4340, decimal=4)
diff --git a/shared/package-files/75/75e129a01a53d8abdbadc520a674a6ca5cdda5d018e6e84fb4f44ace127251c1/test_index_col.py b/shared/package-files/75/75e129a01a53d8abdbadc520a674a6ca5cdda5d018e6e84fb4f44ace127251c1/test_index_col.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba15d061b2deba294cd054d58eac93e4647e8a62
--- /dev/null
+++ b/shared/package-files/75/75e129a01a53d8abdbadc520a674a6ca5cdda5d018e6e84fb4f44ace127251c1/test_index_col.py
@@ -0,0 +1,376 @@
+"""
+Tests that the specified index column (a.k.a "index_col")
+is properly handled or inferred during parsing for all of
+the parsers defined in parsers.py
+"""
+from io import StringIO
+
+import numpy as np
+import pytest
+
+from pandas import (
+    DataFrame,
+    Index,
+    MultiIndex,
+)
+import pandas._testing as tm
+
+pytestmark = pytest.mark.filterwarnings(
+    "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
+)
+
+xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
+skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
+
+
+@pytest.mark.parametrize("with_header", [True, False])
+def test_index_col_named(all_parsers, with_header):
+    parser = all_parsers
+    no_header = """\
+KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
+KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
+KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
+KORD4,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
+KORD5,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
+KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""
+    header = "ID,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir\n"
+
+    if with_header:
+        data = header + no_header
+
+        result = parser.read_csv(StringIO(data), index_col="ID")
+        expected = parser.read_csv(StringIO(data), header=0).set_index("ID")
+        tm.assert_frame_equal(result, expected)
+    else:
+        data = no_header
+        msg = "Index ID invalid"
+
+        with pytest.raises(ValueError, match=msg):
+            parser.read_csv(StringIO(data), index_col="ID")
+
+
+def test_index_col_named2(all_parsers):
+    parser = all_parsers
+    data = """\
+1,2,3,4,hello
+5,6,7,8,world
+9,10,11,12,foo
+"""
+
+    expected = DataFrame(
+        {"a": [1, 5, 9], "b": [2, 6, 10], "c": [3, 7, 11], "d": [4, 8, 12]},
+        index=Index(["hello", "world", "foo"], name="message"),
+    )
+    names = ["a", "b", "c", "d", "message"]
+
+    result = parser.read_csv(StringIO(data), names=names, index_col=["message"])
+    tm.assert_frame_equal(result, expected)
+
+
+def test_index_col_is_true(all_parsers):
+    # see gh-9798
+    data = "a,b\n1,2"
+    parser = all_parsers
+
+    msg = "The value of index_col couldn't be 'True'"
+    with pytest.raises(ValueError, match=msg):
+        parser.read_csv(StringIO(data), index_col=True)
+
+
+@skip_pyarrow  # CSV parse error: Expected 3 columns, got 4
+def test_infer_index_col(all_parsers):
+    data = """A,B,C
+foo,1,2,3
+bar,4,5,6
+baz,7,8,9
+"""
+    parser = all_parsers
+    result = parser.read_csv(StringIO(data))
+
+    expected = DataFrame(
+        [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+        index=["foo", "bar", "baz"],
+        columns=["A", "B", "C"],
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@skip_pyarrow  # CSV parse error: Empty CSV file or block
+@pytest.mark.parametrize(
+    "index_col,kwargs",
+    [
+        (None, {"columns": ["x", "y", "z"]}),
+        (False, {"columns": ["x", "y", "z"]}),
+        (0, {"columns": ["y", "z"], "index": Index([], name="x")}),
+        (1, {"columns": ["x", "z"], "index": Index([], name="y")}),
+        ("x", {"columns": ["y", "z"], "index": Index([], name="x")}),
+        ("y", {"columns": ["x", "z"], "index": Index([], name="y")}),
+        (
+            [0, 1],
+            {
+                "columns": ["z"],
+                "index": MultiIndex.from_arrays([[]] * 2, names=["x", "y"]),
+            },
+        ),
+        (
+            ["x", "y"],
+            {
+                "columns": ["z"],
+                "index": MultiIndex.from_arrays([[]] * 2, names=["x", "y"]),
+            },
+        ),
+        (
+            [1, 0],
+            {
+                "columns": ["z"],
+                "index": MultiIndex.from_arrays([[]] * 2, names=["y", "x"]),
+            },
+        ),
+        (
+            ["y", "x"],
+            {
+                "columns": ["z"],
+                "index": MultiIndex.from_arrays([[]] * 2, names=["y", "x"]),
+            },
+        ),
+    ],
+)
+def test_index_col_empty_data(all_parsers, index_col, kwargs):
+    data = "x,y,z"
+    parser = all_parsers
+    result = parser.read_csv(StringIO(data), index_col=index_col)
+
+    expected = DataFrame(**kwargs)
+    tm.assert_frame_equal(result, expected)
+
+
+@skip_pyarrow  # CSV parse error: Empty CSV file or block
+def test_empty_with_index_col_false(all_parsers):
+    # see gh-10413
+    data = "x,y"
+    parser = all_parsers
+    result = parser.read_csv(StringIO(data), index_col=False)
+
+    expected = DataFrame(columns=["x", "y"])
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+    "index_names",
+    [
+        ["", ""],
+        ["foo", ""],
+        ["", "bar"],
+        ["foo", "bar"],
+        ["NotReallyUnnamed", "Unnamed: 0"],
+    ],
+)
+def test_multi_index_naming(all_parsers, index_names, request):
+    parser = all_parsers
+
+    if parser.engine == "pyarrow" and "" in index_names:
+        mark = pytest.mark.xfail(reason="One case raises, others are wrong")
+        request.applymarker(mark)
+
+    # We don't want empty index names being replaced with "Unnamed: 0"
+    data = ",".join(index_names + ["col\na,c,1\na,d,2\nb,c,3\nb,d,4"])
+    result = parser.read_csv(StringIO(data), index_col=[0, 1])
+
+    expected = DataFrame(
+        {"col": [1, 2, 3, 4]}, index=MultiIndex.from_product([["a", "b"], ["c", "d"]])
+    )
+    expected.index.names = [name if name else None for name in index_names]
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # ValueError: Found non-unique column index
+def test_multi_index_naming_not_all_at_beginning(all_parsers):
+    parser = all_parsers
+    data = ",Unnamed: 2,\na,c,1\na,d,2\nb,c,3\nb,d,4"
+    result = parser.read_csv(StringIO(data), index_col=[0, 2])
+
+    expected = DataFrame(
+        {"Unnamed: 2": ["c", "d", "c", "d"]},
+        index=MultiIndex(
+            levels=[["a", "b"], [1, 2, 3, 4]], codes=[[0, 0, 1, 1], [0, 1, 2, 3]]
+        ),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # ValueError: Found non-unique column index
+def test_no_multi_index_level_names_empty(all_parsers):
+    # GH 10984
+    parser = all_parsers
+    midx = MultiIndex.from_tuples([("A", 1, 2), ("A", 1, 2), ("B", 1, 2)])
+    expected = DataFrame(
+        np.random.default_rng(2).standard_normal((3, 3)),
+        index=midx,
+        columns=["x", "y", "z"],
+    )
+    with tm.ensure_clean() as path:
+        expected.to_csv(path)
+        result = parser.read_csv(path, index_col=[0, 1, 2])
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_header_with_index_col(all_parsers):
+    # GH 33476
+    parser = all_parsers
+    data = """
+I11,A,A
+I12,B,B
+I2,1,3
+"""
+    midx = MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"])
+    idx = Index(["I2"])
+    expected = DataFrame([[1, 3]], index=idx, columns=midx)
+
+    result = parser.read_csv(StringIO(data), index_col=0, header=[0, 1])
+    tm.assert_frame_equal(result, expected)
+
+    col_idx = Index(["A", "A.1"])
+    idx = Index(["I12", "I2"], name="I11")
+    expected = DataFrame([["B", "B"], ["1", "3"]], index=idx, columns=col_idx)
+
+    result = parser.read_csv(StringIO(data), index_col="I11", header=0)
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.slow
+def test_index_col_large_csv(all_parsers, monkeypatch):
+    # https://github.com/pandas-dev/pandas/issues/37094
+    parser = all_parsers
+
+    ARR_LEN = 100
+    df = DataFrame(
+        {
+            "a": range(ARR_LEN + 1),
+            "b": np.random.default_rng(2).standard_normal(ARR_LEN + 1),
+        }
+    )
+
+    with tm.ensure_clean() as path:
+        df.to_csv(path, index=False)
+        with monkeypatch.context() as m:
+            m.setattr("pandas.core.algorithms._MINIMUM_COMP_ARR_LEN", ARR_LEN)
+            result = parser.read_csv(path, index_col=[0])
+
+    tm.assert_frame_equal(result, df.set_index("a"))
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_index_col_multiindex_columns_no_data(all_parsers):
+    # GH#38292
+    parser = all_parsers
+    result = parser.read_csv(
+        StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1], index_col=0
+    )
+    expected = DataFrame(
+        [],
+        index=Index([]),
+        columns=MultiIndex.from_arrays(
+            [["a1", "a2"], ["b1", "b2"]], names=["a0", "b0"]
+        ),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_index_col_header_no_data(all_parsers):
+    # GH#38292
+    parser = all_parsers
+    result = parser.read_csv(StringIO("a0,a1,a2\n"), header=[0], index_col=0)
+    expected = DataFrame(
+        [],
+        columns=["a1", "a2"],
+        index=Index([], name="a0"),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_multiindex_columns_no_data(all_parsers):
+    # GH#38292
+    parser = all_parsers
+    result = parser.read_csv(StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1])
+    expected = DataFrame(
+        [], columns=MultiIndex.from_arrays([["a0", "a1", "a2"], ["b0", "b1", "b2"]])
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_multiindex_columns_index_col_with_data(all_parsers):
+    # GH#38292
+    parser = all_parsers
+    result = parser.read_csv(
+        StringIO("a0,a1,a2\nb0,b1,b2\ndata,data,data"), header=[0, 1], index_col=0
+    )
+    expected = DataFrame(
+        [["data", "data"]],
+        columns=MultiIndex.from_arrays(
+            [["a1", "a2"], ["b1", "b2"]], names=["a0", "b0"]
+        ),
+        index=Index(["data"]),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@skip_pyarrow  # CSV parse error: Empty CSV file or block
+def test_infer_types_boolean_sum(all_parsers):
+    # GH#44079
+    parser = all_parsers
+    result = parser.read_csv(
+        StringIO("0,1"),
+        names=["a", "b"],
+        index_col=["a"],
+        dtype={"a": "UInt8"},
+    )
+    expected = DataFrame(
+        data={
+            "a": [
+                0,
+            ],
+            "b": [1],
+        }
+    ).set_index("a")
+    # Not checking index type now, because the C parser will return a
+    # index column of dtype 'object', and the Python parser will return a
+    # index column of dtype 'int64'.
+    tm.assert_frame_equal(result, expected, check_index_type=False)
+
+
+@pytest.mark.parametrize("dtype, val", [(object, "01"), ("int64", 1)])
+def test_specify_dtype_for_index_col(all_parsers, dtype, val, request):
+    # GH#9435
+    data = "a,b\n01,2"
+    parser = all_parsers
+    if dtype == object and parser.engine == "pyarrow":
+        request.applymarker(
+            pytest.mark.xfail(reason="Cannot disable type-inference for pyarrow engine")
+        )
+    result = parser.read_csv(StringIO(data), index_col="a", dtype={"a": dtype})
+    expected = DataFrame({"b": [2]}, index=Index([val], name="a"))
+    tm.assert_frame_equal(result, expected)
+
+
+@xfail_pyarrow  # TypeError: an integer is required
+def test_multiindex_columns_not_leading_index_col(all_parsers):
+    # GH#38549
+    parser = all_parsers
+    data = """a,b,c,d
+e,f,g,h
+x,y,1,2
+"""
+    result = parser.read_csv(
+        StringIO(data),
+        header=[0, 1],
+        index_col=1,
+    )
+    cols = MultiIndex.from_tuples(
+        [("a", "e"), ("c", "g"), ("d", "h")], names=["b", "f"]
+    )
+    expected = DataFrame([["x", 1, 2]], columns=cols, index=["y"])
+    tm.assert_frame_equal(result, expected)
diff --git a/shared/package-files/75/75e2bd48c09512bc1f4140c5fdb73d0d31f77e1c51071b82c42e0e1dcdc6eaad/test_quantile.py b/shared/package-files/75/75e2bd48c09512bc1f4140c5fdb73d0d31f77e1c51071b82c42e0e1dcdc6eaad/test_quantile.py
new file mode 100644
index 0000000000000000000000000000000000000000..361a8c27fbf9d6744a11d56cf228f06a53d4adaf
--- /dev/null
+++ b/shared/package-files/75/75e2bd48c09512bc1f4140c5fdb73d0d31f77e1c51071b82c42e0e1dcdc6eaad/test_quantile.py
@@ -0,0 +1,496 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+    DataFrame,
+    Index,
+)
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+    "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
+)
+@pytest.mark.parametrize(
+    "a_vals,b_vals",
+    [
+        # Ints
+        ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]),
+        ([1, 2, 3, 4], [4, 3, 2, 1]),
+        ([1, 2, 3, 4, 5], [4, 3, 2, 1]),
+        # Floats
+        ([1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]),
+        # Missing data
+        ([1.0, np.nan, 3.0, np.nan, 5.0], [5.0, np.nan, 3.0, np.nan, 1.0]),
+        ([np.nan, 4.0, np.nan, 2.0, np.nan], [np.nan, 4.0, np.nan, 2.0, np.nan]),
+        # Timestamps
+        (
+            pd.date_range("1/1/18", freq="D", periods=5),
+            pd.date_range("1/1/18", freq="D", periods=5)[::-1],
+        ),
+        (
+            pd.date_range("1/1/18", freq="D", periods=5).as_unit("s"),
+            pd.date_range("1/1/18", freq="D", periods=5)[::-1].as_unit("s"),
+        ),
+        # All NA
+        ([np.nan] * 5, [np.nan] * 5),
+    ],
+)
+@pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1])
+def test_quantile(interpolation, a_vals, b_vals, q, request):
+    if (
+        interpolation == "nearest"
+        and q == 0.5
+        and isinstance(b_vals, list)
+        and b_vals == [4, 3, 2, 1]
+    ):
+        request.applymarker(
+            pytest.mark.xfail(
+                reason="Unclear numpy expectation for nearest "
+                "result with equidistant data"
+            )
+        )
+    all_vals = pd.concat([pd.Series(a_vals), pd.Series(b_vals)])
+
+    a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation)
+    b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation)
+
+    df = DataFrame({"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": all_vals})
+
+    expected = DataFrame(
+        [a_expected, b_expected], columns=["val"], index=Index(["a", "b"], name="key")
+    )
+    if all_vals.dtype.kind == "M" and expected.dtypes.values[0].kind == "M":
+        # TODO(non-nano): this should be unnecessary once array_to_datetime
+        #  correctly infers non-nano from Timestamp.unit
+        expected = expected.astype(all_vals.dtype)
+    result = df.groupby("key").quantile(q, interpolation=interpolation)
+
+    tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array():
+    # https://github.com/pandas-dev/pandas/issues/27526
+    df = DataFrame({"A": [0, 1, 2, 3, 4]})
+    key = np.array([0, 0, 1, 1, 1], dtype=np.int64)
+    result = df.groupby(key).quantile([0.25])
+
+    index = pd.MultiIndex.from_product([[0, 1], [0.25]])
+    expected = DataFrame({"A": [0.25, 2.50]}, index=index)
+    tm.assert_frame_equal(result, expected)
+
+    df = DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]})
+    index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]])
+
+    key = np.array([0, 0, 1, 1], dtype=np.int64)
+    result = df.groupby(key).quantile([0.25, 0.75])
+    expected = DataFrame(
+        {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array2():
+    # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959
+    arr = np.random.default_rng(2).integers(0, 5, size=(10, 3), dtype=np.int64)
+    df = DataFrame(arr, columns=list("ABC"))
+    result = df.groupby("A").quantile([0.3, 0.7])
+    expected = DataFrame(
+        {
+            "B": [2.0, 2.0, 2.3, 2.7, 0.3, 0.7, 3.2, 4.0, 0.3, 0.7],
+            "C": [1.0, 1.0, 1.9, 3.0999999999999996, 0.3, 0.7, 2.6, 3.0, 1.2, 2.8],
+        },
+        index=pd.MultiIndex.from_product(
+            [[0, 1, 2, 3, 4], [0.3, 0.7]], names=["A", None]
+        ),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array_no_sort():
+    df = DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]})
+    key = np.array([1, 0, 1], dtype=np.int64)
+    result = df.groupby(key, sort=False).quantile([0.25, 0.5, 0.75])
+    expected = DataFrame(
+        {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]},
+        index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]),
+    )
+    tm.assert_frame_equal(result, expected)
+
+    result = df.groupby(key, sort=False).quantile([0.75, 0.25])
+    expected = DataFrame(
+        {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]},
+        index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_array_multiple_levels():
+    df = DataFrame(
+        {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]}
+    )
+    result = df.groupby(["c", "d"]).quantile([0.25, 0.75])
+    index = pd.MultiIndex.from_tuples(
+        [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)],
+        names=["c", "d", None],
+    )
+    expected = DataFrame(
+        {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)])
+@pytest.mark.parametrize("groupby", [[0], [0, 1]])
+@pytest.mark.parametrize("q", [[0.5, 0.6]])
+def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, groupby, q):
+    # GH30289
+    nrow, ncol = frame_size
+    df = DataFrame(np.array([ncol * [_ % 4] for _ in range(nrow)]), columns=range(ncol))
+
+    idx_levels = [np.arange(min(nrow, 4))] * len(groupby) + [q]
+    idx_codes = [[x for x in range(min(nrow, 4)) for _ in q]] * len(groupby) + [
+        list(range(len(q))) * min(nrow, 4)
+    ]
+    expected_index = pd.MultiIndex(
+        levels=idx_levels, codes=idx_codes, names=groupby + [None]
+    )
+    expected_values = [
+        [float(x)] * (ncol - len(groupby)) for x in range(min(nrow, 4)) for _ in q
+    ]
+    expected_columns = [x for x in range(ncol) if x not in groupby]
+    expected = DataFrame(
+        expected_values, index=expected_index, columns=expected_columns
+    )
+    result = df.groupby(groupby).quantile(q)
+
+    tm.assert_frame_equal(result, expected)
+
+
+def test_quantile_raises():
+    df = DataFrame([["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"])
+
+    with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"):
+        df.groupby("key").quantile()
+
+
+def test_quantile_out_of_bounds_q_raises():
+    # https://github.com/pandas-dev/pandas/issues/27470
+    df = DataFrame({"a": [0, 0, 0, 1, 1, 1], "b": range(6)})
+    g = df.groupby([0, 0, 0, 1, 1, 1])
+    with pytest.raises(ValueError, match="Got '50.0' instead"):
+        g.quantile(50)
+
+    with pytest.raises(ValueError, match="Got '-1.0' instead"):
+        g.quantile(-1)
+
+
+def test_quantile_missing_group_values_no_segfaults():
+    # GH 28662
+    data = np.array([1.0, np.nan, 1.0])
+    df = DataFrame({"key": data, "val": range(3)})
+
+    # Random segfaults; would have been guaranteed in loop
+    grp = df.groupby("key")
+    for _ in range(100):
+        grp.quantile()
+
+
+@pytest.mark.parametrize(
+    "key, val, expected_key, expected_val",
+    [
+        ([1.0, np.nan, 3.0, np.nan], range(4), [1.0, 3.0], [0.0, 2.0]),
+        ([1.0, np.nan, 2.0, 2.0], range(4), [1.0, 2.0], [0.0, 2.5]),
+        (["a", "b", "b", np.nan], range(4), ["a", "b"], [0, 1.5]),
+        ([0], [42], [0], [42.0]),
+        ([], [], np.array([], dtype="float64"), np.array([], dtype="float64")),
+    ],
+)
+def test_quantile_missing_group_values_correct_results(
+    key, val, expected_key, expected_val
+):
+    # GH 28662, GH 33200, GH 33569
+    df = DataFrame({"key": key, "val": val})
+
+    expected = DataFrame(
+        expected_val, index=Index(expected_key, name="key"), columns=["val"]
+    )
+
+    grp = df.groupby("key")
+
+    result = grp.quantile(0.5)
+    tm.assert_frame_equal(result, expected)
+
+    result = grp.quantile()
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+    "values",
+    [
+        pd.array([1, 0, None] * 2, dtype="Int64"),
+        pd.array([True, False, None] * 2, dtype="boolean"),
+    ],
+)
+@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]])
+def test_groupby_quantile_nullable_array(values, q):
+    # https://github.com/pandas-dev/pandas/issues/33136
+    df = DataFrame({"a": ["x"] * 3 + ["y"] * 3, "b": values})
+    result = df.groupby("a")["b"].quantile(q)
+
+    if isinstance(q, list):
+        idx = pd.MultiIndex.from_product((["x", "y"], q), names=["a", None])
+        true_quantiles = [0.0, 0.5, 1.0]
+    else:
+        idx = Index(["x", "y"], name="a")
+        true_quantiles = [0.5]
+
+    expected = pd.Series(true_quantiles * 2, index=idx, name="b", dtype="Float64")
+    tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]])
+@pytest.mark.parametrize("numeric_only", [True, False])
+def test_groupby_quantile_raises_on_invalid_dtype(q, numeric_only):
+    df = DataFrame({"a": [1], "b": [2.0], "c": ["x"]})
+    if numeric_only:
+        result = df.groupby("a").quantile(q, numeric_only=numeric_only)
+        expected = df.groupby("a")[["b"]].quantile(q)
+        tm.assert_frame_equal(result, expected)
+    else:
+        with pytest.raises(
+            TypeError, match="'quantile' cannot be performed against 'object' dtypes!"
+        ):
+            df.groupby("a").quantile(q, numeric_only=numeric_only)
+
+
+def test_groupby_quantile_NA_float(any_float_dtype):
+    # GH#42849
+    df = DataFrame({"x": [1, 1], "y": [0.2, np.nan]}, dtype=any_float_dtype)
+    result = df.groupby("x")["y"].quantile(0.5)
+    exp_index = Index([1.0], dtype=any_float_dtype, name="x")
+
+    if any_float_dtype in ["Float32", "Float64"]:
+        expected_dtype = any_float_dtype
+    else:
+        expected_dtype = None
+
+    expected = pd.Series([0.2], dtype=expected_dtype, index=exp_index, name="y")
+    tm.assert_series_equal(result, expected)
+
+    result = df.groupby("x")["y"].quantile([0.5, 0.75])
+    expected = pd.Series(
+        [0.2] * 2,
+        index=pd.MultiIndex.from_product((exp_index, [0.5, 0.75]), names=["x", None]),
+        name="y",
+        dtype=expected_dtype,
+    )
+    tm.assert_series_equal(result, expected)
+
+
+def test_groupby_quantile_NA_int(any_int_ea_dtype):
+    # GH#42849
+    df = DataFrame({"x": [1, 1], "y": [2, 5]}, dtype=any_int_ea_dtype)
+    result = df.groupby("x")["y"].quantile(0.5)
+    expected = pd.Series(
+        [3.5],
+        dtype="Float64",
+        index=Index([1], name="x", dtype=any_int_ea_dtype),
+        name="y",
+    )
+    tm.assert_series_equal(expected, result)
+
+    result = df.groupby("x").quantile(0.5)
+    expected = DataFrame(
+        {"y": 3.5}, dtype="Float64", index=Index([1], name="x", dtype=any_int_ea_dtype)
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+    "interpolation, val1, val2", [("lower", 2, 2), ("higher", 2, 3), ("nearest", 2, 2)]
+)
+def test_groupby_quantile_all_na_group_masked(
+    interpolation, val1, val2, any_numeric_ea_dtype
+):
+    # GH#37493
+    df = DataFrame(
+        {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype
+    )
+    result = df.groupby("a").quantile(q=[0.5, 0.7], interpolation=interpolation)
+    expected = DataFrame(
+        {"b": [val1, val2, pd.NA, pd.NA]},
+        dtype=any_numeric_ea_dtype,
+        index=pd.MultiIndex.from_arrays(
+            [pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype), [0.5, 0.7, 0.5, 0.7]],
+            names=["a", None],
+        ),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("interpolation", ["midpoint", "linear"])
+def test_groupby_quantile_all_na_group_masked_interp(
+    interpolation, any_numeric_ea_dtype
+):
+    # GH#37493
+    df = DataFrame(
+        {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype
+    )
+    result = df.groupby("a").quantile(q=[0.5, 0.75], interpolation=interpolation)
+
+    if any_numeric_ea_dtype == "Float32":
+        expected_dtype = any_numeric_ea_dtype
+    else:
+        expected_dtype = "Float64"
+
+    expected = DataFrame(
+        {"b": [2.0, 2.5, pd.NA, pd.NA]},
+        dtype=expected_dtype,
+        index=pd.MultiIndex.from_arrays(
+            [
+                pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype),
+                [0.5, 0.75, 0.5, 0.75],
+            ],
+            names=["a", None],
+        ),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["Float64", "Float32"])
+def test_groupby_quantile_allNA_column(dtype):
+    # GH#42849
+    df = DataFrame({"x": [1, 1], "y": [pd.NA] * 2}, dtype=dtype)
+    result = df.groupby("x")["y"].quantile(0.5)
+    expected = pd.Series(
+        [np.nan], dtype=dtype, index=Index([1.0], dtype=dtype), name="y"
+    )
+    expected.index.name = "x"
+    tm.assert_series_equal(expected, result)
+
+
+def test_groupby_timedelta_quantile():
+    # GH: 29485
+    df = DataFrame(
+        {"value": pd.to_timedelta(np.arange(4), unit="s"), "group": [1, 1, 2, 2]}
+    )
+    result = df.groupby("group").quantile(0.99)
+    expected = DataFrame(
+        {
+            "value": [
+                pd.Timedelta("0 days 00:00:00.990000"),
+                pd.Timedelta("0 days 00:00:02.990000"),
+            ]
+        },
+        index=Index([1, 2], name="group"),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_columns_groupby_quantile():
+    # GH 33795
+    df = DataFrame(
+        np.arange(12).reshape(3, -1),
+        index=list("XYZ"),
+        columns=pd.Series(list("ABAB"), name="col"),
+    )
+    msg = "DataFrame.groupby with axis=1 is deprecated"
+    with tm.assert_produces_warning(FutureWarning, match=msg):
+        gb = df.groupby("col", axis=1)
+    result = gb.quantile(q=[0.8, 0.2])
+    expected = DataFrame(
+        [
+            [1.6, 0.4, 2.6, 1.4],
+            [5.6, 4.4, 6.6, 5.4],
+            [9.6, 8.4, 10.6, 9.4],
+        ],
+        index=list("XYZ"),
+        columns=pd.MultiIndex.from_tuples(
+            [("A", 0.8), ("A", 0.2), ("B", 0.8), ("B", 0.2)], names=["col", None]
+        ),
+    )
+
+    tm.assert_frame_equal(result, expected)
+
+
+def test_timestamp_groupby_quantile(unit):
+    # GH 33168
+    dti = pd.date_range(
+        start="2020-04-19 00:00:00", freq="1min", periods=100, tz="UTC", unit=unit
+    ).floor("1h")
+    df = DataFrame(
+        {
+            "timestamp": dti,
+            "category": list(range(1, 101)),
+            "value": list(range(101, 201)),
+        }
+    )
+
+    result = df.groupby("timestamp").quantile([0.2, 0.8])
+
+    mi = pd.MultiIndex.from_product([dti[::99], [0.2, 0.8]], names=("timestamp", None))
+    expected = DataFrame(
+        [
+            {"category": 12.8, "value": 112.8},
+            {"category": 48.2, "value": 148.2},
+            {"category": 68.8, "value": 168.8},
+            {"category": 92.2, "value": 192.2},
+        ],
+        index=mi,
+    )
+
+    tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_quantile_dt64tz_period():
+    # GH#51373
+    dti = pd.date_range("2016-01-01", periods=1000)
+    df = pd.Series(dti).to_frame().copy()
+    df[1] = dti.tz_localize("US/Pacific")
+    df[2] = dti.to_period("D")
+    df[3] = dti - dti[0]
+    df.iloc[-1] = pd.NaT
+
+    by = np.tile(np.arange(5), 200)
+    gb = df.groupby(by)
+
+    result = gb.quantile(0.5)
+
+    # Check that we match the group-by-group result
+    exp = {i: df.iloc[i::5].quantile(0.5) for i in range(5)}
+    expected = DataFrame(exp).T.infer_objects()
+    expected.index = expected.index.astype(int)
+
+    tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_quantile_nonmulti_levels_order():
+    # Non-regression test for GH #53009
+    ind = pd.MultiIndex.from_tuples(
+        [
+            (0, "a", "B"),
+            (0, "a", "A"),
+            (0, "b", "B"),
+            (0, "b", "A"),
+            (1, "a", "B"),
+            (1, "a", "A"),
+            (1, "b", "B"),
+            (1, "b", "A"),
+        ],
+        names=["sample", "cat0", "cat1"],
+    )
+    ser = pd.Series(range(8), index=ind)
+    result = ser.groupby(level="cat1", sort=False).quantile([0.2, 0.8])
+
+    qind = pd.MultiIndex.from_tuples(
+        [("B", 0.2), ("B", 0.8), ("A", 0.2), ("A", 0.8)], names=["cat1", None]
+    )
+    expected = pd.Series([1.2, 4.8, 2.2, 5.8], index=qind)
+
+    tm.assert_series_equal(result, expected)
+
+    # We need to check that index levels are not sorted
+    expected_levels = pd.core.indexes.frozen.FrozenList([["B", "A"], [0.2, 0.8]])
+    tm.assert_equal(result.index.levels, expected_levels)
diff --git a/shared/package-files/75/75e60b2de86133ecdbce7d9a814ec11eadc62d9557549039d58b829b1685b3db/__init__.cpython-311.pyc b/shared/package-files/75/75e60b2de86133ecdbce7d9a814ec11eadc62d9557549039d58b829b1685b3db/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..901c50c84c2cb5a1580529410b0f823a2f91c87c
Binary files /dev/null and b/shared/package-files/75/75e60b2de86133ecdbce7d9a814ec11eadc62d9557549039d58b829b1685b3db/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/75/75f77642e6917448db4ad38abda40b8b531dfeaae945087c3dfc99ce727c6d66/generated_cudaGL_meta.h b/shared/package-files/75/75f77642e6917448db4ad38abda40b8b531dfeaae945087c3dfc99ce727c6d66/generated_cudaGL_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a52e194b265d32f61d47bd3081f4958755bff46
--- /dev/null
+++ b/shared/package-files/75/75f77642e6917448db4ad38abda40b8b531dfeaae945087c3dfc99ce727c6d66/generated_cudaGL_meta.h
@@ -0,0 +1,116 @@
+// This file is generated.  Any changes you make will be lost during the next clean build.
+
+// Dependent includes
+#ifdef __APPLE__
+#include 
+#else
+#include 
+#endif
+
+// CUDA public interface, for type definitions and cu* function prototypes
+#include "cudaGL.h"
+
+
+// *************************************************************************
+//      Definitions of structs to hold parameters for each function
+// *************************************************************************
+
+typedef struct cuGraphicsGLRegisterBuffer_params_st {
+    CUgraphicsResource *pCudaResource;
+    GLuint buffer;
+    unsigned int Flags;
+} cuGraphicsGLRegisterBuffer_params;
+
+typedef struct cuGraphicsGLRegisterImage_params_st {
+    CUgraphicsResource *pCudaResource;
+    GLuint image;
+    GLenum target;
+    unsigned int Flags;
+} cuGraphicsGLRegisterImage_params;
+
+typedef struct cuGLGetDevices_v2_params_st {
+    unsigned int *pCudaDeviceCount;
+    CUdevice *pCudaDevices;
+    unsigned int cudaDeviceCount;
+    CUGLDeviceList deviceList;
+} cuGLGetDevices_v2_params;
+
+typedef struct cuGLCtxCreate_v2_params_st {
+    CUcontext *pCtx;
+    unsigned int Flags;
+    CUdevice device;
+} cuGLCtxCreate_v2_params;
+
+typedef struct cuGLRegisterBufferObject_params_st {
+    GLuint buffer;
+} cuGLRegisterBufferObject_params;
+
+typedef struct cuGLMapBufferObject_v2_ptds_params_st {
+    CUdeviceptr *dptr;
+    size_t *size;
+    GLuint buffer;
+} cuGLMapBufferObject_v2_ptds_params;
+
+typedef struct cuGLUnmapBufferObject_params_st {
+    GLuint buffer;
+} cuGLUnmapBufferObject_params;
+
+typedef struct cuGLUnregisterBufferObject_params_st {
+    GLuint buffer;
+} cuGLUnregisterBufferObject_params;
+
+typedef struct cuGLSetBufferObjectMapFlags_params_st {
+    GLuint buffer;
+    unsigned int Flags;
+} cuGLSetBufferObjectMapFlags_params;
+
+typedef struct cuGLMapBufferObjectAsync_v2_ptsz_params_st {
+    CUdeviceptr *dptr;
+    size_t *size;
+    GLuint buffer;
+    CUstream hStream;
+} cuGLMapBufferObjectAsync_v2_ptsz_params;
+
+typedef struct cuGLUnmapBufferObjectAsync_params_st {
+    GLuint buffer;
+    CUstream hStream;
+} cuGLUnmapBufferObjectAsync_params;
+
+typedef struct cuGLGetDevices_params_st {
+    unsigned int *pCudaDeviceCount;
+    CUdevice *pCudaDevices;
+    unsigned int cudaDeviceCount;
+    CUGLDeviceList deviceList;
+} cuGLGetDevices_params;
+
+typedef struct cuGLMapBufferObject_v2_params_st {
+    CUdeviceptr *dptr;
+    size_t *size;
+    GLuint buffer;
+} cuGLMapBufferObject_v2_params;
+
+typedef struct cuGLMapBufferObjectAsync_v2_params_st {
+    CUdeviceptr *dptr;
+    size_t *size;
+    GLuint buffer;
+    CUstream hStream;
+} cuGLMapBufferObjectAsync_v2_params;
+
+typedef struct cuGLCtxCreate_params_st {
+    CUcontext *pCtx;
+    unsigned int Flags;
+    CUdevice device;
+} cuGLCtxCreate_params;
+
+typedef struct cuGLMapBufferObject_params_st {
+    CUdeviceptr_v1 *dptr;
+    unsigned int *size;
+    GLuint buffer;
+} cuGLMapBufferObject_params;
+
+typedef struct cuGLMapBufferObjectAsync_params_st {
+    CUdeviceptr_v1 *dptr;
+    unsigned int *size;
+    GLuint buffer;
+    CUstream hStream;
+} cuGLMapBufferObjectAsync_params;
diff --git a/shared/package-files/7c/7c43540c2fc6d3b7b5c9cb52541daecc97000c10f79809309d1f0f28ecf7b767/__init__.cpython-311.pyc b/shared/package-files/7c/7c43540c2fc6d3b7b5c9cb52541daecc97000c10f79809309d1f0f28ecf7b767/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f02bcd225dfef3ee507b9295ebf0125bc15b798
Binary files /dev/null and b/shared/package-files/7c/7c43540c2fc6d3b7b5c9cb52541daecc97000c10f79809309d1f0f28ecf7b767/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/7c/7c8fbfb94fc98aee44216516b61270ca6bc2e5c40d9deb126c2f498104336c60/bam2bcf.h b/shared/package-files/7c/7c8fbfb94fc98aee44216516b61270ca6bc2e5c40d9deb126c2f498104336c60/bam2bcf.h
new file mode 100644
index 0000000000000000000000000000000000000000..8f8f8db5a21f4b987f4d2f8dd107cd5076188912
--- /dev/null
+++ b/shared/package-files/7c/7c8fbfb94fc98aee44216516b61270ca6bc2e5c40d9deb126c2f498104336c60/bam2bcf.h
@@ -0,0 +1,232 @@
+/*  bam2bcf.h -- variant calling.
+
+    Copyright (C) 2010-2012 Broad Institute.
+    Copyright (C) 2012-2022 Genome Research Ltd.
+
+    Author: Heng Li 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#ifndef BAM2BCF_H
+#define BAM2BCF_H
+
+#include 
+#include 
+#include 
+
+/**
+ *  A simplified version of Mann-Whitney U-test is calculated
+ *  by default (no CDF) because it is faster and seems to work
+ *  better in machine learning filtering. When enabled by setting
+ *  CDF_MWU_TESTS, additional annotations will appear on mpileup's
+ *  output (RPB2 in addition to RPB, etc.).
+ */
+#ifndef CDF_MWU_TESTS
+#define CDF_MWU_TESTS 0
+#endif
+
+#define B2B_INDEL_NULL 10000
+
+#define B2B_FMT_DP      (1<<0)
+#define B2B_FMT_SP      (1<<1)
+#define B2B_FMT_DV      (1<<2)
+#define B2B_FMT_DP4     (1<<3)
+#define B2B_FMT_DPR     (1<<4)
+#define B2B_INFO_DPR    (1<<5)
+#define B2B_FMT_AD      (1<<6)
+#define B2B_FMT_ADF     (1<<7)
+#define B2B_FMT_ADR     (1<<8)
+#define B2B_INFO_AD     (1<<9)
+#define B2B_INFO_ADF    (1<<10)
+#define B2B_INFO_ADR    (1<<11)
+#define B2B_INFO_SCR    (1<<12)
+#define B2B_FMT_SCR     (1<<13)
+#define B2B_INFO_VDB    (1<<14)
+#define B2B_FMT_QS      (1<<15)
+#define B2B_FMT_NMBZ    (1<<16) // per-sample NMBZ
+#define B2B_INFO_NMBZ   (1<<17)
+#define B2B_INFO_BQBZ   (1<<18)
+#define B2B_INFO_MQBZ   (1<<19)
+#define B2B_INFO_MQSBZ  (1<<20)
+#define B2B_INFO_RPBZ   (1<<21)
+#define B2B_INFO_SCBZ   (1<<22)
+#define B2B_INFO_SGB    (1<<23)
+#define B2B_INFO_MIN_PL_SUM (1<<24)
+#define B2B_INFO_NM     (1<<25)
+#define B2B_INFO_MQ0F   (1<<26)
+#define B2B_INFO_IDV    (1<<27)
+#define B2B_INFO_IMF    (1<<28)
+#define B2B_INFO_FS     (1<<29)
+
+#define B2B_MAX_ALLELES 5
+#define B2B_N_NM 32             // number of NMBZ bins, i.e. max number of mismatches
+
+
+#define B2B_DROP      0
+#define B2B_INC_AD    1
+#define B2B_INC_AD0   2
+
+
+// Pileup "client data" for each read to cache per-read information
+#define PLP_CD(x) ((plp_cd_t*)((x)->p))
+#define PLP_HAS_SOFT_CLIP(cd) (PLP_CD(cd)->i & 1)
+#define PLP_HAS_INDEL(cd)     (PLP_CD(cd)->i & 2)
+#define PLP_IS_REALN(cd)      (PLP_CD(cd)->i & 4)
+#define PLP_SAMPLE_ID(cd)     (PLP_CD(cd)->i >> 3)
+#define PLP_QLEN(cd)          (PLP_CD(cd)->qlen)
+#define PLP_NM(cd)            (PLP_CD(cd)->nm)
+#define PLP_NM_UNSET          -2
+
+#define PLP_SET_SOFT_CLIP(cd)     (PLP_CD(cd)->i |= 1)
+#define PLP_SET_INDEL(cd)         (PLP_CD(cd)->i |= 2)
+#define PLP_SET_REALN(cd)         (PLP_CD(cd)->i |= 4)
+#define PLP_SET_SAMPLE_ID(cd,n)   (PLP_CD(cd)->i |= (n)<<3)
+
+typedef struct
+{
+    int64_t i;      // used to store sample id and flags for presence of soft-clip and indel
+    uint32_t qlen;  // cached output of bam_cigar2qlen(), 0 if unset
+    int nm;         // -2 PLP_NM_UNSET; -1 not available; >=0 NM value computed by get_aux_nm()
+}
+plp_cd_t;
+
+
+typedef struct __bcf_callaux_t {
+    int fmt_flag, ambig_reads;
+    int capQ, min_baseQ, max_baseQ, delta_baseQ;
+    int openQ, extQ, tandemQ; // for indels
+    uint32_t min_support, max_support; // for collecting indel candidates
+    double min_frac; // for collecting indel candidates
+    float max_frac; // for collecting indel candidates
+    int per_sample_flt; // indel filtering strategy
+    int *ref_pos, *alt_pos, npos, *ref_mq, *alt_mq, *ref_bq, *alt_bq, *fwd_mqs, *rev_mqs, nqual; // for bias tests
+    int *iref_pos, *ialt_pos, *iref_mq, *ialt_mq; // for indels
+    int ref_scl[100], alt_scl[100];   // soft-clip length bias; SNP
+    int iref_scl[100], ialt_scl[100]; // soft-clip length bias; INDEL
+    // for internal uses
+    int max_bases;
+    int indel_types[4];     // indel lengths
+    int indel_win_size, indels_v20, edlib;
+    int seqQ_offset; // edlib mode, seqQ=MIN(seqQ, offset - MIN(20,depth)*5);
+    int maxins, indelreg, poly_mqual;
+    int read_len;
+    char *inscns;
+    uint16_t *bases;        // 5bit: unused, 6:quality, 1:is_rev, 4:2-bit base or indel allele (index to bcf_callaux_t.indel_types)
+    errmod_t *e;
+    void *rghash;
+    float indel_bias;  // adjusts indel score threshold; lower => call more.
+    float del_bias;    // (-.9 < x < .9) error profile; >0 => more del, <0 => more ins
+    float vs_ref;      // 0 to 1.  0: score vs next-best. 1: score vs ref
+    int32_t *ref_nm, *alt_nm;   // pointers to bcf_call_t.{ref_nm,alt_nm}
+    unsigned int nnm[2];        // number of nm observations
+    float nm[2];                // cumulative count of mismatches in ref and alt reads
+    void *iaux;                 // auxiliary structure for --indels-2.0 calling
+    char *chr;                  // current chromosome
+} bcf_callaux_t;
+
+// per-sample values
+typedef struct {
+    uint32_t ori_depth;     // ori_depth = anno[0..3] but before --min-BQ is applied
+    unsigned int mq0;
+    int32_t *ADF, *ADR, SCR, *QS;   // FMT/QS
+    int32_t *ref_nm, *alt_nm;
+    // The fields are:
+    //      depth fwd   .. ref (0) and non-ref (2)
+    //      depth rev   .. ref (1) and non-ref (3)
+    //      baseQ       .. ref (4) and non-ref (6)
+    //      baseQ^2     .. ref (5) and non-ref (7)
+    //      mapQ        .. ref (8) and non-ref (10)
+    //      mapQ^2      .. ref (9) and non-ref (11)
+    //      minDist     .. ref (12) and non-ref (14)
+    //      minDist^2   .. ref (13) and non-ref (15)
+    // Note that this probably needs a more thorough fix: int types in
+    // bcf_call_t do overflow with high-coverage data, such as exomes, and
+    // BCFv2 supports only floats which may not suffice.
+    double anno[16];
+    float p[25];        // phred-scaled likelihood of each genotype
+} bcf_callret1_t;
+
+// values for all samples
+typedef struct {
+    int tid, pos;
+    bcf_hdr_t *bcf_hdr;
+    int a[5]; // alleles: ref, alt, alt2, alt3
+    float qsum[B2B_MAX_ALLELES];  // INFO/QS tag
+    int n, n_alleles, ori_ref, unseen;
+    int32_t shift;  // shift is the sum of min_PL before normalization to 0 across all samples
+    int n_supp; // number of supporting non-reference reads
+    double anno[16];
+    unsigned int depth, ori_depth, mq0;
+    int32_t *PL, *DP4, *ADR, *ADF, *SCR, *QS, *ref_nm, *alt_nm;
+    uint8_t *fmt_arr;
+    float vdb; // variant distance bias
+    float mwu_pos, mwu_mq, mwu_bq, mwu_mqs, mwu_sc, *mwu_nm, nm[2];
+    float seg_bias;
+    float strand_bias; // phred-scaled fisher-exact test
+    kstring_t tmp;
+} bcf_call_t;
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+    bcf_callaux_t *bcf_call_init(double theta, int min_baseQ, int max_baseQ,
+                                 int delta_baseQ);
+    void bcf_call_destroy(bcf_callaux_t *bca);
+    int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r);
+    int bcf_call_combine(int n, const bcf_callret1_t *calls, bcf_callaux_t *bca, int ref_base /*4-bit*/, bcf_call_t *call);
+    int bcf_call2bcf(bcf_call_t *bc, bcf1_t *b, bcf_callret1_t *bcr, int fmt_flag,
+                     const bcf_callaux_t *bca, const char *ref);
+    int bcf_call_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref);
+    int bcf_iaux_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref);
+    int bcf_edlib_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos,
+                           bcf_callaux_t *bca, const char *ref, int ref_len);
+
+    void bcf_callaux_clean(bcf_callaux_t *bca, bcf_call_t *call);
+
+    int bcf_cgp_l_run(const char *ref, int pos);
+    int est_indelreg(int pos, const char *ref, int l, char *ins4);
+
+/* ----------------------------------------------------------------------
+ * Shared between bam2bcf_indel.c and bam2bcf_edlib.c
+ */
+
+// Take a reference position tpos and convert to a query position (returned).
+// This uses the CIGAR string plus alignment c->pos to do the mapping.
+//
+// *_tpos is returned as tpos if query overlaps tpos, but for deletions
+// it'll be either the start (is_left) or end (!is_left) ref position.
+int tpos2qpos(const bam1_core_t *c, const uint32_t *cigar, int32_t tpos, int is_left, int32_t *_tpos);
+
+// Identify spft-clip length, position in seq, and clipped seq len
+void get_pos(const bcf_callaux_t *bca, bam_pileup1_t *p,
+             int *sc_len_r, int *slen_r, int *epos_r, int *end);
+
+// Compute the consensus for this sample 's', minus indels which
+// get added later.
+char *bcf_cgp_calc_cons(int n, int *n_plp, bam_pileup1_t **plp,
+                        int pos, int *types, int n_types,
+                        int max_ins, int s);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/shared/package-files/7c/7ca8420be1662ddb0f49acd14a8055907eedb7b503b15d9d97a5978bf44b0906/conftest_cstd.c b/shared/package-files/7c/7ca8420be1662ddb0f49acd14a8055907eedb7b503b15d9d97a5978bf44b0906/conftest_cstd.c
new file mode 100644
index 0000000000000000000000000000000000000000..58248470c297969e54aedd0fbe0d806af78d4483
--- /dev/null
+++ b/shared/package-files/7c/7ca8420be1662ddb0f49acd14a8055907eedb7b503b15d9d97a5978bf44b0906/conftest_cstd.c
@@ -0,0 +1,11 @@
+#include 
+#include 
+
+// C++-style comment; for-decl; optind
+
+int main(int argc, char **argv) {
+    int sum = 0;
+    for (int i = optind; i < argc; i++)
+        sum += strlen(argv[i]);
+    return sum;
+}
diff --git a/shared/package-files/7c/7caf08f690ef0dbe9e1cf396d98e641c3f5d2ab0fc00c390e2897a3e4a8963a3/_nested_tensor_softmax_with_shape_native.h b/shared/package-files/7c/7caf08f690ef0dbe9e1cf396d98e641c3f5d2ab0fc00c390e2897a3e4a8963a3/_nested_tensor_softmax_with_shape_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..6d2c53ad489875988a28639424606a31f34dbb5d
--- /dev/null
+++ b/shared/package-files/7c/7caf08f690ef0dbe9e1cf396d98e641c3f5d2ab0fc00c390e2897a3e4a8963a3/_nested_tensor_softmax_with_shape_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor NestedTensor_softmax_dropout(const at::Tensor & self, const at::Tensor & query);
+TORCH_API at::Tensor NestedTensor_softmax_dropout_cuda(const at::Tensor & self, const at::Tensor & query);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/7c/7cbe1fd6f9b8d163ddac9d585e531de21cdcf83932424b1131d284746736ec3c/test_store.py b/shared/package-files/7c/7cbe1fd6f9b8d163ddac9d585e531de21cdcf83932424b1131d284746736ec3c/test_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..82d3052e7f5d6738801e973a9f34307ea0dff2cf
--- /dev/null
+++ b/shared/package-files/7c/7cbe1fd6f9b8d163ddac9d585e531de21cdcf83932424b1131d284746736ec3c/test_store.py
@@ -0,0 +1,1119 @@
+import contextlib
+import datetime as dt
+import hashlib
+import tempfile
+import time
+
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import (
+    DataFrame,
+    DatetimeIndex,
+    Index,
+    MultiIndex,
+    Series,
+    Timestamp,
+    concat,
+    date_range,
+    period_range,
+    timedelta_range,
+)
+import pandas._testing as tm
+from pandas.tests.io.pytables.common import (
+    _maybe_remove,
+    ensure_clean_store,
+)
+
+from pandas.io.pytables import (
+    HDFStore,
+    read_hdf,
+)
+
+pytestmark = pytest.mark.single_cpu
+
+tables = pytest.importorskip("tables")
+
+
+def test_context(setup_path):
+    with tm.ensure_clean(setup_path) as path:
+        try:
+            with HDFStore(path) as tbl:
+                raise ValueError("blah")
+        except ValueError:
+            pass
+    with tm.ensure_clean(setup_path) as path:
+        with HDFStore(path) as tbl:
+            tbl["a"] = DataFrame(
+                1.1 * np.arange(120).reshape((30, 4)),
+                columns=Index(list("ABCD"), dtype=object),
+                index=Index([f"i-{i}" for i in range(30)], dtype=object),
+            )
+            assert len(tbl) == 1
+            assert type(tbl["a"]) == DataFrame
+
+
+def test_no_track_times(tmp_path, setup_path):
+    # GH 32682
+    # enables to set track_times (see `pytables` `create_table` documentation)
+
+    def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
+        h = hash_factory()
+        with open(filename, "rb") as f:
+            for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""):
+                h.update(chunk)
+        return h.digest()
+
+    def create_h5_and_return_checksum(tmp_path, track_times):
+        path = tmp_path / setup_path
+        df = DataFrame({"a": [1]})
+
+        with HDFStore(path, mode="w") as hdf:
+            hdf.put(
+                "table",
+                df,
+                format="table",
+                data_columns=True,
+                index=None,
+                track_times=track_times,
+            )
+
+        return checksum(path)
+
+    checksum_0_tt_false = create_h5_and_return_checksum(tmp_path, track_times=False)
+    checksum_0_tt_true = create_h5_and_return_checksum(tmp_path, track_times=True)
+
+    # sleep is necessary to create h5 with different creation time
+    time.sleep(1)
+
+    checksum_1_tt_false = create_h5_and_return_checksum(tmp_path, track_times=False)
+    checksum_1_tt_true = create_h5_and_return_checksum(tmp_path, track_times=True)
+
+    # checksums are the same if track_time = False
+    assert checksum_0_tt_false == checksum_1_tt_false
+
+    # checksums are NOT same if track_time = True
+    assert checksum_0_tt_true != checksum_1_tt_true
+
+
+def test_iter_empty(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        # GH 12221
+        assert list(store) == []
+
+
+def test_repr(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        repr(store)
+        store.info()
+        store["a"] = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        store["b"] = Series(
+            range(10), dtype="float64", index=[f"i_{i}" for i in range(10)]
+        )
+        store["c"] = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        df["obj1"] = "foo"
+        df["obj2"] = "bar"
+        df["bool1"] = df["A"] > 0
+        df["bool2"] = df["B"] > 0
+        df["bool3"] = True
+        df["int1"] = 1
+        df["int2"] = 2
+        df["timestamp1"] = Timestamp("20010102")
+        df["timestamp2"] = Timestamp("20010103")
+        df["datetime1"] = dt.datetime(2001, 1, 2, 0, 0)
+        df["datetime2"] = dt.datetime(2001, 1, 3, 0, 0)
+        df.loc[df.index[3:6], ["obj1"]] = np.nan
+        df = df._consolidate()
+
+        with tm.assert_produces_warning(pd.errors.PerformanceWarning):
+            store["df"] = df
+
+        # make a random group in hdf space
+        store._handle.create_group(store._handle.root, "bah")
+
+        assert store.filename in repr(store)
+        assert store.filename in str(store)
+        store.info()
+
+    # storers
+    with ensure_clean_store(setup_path) as store:
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        store.append("df", df)
+
+        s = store.get_storer("df")
+        repr(s)
+        str(s)
+
+
+def test_contains(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        store["a"] = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        store["b"] = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        store["foo/bar"] = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        assert "a" in store
+        assert "b" in store
+        assert "c" not in store
+        assert "foo/bar" in store
+        assert "/foo/bar" in store
+        assert "/foo/b" not in store
+        assert "bar" not in store
+
+        # gh-2694: tables.NaturalNameWarning
+        with tm.assert_produces_warning(
+            tables.NaturalNameWarning, check_stacklevel=False
+        ):
+            store["node())"] = DataFrame(
+                1.1 * np.arange(120).reshape((30, 4)),
+                columns=Index(list("ABCD"), dtype=object),
+                index=Index([f"i-{i}" for i in range(30)], dtype=object),
+            )
+        assert "node())" in store
+
+
+def test_versioning(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        store["a"] = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        store["b"] = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((20, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=20, freq="B"),
+        )
+        _maybe_remove(store, "df1")
+        store.append("df1", df[:10])
+        store.append("df1", df[10:])
+        assert store.root.a._v_attrs.pandas_version == "0.15.2"
+        assert store.root.b._v_attrs.pandas_version == "0.15.2"
+        assert store.root.df1._v_attrs.pandas_version == "0.15.2"
+
+        # write a file and wipe its versioning
+        _maybe_remove(store, "df2")
+        store.append("df2", df)
+
+        # this is an error because its table_type is appendable, but no
+        # version info
+        store.get_node("df2")._v_attrs.pandas_version = None
+
+        msg = "'NoneType' object has no attribute 'startswith'"
+
+        with pytest.raises(Exception, match=msg):
+            store.select("df2")
+
+
+@pytest.mark.parametrize(
+    "where, expected",
+    [
+        (
+            "/",
+            {
+                "": ({"first_group", "second_group"}, set()),
+                "/first_group": (set(), {"df1", "df2"}),
+                "/second_group": ({"third_group"}, {"df3", "s1"}),
+                "/second_group/third_group": (set(), {"df4"}),
+            },
+        ),
+        (
+            "/second_group",
+            {
+                "/second_group": ({"third_group"}, {"df3", "s1"}),
+                "/second_group/third_group": (set(), {"df4"}),
+            },
+        ),
+    ],
+)
+def test_walk(where, expected):
+    # GH10143
+    objs = {
+        "df1": DataFrame([1, 2, 3]),
+        "df2": DataFrame([4, 5, 6]),
+        "df3": DataFrame([6, 7, 8]),
+        "df4": DataFrame([9, 10, 11]),
+        "s1": Series([10, 9, 8]),
+        # Next 3 items aren't pandas objects and should be ignored
+        "a1": np.array([[1, 2, 3], [4, 5, 6]]),
+        "tb1": np.array([(1, 2, 3), (4, 5, 6)], dtype="i,i,i"),
+        "tb2": np.array([(7, 8, 9), (10, 11, 12)], dtype="i,i,i"),
+    }
+
+    with ensure_clean_store("walk_groups.hdf", mode="w") as store:
+        store.put("/first_group/df1", objs["df1"])
+        store.put("/first_group/df2", objs["df2"])
+        store.put("/second_group/df3", objs["df3"])
+        store.put("/second_group/s1", objs["s1"])
+        store.put("/second_group/third_group/df4", objs["df4"])
+        # Create non-pandas objects
+        store._handle.create_array("/first_group", "a1", objs["a1"])
+        store._handle.create_table("/first_group", "tb1", obj=objs["tb1"])
+        store._handle.create_table("/second_group", "tb2", obj=objs["tb2"])
+
+        assert len(list(store.walk(where=where))) == len(expected)
+        for path, groups, leaves in store.walk(where=where):
+            assert path in expected
+            expected_groups, expected_frames = expected[path]
+            assert expected_groups == set(groups)
+            assert expected_frames == set(leaves)
+            for leaf in leaves:
+                frame_path = "/".join([path, leaf])
+                obj = store.get(frame_path)
+                if "df" in leaf:
+                    tm.assert_frame_equal(obj, objs[leaf])
+                else:
+                    tm.assert_series_equal(obj, objs[leaf])
+
+
+def test_getattr(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        s = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        store["a"] = s
+
+        # test attribute access
+        result = store.a
+        tm.assert_series_equal(result, s)
+        result = getattr(store, "a")
+        tm.assert_series_equal(result, s)
+
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((10, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=10, freq="B"),
+        )
+        store["df"] = df
+        result = store.df
+        tm.assert_frame_equal(result, df)
+
+        # errors
+        for x in ["d", "mode", "path", "handle", "complib"]:
+            msg = f"'HDFStore' object has no attribute '{x}'"
+            with pytest.raises(AttributeError, match=msg):
+                getattr(store, x)
+
+        # not stores
+        for x in ["mode", "path", "handle", "complib"]:
+            getattr(store, f"_{x}")
+
+
+def test_store_dropna(tmp_path, setup_path):
+    df_with_missing = DataFrame(
+        {"col1": [0.0, np.nan, 2.0], "col2": [1.0, np.nan, np.nan]},
+        index=list("abc"),
+    )
+    df_without_missing = DataFrame(
+        {"col1": [0.0, 2.0], "col2": [1.0, np.nan]}, index=list("ac")
+    )
+
+    # # Test to make sure defaults are to not drop.
+    # # Corresponding to Issue 9382
+    path = tmp_path / setup_path
+    df_with_missing.to_hdf(path, key="df", format="table")
+    reloaded = read_hdf(path, "df")
+    tm.assert_frame_equal(df_with_missing, reloaded)
+
+    path = tmp_path / setup_path
+    df_with_missing.to_hdf(path, key="df", format="table", dropna=False)
+    reloaded = read_hdf(path, "df")
+    tm.assert_frame_equal(df_with_missing, reloaded)
+
+    path = tmp_path / setup_path
+    df_with_missing.to_hdf(path, key="df", format="table", dropna=True)
+    reloaded = read_hdf(path, "df")
+    tm.assert_frame_equal(df_without_missing, reloaded)
+
+
+def test_keyword_deprecation(tmp_path, setup_path):
+    # GH 54229
+    path = tmp_path / setup_path
+
+    msg = (
+        "Starting with pandas version 3.0 all arguments of to_hdf except for the "
+        "argument 'path_or_buf' will be keyword-only."
+    )
+    df = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 1, "B": 2, "C": 3}])
+
+    with tm.assert_produces_warning(FutureWarning, match=msg):
+        df.to_hdf(path, "key")
+
+
+def test_to_hdf_with_min_itemsize(tmp_path, setup_path):
+    path = tmp_path / setup_path
+
+    # min_itemsize in index with to_hdf (GH 10381)
+    df = DataFrame(
+        {
+            "A": [0.0, 1.0, 2.0, 3.0, 4.0],
+            "B": [0.0, 1.0, 0.0, 1.0, 0.0],
+            "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object),
+            "D": date_range("20130101", periods=5),
+        }
+    ).set_index("C")
+    df.to_hdf(path, key="ss3", format="table", min_itemsize={"index": 6})
+    # just make sure there is a longer string:
+    df2 = df.copy().reset_index().assign(C="longer").set_index("C")
+    df2.to_hdf(path, key="ss3", append=True, format="table")
+    tm.assert_frame_equal(read_hdf(path, "ss3"), concat([df, df2]))
+
+    # same as above, with a Series
+    df["B"].to_hdf(path, key="ss4", format="table", min_itemsize={"index": 6})
+    df2["B"].to_hdf(path, key="ss4", append=True, format="table")
+    tm.assert_series_equal(read_hdf(path, "ss4"), concat([df["B"], df2["B"]]))
+
+
+@pytest.mark.parametrize("format", ["fixed", "table"])
+def test_to_hdf_errors(tmp_path, format, setup_path):
+    data = ["\ud800foo"]
+    ser = Series(data, index=Index(data))
+    path = tmp_path / setup_path
+    # GH 20835
+    ser.to_hdf(path, key="table", format=format, errors="surrogatepass")
+
+    result = read_hdf(path, "table", errors="surrogatepass")
+    tm.assert_series_equal(result, ser)
+
+
+def test_create_table_index(setup_path):
+    with ensure_clean_store(setup_path) as store:
+
+        def col(t, column):
+            return getattr(store.get_storer(t).table.cols, column)
+
+        # data columns
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((10, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=10, freq="B"),
+        )
+        df["string"] = "foo"
+        df["string2"] = "bar"
+        store.append("f", df, data_columns=["string", "string2"])
+        assert col("f", "index").is_indexed is True
+        assert col("f", "string").is_indexed is True
+        assert col("f", "string2").is_indexed is True
+
+        # specify index=columns
+        store.append("f2", df, index=["string"], data_columns=["string", "string2"])
+        assert col("f2", "index").is_indexed is False
+        assert col("f2", "string").is_indexed is True
+        assert col("f2", "string2").is_indexed is False
+
+        # try to index a non-table
+        _maybe_remove(store, "f2")
+        store.put("f2", df)
+        msg = "cannot create table index on a Fixed format store"
+        with pytest.raises(TypeError, match=msg):
+            store.create_table_index("f2")
+
+
+def test_create_table_index_data_columns_argument(setup_path):
+    # GH 28156
+
+    with ensure_clean_store(setup_path) as store:
+
+        def col(t, column):
+            return getattr(store.get_storer(t).table.cols, column)
+
+        # data columns
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((10, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=10, freq="B"),
+        )
+        df["string"] = "foo"
+        df["string2"] = "bar"
+        store.append("f", df, data_columns=["string"])
+        assert col("f", "index").is_indexed is True
+        assert col("f", "string").is_indexed is True
+
+        msg = "'Cols' object has no attribute 'string2'"
+        with pytest.raises(AttributeError, match=msg):
+            col("f", "string2").is_indexed
+
+        # try to index a col which isn't a data_column
+        msg = (
+            "column string2 is not a data_column.\n"
+            "In order to read column string2 you must reload the dataframe \n"
+            "into HDFStore and include string2 with the data_columns argument."
+        )
+        with pytest.raises(AttributeError, match=msg):
+            store.create_table_index("f", columns=["string2"])
+
+
+def test_mi_data_columns(setup_path):
+    # GH 14435
+    idx = MultiIndex.from_arrays(
+        [date_range("2000-01-01", periods=5), range(5)], names=["date", "id"]
+    )
+    df = DataFrame({"a": [1.1, 1.2, 1.3, 1.4, 1.5]}, index=idx)
+
+    with ensure_clean_store(setup_path) as store:
+        store.append("df", df, data_columns=True)
+
+        actual = store.select("df", where="id == 1")
+        expected = df.iloc[[1], :]
+        tm.assert_frame_equal(actual, expected)
+
+
+def test_table_mixed_dtypes(setup_path):
+    # frame
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+    df["obj1"] = "foo"
+    df["obj2"] = "bar"
+    df["bool1"] = df["A"] > 0
+    df["bool2"] = df["B"] > 0
+    df["bool3"] = True
+    df["int1"] = 1
+    df["int2"] = 2
+    df["timestamp1"] = Timestamp("20010102").as_unit("ns")
+    df["timestamp2"] = Timestamp("20010103").as_unit("ns")
+    df["datetime1"] = Timestamp("20010102").as_unit("ns")
+    df["datetime2"] = Timestamp("20010103").as_unit("ns")
+    df.loc[df.index[3:6], ["obj1"]] = np.nan
+    df = df._consolidate()
+
+    with ensure_clean_store(setup_path) as store:
+        store.append("df1_mixed", df)
+        tm.assert_frame_equal(store.select("df1_mixed"), df)
+
+
+def test_calendar_roundtrip_issue(setup_path):
+    # 8591
+    # doc example from tseries holiday section
+    weekmask_egypt = "Sun Mon Tue Wed Thu"
+    holidays = [
+        "2012-05-01",
+        dt.datetime(2013, 5, 1),
+        np.datetime64("2014-05-01"),
+    ]
+    bday_egypt = pd.offsets.CustomBusinessDay(
+        holidays=holidays, weekmask=weekmask_egypt
+    )
+    mydt = dt.datetime(2013, 4, 30)
+    dts = date_range(mydt, periods=5, freq=bday_egypt)
+
+    s = Series(dts.weekday, dts).map(Series("Mon Tue Wed Thu Fri Sat Sun".split()))
+
+    with ensure_clean_store(setup_path) as store:
+        store.put("fixed", s)
+        result = store.select("fixed")
+        tm.assert_series_equal(result, s)
+
+        store.append("table", s)
+        result = store.select("table")
+        tm.assert_series_equal(result, s)
+
+
+def test_remove(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        ts = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        store["a"] = ts
+        store["b"] = df
+        _maybe_remove(store, "a")
+        assert len(store) == 1
+        tm.assert_frame_equal(df, store["b"])
+
+        _maybe_remove(store, "b")
+        assert len(store) == 0
+
+        # nonexistence
+        with pytest.raises(
+            KeyError, match="'No object named a_nonexistent_store in the file'"
+        ):
+            store.remove("a_nonexistent_store")
+
+        # pathing
+        store["a"] = ts
+        store["b/foo"] = df
+        _maybe_remove(store, "foo")
+        _maybe_remove(store, "b/foo")
+        assert len(store) == 1
+
+        store["a"] = ts
+        store["b/foo"] = df
+        _maybe_remove(store, "b")
+        assert len(store) == 1
+
+        # __delitem__
+        store["a"] = ts
+        store["b"] = df
+        del store["a"]
+        del store["b"]
+        assert len(store) == 0
+
+
+def test_same_name_scoping(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((20, 2)),
+            index=date_range("20130101", periods=20),
+        )
+        store.put("df", df, format="table")
+        expected = df[df.index > Timestamp("20130105")]
+
+        result = store.select("df", "index>datetime.datetime(2013,1,5)")
+        tm.assert_frame_equal(result, expected)
+
+        # changes what 'datetime' points to in the namespace where
+        #  'select' does the lookup
+
+        # technically an error, but allow it
+        result = store.select("df", "index>datetime.datetime(2013,1,5)")
+        tm.assert_frame_equal(result, expected)
+
+        result = store.select("df", "index>datetime(2013,1,5)")
+        tm.assert_frame_equal(result, expected)
+
+
+def test_store_index_name(setup_path):
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+    df.index.name = "foo"
+
+    with ensure_clean_store(setup_path) as store:
+        store["frame"] = df
+        recons = store["frame"]
+        tm.assert_frame_equal(recons, df)
+
+
+@pytest.mark.parametrize("tz", [None, "US/Pacific"])
+@pytest.mark.parametrize("table_format", ["table", "fixed"])
+def test_store_index_name_numpy_str(tmp_path, table_format, setup_path, unit, tz):
+    # GH #13492
+    idx = DatetimeIndex(
+        [dt.date(2000, 1, 1), dt.date(2000, 1, 2)],
+        name="cols\u05d2",
+    ).tz_localize(tz)
+    idx1 = (
+        DatetimeIndex(
+            [dt.date(2010, 1, 1), dt.date(2010, 1, 2)],
+            name="rows\u05d0",
+        )
+        .as_unit(unit)
+        .tz_localize(tz)
+    )
+    df = DataFrame(np.arange(4).reshape(2, 2), columns=idx, index=idx1)
+
+    # This used to fail, returning numpy strings instead of python strings.
+    path = tmp_path / setup_path
+    df.to_hdf(path, key="df", format=table_format)
+    df2 = read_hdf(path, "df")
+
+    tm.assert_frame_equal(df, df2, check_names=True)
+
+    assert isinstance(df2.index.name, str)
+    assert isinstance(df2.columns.name, str)
+
+
+def test_store_series_name(setup_path):
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+    series = df["A"]
+
+    with ensure_clean_store(setup_path) as store:
+        store["series"] = series
+        recons = store["series"]
+        tm.assert_series_equal(recons, series)
+
+
+def test_overwrite_node(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        store["a"] = DataFrame(
+            np.random.default_rng(2).standard_normal((10, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=10, freq="B"),
+        )
+        ts = Series(
+            np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
+        )
+        store["a"] = ts
+
+        tm.assert_series_equal(store["a"], ts)
+
+
+def test_coordinates(setup_path):
+    df = DataFrame(
+        np.random.default_rng(2).standard_normal((10, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=date_range("2000-01-01", periods=10, freq="B"),
+    )
+
+    with ensure_clean_store(setup_path) as store:
+        _maybe_remove(store, "df")
+        store.append("df", df)
+
+        # all
+        c = store.select_as_coordinates("df")
+        assert (c.values == np.arange(len(df.index))).all()
+
+        # get coordinates back & test vs frame
+        _maybe_remove(store, "df")
+
+        df = DataFrame({"A": range(5), "B": range(5)})
+        store.append("df", df)
+        c = store.select_as_coordinates("df", ["index<3"])
+        assert (c.values == np.arange(3)).all()
+        result = store.select("df", where=c)
+        expected = df.loc[0:2, :]
+        tm.assert_frame_equal(result, expected)
+
+        c = store.select_as_coordinates("df", ["index>=3", "index<=4"])
+        assert (c.values == np.arange(2) + 3).all()
+        result = store.select("df", where=c)
+        expected = df.loc[3:4, :]
+        tm.assert_frame_equal(result, expected)
+        assert isinstance(c, Index)
+
+        # multiple tables
+        _maybe_remove(store, "df1")
+        _maybe_remove(store, "df2")
+        df1 = DataFrame(
+            np.random.default_rng(2).standard_normal((10, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=date_range("2000-01-01", periods=10, freq="B"),
+        )
+        df2 = df1.copy().rename(columns="{}_2".format)
+        store.append("df1", df1, data_columns=["A", "B"])
+        store.append("df2", df2)
+
+        c = store.select_as_coordinates("df1", ["A>0", "B>0"])
+        df1_result = store.select("df1", c)
+        df2_result = store.select("df2", c)
+        result = concat([df1_result, df2_result], axis=1)
+
+        expected = concat([df1, df2], axis=1)
+        expected = expected[(expected.A > 0) & (expected.B > 0)]
+        tm.assert_frame_equal(result, expected, check_freq=False)
+        # FIXME: 2021-01-18 on some (mostly windows) builds we get freq=None
+        #  but expect freq="18B"
+
+    # pass array/mask as the coordinates
+    with ensure_clean_store(setup_path) as store:
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((1000, 2)),
+            index=date_range("20000101", periods=1000),
+        )
+        store.append("df", df)
+        c = store.select_column("df", "index")
+        where = c[DatetimeIndex(c).month == 5].index
+        expected = df.iloc[where]
+
+        # locations
+        result = store.select("df", where=where)
+        tm.assert_frame_equal(result, expected)
+
+        # boolean
+        result = store.select("df", where=where)
+        tm.assert_frame_equal(result, expected)
+
+        # invalid
+        msg = (
+            "where must be passed as a string, PyTablesExpr, "
+            "or list-like of PyTablesExpr"
+        )
+        with pytest.raises(TypeError, match=msg):
+            store.select("df", where=np.arange(len(df), dtype="float64"))
+
+        with pytest.raises(TypeError, match=msg):
+            store.select("df", where=np.arange(len(df) + 1))
+
+        with pytest.raises(TypeError, match=msg):
+            store.select("df", where=np.arange(len(df)), start=5)
+
+        with pytest.raises(TypeError, match=msg):
+            store.select("df", where=np.arange(len(df)), start=5, stop=10)
+
+        # selection with filter
+        selection = date_range("20000101", periods=500)
+        result = store.select("df", where="index in selection")
+        expected = df[df.index.isin(selection)]
+        tm.assert_frame_equal(result, expected)
+
+        # list
+        df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+        store.append("df2", df)
+        result = store.select("df2", where=[0, 3, 5])
+        expected = df.iloc[[0, 3, 5]]
+        tm.assert_frame_equal(result, expected)
+
+        # boolean
+        where = [True] * 10
+        where[-2] = False
+        result = store.select("df2", where=where)
+        expected = df.loc[where]
+        tm.assert_frame_equal(result, expected)
+
+        # start/stop
+        result = store.select("df2", start=5, stop=10)
+        expected = df[5:10]
+        tm.assert_frame_equal(result, expected)
+
+
+def test_start_stop_table(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        # table
+        df = DataFrame(
+            {
+                "A": np.random.default_rng(2).random(20),
+                "B": np.random.default_rng(2).random(20),
+            }
+        )
+        store.append("df", df)
+
+        result = store.select("df", "columns=['A']", start=0, stop=5)
+        expected = df.loc[0:4, ["A"]]
+        tm.assert_frame_equal(result, expected)
+
+        # out of range
+        result = store.select("df", "columns=['A']", start=30, stop=40)
+        assert len(result) == 0
+        expected = df.loc[30:40, ["A"]]
+        tm.assert_frame_equal(result, expected)
+
+
+def test_start_stop_multiple(setup_path):
+    # GH 16209
+    with ensure_clean_store(setup_path) as store:
+        df = DataFrame({"foo": [1, 2], "bar": [1, 2]})
+
+        store.append_to_multiple(
+            {"selector": ["foo"], "data": None}, df, selector="selector"
+        )
+        result = store.select_as_multiple(
+            ["selector", "data"], selector="selector", start=0, stop=1
+        )
+        expected = df.loc[[0], ["foo", "bar"]]
+        tm.assert_frame_equal(result, expected)
+
+
+def test_start_stop_fixed(setup_path):
+    with ensure_clean_store(setup_path) as store:
+        # fixed, GH 8287
+        df = DataFrame(
+            {
+                "A": np.random.default_rng(2).random(20),
+                "B": np.random.default_rng(2).random(20),
+            },
+            index=date_range("20130101", periods=20),
+        )
+        store.put("df", df)
+
+        result = store.select("df", start=0, stop=5)
+        expected = df.iloc[0:5, :]
+        tm.assert_frame_equal(result, expected)
+
+        result = store.select("df", start=5, stop=10)
+        expected = df.iloc[5:10, :]
+        tm.assert_frame_equal(result, expected)
+
+        # out of range
+        result = store.select("df", start=30, stop=40)
+        expected = df.iloc[30:40, :]
+        tm.assert_frame_equal(result, expected)
+
+        # series
+        s = df.A
+        store.put("s", s)
+        result = store.select("s", start=0, stop=5)
+        expected = s.iloc[0:5]
+        tm.assert_series_equal(result, expected)
+
+        result = store.select("s", start=5, stop=10)
+        expected = s.iloc[5:10]
+        tm.assert_series_equal(result, expected)
+
+        # sparse; not implemented
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD"), dtype=object),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        df.iloc[3:5, 1:3] = np.nan
+        df.iloc[8:10, -2] = np.nan
+
+
+def test_select_filter_corner(setup_path):
+    df = DataFrame(np.random.default_rng(2).standard_normal((50, 100)))
+    df.index = [f"{c:3d}" for c in df.index]
+    df.columns = [f"{c:3d}" for c in df.columns]
+
+    with ensure_clean_store(setup_path) as store:
+        store.put("frame", df, format="table")
+
+        crit = "columns=df.columns[:75]"
+        result = store.select("frame", [crit])
+        tm.assert_frame_equal(result, df.loc[:, df.columns[:75]])
+
+        crit = "columns=df.columns[:75:2]"
+        result = store.select("frame", [crit])
+        tm.assert_frame_equal(result, df.loc[:, df.columns[:75:2]])
+
+
+def test_path_pathlib():
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+
+    result = tm.round_trip_pathlib(
+        lambda p: df.to_hdf(p, key="df"), lambda p: read_hdf(p, "df")
+    )
+    tm.assert_frame_equal(df, result)
+
+
+@pytest.mark.parametrize("start, stop", [(0, 2), (1, 2), (None, None)])
+def test_contiguous_mixed_data_table(start, stop, setup_path):
+    # GH 17021
+    df = DataFrame(
+        {
+            "a": Series([20111010, 20111011, 20111012]),
+            "b": Series(["ab", "cd", "ab"]),
+        }
+    )
+
+    with ensure_clean_store(setup_path) as store:
+        store.append("test_dataset", df)
+
+        result = store.select("test_dataset", start=start, stop=stop)
+        tm.assert_frame_equal(df[start:stop], result)
+
+
+def test_path_pathlib_hdfstore():
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+
+    def writer(path):
+        with HDFStore(path) as store:
+            df.to_hdf(store, key="df")
+
+    def reader(path):
+        with HDFStore(path) as store:
+            return read_hdf(store, "df")
+
+    result = tm.round_trip_pathlib(writer, reader)
+    tm.assert_frame_equal(df, result)
+
+
+def test_pickle_path_localpath():
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+    result = tm.round_trip_pathlib(
+        lambda p: df.to_hdf(p, key="df"), lambda p: read_hdf(p, "df")
+    )
+    tm.assert_frame_equal(df, result)
+
+
+def test_path_localpath_hdfstore():
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+
+    def writer(path):
+        with HDFStore(path) as store:
+            df.to_hdf(store, key="df")
+
+    def reader(path):
+        with HDFStore(path) as store:
+            return read_hdf(store, "df")
+
+    result = tm.round_trip_localpath(writer, reader)
+    tm.assert_frame_equal(df, result)
+
+
+@pytest.mark.parametrize("propindexes", [True, False])
+def test_copy(propindexes):
+    df = DataFrame(
+        1.1 * np.arange(120).reshape((30, 4)),
+        columns=Index(list("ABCD"), dtype=object),
+        index=Index([f"i-{i}" for i in range(30)], dtype=object),
+    )
+
+    with tm.ensure_clean() as path:
+        with HDFStore(path) as st:
+            st.append("df", df, data_columns=["A"])
+        with tempfile.NamedTemporaryFile() as new_f:
+            with HDFStore(path) as store:
+                with contextlib.closing(
+                    store.copy(new_f.name, keys=None, propindexes=propindexes)
+                ) as tstore:
+                    # check keys
+                    keys = store.keys()
+                    assert set(keys) == set(tstore.keys())
+                    # check indices & nrows
+                    for k in tstore.keys():
+                        if tstore.get_storer(k).is_table:
+                            new_t = tstore.get_storer(k)
+                            orig_t = store.get_storer(k)
+
+                            assert orig_t.nrows == new_t.nrows
+
+                            # check propindixes
+                            if propindexes:
+                                for a in orig_t.axes:
+                                    if a.is_indexed:
+                                        assert new_t[a.name].is_indexed
+
+
+def test_duplicate_column_name(tmp_path, setup_path):
+    df = DataFrame(columns=["a", "a"], data=[[0, 0]])
+
+    path = tmp_path / setup_path
+    msg = "Columns index has to be unique for fixed format"
+    with pytest.raises(ValueError, match=msg):
+        df.to_hdf(path, key="df", format="fixed")
+
+    df.to_hdf(path, key="df", format="table")
+    other = read_hdf(path, "df")
+
+    tm.assert_frame_equal(df, other)
+    assert df.equals(other)
+    assert other.equals(df)
+
+
+def test_preserve_timedeltaindex_type(setup_path):
+    # GH9635
+    df = DataFrame(np.random.default_rng(2).normal(size=(10, 5)))
+    df.index = timedelta_range(start="0s", periods=10, freq="1s", name="example")
+
+    with ensure_clean_store(setup_path) as store:
+        store["df"] = df
+        tm.assert_frame_equal(store["df"], df)
+
+
+def test_columns_multiindex_modified(tmp_path, setup_path):
+    # BUG: 7212
+
+    df = DataFrame(
+        np.random.default_rng(2).random((4, 5)),
+        index=list("abcd"),
+        columns=list("ABCDE"),
+    )
+    df.index.name = "letters"
+    df = df.set_index(keys="E", append=True)
+
+    data_columns = df.index.names + df.columns.tolist()
+    path = tmp_path / setup_path
+    df.to_hdf(
+        path,
+        key="df",
+        mode="a",
+        append=True,
+        data_columns=data_columns,
+        index=False,
+    )
+    cols2load = list("BCD")
+    cols2load_original = list(cols2load)
+    # GH#10055 make sure read_hdf call does not alter cols2load inplace
+    read_hdf(path, "df", columns=cols2load)
+    assert cols2load_original == cols2load
+
+
+@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
+@pytest.mark.parametrize(
+    "columns",
+    [
+        Index([0, 1], dtype=np.int64),
+        Index([0.0, 1.0], dtype=np.float64),
+        date_range("2020-01-01", periods=2),
+        timedelta_range("1 day", periods=2),
+        period_range("2020-01-01", periods=2, freq="D"),
+    ],
+)
+def test_to_hdf_with_object_column_names_should_fail(tmp_path, setup_path, columns):
+    # GH9057
+    df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)), columns=columns)
+    path = tmp_path / setup_path
+    msg = "cannot have non-object label DataIndexableCol"
+    with pytest.raises(ValueError, match=msg):
+        df.to_hdf(path, key="df", format="table", data_columns=True)
+
+
+@pytest.mark.parametrize("dtype", [None, "category"])
+def test_to_hdf_with_object_column_names_should_run(tmp_path, setup_path, dtype):
+    # GH9057
+    df = DataFrame(
+        np.random.default_rng(2).standard_normal((10, 2)),
+        columns=Index(["a", "b"], dtype=dtype),
+    )
+    path = tmp_path / setup_path
+    df.to_hdf(path, key="df", format="table", data_columns=True)
+    result = read_hdf(path, "df", where=f"index = [{df.index[0]}]")
+    assert len(result)
+
+
+def test_hdfstore_strides(setup_path):
+    # GH22073
+    df = DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
+    with ensure_clean_store(setup_path) as store:
+        store.put("df", df)
+        assert df["a"].values.strides == store["df"]["a"].values.strides
+
+
+def test_store_bool_index(tmp_path, setup_path):
+    # GH#48667
+    df = DataFrame([[1]], columns=[True], index=Index([False], dtype="bool"))
+    expected = df.copy()
+
+    # # Test to make sure defaults are to not drop.
+    # # Corresponding to Issue 9382
+    path = tmp_path / setup_path
+    df.to_hdf(path, key="a")
+    result = read_hdf(path, "a")
+    tm.assert_frame_equal(expected, result)
diff --git a/shared/package-files/7c/7cdb06db72884ae63e939245a17fb9859eea19049c8ac5ee1dc744c189573aac/hip_assert.h b/shared/package-files/7c/7cdb06db72884ae63e939245a17fb9859eea19049c8ac5ee1dc744c189573aac/hip_assert.h
new file mode 100644
index 0000000000000000000000000000000000000000..7d634eae0df3a94002d697d641f367ebb5226a2a
--- /dev/null
+++ b/shared/package-files/7c/7cdb06db72884ae63e939245a17fb9859eea19049c8ac5ee1dc744c189573aac/hip_assert.h
@@ -0,0 +1,101 @@
+/*
+Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#pragma once
+
+// abort
+extern "C" __device__ inline __attribute__((weak))
+void abort() {
+  __builtin_trap();
+}
+
+// The noinline attribute helps encapsulate the printf expansion,
+// which otherwise has a performance impact just by increasing the
+// size of the calling function. Additionally, the weak attribute
+// allows the function to exist as a global although its definition is
+// included in every compilation unit.
+#if defined(_WIN32) || defined(_WIN64)
+extern "C" __device__ __attribute__((noinline)) __attribute__((weak))
+void _wassert(const wchar_t *_msg, const wchar_t *_file, unsigned _line) {
+    // FIXME: Need `wchar_t` support to generate assertion message.
+    __builtin_trap();
+}
+#else /* defined(_WIN32) || defined(_WIN64) */
+extern "C" __device__ __attribute__((noinline)) __attribute__((weak))
+void __assert_fail(const char *assertion,
+                   const char *file,
+                   unsigned int line,
+                   const char *function)
+{
+  const char fmt[] = "%s:%u: %s: Device-side assertion `%s' failed.\n";
+
+  // strlen is not available as a built-in yet, so we create our own
+  // loop in a macro. With a string literal argument, the compiler
+  // usually manages to replace the loop with a constant.
+  //
+  // The macro does not check for null pointer, since all the string
+  // arguments are defined to be constant literals when called from
+  // the assert() macro.
+  //
+  // NOTE: The loop below includes the null terminator in the length
+  // as required by append_string_n().
+#define __hip_get_string_length(LEN, STR)       \
+  do {                                          \
+    const char *tmp = STR;                      \
+    while (*tmp++);                             \
+    LEN = tmp - STR;                            \
+  } while (0)
+
+  auto msg = __ockl_fprintf_stderr_begin();
+  int len = 0;
+  __hip_get_string_length(len, fmt);
+  msg = __ockl_fprintf_append_string_n(msg, fmt, len, 0);
+  __hip_get_string_length(len, file);
+  msg = __ockl_fprintf_append_string_n(msg, file, len, 0);
+  msg = __ockl_fprintf_append_args(msg, 1, line, 0, 0, 0, 0, 0, 0, 0);
+  __hip_get_string_length(len, function);
+  msg = __ockl_fprintf_append_string_n(msg, function, len, 0);
+  __hip_get_string_length(len, assertion);
+  __ockl_fprintf_append_string_n(msg, assertion, len, /* is_last = */ 1);
+
+#undef __hip_get_string_length
+
+  __builtin_trap();
+}
+
+extern "C" __device__ __attribute__((noinline)) __attribute__((weak))
+void __assertfail()
+{
+    // ignore all the args for now.
+    __builtin_trap();
+}
+#endif /* defined(_WIN32) || defined(_WIN64) */
+
+#if defined(NDEBUG)
+#define __hip_assert(COND)
+#else
+#define __hip_assert(COND)                          \
+  do {                                              \
+    if (!(COND))                                    \
+      __builtin_trap();                             \
+  } while (0)
+#endif
diff --git a/shared/package-files/a5/a5008cb3df9d1e527cb845b8ac39fb9657501eaf32ad6daddf01643c8304dd91/prufer.cpython-311.pyc b/shared/package-files/a5/a5008cb3df9d1e527cb845b8ac39fb9657501eaf32ad6daddf01643c8304dd91/prufer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f2c23da5d258933d595361d8b91a669f9c61e22
Binary files /dev/null and b/shared/package-files/a5/a5008cb3df9d1e527cb845b8ac39fb9657501eaf32ad6daddf01643c8304dd91/prufer.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a5064b2b9cc1440235fd1a66a6ebfb2e1476e156c54113703cd33d97a1cd019b/hfile_s3.c b/shared/package-files/a5/a5064b2b9cc1440235fd1a66a6ebfb2e1476e156c54113703cd33d97a1cd019b/hfile_s3.c
new file mode 100644
index 0000000000000000000000000000000000000000..c7c52e617842c96fd34c32b9358bde82b672cbe3
--- /dev/null
+++ b/shared/package-files/a5/a5064b2b9cc1440235fd1a66a6ebfb2e1476e156c54113703cd33d97a1cd019b/hfile_s3.c
@@ -0,0 +1,1442 @@
+/*  hfile_s3.c -- Amazon S3 backend for low-level file streams.
+
+    Copyright (C) 2015-2017, 2019-2024 Genome Research Ltd.
+
+    Author: John Marshall 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include "hfile_internal.h"
+#ifdef ENABLE_PLUGINS
+#include "version.h"
+#endif
+#include "htslib/hts.h"  // for hts_version() and hts_verbose
+#include "htslib/kstring.h"
+#include "hts_time_funcs.h"
+
+typedef struct s3_auth_data {
+    kstring_t id;
+    kstring_t token;
+    kstring_t secret;
+    kstring_t region;
+    kstring_t canonical_query_string;
+    kstring_t user_query_string;
+    kstring_t host;
+    kstring_t profile;
+    enum {s3_auto, s3_virtual, s3_path} url_style;
+    time_t creds_expiry_time;
+    char *bucket;
+    kstring_t auth_hdr;
+    time_t auth_time;
+    char date[40];
+    char date_long[17];
+    char date_short[9];
+    kstring_t date_html;
+    char mode;
+    char *headers[5];
+    int refcount;
+} s3_auth_data;
+
+#define AUTH_LIFETIME 60  // Regenerate auth headers if older than this
+#define CREDENTIAL_LIFETIME 60 // Seconds before expiry to reread credentials
+
+#if defined HAVE_COMMONCRYPTO
+
+#include 
+
+#define DIGEST_BUFSIZ CC_SHA1_DIGEST_LENGTH
+#define SHA256_DIGEST_BUFSIZE CC_SHA256_DIGEST_LENGTH
+#define HASH_LENGTH_SHA256 (SHA256_DIGEST_BUFSIZE * 2) + 1
+
+static size_t
+s3_sign(unsigned char *digest, kstring_t *key, kstring_t *message)
+{
+    CCHmac(kCCHmacAlgSHA1, key->s, key->l, message->s, message->l, digest);
+    return CC_SHA1_DIGEST_LENGTH;
+}
+
+
+static void s3_sha256(const unsigned char *in, size_t length, unsigned char *out) {
+    CC_SHA256(in, length, out);
+}
+
+
+static void s3_sign_sha256(const void *key, int key_len, const unsigned char *d, int n, unsigned char *md, unsigned int *md_len) {
+    CCHmac(kCCHmacAlgSHA256, key, key_len, d, n, md);
+    *md_len = CC_SHA256_DIGEST_LENGTH;
+}
+
+
+#elif defined HAVE_HMAC
+
+#include 
+#include 
+
+#define DIGEST_BUFSIZ EVP_MAX_MD_SIZE
+#define SHA256_DIGEST_BUFSIZE SHA256_DIGEST_LENGTH
+#define HASH_LENGTH_SHA256 (SHA256_DIGEST_BUFSIZE * 2) + 1
+
+static size_t
+s3_sign(unsigned char *digest, kstring_t *key, kstring_t *message)
+{
+    unsigned int len;
+    HMAC(EVP_sha1(), key->s, key->l,
+         (unsigned char *) message->s, message->l, digest, &len);
+    return len;
+}
+
+
+static void s3_sha256(const unsigned char *in, size_t length, unsigned char *out) {
+    SHA256(in, length, out);
+}
+
+
+static void s3_sign_sha256(const void *key, int key_len, const unsigned char *d, int n, unsigned char *md, unsigned int *md_len) {
+    HMAC(EVP_sha256(), key, key_len, d, n, md, md_len);
+}
+
+#else
+#error No HMAC() routine found by configure
+#endif
+
+static void
+urldecode_kput(const char *s, int len, kstring_t *str)
+{
+    char buf[3];
+    int i = 0;
+
+    while (i < len)
+        if (s[i] == '%' && i+2 < len) {
+            buf[0] = s[i+1], buf[1] = s[i+2], buf[2] = '\0';
+            kputc(strtol(buf, NULL, 16), str);
+            i += 3;
+        }
+        else kputc(s[i++], str);
+}
+
+static void base64_kput(const unsigned char *data, size_t len, kstring_t *str)
+{
+    static const char base64[] =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+    size_t i = 0;
+    unsigned x = 0;
+    int bits = 0, pad = 0;
+
+    while (bits || i < len) {
+        if (bits < 6) {
+            x <<= 8, bits += 8;
+            if (i < len) x |= data[i++];
+            else pad++;
+        }
+
+        bits -= 6;
+        kputc(base64[(x >> bits) & 63], str);
+    }
+
+    str->l -= pad;
+    kputsn("==", pad, str);
+}
+
+static int is_dns_compliant(const char *s0, const char *slim, int is_https)
+{
+    int has_nondigit = 0, len = 0;
+    const char *s;
+
+    for (s = s0; s < slim; len++, s++)
+        if (islower_c(*s))
+            has_nondigit = 1;
+        else if (*s == '-') {
+            has_nondigit = 1;
+            if (s == s0 || s+1 == slim) return 0;
+        }
+        else if (isdigit_c(*s))
+            ;
+        else if (*s == '.') {
+            if (is_https) return 0;
+            if (s == s0 || ! isalnum_c(s[-1])) return 0;
+            if (s+1 == slim || ! isalnum_c(s[1])) return 0;
+        }
+        else return 0;
+
+    return has_nondigit && len >= 3 && len <= 63;
+}
+
+static FILE *expand_tilde_open(const char *fname, const char *mode)
+{
+    FILE *fp;
+
+    if (strncmp(fname, "~/", 2) == 0) {
+        kstring_t full_fname = { 0, 0, NULL };
+        const char *home = getenv("HOME");
+        if (! home) return NULL;
+
+        kputs(home, &full_fname);
+        kputs(&fname[1], &full_fname);
+
+        fp = fopen(full_fname.s, mode);
+        free(full_fname.s);
+    }
+    else
+        fp = fopen(fname, mode);
+
+    return fp;
+}
+
+static void parse_ini(const char *fname, const char *section, ...)
+{
+    kstring_t line = { 0, 0, NULL };
+    int active = 1;  // Start active, so global properties are accepted
+    char *s;
+
+    FILE *fp = expand_tilde_open(fname, "r");
+    if (fp == NULL) return;
+
+    while (line.l = 0, kgetline(&line, (kgets_func *) fgets, fp) >= 0)
+        if (line.s[0] == '[' && (s = strchr(line.s, ']')) != NULL) {
+            *s = '\0';
+            active = (strcmp(&line.s[1], section) == 0);
+        }
+        else if (active && (s = strpbrk(line.s, ":=")) != NULL) {
+            const char *key = line.s, *value = &s[1], *akey;
+            va_list args;
+
+            while (isspace_c(*key)) key++;
+            while (s > key && isspace_c(s[-1])) s--;
+            *s = '\0';
+
+            while (isspace_c(*value)) value++;
+            while (line.l > 0 && isspace_c(line.s[line.l-1]))
+                line.s[--line.l] = '\0';
+
+            va_start(args, section);
+            while ((akey = va_arg(args, const char *)) != NULL) {
+                kstring_t *avar = va_arg(args, kstring_t *);
+                if (strcmp(key, akey) == 0) {
+                    avar->l = 0;
+                    kputs(value, avar);
+                    break; }
+            }
+            va_end(args);
+        }
+
+    fclose(fp);
+    free(line.s);
+}
+
+static void parse_simple(const char *fname, kstring_t *id, kstring_t *secret)
+{
+    kstring_t text = { 0, 0, NULL };
+    char *s;
+    size_t len;
+
+    FILE *fp = expand_tilde_open(fname, "r");
+    if (fp == NULL) return;
+
+    while (kgetline(&text, (kgets_func *) fgets, fp) >= 0)
+        kputc(' ', &text);
+    fclose(fp);
+
+    s = text.s;
+    while (isspace_c(*s)) s++;
+    kputsn(s, len = strcspn(s, " \t"), id);
+
+    s += len;
+    while (isspace_c(*s)) s++;
+    kputsn(s, strcspn(s, " \t"), secret);
+
+    free(text.s);
+}
+
+static int copy_auth_headers(s3_auth_data *ad, char ***hdrs) {
+    char **hdr = &ad->headers[0];
+    int idx = 0;
+    *hdrs = hdr;
+
+    hdr[idx] = strdup(ad->date);
+    if (!hdr[idx]) return -1;
+    idx++;
+
+    if (ad->token.l) {
+        kstring_t token_hdr = KS_INITIALIZE;
+        kputs("X-Amz-Security-Token: ", &token_hdr);
+        kputs(ad->token.s, &token_hdr);
+        if (token_hdr.s) {
+            hdr[idx++] = token_hdr.s;
+        } else {
+            goto fail;
+        }
+    }
+
+    if (ad->auth_hdr.l) {
+        hdr[idx] = strdup(ad->auth_hdr.s);
+        if (!hdr[idx]) goto fail;
+        idx++;
+    }
+
+    hdr[idx] = NULL;
+    return 0;
+
+ fail:
+    for (--idx; idx >= 0; --idx)
+        free(hdr[idx]);
+    return -1;
+}
+
+static void free_auth_data(s3_auth_data *ad) {
+    if (ad->refcount > 0) {
+        --ad->refcount;
+        return;
+    }
+    free(ad->profile.s);
+    free(ad->id.s);
+    free(ad->token.s);
+    free(ad->secret.s);
+    free(ad->region.s);
+    free(ad->canonical_query_string.s);
+    free(ad->user_query_string.s);
+    free(ad->host.s);
+    free(ad->bucket);
+    free(ad->auth_hdr.s);
+    free(ad->date_html.s);
+    free(ad);
+}
+
+static time_t parse_rfc3339_date(kstring_t *datetime)
+{
+    int offset = 0;
+    time_t when;
+    int num;
+    char should_be_t = '\0', timezone[10] = { '\0' };
+    unsigned int year, mon, day, hour, min, sec;
+
+    if (!datetime->s)
+        return 0;
+
+    // It should be possible to do this with strptime(), but it seems
+    // to not get on with our feature definitions.
+    num = sscanf(datetime->s, "%4u-%2u-%2u%c%2u:%2u:%2u%9s",
+                 &year, &mon, &day, &should_be_t, &hour, &min, &sec, timezone);
+    if (num < 8)
+        return 0;
+    if (should_be_t != 'T' && should_be_t != 't' && should_be_t != ' ')
+        return 0;
+    struct tm parsed = { sec, min, hour, day, mon - 1, year - 1900, 0, 0, 0 };
+
+    switch (timezone[0]) {
+      case 'Z':
+      case 'z':
+      case '\0':
+          break;
+      case '+':
+      case '-': {
+          unsigned hr_off, min_off;
+          if (sscanf(timezone + 1, "%2u:%2u", &hr_off, &min_off)) {
+              if (hr_off < 24 && min_off <= 60) {
+                  offset = ((hr_off * 60 + min_off)
+                            * (timezone[0] == '+' ? -60 : 60));
+              }
+          }
+          break;
+      }
+      default:
+          return 0;
+    }
+
+    when = hts_time_gm(&parsed);
+    return when >= 0 ? when + offset : 0;
+}
+
+static void refresh_auth_data(s3_auth_data *ad) {
+    // Basically a copy of the AWS_SHARED_CREDENTIALS_FILE part of
+    // setup_auth_data(), but this only reads the authorisation parts.
+    const char *v = getenv("AWS_SHARED_CREDENTIALS_FILE");
+    kstring_t expiry_time = KS_INITIALIZE;
+    parse_ini(v? v : "~/.aws/credentials", ad->profile.s,
+              "aws_access_key_id", &ad->id,
+              "aws_secret_access_key", &ad->secret,
+              "aws_session_token", &ad->token,
+              "expiry_time", &expiry_time);
+    if (expiry_time.l) {
+        ad->creds_expiry_time = parse_rfc3339_date(&expiry_time);
+    }
+    ks_free(&expiry_time);
+}
+
+static int auth_header_callback(void *ctx, char ***hdrs) {
+    s3_auth_data *ad = (s3_auth_data *) ctx;
+
+    time_t now = time(NULL);
+#ifdef HAVE_GMTIME_R
+    struct tm tm_buffer;
+    struct tm *tm = gmtime_r(&now, &tm_buffer);
+#else
+    struct tm *tm = gmtime(&now);
+#endif
+    kstring_t message = { 0, 0, NULL };
+    unsigned char digest[DIGEST_BUFSIZ];
+    size_t digest_len;
+
+    if (!hdrs) { // Closing connection
+        free_auth_data(ad);
+        return 0;
+    }
+
+    if (ad->creds_expiry_time > 0
+        && ad->creds_expiry_time - now < CREDENTIAL_LIFETIME) {
+        refresh_auth_data(ad);
+    } else if (now - ad->auth_time < AUTH_LIFETIME) {
+        // Last auth string should still be valid
+        *hdrs = NULL;
+        return 0;
+    }
+
+    strftime(ad->date, sizeof(ad->date), "Date: %a, %d %b %Y %H:%M:%S GMT", tm);
+    if (!ad->id.l || !ad->secret.l) {
+        ad->auth_time = now;
+        return copy_auth_headers(ad, hdrs);
+    }
+
+    if (ksprintf(&message, "%s\n\n\n%s\n%s%s%s%s",
+                 ad->mode == 'r' ? "GET" : "PUT", ad->date + 6,
+                 ad->token.l ? "x-amz-security-token:" : "",
+                 ad->token.l ? ad->token.s : "",
+                 ad->token.l ? "\n" : "",
+                 ad->bucket) < 0) {
+        return -1;
+    }
+
+    digest_len = s3_sign(digest, &ad->secret, &message);
+    ad->auth_hdr.l = 0;
+    if (ksprintf(&ad->auth_hdr, "Authorization: AWS %s:", ad->id.s) < 0)
+        goto fail;
+    base64_kput(digest, digest_len, &ad->auth_hdr);
+
+    free(message.s);
+    ad->auth_time = now;
+    return copy_auth_headers(ad, hdrs);
+
+ fail:
+    free(message.s);
+    return -1;
+}
+
+
+/* like a escape path but for query strings '=' and '&' are untouched */
+static char *escape_query(const char *qs) {
+    size_t i, j = 0, length, alloced;
+    char *escaped;
+
+    length = strlen(qs);
+    alloced = length * 3 + 1;
+    if ((escaped = malloc(alloced)) == NULL) {
+        return NULL;
+    }
+
+    for (i = 0; i < length; i++) {
+        int c = qs[i];
+
+        if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
+             c == '_' || c == '-' || c == '~' || c == '.' || c == '/' || c == '=' || c == '&') {
+            escaped[j++] = c;
+        } else {
+            snprintf(escaped + j, alloced - j, "%%%02X", c);
+            j += 3;
+        }
+    }
+
+    escaped[j] = '\0';
+
+    return escaped;
+}
+
+
+static char *escape_path(const char *path) {
+    size_t i, j = 0, length, alloced;
+    char *escaped;
+
+    length = strlen(path);
+    alloced = length * 3 + 1;
+
+    if ((escaped = malloc(alloced)) == NULL) {
+        return NULL;
+    }
+
+    for (i = 0; i < length; i++) {
+        int c = path[i];
+
+        if (c == '?') break; // don't escape ? or beyond
+
+        if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
+             c == '_' || c == '-' || c == '~' || c == '.' || c == '/') {
+            escaped[j++] = c;
+        } else {
+            snprintf(escaped + j, alloced - j, "%%%02X", c);
+            j += 3;
+        }
+    }
+
+    if (i != length) {
+        // in the case of a '?' copy the rest of the path across unchanged
+        strcpy(escaped + j, path + i);
+    } else {
+        escaped[j] = '\0';
+    }
+
+    return escaped;
+}
+
+
+static int is_escaped(const char *str) {
+    const char *c = str;
+    int escaped = 0;
+    int needs_escape = 0;
+
+    while (*c != '\0') {
+        if (*c == '%' && c[1] != '\0' && c[2] != '\0') {
+            if (isxdigit_c(c[1]) && isxdigit_c(c[2])) {
+                escaped = 1;
+                c += 3;
+                continue;
+            } else {
+                // only escaped if all % signs are escaped
+                escaped = 0;
+            }
+        }
+        if (!((*c >= '0' && *c <= '9') || (*c >= 'A' && *c <= 'Z')
+              || (*c >= 'a' && *c <= 'z') ||
+              *c == '_' || *c == '-' || *c == '~' || *c == '.' || *c == '/')) {
+            needs_escape = 1;
+        }
+        c++;
+    }
+
+    return escaped || !needs_escape;
+}
+
+static int redirect_endpoint_callback(void *auth, long response,
+                                      kstring_t *header, kstring_t *url) {
+    s3_auth_data *ad = (s3_auth_data *)auth;
+    char *new_region;
+    char *end;
+    int ret = -1;
+
+    // get the new region from the reply header
+    if ((new_region = strstr(header->s, "x-amz-bucket-region: "))) {
+
+        new_region += strlen("x-amz-bucket-region: ");
+        end = new_region;
+
+        while (isalnum_c(*end) || ispunct_c(*end)) end++;
+
+        *end = 0;
+
+        if (strstr(ad->host.s, "amazonaws.com")) {
+            ad->region.l = 0;
+            kputs(new_region, &ad->region);
+
+            ad->host.l = 0;
+
+            if (ad->url_style == s3_path) {
+                // Path style https://s3.{region-code}.amazonaws.com/{bucket-name}/{key-name}
+                ksprintf(&ad->host, "s3.%s.amazonaws.com", new_region);
+            } else {
+                // Virtual https://{bucket-name}.s3.{region-code}.amazonaws.com/{key-name}
+                // Extract the {bucket-name} from {ad->host} to include in subdomain
+                kstring_t url_prefix = KS_INITIALIZE;
+                kputsn(ad->host.s, strcspn(ad->host.s, "."), &url_prefix);
+
+                ksprintf(&ad->host, "%s.s3.%s.amazonaws.com", url_prefix.s, new_region);
+                free(url_prefix.s);
+            }
+            if (ad->region.l && ad->host.l) {
+               int e = 0;
+               url->l = 0;
+               e |= kputs("https://", url) < 0;
+               e |= kputs(ad->host.s, url) < 0;
+               e |= kputsn(ad->bucket, strlen(ad->bucket), url) < 0;
+
+               if (!e)
+                   ret = 0;
+            }
+            if (ad->user_query_string.l) {
+                kputc('?', url);
+                kputsn(ad->user_query_string.s, ad->user_query_string.l, url);
+            }
+        }
+    }
+
+    return ret;
+}
+
+static s3_auth_data * setup_auth_data(const char *s3url, const char *mode,
+                                      int sigver, kstring_t *url)
+{
+    s3_auth_data *ad = calloc(1, sizeof(*ad));
+    const char *bucket, *path;
+    char *escaped = NULL;
+    size_t url_path_pos;
+    ptrdiff_t bucket_len;
+    int is_https = 1, dns_compliant;
+    char *query_start;
+
+    if (!ad)
+        return NULL;
+    ad->mode = strchr(mode, 'r') ? 'r' : 'w';
+    ad->url_style = s3_auto;
+
+    // Our S3 URL format is s3[+SCHEME]://[ID[:SECRET[:TOKEN]]@]BUCKET/PATH
+
+    if (s3url[2] == '+') {
+        bucket = strchr(s3url, ':') + 1;
+        if (bucket == NULL) {
+            free(ad);
+            return NULL;
+        }
+        kputsn(&s3url[3], bucket - &s3url[3], url);
+        is_https = strncmp(url->s, "https:", 6) == 0;
+    }
+    else {
+        kputs("https:", url);
+        bucket = &s3url[3];
+    }
+    while (*bucket == '/') kputc(*bucket++, url);
+
+    path = bucket + strcspn(bucket, "/?#@");
+
+    if (*path == '@') {
+        const char *colon = strpbrk(bucket, ":@");
+        if (*colon != ':') {
+            urldecode_kput(bucket, colon - bucket, &ad->profile);
+        }
+        else {
+            const char *colon2 = strpbrk(&colon[1], ":@");
+            urldecode_kput(bucket, colon - bucket, &ad->id);
+            urldecode_kput(&colon[1], colon2 - &colon[1], &ad->secret);
+            if (*colon2 == ':')
+                urldecode_kput(&colon2[1], path - &colon2[1], &ad->token);
+        }
+
+        bucket = &path[1];
+        path = bucket + strcspn(bucket, "/?#");
+    }
+    else {
+        // If the URL has no ID[:SECRET]@, consider environment variables.
+        const char *v;
+        if ((v = getenv("AWS_ACCESS_KEY_ID")) != NULL) kputs(v, &ad->id);
+        if ((v = getenv("AWS_SECRET_ACCESS_KEY")) != NULL) kputs(v, &ad->secret);
+        if ((v = getenv("AWS_SESSION_TOKEN")) != NULL) kputs(v, &ad->token);
+        if ((v = getenv("AWS_DEFAULT_REGION")) != NULL) kputs(v, &ad->region);
+        if ((v = getenv("HTS_S3_HOST")) != NULL) kputs(v, &ad->host);
+
+        if ((v = getenv("AWS_DEFAULT_PROFILE")) != NULL) kputs(v, &ad->profile);
+        else if ((v = getenv("AWS_PROFILE")) != NULL) kputs(v, &ad->profile);
+        else kputs("default", &ad->profile);
+
+        if ((v = getenv("HTS_S3_ADDRESS_STYLE")) != NULL) {
+            if (strcasecmp(v, "virtual") == 0) {
+                ad->url_style = s3_virtual;
+            } else if (strcasecmp(v, "path") == 0) {
+                ad->url_style = s3_path;
+            }
+        }
+    }
+
+    if (ad->id.l == 0) {
+        kstring_t url_style = KS_INITIALIZE;
+        kstring_t expiry_time = KS_INITIALIZE;
+        const char *v = getenv("AWS_SHARED_CREDENTIALS_FILE");
+        parse_ini(v? v : "~/.aws/credentials", ad->profile.s,
+                  "aws_access_key_id", &ad->id,
+                  "aws_secret_access_key", &ad->secret,
+                  "aws_session_token", &ad->token,
+                  "region", &ad->region,
+                  "addressing_style", &url_style,
+                  "expiry_time", &expiry_time,
+                  NULL);
+
+        if (url_style.l) {
+            if (strcmp(url_style.s, "virtual") == 0) {
+                ad->url_style = s3_virtual;
+            } else if (strcmp(url_style.s, "path") == 0) {
+                ad->url_style = s3_path;
+            } else {
+                ad->url_style = s3_auto;
+            }
+        }
+        if (expiry_time.l) {
+            // Not a real part of the AWS configuration file, but it allows
+            // support for short-term credentials like those for the IAM
+            // service.  The botocore library uses the key "expiry_time"
+            // internally for this purpose.
+            // See https://github.com/boto/botocore/blob/develop/botocore/credentials.py
+            ad->creds_expiry_time = parse_rfc3339_date(&expiry_time);
+        }
+
+        ks_free(&url_style);
+        ks_free(&expiry_time);
+    }
+
+    if (ad->id.l == 0) {
+        kstring_t url_style = KS_INITIALIZE;
+        const char *v = getenv("HTS_S3_S3CFG");
+        parse_ini(v? v : "~/.s3cfg", ad->profile.s, "access_key", &ad->id,
+                  "secret_key", &ad->secret, "access_token", &ad->token,
+                  "host_base", &ad->host,
+                  "bucket_location", &ad->region,
+                  "host_bucket", &url_style,
+                  NULL);
+
+        if (url_style.l) {
+            // Conforming to s3cmd's GitHub PR#416, host_bucket without the "%(bucket)s" string
+            // indicates use of path style adressing.
+            if (strstr(url_style.s, "%(bucket)s") == NULL) {
+                ad->url_style = s3_path;
+            } else {
+                ad->url_style = s3_auto;
+            }
+        }
+
+        ks_free(&url_style);
+    }
+
+    if (ad->id.l == 0)
+        parse_simple("~/.awssecret", &ad->id, &ad->secret);
+
+
+    // if address_style is set, force the dns_compliant setting
+    if (ad->url_style == s3_virtual) {
+        dns_compliant = 1;
+    } else if (ad->url_style == s3_path) {
+        dns_compliant = 0;
+    } else {
+        dns_compliant = is_dns_compliant(bucket, path, is_https);
+    }
+
+    if (ad->host.l == 0)
+        kputs("s3.amazonaws.com", &ad->host);
+
+    if (!dns_compliant && ad->region.l > 0
+        && strcmp(ad->host.s, "s3.amazonaws.com") == 0) {
+        // Can avoid a redirection by including the region in the host name
+        // (assuming the right one has been specified)
+        ad->host.l = 0;
+        ksprintf(&ad->host, "s3.%s.amazonaws.com", ad->region.s);
+    }
+
+    if (ad->region.l == 0)
+        kputs("us-east-1", &ad->region);
+
+    if (!is_escaped(path)) {
+        escaped = escape_path(path);
+        if (escaped == NULL) {
+            goto error;
+        }
+    }
+
+    bucket_len = path - bucket;
+
+    // Use virtual hosted-style access if possible, otherwise path-style.
+    if (dns_compliant) {
+        size_t url_host_pos = url->l;
+        // Append "bucket.host" to url
+        kputsn_(bucket, bucket_len, url);
+        kputc('.', url);
+        kputsn(ad->host.s, ad->host.l, url);
+        url_path_pos = url->l;
+
+        if (sigver == 4) {
+            // Copy back to ad->host to use when making the signature
+            ad->host.l = 0;
+            kputsn(url->s + url_host_pos, url->l - url_host_pos, &ad->host);
+        }
+    }
+    else {
+        // Append "host/bucket" to url
+        kputsn(ad->host.s, ad->host.l, url);
+        url_path_pos = url->l;
+        kputc('/', url);
+        kputsn(bucket, bucket_len, url);
+    }
+
+    kputs(escaped == NULL ? path : escaped, url);
+
+    if (sigver == 4 || !dns_compliant) {
+        ad->bucket = malloc(url->l - url_path_pos + 1);
+        if (ad->bucket == NULL) {
+            goto error;
+        }
+        memcpy(ad->bucket, url->s + url_path_pos, url->l - url_path_pos + 1);
+    }
+    else {
+        ad->bucket = malloc(url->l - url_path_pos + bucket_len + 2);
+        if (ad->bucket == NULL) {
+            goto error;
+        }
+        ad->bucket[0] = '/';
+        memcpy(ad->bucket + 1, bucket, bucket_len);
+        memcpy(ad->bucket + bucket_len + 1,
+               url->s + url_path_pos, url->l - url_path_pos + 1);
+    }
+
+    // write any query strings to its own place to use later
+    if ((query_start = strchr(ad->bucket, '?'))) {
+        kputs(query_start + 1, &ad->user_query_string);
+        *query_start = 0;
+    }
+
+    free(escaped);
+
+    return ad;
+
+ error:
+    free(escaped);
+    free_auth_data(ad);
+    return NULL;
+}
+
+static hFILE * s3_rewrite(const char *s3url, const char *mode, va_list *argsp)
+{
+    kstring_t url = { 0, 0, NULL };
+    s3_auth_data *ad = setup_auth_data(s3url, mode, 2, &url);
+
+    if (!ad)
+        return NULL;
+
+    hFILE *fp = hopen(url.s, mode, "va_list", argsp,
+                      "httphdr_callback", auth_header_callback,
+                      "httphdr_callback_data", ad,
+                      "redirect_callback", redirect_endpoint_callback,
+                      "redirect_callback_data", ad,
+                      NULL);
+    if (!fp) goto fail;
+
+    free(url.s);
+    return fp;
+
+ fail:
+    free(url.s);
+    free_auth_data(ad);
+    return NULL;
+}
+
+/***************************************************************
+
+AWS S3 sig version 4 writing code
+
+****************************************************************/
+
+static void hash_string(char *in, size_t length, char *out, size_t out_len) {
+    unsigned char hashed[SHA256_DIGEST_BUFSIZE];
+    int i, j;
+
+    s3_sha256((const unsigned char *)in, length, hashed);
+
+    for (i = 0, j = 0; i < SHA256_DIGEST_BUFSIZE; i++, j+= 2) {
+        snprintf(out + j, out_len - j, "%02x", hashed[i]);
+    }
+}
+
+static void ksinit(kstring_t *s) {
+    s->l = 0;
+    s->m = 0;
+    s->s = NULL;
+}
+
+
+static void ksfree(kstring_t *s) {
+    free(s->s);
+    ksinit(s);
+}
+
+
+static int make_signature(s3_auth_data *ad, kstring_t *string_to_sign, char *signature_string, size_t sig_string_len) {
+    unsigned char date_key[SHA256_DIGEST_BUFSIZE];
+    unsigned char date_region_key[SHA256_DIGEST_BUFSIZE];
+    unsigned char date_region_service_key[SHA256_DIGEST_BUFSIZE];
+    unsigned char signing_key[SHA256_DIGEST_BUFSIZE];
+    unsigned char signature[SHA256_DIGEST_BUFSIZE];
+
+    const unsigned char service[] = "s3";
+    const unsigned char request[] = "aws4_request";
+
+    kstring_t secret_access_key = KS_INITIALIZE;
+    unsigned int len;
+    unsigned int i, j;
+
+    ksprintf(&secret_access_key, "AWS4%s", ad->secret.s);
+
+    if (secret_access_key.l == 0) {
+        return -1;
+    }
+
+    s3_sign_sha256(secret_access_key.s, secret_access_key.l, (const unsigned char *)ad->date_short, strlen(ad->date_short), date_key, &len);
+    s3_sign_sha256(date_key, len, (const unsigned char *)ad->region.s, ad->region.l, date_region_key, &len);
+    s3_sign_sha256(date_region_key, len, service, 2, date_region_service_key, &len);
+    s3_sign_sha256(date_region_service_key, len, request, 12, signing_key, &len);
+    s3_sign_sha256(signing_key, len, (const unsigned char *)string_to_sign->s, string_to_sign->l, signature, &len);
+
+    for (i = 0, j = 0; i < len; i++, j+= 2) {
+        snprintf(signature_string + j, sig_string_len - j, "%02x", signature[i]);
+    }
+
+    ksfree(&secret_access_key);
+
+    return 0;
+}
+
+
+static int make_authorisation(s3_auth_data *ad, char *http_request, char *content, kstring_t *auth) {
+    kstring_t signed_headers = KS_INITIALIZE;
+    kstring_t canonical_headers = KS_INITIALIZE;
+    kstring_t canonical_request = KS_INITIALIZE;
+    kstring_t scope = KS_INITIALIZE;
+    kstring_t string_to_sign = KS_INITIALIZE;
+    char cr_hash[HASH_LENGTH_SHA256];
+    char signature_string[HASH_LENGTH_SHA256];
+    int ret = -1;
+
+
+    if (!ad->token.l) {
+        kputs("host;x-amz-content-sha256;x-amz-date", &signed_headers);
+    } else {
+        kputs("host;x-amz-content-sha256;x-amz-date;x-amz-security-token", &signed_headers);
+    }
+
+    if (signed_headers.l == 0) {
+        return -1;
+    }
+
+
+    if (!ad->token.l) {
+        ksprintf(&canonical_headers, "host:%s\nx-amz-content-sha256:%s\nx-amz-date:%s\n",
+        ad->host.s, content, ad->date_long);
+    } else {
+        ksprintf(&canonical_headers, "host:%s\nx-amz-content-sha256:%s\nx-amz-date:%s\nx-amz-security-token:%s\n",
+        ad->host.s, content, ad->date_long, ad->token.s);
+    }
+
+    if (canonical_headers.l == 0) {
+        goto cleanup;
+    }
+
+    // bucket == canonical_uri
+    ksprintf(&canonical_request, "%s\n%s\n%s\n%s\n%s\n%s",
+        http_request, ad->bucket, ad->canonical_query_string.s,
+        canonical_headers.s, signed_headers.s, content);
+
+    if (canonical_request.l == 0) {
+        goto cleanup;
+    }
+
+    hash_string(canonical_request.s, canonical_request.l, cr_hash, sizeof(cr_hash));
+
+    ksprintf(&scope, "%s/%s/s3/aws4_request", ad->date_short, ad->region.s);
+
+    if (scope.l == 0) {
+        goto cleanup;
+    }
+
+    ksprintf(&string_to_sign, "AWS4-HMAC-SHA256\n%s\n%s\n%s", ad->date_long, scope.s, cr_hash);
+
+    if (string_to_sign.l == 0) {
+        goto cleanup;
+    }
+
+    if (make_signature(ad, &string_to_sign, signature_string, sizeof(signature_string))) {
+        goto cleanup;
+    }
+
+    ksprintf(auth, "Authorization: AWS4-HMAC-SHA256 Credential=%s/%s/%s/s3/aws4_request,SignedHeaders=%s,Signature=%s",
+                ad->id.s, ad->date_short, ad->region.s, signed_headers.s, signature_string);
+
+    if (auth->l == 0) {
+        goto cleanup;
+    }
+
+    ret = 0;
+
+ cleanup:
+    ksfree(&signed_headers);
+    ksfree(&canonical_headers);
+    ksfree(&canonical_request);
+    ksfree(&scope);
+    ksfree(&string_to_sign);
+
+    return ret;
+}
+
+
+static int update_time(s3_auth_data *ad, time_t now) {
+    int ret = -1;
+#ifdef HAVE_GMTIME_R
+    struct tm tm_buffer;
+    struct tm *tm = gmtime_r(&now, &tm_buffer);
+#else
+    struct tm *tm = gmtime(&now);
+#endif
+
+    if (now - ad->auth_time > AUTH_LIFETIME) {
+        // update timestamp
+        ad->auth_time = now;
+
+        if (strftime(ad->date_long, 17, "%Y%m%dT%H%M%SZ", tm) != 16) {
+            return -1;
+        }
+
+        if (strftime(ad->date_short, 9, "%Y%m%d", tm) != 8) {
+            return -1;;
+        }
+
+        ad->date_html.l = 0;
+        ksprintf(&ad->date_html, "x-amz-date: %s", ad->date_long);
+    }
+
+    if (ad->date_html.l) ret = 0;
+
+    return ret;
+}
+
+
+static int query_cmp(const void *p1, const void *p2) {
+    char **q1 = (char **)p1;
+    char **q2 = (char **)p2;
+
+    return strcmp(*q1, *q2);
+}
+
+
+/* Query strings must be in alphabetical order for authorisation */
+
+static int order_query_string(kstring_t *qs) {
+    int *query_offset = NULL;
+    int num_queries, i;
+    char **queries = NULL;
+    kstring_t ordered = KS_INITIALIZE;
+    char *escaped = NULL;
+    int ret = -1;
+
+    if ((query_offset = ksplit(qs, '&', &num_queries)) == NULL) {
+        return -1;
+    }
+
+    if ((queries = malloc(num_queries * sizeof(char*))) == NULL)
+        goto err;
+
+    for (i = 0; i < num_queries; i++) {
+        queries[i] = qs->s + query_offset[i];
+    }
+
+    qsort(queries, num_queries, sizeof(char *), query_cmp);
+
+    for (i = 0; i < num_queries; i++) {
+        if (i) {
+            kputs("&", &ordered);
+        }
+
+        kputs(queries[i], &ordered);
+    }
+
+    if ((escaped = escape_query(ordered.s)) == NULL)
+        goto err;
+
+    qs->l = 0;
+    kputs(escaped, qs);
+
+    ret = 0;
+ err:
+    free(ordered.s);
+    free(queries);
+    free(query_offset);
+    free(escaped);
+
+    return ret;
+}
+
+
+static int write_authorisation_callback(void *auth, char *request, kstring_t *content, char *cqs,
+                                        kstring_t *hash, kstring_t *auth_str, kstring_t *date,
+                                        kstring_t *token, int uqs) {
+    s3_auth_data *ad = (s3_auth_data *)auth;
+    char content_hash[HASH_LENGTH_SHA256];
+    time_t now;
+
+    if (request == NULL) {
+        // signal to free auth data
+        free_auth_data(ad);
+        return 0;
+    }
+
+    now = time(NULL);
+
+    if (update_time(ad, now)) {
+        return -1;
+    }
+    if (ad->creds_expiry_time > 0
+        && ad->creds_expiry_time - now < CREDENTIAL_LIFETIME) {
+        refresh_auth_data(ad);
+    }
+
+    if (content) {
+        hash_string(content->s, content->l, content_hash, sizeof(content_hash));
+    } else {
+        // empty hash
+        hash_string("", 0, content_hash, sizeof(content_hash));
+    }
+
+    ad->canonical_query_string.l = 0;
+    kputs(cqs, &ad->canonical_query_string);
+
+    if (ad->canonical_query_string.l == 0) {
+        return -1;
+    }
+
+    /* add a user provided query string, normally only useful on upload initiation */
+    if (uqs) {
+        kputs("&", &ad->canonical_query_string);
+        kputs(ad->user_query_string.s, &ad->canonical_query_string);
+
+        if (order_query_string(&ad->canonical_query_string)) {
+            return -1;
+        }
+    }
+
+    if (make_authorisation(ad, request, content_hash, auth_str)) {
+        return -1;
+    }
+
+    kputs(ad->date_html.s, date);
+    kputsn(content_hash, HASH_LENGTH_SHA256, hash);
+
+    if (date->l == 0 || hash->l == 0) {
+        return -1;
+    }
+
+    if (ad->token.l) {
+        ksprintf(token, "x-amz-security-token: %s", ad->token.s);
+    }
+
+    return 0;
+}
+
+
+static int v4_auth_header_callback(void *ctx, char ***hdrs) {
+    s3_auth_data *ad = (s3_auth_data *) ctx;
+    char content_hash[HASH_LENGTH_SHA256];
+    kstring_t content = KS_INITIALIZE;
+    kstring_t authorisation = KS_INITIALIZE;
+    kstring_t token_hdr = KS_INITIALIZE;
+    char *date_html = NULL;
+    time_t now;
+    int idx;
+
+    if (!hdrs) { // Closing connection
+        free_auth_data(ad);
+        return 0;
+    }
+
+    now = time(NULL);
+
+    if (update_time(ad, now)) {
+        return -1;
+    }
+
+    if (ad->creds_expiry_time > 0
+        && ad->creds_expiry_time - now < CREDENTIAL_LIFETIME) {
+        refresh_auth_data(ad);
+    }
+
+    if (!ad->id.l || !ad->secret.l) {
+        return copy_auth_headers(ad, hdrs);
+    }
+
+    hash_string("", 0, content_hash, sizeof(content_hash)); // empty hash
+
+    ad->canonical_query_string.l = 0;
+
+    if (ad->user_query_string.l > 0) {
+        kputs(ad->user_query_string.s, &ad->canonical_query_string);
+
+        if (order_query_string(&ad->canonical_query_string)) {
+            return -1;
+        }
+    } else {
+        kputs("", &ad->canonical_query_string);
+    }
+
+    if (make_authorisation(ad, "GET", content_hash, &authorisation)) {
+        return -1;
+    }
+
+    ksprintf(&content, "x-amz-content-sha256: %s", content_hash);
+    date_html = strdup(ad->date_html.s);
+
+    if (ad->token.l > 0) {
+        kputs("X-Amz-Security-Token: ", &token_hdr);
+        kputs(ad->token.s, &token_hdr);
+    }
+
+    if (content.l == 0 || date_html == NULL) {
+        ksfree(&authorisation);
+        ksfree(&content);
+        ksfree(&token_hdr);
+        free(date_html);
+        return -1;
+    }
+
+    *hdrs = &ad->headers[0];
+    idx = 0;
+    ad->headers[idx++] = ks_release(&authorisation);
+    ad->headers[idx++] = date_html;
+    ad->headers[idx++] = ks_release(&content);
+    if (token_hdr.s)
+        ad->headers[idx++] = ks_release(&token_hdr);
+    ad->headers[idx++] = NULL;
+
+    return 0;
+}
+
+static int handle_400_response(hFILE *fp, s3_auth_data *ad) {
+    // v4 signatures in virtual hosted mode return 400 Bad Request if the
+    // wrong region is used to make the signature.  The response is an xml
+    // document which includes the name of the correct region.  This can
+    // be extracted and used to generate a corrected signature.
+    // As the xml is fairly simple, go with something "good enough" instead
+    // of trying to parse it properly.
+
+    char buffer[1024], *region, *reg_end;
+    ssize_t bytes;
+
+    bytes = hread(fp, buffer, sizeof(buffer) - 1);
+    if (bytes < 0) {
+        return -1;
+    }
+    buffer[bytes] = '\0';
+    region = strstr(buffer, "");
+    if (region == NULL) {
+        return -1;
+    }
+    region += 8;
+    while (isspace((unsigned char) *region)) ++region;
+    reg_end = strchr(region, '<');
+    if (reg_end == NULL || strncmp(reg_end + 1, "/Region>", 8) != 0) {
+        return -1;
+    }
+    while (reg_end > region && isspace((unsigned char) reg_end[-1])) --reg_end;
+    ad->region.l = 0;
+    kputsn(region, reg_end - region, &ad->region);
+    if (ad->region.l == 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+static int set_region(void *adv, kstring_t *region) {
+    s3_auth_data *ad = (s3_auth_data *) adv;
+
+    ad->region.l = 0;
+    return kputsn(region->s, region->l, &ad->region) < 0;
+}
+
+static int http_status_errno(int status)
+{
+    if (status >= 500)
+        switch (status) {
+        case 501: return ENOSYS;
+        case 503: return EBUSY;
+        case 504: return ETIMEDOUT;
+        default:  return EIO;
+        }
+    else if (status >= 400)
+        switch (status) {
+        case 401: return EPERM;
+        case 403: return EACCES;
+        case 404: return ENOENT;
+        case 405: return EROFS;
+        case 407: return EPERM;
+        case 408: return ETIMEDOUT;
+        case 410: return ENOENT;
+        default:  return EINVAL;
+        }
+    else return 0;
+}
+
+static hFILE *s3_open_v4(const char *s3url, const char *mode, va_list *argsp) {
+    kstring_t url = { 0, 0, NULL };
+
+    s3_auth_data *ad = setup_auth_data(s3url, mode, 4, &url);
+    hFILE *fp = NULL;
+
+    if (ad == NULL) {
+        return NULL;
+    }
+
+    if (ad->mode == 'r') {
+        long http_response = 0;
+
+        fp = hopen(url.s, mode, "va_list", argsp,
+                   "httphdr_callback", v4_auth_header_callback,
+                   "httphdr_callback_data", ad,
+                   "redirect_callback", redirect_endpoint_callback,
+                   "redirect_callback_data", ad,
+                   "http_response_ptr", &http_response,
+                   "fail_on_error", 0,
+                   NULL);
+
+        if (fp == NULL) goto error;
+
+        if (http_response == 307) {
+            // Follow additional redirect.
+            ad->refcount = 1;
+            hclose_abruptly(fp);
+
+            url.l  = 0;
+            ksprintf(&url, "https://%s%s", ad->host.s, ad->bucket);
+
+            fp = hopen(url.s, mode, "va_list", argsp,
+                   "httphdr_callback", v4_auth_header_callback,
+                   "httphdr_callback_data", ad,
+                   "redirect_callback", redirect_endpoint_callback,
+                   "redirect_callback_data", ad,
+                   "http_response_ptr", &http_response,
+                   "fail_on_error", 0,
+                   NULL);
+        }
+
+        if (http_response == 400) {
+            ad->refcount = 1;
+            if (handle_400_response(fp, ad) != 0) {
+                goto error;
+            }
+            hclose_abruptly(fp);
+            fp = hopen(url.s, mode, "va_list", argsp,
+                       "httphdr_callback", v4_auth_header_callback,
+                       "httphdr_callback_data", ad,
+                       "redirect_callback", redirect_endpoint_callback,
+                       "redirect_callback_data", ad,
+                       NULL);
+        } else if (http_response > 400) {
+            ad->refcount = 1;
+            errno = http_status_errno(http_response);
+            goto error;
+        }
+
+        if (fp == NULL) goto error;
+    } else {
+        kstring_t final_url = KS_INITIALIZE;
+
+         // add the scheme marker
+        ksprintf(&final_url, "s3w+%s", url.s);
+
+        if(final_url.l == 0) goto error;
+
+        fp = hopen(final_url.s, mode, "va_list", argsp,
+                   "s3_auth_callback",  write_authorisation_callback,
+                   "s3_auth_callback_data", ad,
+                   "redirect_callback", redirect_endpoint_callback,
+                   "set_region_callback", set_region,
+                   NULL);
+        free(final_url.s);
+
+        if (fp == NULL) goto error;
+    }
+
+    free(url.s);
+
+    return fp;
+
+  error:
+
+    if (fp) hclose_abruptly(fp);
+    free(url.s);
+    free_auth_data(ad);
+
+    return NULL;
+}
+
+
+static hFILE *s3_open(const char *url, const char *mode)
+{
+    hFILE *fp;
+
+    kstring_t mode_colon = { 0, 0, NULL };
+    kputs(mode, &mode_colon);
+    kputc(':', &mode_colon);
+
+    if (getenv("HTS_S3_V2") == NULL) { // Force the v2 signature code
+        fp = s3_open_v4(url, mode_colon.s, NULL);
+    } else {
+        fp = s3_rewrite(url, mode_colon.s, NULL);
+    }
+
+    free(mode_colon.s);
+
+    return fp;
+}
+
+static hFILE *s3_vopen(const char *url, const char *mode_colon, va_list args0)
+{
+    hFILE *fp;
+    // Need to use va_copy() as we can only take the address of an actual
+    // va_list object, not that of a parameter whose type may have decayed.
+    va_list args;
+    va_copy(args, args0);
+
+    if (getenv("HTS_S3_V2") == NULL) { // Force the v2 signature code
+        fp = s3_open_v4(url, mode_colon, &args);
+    } else {
+        fp = s3_rewrite(url, mode_colon, &args);
+    }
+
+    va_end(args);
+    return fp;
+}
+
+int PLUGIN_GLOBAL(hfile_plugin_init,_s3)(struct hFILE_plugin *self)
+{
+    static const struct hFILE_scheme_handler handler =
+        { s3_open, hfile_always_remote, "Amazon S3", 2000 + 50, s3_vopen
+        };
+
+#ifdef ENABLE_PLUGINS
+    // Embed version string for examination via strings(1) or what(1)
+    static const char id[] = "@(#)hfile_s3 plugin (htslib)\t" HTS_VERSION_TEXT;
+    if (hts_verbose >= 9)
+        fprintf(stderr, "[M::hfile_s3.init] version %s\n", strchr(id, '\t')+1);
+#endif
+
+    self->name = "Amazon S3";
+    hfile_add_scheme_handler("s3", &handler);
+    hfile_add_scheme_handler("s3+http", &handler);
+    hfile_add_scheme_handler("s3+https", &handler);
+    return 0;
+}
diff --git a/shared/package-files/a5/a5078db815d92d5b11e30adf8eb50a4187384259f35c31bf0a486691fa9e1856/_reshape_alias_copy_ops.h b/shared/package-files/a5/a5078db815d92d5b11e30adf8eb50a4187384259f35c31bf0a486691fa9e1856/_reshape_alias_copy_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad381d6c0fd21da73805a9e4c346311506b0fdd0
--- /dev/null
+++ b/shared/package-files/a5/a5078db815d92d5b11e30adf8eb50a4187384259f35c31bf0a486691fa9e1856/_reshape_alias_copy_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _reshape_alias_copy {
+  using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_reshape_alias_copy";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_reshape_alias_copy(Tensor self, SymInt[] size, SymInt[] stride) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride);
+};
+
+struct TORCH_API _reshape_alias_copy_out {
+  using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_reshape_alias_copy";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "_reshape_alias_copy.out(Tensor self, SymInt[] size, SymInt[] stride, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/a5/a50931862f289050db17a51e6be75b791ae335f9a573a9f325d217389c40a942/test_matexpr.py b/shared/package-files/a5/a50931862f289050db17a51e6be75b791ae335f9a573a9f325d217389c40a942/test_matexpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2319e8d8097c2ad3519eab783c4665623c55b80
--- /dev/null
+++ b/shared/package-files/a5/a50931862f289050db17a51e6be75b791ae335f9a573a9f325d217389c40a942/test_matexpr.py
@@ -0,0 +1,592 @@
+from sympy.concrete.summations import Sum
+from sympy.core.exprtools import gcd_terms
+from sympy.core.function import (diff, expand)
+from sympy.core.relational import Eq
+from sympy.core.symbol import (Dummy, Symbol, Str)
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.matrices.dense import zeros
+from sympy.polys.polytools import factor
+
+from sympy.core import (S, symbols, Add, Mul, SympifyError, Rational,
+                    Function)
+from sympy.functions import sin, cos, tan, sqrt, cbrt, exp
+from sympy.simplify import simplify
+from sympy.matrices import (ImmutableMatrix, Inverse, MatAdd, MatMul,
+        MatPow, Matrix, MatrixExpr, MatrixSymbol,
+        SparseMatrix, Transpose, Adjoint, MatrixSet)
+from sympy.matrices.exceptions import NonSquareMatrixError
+from sympy.matrices.expressions.determinant import Determinant, det
+from sympy.matrices.expressions.matexpr import MatrixElement
+from sympy.matrices.expressions.special import ZeroMatrix, Identity
+from sympy.testing.pytest import raises, XFAIL, skip
+from importlib.metadata import version
+
+n, m, l, k, p = symbols('n m l k p', integer=True)
+x = symbols('x')
+A = MatrixSymbol('A', n, m)
+B = MatrixSymbol('B', m, l)
+C = MatrixSymbol('C', n, n)
+D = MatrixSymbol('D', n, n)
+E = MatrixSymbol('E', m, n)
+w = MatrixSymbol('w', n, 1)
+
+
+def test_matrix_symbol_creation():
+    assert MatrixSymbol('A', 2, 2)
+    assert MatrixSymbol('A', 0, 0)
+    raises(ValueError, lambda: MatrixSymbol('A', -1, 2))
+    raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2))
+    raises(ValueError, lambda: MatrixSymbol('A', 2j, 2))
+    raises(ValueError, lambda: MatrixSymbol('A', 2, -1))
+    raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0))
+    raises(ValueError, lambda: MatrixSymbol('A', 2, 2j))
+
+    n = symbols('n')
+    assert MatrixSymbol('A', n, n)
+    n = symbols('n', integer=False)
+    raises(ValueError, lambda: MatrixSymbol('A', n, n))
+    n = symbols('n', negative=True)
+    raises(ValueError, lambda: MatrixSymbol('A', n, n))
+
+
+def test_matexpr_properties():
+    assert A.shape == (n, m)
+    assert (A * B).shape == (n, l)
+    assert A[0, 1].indices == (0, 1)
+    assert A[0, 0].symbol == A
+    assert A[0, 0].symbol.name == 'A'
+
+
+def test_matexpr():
+    assert (x*A).shape == A.shape
+    assert (x*A).__class__ == MatMul
+    assert 2*A - A - A == ZeroMatrix(*A.shape)
+    assert (A*B).shape == (n, l)
+
+
+def test_matexpr_subs():
+    A = MatrixSymbol('A', n, m)
+    B = MatrixSymbol('B', m, l)
+    C = MatrixSymbol('C', m, l)
+
+    assert A.subs(n, m).shape == (m, m)
+    assert (A*B).subs(B, C) == A*C
+    assert (A*B).subs(l, n).is_square
+
+    W = MatrixSymbol("W", 3, 3)
+    X = MatrixSymbol("X", 2, 2)
+    Y = MatrixSymbol("Y", 1, 2)
+    Z = MatrixSymbol("Z", n, 2)
+    # no restrictions on Symbol replacement
+    assert X.subs(X, Y) == Y
+    # it might be better to just change the name
+    y = Str('y')
+    assert X.subs(Str("X"), y).args == (y, 2, 2)
+    # it's ok to introduce a wider matrix
+    assert X[1, 1].subs(X, W) == W[1, 1]
+    # but for a given MatrixExpression, only change
+    # name if indexing on the new shape is valid.
+    # Here, X is 2,2; Y is 1,2 and Y[1, 1] is out
+    # of range so an error is raised
+    raises(IndexError, lambda: X[1, 1].subs(X, Y))
+    # here, [0, 1] is in range so the subs succeeds
+    assert X[0, 1].subs(X, Y) == Y[0, 1]
+    # and here the size of n will accept any index
+    # in the first position
+    assert W[2, 1].subs(W, Z) == Z[2, 1]
+    # but not in the second position
+    raises(IndexError, lambda: W[2, 2].subs(W, Z))
+    # any matrix should raise if invalid
+    raises(IndexError, lambda: W[2, 2].subs(W, zeros(2)))
+
+    A = SparseMatrix([[1, 2], [3, 4]])
+    B = Matrix([[1, 2], [3, 4]])
+    C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2)
+
+    assert (C*D).subs({C: A, D: B}) == MatMul(A, B)
+
+
+def test_addition():
+    A = MatrixSymbol('A', n, m)
+    B = MatrixSymbol('B', n, m)
+
+    assert isinstance(A + B, MatAdd)
+    assert (A + B).shape == A.shape
+    assert isinstance(A - A + 2*B, MatMul)
+
+    raises(TypeError, lambda: A + 1)
+    raises(TypeError, lambda: 5 + A)
+    raises(TypeError, lambda: 5 - A)
+
+    assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m)
+    raises(TypeError, lambda: ZeroMatrix(n, m) + S.Zero)
+
+
+def test_multiplication():
+    A = MatrixSymbol('A', n, m)
+    B = MatrixSymbol('B', m, l)
+    C = MatrixSymbol('C', n, n)
+
+    assert (2*A*B).shape == (n, l)
+    assert (A*0*B) == ZeroMatrix(n, l)
+    assert (2*A).shape == A.shape
+
+    assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l)
+
+    assert C * Identity(n) * C.I == Identity(n)
+
+    assert B/2 == S.Half*B
+    raises(NotImplementedError, lambda: 2/B)
+
+    A = MatrixSymbol('A', n, n)
+    B = MatrixSymbol('B', n, n)
+    assert Identity(n) * (A + B) == A + B
+
+    assert A**2*A == A**3
+    assert A**2*(A.I)**3 == A.I
+    assert A**3*(A.I)**2 == A
+
+
+def test_MatPow():
+    A = MatrixSymbol('A', n, n)
+
+    AA = MatPow(A, 2)
+    assert AA.exp == 2
+    assert AA.base == A
+    assert (A**n).exp == n
+
+    assert A**0 == Identity(n)
+    assert A**1 == A
+    assert A**2 == AA
+    assert A**-1 == Inverse(A)
+    assert (A**-1)**-1 == A
+    assert (A**2)**3 == A**6
+    assert A**S.Half == sqrt(A)
+    assert A**Rational(1, 3) == cbrt(A)
+    raises(NonSquareMatrixError, lambda: MatrixSymbol('B', 3, 2)**2)
+
+
+def test_MatrixSymbol():
+    n, m, t = symbols('n,m,t')
+    X = MatrixSymbol('X', n, m)
+    assert X.shape == (n, m)
+    raises(TypeError, lambda: MatrixSymbol('X', n, m)(t))  # issue 5855
+    assert X.doit() == X
+
+
+def test_dense_conversion():
+    X = MatrixSymbol('X', 2, 2)
+    assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j])
+    assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
+
+
+def test_free_symbols():
+    assert (C*D).free_symbols == {C, D}
+
+
+def test_zero_matmul():
+    assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr)
+
+
+def test_matadd_simplify():
+    A = MatrixSymbol('A', 1, 1)
+    assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
+        MatAdd(A, Matrix([[1]]))
+
+
+def test_matmul_simplify():
+    A = MatrixSymbol('A', 1, 1)
+    assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
+        MatMul(A, Matrix([[1]]))
+
+
+def test_invariants():
+    A = MatrixSymbol('A', n, m)
+    B = MatrixSymbol('B', m, l)
+    X = MatrixSymbol('X', n, n)
+    objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A),
+            Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1),
+            MatPow(X, 0)]
+    for obj in objs:
+        assert obj == obj.__class__(*obj.args)
+
+
+def test_matexpr_indexing():
+    A = MatrixSymbol('A', n, m)
+    A[1, 2]
+    A[l, k]
+    A[l + 1, k + 1]
+    A = MatrixSymbol('A', 2, 1)
+    for i in range(-2, 2):
+        for j in range(-1, 1):
+            A[i, j]
+
+
+def test_single_indexing():
+    A = MatrixSymbol('A', 2, 3)
+    assert A[1] == A[0, 1]
+    assert A[int(1)] == A[0, 1]
+    assert A[3] == A[1, 0]
+    assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]]
+    raises(IndexError, lambda: A[6])
+    raises(IndexError, lambda: A[n])
+    B = MatrixSymbol('B', n, m)
+    raises(IndexError, lambda: B[1])
+    B = MatrixSymbol('B', n, 3)
+    assert B[3] == B[1, 0]
+
+
+def test_MatrixElement_commutative():
+    assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1]
+
+
+def test_MatrixSymbol_determinant():
+    A = MatrixSymbol('A', 4, 4)
+    assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \
+        A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \
+        A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \
+        A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \
+        A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \
+        A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \
+        A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \
+        A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \
+        A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \
+        A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \
+        A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \
+        A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \
+        A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0]
+
+    B = MatrixSymbol('B', 4, 4)
+    assert Determinant(A + B).doit() == det(A + B) == (A + B).det()
+
+
+def test_MatrixElement_diff():
+    assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
+
+
+def test_MatrixElement_doit():
+    u = MatrixSymbol('u', 2, 1)
+    v = ImmutableMatrix([3, 5])
+    assert u[0, 0].subs(u, v).doit() == v[0, 0]
+
+
+def test_identity_powers():
+    M = Identity(n)
+    assert MatPow(M, 3).doit() == M**3
+    assert M**n == M
+    assert MatPow(M, 0).doit() == M**2
+    assert M**-2 == M
+    assert MatPow(M, -2).doit() == M**0
+    N = Identity(3)
+    assert MatPow(N, 2).doit() == N**n
+    assert MatPow(N, 3).doit() == N
+    assert MatPow(N, -2).doit() == N**4
+    assert MatPow(N, 2).doit() == N**0
+
+
+def test_Zero_power():
+    z1 = ZeroMatrix(n, n)
+    assert z1**4 == z1
+    raises(ValueError, lambda:z1**-2)
+    assert z1**0 == Identity(n)
+    assert MatPow(z1, 2).doit() == z1**2
+    raises(ValueError, lambda:MatPow(z1, -2).doit())
+    z2 = ZeroMatrix(3, 3)
+    assert MatPow(z2, 4).doit() == z2**4
+    raises(ValueError, lambda:z2**-3)
+    assert z2**3 == MatPow(z2, 3).doit()
+    assert z2**0 == Identity(3)
+    raises(ValueError, lambda:MatPow(z2, -1).doit())
+
+
+def test_matrixelement_diff():
+    dexpr = diff((D*w)[k,0], w[p,0])
+
+    assert w[k, p].diff(w[k, p]) == 1
+    assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0))
+    _i_1 = Dummy("_i_1")
+    assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1)))
+    assert dexpr.doit() == D[k, p]
+
+
+def test_MatrixElement_with_values():
+    x, y, z, w = symbols("x y z w")
+    M = Matrix([[x, y], [z, w]])
+    i, j = symbols("i, j")
+    Mij = M[i, j]
+    assert isinstance(Mij, MatrixElement)
+    Ms = SparseMatrix([[2, 3], [4, 5]])
+    msij = Ms[i, j]
+    assert isinstance(msij, MatrixElement)
+    for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
+        assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
+        assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
+    A = MatrixSymbol("A", 2, 2)
+    assert A[0, 0].subs(A, M) == x
+    assert A[i, j].subs(A, M) == M[i, j]
+    assert M[i, j].subs(M, A) == A[i, j]
+
+    assert isinstance(M[3*i - 2, j], MatrixElement)
+    assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
+    assert isinstance(M[i, 0], MatrixElement)
+    assert M[i, 0].subs(i, 0) == M[0, 0]
+    assert M[0, i].subs(i, 1) == M[0, 1]
+
+    assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j]
+
+    raises(ValueError, lambda: M[i, 2])
+    raises(ValueError, lambda: M[i, -1])
+    raises(ValueError, lambda: M[2, i])
+    raises(ValueError, lambda: M[-1, i])
+
+
+def test_inv():
+    B = MatrixSymbol('B', 3, 3)
+    assert B.inv() == B**-1
+
+    # https://github.com/sympy/sympy/issues/19162
+    X = MatrixSymbol('X', 1, 1).as_explicit()
+    assert X.inv() == Matrix([[1/X[0, 0]]])
+
+    X = MatrixSymbol('X', 2, 2).as_explicit()
+    detX = X[0, 0]*X[1, 1] - X[0, 1]*X[1, 0]
+    invX = Matrix([[ X[1, 1], -X[0, 1]],
+                   [-X[1, 0],  X[0, 0]]]) / detX
+    assert X.inv() == invX
+
+
+@XFAIL
+def test_factor_expand():
+    A = MatrixSymbol("A", n, n)
+    B = MatrixSymbol("B", n, n)
+    expr1 = (A + B)*(C + D)
+    expr2 = A*C + B*C + A*D + B*D
+    assert expr1 != expr2
+    assert expand(expr1) == expr2
+    assert factor(expr2) == expr1
+
+    expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
+    I = Identity(n)
+    # Ideally we get the first, but we at least don't want a wrong answer
+    assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
+
+def test_numpy_conversion():
+    try:
+        from numpy import array, array_equal
+    except ImportError:
+        skip('NumPy must be available to test creating matrices from ndarrays')
+    A = MatrixSymbol('A', 2, 2)
+    np_array = array([[MatrixElement(A, 0, 0), MatrixElement(A, 0, 1)],
+    [MatrixElement(A, 1, 0), MatrixElement(A, 1, 1)]])
+    assert array_equal(array(A), np_array)
+    assert array_equal(array(A, copy=True), np_array)
+    if(int(version('numpy').split('.')[0]) >= 2): #run this test only if numpy is new enough that copy variable is passed properly.
+        raises(TypeError, lambda: array(A, copy=False))
+
+def test_issue_2749():
+    A = MatrixSymbol("A", 5, 2)
+    assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \
+    [(A.T * A).I[1, 0], (A.T * A).I[1, 1]]])
+
+
+def test_issue_2750():
+    x = MatrixSymbol('x', 1, 1)
+    assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]])
+
+
+def test_issue_7842():
+    A = MatrixSymbol('A', 3, 1)
+    B = MatrixSymbol('B', 2, 1)
+    assert Eq(A, B) == False
+    assert Eq(A[1,0], B[1, 0]).func is Eq
+    A = ZeroMatrix(2, 3)
+    B = ZeroMatrix(2, 3)
+    assert Eq(A, B) == True
+
+
+def test_issue_21195():
+    t = symbols('t')
+    x = Function('x')(t)
+    dx = x.diff(t)
+    exp1 = cos(x) + cos(x)*dx
+    exp2 = sin(x) + tan(x)*(dx.diff(t))
+    exp3 = sin(x)*sin(t)*(dx.diff(t)).diff(t)
+    A = Matrix([[exp1], [exp2], [exp3]])
+    B = Matrix([[exp1.diff(x)], [exp2.diff(x)], [exp3.diff(x)]])
+    assert A.diff(x) == B
+
+
+def test_issue_24859():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 3, 2)
+    J = A*B
+    Jinv = Matrix(J).adjugate()
+    u = MatrixSymbol('u', 2, 3)
+    Jk = Jinv.subs(A, A + x*u)
+
+    expected = B[0, 1]*u[1, 0] + B[1, 1]*u[1, 1] + B[2, 1]*u[1, 2]
+    assert Jk[0, 0].diff(x) == expected
+    assert diff(Jk[0, 0], x).doit() == expected
+
+
+def test_MatMul_postprocessor():
+    z = zeros(2)
+    z1 = ZeroMatrix(2, 2)
+    assert Mul(0, z) == Mul(z, 0) in [z, z1]
+
+    M = Matrix([[1, 2], [3, 4]])
+    Mx = Matrix([[x, 2*x], [3*x, 4*x]])
+    assert Mul(x, M) == Mul(M, x) == Mx
+
+    A = MatrixSymbol("A", 2, 2)
+    assert Mul(A, M) == MatMul(A, M)
+    assert Mul(M, A) == MatMul(M, A)
+    # Scalars should be absorbed into constant matrices
+    a = Mul(x, M, A)
+    b = Mul(M, x, A)
+    c = Mul(M, A, x)
+    assert a == b == c == MatMul(Mx, A)
+    a = Mul(x, A, M)
+    b = Mul(A, x, M)
+    c = Mul(A, M, x)
+    assert a == b == c == MatMul(A, Mx)
+    assert Mul(M, M) == M**2
+    assert Mul(A, M, M) == MatMul(A, M**2)
+    assert Mul(M, M, A) == MatMul(M**2, A)
+    assert Mul(M, A, M) == MatMul(M, A, M)
+
+    assert Mul(A, x, M, M, x) == MatMul(A, Mx**2)
+
+
+@XFAIL
+def test_MatAdd_postprocessor_xfail():
+    # This is difficult to get working because of the way that Add processes
+    # its args.
+    z = zeros(2)
+    assert Add(z, S.NaN) == Add(S.NaN, z)
+
+
+def test_MatAdd_postprocessor():
+    # Some of these are nonsensical, but we do not raise errors for Add
+    # because that breaks algorithms that want to replace matrices with dummy
+    # symbols.
+
+    z = zeros(2)
+
+    assert Add(0, z) == Add(z, 0) == z
+
+    a = Add(S.Infinity, z)
+    assert a == Add(z, S.Infinity)
+    assert isinstance(a, Add)
+    assert a.args == (S.Infinity, z)
+
+    a = Add(S.ComplexInfinity, z)
+    assert a == Add(z, S.ComplexInfinity)
+    assert isinstance(a, Add)
+    assert a.args == (S.ComplexInfinity, z)
+
+    a = Add(z, S.NaN)
+    # assert a == Add(S.NaN, z) # See the XFAIL above
+    assert isinstance(a, Add)
+    assert a.args == (S.NaN, z)
+
+    M = Matrix([[1, 2], [3, 4]])
+    a = Add(x, M)
+    assert a == Add(M, x)
+    assert isinstance(a, Add)
+    assert a.args == (x, M)
+
+    A = MatrixSymbol("A", 2, 2)
+    assert Add(A, M) == Add(M, A) == A + M
+
+    # Scalars should be absorbed into constant matrices (producing an error)
+    a = Add(x, M, A)
+    assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x)
+    assert isinstance(a, Add)
+    assert a.args == (x, A + M)
+
+    assert Add(M, M) == 2*M
+    assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M
+
+    a = Add(A, x, M, M, x)
+    assert isinstance(a, Add)
+    assert a.args == (2*x, A + 2*M)
+
+
+def test_simplify_matrix_expressions():
+    # Various simplification functions
+    assert type(gcd_terms(C*D + D*C)) == MatAdd
+    a = gcd_terms(2*C*D + 4*D*C)
+    assert type(a) == MatAdd
+    assert a.args == (2*C*D, 4*D*C)
+
+
+def test_exp():
+    A = MatrixSymbol('A', 2, 2)
+    B = MatrixSymbol('B', 2, 2)
+    expr1 = exp(A)*exp(B)
+    expr2 = exp(B)*exp(A)
+    assert expr1 != expr2
+    assert expr1 - expr2 != 0
+    assert not isinstance(expr1, exp)
+    assert not isinstance(expr2, exp)
+
+
+def test_invalid_args():
+    raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A'))
+
+
+def test_matrixsymbol_from_symbol():
+    # The label should be preserved during doit and subs
+    A_label = Symbol('A', complex=True)
+    A = MatrixSymbol(A_label, 2, 2)
+
+    A_1 = A.doit()
+    A_2 = A.subs(2, 3)
+    assert A_1.args == A.args
+    assert A_2.args[0] == A.args[0]
+
+
+def test_as_explicit():
+    Z = MatrixSymbol('Z', 2, 3)
+    assert Z.as_explicit() == ImmutableMatrix([
+        [Z[0, 0], Z[0, 1], Z[0, 2]],
+        [Z[1, 0], Z[1, 1], Z[1, 2]],
+    ])
+    raises(ValueError, lambda: A.as_explicit())
+
+
+def test_MatrixSet():
+    M = MatrixSet(2, 2, set=S.Reals)
+    assert M.shape == (2, 2)
+    assert M.set == S.Reals
+    X = Matrix([[1, 2], [3, 4]])
+    assert X in M
+    X = ZeroMatrix(2, 2)
+    assert X in M
+    raises(TypeError, lambda: A in M)
+    raises(TypeError, lambda: 1 in M)
+    M = MatrixSet(n, m, set=S.Reals)
+    assert A in M
+    raises(TypeError, lambda: C in M)
+    raises(TypeError, lambda: X in M)
+    M = MatrixSet(2, 2, set={1, 2, 3})
+    X = Matrix([[1, 2], [3, 4]])
+    Y = Matrix([[1, 2]])
+    assert (X in M) == S.false
+    assert (Y in M) == S.false
+    raises(ValueError, lambda: MatrixSet(2, -2, S.Reals))
+    raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals))
+    raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
+
+
+def test_matrixsymbol_solving():
+    A = MatrixSymbol('A', 2, 2)
+    B = MatrixSymbol('B', 2, 2)
+    Z = ZeroMatrix(2, 2)
+    assert -(-A + B) - A + B == Z
+    assert (-(-A + B) - A + B).simplify() == Z
+    assert (-(-A + B) - A + B).expand() == Z
+    assert (-(-A + B) - A + B - Z).simplify() == Z
+    assert (-(-A + B) - A + B - Z).expand() == Z
+    assert (A*(A + B) + B*(A.T + B.T)).expand() == A**2 + A*B + B*A.T + B*B.T
diff --git a/shared/package-files/a5/a520873291e2396cc24ff7f61a4bf96affedf73f9ffcdbcde63cfa5c7536b53c/test_rpc.cpython-311.pyc b/shared/package-files/a5/a520873291e2396cc24ff7f61a4bf96affedf73f9ffcdbcde63cfa5c7536b53c/test_rpc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c782cda44e9a21cfa233f1a7f6712e48ba820bf
Binary files /dev/null and b/shared/package-files/a5/a520873291e2396cc24ff7f61a4bf96affedf73f9ffcdbcde63cfa5c7536b53c/test_rpc.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a52af5a8ee8d375670dd68a6eb4f1fdd91f35f557f561c749b5f53971172cf7d/__init__.cpython-311.pyc b/shared/package-files/a5/a52af5a8ee8d375670dd68a6eb4f1fdd91f35f557f561c749b5f53971172cf7d/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4773e045ad88db36fd7ac7681d5dd7712e8b23c7
Binary files /dev/null and b/shared/package-files/a5/a52af5a8ee8d375670dd68a6eb4f1fdd91f35f557f561c749b5f53971172cf7d/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a52c729029203f0713fd8909865401bb4f17481b6d71fc108df2310f58297347/em.c.pysam.c b/shared/package-files/a5/a52c729029203f0713fd8909865401bb4f17481b6d71fc108df2310f58297347/em.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..37a3dea2e24a5d1ccb62f4b4531f03bddc75c96b
--- /dev/null
+++ b/shared/package-files/a5/a52c729029203f0713fd8909865401bb4f17481b6d71fc108df2310f58297347/em.c.pysam.c
@@ -0,0 +1,261 @@
+#include "bcftools.pysam.h"
+
+/*  em.c -- mathematical functions.
+
+    Copyright (C) 2010, 2011 Broad Institute.
+    Portions copyright (C) 2013-2014 Genome Research Ltd.
+
+    Author: Heng Li 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.  */
+
+#include 
+#include 
+#include 
+#include 
+#include "kmin.h"
+#include "call.h"
+
+#define ITER_MAX 50
+#define ITER_TRY 10
+#define EPS 1e-5
+
+extern double kf_gammaq(double, double);
+
+/*
+    Generic routines
+ */
+
+// estimate site allele frequency in a very naive and inaccurate way
+static double est_freq(int n, const double *pdg)
+{
+    int i, gcnt[3], tmp1;
+    // get a rough estimate of the genotype frequency
+    gcnt[0] = gcnt[1] = gcnt[2] = 0;
+    for (i = 0; i < n; ++i) {
+        const double *p = pdg + i * 3;
+        if (p[0] != 1. || p[1] != 1. || p[2] != 1.) {
+            int which = p[0] > p[1]? 0 : 1;
+            which = p[which] > p[2]? which : 2;
+            ++gcnt[which];
+        }
+    }
+    tmp1 = gcnt[0] + gcnt[1] + gcnt[2];
+    return (tmp1 == 0)? -1.0 : (.5 * gcnt[1] + gcnt[2]) / tmp1;
+}
+
+/*
+    Single-locus EM
+ */
+
+typedef struct {
+    int beg, end;
+    const double *pdg;
+} minaux1_t;
+
+static double prob1(double f, void *data)
+{
+    minaux1_t *a = (minaux1_t*)data;
+    double p = 1., l = 0., f3[3];
+    int i;
+//  fprintf(bcftools_stdout, "brent %lg\n", f);
+    if (f < 0 || f > 1) return 1e300;
+    f3[0] = (1.-f)*(1.-f); f3[1] = 2.*f*(1.-f); f3[2] = f*f;
+    for (i = a->beg; i < a->end; ++i) {
+        const double *pdg = a->pdg + i * 3;
+        p *= pdg[0] * f3[0] + pdg[1] * f3[1] + pdg[2] * f3[2];
+        if (p < 1e-200) l -= log(p), p = 1.;
+    }
+    return l - log(p);
+}
+
+// one EM iteration for allele frequency estimate
+static double freq_iter(double *f, const double *_pdg, int beg, int end)
+{
+    double f0 = *f, f3[3], err;
+    int i;
+//  fprintf(bcftools_stdout, "em %lg\n", *f);
+    f3[0] = (1.-f0)*(1.-f0); f3[1] = 2.*f0*(1.-f0); f3[2] = f0*f0;
+    for (i = beg, f0 = 0.; i < end; ++i) {
+        const double *pdg = _pdg + i * 3;
+        f0 += (pdg[1] * f3[1] + 2. * pdg[2] * f3[2])
+            / (pdg[0] * f3[0] + pdg[1] * f3[1] + pdg[2] * f3[2]);
+    }
+    f0 /= (end - beg) * 2;
+    err = fabs(f0 - *f);
+    *f = f0;
+    return err;
+}
+
+/* The following function combines EM and Brent's method. When the signal from
+ * the data is strong, EM is faster but sometimes, EM may converge very slowly.
+ * When this happens, we switch to Brent's method. The idea is learned from
+ * Rasmus Nielsen.
+ */
+static double freqml(double f0, int beg, int end, const double *pdg)
+{
+    int i;
+    double f;
+    for (i = 0, f = f0; i < ITER_TRY; ++i)
+        if (freq_iter(&f, pdg, beg, end) < EPS) break;
+    if (i == ITER_TRY) { // haven't converged yet; try Brent's method
+        minaux1_t a;
+        a.beg = beg; a.end = end; a.pdg = pdg;
+        kmin_brent(prob1, f0 == f? .5*f0 : f0, f, (void*)&a, EPS, &f);
+    }
+    return f;
+}
+
+// one EM iteration for genotype frequency estimate
+static double g3_iter(double g[3], const double *_pdg, int beg, int end)
+{
+    double err, gg[3];
+    int i;
+    gg[0] = gg[1] = gg[2] = 0.;
+//  fprintf(bcftools_stdout, "%lg,%lg,%lg\n", g[0], g[1], g[2]);
+    for (i = beg; i < end; ++i) {
+        double sum, tmp[3];
+        const double *pdg = _pdg + i * 3;
+        tmp[0] = pdg[0] * g[0]; tmp[1] = pdg[1] * g[1]; tmp[2] = pdg[2] * g[2];
+        sum = (tmp[0] + tmp[1] + tmp[2]) * (end - beg);
+        gg[0] += tmp[0] / sum; gg[1] += tmp[1] / sum; gg[2] += tmp[2] / sum;
+    }
+    err = fabs(gg[0] - g[0]) > fabs(gg[1] - g[1])? fabs(gg[0] - g[0]) : fabs(gg[1] - g[1]);
+    err = err > fabs(gg[2] - g[2])? err : fabs(gg[2] - g[2]);
+    g[0] = gg[0]; g[1] = gg[1]; g[2] = gg[2];
+    return err;
+}
+
+// perform likelihood ratio test
+static double lk_ratio_test(int n, int n1, const double *pdg, double f3[3][3])
+{
+    double r;
+    int i;
+    for (i = 0, r = 1.; i < n1; ++i) {
+        const double *p = pdg + i * 3;
+        r *= (p[0] * f3[1][0] + p[1] * f3[1][1] + p[2] * f3[1][2])
+            / (p[0] * f3[0][0] + p[1] * f3[0][1] + p[2] * f3[0][2]);
+    }
+    for (; i < n; ++i) {
+        const double *p = pdg + i * 3;
+        r *= (p[0] * f3[2][0] + p[1] * f3[2][1] + p[2] * f3[2][2])
+            / (p[0] * f3[0][0] + p[1] * f3[0][1] + p[2] * f3[0][2]);
+    }
+    return r;
+}
+
+// x[0]: ref frequency
+// x[1..3]: alt-alt, alt-ref, ref-ref frequenc
+// x[4]: HWE P-value
+// x[5..6]: group1 freq, group2 freq
+// x[7]: 1-degree P-value
+// x[8]: 2-degree P-value
+int bcf_em1(call_t *call, const bcf1_t *rec, int n1, int flag, double x[10])
+{
+    double *pdg;
+    int i, n; //, n2;
+    if (rec->n_allele < 2) return -1; // one allele only
+    // initialization
+    if (n1 < 0 || n1 > rec->n_sample) n1 = 0;
+    if (flag & 1<<7) flag |= 7<<5; // compute group freq if LRT is required
+    if (flag & 0xf<<1) flag |= 0xf<<1;
+    n = rec->n_sample; //n2 = n - n1;
+    pdg = call->pdg;
+    if (pdg == 0) return -1;
+    for (i = 0; i < 10; ++i) x[i] = -1.; // set to negative
+    {
+        if ((x[0] = est_freq(n, pdg)) < 0.) return -1; // no data
+        x[0] = freqml(x[0], 0, n, pdg);
+    }
+    if (flag & (0xf<<1|3<<8)) { // estimate the genotype frequency and test HWE
+        double *g = x + 1, f3[3], r;
+        f3[0] = g[0] = (1 - x[0]) * (1 - x[0]);
+        f3[1] = g[1] = 2 * x[0] * (1 - x[0]);
+        f3[2] = g[2] = x[0] * x[0];
+        for (i = 0; i < ITER_MAX; ++i)
+            if (g3_iter(g, pdg, 0, n) < EPS) break;
+        // Hardy-Weinberg equilibrium (HWE)
+        for (i = 0, r = 1.; i < n; ++i) {
+            double *p = pdg + i * 3;
+            r *= (p[0] * g[0] + p[1] * g[1] + p[2] * g[2]) / (p[0] * f3[0] + p[1] * f3[1] + p[2] * f3[2]);
+        }
+        x[4] = kf_gammaq(.5, log(r));
+    }
+    if ((flag & 7<<5) && n1 > 0 && n1 < n) { // group frequency
+        x[5] = freqml(x[0], 0, n1, pdg);
+        x[6] = freqml(x[0], n1, n, pdg);
+    }
+    if ((flag & 1<<7) && n1 > 0 && n1 < n) { // 1-degree P-value
+        double f[3], f3[3][3], tmp;
+        f[0] = x[0]; f[1] = x[5]; f[2] = x[6];
+        for (i = 0; i < 3; ++i)
+            f3[i][0] = (1-f[i])*(1-f[i]), f3[i][1] = 2*f[i]*(1-f[i]), f3[i][2] = f[i]*f[i];
+        tmp = log(lk_ratio_test(n, n1, pdg, f3));
+        if (tmp < 0) tmp = 0;
+        x[7] = kf_gammaq(.5, tmp);
+    }
+    if ((flag & 3<<8) && n1 > 0 && n1 < n) { // 2-degree P-value
+        double g[3][3], tmp;
+        for (i = 0; i < 3; ++i) memcpy(g[i], x + 1, 3 * sizeof(double));
+        for (i = 0; i < ITER_MAX; ++i)
+            if (g3_iter(g[1], pdg, 0, n1) < EPS) break;
+        for (i = 0; i < ITER_MAX; ++i)
+            if (g3_iter(g[2], pdg, n1, n) < EPS) break;
+        tmp = log(lk_ratio_test(n, n1, pdg, g));
+        if (tmp < 0) tmp = 0;
+        x[8] = kf_gammaq(1., tmp);
+    }
+    return 0;
+}
+
+/*
+    Two-locus EM (LD)
+ */
+
+#define _G1(h, k) ((h>>1&1) + (k>>1&1))
+#define _G2(h, k) ((h&1) + (k&1))
+
+#if 0
+// 0: the previous site; 1: the current site
+static int pair_freq_iter(int n, double *pdg[2], double f[4])
+{
+    double ff[4];
+    int i, k, h;
+//  fprintf(bcftools_stdout, "%lf,%lf,%lf,%lf\n", f[0], f[1], f[2], f[3]);
+    memset(ff, 0, 4 * sizeof(double));
+    for (i = 0; i < n; ++i) {
+        double *p[2], sum, tmp;
+        p[0] = pdg[0] + i * 3; p[1] = pdg[1] + i * 3;
+        for (k = 0, sum = 0.; k < 4; ++k)
+            for (h = 0; h < 4; ++h)
+                sum += f[k] * f[h] * p[0][_G1(k,h)] * p[1][_G2(k,h)];
+        for (k = 0; k < 4; ++k) {
+            tmp = f[0] * (p[0][_G1(0,k)] * p[1][_G2(0,k)] + p[0][_G1(k,0)] * p[1][_G2(k,0)])
+                + f[1] * (p[0][_G1(1,k)] * p[1][_G2(1,k)] + p[0][_G1(k,1)] * p[1][_G2(k,1)])
+                + f[2] * (p[0][_G1(2,k)] * p[1][_G2(2,k)] + p[0][_G1(k,2)] * p[1][_G2(k,2)])
+                + f[3] * (p[0][_G1(3,k)] * p[1][_G2(3,k)] + p[0][_G1(k,3)] * p[1][_G2(k,3)]);
+            ff[k] += f[k] * tmp / sum;
+        }
+    }
+    for (k = 0; k < 4; ++k) f[k] = ff[k] / (2 * n);
+    return 0;
+}
+#endif
+
+
diff --git a/shared/package-files/a5/a52d7fbd0eb876d2b183ee4dcd7a1e4b2fcffe533c862c71a9eae23e7da299ce/nanmedian.h b/shared/package-files/a5/a52d7fbd0eb876d2b183ee4dcd7a1e4b2fcffe533c862c71a9eae23e7da299ce/nanmedian.h
new file mode 100644
index 0000000000000000000000000000000000000000..cb44c2f0be21aabafcda619e5bed561a0db9fe81
--- /dev/null
+++ b/shared/package-files/a5/a52d7fbd0eb876d2b183ee4dcd7a1e4b2fcffe533c862c71a9eae23e7da299ce/nanmedian.h
@@ -0,0 +1,68 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::nanmedian(Tensor self) -> Tensor
+inline at::Tensor nanmedian(const at::Tensor & self) {
+    return at::_ops::nanmedian::call(self);
+}
+
+// aten::nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+inline ::std::tuple nanmedian(const at::Tensor & self, int64_t dim, bool keepdim=false) {
+    return at::_ops::nanmedian_dim::call(self, dim, keepdim);
+}
+
+// aten::nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+inline ::std::tuple nanmedian_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t dim, bool keepdim=false) {
+    return at::_ops::nanmedian_dim_values::call(self, dim, keepdim, values, indices);
+}
+// aten::nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+inline ::std::tuple nanmedian_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & values, at::Tensor & indices) {
+    return at::_ops::nanmedian_dim_values::call(self, dim, keepdim, values, indices);
+}
+
+// aten::nanmedian.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+inline ::std::tuple nanmedian(const at::Tensor & self, at::Dimname dim, bool keepdim=false) {
+    return at::_ops::nanmedian_names_dim::call(self, dim, keepdim);
+}
+
+// aten::nanmedian.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+inline ::std::tuple nanmedian_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, at::Dimname dim, bool keepdim=false) {
+    return at::_ops::nanmedian_names_dim_values::call(self, dim, keepdim, values, indices);
+}
+// aten::nanmedian.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+inline ::std::tuple nanmedian_outf(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & values, at::Tensor & indices) {
+    return at::_ops::nanmedian_names_dim_values::call(self, dim, keepdim, values, indices);
+}
+
+// aten::nanmedian.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & nanmedian_out(at::Tensor & out, const at::Tensor & self) {
+    return at::_ops::nanmedian_out::call(self, out);
+}
+// aten::nanmedian.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & nanmedian_outf(const at::Tensor & self, at::Tensor & out) {
+    return at::_ops::nanmedian_out::call(self, out);
+}
+
+}
diff --git a/shared/package-files/a5/a531e3f43d910f7915a0f6edac0c967abcdd196fbd5ce1fd2d8ddd7f28886c2a/atan2_meta.h b/shared/package-files/a5/a531e3f43d910f7915a0f6edac0c967abcdd196fbd5ce1fd2d8ddd7f28886c2a/atan2_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..f135a917b01a1ab9aef62d485c03cfadbc8c71d8
--- /dev/null
+++ b/shared/package-files/a5/a531e3f43d910f7915a0f6edac0c967abcdd196fbd5ce1fd2d8ddd7f28886c2a/atan2_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_atan2 : public TensorIteratorBase {
+    
+    
+    void meta(const at::Tensor & self, const at::Tensor & other);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/a5/a549155d07487a42be39c99aaa9ad8329edcc0d0f7b7ce18d94db968cb5852ad/test_logical_ops.py b/shared/package-files/a5/a549155d07487a42be39c99aaa9ad8329edcc0d0f7b7ce18d94db968cb5852ad/test_logical_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..16ca3a202f1e0242104d9516b4dd2318599cefef
--- /dev/null
+++ b/shared/package-files/a5/a549155d07487a42be39c99aaa9ad8329edcc0d0f7b7ce18d94db968cb5852ad/test_logical_ops.py
@@ -0,0 +1,218 @@
+import operator
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+    CategoricalIndex,
+    DataFrame,
+    Interval,
+    Series,
+    isnull,
+)
+import pandas._testing as tm
+
+
+class TestDataFrameLogicalOperators:
+    # &, |, ^
+
+    @pytest.mark.parametrize(
+        "left, right, op, expected",
+        [
+            (
+                [True, False, np.nan],
+                [True, False, True],
+                operator.and_,
+                [True, False, False],
+            ),
+            (
+                [True, False, True],
+                [True, False, np.nan],
+                operator.and_,
+                [True, False, False],
+            ),
+            (
+                [True, False, np.nan],
+                [True, False, True],
+                operator.or_,
+                [True, False, False],
+            ),
+            (
+                [True, False, True],
+                [True, False, np.nan],
+                operator.or_,
+                [True, False, True],
+            ),
+        ],
+    )
+    def test_logical_operators_nans(self, left, right, op, expected, frame_or_series):
+        # GH#13896
+        result = op(frame_or_series(left), frame_or_series(right))
+        expected = frame_or_series(expected)
+
+        tm.assert_equal(result, expected)
+
+    def test_logical_ops_empty_frame(self):
+        # GH#5808
+        # empty frames, non-mixed dtype
+        df = DataFrame(index=[1])
+
+        result = df & df
+        tm.assert_frame_equal(result, df)
+
+        result = df | df
+        tm.assert_frame_equal(result, df)
+
+        df2 = DataFrame(index=[1, 2])
+        result = df & df2
+        tm.assert_frame_equal(result, df2)
+
+        dfa = DataFrame(index=[1], columns=["A"])
+
+        result = dfa & dfa
+        expected = DataFrame(False, index=[1], columns=["A"])
+        tm.assert_frame_equal(result, expected)
+
+    def test_logical_ops_bool_frame(self):
+        # GH#5808
+        df1a_bool = DataFrame(True, index=[1], columns=["A"])
+
+        result = df1a_bool & df1a_bool
+        tm.assert_frame_equal(result, df1a_bool)
+
+        result = df1a_bool | df1a_bool
+        tm.assert_frame_equal(result, df1a_bool)
+
+    def test_logical_ops_int_frame(self):
+        # GH#5808
+        df1a_int = DataFrame(1, index=[1], columns=["A"])
+        df1a_bool = DataFrame(True, index=[1], columns=["A"])
+
+        result = df1a_int | df1a_bool
+        tm.assert_frame_equal(result, df1a_bool)
+
+        # Check that this matches Series behavior
+        res_ser = df1a_int["A"] | df1a_bool["A"]
+        tm.assert_series_equal(res_ser, df1a_bool["A"])
+
+    def test_logical_ops_invalid(self, using_infer_string):
+        # GH#5808
+
+        df1 = DataFrame(1.0, index=[1], columns=["A"])
+        df2 = DataFrame(True, index=[1], columns=["A"])
+        msg = re.escape("unsupported operand type(s) for |: 'float' and 'bool'")
+        with pytest.raises(TypeError, match=msg):
+            df1 | df2
+
+        df1 = DataFrame("foo", index=[1], columns=["A"])
+        df2 = DataFrame(True, index=[1], columns=["A"])
+        msg = re.escape("unsupported operand type(s) for |: 'str' and 'bool'")
+        if using_infer_string:
+            import pyarrow as pa
+
+            with pytest.raises(pa.lib.ArrowNotImplementedError, match="|has no kernel"):
+                df1 | df2
+        else:
+            with pytest.raises(TypeError, match=msg):
+                df1 | df2
+
+    def test_logical_operators(self):
+        def _check_bin_op(op):
+            result = op(df1, df2)
+            expected = DataFrame(
+                op(df1.values, df2.values), index=df1.index, columns=df1.columns
+            )
+            assert result.values.dtype == np.bool_
+            tm.assert_frame_equal(result, expected)
+
+        def _check_unary_op(op):
+            result = op(df1)
+            expected = DataFrame(op(df1.values), index=df1.index, columns=df1.columns)
+            assert result.values.dtype == np.bool_
+            tm.assert_frame_equal(result, expected)
+
+        df1 = {
+            "a": {"a": True, "b": False, "c": False, "d": True, "e": True},
+            "b": {"a": False, "b": True, "c": False, "d": False, "e": False},
+            "c": {"a": False, "b": False, "c": True, "d": False, "e": False},
+            "d": {"a": True, "b": False, "c": False, "d": True, "e": True},
+            "e": {"a": True, "b": False, "c": False, "d": True, "e": True},
+        }
+
+        df2 = {
+            "a": {"a": True, "b": False, "c": True, "d": False, "e": False},
+            "b": {"a": False, "b": True, "c": False, "d": False, "e": False},
+            "c": {"a": True, "b": False, "c": True, "d": False, "e": False},
+            "d": {"a": False, "b": False, "c": False, "d": True, "e": False},
+            "e": {"a": False, "b": False, "c": False, "d": False, "e": True},
+        }
+
+        df1 = DataFrame(df1)
+        df2 = DataFrame(df2)
+
+        _check_bin_op(operator.and_)
+        _check_bin_op(operator.or_)
+        _check_bin_op(operator.xor)
+
+        _check_unary_op(operator.inv)  # TODO: belongs elsewhere
+
+    @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")
+    def test_logical_with_nas(self):
+        d = DataFrame({"a": [np.nan, False], "b": [True, True]})
+
+        # GH4947
+        # bool comparisons should return bool
+        result = d["a"] | d["b"]
+        expected = Series([False, True])
+        tm.assert_series_equal(result, expected)
+
+        # GH4604, automatic casting here
+        result = d["a"].fillna(False) | d["b"]
+        expected = Series([True, True])
+        tm.assert_series_equal(result, expected)
+
+        msg = "The 'downcast' keyword in fillna is deprecated"
+        with tm.assert_produces_warning(FutureWarning, match=msg):
+            result = d["a"].fillna(False, downcast=False) | d["b"]
+        expected = Series([True, True])
+        tm.assert_series_equal(result, expected)
+
+    def test_logical_ops_categorical_columns(self):
+        # GH#38367
+        intervals = [Interval(1, 2), Interval(3, 4)]
+        data = DataFrame(
+            [[1, np.nan], [2, np.nan]],
+            columns=CategoricalIndex(
+                intervals, categories=intervals + [Interval(5, 6)]
+            ),
+        )
+        mask = DataFrame(
+            [[False, False], [False, False]], columns=data.columns, dtype=bool
+        )
+        result = mask | isnull(data)
+        expected = DataFrame(
+            [[False, True], [False, True]],
+            columns=CategoricalIndex(
+                intervals, categories=intervals + [Interval(5, 6)]
+            ),
+        )
+        tm.assert_frame_equal(result, expected)
+
+    def test_int_dtype_different_index_not_bool(self):
+        # GH 52500
+        df1 = DataFrame([1, 2, 3], index=[10, 11, 23], columns=["a"])
+        df2 = DataFrame([10, 20, 30], index=[11, 10, 23], columns=["a"])
+        result = np.bitwise_xor(df1, df2)
+        expected = DataFrame([21, 8, 29], index=[10, 11, 23], columns=["a"])
+        tm.assert_frame_equal(result, expected)
+
+        result = df1 ^ df2
+        tm.assert_frame_equal(result, expected)
+
+    def test_different_dtypes_different_index_raises(self):
+        # GH 52538
+        df1 = DataFrame([1, 2], index=["a", "b"])
+        df2 = DataFrame([3, 4], index=["b", "c"])
+        with pytest.raises(TypeError, match="unsupported operand type"):
+            df1 & df2
diff --git a/shared/package-files/a5/a553dab3bb8d51bc9a9e3727aa250e54cd5bab2be20e3e444b81d004d6d2951c/hub.py b/shared/package-files/a5/a553dab3bb8d51bc9a9e3727aa250e54cd5bab2be20e3e444b81d004d6d2951c/hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2ad124f9286044bd04594c197fd0cf8e0f34a56
--- /dev/null
+++ b/shared/package-files/a5/a553dab3bb8d51bc9a9e3727aa250e54cd5bab2be20e3e444b81d004d6d2951c/hub.py
@@ -0,0 +1,875 @@
+# mypy: allow-untyped-defs
+import contextlib
+import errno
+import hashlib
+import json
+import os
+import re
+import shutil
+import sys
+import tempfile
+import uuid
+import warnings
+import zipfile
+from pathlib import Path
+from typing import Any, Optional, Union
+from typing_extensions import deprecated
+from urllib.error import HTTPError, URLError
+from urllib.parse import urlparse  # noqa: F401
+from urllib.request import Request, urlopen
+
+import torch
+from torch.serialization import MAP_LOCATION
+
+
+class _Faketqdm:  # type: ignore[no-redef]
+    def __init__(self, total=None, disable=False, unit=None, *args, **kwargs):
+        self.total = total
+        self.disable = disable
+        self.n = 0
+        # Ignore all extra *args and **kwargs lest you want to reinvent tqdm
+
+    def update(self, n):
+        if self.disable:
+            return
+
+        self.n += n
+        if self.total is None:
+            sys.stderr.write(f"\r{self.n:.1f} bytes")
+        else:
+            sys.stderr.write(f"\r{100 * self.n / float(self.total):.1f}%")
+        sys.stderr.flush()
+
+    # Don't bother implementing; use real tqdm if you want
+    def set_description(self, *args, **kwargs):
+        pass
+
+    def write(self, s):
+        sys.stderr.write(f"{s}\n")
+
+    def close(self):
+        self.disable = True
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        if self.disable:
+            return
+
+        sys.stderr.write("\n")
+
+
+try:
+    from tqdm import tqdm  # If tqdm is installed use it, otherwise use the fake wrapper
+except ImportError:
+    tqdm = _Faketqdm
+
+__all__ = [
+    "download_url_to_file",
+    "get_dir",
+    "help",
+    "list",
+    "load",
+    "load_state_dict_from_url",
+    "set_dir",
+]
+
+# matches bfd8deac from resnet18-bfd8deac.pth
+HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
+
+_TRUSTED_REPO_OWNERS = (
+    "facebookresearch",
+    "facebookincubator",
+    "pytorch",
+    "fairinternal",
+)
+ENV_GITHUB_TOKEN = "GITHUB_TOKEN"
+ENV_TORCH_HOME = "TORCH_HOME"
+ENV_XDG_CACHE_HOME = "XDG_CACHE_HOME"
+DEFAULT_CACHE_DIR = "~/.cache"
+VAR_DEPENDENCY = "dependencies"
+MODULE_HUBCONF = "hubconf.py"
+READ_DATA_CHUNK = 128 * 1024
+_hub_dir: Optional[str] = None
+
+
+@contextlib.contextmanager
+def _add_to_sys_path(path):
+    sys.path.insert(0, path)
+    try:
+        yield
+    finally:
+        sys.path.remove(path)
+
+
+# Copied from tools/shared/module_loader to be included in torch package
+def _import_module(name, path):
+    import importlib.util
+    from importlib.abc import Loader
+
+    spec = importlib.util.spec_from_file_location(name, path)
+    assert spec is not None
+    module = importlib.util.module_from_spec(spec)
+    assert isinstance(spec.loader, Loader)
+    spec.loader.exec_module(module)
+    return module
+
+
+def _remove_if_exists(path):
+    if os.path.exists(path):
+        if os.path.isfile(path):
+            os.remove(path)
+        else:
+            shutil.rmtree(path)
+
+
+def _git_archive_link(repo_owner, repo_name, ref):
+    # See https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip
+    return f"https://github.com/{repo_owner}/{repo_name}/zipball/{ref}"
+
+
+def _load_attr_from_module(module, func_name):
+    # Check if callable is defined in the module
+    if func_name not in dir(module):
+        return None
+    return getattr(module, func_name)
+
+
+def _get_torch_home():
+    torch_home = os.path.expanduser(
+        os.getenv(
+            ENV_TORCH_HOME,
+            os.path.join(os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), "torch"),
+        )
+    )
+    return torch_home
+
+
+def _parse_repo_info(github):
+    if ":" in github:
+        repo_info, ref = github.split(":")
+    else:
+        repo_info, ref = github, None
+    repo_owner, repo_name = repo_info.split("/")
+
+    if ref is None:
+        # The ref wasn't specified by the user, so we need to figure out the
+        # default branch: main or master. Our assumption is that if main exists
+        # then it's the default branch, otherwise it's master.
+        try:
+            with urlopen(f"https://github.com/{repo_owner}/{repo_name}/tree/main/"):
+                ref = "main"
+        except HTTPError as e:
+            if e.code == 404:
+                ref = "master"
+            else:
+                raise
+        except URLError as e:
+            # No internet connection, need to check for cache as last resort
+            for possible_ref in ("main", "master"):
+                if os.path.exists(
+                    f"{get_dir()}/{repo_owner}_{repo_name}_{possible_ref}"
+                ):
+                    ref = possible_ref
+                    break
+            if ref is None:
+                raise RuntimeError(
+                    "It looks like there is no internet connection and the "
+                    f"repo could not be found in the cache ({get_dir()})"
+                ) from e
+    return repo_owner, repo_name, ref
+
+
+def _read_url(url):
+    with urlopen(url) as r:
+        return r.read().decode(r.headers.get_content_charset("utf-8"))
+
+
+def _validate_not_a_forked_repo(repo_owner, repo_name, ref):
+    # Use urlopen to avoid depending on local git.
+    headers = {"Accept": "application/vnd.github.v3+json"}
+    token = os.environ.get(ENV_GITHUB_TOKEN)
+    if token is not None:
+        headers["Authorization"] = f"token {token}"
+    for url_prefix in (
+        f"https://api.github.com/repos/{repo_owner}/{repo_name}/branches",
+        f"https://api.github.com/repos/{repo_owner}/{repo_name}/tags",
+    ):
+        page = 0
+        while True:
+            page += 1
+            url = f"{url_prefix}?per_page=100&page={page}"
+            response = json.loads(_read_url(Request(url, headers=headers)))
+            # Empty response means no more data to process
+            if not response:
+                break
+            for br in response:
+                if br["name"] == ref or br["commit"]["sha"].startswith(ref):
+                    return
+
+    raise ValueError(
+        f"Cannot find {ref} in https://github.com/{repo_owner}/{repo_name}. "
+        "If it's a commit from a forked repo, please call hub.load() with forked repo directly."
+    )
+
+
+def _get_cache_or_reload(
+    github,
+    force_reload,
+    trust_repo,
+    calling_fn,
+    verbose=True,
+    skip_validation=False,
+):
+    # Setup hub_dir to save downloaded files
+    hub_dir = get_dir()
+    os.makedirs(hub_dir, exist_ok=True)
+    # Parse github repo information
+    repo_owner, repo_name, ref = _parse_repo_info(github)
+    # Github allows branch name with slash '/',
+    # this causes confusion with path on both Linux and Windows.
+    # Backslash is not allowed in Github branch name so no need to
+    # to worry about it.
+    normalized_br = ref.replace("/", "_")
+    # Github renames folder repo-v1.x.x to repo-1.x.x
+    # We don't know the repo name before downloading the zip file
+    # and inspect name from it.
+    # To check if cached repo exists, we need to normalize folder names.
+    owner_name_branch = "_".join([repo_owner, repo_name, normalized_br])
+    repo_dir = os.path.join(hub_dir, owner_name_branch)
+    # Check that the repo is in the trusted list
+    _check_repo_is_trusted(
+        repo_owner,
+        repo_name,
+        owner_name_branch,
+        trust_repo=trust_repo,
+        calling_fn=calling_fn,
+    )
+
+    use_cache = (not force_reload) and os.path.exists(repo_dir)
+
+    if use_cache:
+        if verbose:
+            sys.stderr.write(f"Using cache found in {repo_dir}\n")
+    else:
+        # Validate the tag/branch is from the original repo instead of a forked repo
+        if not skip_validation:
+            _validate_not_a_forked_repo(repo_owner, repo_name, ref)
+
+        cached_file = os.path.join(hub_dir, normalized_br + ".zip")
+        _remove_if_exists(cached_file)
+
+        try:
+            url = _git_archive_link(repo_owner, repo_name, ref)
+            sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n')
+            download_url_to_file(url, cached_file, progress=False)
+        except HTTPError as err:
+            if err.code == 300:
+                # Getting a 300 Multiple Choices error likely means that the ref is both a tag and a branch
+                # in the repo. This can be disambiguated by explicitely using refs/heads/ or refs/tags
+                # See https://git-scm.com/book/en/v2/Git-Internals-Git-References
+                # Here, we do the same as git: we throw a warning, and assume the user wanted the branch
+                warnings.warn(
+                    f"The ref {ref} is ambiguous. Perhaps it is both a tag and a branch in the repo? "
+                    "Torchhub will now assume that it's a branch. "
+                    "You can disambiguate tags and branches by explicitly passing refs/heads/branch_name or "
+                    "refs/tags/tag_name as the ref. That might require using skip_validation=True."
+                )
+                disambiguated_branch_ref = f"refs/heads/{ref}"
+                url = _git_archive_link(
+                    repo_owner, repo_name, ref=disambiguated_branch_ref
+                )
+                download_url_to_file(url, cached_file, progress=False)
+            else:
+                raise
+
+        with zipfile.ZipFile(cached_file) as cached_zipfile:
+            extraced_repo_name = cached_zipfile.infolist()[0].filename
+            extracted_repo = os.path.join(hub_dir, extraced_repo_name)
+            _remove_if_exists(extracted_repo)
+            # Unzip the code and rename the base folder
+            cached_zipfile.extractall(hub_dir)
+
+        _remove_if_exists(cached_file)
+        _remove_if_exists(repo_dir)
+        shutil.move(extracted_repo, repo_dir)  # rename the repo
+
+    return repo_dir
+
+
+def _check_repo_is_trusted(
+    repo_owner,
+    repo_name,
+    owner_name_branch,
+    trust_repo,
+    calling_fn="load",
+):
+    hub_dir = get_dir()
+    filepath = os.path.join(hub_dir, "trusted_list")
+
+    if not os.path.exists(filepath):
+        Path(filepath).touch()
+    with open(filepath) as file:
+        trusted_repos = tuple(line.strip() for line in file)
+
+    # To minimize friction of introducing the new trust_repo mechanism, we consider that
+    # if a repo was already downloaded by torchhub, then it is already trusted (even if it's not in the allowlist)
+    trusted_repos_legacy = next(os.walk(hub_dir))[1]
+
+    owner_name = "_".join([repo_owner, repo_name])
+    is_trusted = (
+        owner_name in trusted_repos
+        or owner_name_branch in trusted_repos_legacy
+        or repo_owner in _TRUSTED_REPO_OWNERS
+    )
+
+    # TODO: Remove `None` option in 2.0 and change the default to "check"
+    if trust_repo is None:
+        if not is_trusted:
+            warnings.warn(
+                "You are about to download and run code from an untrusted repository. In a future release, this won't "
+                "be allowed. To add the repository to your trusted list, change the command to {calling_fn}(..., "
+                "trust_repo=False) and a command prompt will appear asking for an explicit confirmation of trust, "
+                f"or {calling_fn}(..., trust_repo=True), which will assume that the prompt is to be answered with "
+                f"'yes'. You can also use {calling_fn}(..., trust_repo='check') which will only prompt for "
+                f"confirmation if the repo is not already trusted. This will eventually be the default behaviour"
+            )
+        return
+
+    if (trust_repo is False) or (trust_repo == "check" and not is_trusted):
+        response = input(
+            f"The repository {owner_name} does not belong to the list of trusted repositories and as such cannot be downloaded. "
+            "Do you trust this repository and wish to add it to the trusted list of repositories (y/N)?"
+        )
+        if response.lower() in ("y", "yes"):
+            if is_trusted:
+                print("The repository is already trusted.")
+        elif response.lower() in ("n", "no", ""):
+            raise Exception("Untrusted repository.")  # noqa: TRY002
+        else:
+            raise ValueError(f"Unrecognized response {response}.")
+
+    # At this point we're sure that the user trusts the repo (or wants to trust it)
+    if not is_trusted:
+        with open(filepath, "a") as file:
+            file.write(owner_name + "\n")
+
+
+def _check_module_exists(name):
+    import importlib.util
+
+    return importlib.util.find_spec(name) is not None
+
+
+def _check_dependencies(m):
+    dependencies = _load_attr_from_module(m, VAR_DEPENDENCY)
+
+    if dependencies is not None:
+        missing_deps = [pkg for pkg in dependencies if not _check_module_exists(pkg)]
+        if len(missing_deps):
+            raise RuntimeError(f"Missing dependencies: {', '.join(missing_deps)}")
+
+
+def _load_entry_from_hubconf(m, model):
+    if not isinstance(model, str):
+        raise ValueError("Invalid input: model should be a string of function name")
+
+    # Note that if a missing dependency is imported at top level of hubconf, it will
+    # throw before this function. It's a chicken and egg situation where we have to
+    # load hubconf to know what're the dependencies, but to import hubconf it requires
+    # a missing package. This is fine, Python will throw proper error message for users.
+    _check_dependencies(m)
+
+    func = _load_attr_from_module(m, model)
+
+    if func is None or not callable(func):
+        raise RuntimeError(f"Cannot find callable {model} in hubconf")
+
+    return func
+
+
+def get_dir() -> str:
+    r"""
+    Get the Torch Hub cache directory used for storing downloaded models & weights.
+
+    If :func:`~torch.hub.set_dir` is not called, default path is ``$TORCH_HOME/hub`` where
+    environment variable ``$TORCH_HOME`` defaults to ``$XDG_CACHE_HOME/torch``.
+    ``$XDG_CACHE_HOME`` follows the X Design Group specification of the Linux
+    filesystem layout, with a default value ``~/.cache`` if the environment
+    variable is not set.
+    """
+    # Issue warning to move data if old env is set
+    if os.getenv("TORCH_HUB"):
+        warnings.warn("TORCH_HUB is deprecated, please use env TORCH_HOME instead")
+
+    if _hub_dir is not None:
+        return _hub_dir
+    return os.path.join(_get_torch_home(), "hub")
+
+
+def set_dir(d: Union[str, os.PathLike]) -> None:
+    r"""
+    Optionally set the Torch Hub directory used to save downloaded models & weights.
+
+    Args:
+        d (str): path to a local folder to save downloaded models & weights.
+    """
+    global _hub_dir
+    _hub_dir = os.path.expanduser(d)
+
+
+def list(
+    github,
+    force_reload=False,
+    skip_validation=False,
+    trust_repo=None,
+    verbose=True,
+):
+    r"""
+    List all callable entrypoints available in the repo specified by ``github``.
+
+    Args:
+        github (str): a string with format "repo_owner/repo_name[:ref]" with an optional
+            ref (tag or branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if
+            it exists, and otherwise ``master``.
+            Example: 'pytorch/vision:0.10'
+        force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
+            Default is ``False``.
+        skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
+            specified by the ``github`` argument properly belongs to the repo owner. This will make
+            requests to the GitHub API; you can specify a non-default GitHub token by setting the
+            ``GITHUB_TOKEN`` environment variable. Default is ``False``.
+        trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
+            This parameter was introduced in v1.12 and helps ensuring that users
+            only run code from repos that they trust.
+
+            - If ``False``, a prompt will ask the user whether the repo should
+              be trusted.
+            - If ``True``, the repo will be added to the trusted list and loaded
+              without requiring explicit confirmation.
+            - If ``"check"``, the repo will be checked against the list of
+              trusted repos in the cache. If it is not present in that list, the
+              behaviour will fall back onto the ``trust_repo=False`` option.
+            - If ``None``: this will raise a warning, inviting the user to set
+              ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
+              is only present for backward compatibility and will be removed in
+              v2.0.
+
+            Default is ``None`` and will eventually change to ``"check"`` in v2.0.
+        verbose (bool, optional): If ``False``, mute messages about hitting
+            local caches. Note that the message about first download cannot be
+            muted. Default is ``True``.
+
+    Returns:
+        list: The available callables entrypoint
+
+    Example:
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
+        >>> entrypoints = torch.hub.list("pytorch/vision", force_reload=True)
+    """
+    repo_dir = _get_cache_or_reload(
+        github,
+        force_reload,
+        trust_repo,
+        "list",
+        verbose=verbose,
+        skip_validation=skip_validation,
+    )
+
+    with _add_to_sys_path(repo_dir):
+        hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
+        hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
+
+    # We take functions starts with '_' as internal helper functions
+    entrypoints = [
+        f
+        for f in dir(hub_module)
+        if callable(getattr(hub_module, f)) and not f.startswith("_")
+    ]
+
+    return entrypoints
+
+
+def help(github, model, force_reload=False, skip_validation=False, trust_repo=None):
+    r"""
+    Show the docstring of entrypoint ``model``.
+
+    Args:
+        github (str): a string with format  with an optional
+            ref (a tag or a branch). If ``ref`` is not specified, the default branch is assumed
+            to be ``main`` if it exists, and otherwise ``master``.
+            Example: 'pytorch/vision:0.10'
+        model (str): a string of entrypoint name defined in repo's ``hubconf.py``
+        force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
+            Default is ``False``.
+        skip_validation (bool, optional): if ``False``, torchhub will check that the ref
+            specified by the ``github`` argument properly belongs to the repo owner. This will make
+            requests to the GitHub API; you can specify a non-default GitHub token by setting the
+            ``GITHUB_TOKEN`` environment variable. Default is ``False``.
+        trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
+            This parameter was introduced in v1.12 and helps ensuring that users
+            only run code from repos that they trust.
+
+            - If ``False``, a prompt will ask the user whether the repo should
+              be trusted.
+            - If ``True``, the repo will be added to the trusted list and loaded
+              without requiring explicit confirmation.
+            - If ``"check"``, the repo will be checked against the list of
+              trusted repos in the cache. If it is not present in that list, the
+              behaviour will fall back onto the ``trust_repo=False`` option.
+            - If ``None``: this will raise a warning, inviting the user to set
+              ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
+              is only present for backward compatibility and will be removed in
+              v2.0.
+
+            Default is ``None`` and will eventually change to ``"check"`` in v2.0.
+    Example:
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
+        >>> print(torch.hub.help("pytorch/vision", "resnet18", force_reload=True))
+    """
+    repo_dir = _get_cache_or_reload(
+        github,
+        force_reload,
+        trust_repo,
+        "help",
+        verbose=True,
+        skip_validation=skip_validation,
+    )
+
+    with _add_to_sys_path(repo_dir):
+        hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
+        hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
+
+    entry = _load_entry_from_hubconf(hub_module, model)
+
+    return entry.__doc__
+
+
+def load(
+    repo_or_dir,
+    model,
+    *args,
+    source="github",
+    trust_repo=None,
+    force_reload=False,
+    verbose=True,
+    skip_validation=False,
+    **kwargs,
+):
+    r"""
+    Load a model from a github repo or a local directory.
+
+    Note: Loading a model is the typical use case, but this can also be used to
+    for loading other objects such as tokenizers, loss functions, etc.
+
+    If ``source`` is 'github', ``repo_or_dir`` is expected to be
+    of the form ``repo_owner/repo_name[:ref]`` with an optional
+    ref (a tag or a branch).
+
+    If ``source`` is 'local', ``repo_or_dir`` is expected to be a
+    path to a local directory.
+
+    Args:
+        repo_or_dir (str): If ``source`` is 'github',
+            this should correspond to a github repo with format ``repo_owner/repo_name[:ref]`` with
+            an optional ref (tag or branch), for example 'pytorch/vision:0.10'. If ``ref`` is not specified,
+            the default branch is assumed to be ``main`` if it exists, and otherwise ``master``.
+            If ``source`` is 'local'  then it should be a path to a local directory.
+        model (str): the name of a callable (entrypoint) defined in the
+            repo/dir's ``hubconf.py``.
+        *args (optional): the corresponding args for callable ``model``.
+        source (str, optional): 'github' or 'local'. Specifies how
+            ``repo_or_dir`` is to be interpreted. Default is 'github'.
+        trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
+            This parameter was introduced in v1.12 and helps ensuring that users
+            only run code from repos that they trust.
+
+            - If ``False``, a prompt will ask the user whether the repo should
+              be trusted.
+            - If ``True``, the repo will be added to the trusted list and loaded
+              without requiring explicit confirmation.
+            - If ``"check"``, the repo will be checked against the list of
+              trusted repos in the cache. If it is not present in that list, the
+              behaviour will fall back onto the ``trust_repo=False`` option.
+            - If ``None``: this will raise a warning, inviting the user to set
+              ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
+              is only present for backward compatibility and will be removed in
+              v2.0.
+
+            Default is ``None`` and will eventually change to ``"check"`` in v2.0.
+        force_reload (bool, optional): whether to force a fresh download of
+            the github repo unconditionally. Does not have any effect if
+            ``source = 'local'``. Default is ``False``.
+        verbose (bool, optional): If ``False``, mute messages about hitting
+            local caches. Note that the message about first download cannot be
+            muted. Does not have any effect if ``source = 'local'``.
+            Default is ``True``.
+        skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
+            specified by the ``github`` argument properly belongs to the repo owner. This will make
+            requests to the GitHub API; you can specify a non-default GitHub token by setting the
+            ``GITHUB_TOKEN`` environment variable. Default is ``False``.
+        **kwargs (optional): the corresponding kwargs for callable ``model``.
+
+    Returns:
+        The output of the ``model`` callable when called with the given
+        ``*args`` and ``**kwargs``.
+
+    Example:
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
+        >>> # from a github repo
+        >>> repo = "pytorch/vision"
+        >>> model = torch.hub.load(
+        ...     repo, "resnet50", weights="ResNet50_Weights.IMAGENET1K_V1"
+        ... )
+        >>> # from a local directory
+        >>> path = "/some/local/path/pytorch/vision"
+        >>> # xdoctest: +SKIP
+        >>> model = torch.hub.load(path, "resnet50", weights="ResNet50_Weights.DEFAULT")
+    """
+    source = source.lower()
+
+    if source not in ("github", "local"):
+        raise ValueError(
+            f'Unknown source: "{source}". Allowed values: "github" | "local".'
+        )
+
+    if source == "github":
+        repo_or_dir = _get_cache_or_reload(
+            repo_or_dir,
+            force_reload,
+            trust_repo,
+            "load",
+            verbose=verbose,
+            skip_validation=skip_validation,
+        )
+
+    model = _load_local(repo_or_dir, model, *args, **kwargs)
+    return model
+
+
+def _load_local(hubconf_dir, model, *args, **kwargs):
+    r"""
+    Load a model from a local directory with a ``hubconf.py``.
+
+    Args:
+        hubconf_dir (str): path to a local directory that contains a
+            ``hubconf.py``.
+        model (str): name of an entrypoint defined in the directory's
+            ``hubconf.py``.
+        *args (optional): the corresponding args for callable ``model``.
+        **kwargs (optional): the corresponding kwargs for callable ``model``.
+
+    Returns:
+        a single model with corresponding pretrained weights.
+
+    Example:
+        >>> # xdoctest: +SKIP("stub local path")
+        >>> path = "/some/local/path/pytorch/vision"
+        >>> model = _load_local(
+        ...     path,
+        ...     "resnet50",
+        ...     weights="ResNet50_Weights.IMAGENET1K_V1",
+        ... )
+    """
+    with _add_to_sys_path(hubconf_dir):
+        hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF)
+        hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
+
+        entry = _load_entry_from_hubconf(hub_module, model)
+        model = entry(*args, **kwargs)
+
+    return model
+
+
+def download_url_to_file(
+    url: str,
+    dst: str,
+    hash_prefix: Optional[str] = None,
+    progress: bool = True,
+) -> None:
+    r"""Download object at the given URL to a local path.
+
+    Args:
+        url (str): URL of the object to download
+        dst (str): Full path where object will be saved, e.g. ``/tmp/temporary_file``
+        hash_prefix (str, optional): If not None, the SHA256 downloaded file should start with ``hash_prefix``.
+            Default: None
+        progress (bool, optional): whether or not to display a progress bar to stderr
+            Default: True
+
+    Example:
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
+        >>> # xdoctest: +REQUIRES(POSIX)
+        >>> torch.hub.download_url_to_file(
+        ...     "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth",
+        ...     "/tmp/temporary_file",
+        ... )
+
+    """
+    file_size = None
+    req = Request(url, headers={"User-Agent": "torch.hub"})
+    u = urlopen(req)
+    meta = u.info()
+    if hasattr(meta, "getheaders"):
+        content_length = meta.getheaders("Content-Length")
+    else:
+        content_length = meta.get_all("Content-Length")
+    if content_length is not None and len(content_length) > 0:
+        file_size = int(content_length[0])
+
+    # We deliberately save it in a temp file and move it after
+    # download is complete. This prevents a local working checkpoint
+    # being overridden by a broken download.
+    # We deliberately do not use NamedTemporaryFile to avoid restrictive
+    # file permissions being applied to the downloaded file.
+    dst = os.path.expanduser(dst)
+    for _ in range(tempfile.TMP_MAX):
+        tmp_dst = dst + "." + uuid.uuid4().hex + ".partial"
+        try:
+            f = open(tmp_dst, "w+b")
+        except FileExistsError:
+            continue
+        break
+    else:
+        raise FileExistsError(errno.EEXIST, "No usable temporary file name found")
+
+    try:
+        if hash_prefix is not None:
+            sha256 = hashlib.sha256()
+        with tqdm(
+            total=file_size,
+            disable=not progress,
+            unit="B",
+            unit_scale=True,
+            unit_divisor=1024,
+        ) as pbar:
+            while True:
+                buffer = u.read(READ_DATA_CHUNK)
+                if len(buffer) == 0:
+                    break
+                f.write(buffer)  # type: ignore[possibly-undefined]
+                if hash_prefix is not None:
+                    sha256.update(buffer)  # type: ignore[possibly-undefined]
+                pbar.update(len(buffer))
+
+        f.close()
+        if hash_prefix is not None:
+            digest = sha256.hexdigest()  # type: ignore[possibly-undefined]
+            if digest[: len(hash_prefix)] != hash_prefix:
+                raise RuntimeError(
+                    f'invalid hash value (expected "{hash_prefix}", got "{digest}")'
+                )
+        shutil.move(f.name, dst)
+    finally:
+        f.close()
+        if os.path.exists(f.name):
+            os.remove(f.name)
+
+
+# Hub used to support automatically extracts from zipfile manually compressed by users.
+# The legacy zip format expects only one file from torch.save() < 1.6 in the zip.
+# We should remove this support since zipfile is now default zipfile format for torch.save().
+def _is_legacy_zip_format(filename: str) -> bool:
+    if zipfile.is_zipfile(filename):
+        infolist = zipfile.ZipFile(filename).infolist()
+        return len(infolist) == 1 and not infolist[0].is_dir()
+    return False
+
+
+@deprecated(
+    "Falling back to the old format < 1.6. This support will be "
+    "deprecated in favor of default zipfile format introduced in 1.6. "
+    "Please redo torch.save() to save it in the new zipfile format.",
+    category=FutureWarning,
+)
+def _legacy_zip_load(
+    filename: str,
+    model_dir: str,
+    map_location: MAP_LOCATION,
+    weights_only: bool,
+) -> dict[str, Any]:
+    # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.
+    #       We deliberately don't handle tarfile here since our legacy serialization format was in tar.
+    #       E.g. resnet18-5c106cde.pth which is widely used.
+    with zipfile.ZipFile(filename) as f:
+        members = f.infolist()
+        if len(members) != 1:
+            raise RuntimeError("Only one file(not dir) is allowed in the zipfile")
+        f.extractall(model_dir)
+        extraced_name = members[0].filename
+        extracted_file = os.path.join(model_dir, extraced_name)
+    return torch.load(
+        extracted_file, map_location=map_location, weights_only=weights_only
+    )
+
+
+def load_state_dict_from_url(
+    url: str,
+    model_dir: Optional[str] = None,
+    map_location: MAP_LOCATION = None,
+    progress: bool = True,
+    check_hash: bool = False,
+    file_name: Optional[str] = None,
+    weights_only: bool = False,
+) -> dict[str, Any]:
+    r"""Loads the Torch serialized object at the given URL.
+
+    If downloaded file is a zip file, it will be automatically
+    decompressed.
+
+    If the object is already present in `model_dir`, it's deserialized and
+    returned.
+    The default value of ``model_dir`` is ``/checkpoints`` where
+    ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.
+
+    Args:
+        url (str): URL of the object to download
+        model_dir (str, optional): directory in which to save the object
+        map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load)
+        progress (bool, optional): whether or not to display a progress bar to stderr.
+            Default: True
+        check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention
+            ``filename-.ext`` where ```` is the first eight or more
+            digits of the SHA256 hash of the contents of the file. The hash is used to
+            ensure unique names and to verify the contents of the file.
+            Default: False
+        file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set.
+        weights_only(bool, optional): If True, only weights will be loaded and no complex pickled objects.
+            Recommended for untrusted sources. See :func:`~torch.load` for more details.
+
+    Example:
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
+        >>> state_dict = torch.hub.load_state_dict_from_url(
+        ...     "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth"
+        ... )
+
+    """
+    # Issue warning to move data if old env is set
+    if os.getenv("TORCH_MODEL_ZOO"):
+        warnings.warn(
+            "TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead"
+        )
+
+    if model_dir is None:
+        hub_dir = get_dir()
+        model_dir = os.path.join(hub_dir, "checkpoints")
+
+    os.makedirs(model_dir, exist_ok=True)
+
+    parts = urlparse(url)
+    filename = os.path.basename(parts.path)
+    if file_name is not None:
+        filename = file_name
+    cached_file = os.path.join(model_dir, filename)
+    if not os.path.exists(cached_file):
+        sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n')
+        hash_prefix = None
+        if check_hash:
+            r = HASH_REGEX.search(filename)  # r is Optional[Match[str]]
+            hash_prefix = r.group(1) if r else None
+        download_url_to_file(url, cached_file, hash_prefix, progress=progress)
+
+    if _is_legacy_zip_format(cached_file):
+        return _legacy_zip_load(cached_file, model_dir, map_location, weights_only)
+    return torch.load(cached_file, map_location=map_location, weights_only=weights_only)
diff --git a/shared/package-files/a5/a569f95049b5e6026ffe10f7e65bc9874dd4bb0e28efdadb09062f6d7412db19/test_laplace.py b/shared/package-files/a5/a569f95049b5e6026ffe10f7e65bc9874dd4bb0e28efdadb09062f6d7412db19/test_laplace.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb7222d01e3dcb3e14e8d0564610ab553e637155
--- /dev/null
+++ b/shared/package-files/a5/a569f95049b5e6026ffe10f7e65bc9874dd4bb0e28efdadb09062f6d7412db19/test_laplace.py
@@ -0,0 +1,774 @@
+from sympy.integrals.laplace import (
+    laplace_transform, inverse_laplace_transform,
+    LaplaceTransform, InverseLaplaceTransform,
+    _laplace_deep_collect, laplace_correspondence,
+    laplace_initial_conds)
+from sympy.core.function import Function, expand_mul
+from sympy.core import EulerGamma, Subs, Derivative, diff
+from sympy.core.exprtools import factor_terms
+from sympy.core.numbers import I, oo, pi
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol, symbols
+from sympy.simplify.simplify import simplify
+from sympy.functions.elementary.complexes import Abs, re
+from sympy.functions.elementary.exponential import exp, log, exp_polar
+from sympy.functions.elementary.hyperbolic import cosh, sinh, coth, asinh
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import atan, cos, sin
+from sympy.logic.boolalg import And
+from sympy.functions.special.gamma_functions import (
+    lowergamma, gamma, uppergamma)
+from sympy.functions.special.delta_functions import DiracDelta, Heaviside
+from sympy.functions.special.singularity_functions import SingularityFunction
+from sympy.functions.special.zeta_functions import lerchphi
+from sympy.functions.special.error_functions import (
+    fresnelc, fresnels, erf, erfc, Ei, Ci, expint, E1)
+from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
+from sympy.testing.pytest import slow, warns_deprecated_sympy
+from sympy.matrices import Matrix, eye
+from sympy.abc import s
+
+
+@slow
+def test_laplace_transform():
+    LT = laplace_transform
+    ILT = inverse_laplace_transform
+    a, b, c = symbols('a, b, c', positive=True)
+    np = symbols('np', integer=True, positive=True)
+    t, w, x = symbols('t, w, x')
+    f = Function('f')
+    F = Function('F')
+    g = Function('g')
+    y = Function('y')
+    Y = Function('Y')
+
+    # Test helper functions
+    assert (
+        _laplace_deep_collect(exp((t+a)*(t+b)) +
+                              besselj(2, exp((t+a)*(t+b)-t**2)), t) ==
+        exp(a*b + t**2 + t*(a + b)) + besselj(2, exp(a*b + t*(a + b))))
+    L = laplace_transform(diff(y(t), t, 3), t, s, noconds=True)
+    L = laplace_correspondence(L, {y: Y})
+    L = laplace_initial_conds(L, t, {y: [2, 4, 8, 16, 32]})
+    assert L == s**3*Y(s) - 2*s**2 - 4*s - 8
+    # Test whether `noconds=True` in `doit`:
+    assert (2*LaplaceTransform(exp(t), t, s) - 1).doit() == -1 + 2/(s - 1)
+    assert (LT(a*t+t**2+t**(S(5)/2), t, s) ==
+            (a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True))
+    assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True)
+    assert (LT(1/sqrt(t+a), t, s) ==
+            (sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
+    assert (LT(sqrt(t)/(t+a), t, s) ==
+            (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
+             0, True))
+    assert (LT((t+a)**(-S(3)/2), t, s) ==
+            (-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a),
+             0, True))
+    assert (LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==
+            (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
+             0, True))
+    assert (LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==
+            (pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
+    assert (LT((t+a)**b, t, s) ==
+            (s**(-b - 1)*exp(-a*s)*uppergamma(b + 1, a*s), 0, True))
+    assert LT(t**5/(t+a), t, s) == (120*a**5*uppergamma(-5, a*s), 0, True)
+    assert LT(exp(t), t, s) == (1/(s - 1), 1, True)
+    assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True)
+    assert LT(exp(a*t), t, s) == (1/(s - a), a, True)
+    assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True)
+    assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True)
+    assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True)
+    assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True)
+    assert LT(exp(-a*exp(-t)), t, s) == (lowergamma(s, a)/a**s, 0, True)
+    assert LT(exp(-a*exp(t)), t, s) == (a**s*uppergamma(-s, a), 0, True)
+    assert (LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==
+            ((s + 8)**(-S(11)/4), -8, True))
+    assert (LT(t**(S(3)/2)*exp(-8*t), t, s) ==
+            (3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True))
+    assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True)
+    assert (LT(b*exp(-a*t**2), t, s) ==
+            (sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)),
+             0, True))
+    assert (LT(exp(-2*t**2), t, s) ==
+            (sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True))
+    assert (LT(b*exp(2*t**2), t, s) ==
+            (b*LaplaceTransform(exp(2*t**2), t, s), -oo, True))
+    assert (LT(t*exp(-a*t**2), t, s) ==
+            (1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)),
+             0, True))
+    assert (LT(exp(-a/t), t, s) ==
+            (2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True))
+    assert LT(sqrt(t)*exp(-a/t), t, s, simplify=True) == (
+        sqrt(pi)*(sqrt(a)*sqrt(s) + 1/S(2))*sqrt(s**(-3)) *
+        exp(-2*sqrt(a)*sqrt(s)), 0, True)
+    assert (LT(exp(-a/t)/sqrt(t), t, s) ==
+            (sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
+    assert (LT(exp(-a/t)/(t*sqrt(t)), t, s) ==
+            (sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
+    # TODO: rules with sqrt(a*t) and sqrt(a/t) have stopped working after
+    #       changes to as_base_exp
+    # assert (
+    #     LT(exp(-2*sqrt(a*t)), t, s) ==
+    #     (1/s - sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s)) /
+    #      s**(S(3)/2), 0, True))
+    # assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (
+    #     exp(a/s)*erfc(sqrt(a) * sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True)
+    assert (LT(t**4*exp(-2/t), t, s) ==
+            (8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)),
+             0, True))
+    assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True)
+    assert (LT(b*sinh(a*t)**2, t, s) ==
+            (2*a**2*b/(-4*a**2*s + s**3), 2*a, True))
+    assert (LT(b*sinh(a*t)**2, t, s, simplify=True) ==
+            (2*a**2*b/(s*(-4*a**2 + s**2)), 2*a, True))
+    # The following line confirms that issue #21202 is solved
+    assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True)
+    assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True)
+    assert (LT(cosh(a*t)**2, t, s, simplify=True) ==
+            ((2*a**2 - s**2)/(s*(4*a**2 - s**2)), 2*a, True))
+    assert (LT(sinh(x+3), x, s, simplify=True) ==
+            ((s*sinh(3) + cosh(3))/(s**2 - 1), 1, True))
+    L, _, _ = LT(42*sin(w*t+x)**2, t, s)
+    assert (
+        L -
+        21*(s**2 + s*(-s*cos(2*x) + 2*w*sin(2*x)) +
+            4*w**2)/(s*(s**2 + 4*w**2))).simplify() == 0
+    # The following line replaces the old test test_issue_7173()
+    assert LT(sinh(a*t)*cosh(a*t), t, s, simplify=True) == (a/(-4*a**2 + s**2),
+                                                            2*a, True)
+    assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True)
+    assert (LT(t**(-S(3)/2)*sinh(a*t), t, s) ==
+            (-sqrt(pi)*(sqrt(-a + s) - sqrt(a + s)), a, True))
+    # assert (LT(sinh(2*sqrt(a*t)), t, s) ==
+    #         (sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True))
+    # assert (LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s, simplify=True) ==
+    #         ((-sqrt(a)*s**(S(5)/2) + sqrt(pi)*s**2*(2*a + s)*exp(a/s) *
+    #           erf(sqrt(a)*sqrt(1/s))/2)/s**(S(9)/2), 0, True))
+    # assert (LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==
+    #         (sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True))
+    # assert (LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==
+    #         (sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True))
+    assert (LT(t**(S(3)/7)*cosh(a*t), t, s) ==
+            (((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2,
+             a, True))
+    # assert (LT(cosh(2*sqrt(a*t)), t, s) ==
+    #         (sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) +
+    #          1/s, 0, True))
+    # assert (LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==
+    #         (sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True))
+    # assert (LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==
+    #         (sqrt(pi)*exp(a/s)/sqrt(s), 0, True))
+    # assert (LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==
+    #         (sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True))
+    assert LT(log(t), t, s, simplify=True) == (
+        (-log(s) - EulerGamma)/s, 0, True)
+    assert (LT(-log(t/a), t, s, simplify=True) ==
+            ((log(a) + log(s) + EulerGamma)/s, 0, True))
+    assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True)
+    assert (LT(log(t+a), t, s, simplify=True) ==
+            ((s*log(a) - exp(s/a)*Ei(-s/a))/s**2, 0, True))
+    assert (LT(log(t)/sqrt(t), t, s, simplify=True) ==
+            (sqrt(pi)*(-log(s) - log(4) - EulerGamma)/sqrt(s), 0, True))
+    assert (LT(t**(S(5)/2)*log(t), t, s, simplify=True) ==
+            (sqrt(pi)*(-15*log(s) - log(1073741824) - 15*EulerGamma + 46) /
+             (8*s**(S(7)/2)), 0, True))
+    assert (LT(t**3*log(t), t, s, noconds=True, simplify=True) -
+            6*(-log(s) - S.EulerGamma + S(11)/6)/s**4).simplify() == S.Zero
+    assert (LT(log(t)**2, t, s, simplify=True) ==
+            (((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True))
+    assert (LT(exp(-a*t)*log(t), t, s, simplify=True) ==
+            ((-log(a + s) - EulerGamma)/(a + s), -a, True))
+    assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
+    assert (LT(Abs(sin(a*t)), t, s) ==
+            (a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True))
+    assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True)
+    assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True)
+    assert (LT(sin(a*t)**2/t**2, t, s) ==
+            (a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True))
+    # assert (LT(sin(2*sqrt(a*t)), t, s) ==
+    #         (sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True))
+    # assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True)
+    assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
+    assert (LT(cos(a*t)**2, t, s) ==
+            ((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True))
+    # assert (LT(sqrt(t)*cos(2*sqrt(a*t)), t, s, simplify=True) ==
+    #         (sqrt(pi)*(-a + s/2)*exp(-a/s)/s**(S(5)/2), 0, True))
+    # assert (LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==
+    #         (sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True))
+    assert (LT(sin(a*t)*sin(b*t), t, s) ==
+            (2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True))
+    assert (LT(cos(a*t)*sin(b*t), t, s) ==
+            (b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
+             0, True))
+    assert (LT(cos(a*t)*cos(b*t), t, s) ==
+            (s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
+             0, True))
+    assert (LT(-a*t*cos(a*t) + sin(a*t), t, s, simplify=True) ==
+            (2*a**3/(a**4 + 2*a**2*s**2 + s**4), 0, True))
+    assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a *
+                                              c/(a**2 + (b + s)**2), -b, True)
+    assert LT(c*exp(-b*t)*cos(a*t), t, s) == (c*(b + s)/(a**2 + (b + s)**2),
+                                              -b, True)
+    L, plane, cond = LT(cos(x + 3), x, s, simplify=True)
+    assert plane == 0
+    assert L - (s*cos(3) - sin(3))/(s**2 + 1) == 0
+    # Error functions (laplace7.pdf)
+    assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True)
+    # assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True)
+    # assert (LT(exp(a*t)*erf(sqrt(a*t)), t, s, simplify=True) ==
+    #         (-sqrt(a)/(sqrt(s)*(a - s)), a, True))
+    # assert (LT(erf(sqrt(a/t)/2), t, s, simplify=True) ==
+    #         (1/s - exp(-sqrt(a)*sqrt(s))/s, 0, True))
+    # assert (LT(erfc(sqrt(a*t)), t, s, simplify=True) ==
+    #         (-sqrt(a)/(s*sqrt(a + s)) + 1/s, -a, True))
+    # assert (LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==
+    #         (1/(sqrt(a)*sqrt(s) + s), 0, True))
+    # assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True)
+    # Bessel functions (laplace8.pdf)
+    assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True)
+    assert (LT(besselj(1, a*t), t, s, simplify=True) ==
+            (a/(a**2 + s**2 + s*sqrt(a**2 + s**2)), 0, True))
+    assert (LT(besselj(2, a*t), t, s, simplify=True) ==
+            (a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True))
+    assert (LT(t*besselj(0, a*t), t, s) ==
+            (s/(a**2 + s**2)**(S(3)/2), 0, True))
+    assert (LT(t*besselj(1, a*t), t, s) ==
+            (a/(a**2 + s**2)**(S(3)/2), 0, True))
+    assert (LT(t**2*besselj(2, a*t), t, s) ==
+            (3*a**2/(a**2 + s**2)**(S(5)/2), 0, True))
+    # assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True)
+    # assert (LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==
+    #         (a**(S(3)/2)*exp(-a/s)/s**4, 0, True))
+    assert (LT(besselj(0, a*sqrt(t**2+b*t)), t, s, simplify=True) ==
+            (exp(b*(s - sqrt(a**2 + s**2)))/sqrt(a**2 + s**2), 0, True))
+    assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True)
+    assert (LT(besseli(1, a*t), t, s, simplify=True) ==
+            (a/(-a**2 + s**2 + s*sqrt(-a**2 + s**2)), a, True))
+    assert (LT(besseli(2, a*t), t, s, simplify=True) ==
+            (a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True))
+    assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True)
+    assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True)
+    assert (LT(t**2*besseli(2, a*t), t, s) ==
+            (3*a**2/(-a**2 + s**2)**(S(5)/2), a, True))
+    # assert (LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==
+    #         (a**(S(3)/2)*exp(a/s)/s**4, 0, True))
+    assert (LT(bessely(0, a*t), t, s) ==
+            (-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True))
+    assert (LT(besselk(0, a*t), t, s) ==
+            (log((s + sqrt(-a**2 + s**2))/a)/sqrt(-a**2 + s**2), -a, True))
+    assert (LT(sin(a*t)**4, t, s, simplify=True) ==
+            (24*a**4/(s*(64*a**4 + 20*a**2*s**2 + s**4)), 0, True))
+    # Test general rules and unevaluated forms
+    # These all also test whether issue #7219 is solved.
+    assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True)
+    assert LT(a*f(t), t, w) == (a*LaplaceTransform(f(t), t, w), -oo, True)
+    assert (LT(a*Heaviside(t+1)*f(t+1), t, s) ==
+            (a*LaplaceTransform(f(t + 1), t, s), -oo, True))
+    assert (LT(a*Heaviside(t-1)*f(t-1), t, s) ==
+            (a*LaplaceTransform(f(t), t, s)*exp(-s), -oo, True))
+    assert (LT(b*f(t/a), t, s) ==
+            (a*b*LaplaceTransform(f(t), t, a*s), -oo, True))
+    assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -re(f(x)), True)
+    assert (LT(exp(-a*t)*f(t), t, s) ==
+            (LaplaceTransform(f(t), t, a + s), -oo, True))
+    # assert (LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==
+    #         (exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True))
+    assert (LT(sinh(a*t)*f(t), t, s) ==
+            (LaplaceTransform(f(t), t, -a + s)/2 -
+             LaplaceTransform(f(t), t, a + s)/2, -oo, True))
+    assert (LT(sinh(a*t)*t, t, s, simplify=True) ==
+            (2*a*s/(a**4 - 2*a**2*s**2 + s**4), a, True))
+    assert (LT(cosh(a*t)*f(t), t, s) ==
+            (LaplaceTransform(f(t), t, -a + s)/2 +
+             LaplaceTransform(f(t), t, a + s)/2, -oo, True))
+    assert (LT(cosh(a*t)*t, t, s, simplify=True) ==
+            (1/(2*(a + s)**2) + 1/(2*(a - s)**2), a, True))
+    assert (LT(sin(a*t)*f(t), t, s, simplify=True) ==
+            (I*(-LaplaceTransform(f(t), t, -I*a + s) +
+                LaplaceTransform(f(t), t, I*a + s))/2, -oo, True))
+    assert (LT(sin(f(t)), t, s) ==
+            (LaplaceTransform(sin(f(t)), t, s), -oo, True))
+    assert (LT(sin(a*t)*t, t, s, simplify=True) ==
+            (2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True))
+    assert (LT(cos(a*t)*f(t), t, s) ==
+            (LaplaceTransform(f(t), t, -I*a + s)/2 +
+             LaplaceTransform(f(t), t, I*a + s)/2, -oo, True))
+    assert (LT(cos(a*t)*t, t, s, simplify=True) ==
+            ((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True))
+    L, plane, _ = LT(sin(a*t+b)**2*f(t), t, s)
+    assert plane == -oo
+    assert (
+        -L + (
+            LaplaceTransform(f(t), t, s)/2 -
+            LaplaceTransform(f(t), t, -2*I*a + s)*exp(2*I*b)/4 -
+            LaplaceTransform(f(t), t, 2*I*a + s)*exp(-2*I*b)/4)) == 0
+    L = LT(sin(a*t+b)**2*f(t), t, s, noconds=True)
+    assert (
+        laplace_correspondence(L, {f: F}) ==
+        F(s)/2 - F(-2*I*a + s)*exp(2*I*b)/4 -
+        F(2*I*a + s)*exp(-2*I*b)/4)
+    L, plane, _ = LT(sin(a*t)**3*cosh(b*t), t, s)
+    assert plane == b
+    assert (
+        -L - 3*a/(8*(9*a**2 + b**2 + 2*b*s + s**2)) -
+        3*a/(8*(9*a**2 + b**2 - 2*b*s + s**2)) +
+        3*a/(8*(a**2 + b**2 + 2*b*s + s**2)) +
+        3*a/(8*(a**2 + b**2 - 2*b*s + s**2))).simplify() == 0
+    assert (LT(t**2*exp(-t**2), t, s) ==
+            (sqrt(pi)*s**2*exp(s**2/4)*erfc(s/2)/8 - s/4 +
+             sqrt(pi)*exp(s**2/4)*erfc(s/2)/4, 0, True))
+    assert (LT((a*t**2 + b*t + c)*f(t), t, s) ==
+            (a*Derivative(LaplaceTransform(f(t), t, s), (s, 2)) -
+             b*Derivative(LaplaceTransform(f(t), t, s), s) +
+            c*LaplaceTransform(f(t), t, s), -oo, True))
+    assert (LT(t**np*g(t), t, s) ==
+            ((-1)**np*Derivative(LaplaceTransform(g(t), t, s), (s, np)),
+             -oo, True))
+    # The following tests check whether _piecewise_to_heaviside works:
+    x1 = Piecewise((0, t <= 0), (1, t <= 1), (0, True))
+    X1 = LT(x1, t, s)[0]
+    assert X1 == 1/s - exp(-s)/s
+    y1 = ILT(X1, s, t)
+    assert y1 == Heaviside(t) - Heaviside(t - 1)
+    x1 = Piecewise((0, t <= 0), (t, t <= 1), (2-t, t <= 2), (0, True))
+    X1 = LT(x1, t, s)[0].simplify()
+    assert X1 == (exp(2*s) - 2*exp(s) + 1)*exp(-2*s)/s**2
+    y1 = ILT(X1, s, t)
+    assert (
+        -y1 + t*Heaviside(t) + (t - 2)*Heaviside(t - 2) -
+        2*(t - 1)*Heaviside(t - 1)).simplify() == 0
+    x1 = Piecewise((exp(t), t <= 0), (1, t <= 1), (exp(-(t)), True))
+    X1 = LT(x1, t, s)[0]
+    assert X1 == exp(-1)*exp(-s)/(s + 1) + 1/s - exp(-s)/s
+    y1 = ILT(X1, s, t)
+    assert y1 == (
+        exp(-1)*exp(1 - t)*Heaviside(t - 1) + Heaviside(t) - Heaviside(t - 1))
+    x1 = Piecewise((0, x <= 0), (1, x <= 1), (0, True))
+    X1 = LT(x1, t, s)[0]
+    assert X1 == Piecewise((0, x <= 0), (1, x <= 1), (0, True))/s
+    x1 = [
+        a*Piecewise((1, And(t > 1, t <= 3)), (2, True)),
+        a*Piecewise((1, And(t >= 1, t <= 3)), (2, True)),
+        a*Piecewise((1, And(t >= 1, t < 3)), (2, True)),
+        a*Piecewise((1, And(t > 1, t < 3)), (2, True))]
+    for x2 in x1:
+        assert LT(x2, t, s)[0].expand() == 2*a/s - a*exp(-s)/s + a*exp(-3*s)/s
+    assert (
+        LT(Piecewise((1, Eq(t, 1)), (2, True)), t, s)[0] ==
+        LaplaceTransform(Piecewise((1, Eq(t, 1)), (2, True)), t, s))
+    # The following lines test whether _laplace_transform successfully
+    # removes Heaviside(1) before processing espressions. It fails if
+    # Heaviside(t) remains because then meijerg functions will appear.
+    X1 = 1/sqrt(a*s**2-b)
+    x1 = ILT(X1, s, t)
+    Y1 = LT(x1, t, s)[0]
+    Z1 = (Y1**2/X1**2).simplify()
+    assert Z1 == 1
+    # The following two lines test whether issues #5813 and #7176 are solved.
+    assert (LT(diff(f(t), (t, 1)), t, s, noconds=True) ==
+            s*LaplaceTransform(f(t), t, s) - f(0))
+    assert (LT(diff(f(t), (t, 3)), t, s, noconds=True) ==
+            s**3*LaplaceTransform(f(t), t, s) - s**2*f(0) -
+            s*Subs(Derivative(f(t), t), t, 0) -
+            Subs(Derivative(f(t), (t, 2)), t, 0))
+    # Issue #7219
+    assert (LT(diff(f(x, t, w), t, 2), t, s) ==
+            (s**2*LaplaceTransform(f(x, t, w), t, s) - s*f(x, 0, w) -
+             Subs(Derivative(f(x, t, w), t), t, 0), -oo, True))
+    # Issue #23307
+    assert (LT(10*diff(f(t), (t, 1)), t, s, noconds=True) ==
+            10*s*LaplaceTransform(f(t), t, s) - 10*f(0))
+    assert (LT(a*f(b*t)+g(c*t), t, s, noconds=True) ==
+            a*LaplaceTransform(f(t), t, s/b)/b +
+            LaplaceTransform(g(t), t, s/c)/c)
+    assert inverse_laplace_transform(
+        f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
+    assert (LT(f(t)*g(t), t, s, noconds=True) ==
+            LaplaceTransform(f(t)*g(t), t, s))
+    # Issue #24294
+    assert (LT(b*f(a*t), t, s, noconds=True) ==
+            b*LaplaceTransform(f(t), t, s/a)/a)
+    assert LT(3*exp(t)*Heaviside(t), t, s) == (3/(s - 1), 1, True)
+    assert (LT(2*sin(t)*Heaviside(t), t, s, simplify=True) ==
+            (2/(s**2 + 1), 0, True))
+    # Issue #25293
+    assert (
+        LT((1/(t-1))*sin(4*pi*(t-1))*DiracDelta(t-1) *
+           (Heaviside(t-1/4) - Heaviside(t-2)), t, s)[0] == 4*pi*exp(-s))
+    # additional basic tests from wikipedia
+    assert (LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) ==
+            ((c + s)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True))
+    assert (
+        LT((exp(2*t)-1)*exp(-b-t)*Heaviside(t)/2, t, s, noconds=True,
+           simplify=True) ==
+        exp(-b)/(s**2 - 1))
+    # DiracDelta function: standard cases
+    assert LT(DiracDelta(t), t, s) == (1, -oo, True)
+    assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True)
+    assert LT(DiracDelta(t/42), t, s) == (42, -oo, True)
+    assert LT(DiracDelta(t+42), t, s) == (0, -oo, True)
+    assert (LT(DiracDelta(t)+DiracDelta(t-42), t, s) ==
+            (1 + exp(-42*s), -oo, True))
+    assert (LT(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) ==
+            (s/(a + s), -a, True))
+    assert (
+        LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s, simplify=True) ==
+        (exp(-42*s - 42) + 1, -oo, True))
+    assert LT(f(t)*DiracDelta(t-42), t, s) == (f(42)*exp(-42*s), -oo, True)
+    assert LT(f(t)*DiracDelta(b*t-a), t, s) == (f(a/b)*exp(-a*s/b)/b,
+                                                -oo, True)
+    assert LT(f(t)*DiracDelta(b*t+a), t, s) == (0, -oo, True)
+    # SingularityFunction
+    assert LT(SingularityFunction(t, a, -1), t, s)[0] == exp(-a*s)
+    assert LT(SingularityFunction(t, a, 1), t, s)[0] == exp(-a*s)/s**2
+    assert LT(SingularityFunction(t, a, x), t, s)[0] == (
+        LaplaceTransform(SingularityFunction(t, a, x), t, s))
+    # Collection of cases that cannot be fully evaluated and/or would catch
+    # some common implementation errors
+    assert (LT(DiracDelta(t**2), t, s, noconds=True) ==
+            LaplaceTransform(DiracDelta(t**2), t, s))
+    assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True)
+    assert LT(DiracDelta(t*(1 - t)), t, s) == (1 - exp(-s), -oo, True)
+    assert (LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) ==
+            (LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) +
+             1 + exp(-s) + 1/s, 0, True))
+    assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
+    assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
+    # Heaviside tests
+    assert LT(Heaviside(t), t, s) == (1/s, 0, True)
+    assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
+    assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True)
+    assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True)
+    assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True)
+    assert (LT(Heaviside(-2*t+4), t, s, simplify=True) ==
+            (1/s - exp(-2*s)/s, 0, True))
+    assert (LT(g(t)*Heaviside(t - w), t, s) ==
+            (LaplaceTransform(g(t)*Heaviside(t - w), t, s), -oo, True))
+    assert (
+        LT(Heaviside(t-a)*g(t), t, s) ==
+        (LaplaceTransform(g(a + t), t, s)*exp(-a*s), -oo, True))
+    assert (
+        LT(Heaviside(t+a)*g(t), t, s) ==
+        (LaplaceTransform(g(t), t, s), -oo, True))
+    assert (
+        LT(Heaviside(-t+a)*g(t), t, s) ==
+        (LaplaceTransform(g(t), t, s) -
+         LaplaceTransform(g(a + t), t, s)*exp(-a*s), -oo, True))
+    assert (
+        LT(Heaviside(-t-a)*g(t), t, s) == (0, 0, True))
+    # Fresnel functions
+    assert (laplace_transform(fresnels(t), t, s, simplify=True) ==
+            ((-sin(s**2/(2*pi))*fresnels(s/pi) +
+              sqrt(2)*sin(s**2/(2*pi) + pi/4)/2 -
+              cos(s**2/(2*pi))*fresnelc(s/pi))/s, 0, True))
+    assert (laplace_transform(fresnelc(t), t, s, simplify=True) ==
+            ((sin(s**2/(2*pi))*fresnelc(s/pi) -
+              cos(s**2/(2*pi))*fresnels(s/pi) +
+              sqrt(2)*cos(s**2/(2*pi) + pi/4)/2)/s, 0, True))
+    # Matrix tests
+    Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]])
+    Ms = Matrix([[1/(s - 1), (s + 1)**(-2)],
+                 [(s + 1)**(-2),     1/(s - 1)]])
+    # The default behaviour for Laplace transform of a Matrix returns a Matrix
+    # of Tuples and is deprecated:
+    with warns_deprecated_sympy():
+        Ms_conds = Matrix(
+            [[(1/(s - 1), 1, True), ((s + 1)**(-2), -1, True)],
+             [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]])
+    with warns_deprecated_sympy():
+        assert LT(Mt, t, s) == Ms_conds
+    # The new behavior is to return a tuple of a Matrix and the convergence
+    # conditions for the matrix as a whole:
+    assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True)
+    # With noconds=True the transformed matrix is returned without conditions
+    # either way:
+    assert LT(Mt, t, s, noconds=True) == Ms
+    assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms
+
+
+@slow
+def test_inverse_laplace_transform():
+    s = symbols('s')
+    k, n, t = symbols('k, n, t', real=True)
+    a, b, c, d = symbols('a, b, c, d', positive=True)
+    f = Function('f')
+    F = Function('F')
+
+    def ILT(g):
+        return inverse_laplace_transform(g, s, t)
+
+    def ILTS(g):
+        return inverse_laplace_transform(g, s, t, simplify=True)
+
+    def ILTF(g):
+        return laplace_correspondence(
+            inverse_laplace_transform(g, s, t), {f: F})
+
+    # Tests for the rules in Bateman54.
+
+    # Section 4.1: Some of the Laplace transform rules can also be used well
+    #     in the inverse transform.
+    assert ILTF(exp(-a*s)*F(s)) == f(-a + t)
+    assert ILTF(k*F(s-a)) == k*f(t)*exp(-a*t)
+    assert ILTF(diff(F(s), s, 3)) == -t**3*f(t)
+    assert ILTF(diff(F(s), s, 4)) == t**4*f(t)
+
+    # Section 5.1: Most rules are impractical for a computer algebra system.
+
+    # Section 5.2: Rational functions
+    assert ILT(2) == 2*DiracDelta(t)
+    assert ILT(1/s) == Heaviside(t)
+    assert ILT(1/s**2) == t*Heaviside(t)
+    assert ILT(1/s**5) == t**4*Heaviside(t)/24
+    assert ILT(1/s**n) == t**(n - 1)*Heaviside(t)/gamma(n)
+    assert ILT(a/(a + s)) == a*exp(-a*t)*Heaviside(t)
+    assert ILT(s/(a + s)) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t)
+    assert (ILT(b*s/(s+a)**2) ==
+            b*(-a*t*exp(-a*t)*Heaviside(t) + exp(-a*t)*Heaviside(t)))
+    assert (ILTS(c/((s+a)*(s+b))) ==
+            c*(exp(a*t) - exp(b*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
+    assert (ILTS(c*s/((s+a)*(s+b))) ==
+            c*(a*exp(b*t) - b*exp(a*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
+    assert ILTS(s/(a + s)**3) == t*(-a*t + 2)*exp(-a*t)*Heaviside(t)/2
+    assert ILTS(1/(s*(a + s)**3)) == (
+        -a**2*t**2 - 2*a*t + 2*exp(a*t) - 2)*exp(-a*t)*Heaviside(t)/(2*a**3)
+    assert ILT(1/(s*(a + s)**n)) == (
+        Heaviside(t)*lowergamma(n, a*t)/(a**n*gamma(n)))
+    assert ILT((s-a)**(-b)) == t**(b - 1)*exp(a*t)*Heaviside(t)/gamma(b)
+    assert ILT((a + s)**(-2)) == t*exp(-a*t)*Heaviside(t)
+    assert ILT((a + s)**(-5)) == t**4*exp(-a*t)*Heaviside(t)/24
+    assert ILT(s**2/(s**2 + 1)) == -sin(t)*Heaviside(t) + DiracDelta(t)
+    assert ILT(1 - 1/(s**2 + 1)) == -sin(t)*Heaviside(t) + DiracDelta(t)
+    assert ILT(a/(a**2 + s**2)) == sin(a*t)*Heaviside(t)
+    assert ILT(s/(s**2 + a**2)) == cos(a*t)*Heaviside(t)
+    assert ILT(b/(b**2 + (a + s)**2)) == exp(-a*t)*sin(b*t)*Heaviside(t)
+    assert (ILT(b*s/(b**2 + (a + s)**2)) ==
+            b*(-a*exp(-a*t)*sin(b*t)/b + exp(-a*t)*cos(b*t))*Heaviside(t))
+    assert ILT(1/(s**2*(s**2 + 1))) == t*Heaviside(t) - sin(t)*Heaviside(t)
+    assert (ILTS(c*s/(d**2*(s+a)**2+b**2)) ==
+            c*(-a*d*sin(b*t/d) + b*cos(b*t/d))*exp(-a*t)*Heaviside(t)/(b*d**2))
+    assert ILTS((b*s**2 + d)/(a**2 + s**2)**2) == (
+        2*a**2*b*sin(a*t) + (a**2*b - d)*(a*t*cos(a*t) -
+                                          sin(a*t)))*Heaviside(t)/(2*a**3)
+    assert ILTS(b/(s**2-a**2)) == b*sinh(a*t)*Heaviside(t)/a
+    assert (ILT(b/(s**2-a**2)) ==
+            b*(exp(a*t)*Heaviside(t)/(2*a) - exp(-a*t)*Heaviside(t)/(2*a)))
+    assert ILTS(b*s/(s**2-a**2)) == b*cosh(a*t)*Heaviside(t)
+    assert (ILT(b/(s*(s+a))) ==
+            b*(Heaviside(t)/a - exp(-a*t)*Heaviside(t)/a))
+    # Issue #24424
+    assert (ILTS((s + 8)/((s + 2)*(s**2 + 2*s + 10))) ==
+            ((8*sin(3*t) - 9*cos(3*t))*exp(t) + 9)*exp(-2*t)*Heaviside(t)/15)
+    # Issue #8514; this is not important anymore, since this function
+    # is not solved by integration anymore
+    assert (ILT(1/(a*s**2+b*s+c)) ==
+            2*exp(-b*t/(2*a))*sin(t*sqrt(4*a*c - b**2)/(2*a)) *
+            Heaviside(t)/sqrt(4*a*c - b**2))
+
+    # Section 5.3: Irrational algebraic functions
+    assert (  # (1)
+        ILT(1/sqrt(s)/(b*s-a)) ==
+        exp(a*t/b)*Heaviside(t)*erf(sqrt(a)*sqrt(t)/sqrt(b))/(sqrt(a)*sqrt(b)))
+    assert (  # (2)
+        ILT(1/sqrt(k*s)/(c*s-a)/s) ==
+        (-2*c*sqrt(t)/(sqrt(pi)*a) +
+         c**(S(3)/2)*exp(a*t/c)*erf(sqrt(a)*sqrt(t)/sqrt(c))/a**(S(3)/2)) *
+        Heaviside(t)/(c*sqrt(k)))
+    assert (  # (4)
+        ILT(1/(sqrt(c*s)+a)) == (-a*exp(a**2*t/c)*erfc(a*sqrt(t)/sqrt(c))/c +
+                                 1/(sqrt(pi)*sqrt(c)*sqrt(t)))*Heaviside(t))
+    assert (  # (5)
+        ILT(a/s/(b*sqrt(s)+a)) ==
+        (-exp(a**2*t/b**2)*erfc(a*sqrt(t)/b) + 1)*Heaviside(t))
+    assert (  # (6)
+            ILT((a-b)*sqrt(s)/(sqrt(s)+sqrt(a))/(s-b)) ==
+            (sqrt(a)*sqrt(b)*exp(b*t)*erfc(sqrt(b)*sqrt(t)) +
+             a*exp(a*t)*erfc(sqrt(a)*sqrt(t)) - b*exp(b*t))*Heaviside(t))
+    assert (  # (7)
+            ILT(1/sqrt(s)/(sqrt(b*s)+a)) ==
+            exp(a**2*t/b)*Heaviside(t)*erfc(a*sqrt(t)/sqrt(b))/sqrt(b))
+    assert (  # (8)
+            ILT(a**2/(sqrt(s)+a)/s**(S(3)/2)) ==
+            (2*a*sqrt(t)/sqrt(pi) + exp(a**2*t)*erfc(a*sqrt(t)) - 1) *
+            Heaviside(t))
+    assert (  # (9)
+            ILT((a-b)*sqrt(b)/(s-b)/sqrt(s)/(sqrt(s)+sqrt(a))) ==
+            (sqrt(a)*exp(b*t)*erf(sqrt(b)*sqrt(t)) +
+             sqrt(b)*exp(a*t)*erfc(sqrt(a)*sqrt(t)) -
+             sqrt(b)*exp(b*t))*Heaviside(t))
+    assert (  # (10)
+            ILT(1/(sqrt(s)+sqrt(a))**2) ==
+            (-2*sqrt(a)*sqrt(t)/sqrt(pi) +
+             (-2*a*t + 1)*(erf(sqrt(a)*sqrt(t)) -
+                           1)*exp(a*t) + 1)*Heaviside(t))
+    assert (  # (11)
+            ILT(1/(sqrt(s)+sqrt(a))**2/s) ==
+            ((2*t - 1/a)*exp(a*t)*erfc(sqrt(a)*sqrt(t)) + 1/a -
+             2*sqrt(t)/(sqrt(pi)*sqrt(a)))*Heaviside(t))
+    assert (  # (12)
+            ILT(1/(sqrt(s)+a)**2/sqrt(s)) ==
+            (-2*a*t*exp(a**2*t)*erfc(a*sqrt(t)) +
+             2*sqrt(t)/sqrt(pi))*Heaviside(t))
+    assert (  # (13)
+            ILT(1/(sqrt(s)+a)**3) ==
+            (-a*t*(2*a**2*t + 3)*exp(a**2*t)*erfc(a*sqrt(t)) +
+             2*sqrt(t)*(a**2*t + 1)/sqrt(pi))*Heaviside(t))
+    x = (
+        - ILT(sqrt(s)/(sqrt(s)+a)**3) +
+        2*(sqrt(pi)*a**2*t*(-2*sqrt(pi)*erfc(a*sqrt(t)) +
+                            2*exp(-a**2*t)/(a*sqrt(t))) *
+           (-a**4*t**2 - 5*a**2*t/2 - S.Half) * exp(a**2*t)/2 +
+           sqrt(pi)*a*sqrt(t)*(a**2*t + 1)/2) *
+        Heaviside(t)/(pi*a**2*t)).simplify()
+    assert (  # (14)
+            x == 0)
+    x = (
+        - ILT(1/sqrt(s)/(sqrt(s)+a)**3) +
+        Heaviside(t)*(sqrt(t)*((2*a**2*t + 1) *
+                               (sqrt(pi)*a*sqrt(t)*exp(a**2*t) *
+                                erfc(a*sqrt(t)) - 1) + 1) /
+                      (sqrt(pi)*a))).simplify()
+    assert (  # (15)
+            x == 0)
+    assert (  # (16)
+            factor_terms(ILT(3/(sqrt(s)+a)**4)) ==
+            3*(-2*a**3*t**(S(5)/2)*(2*a**2*t + 5)/(3*sqrt(pi)) +
+               t*(4*a**4*t**2 + 12*a**2*t + 3)*exp(a**2*t) *
+               erfc(a*sqrt(t))/3)*Heaviside(t))
+    assert (  # (17)
+            ILT((sqrt(s)-a)/(s*(sqrt(s)+a))) ==
+            (2*exp(a**2*t)*erfc(a*sqrt(t))-1)*Heaviside(t))
+    assert (  # (18)
+            ILT((sqrt(s)-a)**2/(s*(sqrt(s)+a)**2)) == (
+                1 + 8*a**2*t*exp(a**2*t)*erfc(a*sqrt(t)) -
+                8/sqrt(pi)*a*sqrt(t))*Heaviside(t))
+    assert (  # (19)
+            ILT((sqrt(s)-a)**3/(s*(sqrt(s)+a)**3)) == Heaviside(t)*(
+                2*(8*a**4*t**2+8*a**2*t+1)*exp(a**2*t) *
+                erfc(a*sqrt(t))-8/sqrt(pi)*a*sqrt(t)*(2*a**2*t+1)-1))
+    assert (  # (22)
+            ILT(sqrt(s+a)/(s+b)) == Heaviside(t)*(
+                exp(-a*t)/sqrt(t)/sqrt(pi) +
+                sqrt(a-b)*exp(-b*t)*erf(sqrt(a-b)*sqrt(t))))
+    assert (  # (23)
+            ILT(1/sqrt(s+b)/(s+a)) == Heaviside(t)*(
+                1/sqrt(b-a)*exp(-a*t)*erf(sqrt(b-a)*sqrt(t))))
+    assert (  # (35)
+            ILT(1/sqrt(s**2+a**2)) == Heaviside(t)*(
+                besselj(0, a*t)))
+    assert (  # (44)
+            ILT(1/sqrt(s**2-a**2)) == Heaviside(t)*(
+                besseli(0, a*t)))
+
+    # Miscellaneous tests
+    # Can _inverse_laplace_time_shift deal with positive exponents?
+    assert (
+        - ILT((s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1))) +
+        cos(t)*Heaviside(t) + 4*cos(t - 2)*Heaviside(t - 2) -
+        4*cos(t - 1)*Heaviside(t - 1) - 4*Heaviside(t - 2) +
+        4*Heaviside(t - 1)).simplify() == 0
+
+
+@slow
+def test_inverse_laplace_transform_old():
+    from sympy.functions.special.delta_functions import DiracDelta
+    ILT = inverse_laplace_transform
+    a, b, c, d = symbols('a b c d', positive=True)
+    n, r = symbols('n, r', real=True)
+    t, z = symbols('t z')
+    f = Function('f')
+    F = Function('F')
+
+    def simp_hyp(expr):
+        return factor_terms(expand_mul(expr)).rewrite(sin)
+
+    L = ILT(F(s), s, t)
+    assert laplace_correspondence(L, {f: F}) == f(t)
+    assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t)
+    assert ILT(exp(-a*s)/(b + s), s, t) == exp(-b*(-a + t))*Heaviside(-a + t)
+    assert (ILT((b + s)/(a**2 + (b + s)**2), s, t) ==
+            exp(-b*t)*cos(a*t)*Heaviside(t))
+    assert (ILT(exp(-a*s)/s**b, s, t) ==
+            (-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b))
+    assert (ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) ==
+            Heaviside(-a + t)*besselj(0, a - t))
+    assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
+    # TODO sinh/cosh shifted come out a mess. also delayed trig is a mess
+    # TODO should this simplify further?
+    assert (ILT(exp(-a*s)/s**b, s, t) ==
+            (t - a)**(b - 1)*Heaviside(t - a)/gamma(b))
+    assert (ILT(exp(-a*s)/sqrt(1 + s**2), s, t) ==
+            Heaviside(t - a)*besselj(0, a - t))  # note: besselj(0, x) is even
+    # XXX ILT turns these branch factor into trig functions ...
+    assert (
+        simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2),
+                     s, t).rewrite(exp)) ==
+        Heaviside(t)*besseli(b, a*t))
+    assert (
+        ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2),
+            s, t, simplify=True).rewrite(exp) ==
+        Heaviside(t)*besselj(b, a*t))
+    assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
+    # TODO can we make erf(t) work?
+    assert (ILT((s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==
+            Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]))
+    # Test time_diff rule
+    assert (ILT(s**42*f(s), s, t) ==
+            Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 42)))
+    assert ILT(cos(s), s, t) == InverseLaplaceTransform(cos(s), s, t, None)
+    # Rules for testing different DiracDelta cases
+    assert (
+        ILT(1 + 2*s + 3*s**2 + 5*s**3, s, t) == DiracDelta(t) +
+        2*DiracDelta(t, 1) + 3*DiracDelta(t, 2) + 5*DiracDelta(t, 3))
+    assert (ILT(2*exp(3*s) - 5*exp(-7*s), s, t) ==
+            2*InverseLaplaceTransform(exp(3*s), s, t, None) -
+            5*DiracDelta(t - 7))
+    a = cos(sin(7)/2)
+    assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3)
+    assert ILT(exp(2*s), s, t) == InverseLaplaceTransform(exp(2*s), s, t, None)
+    r = Symbol('r', real=True)
+    assert ILT(exp(r*s), s, t) == InverseLaplaceTransform(exp(r*s), s, t, None)
+    # Rules for testing whether Heaviside(t) is treated properly in diff rule
+    assert ILT(s**2/(a**2 + s**2), s, t) == (
+        -a*sin(a*t)*Heaviside(t) + DiracDelta(t))
+    assert ILT(s**2*(f(s) + 1/(a**2 + s**2)), s, t) == (
+        -a*sin(a*t)*Heaviside(t) + DiracDelta(t) +
+        Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 2)))
+    # Rules from the previous test_inverse_laplace_transform_delta_cond():
+    assert (ILT(exp(r*s), s, t, noconds=False) ==
+            (InverseLaplaceTransform(exp(r*s), s, t, None), True))
+    # inversion does not exist: verify it doesn't evaluate to DiracDelta
+    for z in (Symbol('z', extended_real=False),
+              Symbol('z', imaginary=True, zero=False)):
+        f = ILT(exp(z*s), s, t, noconds=False)
+        f = f[0] if isinstance(f, tuple) else f
+        assert f.func != DiracDelta
+
+
+@slow
+def test_expint():
+    x = Symbol('x')
+    a = Symbol('a')
+    u = Symbol('u', polar=True)
+
+    # TODO LT of Si, Shi, Chi is a mess ...
+    assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True)
+    assert (laplace_transform(expint(a, x), x, s, simplify=True) ==
+            (lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero))
+    assert (laplace_transform(expint(1, x), x, s, simplify=True) ==
+            (log(s + 1)/s, 0, True))
+    assert (laplace_transform(expint(2, x), x, s, simplify=True) ==
+            ((s - log(s + 1))/s**2, 0, True))
+    assert (inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() ==
+            Heaviside(u)*Ci(u))
+    assert (
+        inverse_laplace_transform(log(s + 1)/s, s, x,
+                                  simplify=True).rewrite(expint) ==
+        Heaviside(x)*E1(x))
+    assert (
+        inverse_laplace_transform(
+            (s - log(s + 1))/s**2, s, x,
+            simplify=True).rewrite(expint).expand() ==
+        (expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand())
diff --git a/shared/package-files/a5/a574daf11931c5f61760a85f8f5b8f2291aa5f33ebbd16d5f3e15782a12e877a/_foreach_erfc_ops.h b/shared/package-files/a5/a574daf11931c5f61760a85f8f5b8f2291aa5f33ebbd16d5f3e15782a12e877a/_foreach_erfc_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..c801a7ec049c491a37ea584f4d457d6112e7c01d
--- /dev/null
+++ b/shared/package-files/a5/a574daf11931c5f61760a85f8f5b8f2291aa5f33ebbd16d5f3e15782a12e877a/_foreach_erfc_ops.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _foreach_erfc {
+  using schema = ::std::vector (at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_erfc";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_foreach_erfc(Tensor[] self) -> Tensor[]";
+  static ::std::vector call(at::TensorList self);
+  static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
+};
+
+struct TORCH_API _foreach_erfc_ {
+  using schema = void (at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_erfc_";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_foreach_erfc_(Tensor(a!)[] self) -> ()";
+  static void call(at::TensorList self);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
+};
+
+struct TORCH_API _foreach_erfc_out {
+  using schema = void (at::TensorList, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_erfc";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "_foreach_erfc.out(Tensor[] self, *, Tensor(a!)[] out) -> ()";
+  static void call(at::TensorList self, at::TensorList out);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/a5/a58186f850def7b4fd33b6e2b1e8060627c49581469675e7c656274f4e176e4f/cholesky_inverse_ops.h b/shared/package-files/a5/a58186f850def7b4fd33b6e2b1e8060627c49581469675e7c656274f4e176e4f/cholesky_inverse_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..e6baef43d90fbae7169f646202d5084c28e4af1b
--- /dev/null
+++ b/shared/package-files/a5/a58186f850def7b4fd33b6e2b1e8060627c49581469675e7c656274f4e176e4f/cholesky_inverse_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API cholesky_inverse {
+  using schema = at::Tensor (const at::Tensor &, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::cholesky_inverse";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "cholesky_inverse(Tensor self, bool upper=False) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, bool upper);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool upper);
+};
+
+struct TORCH_API cholesky_inverse_out {
+  using schema = at::Tensor & (const at::Tensor &, bool, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::cholesky_inverse";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "cholesky_inverse.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, bool upper, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool upper, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Eastern b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Eastern
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Eastern differ
diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Montreal b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Montreal
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Montreal differ
diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Thunder_Bay b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Thunder_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Thunder_Bay differ
diff --git a/shared/package-files/a5/a592284225f6b671a89b3de062e5e0df485c3f50c688956f6dbf2fb6a61ebe67/idtracking.cpython-311.pyc b/shared/package-files/a5/a592284225f6b671a89b3de062e5e0df485c3f50c688956f6dbf2fb6a61ebe67/idtracking.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78b0ecc43083429fa7917f586165d38d6f006159
Binary files /dev/null and b/shared/package-files/a5/a592284225f6b671a89b3de062e5e0df485c3f50c688956f6dbf2fb6a61ebe67/idtracking.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a59396b6df771f708471c55d2d0764fe5c368f0a76d1788785a43d31a3f8a19d/tensorpipe_rpc_agent_test_fixture.py b/shared/package-files/a5/a59396b6df771f708471c55d2d0764fe5c368f0a76d1788785a43d31a3f8a19d/tensorpipe_rpc_agent_test_fixture.py
new file mode 100644
index 0000000000000000000000000000000000000000..629b0328f1aed6d14d71589faee40a9b702a1b22
--- /dev/null
+++ b/shared/package-files/a5/a59396b6df771f708471c55d2d0764fe5c368f0a76d1788785a43d31a3f8a19d/tensorpipe_rpc_agent_test_fixture.py
@@ -0,0 +1,34 @@
+# mypy: allow-untyped-defs
+
+import torch.distributed.rpc as rpc
+from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import (
+    RpcAgentTestFixture,
+)
+from torch.testing._internal.common_distributed import (
+    tp_transports,
+)
+
+
+class TensorPipeRpcAgentTestFixture(RpcAgentTestFixture):
+    @property
+    def rpc_backend(self):
+        return rpc.backend_registry.BackendType[
+            "TENSORPIPE"
+        ]
+
+    @property
+    def rpc_backend_options(self):
+        return rpc.backend_registry.construct_rpc_backend_options(
+            self.rpc_backend,
+            init_method=self.init_method,
+            _transports=tp_transports()
+        )
+
+    def get_shutdown_error_regex(self):
+        # FIXME Once we consolidate the error messages returned by the
+        # TensorPipe agent put some more specific regex here.
+        error_regexes = [".*"]
+        return "|".join([f"({error_str})" for error_str in error_regexes])
+
+    def get_timeout_error_regex(self):
+        return "RPC ran for more than"
diff --git a/shared/package-files/a5/a5a7353c9a4db0f8ed03ce8f144d564241391e9812f5c759af4ad5fb4ccd7ddc/max_pool2d_with_indices_meta.h b/shared/package-files/a5/a5a7353c9a4db0f8ed03ce8f144d564241391e9812f5c759af4ad5fb4ccd7ddc/max_pool2d_with_indices_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f3e4d5a95a3409c0ed2d18d88fc52a2877b5c66
--- /dev/null
+++ b/shared/package-files/a5/a5a7353c9a4db0f8ed03ce8f144d564241391e9812f5c759af4ad5fb4ccd7ddc/max_pool2d_with_indices_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_max_pool2d_with_indices : public at::impl::MetaBase {
+    
+    
+    void meta(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/a5/a5ab922c3331cd324c3a3bd7d561142b470cc8592b171a5626cc85cb06afec0f/exceptions.py b/shared/package-files/a5/a5ab922c3331cd324c3a3bd7d561142b470cc8592b171a5626cc85cb06afec0f/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae8905475f02655f4fc5863931d99ca9da55db78
--- /dev/null
+++ b/shared/package-files/a5/a5ab922c3331cd324c3a3bd7d561142b470cc8592b171a5626cc85cb06afec0f/exceptions.py
@@ -0,0 +1,18 @@
+"""
+fsspec user-defined exception classes
+"""
+
+import asyncio
+
+
+class BlocksizeMismatchError(ValueError):
+    """
+    Raised when a cached file is opened with a different blocksize than it was
+    written with
+    """
+
+
+class FSTimeoutError(asyncio.TimeoutError):
+    """
+    Raised when a fsspec function timed out occurs
+    """
diff --git a/shared/package-files/a5/a5bbc480a957bb0f98ec1087eba0aea3dde3de68a19d40c0cda32410155e6bf6/test_string.cpython-311.pyc b/shared/package-files/a5/a5bbc480a957bb0f98ec1087eba0aea3dde3de68a19d40c0cda32410155e6bf6/test_string.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ddb0df911bffa1c2d27547570a96ff21e0bc428
Binary files /dev/null and b/shared/package-files/a5/a5bbc480a957bb0f98ec1087eba0aea3dde3de68a19d40c0cda32410155e6bf6/test_string.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a5bcd19938a25fdff99bf8cb0ef3d95eafc74d51d9082e7e91253bfe91a58b4e/test_fnodes.cpython-311.pyc b/shared/package-files/a5/a5bcd19938a25fdff99bf8cb0ef3d95eafc74d51d9082e7e91253bfe91a58b4e/test_fnodes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..320d0593c69e6b9778bdd30484beb237b86f0d79
Binary files /dev/null and b/shared/package-files/a5/a5bcd19938a25fdff99bf8cb0ef3d95eafc74d51d9082e7e91253bfe91a58b4e/test_fnodes.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a5c0c8c803637a59453d0e78ebe10bf4adcfb1f16ece4817dbbc304e0cf04689/common.cpython-311.pyc b/shared/package-files/a5/a5c0c8c803637a59453d0e78ebe10bf4adcfb1f16ece4817dbbc304e0cf04689/common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ff0b4a6cd88fe10d5b3e9c09b3f93f3acd926da
Binary files /dev/null and b/shared/package-files/a5/a5c0c8c803637a59453d0e78ebe10bf4adcfb1f16ece4817dbbc304e0cf04689/common.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a5c38961c05063939a0bb621c34177c23834f102d80291a6a08482adbb39f64b/cache_metadata.py b/shared/package-files/a5/a5c38961c05063939a0bb621c34177c23834f102d80291a6a08482adbb39f64b/cache_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd9b5cdd99d7f4a0a989c0f7d0c70ddcf324816a
--- /dev/null
+++ b/shared/package-files/a5/a5c38961c05063939a0bb621c34177c23834f102d80291a6a08482adbb39f64b/cache_metadata.py
@@ -0,0 +1,232 @@
+from __future__ import annotations
+
+import os
+import pickle
+import time
+from typing import TYPE_CHECKING
+
+from fsspec.utils import atomic_write
+
+try:
+    import ujson as json
+except ImportError:
+    if not TYPE_CHECKING:
+        import json
+
+if TYPE_CHECKING:
+    from typing import Any, Dict, Iterator, Literal
+
+    from typing_extensions import TypeAlias
+
+    from .cached import CachingFileSystem
+
+    Detail: TypeAlias = Dict[str, Any]
+
+
+class CacheMetadata:
+    """Cache metadata.
+
+    All reading and writing of cache metadata is performed by this class,
+    accessing the cached files and blocks is not.
+
+    Metadata is stored in a single file per storage directory in JSON format.
+    For backward compatibility, also reads metadata stored in pickle format
+    which is converted to JSON when next saved.
+    """
+
+    def __init__(self, storage: list[str]):
+        """
+
+        Parameters
+        ----------
+        storage: list[str]
+            Directories containing cached files, must be at least one. Metadata
+            is stored in the last of these directories by convention.
+        """
+        if not storage:
+            raise ValueError("CacheMetadata expects at least one storage location")
+
+        self._storage = storage
+        self.cached_files: list[Detail] = [{}]
+
+        # Private attribute to force saving of metadata in pickle format rather than
+        # JSON for use in tests to confirm can read both pickle and JSON formats.
+        self._force_save_pickle = False
+
+    def _load(self, fn: str) -> Detail:
+        """Low-level function to load metadata from specific file"""
+        try:
+            with open(fn, "r") as f:
+                loaded = json.load(f)
+        except ValueError:
+            with open(fn, "rb") as f:
+                loaded = pickle.load(f)
+        for c in loaded.values():
+            if isinstance(c.get("blocks"), list):
+                c["blocks"] = set(c["blocks"])
+        return loaded
+
+    def _save(self, metadata_to_save: Detail, fn: str) -> None:
+        """Low-level function to save metadata to specific file"""
+        if self._force_save_pickle:
+            with atomic_write(fn) as f:
+                pickle.dump(metadata_to_save, f)
+        else:
+            with atomic_write(fn, mode="w") as f:
+                json.dump(metadata_to_save, f)
+
+    def _scan_locations(
+        self, writable_only: bool = False
+    ) -> Iterator[tuple[str, str, bool]]:
+        """Yield locations (filenames) where metadata is stored, and whether
+        writable or not.
+
+        Parameters
+        ----------
+        writable: bool
+            Set to True to only yield writable locations.
+
+        Returns
+        -------
+        Yields (str, str, bool)
+        """
+        n = len(self._storage)
+        for i, storage in enumerate(self._storage):
+            writable = i == n - 1
+            if writable_only and not writable:
+                continue
+            yield os.path.join(storage, "cache"), storage, writable
+
+    def check_file(
+        self, path: str, cfs: CachingFileSystem | None
+    ) -> Literal[False] | tuple[Detail, str]:
+        """If path is in cache return its details, otherwise return ``False``.
+
+        If the optional CachingFileSystem is specified then it is used to
+        perform extra checks to reject possible matches, such as if they are
+        too old.
+        """
+        for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files):
+            if path not in cache:
+                continue
+            detail = cache[path].copy()
+
+            if cfs is not None:
+                if cfs.check_files and detail["uid"] != cfs.fs.ukey(path):
+                    # Wrong file as determined by hash of file properties
+                    continue
+                if cfs.expiry and time.time() - detail["time"] > cfs.expiry:
+                    # Cached file has expired
+                    continue
+
+            fn = os.path.join(base, detail["fn"])
+            if os.path.exists(fn):
+                return detail, fn
+        return False
+
+    def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]:
+        """Remove expired metadata from the cache.
+
+        Returns names of files corresponding to expired metadata and a boolean
+        flag indicating whether the writable cache is empty. Caller is
+        responsible for deleting the expired files.
+        """
+        expired_files = []
+        for path, detail in self.cached_files[-1].copy().items():
+            if time.time() - detail["time"] > expiry_time:
+                fn = detail.get("fn", "")
+                if not fn:
+                    raise RuntimeError(
+                        f"Cache metadata does not contain 'fn' for {path}"
+                    )
+                fn = os.path.join(self._storage[-1], fn)
+                expired_files.append(fn)
+                self.cached_files[-1].pop(path)
+
+        if self.cached_files[-1]:
+            cache_path = os.path.join(self._storage[-1], "cache")
+            self._save(self.cached_files[-1], cache_path)
+
+        writable_cache_empty = not self.cached_files[-1]
+        return expired_files, writable_cache_empty
+
+    def load(self) -> None:
+        """Load all metadata from disk and store in ``self.cached_files``"""
+        cached_files = []
+        for fn, _, _ in self._scan_locations():
+            if os.path.exists(fn):
+                # TODO: consolidate blocks here
+                cached_files.append(self._load(fn))
+            else:
+                cached_files.append({})
+        self.cached_files = cached_files or [{}]
+
+    def on_close_cached_file(self, f: Any, path: str) -> None:
+        """Perform side-effect actions on closing a cached file.
+
+        The actual closing of the file is the responsibility of the caller.
+        """
+        # File must be writeble, so in self.cached_files[-1]
+        c = self.cached_files[-1][path]
+        if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
+            c["blocks"] = True
+
+    def pop_file(self, path: str) -> str | None:
+        """Remove metadata of cached file.
+
+        If path is in the cache, return the filename of the cached file,
+        otherwise return ``None``.  Caller is responsible for deleting the
+        cached file.
+        """
+        details = self.check_file(path, None)
+        if not details:
+            return None
+        _, fn = details
+        if fn.startswith(self._storage[-1]):
+            self.cached_files[-1].pop(path)
+            self.save()
+        else:
+            raise PermissionError(
+                "Can only delete cached file in last, writable cache location"
+            )
+        return fn
+
+    def save(self) -> None:
+        """Save metadata to disk"""
+        for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files):
+            if not writable:
+                continue
+
+            if os.path.exists(fn):
+                cached_files = self._load(fn)
+                for k, c in cached_files.items():
+                    if k in cache:
+                        if c["blocks"] is True or cache[k]["blocks"] is True:
+                            c["blocks"] = True
+                        else:
+                            # self.cached_files[*][*]["blocks"] must continue to
+                            # point to the same set object so that updates
+                            # performed by MMapCache are propagated back to
+                            # self.cached_files.
+                            blocks = cache[k]["blocks"]
+                            blocks.update(c["blocks"])
+                            c["blocks"] = blocks
+                        c["time"] = max(c["time"], cache[k]["time"])
+                        c["uid"] = cache[k]["uid"]
+
+                # Files can be added to cache after it was written once
+                for k, c in cache.items():
+                    if k not in cached_files:
+                        cached_files[k] = c
+            else:
+                cached_files = cache
+            cache = {k: v.copy() for k, v in cached_files.items()}
+            for c in cache.values():
+                if isinstance(c["blocks"], set):
+                    c["blocks"] = list(c["blocks"])
+            self._save(cache, fn)
+            self.cached_files[-1] = cached_files
+
+    def update_file(self, path: str, detail: Detail) -> None:
+        """Update metadata for specific file in memory, do not save"""
+        self.cached_files[-1][path] = detail
diff --git a/shared/package-files/a5/a5ec6796f2fbb34cb107c429eac06d69831e99d301b1cbb1d0adabef80d92514/special_math.h b/shared/package-files/a5/a5ec6796f2fbb34cb107c429eac06d69831e99d301b1cbb1d0adabef80d92514/special_math.h
new file mode 100644
index 0000000000000000000000000000000000000000..0bd442513da6fbd704b73e6bb32539ef15e6a2e6
--- /dev/null
+++ b/shared/package-files/a5/a5ec6796f2fbb34cb107c429eac06d69831e99d301b1cbb1d0adabef80d92514/special_math.h
@@ -0,0 +1,552 @@
+// Implementation of specal math functions for Metal
+#pragma once
+#include 
+#include 
+
+namespace c10 {
+namespace metal {
+
+// Translated to metal from https://www.johndcook.com/cpp_erf.html
+
+template 
+inline T erf(T x) {
+  T a1 = 0.254829592;
+  T a2 = -0.284496736;
+  T a3 = 1.421413741;
+  T a4 = -1.453152027;
+  T a5 = 1.061405429;
+  T p = 0.3275911;
+
+  // Save the sign of x
+  int sign = 1;
+  if (x < 0)
+    sign = -1;
+  x = ::metal::fabs(x);
+
+  // A&S formula 7.1.26
+  T t = 1.0 / (1.0 + p * x);
+  T y = 1.0 -
+      (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *
+          ::metal::exp(-x * x);
+
+  return sign * y;
+}
+
+template 
+inline float erfinv(T y) {
+  /* coefficients in rational expansion */
+  constexpr float a[4] = {0.886226899, -1.645349621, 0.914624893, -0.140543331};
+  constexpr float b[4] = {-2.118377725, 1.442710462, -0.329097515, 0.012229801};
+  constexpr float c[4] = {-1.970840454, -1.624906493, 3.429567803, 1.641345311};
+  constexpr float d[2] = {3.543889200, 1.637067800};
+
+  float x, z, num, dem; /*working variables */
+
+  float y_abs = ::metal::abs(static_cast(y));
+  if (y_abs >= 1.0f) {
+    return y_abs > 1.0f ? NAN
+                        : ::metal::copysign(INFINITY, static_cast(y));
+  }
+  if (y_abs <= 0.7f) {
+    z = y * y;
+    num = ((a[3] * z + a[2]) * z + a[1]) * z + a[0];
+    dem = (((b[3] * z + b[2]) * z + b[1]) * z + b[0]) * z + 1.0f;
+    x = y * num / dem;
+  } else {
+    z = ::metal::sqrt(-1.0f * ::metal::log((1.0 - y_abs) / 2.0));
+    num = ((c[3] * z + c[2]) * z + c[1]) * z + c[0];
+    dem = (d[1] * z + d[0]) * z + 1.0f;
+    x = ::metal::copysign(num, static_cast(y)) / dem;
+  }
+
+  return x;
+}
+
+/*
+ * For licensing information and documentation, please refer to the cpu
+ * implementation located in "ATen/native/Math.h".
+ */
+
+template 
+inline T chbevl(T x, const float array[], const int len) {
+  T b0, b1, b2;
+
+  b0 = array[0];
+  b1 = 0;
+
+  for (int i = 1; i < len; ++i) {
+    b2 = b1;
+    b1 = b0;
+    b0 = x * b1 - b2 + array[i];
+  }
+
+  return T{0.5} * (b0 - b2);
+}
+
+// Copied from
+// https://github.com/pytorch/pytorch/blob/58b661cda2c002a8e1ac3bee494bfe1f7420437c/aten/src/ATen/native/cuda/Math.cuh#L502
+
+template 
+inline T i0(T _x) {
+  auto x = ::metal::fabs(_x);
+
+  if (x <= 8.0) {
+    /* Chebyshev coefficients for exp(-x) I0(x)
+     *   in the interval [0,8].
+     *
+     * lim(x->0){ exp(-x) I0(x) } = 1.
+     */
+    constexpr float A[] = {
+        -4.41534164647933937950E-18, 3.33079451882223809783E-17,
+        -2.43127984654795469359E-16, 1.71539128555513303061E-15,
+        -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+        -4.85644678311192946090E-13, 2.95505266312963983461E-12,
+        -1.72682629144155570723E-11, 9.67580903537323691224E-11,
+        -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+        -1.30002500998624804212E-8,  6.04699502254191894932E-8,
+        -2.67079385394061173391E-7,  1.11738753912010371815E-6,
+        -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+        -5.75419501008210370398E-5,  1.88502885095841655729E-4,
+        -5.76375574538582365885E-4,  1.63947561694133579842E-3,
+        -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+        -2.37374148058994688156E-2,  4.93052842396707084878E-2,
+        -9.49010970480476444210E-2,  1.71620901522208775349E-1,
+        -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+
+    auto y = (x / 2.0) - 2.0;
+    return static_cast(::metal::exp(x) * chbevl(y, A, 30));
+  }
+
+  // Handles x > 8 case
+  /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
+   * in the inverted interval [8,infinity].
+   *
+   * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
+   */
+  constexpr float B[] = {
+      -7.23318048787475395456E-18, -4.83050448594418207126E-18,
+      4.46562142029675999901E-17,  3.46122286769746109310E-17,
+      -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+      1.77256013305652638360E-15,  3.81168066935262242075E-15,
+      -9.55484669882830764870E-15, -4.15056934728722208663E-14,
+      1.54008621752140982691E-14,  3.85277838274214270114E-13,
+      7.18012445138366623367E-13,  -1.79417853150680611778E-12,
+      -1.32158118404477131188E-11, -3.14991652796324136454E-11,
+      1.18891471078464383424E-11,  4.94060238822496958910E-10,
+      3.39623202570838634515E-9,   2.26666899049817806459E-8,
+      2.04891858946906374183E-7,   2.89137052083475648297E-6,
+      6.88975834691682398426E-5,   3.36911647825569408990E-3,
+      8.04490411014108831608E-1};
+
+  return static_cast(
+      (::metal::exp(x) * chbevl(32.0 / x - 2.0, B, 25)) / ::metal::sqrt(x));
+}
+
+// Copied from
+// https://github.com/pytorch/pytorch/blob/58b661cda2c002a8e1ac3bee494bfe1f7420437c/aten/src/ATen/native/cuda/Math.cuh#L576
+
+template 
+inline T i1(T _x) {
+  const auto x = ::metal::fabs(_x);
+
+  if (x <= 8.0) {
+    // Chebyshev coefficients for exp(-x) i1(x) in the internal [0, 8]
+    //   lim(x->0){ exp(-x) i1(x) / x } = 1/2
+    constexpr float coefficients[] = {
+        2.77791411276104639959E-18, -2.11142121435816608115E-17,
+        1.55363195773620046921E-16, -1.10559694773538630805E-15,
+        7.60068429473540693410E-15, -5.04218550472791168711E-14,
+        3.22379336594557470981E-13, -1.98397439776494371520E-12,
+        1.17361862988909016308E-11, -6.66348972350202774223E-11,
+        3.62559028155211703701E-10, -1.88724975172282928790E-9,
+        9.38153738649577178388E-9,  -4.44505912879632808065E-8,
+        2.00329475355213526229E-7,  -8.56872026469545474066E-7,
+        3.47025130813767847674E-6,  -1.32731636560394358279E-5,
+        4.78156510755005422638E-5,  -1.61760815825896745588E-4,
+        5.12285956168575772895E-4,  -1.51357245063125314899E-3,
+        4.15642294431288815669E-3,  -1.05640848946261981558E-2,
+        2.47264490306265168283E-2,  -5.29459812080949914269E-2,
+        1.02643658689847095384E-1,  -1.76416518357834055153E-1,
+        2.52587186443633654823E-1};
+    const auto y = x / 2.0 - 2.0;
+    const auto out = ::metal::exp(x) * x * chbevl(y, coefficients, 29);
+    return static_cast(_x < T(0.) ? -out : out);
+  }
+
+  // Chebyshev coefficients for exp(-x) sqrt(x) i1(x)
+  //   in the inverted interval [8, infinity]
+  //   lim(x->inf){ exp(-x) sqrt(x) i1(x) } = 1/sqrt(2pi)
+  constexpr float coefficients[] = {
+      7.51729631084210481353E-18,  4.41434832307170791151E-18,
+      -4.65030536848935832153E-17, -3.20952592199342395980E-17,
+      2.96262899764595013876E-16,  3.30820231092092828324E-16,
+      -1.88035477551078244854E-15, -3.81440307243700780478E-15,
+      1.04202769841288027642E-14,  4.27244001671195135429E-14,
+      -2.10154184277266431302E-14, -4.08355111109219731823E-13,
+      -7.19855177624590851209E-13, 2.03562854414708950722E-12,
+      1.41258074366137813316E-11,  3.25260358301548823856E-11,
+      -1.89749581235054123450E-11, -5.58974346219658380687E-10,
+      -3.83538038596423702205E-9,  -2.63146884688951950684E-8,
+      -2.51223623787020892529E-7,  -3.88256480887769039346E-6,
+      -1.10588938762623716291E-4,  -9.76109749136146840777E-3,
+      7.78576235018280120474E-1};
+  const auto out = (::metal::exp(x) * chbevl(32. / x - 2., coefficients, 25)) /
+      ::metal::sqrt(x);
+  return static_cast(_x < T(0.) ? -out : out);
+}
+
+// gamma, lgamma
+template 
+inline float log_gamma(const T);
+
+template 
+inline float gamma(const T x) {
+  if (x < 0.001) {
+    constexpr float EULER_MASCHERONI = 0.577215664901532860606512090;
+    // For small x, 1/gamma(x) has power series x + gamma x^2  - ...
+    // So in this range, 1/gamma(x) = x + gamma x^2 with error on the order of
+    // x^3. The relative error over this interval is less than 6e-7.
+
+    return 1.0 / (x * (1.0 + EULER_MASCHERONI * x));
+  }
+  if (x >= 12.0) {
+    return ::metal::exp(log_gamma(x));
+  }
+  // The algorithm directly approximates gamma over (1,2) and uses
+  // reduction identities to reduce other arguments to this interval.
+  // numerator coefficients for gamma approximation over the interval (1,2)
+  constexpr float GAMMA_NUMERATOR_COEF[8] = {
+      -1.71618513886549492533811E+0,
+      2.47656508055759199108314E+1,
+      -3.79804256470945635097577E+2,
+      6.29331155312818442661052E+2,
+      8.66966202790413211295064E+2,
+      -3.14512729688483675254357E+4,
+      -3.61444134186911729807069E+4,
+      6.64561438202405440627855E+4};
+
+  // denominator coefficients for gamma approximation over the interval (1,2)
+  constexpr float GAMMA_DENOMINATOR_COEF[8] = {
+      -3.08402300119738975254353E+1,
+      3.15350626979604161529144E+2,
+      -1.01515636749021914166146E+3,
+      -3.10777167157231109440444E+3,
+      2.25381184209801510330112E+4,
+      4.75584627752788110767815E+3,
+      -1.34659959864969306392456E+5,
+      -1.15132259675553483497211E+5};
+
+  // Add or subtract integers as necessary to bring y into (1,2)
+  float y = 1.0 + ::metal::fract(x);
+
+  float num = 0.0;
+  float den = 1.0;
+
+  float z = y - 1;
+  for (int i = 0; i < 8; i++) {
+    num = (num + GAMMA_NUMERATOR_COEF[i]) * z;
+    den = den * z + GAMMA_DENOMINATOR_COEF[i];
+  }
+  float result = num / den + 1.0;
+
+  // Apply correction if argument was not initially in (1,2)
+  if (x < 1.0) {
+    // identity gamma(z) = gamma(z+1)/z
+    result /= (y - 1.0);
+  } else {
+    // identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z)
+    auto n = static_cast(::metal::floor(x));
+    for (int i = 1; i < n; i++) {
+      result *= y++;
+    }
+  }
+
+  return result;
+}
+
+template 
+inline float log_gamma(const T x) {
+  constexpr float LOG_PI = 1.14472988584940017414342735135305;
+  constexpr float HALF_LOG_TWO_PI = 0.91893853320467274178032973640562;
+  constexpr float LGAMMA_EXPANSION_COEF[8] = {
+      1.0 / 12.0,
+      -1.0 / 360.0,
+      1.0 / 1260.0,
+      -1.0 / 1680.0,
+      1.0 / 1188.0,
+      -691.0 / 360360.0,
+      1.0 / 156.0,
+      -3617.0 / 122400.0};
+
+  float rc;
+
+  const auto abs_x = ::metal::abs(static_cast(x));
+  if (abs_x == 0) {
+    return INFINITY;
+  }
+  if (abs_x < 12.0) {
+    rc = ::metal::log(::metal::abs(gamma(abs_x)));
+  } else {
+    // Abramowitz and Stegun 6.1.41
+    // Asymptotic series should be good to at least 11 or 12 figures
+    // For error analysis, see Whittiker and Watson
+    // A Course in Modern Analysis (1927), page 252
+
+    float z = 1.0 / (abs_x * abs_x);
+    float sum = LGAMMA_EXPANSION_COEF[7];
+
+    for (int i = 6; i >= 0; i--) {
+      sum *= z;
+      sum += LGAMMA_EXPANSION_COEF[i];
+    }
+    float series = sum / abs_x;
+
+    rc = (abs_x - 0.5) * ::metal::log(abs_x) - abs_x + HALF_LOG_TWO_PI + series;
+  }
+
+  if (x >= 0) {
+    return rc;
+  }
+
+  // Reflection formula
+  // Compute arg first to workaround Metal compiler bgg of sorts on M4
+  // See https://github.com/pytorch/pytorch/pull/145740 for more details
+  auto log_arg = abs_x * ::metal::abs(::metal::sinpi(abs_x));
+  return LOG_PI - rc - ::metal::log(log_arg);
+}
+
+inline float zeta(float x, float q) {
+  constexpr float MACHEP = 1.11022302462515654042E-16;
+  constexpr float ZETA_EXPANSION[] = {
+      12.0,
+      -720.0,
+      30240.0,
+      -1209600.0,
+      47900160.0,
+      -1.8924375803183791606e9,
+      7.47242496e10,
+      -2.950130727918164224e12,
+      1.1646782814350067249e14,
+      -4.5979787224074726105e15,
+      1.8152105401943546773e17,
+      -7.1661652561756670113e18};
+  if (x == 1.0f) {
+    return INFINITY;
+  }
+
+  if (x < 1.0f) {
+    return NAN;
+  }
+
+  if (q <= 0.0f) {
+    if (q == ::metal::trunc(q)) {
+      return INFINITY;
+    }
+    if (x != ::metal::trunc(x)) {
+      return NAN;
+    }
+  }
+
+  float s = ::metal::pow(q, -x);
+  float a = q;
+  int i = 0;
+  float b = 0.0f;
+  while ((i < 9) || (a <= 9.0f)) {
+    i += 1;
+    a += 1.0f;
+    b = ::metal::pow(a, -x);
+    s += b;
+    if ((-MACHEP * s < b) && (b < MACHEP * s)) {
+      return s;
+    }
+  }
+
+  float w = a;
+  s += b * w / (x - 1.0f);
+  s -= 0.5f * b;
+  a = 1.0f;
+  float t;
+  float k = 0.0f;
+  for (int i = 0; i < 12; i++) {
+    a *= x + k;
+    b /= w;
+    t = a * b / ZETA_EXPANSION[i];
+    s += t;
+    t = ::metal::fabs(t / s);
+    if (t < MACHEP) {
+      return s;
+    }
+    k += 1.0f;
+    a *= x + k;
+    b /= w;
+    k += 1.0f;
+  }
+  return s;
+}
+
+template 
+inline float polygamma(const int64_t order, const T0 input) {
+  float x = input;
+  float n = order;
+  float sgn = ((order % 2) ? 1 : -1);
+  return sgn * gamma(n + 1) * zeta(n + 1, x);
+}
+
+inline float calc_digamma_positive_domain(float x) {
+  constexpr float DIGAMMA_COEF[7] = {
+      8.33333333333333333333E-2,
+      -2.10927960927960927961E-2,
+      7.57575757575757575758E-3,
+      -4.16666666666666666667E-3,
+      3.96825396825396825397E-3,
+      -8.33333333333333333333E-3,
+      8.33333333333333333333E-2,
+  };
+
+  // Push x to be >= 10
+  float result = 0;
+  while (x < 10) {
+    result -= 1 / x;
+    x += 1;
+  }
+  if (x == 10) {
+    constexpr float PSI_10 = 2.25175258906672110764;
+    return result + PSI_10;
+  }
+
+  // Compute asymptotic digamma
+  float y = 0;
+  if (x < 1.0E+17) {
+    float z = 1.0 / (x * x);
+    for (int i = 0; i <= 6; i++) {
+      y += ::metal::pow(z, i) * DIGAMMA_COEF[i];
+    }
+    y *= z;
+  }
+  return result + ::metal::log(x) - (0.5 / x) - y;
+}
+
+template 
+inline float digamma(T0 x) {
+  if (x < 0.0f) {
+    if (x == ::metal::trunc(x)) {
+      // As per C++ standard for gamma related functions and SciPy,
+      // If the argument is a negative integer, NaN is returned
+      return NAN;
+    } else {
+      // Extracts the fractional part of x as r, since tan(pi * r) is more
+      // numerically accurate than tan(pi * x). While these operations are
+      // mathematically equivalent since both x and r are in radians and tan()
+      // has a periodicity of pi, in practice the computation of pi * x is a
+      // source of error (when |x| > 1).
+      float r = ::metal::fract(x);
+      return calc_digamma_positive_domain(1.0f - x) -
+          M_PI_F / ::metal::tan(M_PI_F * r);
+    }
+  } else if (x == 0.0f) {
+    // As per C++ standard for gamma related functions and SciPy,
+    // If the argument is ±0, ±∞ is returned
+    return ::metal::copysign(INFINITY, static_cast(-x));
+  } else {
+    return calc_digamma_positive_domain(x);
+  }
+}
+
+template 
+inline ::metal::enable_if_t, T> sinc(T a) {
+  if (a == static_cast(0)) {
+    return static_cast(1);
+  }
+  auto product = M_PI_F * static_cast(a);
+  return static_cast(::metal::precise::sin(product) / product);
+}
+
+// Complex sinc2 implementation
+template 
+inline ::metal::enable_if_t, T> sinc(T inp) {
+  auto a = static_cast(inp) * M_PI_F;
+  const float a2 = a.x * a.x + a.y * a.y;
+  if (a2 == 0) {
+    return 0;
+  }
+  float cosx;
+  float sinx = ::metal::sincos(a.x, cosx);
+  float sinhy = ::metal::sinh(a.y);
+  float coshy = ::metal::cosh(a.y);
+  auto re = sinx * coshy * a.x + cosx * sinhy * a.y;
+  auto im = cosx * sinhy * a.x - sinx * coshy * a.y;
+  return T(re, im) / a2;
+}
+
+template 
+inline T spherical_bessel_j0(T x) {
+  if (::metal::isinf(x))
+    return T(0.0);
+  T x2 = x * x;
+  T k1 = static_cast(-1.0);
+  T k2 = static_cast(1.0);
+
+  if (::metal::fabs(static_cast(x)) < T(0.5)) {
+    return T(1.0) +
+        x2 *
+        (k1 / T(6.0) +
+         x2 *
+             (k2 / T(120.0) +
+              x2 *
+                  (k1 / T(5040.0) +
+                   x2 *
+                       (k2 / T(362880.0) +
+                        x2 *
+                            (k1 / T(39916800.0) +
+                             x2 * (k2 / T(6227020800.0)))))));
+  }
+
+  return static_cast(::metal::sin(x) / x);
+}
+
+// Compute log(1+x) without losing precision for small values of x
+// Adapted from https://www.johndcook.com/blog/cpp_log_one_plus_x/
+template 
+inline float log1p(T x) {
+  // x is large enough that the obvious evaluation is OK
+  if (::metal::fabs(x) > 1E-4) {
+    return ::metal::log(1. + x);
+  }
+
+  // Use Taylor approx. log(1 + x) = x - x^2/2 with error roughly x^3/3
+  // Since |x| < 10^-4, |x|^3 < 10^-12, relative error less than 10^-8
+  return (-0.5 * x + 1.0) * x;
+}
+
+template 
+inline float xlog1py(T x, T y) {
+  if (::metal::isnan(y)) {
+    return NAN;
+  }
+
+  if (x == 0) {
+    return x;
+  }
+
+  return x * log1p(y);
+}
+
+template 
+inline T entr(T a) {
+  if (a != a) {
+    return a;
+  }
+
+  if (a > 0) {
+    return static_cast(-a * ::metal::log(a));
+  }
+
+  if (a == 0) {
+    return 0;
+  }
+
+  return static_cast(-INFINITY);
+}
+
+} // namespace metal
+} // namespace c10
diff --git a/shared/package-files/a5/a5ed50c79ebbe4493ca2db226858f89d59fade9f94576259e86457d3d719695a/var_cpu_dispatch.h b/shared/package-files/a5/a5ed50c79ebbe4493ca2db226858f89d59fade9f94576259e86457d3d719695a/var_cpu_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b373a33d14e67826f2495c1a76afbfc91ccafaf
--- /dev/null
+++ b/shared/package-files/a5/a5ed50c79ebbe4493ca2db226858f89d59fade9f94576259e86457d3d719695a/var_cpu_dispatch.h
@@ -0,0 +1,25 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cpu {
+
+TORCH_API at::Tensor var(const at::Tensor & self, at::OptionalIntArrayRef dim=::std::nullopt, const ::std::optional & correction=::std::nullopt, bool keepdim=false);
+TORCH_API at::Tensor & var_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim=::std::nullopt, const ::std::optional & correction=::std::nullopt, bool keepdim=false);
+TORCH_API at::Tensor & var_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, const ::std::optional & correction, bool keepdim, at::Tensor & out);
+
+} // namespace cpu
+} // namespace at
diff --git a/shared/package-files/a5/a5f2a48dfa693862f353af133a754e3afb6034aecd8811cf1c6b828f32529174/test_compare.cpython-311.pyc b/shared/package-files/a5/a5f2a48dfa693862f353af133a754e3afb6034aecd8811cf1c6b828f32529174/test_compare.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db0d112a5c58e8dfbde2707623c74e30ff2c2efc
Binary files /dev/null and b/shared/package-files/a5/a5f2a48dfa693862f353af133a754e3afb6034aecd8811cf1c6b828f32529174/test_compare.cpython-311.pyc differ
diff --git a/shared/package-files/a5/a5f94d89c868818f1adcdccd2f784b4c233a4527fdec2857278ce6fb5ffa240f/expand_as.h b/shared/package-files/a5/a5f94d89c868818f1adcdccd2f784b4c233a4527fdec2857278ce6fb5ffa240f/expand_as.h
new file mode 100644
index 0000000000000000000000000000000000000000..ba1f73b3b941a094a718f177b10d89d7d2beb9de
--- /dev/null
+++ b/shared/package-files/a5/a5f94d89c868818f1adcdccd2f784b4c233a4527fdec2857278ce6fb5ffa240f/expand_as.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+
+}
diff --git a/shared/package-files/b6/b604bb2bd32d0b2284ed755922f34ceb1864c991d6a5a6926e5680fd8781657e/test_pathway.cpython-311.pyc b/shared/package-files/b6/b604bb2bd32d0b2284ed755922f34ceb1864c991d6a5a6926e5680fd8781657e/test_pathway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5f4a2ed05434092416e9f19bc70f7cec4c12503
Binary files /dev/null and b/shared/package-files/b6/b604bb2bd32d0b2284ed755922f34ceb1864c991d6a5a6926e5680fd8781657e/test_pathway.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b60602e4dcaf397a7f44d84b41c2c6c09e946823567a1f83c8236e94aa073ca2/cpp_gemm_template.cpython-311.pyc b/shared/package-files/b6/b60602e4dcaf397a7f44d84b41c2c6c09e946823567a1f83c8236e94aa073ca2/cpp_gemm_template.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d919bf5aba4158c8cf23a9e7141c74981a181e1b
Binary files /dev/null and b/shared/package-files/b6/b60602e4dcaf397a7f44d84b41c2c6c09e946823567a1f83c8236e94aa073ca2/cpp_gemm_template.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b616015f724e553348f5b019f7324dec130f7bbaf984d43300fa69c7c2fdda2f/math.py b/shared/package-files/b6/b616015f724e553348f5b019f7324dec130f7bbaf984d43300fa69c7c2fdda2f/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ecdcf2eacb020bf5d7af21f819f729f75ab3ccc
--- /dev/null
+++ b/shared/package-files/b6/b616015f724e553348f5b019f7324dec130f7bbaf984d43300fa69c7c2fdda2f/math.py
@@ -0,0 +1,250 @@
+from . import core
+from . import semantic
+from functools import wraps
+from typing import List
+
+T = core.TypeVar('T')
+
+
+def _check_dtype(dtypes: List[str]) -> T:
+    """
+    We're following libdevice's convention to check accepted data types for math functions.
+    It is not a good practice to support all data types as accelerators/GPUs don't support
+    many float16 and bfloat16 math operations.
+    We should let the users know that they are using and invoke explicit cast to convert
+    the data type to the supported one.
+    """
+
+    def wrapper(fn):
+
+        @wraps(fn)
+        def check(*args, **kwargs):
+            # concatenate args and kwargs
+            all_args = list(args) + list(kwargs.values())
+            for arg in [a for a in all_args if isinstance(a, core.tensor)]:
+                if arg.type.scalar.name not in dtypes:
+                    raise ValueError(f"Expected dtype {dtypes} but got {arg.type.scalar.name}")
+            return fn(*args, **kwargs)
+
+        return check
+
+    return wrapper
+
+
+def _add_math_1arg_docstr(name: str) -> core.Callable[[T], T]:
+
+    def _decorator(func: T) -> T:
+        docstr = """
+    Computes the element-wise {name} of :code:`x`.
+
+    :param x: the input values
+    :type x: Block
+    """
+        func.__doc__ = docstr.format(name=name)
+        return func
+
+    return _decorator
+
+
+def _add_math_2arg_docstr(name: str) -> core.Callable[[T], T]:
+
+    def _decorator(func: T) -> T:
+        docstr = """
+    Computes the element-wise {name} of :code:`x` and :code:`y`.
+
+    :param x: the input values
+    :type x: Block
+    :param y: the input values
+    :type y: Block
+    """
+        func.__doc__ = docstr.format(name=name)
+        return func
+
+    return _decorator
+
+
+def _add_math_3arg_docstr(name: str) -> core.Callable[[T], T]:
+
+    def _decorator(func: T) -> T:
+        docstr = """
+    Computes the element-wise {name} of :code:`x`, :code:`y`, and :code:`z`.
+
+    :param x: the input values
+    :type x: Block
+    :param y: the input values
+    :type y: Block
+    :param z: the input values
+    :type z: Block
+    """
+        func.__doc__ = docstr.format(name=name)
+        return func
+
+    return _decorator
+
+
+@core.builtin
+@_check_dtype(dtypes=["int32", "int64", "uint32", "uint64"])
+@_add_math_2arg_docstr("most significant N bits of the 2N-bit product")
+def umulhi(x, y, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    y = semantic.to_tensor(y, _builder)
+    x, y = core.binary_op_type_legalization(x, y, _builder)
+    return core.tensor(_builder.create_umulhi(x.handle, y.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("exponential")
+@core._tensor_member_fn
+def exp(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_exp(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("exponential (base 2)")
+@core._tensor_member_fn
+def exp2(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_exp2(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("natural logarithm")
+@core._tensor_member_fn
+def log(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_log(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("logarithm (base 2)")
+@core._tensor_member_fn
+def log2(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_log2(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("cosine")
+@core._tensor_member_fn
+def cos(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_cos(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("sine")
+@core._tensor_member_fn
+def sin(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_sin(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("fast square root")
+@core._tensor_member_fn
+def sqrt(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_sqrt(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32"])
+@_add_math_1arg_docstr("precise square root (rounding to nearest wrt the IEEE standard)")
+@core._tensor_member_fn
+def sqrt_rn(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_precise_sqrt(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("inverse square root")
+@core._tensor_member_fn
+def rsqrt(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_rsqrt(x.handle), x.type)
+
+
+@core._tensor_member_fn
+@core.builtin
+@_add_math_1arg_docstr("absolute value")
+def abs(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    dtype = x.dtype
+    if dtype.is_fp8e4b15():
+        mask = core.full(x.shape, 0x7F, core.int8, _builder=_builder)
+        return core.tensor(_builder.create_and(x.handle, mask.handle), x.type)
+    elif dtype.is_floating():
+        return core.tensor(_builder.create_fabs(x.handle), x.type)
+    elif dtype.is_int_signed():
+        return core.tensor(_builder.create_iabs(x.handle), x.type)
+    elif dtype.is_int_unsigned():
+        return x  # no-op
+    else:
+        assert False, f"Unexpected dtype {dtype}"
+
+
+@core.builtin
+@_add_math_2arg_docstr("fast division")
+def fdiv(x, y, ieee_rounding=False, _builder=None):
+    ieee_rounding = core._constexpr_to_value(ieee_rounding)
+    x = semantic.to_tensor(x, _builder)
+    y = semantic.to_tensor(y, _builder)
+    return semantic.fdiv(x, y, ieee_rounding, _builder)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32"])
+@_add_math_2arg_docstr("precise division (rounding to nearest wrt the IEEE standard)")
+def div_rn(x, y, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    y = semantic.to_tensor(y, _builder)
+    x, y = core.binary_op_type_legalization(x, y, _builder)
+    return core.tensor(_builder.create_precise_divf(x.handle, y.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("error function")
+@core._tensor_member_fn
+def erf(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_erf(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("floor")
+@core._tensor_member_fn
+def floor(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_floor(x.handle), x.type)
+
+
+@core.builtin
+@_check_dtype(dtypes=["fp32", "fp64"])
+@_add_math_1arg_docstr("ceil")
+@core._tensor_member_fn
+def ceil(x, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    return core.tensor(_builder.create_ceil(x.handle), x.type)
+
+
+@core.builtin
+@_add_math_3arg_docstr("fused multiply-add")
+def fma(x, y, z, _builder=None):
+    x = semantic.to_tensor(x, _builder)
+    y = semantic.to_tensor(y, _builder)
+    z = semantic.to_tensor(z, _builder)
+    x, y = core.binary_op_type_legalization(x, y, _builder)
+    z, x = core.binary_op_type_legalization(z, x, _builder)
+    z, y = core.binary_op_type_legalization(z, y, _builder)
+    return core.tensor(_builder.create_fma(x.handle, y.handle, z.handle), x.type)
diff --git a/shared/package-files/b6/b61f9297c8e5048ee946f7d6e5388fb2e503da9a24057ef15f52a74a8162db44/python_parser.cpython-311.pyc b/shared/package-files/b6/b61f9297c8e5048ee946f7d6e5388fb2e503da9a24057ef15f52a74a8162db44/python_parser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffcae090828aa5951e3aaaee56732344c934cf01
Binary files /dev/null and b/shared/package-files/b6/b61f9297c8e5048ee946f7d6e5388fb2e503da9a24057ef15f52a74a8162db44/python_parser.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b6205f835b48d35d99a2b24167e32d4acd29388c3d67f300059f6752feef63d4/CUDAHooksInterface.h b/shared/package-files/b6/b6205f835b48d35d99a2b24167e32d4acd29388c3d67f300059f6752feef63d4/CUDAHooksInterface.h
new file mode 100644
index 0000000000000000000000000000000000000000..9b54a84dd68dfe7e7767656c3bce8b3a80d42b5b
--- /dev/null
+++ b/shared/package-files/b6/b6205f835b48d35d99a2b24167e32d4acd29388c3d67f300059f6752feef63d4/CUDAHooksInterface.h
@@ -0,0 +1,220 @@
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include 
+
+// NB: Class must live in `at` due to limitations of Registry.h.
+namespace at {
+
+// Forward-declares at::cuda::NVRTC
+namespace cuda {
+struct NVRTC;
+} // namespace cuda
+
+#ifdef _MSC_VER
+constexpr const char* CUDA_HELP =
+  "PyTorch splits its backend into two shared libraries: a CPU library "
+  "and a CUDA library; this error has occurred because you are trying "
+  "to use some CUDA functionality, but the CUDA library has not been "
+  "loaded by the dynamic linker for some reason.  The CUDA library MUST "
+  "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! "
+  "One common culprit is a lack of -INCLUDE:?warp_size@cuda@at@@YAHXZ "
+  "in your link arguments; many dynamic linkers will delete dynamic library "
+  "dependencies if you don't depend on any of their symbols.  You can check "
+  "if this has occurred by using link on your binary to see if there is a "
+  "dependency on *_cuda.dll library.";
+#else
+constexpr const char* CUDA_HELP =
+  "PyTorch splits its backend into two shared libraries: a CPU library "
+  "and a CUDA library; this error has occurred because you are trying "
+  "to use some CUDA functionality, but the CUDA library has not been "
+  "loaded by the dynamic linker for some reason.  The CUDA library MUST "
+  "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! "
+  "One common culprit is a lack of -Wl,--no-as-needed in your link arguments; many "
+  "dynamic linkers will delete dynamic library dependencies if you don't "
+  "depend on any of their symbols.  You can check if this has occurred by "
+  "using ldd on your binary to see if there is a dependency on *_cuda.so "
+  "library.";
+#endif
+
+// The CUDAHooksInterface is an omnibus interface for any CUDA functionality
+// which we may want to call into from CPU code (and thus must be dynamically
+// dispatched, to allow for separate compilation of CUDA code).  How do I
+// decide if a function should live in this class?  There are two tests:
+//
+//  1. Does the *implementation* of this function require linking against
+//     CUDA libraries?
+//
+//  2. Is this function *called* from non-CUDA ATen code?
+//
+// (2) should filter out many ostensible use-cases, since many times a CUDA
+// function provided by ATen is only really ever used by actual CUDA code.
+//
+// TODO: Consider putting the stub definitions in another class, so that one
+// never forgets to implement each virtual function in the real implementation
+// in CUDAHooks.  This probably doesn't buy us much though.
+struct TORCH_API CUDAHooksInterface : AcceleratorHooksInterface {
+  // This should never actually be implemented, but it is used to
+  // squelch -Werror=non-virtual-dtor
+  ~CUDAHooksInterface() override = default;
+
+  // Initialize THCState and, transitively, the CUDA state
+  void init() const override {
+    TORCH_CHECK(false, "Cannot initialize CUDA without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  const Generator& getDefaultGenerator(
+      [[maybe_unused]] DeviceIndex device_index = -1) const override {
+    TORCH_CHECK(
+        false,
+        "Cannot get default CUDA generator without ATen_cuda library. ",
+        CUDA_HELP);
+  }
+
+  Generator getNewGenerator(
+      [[maybe_unused]] DeviceIndex device_index = -1) const override {
+    TORCH_CHECK(
+        false,
+        "Cannot get CUDA generator without ATen_cuda library. ",
+        CUDA_HELP);
+  }
+
+  Device getDeviceFromPtr(void* /*data*/) const override {
+    TORCH_CHECK(false, "Cannot get device of pointer on CUDA without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  bool isPinnedPtr(const void* data) const override {
+    return false;
+  }
+
+  virtual bool hasCUDA() const {
+    return false;
+  }
+
+  virtual bool hasCUDART() const {
+    return false;
+  }
+
+  virtual bool hasMAGMA() const {
+    return false;
+  }
+
+  virtual bool hasCuDNN() const {
+    return false;
+  }
+
+  virtual bool hasCuSOLVER() const {
+    return false;
+  }
+
+  virtual bool hasCuBLASLt() const {
+    return false;
+  }
+
+  virtual bool hasROCM() const {
+    return false;
+  }
+
+  virtual const at::cuda::NVRTC& nvrtc() const {
+    TORCH_CHECK(false, "NVRTC requires CUDA. ", CUDA_HELP);
+  }
+
+  bool hasPrimaryContext(DeviceIndex device_index) const override {
+    TORCH_CHECK(false, "Cannot call hasPrimaryContext(", device_index, ") without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual DeviceIndex current_device() const {
+    return -1;
+  }
+
+  Allocator* getPinnedMemoryAllocator() const override {
+    TORCH_CHECK(false, "Pinned memory requires CUDA. ", CUDA_HELP);
+  }
+
+  virtual Allocator* getCUDADeviceAllocator() const {
+    TORCH_CHECK(false, "CUDADeviceAllocator requires CUDA. ", CUDA_HELP);
+  }
+
+  virtual bool compiledWithCuDNN() const {
+    return false;
+  }
+
+  virtual bool compiledWithMIOpen() const {
+    return false;
+  }
+
+  virtual bool supportsDilatedConvolutionWithCuDNN() const {
+    return false;
+  }
+
+  virtual bool supportsDepthwiseConvolutionWithCuDNN() const {
+    return false;
+  }
+
+  virtual bool supportsBFloat16ConvolutionWithCuDNNv8() const {
+    return false;
+  }
+
+  virtual long versionCuDNN() const {
+    TORCH_CHECK(false, "Cannot query cuDNN version without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual long versionCUDART() const {
+    TORCH_CHECK(false, "Cannot query CUDART version without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual std::string showConfig() const {
+    TORCH_CHECK(false, "Cannot query detailed CUDA version without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual double batchnormMinEpsilonCuDNN() const {
+    TORCH_CHECK(false,
+        "Cannot query batchnormMinEpsilonCuDNN() without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex /*device_index*/) const {
+    TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual void cuFFTSetPlanCacheMaxSize(DeviceIndex /*device_index*/, int64_t /*max_size*/) const {
+    TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual int64_t cuFFTGetPlanCacheSize(DeviceIndex /*device_index*/) const {
+    TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual void cuFFTClearPlanCache(DeviceIndex /*device_index*/) const {
+    TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP);
+  }
+
+  virtual int getNumGPUs() const {
+    return 0;
+  }
+
+#ifdef USE_ROCM
+  virtual bool isGPUArch(DeviceIndex /*device_index*/, const std::vector& /*archs*/) const {
+    TORCH_CHECK(false, "Cannot check GPU arch without ATen_cuda library. ", CUDA_HELP);
+  }
+#endif
+
+  virtual void deviceSynchronize(DeviceIndex /*device_index*/) const {
+    TORCH_CHECK(false, "Cannot synchronize CUDA device without ATen_cuda library. ", CUDA_HELP);
+  }
+};
+
+// NB: dummy argument to suppress "ISO C++11 requires at least one argument
+// for the "..." in a variadic macro"
+struct TORCH_API CUDAHooksArgs {};
+
+TORCH_DECLARE_REGISTRY(CUDAHooksRegistry, CUDAHooksInterface, CUDAHooksArgs);
+#define REGISTER_CUDA_HOOKS(clsname) \
+  C10_REGISTER_CLASS(CUDAHooksRegistry, clsname, clsname)
+
+namespace detail {
+TORCH_API const CUDAHooksInterface& getCUDAHooks();
+} // namespace detail
+} // namespace at
diff --git a/shared/package-files/b6/b624bdf65f735e8b486b5212de68fd5f28fbc0544f7c4d0973efc1c8ce473021/saveopts.cpython-311.pyc b/shared/package-files/b6/b624bdf65f735e8b486b5212de68fd5f28fbc0544f7c4d0973efc1c8ce473021/saveopts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a151a6536037c64571fa3a067f0b98b44f8d1e3
Binary files /dev/null and b/shared/package-files/b6/b624bdf65f735e8b486b5212de68fd5f28fbc0544f7c4d0973efc1c8ce473021/saveopts.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b62853f3b78ff0c176e020c7dc53021fbbc577522af22f24afb1fcfd48d18100/test_orc.py b/shared/package-files/b6/b62853f3b78ff0c176e020c7dc53021fbbc577522af22f24afb1fcfd48d18100/test_orc.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0f9e813b103d45374ca807aef50504436330580
--- /dev/null
+++ b/shared/package-files/b6/b62853f3b78ff0c176e020c7dc53021fbbc577522af22f24afb1fcfd48d18100/test_orc.py
@@ -0,0 +1,693 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import decimal
+import datetime
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+import pyarrow as pa
+from pyarrow import fs
+from pyarrow.tests import util
+
+
+# Marks all of the tests in this module
+# Ignore these with pytest ... -m 'not orc'
+pytestmark = pytest.mark.orc
+
+
+try:
+    from pandas.testing import assert_frame_equal
+    import pandas as pd
+except ImportError:
+    pass
+
+
+@pytest.fixture(scope="module")
+def datadir(base_datadir):
+    return base_datadir / "orc"
+
+
+def fix_example_values(actual_cols, expected_cols):
+    """
+    Fix type of expected values (as read from JSON) according to
+    actual ORC datatype.
+    """
+    for name in expected_cols:
+        expected = expected_cols[name]
+        actual = actual_cols[name]
+        if (name == "map" and
+                [d.keys() == {'key', 'value'} for m in expected for d in m]):
+            # convert [{'key': k, 'value': v}, ...] to [(k, v), ...]
+            col = expected_cols[name].copy()
+            for i, m in enumerate(expected):
+                col[i] = [(d['key'], d['value']) for d in m]
+            expected_cols[name] = col
+            continue
+
+        typ = actual[0].__class__
+        if issubclass(typ, datetime.datetime):
+            # timestamp fields are represented as strings in JSON files
+            expected = pd.to_datetime(expected)
+        elif issubclass(typ, datetime.date):
+            # date fields are represented as strings in JSON files
+            expected = expected.dt.date
+        elif typ is decimal.Decimal:
+            converted_decimals = [None] * len(expected)
+            # decimal fields are represented as reals in JSON files
+            for i, (d, v) in enumerate(zip(actual, expected)):
+                if not pd.isnull(v):
+                    exp = d.as_tuple().exponent
+                    factor = 10 ** -exp
+                    converted_decimals[i] = (
+                        decimal.Decimal(round(v * factor)).scaleb(exp))
+            expected = pd.Series(converted_decimals)
+
+        expected_cols[name] = expected
+
+
+def check_example_values(orc_df, expected_df, start=None, stop=None):
+    if start is not None or stop is not None:
+        expected_df = expected_df[start:stop].reset_index(drop=True)
+    assert_frame_equal(orc_df, expected_df, check_dtype=False)
+
+
+def check_example_file(orc_path, expected_df, need_fix=False):
+    """
+    Check a ORC file against the expected columns dictionary.
+    """
+    from pyarrow import orc
+
+    orc_file = orc.ORCFile(orc_path)
+    # Exercise ORCFile.read()
+    table = orc_file.read()
+    assert isinstance(table, pa.Table)
+    table.validate()
+
+    # This workaround needed because of ARROW-3080
+    orc_df = pd.DataFrame(table.to_pydict())
+
+    assert set(expected_df.columns) == set(orc_df.columns)
+
+    # reorder columns if necessary
+    if not orc_df.columns.equals(expected_df.columns):
+        expected_df = expected_df.reindex(columns=orc_df.columns)
+
+    if need_fix:
+        fix_example_values(orc_df, expected_df)
+
+    check_example_values(orc_df, expected_df)
+    # Exercise ORCFile.read_stripe()
+    json_pos = 0
+    for i in range(orc_file.nstripes):
+        batch = orc_file.read_stripe(i)
+        check_example_values(pd.DataFrame(batch.to_pydict()),
+                             expected_df,
+                             start=json_pos,
+                             stop=json_pos + len(batch))
+        json_pos += len(batch)
+    assert json_pos == orc_file.nrows
+
+
+@pytest.mark.pandas
+@pytest.mark.parametrize('filename', [
+    'TestOrcFile.test1.orc',
+    'TestOrcFile.testDate1900.orc',
+    'decimal.orc'
+])
+def test_example_using_json(filename, datadir):
+    """
+    Check a ORC file example against the equivalent JSON file, as given
+    in the Apache ORC repository (the JSON file has one JSON object per
+    line, corresponding to one row in the ORC file).
+    """
+    # Read JSON file
+    path = datadir / filename
+    table = pd.read_json(str(path.with_suffix('.jsn.gz')), lines=True)
+    check_example_file(path, table, need_fix=True)
+
+
+def test_timezone_database_absent(datadir):
+    # Example file relies on the timezone "US/Pacific". It should gracefully
+    # fail, not crash, if the timezone database is not found.
+    path = datadir / 'TestOrcFile.testDate1900.orc'
+    code = f"""if 1:
+        import os
+        os.environ['TZDIR'] = '/tmp/non_existent'
+
+        from pyarrow import orc
+        try:
+            orc_file = orc.ORCFile({str(path)!r})
+            orc_file.read()
+        except Exception as e:
+            assert "time zone database" in str(e).lower(), e
+        else:
+            assert False, "Should have raised exception"
+    """
+    subprocess.run([sys.executable, "-c", code], check=True)
+
+
+def test_timezone_absent(datadir, tmpdir):
+    # Example file relies on the timezone "US/Pacific". It should gracefully
+    # fail, not crash, if the timezone database is present but the timezone
+    # is not found (GH-40633).
+    source_tzdir = Path('/usr/share/zoneinfo')
+    if not source_tzdir.exists():
+        pytest.skip(f"Test needs timezone database in {source_tzdir}")
+    tzdir = Path(tmpdir / 'zoneinfo')
+    try:
+        shutil.copytree(source_tzdir, tzdir, symlinks=True)
+    except OSError as e:
+        pytest.skip(f"Failed to copy timezone database: {e}")
+    (tzdir / 'US' / 'Pacific').unlink(missing_ok=True)
+
+    path = datadir / 'TestOrcFile.testDate1900.orc'
+    code = f"""if 1:
+        import os
+        os.environ['TZDIR'] = {str(tzdir)!r}
+
+        from pyarrow import orc
+        orc_file = orc.ORCFile({str(path)!r})
+        try:
+            orc_file.read()
+        except Exception as e:
+            assert "zoneinfo/US/Pacific" in str(e), e
+        else:
+            assert False, "Should have raised exception"
+    """
+    subprocess.run([sys.executable, "-c", code], check=True)
+
+
+def test_orcfile_empty(datadir):
+    from pyarrow import orc
+
+    table = orc.ORCFile(datadir / "TestOrcFile.emptyFile.orc").read()
+    assert table.num_rows == 0
+
+    expected_schema = pa.schema([
+        ("boolean1", pa.bool_()),
+        ("byte1", pa.int8()),
+        ("short1", pa.int16()),
+        ("int1", pa.int32()),
+        ("long1", pa.int64()),
+        ("float1", pa.float32()),
+        ("double1", pa.float64()),
+        ("bytes1", pa.binary()),
+        ("string1", pa.string()),
+        ("middle", pa.struct(
+            [("list", pa.list_(
+                pa.struct([("int1", pa.int32()),
+                           ("string1", pa.string())])))
+             ])),
+        ("list", pa.list_(
+            pa.struct([("int1", pa.int32()),
+                       ("string1", pa.string())])
+        )),
+        ("map", pa.map_(pa.string(),
+                        pa.struct([("int1", pa.int32()),
+                                   ("string1", pa.string())])
+                        )),
+    ])
+    assert table.schema == expected_schema
+
+
+def test_filesystem_uri(tmpdir):
+    from pyarrow import orc
+    table = pa.table({"a": [1, 2, 3]})
+
+    directory = tmpdir / "data_dir"
+    directory.mkdir()
+    path = directory / "data.orc"
+    orc.write_table(table, str(path))
+
+    # filesystem object
+    result = orc.read_table(path, filesystem=fs.LocalFileSystem())
+    assert result.equals(table)
+
+    # filesystem URI
+    result = orc.read_table(
+        "data_dir/data.orc", filesystem=util._filesystem_uri(tmpdir))
+    assert result.equals(table)
+
+    # use the path only
+    result = orc.read_table(
+        util._filesystem_uri(path))
+    assert result.equals(table)
+
+
+def test_orcfile_readwrite(tmpdir):
+    from pyarrow import orc
+    a = pa.array([1, None, 3, None])
+    b = pa.array([None, "Arrow", None, "ORC"])
+    table = pa.table({"int64": a, "utf8": b})
+    file = tmpdir.join("test.orc")
+    orc.write_table(table, file)
+    output_table = orc.read_table(file)
+    assert table.equals(output_table)
+
+    output_table = orc.read_table(file, [])
+    assert 4 == output_table.num_rows
+    assert 0 == output_table.num_columns
+
+    output_table = orc.read_table(file, columns=["int64"])
+    assert 4 == output_table.num_rows
+    assert 1 == output_table.num_columns
+
+
+def test_bytesio_readwrite():
+    from pyarrow import orc
+    from io import BytesIO
+
+    buf = BytesIO()
+    a = pa.array([1, None, 3, None])
+    b = pa.array([None, "Arrow", None, "ORC"])
+    table = pa.table({"int64": a, "utf8": b})
+    orc.write_table(table, buf)
+    buf.seek(0)
+    orc_file = orc.ORCFile(buf)
+    output_table = orc_file.read()
+    assert table.equals(output_table)
+
+
+def test_buffer_readwrite():
+    from pyarrow import orc
+
+    buffer_output_stream = pa.BufferOutputStream()
+    a = pa.array([1, None, 3, None])
+    b = pa.array([None, "Arrow", None, "ORC"])
+    table = pa.table({"int64": a, "utf8": b})
+    orc.write_table(table, buffer_output_stream)
+    buffer_reader = pa.BufferReader(buffer_output_stream.getvalue())
+    orc_file = orc.ORCFile(buffer_reader)
+    output_table = orc_file.read()
+    assert table.equals(output_table)
+    # Check for default WriteOptions
+    assert orc_file.compression == 'UNCOMPRESSED'
+    assert orc_file.file_version == '0.12'
+    assert orc_file.row_index_stride == 10000
+    assert orc_file.compression_size == 65536
+
+    # deprecated keyword order
+    buffer_output_stream = pa.BufferOutputStream()
+    with pytest.warns(FutureWarning):
+        orc.write_table(buffer_output_stream, table)
+    buffer_reader = pa.BufferReader(buffer_output_stream.getvalue())
+    orc_file = orc.ORCFile(buffer_reader)
+    output_table = orc_file.read()
+    assert table.equals(output_table)
+    # Check for default WriteOptions
+    assert orc_file.compression == 'UNCOMPRESSED'
+    assert orc_file.file_version == '0.12'
+    assert orc_file.row_index_stride == 10000
+    assert orc_file.compression_size == 65536
+
+
+@pytest.mark.snappy
+def test_buffer_readwrite_with_writeoptions():
+    from pyarrow import orc
+
+    buffer_output_stream = pa.BufferOutputStream()
+    a = pa.array([1, None, 3, None])
+    b = pa.array([None, "Arrow", None, "ORC"])
+    table = pa.table({"int64": a, "utf8": b})
+    orc.write_table(
+        table,
+        buffer_output_stream,
+        compression='snappy',
+        file_version='0.11',
+        row_index_stride=5000,
+        compression_block_size=32768,
+    )
+    buffer_reader = pa.BufferReader(buffer_output_stream.getvalue())
+    orc_file = orc.ORCFile(buffer_reader)
+    output_table = orc_file.read()
+    assert table.equals(output_table)
+    # Check for modified WriteOptions
+    assert orc_file.compression == 'SNAPPY'
+    assert orc_file.file_version == '0.11'
+    assert orc_file.row_index_stride == 5000
+    assert orc_file.compression_size == 32768
+
+    # deprecated keyword order
+    buffer_output_stream = pa.BufferOutputStream()
+    with pytest.warns(FutureWarning):
+        orc.write_table(
+            buffer_output_stream,
+            table,
+            compression='uncompressed',
+            file_version='0.11',
+            row_index_stride=20000,
+            compression_block_size=16384,
+        )
+    buffer_reader = pa.BufferReader(buffer_output_stream.getvalue())
+    orc_file = orc.ORCFile(buffer_reader)
+    output_table = orc_file.read()
+    assert table.equals(output_table)
+    # Check for default WriteOptions
+    assert orc_file.compression == 'UNCOMPRESSED'
+    assert orc_file.file_version == '0.11'
+    assert orc_file.row_index_stride == 20000
+    assert orc_file.compression_size == 16384
+
+
+def test_buffer_readwrite_with_bad_writeoptions():
+    from pyarrow import orc
+    buffer_output_stream = pa.BufferOutputStream()
+    a = pa.array([1, None, 3, None])
+    table = pa.table({"int64": a})
+
+    # batch_size must be a positive integer
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            batch_size=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            batch_size=-100,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            batch_size=1024.23,
+        )
+
+    # file_version must be 0.11 or 0.12
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            file_version=0.13,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            file_version='1.1',
+        )
+
+    # stripe_size must be a positive integer
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            stripe_size=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            stripe_size=-400,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            stripe_size=4096.73,
+        )
+
+    # compression must be among the given options
+    with pytest.raises(TypeError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression='none',
+        )
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression='zlid',
+        )
+
+    # compression_block_size must be a positive integer
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_block_size=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_block_size=-200,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_block_size=1096.73,
+        )
+
+    # compression_strategy must be among the given options
+    with pytest.raises(TypeError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_strategy=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_strategy='no',
+        )
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            compression_strategy='large',
+        )
+
+    # row_index_stride must be a positive integer
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            row_index_stride=0,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            row_index_stride=-800,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            row_index_stride=3096.29,
+        )
+
+    # padding_tolerance must be possible to cast to float
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            padding_tolerance='cat',
+        )
+
+    # dictionary_key_size_threshold must be possible to cast to
+    # float between 0.0 and 1.0
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            dictionary_key_size_threshold='arrow',
+        )
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            dictionary_key_size_threshold=1.2,
+        )
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            dictionary_key_size_threshold=-3.2,
+        )
+
+    # bloom_filter_columns must be convertible to a list containing
+    # nonnegative integers
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_columns="string",
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_columns=[0, 1.4],
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_columns={0, 2, -1},
+        )
+
+    # bloom_filter_fpp must be convertible to a float between 0.0 and 1.0
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_fpp='arrow',
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_fpp=1.1,
+        )
+
+    with pytest.raises(ValueError):
+        orc.write_table(
+            table,
+            buffer_output_stream,
+            bloom_filter_fpp=-0.1,
+        )
+
+
+def test_column_selection(tempdir):
+    from pyarrow import orc
+
+    # create a table with nested types
+    inner = pa.field('inner', pa.int64())
+    middle = pa.field('middle', pa.struct([inner]))
+    fields = [
+        pa.field('basic', pa.int32()),
+        pa.field(
+            'list', pa.list_(pa.field('item', pa.int32()))
+        ),
+        pa.field(
+            'struct', pa.struct([middle, pa.field('inner2', pa.int64())])
+        ),
+        pa.field(
+            'list-struct', pa.list_(pa.field(
+                'item', pa.struct([
+                    pa.field('inner1', pa.int64()),
+                    pa.field('inner2', pa.int64())
+                ])
+            ))
+        ),
+        pa.field('basic2', pa.int64()),
+    ]
+    arrs = [
+        [0], [[1, 2]], [{"middle": {"inner": 3}, "inner2": 4}],
+        [[{"inner1": 5, "inner2": 6}, {"inner1": 7, "inner2": 8}]], [9]]
+    table = pa.table(arrs, schema=pa.schema(fields))
+
+    path = str(tempdir / 'test.orc')
+    orc.write_table(table, path)
+    orc_file = orc.ORCFile(path)
+
+    # default selecting all columns
+    result1 = orc_file.read()
+    assert result1.equals(table)
+
+    # selecting with columns names
+    result2 = orc_file.read(columns=["basic", "basic2"])
+    assert result2.equals(table.select(["basic", "basic2"]))
+
+    result3 = orc_file.read(columns=["list", "struct", "basic2"])
+    assert result3.equals(table.select(["list", "struct", "basic2"]))
+
+    # using dotted paths
+    result4 = orc_file.read(columns=["struct.middle.inner"])
+    expected4 = pa.table({"struct": [{"middle": {"inner": 3}}]})
+    assert result4.equals(expected4)
+
+    result5 = orc_file.read(columns=["struct.inner2"])
+    expected5 = pa.table({"struct": [{"inner2": 4}]})
+    assert result5.equals(expected5)
+
+    result6 = orc_file.read(
+        columns=["list", "struct.middle.inner", "struct.inner2"]
+    )
+    assert result6.equals(table.select(["list", "struct"]))
+
+    result7 = orc_file.read(columns=["list-struct.inner1"])
+    expected7 = pa.table({"list-struct": [[{"inner1": 5}, {"inner1": 7}]]})
+    assert result7.equals(expected7)
+
+    # selecting with (Arrow-based) field indices
+    result2 = orc_file.read(columns=[0, 4])
+    assert result2.equals(table.select(["basic", "basic2"]))
+
+    result3 = orc_file.read(columns=[1, 2, 3])
+    assert result3.equals(table.select(["list", "struct", "list-struct"]))
+
+    # error on non-existing name or index
+    with pytest.raises(IOError):
+        # liborc returns ParseError, which gets translated into IOError
+        # instead of ValueError
+        orc_file.read(columns=["wrong"])
+
+    with pytest.raises(ValueError):
+        orc_file.read(columns=[5])
+
+
+def test_wrong_usage_orc_writer(tempdir):
+    from pyarrow import orc
+
+    path = str(tempdir / 'test.orc')
+    with orc.ORCWriter(path) as writer:
+        with pytest.raises(AttributeError):
+            writer.test()
+
+
+def test_orc_writer_with_null_arrays(tempdir):
+    from pyarrow import orc
+
+    path = str(tempdir / 'test.orc')
+    a = pa.array([1, None, 3, None])
+    b = pa.array([None, None, None, None])
+    table = pa.table({"int64": a, "utf8": b})
+    with pytest.raises(pa.ArrowNotImplementedError):
+        orc.write_table(table, path)
diff --git a/shared/package-files/b6/b62cde44ea5638ac7da65bd699d35db7ba8adad0b304810955f48df17610ae05/constructor.cpython-311.pyc b/shared/package-files/b6/b62cde44ea5638ac7da65bd699d35db7ba8adad0b304810955f48df17610ae05/constructor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10f01cca1565e0f6d593ff4192a3c01386cbf601
Binary files /dev/null and b/shared/package-files/b6/b62cde44ea5638ac7da65bd699d35db7ba8adad0b304810955f48df17610ae05/constructor.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b62ea242642d3a18f1e29b0c1fe082415a6943fe158ee22b48cff3762f354009/NOTICE.txt b/shared/package-files/b6/b62ea242642d3a18f1e29b0c1fe082415a6943fe158ee22b48cff3762f354009/NOTICE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2089c6fb20358ccf5e3a58ea27a234555b923f6b
--- /dev/null
+++ b/shared/package-files/b6/b62ea242642d3a18f1e29b0c1fe082415a6943fe158ee22b48cff3762f354009/NOTICE.txt
@@ -0,0 +1,84 @@
+Apache Arrow
+Copyright 2016-2024 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+This product includes software from the SFrame project (BSD, 3-clause).
+* Copyright (C) 2015 Dato, Inc.
+* Copyright (c) 2009 Carnegie Mellon University.
+
+This product includes software from the Feather project (Apache 2.0)
+https://github.com/wesm/feather
+
+This product includes software from the DyND project (BSD 2-clause)
+https://github.com/libdynd
+
+This product includes software from the LLVM project
+ * distributed under the University of Illinois Open Source
+
+This product includes software from the google-lint project
+ * Copyright (c) 2009 Google Inc. All rights reserved.
+
+This product includes software from the mman-win32 project
+ * Copyright https://code.google.com/p/mman-win32/
+ * Licensed under the MIT License;
+
+This product includes software from the LevelDB project
+ * Copyright (c) 2011 The LevelDB Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * Moved from Kudu http://github.com/cloudera/kudu
+
+This product includes software from the CMake project
+ * Copyright 2001-2009 Kitware, Inc.
+ * Copyright 2012-2014 Continuum Analytics, Inc.
+ * All rights reserved.
+
+This product includes software from https://github.com/matthew-brett/multibuild (BSD 2-clause)
+ * Copyright (c) 2013-2016, Matt Terry and Matthew Brett; all rights reserved.
+
+This product includes software from the Ibis project (Apache 2.0)
+ * Copyright (c) 2015 Cloudera, Inc.
+ * https://github.com/cloudera/ibis
+
+This product includes software from Dremio (Apache 2.0)
+  * Copyright (C) 2017-2018 Dremio Corporation
+  * https://github.com/dremio/dremio-oss
+
+This product includes software from Google Guava (Apache 2.0)
+  * Copyright (C) 2007 The Guava Authors
+  * https://github.com/google/guava
+
+This product include software from CMake (BSD 3-Clause)
+  * CMake - Cross Platform Makefile Generator
+  * Copyright 2000-2019 Kitware, Inc. and Contributors
+
+The web site includes files generated by Jekyll.
+
+--------------------------------------------------------------------------------
+
+This product includes code from Apache Kudu, which includes the following in
+its NOTICE file:
+
+  Apache Kudu
+  Copyright 2016 The Apache Software Foundation
+
+  This product includes software developed at
+  The Apache Software Foundation (http://www.apache.org/).
+
+  Portions of this software were developed at
+  Cloudera, Inc (http://www.cloudera.com/).
+
+--------------------------------------------------------------------------------
+
+This product includes code from Apache ORC, which includes the following in
+its NOTICE file:
+
+  Apache ORC
+  Copyright 2013-2019 The Apache Software Foundation
+
+  This product includes software developed by The Apache Software
+  Foundation (http://www.apache.org/).
+
+  This product includes software developed by Hewlett-Packard:
+  (c) Copyright [2014-2015] Hewlett-Packard Development Company, L.P
diff --git a/shared/package-files/b6/b631cb928840e16b2f3a2b734f2f51b070c434eed50fd64d3c7448ac08a183b8/__init__.cpython-311.pyc b/shared/package-files/b6/b631cb928840e16b2f3a2b734f2f51b070c434eed50fd64d3c7448ac08a183b8/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c0f1bba783618b091da6c5b404fe6029ef58e7a
Binary files /dev/null and b/shared/package-files/b6/b631cb928840e16b2f3a2b734f2f51b070c434eed50fd64d3c7448ac08a183b8/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b632822da4acd065d05f7e6a76c907c9aa5bb39533439abb004395f7143a4654/test_factor_.cpython-311.pyc b/shared/package-files/b6/b632822da4acd065d05f7e6a76c907c9aa5bb39533439abb004395f7143a4654/test_factor_.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee93e8514883229c30d992ea68bd0dd21c02983c
Binary files /dev/null and b/shared/package-files/b6/b632822da4acd065d05f7e6a76c907c9aa5bb39533439abb004395f7143a4654/test_factor_.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b635f0b9a638dc71b772fe9de928664af34c3aa37898cd6d334340193491395b/convert.cpython-311.pyc b/shared/package-files/b6/b635f0b9a638dc71b772fe9de928664af34c3aa37898cd6d334340193491395b/convert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b61e282124ea0a0e8f0f2a0a30e2d539b3b50f1
Binary files /dev/null and b/shared/package-files/b6/b635f0b9a638dc71b772fe9de928664af34c3aa37898cd6d334340193491395b/convert.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b637450b2a564ef9600a2e74ddf9e96f9a50f501c5823cb7f4b37b00ec32343e/test_utils.cpython-311.pyc b/shared/package-files/b6/b637450b2a564ef9600a2e74ddf9e96f9a50f501c5823cb7f4b37b00ec32343e/test_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d46cb35c9248d59094f648e48c4e48681479d38f
Binary files /dev/null and b/shared/package-files/b6/b637450b2a564ef9600a2e74ddf9e96f9a50f501c5823cb7f4b37b00ec32343e/test_utils.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b639b86d635c7883daae3411dd2b0f70c0531cdcd0402cb8c8045406267735a9/__init__.cpython-311.pyc b/shared/package-files/b6/b639b86d635c7883daae3411dd2b0f70c0531cdcd0402cb8c8045406267735a9/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a52d6402e5a4e6801d9bd23433fac7caa735be2c
Binary files /dev/null and b/shared/package-files/b6/b639b86d635c7883daae3411dd2b0f70c0531cdcd0402cb8c8045406267735a9/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b63b18b32c6fa532b836b902b1e876ba3bc320657431ffdbe522397cfd93d323/support.py b/shared/package-files/b6/b63b18b32c6fa532b836b902b1e876ba3bc320657431ffdbe522397cfd93d323/support.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cd2b8a9eedbb9f11a3ed793af57b3290c5febef
--- /dev/null
+++ b/shared/package-files/b6/b63b18b32c6fa532b836b902b1e876ba3bc320657431ffdbe522397cfd93d323/support.py
@@ -0,0 +1,134 @@
+"""Support code for distutils test cases."""
+
+import itertools
+import os
+import pathlib
+import shutil
+import sys
+import sysconfig
+import tempfile
+from distutils.core import Distribution
+
+import pytest
+from more_itertools import always_iterable
+
+
+@pytest.mark.usefixtures('distutils_managed_tempdir')
+class TempdirManager:
+    """
+    Mix-in class that handles temporary directories for test cases.
+    """
+
+    def mkdtemp(self):
+        """Create a temporary directory that will be cleaned up.
+
+        Returns the path of the directory.
+        """
+        d = tempfile.mkdtemp()
+        self.tempdirs.append(d)
+        return d
+
+    def write_file(self, path, content='xxx'):
+        """Writes a file in the given path.
+
+        path can be a string or a sequence.
+        """
+        pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8')
+
+    def create_dist(self, pkg_name='foo', **kw):
+        """Will generate a test environment.
+
+        This function creates:
+         - a Distribution instance using keywords
+         - a temporary directory with a package structure
+
+        It returns the package directory and the distribution
+        instance.
+        """
+        tmp_dir = self.mkdtemp()
+        pkg_dir = os.path.join(tmp_dir, pkg_name)
+        os.mkdir(pkg_dir)
+        dist = Distribution(attrs=kw)
+
+        return pkg_dir, dist
+
+
+class DummyCommand:
+    """Class to store options for retrieval via set_undefined_options()."""
+
+    def __init__(self, **kwargs):
+        vars(self).update(kwargs)
+
+    def ensure_finalized(self):
+        pass
+
+
+def copy_xxmodule_c(directory):
+    """Helper for tests that need the xxmodule.c source file.
+
+    Example use:
+
+        def test_compile(self):
+            copy_xxmodule_c(self.tmpdir)
+            self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
+
+    If the source file can be found, it will be copied to *directory*.  If not,
+    the test will be skipped.  Errors during copy are not caught.
+    """
+    shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c'))
+
+
+def _get_xxmodule_path():
+    source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c'
+    return os.path.join(os.path.dirname(__file__), source_name)
+
+
+def fixup_build_ext(cmd):
+    """Function needed to make build_ext tests pass.
+
+    When Python was built with --enable-shared on Unix, -L. is not enough to
+    find libpython.so, because regrtest runs in a tempdir, not in the
+    source directory where the .so lives.
+
+    When Python was built with in debug mode on Windows, build_ext commands
+    need their debug attribute set, and it is not done automatically for
+    some reason.
+
+    This function handles both of these things.  Example use:
+
+        cmd = build_ext(dist)
+        support.fixup_build_ext(cmd)
+        cmd.ensure_finalized()
+
+    Unlike most other Unix platforms, Mac OS X embeds absolute paths
+    to shared libraries into executables, so the fixup is not needed there.
+    """
+    if os.name == 'nt':
+        cmd.debug = sys.executable.endswith('_d.exe')
+    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
+        # To further add to the shared builds fun on Unix, we can't just add
+        # library_dirs to the Extension() instance because that doesn't get
+        # plumbed through to the final compiler command.
+        runshared = sysconfig.get_config_var('RUNSHARED')
+        if runshared is None:
+            cmd.library_dirs = ['.']
+        else:
+            if sys.platform == 'darwin':
+                cmd.library_dirs = []
+            else:
+                name, equals, value = runshared.partition('=')
+                cmd.library_dirs = [d for d in value.split(os.pathsep) if d]
+
+
+def combine_markers(cls):
+    """
+    pytest will honor markers as found on the class, but when
+    markers are on multiple subclasses, only one appears. Use
+    this decorator to combine those markers.
+    """
+    cls.pytestmark = [
+        mark
+        for base in itertools.chain([cls], cls.__bases__)
+        for mark in getattr(base, 'pytestmark', [])
+    ]
+    return cls
diff --git a/shared/package-files/b6/b6453ad9809184b12ae163c0bb29401f2592cd60f9d5496170005582c1c765b8/sym_constrain_range_for_size_compositeexplicitautograd_dispatch.h b/shared/package-files/b6/b6453ad9809184b12ae163c0bb29401f2592cd60f9d5496170005582c1c765b8/sym_constrain_range_for_size_compositeexplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..b62385cffc25d3b9a99643a640c35b527bfc3e8f
--- /dev/null
+++ b/shared/package-files/b6/b6453ad9809184b12ae163c0bb29401f2592cd60f9d5496170005582c1c765b8/sym_constrain_range_for_size_compositeexplicitautograd_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautograd {
+
+TORCH_API void sym_constrain_range_for_size(const at::Scalar & size, ::std::optional min=::std::nullopt, ::std::optional max=::std::nullopt);
+
+} // namespace compositeexplicitautograd
+} // namespace at
diff --git a/shared/package-files/b6/b6554b55dd4b7fb0ece0e3d4a043c425f1fa2213a9cf3167c3b4b26b44f9f279/unfold_backward_native.h b/shared/package-files/b6/b6554b55dd4b7fb0ece0e3d4a043c425f1fa2213a9cf3167c3b4b26b44f9f279/unfold_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..c0f54ba6f4458e7d5171d53431f2da54147d70f6
--- /dev/null
+++ b/shared/package-files/b6/b6554b55dd4b7fb0ece0e3d4a043c425f1fa2213a9cf3167c3b4b26b44f9f279/unfold_backward_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & unfold_backward_out_symint(const at::Tensor & grad_in, c10::SymIntArrayRef input_sizes, int64_t dim, int64_t size, int64_t step, at::Tensor & out);
+TORCH_API at::Tensor unfold_backward(const at::Tensor & grad_in, at::IntArrayRef input_sizes, int64_t dim, int64_t size, int64_t step);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b6/b6580b503231f8b5c912603b09b7a314bc756d63f7519a2e67dbfd319ff8642b/PackedParams.h b/shared/package-files/b6/b6580b503231f8b5c912603b09b7a314bc756d63f7519a2e67dbfd319ff8642b/PackedParams.h
new file mode 100644
index 0000000000000000000000000000000000000000..d73bc0adbc4ef953e0580585ab9261700374a45d
--- /dev/null
+++ b/shared/package-files/b6/b6580b503231f8b5c912603b09b7a314bc756d63f7519a2e67dbfd319ff8642b/PackedParams.h
@@ -0,0 +1,147 @@
+#pragma once
+
+#include 
+#include 
+
+struct LinearPackedParamsBase : public torch::jit::CustomClassHolder {
+  virtual at::Tensor apply(
+      at::Tensor input,
+      double output_scale,
+      int64_t output_zero_point) = 0;
+  virtual at::Tensor apply_relu(
+      at::Tensor input,
+      double output_scale,
+      int64_t output_zero_point) = 0;
+
+  // out variant of LinearPackedParamsBase::apply
+  virtual at::Tensor& apply_out(
+      const at::Tensor& /*input*/,
+      double /*output_scale*/,
+      int64_t /*output_zero_point*/,
+      at::Tensor& output) {
+    throw std::runtime_error(
+        "apply_out is not implemented for this packed "
+        "parameter type");
+    return output;
+  }
+
+  virtual at::Tensor& apply_relu_out(
+      const at::Tensor& /*input*/,
+      double /*output_scale*/,
+      int64_t /*output_zero_point*/,
+      at::Tensor& output) {
+    throw std::runtime_error(
+        "apply_relu_out is not implemented for this packed "
+        "parameter type");
+    return output;
+  }
+
+  // Corresponding pattern (the ops with `*` are part of the pattern that
+  // represents the computation of quantized::linear_with_input_q_dq_qweight_dq_output_fp32):
+  // input -> q* -> dq* -> linear* ->
+  //         qweight -> dq* /
+  //
+  // After fusion:
+  // input -> quantized::linear_with_input_q_dq_qweight_dq_output_fp32* ->
+  //         qweight /
+  //
+  // Additional Note: the weight is packed as well
+  // Params:
+  //    X: float32 Tensor, will be quantized to quint8 in the op
+  //    W_prepack: packed qint8 quantized weight and bias
+  // Returns:
+  //    Y: float32 Tensor
+  virtual at::Tensor apply_with_input_q_dq_qweight_dq_output_fp32(
+      at::Tensor input,
+      double input_scale,
+      int64_t input_zero_point) {
+    throw std::runtime_error(
+        "apply_with_input_q_dq_qweight_dq_output_fp32 is not implemented for this packed "
+        "parameter type");
+    return {};
+  }
+
+  // Corresponding pattern (the ops with `*` are part of the pattern that
+  // represents the computation of quantized::linear_with_input_q_dq_qweight_dq_relu_output_fp32):
+  // input -> q* -> dq* -> linear* -> relu* ->
+  //         qweight -> dq* /
+  //
+  // After fusion:
+  // input -> quantized::linear_with_input_q_dq_qweight_dq_relu_output_fp32* ->
+  //         qweight /
+  //
+  // Additional Note: the weight is packed as well
+  // Params:
+  //    input: float32 Tensor, will be quantized to quint8 in the op
+  // Returns:
+  //    float32 Tensor
+  virtual at::Tensor apply_with_input_q_dq_qweight_dq_relu_output_fp32(
+      at::Tensor input,
+      double input_scale,
+      int64_t input_zero_point) {
+    throw std::runtime_error(
+        "apply_with_input_q_dq_qweight_dq_relu_output_fp32 is not implemented for this packed "
+        "parameter type");
+    return {};
+  }
+
+  virtual at::Tensor apply_dynamic(
+      at::Tensor input,
+      bool reduce_range = false) = 0;
+  virtual at::Tensor apply_dynamic_relu(
+      at::Tensor input,
+      bool reduce_range = false) = 0;
+
+  virtual at::Tensor& apply_dynamic_out(
+      const at::Tensor& /* input */,
+      at::Tensor& output,
+      bool /* reduce_range */) {
+    throw std::runtime_error(
+        "apply_dynamic_out is not implemented for this packed "
+        "parameter type");
+    return output;
+  }
+  virtual at::Tensor& apply_dynamic_relu_out(
+      const at::Tensor& /* input */,
+      at::Tensor& output,
+      bool /* reduce_range */) {
+    throw std::runtime_error(
+        "apply_dynamic_relu_out is not implemented for this packed "
+        "parameter type");
+    return output;
+  }
+
+  virtual std::tuple> unpack() = 0;
+
+  virtual std::optional bias() = 0;
+
+  virtual void set_bias(std::optional /*bias*/) {
+    throw std::runtime_error(
+        "set_bias is not implemented for this packed "
+        "parameter type");
+  }
+};
+
+template 
+struct ConvPackedParamsBase : public torch::jit::CustomClassHolder {
+  virtual at::Tensor apply(
+      const at::Tensor& input,
+      double output_scale,
+      int64_t output_zero_point) = 0;
+  virtual at::Tensor apply_relu(
+      const at::Tensor& input,
+      double output_scale,
+      int64_t output_zero_point) = 0;
+  virtual at::Tensor apply_dynamic(
+      const at::Tensor& input,
+      bool reduce_range) = 0;
+
+  virtual std::tuple> unpack() = 0;
+
+  virtual torch::List stride() const = 0;
+  virtual torch::List padding() const = 0;
+  virtual torch::List output_padding() const = 0;
+  virtual torch::List dilation() const = 0;
+  virtual int64_t groups() const = 0;
+  virtual bool transpose() const = 0;
+};
diff --git a/shared/package-files/b6/b65c385654e6bded3a48103b9b0c8620771e31da9ea7fd657f71440f1260b5fb/isnan_native.h b/shared/package-files/b6/b65c385654e6bded3a48103b9b0c8620771e31da9ea7fd657f71440f1260b5fb/isnan_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..dfc36c34a4abdba03c40c3685b067083937e95e1
--- /dev/null
+++ b/shared/package-files/b6/b65c385654e6bded3a48103b9b0c8620771e31da9ea7fd657f71440f1260b5fb/isnan_native.h
@@ -0,0 +1,25 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & isnan_out(const at::Tensor & self, at::Tensor & out);
+TORCH_API at::Tensor isnan(const at::Tensor & self);
+TORCH_API at::Tensor NestedTensor_isnan(const at::Tensor & self);
+TORCH_API at::Tensor isnan_sparse(const at::Tensor & self);
+TORCH_API at::Tensor isnan_sparse_csr(const at::Tensor & self);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b6/b65f6115e95d676570a8a2570266df55811640bea48be37bf2101d03722dee79/__init__.cpython-311.pyc b/shared/package-files/b6/b65f6115e95d676570a8a2570266df55811640bea48be37bf2101d03722dee79/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a43e13c11b8df25dd7f2ae394ae02a24fd3ba3b
Binary files /dev/null and b/shared/package-files/b6/b65f6115e95d676570a8a2570266df55811640bea48be37bf2101d03722dee79/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b666ce7469674cdc696ff4668624e13e25ca7df524a6f95a1eff1d749ad3472a/percolator.cpython-311.pyc b/shared/package-files/b6/b666ce7469674cdc696ff4668624e13e25ca7df524a6f95a1eff1d749ad3472a/percolator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afb4cb7888d514afe40490bc9f1ae3e62b18e83a
Binary files /dev/null and b/shared/package-files/b6/b666ce7469674cdc696ff4668624e13e25ca7df524a6f95a1eff1d749ad3472a/percolator.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b667a73bdf0ed845df74182840e6bb043984cd2b379d4ed7773cdecab214f367/pattern_utils.cpython-311.pyc b/shared/package-files/b6/b667a73bdf0ed845df74182840e6bb043984cd2b379d4ed7773cdecab214f367/pattern_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ea9a9f47b19911dd88604fbd519d9fc5a518375
Binary files /dev/null and b/shared/package-files/b6/b667a73bdf0ed845df74182840e6bb043984cd2b379d4ed7773cdecab214f367/pattern_utils.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b66a3983126085294f844f39cfdcc3696f30188de395aac2fafcc303d0257188/libcalignmentfile.pyi b/shared/package-files/b6/b66a3983126085294f844f39cfdcc3696f30188de395aac2fafcc303d0257188/libcalignmentfile.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6f106af9b7bd6d54fdbad4733c9b46f3e623e6ce
--- /dev/null
+++ b/shared/package-files/b6/b66a3983126085294f844f39cfdcc3696f30188de395aac2fafcc303d0257188/libcalignmentfile.pyi
@@ -0,0 +1,241 @@
+import array
+import sys
+from typing import (
+    Any,
+    Dict,
+    Type,
+    NamedTuple,
+    Tuple,
+    Optional,
+    Sequence,
+    Union,
+    Callable,
+    List,
+    Iterable,
+)
+
+if sys.version_info < (3, 8):
+    from typing_extensions import Literal
+else:
+    from typing import Literal
+
+from pysam.libchtslib import HTSFile, _HasFileNo
+from pysam.libcalignedsegment import AlignedSegment, PileupColumn
+from pysam.libcfaidx import FastaFile
+
+class IndexStats(NamedTuple):
+    contig: str
+    mapped: int
+    unmapped: int
+    total: int
+
+VALID_HEADER_TYPES: Dict[str, Type]
+VALID_HEADERS: Tuple[str]
+KNOWN_HEADER_FIELDS: Dict[str, Dict[str, Type]]
+VALID_HEADER_ORDER: Dict[str, Tuple[str]]
+
+def build_header_line(fields: Dict[str, str], record: str) -> str: ...
+
+class AlignmentHeader:
+    def __init__(self) -> None: ...
+    @classmethod
+    def _from_text_and_lengths(
+        cls,
+        text: Optional[str],
+        reference_names: Optional[Sequence[str]],
+        reference_lengths: Optional[Sequence[int]],
+    ) -> AlignmentHeader: ...
+    @classmethod
+    def from_text(cls, text: str) -> AlignmentHeader: ...
+    @classmethod
+    def from_dict(cls, header_dict: Dict) -> AlignmentHeader: ...
+    @classmethod
+    def from_references(
+        cls,
+        reference_names: Sequence[str],
+        reference_lengths: Sequence[int],
+        text: Optional[str] = ...,
+        add_sq_text: bool = ...,
+    ) -> AlignmentHeader: ...
+    def __bool__(self) -> bool: ...
+    def copy(self) -> AlignmentHeader: ...
+    @property
+    def nreferences(self) -> int: ...
+    @property
+    def references(self) -> Tuple[str]: ...
+    @property
+    def lengths(self) -> Tuple[int]: ...
+    def to_dict(self) -> Dict: ...
+    def get_reference_name(self, tid: int) -> Optional[str]: ...
+    def get_reference_length(self, reference: str) -> int: ...
+    def is_valid_tid(self, tid: int) -> bool: ...
+    def get_tid(self, reference: str) -> int: ...
+
+# The iterator produced by AlignmentFile is currently itself, but this may
+# change in future and code should not make assumptions about this type.
+AlignmentFileIterator = AlignmentFile
+
+class AlignmentFile(HTSFile):
+    def __init__(
+        self,
+        filename: Union[str, bytes, int, _HasFileNo],
+        mode: Optional[
+            Literal["r", "w", "wh", "rb", "wb", "wbu", "wb0", "rc", "wc"]
+        ] = ...,
+        template: Optional[AlignmentFile] = ...,
+        reference_names: Optional[Sequence[str]] = ...,
+        reference_lengths: Optional[Sequence[int]] = ...,
+        reference_filename: Optional[str] = ...,
+        text: Optional[str] = ...,
+        header: Union[None, Dict, AlignmentHeader] = ...,
+        add_sq_text: bool = ...,
+        add_sam_header: bool = ...,
+        check_sq: bool = ...,
+        index_filename: Optional[str] = ...,
+        filepath_index: Optional[str] = ...,
+        require_index: bool = ...,
+        duplicate_filehandle: bool = ...,
+        ignore_truncation: bool = ...,
+        format_options: Optional[Sequence[str]] = ...,
+        threads: int = ...,
+    ) -> None: ...
+    def has_index(self) -> bool: ...
+    def check_index(self) -> bool: ...
+    def fetch(
+        self,
+        contig: Optional[str] = ...,
+        start: Optional[int] = ...,
+        stop: Optional[int] = ...,
+        region: Optional[str] = ...,
+        tid: Optional[int] = ...,
+        until_eof: bool = ...,
+        multiple_iterators: bool = ...,
+        reference: Optional[str] = ...,
+        end: int = ...,
+    ) -> IteratorRow: ...
+    def head(self, n: int, multiple_iterators: bool = ...) -> IteratorRow: ...
+    def mate(self, read: AlignedSegment) -> AlignedSegment: ...
+    def pileup(
+        self,
+        contig: Optional[str] = ...,
+        start: Optional[int] = ...,
+        stop: Optional[int] = ...,
+        region: Optional[str] = ...,
+        reference: Optional[str] = ...,
+        end: Optional[int] = ...,
+        truncate: bool = ...,
+        max_depth: int = ...,
+        stepper: str = ...,
+        fastafile: Optional[FastaFile] = ...,
+        ignore_overlaps: bool = ...,
+        flag_filter: int = ...,
+        flag_require: int = ...,
+        ignore_orphans: bool = ...,
+        min_base_quality: int = ...,
+        adjust_capq_threshold: int = ...,
+        min_mapping_quality: int = ...,
+        compute_baq: bool = ...,
+        redo_baq: bool = ...,
+    ) -> IteratorColumn: ...
+    def count(
+        self,
+        contig: Optional[str] = ...,
+        start: Optional[int] = ...,
+        stop: Optional[int] = ...,
+        region: Optional[str] = ...,
+        until_eof: bool = ...,
+        read_callback: Union[str, Callable[[AlignedSegment], bool]] = ...,
+        reference: Optional[str] = ...,
+        end: Optional[int] = ...,
+    ) -> int: ...
+    def count_coverage(
+        self,
+        contig: Optional[str] = ...,
+        start: Optional[int] = ...,
+        stop: Optional[int] = ...,
+        region: Optional[str] = ...,
+        quality_threshold: int = ...,
+        read_callback: Union[str, Callable[[AlignedSegment], bool]] = ...,
+        reference: Optional[str] = ...,
+        end: Optional[int] = ...,
+    ) -> Tuple[array.array, array.array, array.array, array.array]: ...
+    def find_introns_slow(
+        self, read_iterator: Iterable[AlignedSegment]
+    ) -> Dict[Tuple[int, int], int]: ...
+    def find_introns(
+        self, read_iterator: Iterable[AlignedSegment]
+    ) -> Dict[Tuple[int, int], int]: ...
+    def close(self) -> None: ...
+    def write(self, read: AlignedSegment) -> int: ...
+    def __enter__(self) -> AlignmentFile: ...
+    def __exit__(self, exc_type, exc_value, traceback): ...
+    @property
+    def mapped(self) -> int: ...
+    @property
+    def unmapped(self) -> int: ...
+    @property
+    def nocoordinate(self) -> int: ...
+    def get_index_statistics(self) -> List[IndexStats]: ...
+    def __iter__(self) -> AlignmentFileIterator: ...
+    def __next__(self) -> AlignedSegment: ...
+    def is_valid_tid(self, tid: int) -> bool: ...
+    def get_tid(self, reference: str) -> int: ...
+    def get_reference_name(self, tid: int) -> str: ...
+    def get_reference_length(self, reference: str) -> int: ...
+    @property
+    def nreferences(self) -> int: ...
+    @property
+    def references(self) -> Tuple[str, ...]: ...
+    @property
+    def lengths(self) -> Tuple[int, ...]: ...
+    @property
+    def reference_filename(self) -> Optional[str]: ...
+    @property
+    def header(self) -> AlignmentHeader: ...
+
+class IteratorRow:
+    def __iter__(self) -> IteratorRow: ...
+    def __next__(self) -> AlignedSegment: ...
+
+class IteratorRowAll(IteratorRow): ...
+class IteratorRowAllRefs(IteratorRow): ...
+class IteratorRowHead(IteratorRow): ...
+class IteratorRowRegion(IteratorRow): ...
+class IteratorRowSelection(IteratorRow): ...
+
+class IteratorColumn:
+    def __iter__(self) -> IteratorColumn: ...
+    def __next__(self) -> PileupColumn: ...
+    @property
+    def seq_len(self) -> int: ...
+    def add_reference(self, fastafile: FastaFile) -> None: ...
+    def has_reference(self) -> bool: ...
+
+class IteratorColumnAll(IteratorColumn): ...
+class IteratorColumnAllRefs(IteratorColumn): ...
+class IteratorColumnRegion(IteratorColumn): ...
+
+class SNPCall:
+    @property
+    def tid(self) -> int: ...
+    @property
+    def pos(self) -> int: ...
+    @property
+    def reference_base(self) -> str: ...
+    @property
+    def genotype(self) -> str: ...
+    @property
+    def consensus_quality(self) -> int: ...
+    @property
+    def snp_quality(self) -> int: ...
+    @property
+    def mapping_quality(self) -> int: ...
+    @property
+    def coverage(self) -> int: ...
+
+class IndexedReads:
+    def __init__(
+        self, samfile: AlignmentFile, multiple_iterators: bool = ...
+    ) -> None: ...
+    def build(self) -> None: ...
+    def find(self, query_name: str) -> IteratorRow: ...
diff --git a/shared/package-files/b6/b66d458c24b40e2c9b95c3ac1159642f51265ac17aa74b29e67c294b7d8b605d/__init__.cpython-311.pyc b/shared/package-files/b6/b66d458c24b40e2c9b95c3ac1159642f51265ac17aa74b29e67c294b7d8b605d/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad8552b205bde42e4cc2979bf97432db97e25372
Binary files /dev/null and b/shared/package-files/b6/b66d458c24b40e2c9b95c3ac1159642f51265ac17aa74b29e67c294b7d8b605d/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b679316af48c95b5c7c0d8b03e2938ec9f0ee2a8cb481972f4c3de1148017c72/__init__.cpython-311.pyc b/shared/package-files/b6/b679316af48c95b5c7c0d8b03e2938ec9f0ee2a8cb481972f4c3de1148017c72/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15e736884d7cbfb8e966d809a94b3754346857ff
Binary files /dev/null and b/shared/package-files/b6/b679316af48c95b5c7c0d8b03e2938ec9f0ee2a8cb481972f4c3de1148017c72/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b67f714db5f3b036118ea2b740998187ae2f340f1e574268195d98009af14e75/test_api.py b/shared/package-files/b6/b67f714db5f3b036118ea2b740998187ae2f340f1e574268195d98009af14e75/test_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7b444045a0f23ea9d7b9ad94a1244b0b320fee6
--- /dev/null
+++ b/shared/package-files/b6/b67f714db5f3b036118ea2b740998187ae2f340f1e574268195d98009af14e75/test_api.py
@@ -0,0 +1,392 @@
+from copy import deepcopy
+import inspect
+import pydoc
+
+import numpy as np
+import pytest
+
+from pandas._config import using_pyarrow_string_dtype
+from pandas._config.config import option_context
+
+import pandas as pd
+from pandas import (
+    DataFrame,
+    Series,
+    date_range,
+    timedelta_range,
+)
+import pandas._testing as tm
+
+
+class TestDataFrameMisc:
+    def test_getitem_pop_assign_name(self, float_frame):
+        s = float_frame["A"]
+        assert s.name == "A"
+
+        s = float_frame.pop("A")
+        assert s.name == "A"
+
+        s = float_frame.loc[:, "B"]
+        assert s.name == "B"
+
+        s2 = s.loc[:]
+        assert s2.name == "B"
+
+    def test_get_axis(self, float_frame):
+        f = float_frame
+        assert f._get_axis_number(0) == 0
+        assert f._get_axis_number(1) == 1
+        assert f._get_axis_number("index") == 0
+        assert f._get_axis_number("rows") == 0
+        assert f._get_axis_number("columns") == 1
+
+        assert f._get_axis_name(0) == "index"
+        assert f._get_axis_name(1) == "columns"
+        assert f._get_axis_name("index") == "index"
+        assert f._get_axis_name("rows") == "index"
+        assert f._get_axis_name("columns") == "columns"
+
+        assert f._get_axis(0) is f.index
+        assert f._get_axis(1) is f.columns
+
+        with pytest.raises(ValueError, match="No axis named"):
+            f._get_axis_number(2)
+
+        with pytest.raises(ValueError, match="No axis.*foo"):
+            f._get_axis_name("foo")
+
+        with pytest.raises(ValueError, match="No axis.*None"):
+            f._get_axis_name(None)
+
+        with pytest.raises(ValueError, match="No axis named"):
+            f._get_axis_number(None)
+
+    def test_column_contains_raises(self, float_frame):
+        with pytest.raises(TypeError, match="unhashable type: 'Index'"):
+            float_frame.columns in float_frame
+
+    def test_tab_completion(self):
+        # DataFrame whose columns are identifiers shall have them in __dir__.
+        df = DataFrame([list("abcd"), list("efgh")], columns=list("ABCD"))
+        for key in list("ABCD"):
+            assert key in dir(df)
+        assert isinstance(df.__getitem__("A"), Series)
+
+        # DataFrame whose first-level columns are identifiers shall have
+        # them in __dir__.
+        df = DataFrame(
+            [list("abcd"), list("efgh")],
+            columns=pd.MultiIndex.from_tuples(list(zip("ABCD", "EFGH"))),
+        )
+        for key in list("ABCD"):
+            assert key in dir(df)
+        for key in list("EFGH"):
+            assert key not in dir(df)
+        assert isinstance(df.__getitem__("A"), DataFrame)
+
+    def test_display_max_dir_items(self):
+        # display.max_dir_items increaes the number of columns that are in __dir__.
+        columns = ["a" + str(i) for i in range(420)]
+        values = [range(420), range(420)]
+        df = DataFrame(values, columns=columns)
+
+        # The default value for display.max_dir_items is 100
+        assert "a99" in dir(df)
+        assert "a100" not in dir(df)
+
+        with option_context("display.max_dir_items", 300):
+            df = DataFrame(values, columns=columns)
+            assert "a299" in dir(df)
+            assert "a300" not in dir(df)
+
+        with option_context("display.max_dir_items", None):
+            df = DataFrame(values, columns=columns)
+            assert "a419" in dir(df)
+
+    def test_not_hashable(self):
+        empty_frame = DataFrame()
+
+        df = DataFrame([1])
+        msg = "unhashable type: 'DataFrame'"
+        with pytest.raises(TypeError, match=msg):
+            hash(df)
+        with pytest.raises(TypeError, match=msg):
+            hash(empty_frame)
+
+    @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="surrogates not allowed")
+    def test_column_name_contains_unicode_surrogate(self):
+        # GH 25509
+        colname = "\ud83d"
+        df = DataFrame({colname: []})
+        # this should not crash
+        assert colname not in dir(df)
+        assert df.columns[0] == colname
+
+    def test_new_empty_index(self):
+        df1 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
+        df2 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
+        df1.index.name = "foo"
+        assert df2.index.name is None
+
+    def test_get_agg_axis(self, float_frame):
+        cols = float_frame._get_agg_axis(0)
+        assert cols is float_frame.columns
+
+        idx = float_frame._get_agg_axis(1)
+        assert idx is float_frame.index
+
+        msg = r"Axis must be 0 or 1 \(got 2\)"
+        with pytest.raises(ValueError, match=msg):
+            float_frame._get_agg_axis(2)
+
+    def test_empty(self, float_frame, float_string_frame):
+        empty_frame = DataFrame()
+        assert empty_frame.empty
+
+        assert not float_frame.empty
+        assert not float_string_frame.empty
+
+        # corner case
+        df = DataFrame({"A": [1.0, 2.0, 3.0], "B": ["a", "b", "c"]}, index=np.arange(3))
+        del df["A"]
+        assert not df.empty
+
+    def test_len(self, float_frame):
+        assert len(float_frame) == len(float_frame.index)
+
+        # single block corner case
+        arr = float_frame[["A", "B"]].values
+        expected = float_frame.reindex(columns=["A", "B"]).values
+        tm.assert_almost_equal(arr, expected)
+
+    def test_axis_aliases(self, float_frame):
+        f = float_frame
+
+        # reg name
+        expected = f.sum(axis=0)
+        result = f.sum(axis="index")
+        tm.assert_series_equal(result, expected)
+
+        expected = f.sum(axis=1)
+        result = f.sum(axis="columns")
+        tm.assert_series_equal(result, expected)
+
+    def test_class_axis(self):
+        # GH 18147
+        # no exception and no empty docstring
+        assert pydoc.getdoc(DataFrame.index)
+        assert pydoc.getdoc(DataFrame.columns)
+
+    def test_series_put_names(self, float_string_frame):
+        series = float_string_frame._series
+        for k, v in series.items():
+            assert v.name == k
+
+    def test_empty_nonzero(self):
+        df = DataFrame([1, 2, 3])
+        assert not df.empty
+        df = DataFrame(index=[1], columns=[1])
+        assert not df.empty
+        df = DataFrame(index=["a", "b"], columns=["c", "d"]).dropna()
+        assert df.empty
+        assert df.T.empty
+
+    @pytest.mark.parametrize(
+        "df",
+        [
+            DataFrame(),
+            DataFrame(index=[1]),
+            DataFrame(columns=[1]),
+            DataFrame({1: []}),
+        ],
+    )
+    def test_empty_like(self, df):
+        assert df.empty
+        assert df.T.empty
+
+    def test_with_datetimelikes(self):
+        df = DataFrame(
+            {
+                "A": date_range("20130101", periods=10),
+                "B": timedelta_range("1 day", periods=10),
+            }
+        )
+        t = df.T
+
+        result = t.dtypes.value_counts()
+        expected = Series({np.dtype("object"): 10}, name="count")
+        tm.assert_series_equal(result, expected)
+
+    def test_deepcopy(self, float_frame):
+        cp = deepcopy(float_frame)
+        cp.loc[0, "A"] = 10
+        assert not float_frame.equals(cp)
+
+    def test_inplace_return_self(self):
+        # GH 1893
+
+        data = DataFrame(
+            {"a": ["foo", "bar", "baz", "qux"], "b": [0, 0, 1, 1], "c": [1, 2, 3, 4]}
+        )
+
+        def _check_f(base, f):
+            result = f(base)
+            assert result is None
+
+        # -----DataFrame-----
+
+        # set_index
+        f = lambda x: x.set_index("a", inplace=True)
+        _check_f(data.copy(), f)
+
+        # reset_index
+        f = lambda x: x.reset_index(inplace=True)
+        _check_f(data.set_index("a"), f)
+
+        # drop_duplicates
+        f = lambda x: x.drop_duplicates(inplace=True)
+        _check_f(data.copy(), f)
+
+        # sort
+        f = lambda x: x.sort_values("b", inplace=True)
+        _check_f(data.copy(), f)
+
+        # sort_index
+        f = lambda x: x.sort_index(inplace=True)
+        _check_f(data.copy(), f)
+
+        # fillna
+        f = lambda x: x.fillna(0, inplace=True)
+        _check_f(data.copy(), f)
+
+        # replace
+        f = lambda x: x.replace(1, 0, inplace=True)
+        _check_f(data.copy(), f)
+
+        # rename
+        f = lambda x: x.rename({1: "foo"}, inplace=True)
+        _check_f(data.copy(), f)
+
+        # -----Series-----
+        d = data.copy()["c"]
+
+        # reset_index
+        f = lambda x: x.reset_index(inplace=True, drop=True)
+        _check_f(data.set_index("a")["c"], f)
+
+        # fillna
+        f = lambda x: x.fillna(0, inplace=True)
+        _check_f(d.copy(), f)
+
+        # replace
+        f = lambda x: x.replace(1, 0, inplace=True)
+        _check_f(d.copy(), f)
+
+        # rename
+        f = lambda x: x.rename({1: "foo"}, inplace=True)
+        _check_f(d.copy(), f)
+
+    def test_tab_complete_warning(self, ip, frame_or_series):
+        # GH 16409
+        pytest.importorskip("IPython", minversion="6.0.0")
+        from IPython.core.completer import provisionalcompleter
+
+        if frame_or_series is DataFrame:
+            code = "from pandas import DataFrame; obj = DataFrame()"
+        else:
+            code = "from pandas import Series; obj = Series(dtype=object)"
+
+        ip.run_cell(code)
+        # GH 31324 newer jedi version raises Deprecation warning;
+        #  appears resolved 2021-02-02
+        with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
+            with provisionalcompleter("ignore"):
+                list(ip.Completer.completions("obj.", 1))
+
+    def test_attrs(self):
+        df = DataFrame({"A": [2, 3]})
+        assert df.attrs == {}
+        df.attrs["version"] = 1
+
+        result = df.rename(columns=str)
+        assert result.attrs == {"version": 1}
+
+    def test_attrs_deepcopy(self):
+        df = DataFrame({"A": [2, 3]})
+        assert df.attrs == {}
+        df.attrs["tags"] = {"spam", "ham"}
+
+        result = df.rename(columns=str)
+        assert result.attrs == df.attrs
+        assert result.attrs["tags"] is not df.attrs["tags"]
+
+    @pytest.mark.parametrize("allows_duplicate_labels", [True, False, None])
+    def test_set_flags(
+        self,
+        allows_duplicate_labels,
+        frame_or_series,
+        using_copy_on_write,
+        warn_copy_on_write,
+    ):
+        obj = DataFrame({"A": [1, 2]})
+        key = (0, 0)
+        if frame_or_series is Series:
+            obj = obj["A"]
+            key = 0
+
+        result = obj.set_flags(allows_duplicate_labels=allows_duplicate_labels)
+
+        if allows_duplicate_labels is None:
+            # We don't update when it's not provided
+            assert result.flags.allows_duplicate_labels is True
+        else:
+            assert result.flags.allows_duplicate_labels is allows_duplicate_labels
+
+        # We made a copy
+        assert obj is not result
+
+        # We didn't mutate obj
+        assert obj.flags.allows_duplicate_labels is True
+
+        # But we didn't copy data
+        if frame_or_series is Series:
+            assert np.may_share_memory(obj.values, result.values)
+        else:
+            assert np.may_share_memory(obj["A"].values, result["A"].values)
+
+        with tm.assert_cow_warning(warn_copy_on_write):
+            result.iloc[key] = 0
+        if using_copy_on_write:
+            assert obj.iloc[key] == 1
+        else:
+            assert obj.iloc[key] == 0
+            # set back to 1 for test below
+            with tm.assert_cow_warning(warn_copy_on_write):
+                result.iloc[key] = 1
+
+        # Now we do copy.
+        result = obj.set_flags(
+            copy=True, allows_duplicate_labels=allows_duplicate_labels
+        )
+        result.iloc[key] = 10
+        assert obj.iloc[key] == 1
+
+    def test_constructor_expanddim(self):
+        # GH#33628 accessing _constructor_expanddim should not raise NotImplementedError
+        # GH38782 pandas has no container higher than DataFrame (two-dim), so
+        # DataFrame._constructor_expand_dim, doesn't make sense, so is removed.
+        df = DataFrame()
+
+        msg = "'DataFrame' object has no attribute '_constructor_expanddim'"
+        with pytest.raises(AttributeError, match=msg):
+            df._constructor_expanddim(np.arange(27).reshape(3, 3, 3))
+
+    def test_inspect_getmembers(self):
+        # GH38740
+        pytest.importorskip("jinja2")
+        df = DataFrame()
+        msg = "DataFrame._data is deprecated"
+        with tm.assert_produces_warning(
+            DeprecationWarning, match=msg, check_stacklevel=False
+        ):
+            inspect.getmembers(df)
diff --git a/shared/package-files/b6/b68123bf4e55113968cb9ffb0265735c1a51d61d860a28357db98274382598be/Math.h b/shared/package-files/b6/b68123bf4e55113968cb9ffb0265735c1a51d61d860a28357db98274382598be/Math.h
new file mode 100644
index 0000000000000000000000000000000000000000..47c0a2be030311a603b2b9675cb109ef0947c1bf
--- /dev/null
+++ b/shared/package-files/b6/b68123bf4e55113968cb9ffb0265735c1a51d61d860a28357db98274382598be/Math.h
@@ -0,0 +1,3927 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+C10_CLANG_DIAGNOSTIC_PUSH()
+#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion")
+C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion")
+#endif
+
+/* The next function is taken from  https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c.
+Below is the copyright.
+Output was modified to be inf or -inf when input is 1 or -1. */
+
+
+/*
+    Copyright (c) 2014 Indiana University
+    All rights reserved.
+
+    Written by Prof. Gary L. Pavlis, Dept. of Geol. Sci.,
+            Indiana University, Bloomington, IN
+
+    This software is licensed under the New BSD license:
+
+    Redistribution and use in source and binary forms,
+    with or without modification, are permitted provided
+    that the following conditions are met:
+
+    Redistributions of source code must retain the above
+    copyright notice, this list of conditions and the
+    following disclaimer.
+
+    Redistributions in binary form must reproduce the
+    above copyright notice, this list of conditions and
+    the following disclaimer in the documentation and/or
+    other materials provided with the distribution.
+
+    Neither the name of Indiana University nor
+    the names of its contributors may be used to endorse
+    or promote products derived from this software without
+    specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+    CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+    THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+    USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
+    IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+    USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+    POSSIBILITY OF SUCH DAMAGE.
+*/
+
+namespace {
+/*
+ * This function is derived from the implementation of the i0e function in the
+ * Cephes Math Library. See note [3-Clause BSD License for the Cephes Math
+ * Library].
+ *
+ * Computes an approximation of the exponentially scaled zeroth order modified
+ * Bessel function of the first kind. The approximation is actually two
+ * (sub)approximations, both using a Chebyshev polynomial expansion. One
+ * approximates the function over [0, 8], and the other over (8, infinity). This
+ * function takes the absolute value of all inputs to convert them into the
+ * domain of the approximation.
+ */
+jiterator_also_stringify_as(jiterator_code(
+  template 
+  JITERATOR_HOST_DEVICE T chbevl(T x, const T array[], const int len) {
+    T b0, b1, b2;
+
+    b0 = array[0];
+    b1 = 0;
+
+    for (int i = 1; i < len; ++i) {
+      b2 = b1;
+      b1 = b0;
+      b0 = x * b1 - b2 + array[i];
+    }
+
+    return T{0.5} * (b0 - b2);
+  }
+
+  template 
+  JITERATOR_HOST_DEVICE T calc_i0e(T _x) {
+    T x = std::fabs(_x);
+
+    if (x <= T{8.0}) {
+      static const T coefficients[] = {
+          -4.41534164647933937950E-18, 3.33079451882223809783E-17,
+          -2.43127984654795469359E-16, 1.71539128555513303061E-15,
+          -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+          -4.85644678311192946090E-13, 2.95505266312963983461E-12,
+          -1.72682629144155570723E-11, 9.67580903537323691224E-11,
+          -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+          -1.30002500998624804212E-8,  6.04699502254191894932E-8,
+          -2.67079385394061173391E-7,  1.11738753912010371815E-6,
+          -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+          -5.75419501008210370398E-5,  1.88502885095841655729E-4,
+          -5.76375574538582365885E-4,  1.63947561694133579842E-3,
+          -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+          -2.37374148058994688156E-2,  4.93052842396707084878E-2,
+          -9.49010970480476444210E-2,  1.71620901522208775349E-1,
+          -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+
+      T y = (x / T{2.0}) - T{2.0};
+      return chbevl(y, coefficients, int{30});
+    }
+
+    // x > 8
+    static const T coefficients[] = {
+        -7.23318048787475395456E-18, -4.83050448594418207126E-18,
+        4.46562142029675999901E-17,  3.46122286769746109310E-17,
+        -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+        1.77256013305652638360E-15,  3.81168066935262242075E-15,
+        -9.55484669882830764870E-15, -4.15056934728722208663E-14,
+        1.54008621752140982691E-14,  3.85277838274214270114E-13,
+        7.18012445138366623367E-13,  -1.79417853150680611778E-12,
+        -1.32158118404477131188E-11, -3.14991652796324136454E-11,
+        1.18891471078464383424E-11,  4.94060238822496958910E-10,
+        3.39623202570838634515E-9,   2.26666899049817806459E-8,
+        2.04891858946906374183E-7,   2.89137052083475648297E-6,
+        6.88975834691682398426E-5,   3.36911647825569408990E-3,
+        8.04490411014108831608E-1};
+
+    return chbevl(T{32.0} / x - T{2.0}, coefficients, int{25}) / std::sqrt(x);
+  }),
+  i0e_string) // i0e_string
+}
+
+#define CENTRAL_RANGE 0.7
+
+template 
+inline typename std::enable_if_t, T>
+calc_erfinv(T y) {
+/* Function to calculate inverse error function.  Rational approximation
+is used to generate an initial approximation, which is then improved to
+full accuracy by two steps of Newton's method.  Code is a direct
+translation of the erfinv m file in matlab version 2.0.
+Author:  Gary L. Pavlis, Indiana University
+Date:  February 1996
+*/
+  T x, z, num, dem; /*working variables */
+  /* coefficients in rational expansion */
+  T a[4] = {  T(0.886226899), T(-1.645349621),  T(0.914624893), T(-0.140543331) };
+  T b[4] = { T(-2.118377725),  T(1.442710462), T(-0.329097515),  T(0.012229801) };
+  T c[4] = { T(-1.970840454), T(-1.624906493),  T(3.429567803),  T(1.641345311) };
+  T d[2] = {  T(3.543889200),  T(1.637067800) };
+  T y_abs = std::abs(y);
+  if(y_abs > 1.0) return std::numeric_limits::quiet_NaN();
+#ifdef _WIN32
+  // error C2039: '_copysign': is not a member of 'std'
+  if(y_abs == 1.0) return copysign(std::numeric_limits::infinity(), y);
+#else
+  if(y_abs == 1.0) return std::copysign(std::numeric_limits::infinity(), y);
+#endif
+  if(y_abs <= static_cast(CENTRAL_RANGE)) {
+    z = y * y;
+    num = (((a[3]*z + a[2])*z + a[1])*z + a[0]);
+    dem = ((((b[3]*z + b[2])*z + b[1])*z +b[0]) * z + static_cast(1.0));
+    x = y * num / dem;
+  }
+  else{
+    z = std::sqrt(-std::log((static_cast(1.0)-y_abs)/static_cast(2.0)));
+    num = ((c[3]*z + c[2])*z + c[1]) * z + c[0];
+    dem = (d[1]*z + d[0])*z + static_cast(1.0);
+#ifdef _WIN32
+    // error C2039: '_copysign': is not a member of 'std'
+    x = copysign(num, y) / dem;
+#else
+    x = std::copysign(num, y) / dem;
+#endif
+  }
+  /* Two steps of Newton-Raphson correction */
+  x = x - (std::erf(x) - y) / ((static_cast(2.0)/static_cast(std::sqrt(c10::pi)))*std::exp(-x*x));
+  x = x - (std::erf(x) - y) / ((static_cast(2.0)/static_cast(std::sqrt(c10::pi)))*std::exp(-x*x));
+
+  return(x);
+}
+
+#undef CENTRAL_RANGE
+
+/*
+ * Note [3-Clause BSD License for the Cephes Math Library]
+ * Code derived from implementations in the Cephes Math Library should mention its derivation and reference
+ * this note (ex. 'This function is derived from the implementation of X in the Cephes Math Library. See note
+ * [3-Clause BSD License for the Cephes Math Library]. The license is:
+ * Copyright (c) 2018, Steven Moshier
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of the nor the
+ * names of its contributors may be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL Steven Moshier BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This function is derived from the implementation of the zeta function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ */
+template 
+C10_HOST_DEVICE inline scalar_t zeta(scalar_t x, scalar_t q) __ubsan_ignore_float_divide_by_zero__ {
+  using acc_t = at::acc_type;
+  const acc_t MACHEP = acc_t{1.11022302462515654042E-16};
+  constexpr acc_t zero = acc_t{0.0};
+  constexpr acc_t half = acc_t{0.5};
+  constexpr acc_t one = acc_t{1.0};
+  static const acc_t A[] = {
+      12.0,
+      -720.0,
+      30240.0,
+      -1209600.0,
+      47900160.0,
+      -1.8924375803183791606e9, /*1.307674368e12/691*/
+      7.47242496e10,
+      -2.950130727918164224e12, /*1.067062284288e16/3617*/
+      1.1646782814350067249e14, /*5.109094217170944e18/43867*/
+      -4.5979787224074726105e15, /*8.028576626982912e20/174611*/
+      1.8152105401943546773e17, /*1.5511210043330985984e23/854513*/
+      -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091*/
+  };
+
+  acc_t a, b, k, s, t, w;
+  if (x == one) {
+    return std::numeric_limits::infinity();
+  }
+
+  if (x < one) {
+    return std::numeric_limits::quiet_NaN();
+  }
+
+  if (q <= zero) {
+    if (q == std::floor(q)) {
+      return std::numeric_limits::infinity();
+    }
+    if (x != std::floor(x)) {
+      return std::numeric_limits::quiet_NaN();
+    }
+  }
+
+  s = std::pow(q, -x);
+  a = q;
+  int i = 0;
+  b = zero;
+  while ((i < 9) || (a <= acc_t{9.0})) {
+    i += 1;
+    a += one;
+    b = ::pow(a, -x);
+    s += b;
+    if ((-MACHEP * s < b) && (b < MACHEP * s)) {
+      return static_cast(s);
+    }
+  };
+
+  w = a;
+  s += b * w / (x - one);
+  s -= half * b;
+  a = one;
+  k = zero;
+  for (i = 0; i < 12; i++) {
+    a *= x + k;
+    b /= w;
+    t = a * b / A[i];
+    s = s + t;
+    t = ::fabs(t / s);
+    if (t < MACHEP) {
+      return static_cast(s);
+    }
+    k += one;
+    a *= x + k;
+    b /= w;
+    k += one;
+  }
+  return static_cast(s);
+}
+
+/*
+ * This function is derived from the implementation of the digamma function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Evaluates polynomial of degree N:
+ *
+ *                     2          N
+ * y  =  C  + C x + C x  +...+ C x
+ *        0    1     2          N
+ *
+ * Coefficients are stored in reverse order:
+ *
+ * coef[0] = C  , ..., coef[N] = C  .
+ *            N                   0
+ */
+template 
+C10_HOST_DEVICE inline T polevl(const T x, const T A[], size_t len) {
+  T result = 0;
+  for (size_t i = 0; i <= len; i++) {
+    result = result * x + A[i];
+  }
+  return result;
+}
+
+inline double trigamma(double x) __ubsan_ignore_float_divide_by_zero__ {
+  double sign = +1;
+  double result = 0;
+  if (x < 0.5) {
+    sign = -1;
+    const double sin_pi_x = sin(c10::pi * x);
+    result -= (c10::pi * c10::pi) / (sin_pi_x * sin_pi_x);
+    x = 1 - x;
+  }
+  for (int i = 0; i < 6; ++i) {
+    result += 1 / (x * x);
+    x += 1;
+  }
+  const double ixx = 1 / (x*x);
+  result += (1 + 1 / (2*x) + ixx * (1./6 - ixx * (1./30 - ixx * (1./42)))) / x;
+  return sign * result;
+}
+
+inline float trigamma(float x) __ubsan_ignore_float_divide_by_zero__ {
+  float sign = +1;
+  float result = 0;
+  if (x < 0.5f) {
+    sign = -1;
+    const float sin_pi_x = sinf(c10::pi * x);
+    result -= (c10::pi * c10::pi) / (sin_pi_x * sin_pi_x);
+    x = 1 - x;
+  }
+  for (int i = 0; i < 6; ++i) {
+    result += 1 / (x * x);
+    x += 1;
+  }
+  const float ixx = 1 / (x*x);
+  result += (1 + 1 / (2*x) + ixx * (1.f/6 - ixx * (1.f/30 - ixx * (1.f/42)))) / x;
+  return sign * result;
+}
+
+/*
+ * This function is derived from the implementation of the digamma function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ */
+inline double calc_digamma(double x) {
+  // [C++ Standard Reference: Gamma Function] https://en.cppreference.com/w/cpp/numeric/math/tgamma
+  static double PSI_10 = 2.25175258906672110764;
+  if (x == 0) {
+    // As per C++ standard for gamma related functions and SciPy,
+    // If the argument is ±0, ±∞ is returned
+    return std::copysign(INFINITY, -x);
+  }
+
+  bool x_is_integer = x == trunc(x);
+  if (x < 0) {
+    if (x_is_integer) {
+      // As per C++ standard for gamma related functions and SciPy,
+      // If the argument is a negative integer, NaN is returned
+      return std::numeric_limits::quiet_NaN();
+    }
+    // Extracts the fractional part of x as r, since tan(pi * r) is more numerically
+    // accurate than tan(pi * x). While these operations are mathematically equivalent
+    // since both x and r are in radians and tan() has a periodicity of pi, in practice
+    // the computation of pi * x is a source of error (when |x| > 1).
+    double q, r;
+    r = std::modf(x, &q);
+    return calc_digamma(1 - x) - c10::pi / tan(c10::pi * r);
+  }
+
+  // Push x to be >= 10
+  double result = 0;
+  while (x < 10) {
+    result -= 1 / x;
+    x += 1;
+  }
+  if (x == 10) {
+    return result + PSI_10;
+  }
+
+  // Compute asymptotic digamma
+  static const double A[] = {
+      8.33333333333333333333E-2,
+      -2.10927960927960927961E-2,
+      7.57575757575757575758E-3,
+      -4.16666666666666666667E-3,
+      3.96825396825396825397E-3,
+      -8.33333333333333333333E-3,
+      8.33333333333333333333E-2,
+  };
+
+  double y = 0;
+  if (x < 1.0e17) {
+    double z = 1.0 / (x * x);
+    y = z * polevl(z, A, 6);
+  }
+  return result + log(x) - (0.5 / x) - y;
+}
+
+/*
+ * This function is derived from the implementation of the digamma function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ */
+inline float calc_digamma(float x) {
+  // See [C++ Standard Reference: Gamma Function]
+  static float PSI_10 = 2.25175258906672110764f;
+  if (x == 0) {
+    // As per C++ standard for gamma related functions and SciPy,
+    // If the argument is ±0, ±∞ is returned
+    return std::copysign(INFINITY, -x);
+  }
+
+  bool x_is_integer = x == truncf(x);
+  if (x < 0) {
+    if (x_is_integer) {
+    // As per C++ standard for gamma related functions and SciPy,
+    // If the argument is a negative integer, NaN is returned
+      return std::numeric_limits::quiet_NaN();
+    }
+    // Extracts the fractional part of x as r, since tan(pi * r) is more numerically
+    // accurate than tan(pi * x). While these operations are mathematically equivalent
+    // since both x and r are in radians and tan() has a periodicity of pi, in practice
+    // the computation of pi * x is a source of error (when |x| > 1).
+    double q, r;
+    r = std::modf(x, &q);
+    float pi_over_tan_pi_x = (float)(c10::pi / tan(c10::pi * r));
+    return calc_digamma(1 - x) - pi_over_tan_pi_x;
+  }
+
+  // Push x to be >= 10
+  float result = 0;
+  while (x < 10) {
+    result -= 1 / x;
+    x += 1;
+  }
+  if (x == 10) {
+    return result + PSI_10;
+  }
+
+  // Compute asymptotic digamma
+  static const float A[] = {
+      8.33333333333333333333E-2f,
+      -2.10927960927960927961E-2f,
+      7.57575757575757575758E-3f,
+      -4.16666666666666666667E-3f,
+      3.96825396825396825397E-3f,
+      -8.33333333333333333333E-3f,
+      8.33333333333333333333E-2f,
+  };
+
+  float y = 0;
+  if (x < 1.0e17f) {
+    float z = 1 / (x * x);
+    y = z * polevl(z, A, 6);
+  }
+  return result + logf(x) - (0.5f / x) - y;
+}
+
+inline c10::BFloat16 calc_digamma(c10::BFloat16 a) {
+  return calc_digamma(static_cast(a));
+}
+
+inline c10::Half calc_digamma(c10::Half a) {
+  return calc_digamma(static_cast(a));
+}
+
+template 
+inline C10_HOST_DEVICE scalar_t calc_polygamma(scalar_t x, int n) {
+  // already blocked if n <= 1
+  const auto one = scalar_t{1};
+  return ((n % 2) ? one : -one) *
+      std::exp(std::lgamma(static_cast(n) + one)) *
+      zeta(static_cast(n + 1), x);
+}
+
+// regularized lower incomplete gamma
+// the regularized lower, upper incomplete gamma, as well as their
+// helper functions follow SciPy's implementation
+
+/* References
+ * [igam1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ * [igam2] Maddock et al., "Incomplete Gamma Functions",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html
+ */
+
+/*
+ * This implementation of the regularized incomplete gamma functions and
+ * their helper functions are derived from the implementation of SciPy's
+ * gammainc, Cephes's igam and igamc, and Boost's Lanczos approximations.
+ * See NOTICE for the licenses.
+ */
+template 
+scalar_t ratevl(scalar_t x, const scalar_t num[], int64_t M,
+    const scalar_t denom[], int64_t N) {
+  // evaluating rational function, i.e., the ratio of two polynomials
+  // the coefficients for numerator are given by `num` while coeffs for
+  // denumerator are given by `denom`
+
+  int64_t i, dir;
+  scalar_t y, num_ans, denom_ans;
+  scalar_t absx = std::fabs(x);
+  const scalar_t *p;
+
+  if (absx > 1) {
+    /* Evaluate as a polynomial in 1/x. */
+    dir = -1;
+    p = num + M;
+    y = 1 / x;
+  }
+  else {
+    dir = 1;
+    p = num;
+    y = x;
+  }
+
+  /* Evaluate the numerator */
+  num_ans = *p;
+  p += dir;
+  for (i = 1; i <= M; i++) {
+    num_ans = num_ans * y + *p;
+    p += dir;
+  }
+  /* Evaluate the denominator */
+  if (absx > 1) {
+    p = denom + N;
+  }
+  else {
+    p = denom;
+  }
+
+  denom_ans = *p;
+  p += dir;
+  for (i = 1; i <= N; i++) {
+    denom_ans = denom_ans * y + *p;
+    p += dir;
+  }
+  if (absx > 1) {
+    i = N - M;
+    return std::pow(x, i) * num_ans / denom_ans;
+  }
+  else {
+    return num_ans / denom_ans;
+  }
+}
+
+// SciPy's lanczos implementation is taken from Boost
+/* (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. See
+ * https://www.boost.org/LICENSE_1_0.txt or see NOTICE.
+ */
+template 
+static scalar_t lanczos_sum_expg_scaled(scalar_t x) {
+  // lanczos approximation
+  static const scalar_t lanczos_sum_expg_scaled_num[13] = {
+    0.006061842346248906525783753964555936883222,
+    0.5098416655656676188125178644804694509993,
+    19.51992788247617482847860966235652136208,
+    449.9445569063168119446858607650988409623,
+    6955.999602515376140356310115515198987526,
+    75999.29304014542649875303443598909137092,
+    601859.6171681098786670226533699352302507,
+    3481712.15498064590882071018964774556468,
+    14605578.08768506808414169982791359218571,
+    43338889.32467613834773723740590533316085,
+    86363131.28813859145546927288977868422342,
+    103794043.1163445451906271053616070238554,
+    56906521.91347156388090791033559122686859
+  };
+  static const scalar_t lanczos_sum_expg_scaled_denom[13] = {
+    1.,
+    66.,
+    1925.,
+    32670.,
+    357423.,
+    2637558.,
+    13339535.,
+    45995730.,
+    105258076.,
+    150917976.,
+    120543840.,
+    39916800.,
+    0.
+  };
+  return ratevl(x, lanczos_sum_expg_scaled_num,
+      sizeof(lanczos_sum_expg_scaled_num) / sizeof(lanczos_sum_expg_scaled_num[0]) - 1,
+      lanczos_sum_expg_scaled_denom,
+      sizeof(lanczos_sum_expg_scaled_denom) / sizeof(lanczos_sum_expg_scaled_denom[0]) - 1);
+}
+
+template 
+static scalar_t _igam_helper_fac(scalar_t a, scalar_t x) {
+  // compute x^a * exp(-a) / gamma(a)
+  // corrected from (15) and (16) in [igam2] by replacing exp(x - a) with
+  // exp(a - x).
+
+  scalar_t ax, fac, res, num, numfac;
+  static scalar_t MAXLOG = std::is_same_v ?
+    7.09782712893383996843E2 : 88.72283905206835;
+  static scalar_t EXP1 = 2.718281828459045;
+  static scalar_t lanczos_g = 6.024680040776729583740234375;
+
+  if (std::fabs(a - x) > 0.4 * std::fabs(a)) {
+    ax = a * std::log(x) - x - std::lgamma(a);
+    if (ax < -MAXLOG) {
+      return 0.0;
+    }
+    return std::exp(ax);
+  }
+
+  fac = a + lanczos_g - 0.5;
+  res = std::sqrt(fac / EXP1) / lanczos_sum_expg_scaled(a);
+
+  if ((a < 200) && (x < 200)) {
+    res *= std::exp(a - x) * std::pow(x / fac, a);
+  }
+  else {
+    num = x - a - lanczos_g + 0.5;
+    numfac = num / fac;
+    res *= std::exp(a * (std::log1p(numfac) - numfac) + x * (0.5 - lanczos_g) / fac);
+  }
+  return res;
+}
+
+template 
+static scalar_t _igam_helper_series(scalar_t a, scalar_t x) {
+  // Compute igam using DLMF 8.11.4. [igam1]
+  static scalar_t MACHEP = std::is_same_v ?
+    1.11022302462515654042E-16 : 5.9604644775390625E-8;
+  static int MAXITER = 2000;
+
+  int i;
+  scalar_t ans, ax, c, r;
+
+  ax = _igam_helper_fac(a, x);
+  if (ax == 0.0) {
+    return 0.0;
+  }
+
+  /* power series */
+  r = a;
+  c = 1.0;
+  ans = 1.0;
+
+  for (i = 0; i < MAXITER; i++) {
+    r += 1.0;
+    c *= x / r;
+    ans += c;
+    if (c <= MACHEP * ans) {
+      break;
+    }
+  }
+  return (ans * ax / a);
+}
+
+template 
+static scalar_t _igamc_helper_series(scalar_t a, scalar_t x) {
+  // Compute igamc using DLMF 8.7.3 [igam1]. This is related to the series in
+  // _igam_helper_series but extra care is taken to avoid cancellation.
+
+  int n;
+  scalar_t fac = 1;
+  scalar_t sum = 0;
+  scalar_t term, logx;
+  static scalar_t MAXITER = 2000;
+  static scalar_t MACHEP = std::is_same_v ?
+    1.11022302462515654042E-16 : 5.9604644775390625E-8;
+
+  for (n = 1; n < MAXITER; n++) {
+    fac *= -x / n;
+    term = fac / (a + n);
+    sum += term;
+    if (std::fabs(term) <= MACHEP * std::fabs(sum)) {
+        break;
+    }
+  }
+
+  logx = std::log(x);
+  term = -std::expm1(a * logx - std::lgamma(1+a));
+  return term - std::exp(a * logx - std::lgamma(a)) * sum;
+}
+
+template 
+static scalar_t _igam_helper_asymptotic_series(scalar_t a, scalar_t x, bool igam) {
+  // Compute igam/igamc using DLMF 8.12.3/8.12.4 [igam1]
+  static const scalar_t d[25][25] =
+    {{-3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2,
+      1.1574074074074074e-3, 3.527336860670194e-4, -1.7875514403292181e-4,
+      3.9192631785224378e-5, -2.1854485106799922e-6, -1.85406221071516e-6,
+      8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9,
+      1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10,
+      -2.551419399494625e-11, -5.8307721325504251e-11, 2.4361948020667416e-11,
+      -5.0276692801141756e-12, 1.1004392031956135e-13, 3.3717632624009854e-13,
+      -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16,
+      -1.9752288294349443e-15},
+    {-1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3,
+      -9.9022633744855967e-4, 2.0576131687242798e-4, -4.0187757201646091e-7,
+      -1.8098550334489978e-5, 7.6491609160811101e-6, -1.6120900894563446e-6,
+      4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8,
+      1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9,
+      4.1627929918425826e-10, -8.5639070264929806e-11, 6.0672151016047586e-14,
+      7.1624989648114854e-12, -2.9331866437714371e-12, 5.9966963656836887e-13,
+      -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14,
+      -4.13125571381061e-15},
+    {4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4,
+      2.0093878600823045e-6, -1.0736653226365161e-4, 5.2923448829120125e-5,
+      -1.2760635188618728e-5, 3.4235787340961381e-8, 1.3721957309062933e-6,
+      -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10,
+      -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9,
+      9.4283561590146782e-13, 1.2872252400089318e-10, -5.5645956134363321e-11,
+      1.1975935546366981e-11, -4.1689782251838635e-15, -1.0940640427884594e-12,
+      4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17,
+      8.8592218725911273e-15},
+    {6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4,
+      2.6772063206283885e-4, -7.5618016718839764e-5, -2.3965051138672967e-7,
+      1.1082654115347302e-5, -5.6749528269915966e-6, 1.4230900732435884e-6,
+      -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8,
+      -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9,
+      -9.4604966618551322e-10, 2.1541049775774908e-10, -1.388823336813903e-14,
+      -2.1894761681963939e-11, 9.7909989511716851e-12, -2.1782191880180962e-12,
+      6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14,
+      2.0453671226782849e-14},
+    {-8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4,
+      -1.4638452578843418e-6, 6.6414982154651222e-5, -3.9683650471794347e-5,
+      1.1375726970678419e-5, 2.5074972262375328e-10, -1.6954149536558306e-6,
+      8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11,
+      2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9,
+      -2.3024517174528067e-13, -3.9409233028046405e-10, 1.8602338968504502e-10,
+      -4.356323005056618e-11, 1.2786001016296231e-15, 4.6792750266579195e-12,
+      -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18,
+      -5.0453320690800944e-14},
+    {-3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4,
+      -1.9932570516188848e-4, 6.7977804779372078e-5, 1.419062920643967e-7,
+      -1.3594048189768693e-5, 8.0184702563342015e-6, -2.2914811765080952e-6,
+      -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7,
+      4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9,
+      3.1624176287745679e-9, -7.8409242536974293e-10, 5.1926791652540407e-15,
+      9.3589442423067836e-11, -4.5134262161632782e-11, 1.0799129993116827e-11,
+      -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13,
+      -1.3249659916340829e-13},
+    {5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4,
+      7.9023532326603279e-7, -8.1539693675619688e-5, 5.6116827531062497e-5,
+      -1.8329116582843376e-5, -3.0796134506033048e-9, 3.4651553688036091e-6,
+      -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13,
+      -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8,
+      8.6496488580102925e-14, 1.6846058979264063e-9, -8.5754928235775947e-10,
+      2.1598224929232125e-10, -7.6132305204761539e-16, -2.6639822008536144e-11,
+      1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18,
+      3.6902800842763467e-13},
+    {3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4,
+      2.812695154763237e-4, -1.0976582244684731e-4, -1.2741009095484485e-7,
+      2.7744451511563644e-5, -1.8263488805711333e-5, 5.7876949497350524e-6,
+      4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7,
+      -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8,
+      -1.4578352908731271e-8, 3.887645959386175e-9, -3.8810022510194121e-17,
+      -5.3279941738772867e-10, 2.7437977643314845e-10, -6.9957960920705679e-11,
+      2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12,
+      1.0865561947091654e-12},
+    {-6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4,
+      -6.969091458420552e-7, 1.6644846642067548e-4, -1.2783517679769219e-4,
+      4.6299532636913043e-5, 4.5579098679227077e-9, -1.0595271125805195e-5,
+      6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11,
+      3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8,
+      6.5977038267330006e-16, -9.5903864974256858e-9, 5.2132144922808078e-9,
+      -1.3991589583935709e-9, 5.382058999060575e-16, 1.9484714275467745e-10,
+      -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18,
+      -3.3721464474854592e-12},
+    {-5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4,
+      -6.4014752602627585e-4, 2.7750107634328704e-4, 1.8197008380465151e-7,
+      -8.4795071170685032e-5, 6.105192082501531e-5, -2.1073920183404862e-5,
+      -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6,
+      8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7,
+      8.862466778790695e-8, -2.5184812301826817e-8, -1.0225912098215092e-14,
+      3.8969470758154777e-9, -2.1267304792235635e-9, 5.7370135528051385e-10,
+      -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11,
+      -1.1002224534207726e-11},
+    {1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3,
+      9.932404122642299e-7, -5.0874501293093199e-4, 4.2735056665392884e-4,
+      -1.6858853767910799e-4, -8.1301893922784998e-9, 4.5284402370562147e-5,
+      -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11,
+      -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7,
+      -1.7567877666323291e-13, 7.0145043163668257e-8, -4.040787734999483e-8,
+      1.1474026743371963e-8, 3.9642746853563325e-18, -1.7804938269892714e-9,
+      9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18,
+      3.7647749553543836e-11},
+    {1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3,
+      2.1389686185689098e-3, -1.0108559391263003e-3, -3.9912705529919201e-7,
+      3.6235025084764691e-4, -2.8143901463712154e-4, 1.0449513336495887e-4,
+      2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5,
+      -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6,
+      -6.8693396379526735e-7, 2.0653236975414887e-7, 4.6714772409838506e-14,
+      -3.5609886164949055e-8, 2.0470855345905963e-8, -5.8091738633283358e-9,
+      -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10,
+      1.3481607129399749e-10},
+    {-4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3,
+      -2.183732802866233e-6, 2.1740441801254639e-3, -1.9700440518418892e-3,
+      8.3595469747962458e-4, 1.9445447567109655e-8, -2.5779387120421696e-4,
+      1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10,
+      1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6,
+      7.9829760242325709e-13, -6.4097794149313004e-7, 3.8894624761300056e-7,
+      -1.1618347644948869e-7, -2.816808630596451e-15, 1.9878012911297093e-8,
+      -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20,
+      -5.0423112718105824e-10},
+    {-5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3,
+      -9.8576315587856125e-3, 5.0134695031021538e-3, 1.2807521786221875e-6,
+      -2.0626019342754683e-3, 1.7109128573523058e-3, -6.7695312714133799e-4,
+      -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4,
+      4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5,
+      6.612086372797651e-6, -2.0913022027253008e-6, -2.0951775649603837e-13,
+      3.9756029041993247e-7, -2.3956211978815887e-7, 7.1182883382145864e-8,
+      8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9,
+      -1.9661464453856102e-9},
+    {1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2,
+      7.0289515966903407e-6, -1.2375421071343148e-2, 1.1976293444235254e-2,
+      -5.4156038466518525e-3, -6.3290893396418616e-8, 1.8855118129005065e-3,
+      -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10,
+      -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5,
+      -3.5755837291098993e-12, 7.1560851960630076e-6, -4.5516802628155526e-6,
+      1.4236576649271475e-6, 1.8803149082089664e-14, -2.6623403898929211e-7,
+      1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17,
+      7.9795091026746235e-9},
+    {3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2,
+      5.9915643009307869e-2, -3.2483207601623391e-2, -5.7212968652103441e-6,
+      1.5085251778569354e-2, -1.3261324005088445e-2, 5.5515262632426148e-3,
+      3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3,
+      -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4,
+      -7.7378565221244477e-5, 2.5625836246985201e-5, 1.0766165333192814e-12,
+      -5.3246809282422621e-6, 3.349634863064464e-6, -1.0381253128684018e-6,
+      -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7,
+      3.3654425209171788e-8},
+    {-9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1,
+      -3.1478872752284357e-5, 9.0510635276848131e-2, -9.2828824411184397e-2,
+      4.4412112839877808e-2, 2.7779236316835888e-7, -1.7229543805449697e-2,
+      1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9,
+      1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4,
+      1.8365800754090661e-11, -9.5844256563655903e-5, 6.3643062337764708e-5,
+      -2.076250624489065e-5, -1.1806020912804483e-13, 4.2131808239120649e-6,
+      -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16,
+      -1.4729737374018841e-7},
+    {-1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1,
+      -4.6435192311733545e-1, 2.6640934719197893e-1, 3.4038266027147191e-5,
+      -1.3784338709329624e-1, 1.276467178337056e-1, -5.6213828755200985e-2,
+      -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2,
+      5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3,
+      1.0819320643228214e-3, -3.7372510193945659e-4, -6.6170909729031985e-12,
+      8.4263617380909628e-5, -5.5150706827483479e-5, 1.7769536448348069e-5,
+      3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6,
+      -6.6812849447625594e-7},
+    {7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968,
+      1.876173868950258e-4, -8.2705501176152696e-1, 8.9352433347828414e-1,
+      -4.4971003995291339e-1, -1.6107401567546652e-6, 1.9235590165271091e-1,
+      -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8,
+      -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3,
+      -1.1287469112826745e-10, 1.5167451119784857e-3, -1.0478634293553899e-3,
+      3.5539072889126421e-4, 8.1704322111801517e-13, -7.7773013442452395e-5,
+      5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14,
+      3.1369106244517615e-6},
+    {1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906,
+      4.4692325482864037, -2.6977693045875807, -2.600667859891061e-4,
+      1.5389017615694539, -1.4937962361134612, 6.8881964633233148e-1,
+      1.3077482004552385e-6, -2.5762963325596288e-1, 2.1097676102125449e-1,
+      -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2,
+      -1.7813678334552311e-2, 6.3970330388900056e-3, 4.9430807090480523e-11,
+      -1.5554602758465635e-3, 1.0561196919903214e-3, -3.5277184460472902e-4,
+      9.3002334645022459e-14, 7.5285855026557172e-5, -4.8186515569156351e-5,
+      1.5227271505597605e-5},
+    {-6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1,
+      -1.4352254537875018e-3, 9.2333694596189809, -1.0456552819547769e+1,
+      5.5105526029033471, 1.2024439690716742e-5, -2.5762961164755816,
+      2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7,
+      3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1,
+      8.4329730484871625e-10, -2.7998284958442595e-2, 2.0066274144976813e-2,
+      -7.0554368915086242e-3, 1.9402238183698188e-12, 1.6562888105449611e-3,
+      -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11,
+      -7.6340103696869031e-5},
+    {-1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1,
+      -5.2298271025348962e+1, 3.3058589696624618e+1, 2.4791298976200222e-3,
+      -2.061089403411526e+1, 2.088672775145582e+1, -1.0045703956517752e+1,
+      -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195,
+      1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1,
+      3.4112666080644461e-1, -1.2699786326594923e-1, -2.8953677269081528e-10,
+      3.3125776278259863e-2, -2.3274087021036101e-2, 8.0399993503648882e-3,
+      -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3,
+      -3.9479941246822517e-4},
+    {7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2,
+      1.3692876877324546e-2, -1.2366496885920151e+2, 1.4620689391062729e+2,
+      -8.0365587724865346e+1, -1.1259851148881298e-4, 4.0770132196179938e+1,
+      -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7,
+      -6.2716159907747034, 5.1168999071852637, -2.0319658112299095,
+      -4.9507215582761543e-9, 5.9626397294332597e-1, -4.4220765337238094e-1,
+      1.6079998700166273e-1, -2.4733786203223402e-8, -4.0307574759979762e-2,
+      2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6,
+      2.1250180774699461e-3},
+    {2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2,
+      7.3121595266969204e+2, -4.8213821720890847e+2, -2.8817248692894889e-2,
+      3.2616720302947102e+2, -3.4389340280087117e+2, 1.7195193870816232e+2,
+      1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1,
+      -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373,
+      -7.5175301113311376, 2.8943997568871961, -4.6612194999538201e-7,
+      -8.0615149598794088e-1, 5.8483006570631029e-1, -2.0845408972964956e-1,
+      1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2,
+      1.5109265210467774e-2},
+    {-9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3,
+      -1.5925738122215253e-1, 1.9569985945919857e+3, -2.4072514765081556e+3,
+      1.3756149959336496e+3, 1.2920735237496668e-3, -7.525941715948055e+2,
+      7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6,
+      1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1,
+      -7.9237387133614756e-6, -1.4510726927018646e+1, 1.1111771248100563e+1,
+      -4.1690817945270892, 3.1008219800117808e-3, 1.1220095449981468,
+      -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1,
+      4.8683443692930507e-1}};
+
+  int k, n, sgn;
+  int maxpow = 0;
+  static scalar_t MACHEP = std::is_same_v ?
+    1.11022302462515654042E-16 : 5.9604644775390625E-8;
+  scalar_t lambda = x / a;
+  scalar_t sigma = (x - a) / a;
+  scalar_t eta, res, ck, ckterm, term, absterm;
+  scalar_t absoldterm = INFINITY;
+  scalar_t etapow[25] = {1};
+  scalar_t sum = 0;
+  scalar_t afac = 1;
+
+  if (igam) {
+    sgn = -1;
+  }
+  else {
+    sgn = 1;
+  }
+
+  if (lambda > 1) {
+    eta = std::sqrt(-2 * (std::log1p(sigma) - sigma));
+  }
+  else if (lambda < 1) {
+    eta = -std::sqrt(-2 * (std::log1p(sigma) - sigma));
+  }
+  else {
+    eta = 0;
+  }
+  res = 0.5 * std::erfc(sgn * eta * std::sqrt(a / 2));
+
+  for (k = 0; k < 25; k++) {
+    ck = d[k][0];
+    for (n = 1; n < 25; n++) {
+      if (n > maxpow) {
+        etapow[n] = eta * etapow[n-1];
+        maxpow += 1;
+      }
+      ckterm = d[k][n]*etapow[n];
+      ck += ckterm;
+      if (std::fabs(ckterm) < MACHEP * std::fabs(ck)) {
+        break;
+      }
+    }
+    term = ck * afac;
+    absterm = std::fabs(term);
+    if (absterm > absoldterm) {
+      break;
+    }
+    sum += term;
+    if (absterm < MACHEP * std::fabs(sum)) {
+      break;
+    }
+    absoldterm = absterm;
+    afac /= a;
+  }
+  res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * c10::pi * a);
+
+  return res;
+}
+
+template 
+static scalar_t _igamc_helper_continued_fraction(scalar_t a, scalar_t x) {
+  // Compute igamc using DLMF 8.9.2. [igam1]
+  int i;
+  scalar_t ans, ax, c, yc, r, t, y, z;
+  scalar_t pk, pkm1, pkm2, qk, qkm1, qkm2;
+  int MAXITER = 2000;
+  static scalar_t MACHEP = std::is_same_v ?
+    1.11022302462515654042E-16 : 5.9604644775390625E-8;
+  static scalar_t BIG = std::is_same_v ?
+    4.503599627370496e15 : 16777216.;
+  static scalar_t BIGINV = std::is_same_v ?
+    2.22044604925031308085e-16 : 5.9604644775390625E-8;
+
+  ax = _igam_helper_fac(a, x);
+  if (ax == 0.0) {
+    return 0.0;
+  }
+
+  /* continued fraction */
+  y = 1.0 - a;
+  z = x + y + 1.0;
+  c = 0.0;
+  pkm2 = 1.0;
+  qkm2 = x;
+  pkm1 = x + 1.0;
+  qkm1 = z * x;
+  ans = pkm1 / qkm1;
+
+  for (i = 0; i < MAXITER; i++) {
+    c += 1.0;
+    y += 1.0;
+    z += 2.0;
+    yc = y * c;
+    pk = pkm1 * z - pkm2 * yc;
+    qk = qkm1 * z - qkm2 * yc;
+    if (qk != 0) {
+      r = pk / qk;
+      t = std::fabs((ans - r) / r);
+      ans = r;
+    }
+    else {
+      t = 1.0;
+    }
+    pkm2 = pkm1;
+    pkm1 = pk;
+    qkm2 = qkm1;
+    qkm1 = qk;
+    if (std::fabs(pk) > BIG) {
+      pkm2 *= BIGINV;
+      pkm1 *= BIGINV;
+      qkm2 *= BIGINV;
+      qkm1 *= BIGINV;
+    }
+    if (t <= MACHEP) {
+      break;
+    }
+  }
+  return ans * ax;
+}
+
+template 
+inline scalar_t calc_igammac(scalar_t a, scalar_t x) {
+  /* the calculation of the regularized upper incomplete gamma function
+   * is done differently based on the values of a and x:
+   * - if x and/or a is at the boundary of defined region, then assign the
+   *   result at the boundary
+   * - if a is large and a ~ x, then using Uniform Asymptotic Expansions for
+   *   Large Parameter (see DLMF 8.12.4 [igam1])
+   * - if x > 1.1 and x < a, using the substraction from the regularized lower
+   *   incomplete gamma
+   * - otherwise, calculate the series from [igam2] eq (5)
+   */
+  scalar_t absxma_a;
+
+  static scalar_t SMALL = 20.0;
+  static scalar_t LARGE = 200.0;
+  static scalar_t SMALLRATIO = 0.3;
+  static scalar_t LARGERATIO = 4.5;
+
+  // note that in SciPy, a and x are non-negative, with exclusive 0s (i.e.,
+  // at most 1 of them can be 0), where igammac(0, x) = 0.0 iff x > 0.
+  if ((x < 0) || (a < 0)) {
+    // out of defined-region of the function
+    return std::numeric_limits::quiet_NaN();
+  }
+  else if (a == 0) {
+    if (x > 0) {
+      return 0.0;
+    }
+    else {
+      return std::numeric_limits::quiet_NaN();
+    }
+  }
+  else if (x == 0) {
+    return 1.0;
+  }
+  else if (std::isinf(a)) {
+    if (std::isinf(x)) {
+      return std::numeric_limits::quiet_NaN();
+    }
+    return 1.0;
+  }
+  else if (std::isinf(x)) {
+    return 0.0;
+  }
+
+  absxma_a = std::fabs(x - a) / a;
+  if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) {
+     return _igam_helper_asymptotic_series(a, x, 0);
+  }
+  else if ((a > LARGE) && (absxma_a < LARGERATIO / std::sqrt(a))) {
+     return _igam_helper_asymptotic_series(a, x, 0);
+  }
+
+  if (x > 1.1) {
+    if (x < a) {
+      return 1.0 - _igam_helper_series(a, x);
+    }
+    else {
+      return _igamc_helper_continued_fraction(a, x);
+    }
+  }
+  else if (x <= 0.5) {
+    if (-0.4 / std::log(x) < a) {
+      return 1.0 - _igam_helper_series(a, x);
+    }
+    else {
+      return _igamc_helper_series(a, x);
+    }
+  }
+  else {
+    if (x * 1.1 < a) {
+      return 1.0 - _igam_helper_series(a, x);
+    }
+    else {
+      return _igamc_helper_series(a, x);
+    }
+  }
+}
+
+template 
+scalar_t calc_igamma(scalar_t a, scalar_t x) {
+  /* the calculation of the regularized lower incomplete gamma function
+   * is done differently based on the values of a and x:
+   * - if x and/or a is at the boundary of defined region, then assign the
+   *   result at the boundary
+   * - if a is large and a ~ x, then using Uniform Asymptotic Expansions for
+   *   Large Parameter (see DLMF 8.12.3 [igam1])
+   * - if x > 1 and x > a, using the substraction from the regularized upper
+   *   incomplete gamma
+   * - otherwise, calculate the series from [igam2] eq (4)
+   */
+  scalar_t absxma_a;
+  static scalar_t SMALL = 20.0;
+  static scalar_t LARGE = 200.0;
+  static scalar_t SMALLRATIO = 0.3;
+  static scalar_t LARGERATIO = 4.5;
+
+  // boundary values following SciPy
+  // note that in SciPy, a and x are non-negative, with exclusive 0s (i.e.,
+  // at most 1 of them can be 0), where igamma(0, x) = 1.0 iff x > 0.
+  if ((x < 0) || (a < 0)) {
+    // out of defined-region of the function
+    return std::numeric_limits::quiet_NaN();
+  }
+  else if (a == 0) {
+    if (x > 0) {
+      return 1.0;
+    }
+    else {
+      return std::numeric_limits::quiet_NaN();
+    }
+  }
+  else if (x == 0) {
+    return 0.0; // zero integration limit
+  }
+  else if (std::isinf(a)) {
+    if (std::isinf(x)) {
+      return std::numeric_limits::quiet_NaN();
+    }
+    return 0.0;
+  }
+  else if (std::isinf(x)) {
+    return 1.0;
+  }
+
+  /* Asymptotic regime where a ~ x. See [igam2] */
+  absxma_a = std::fabs(x - a) / a;
+  if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) {
+    return _igam_helper_asymptotic_series(a, x, 1);
+  }
+  else if ((a > LARGE) && (absxma_a < LARGERATIO / std::sqrt(a))) {
+    return _igam_helper_asymptotic_series(a, x, 1);
+  }
+
+  if ((x > 1.0) && (x > a)) {
+    return 1.0 - calc_igammac(a, x);
+  }
+
+  return _igam_helper_series(a, x);
+}
+
+template <>
+[[maybe_unused]] inline c10::BFloat16 calc_igamma(
+    c10::BFloat16 a,
+    c10::BFloat16 x) {
+  return calc_igamma(float(a), float(x));
+}
+
+template <>
+[[maybe_unused]] inline c10::Half calc_igamma(
+    c10::Half a,
+    c10::Half x) {
+  return calc_igamma(float(a), float(x));
+}
+
+template <>
+[[maybe_unused]] inline c10::BFloat16 calc_igammac(
+    c10::BFloat16 a,
+    c10::BFloat16 x) {
+  return calc_igammac(float(a), float(x));
+}
+
+template <>
+[[maybe_unused]] inline c10::Half calc_igammac(
+    c10::Half a,
+    c10::Half x) {
+  return calc_igammac(float(a), float(x));
+}
+
+inline c10::BFloat16 calc_erfinv(c10::BFloat16 a) { return calc_erfinv(float(a)); }
+
+template 
+inline T abs_impl(T v) {
+  return std::abs(v);
+}
+
+template <>
+[[maybe_unused]] inline uint8_t abs_impl(uint8_t v) {
+  return v;
+}
+
+template 
+inline typename std::enable_if_t, T>
+calc_gcd(T a, T b) {
+  a = abs_impl(a);
+  b = abs_impl(b);
+  while (a != 0) {
+    T c = a;
+    a = b % a;
+    b = c;
+  }
+  return b;
+}
+
+template 
+C10_HOST_DEVICE T exp2_impl(T x) {
+  return std::exp2(x);
+}
+
+template 
+C10_HOST_DEVICE c10::complex exp2_impl(c10::complex x) {
+  // There is no std::exp2 overload for complex, so instead
+  // use the identity 2^x = e^(ln(2) * x)
+  constexpr auto ln2 = c10::ln_2;
+  return std::exp(ln2 * x);
+}
+
+/*
+ * This function is derived from the implementation of the chbevl function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Evaluates the series
+ *
+ *       len-1
+ *         - '
+ *  y  =   >   array[i] T (x/2)
+ *         -             i
+ *        i=0
+ *
+ * of Chebyshev polynomials Ti at argument x/2.
+ *
+ * Coefficients are stored in reverse order, i.e. the zero order term is last in the array.  Note len is the number of
+ * coefficients, not the order.
+ *
+ * If coefficients are for the interval a to b, x must have been transformed to x -> 2(2x - b - a)/(b-a) before
+ * entering the routine.  This maps x from (a, b) to (-1, 1), over which the Chebyshev polynomials are defined.
+ *
+ * If the coefficients are for the inverted interval, in which (a, b) is mapped to (1/b, 1/a), the transformation
+ * required is x -> 2(2ab/x - b - a)/(b-a).  If b is infinity, this becomes x -> 4a/x - 1.
+ */
+template 
+inline typename std::enable_if_t, T>
+chbevl(const T x, const T array[], size_t len) {
+  T b0, b1, b2;
+
+  b0 = array[0];
+  b1 = static_cast(0.0);
+
+  for (size_t i = 1; i < len; ++i) {
+    b2 = b1;
+    b1 = b0;
+    b0 = x * b1 - b2 + array[i];
+  }
+
+  return (static_cast(0.5) * (b0 - b2));
+}
+
+/*
+ * This function is derived from the implementation of the i0 function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Computes an approximation of the zeroth order modified Bessel function of the first kind.
+ * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion.
+ * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value
+ * of all inputs to convert them into the domain of the approximation.
+ */
+template 
+inline std::tuple chebyshev_coefficients_i0e_A() {
+  /* Chebyshev coefficients for exp(-x) I0(x)
+   * in the interval [0,8].
+   *
+   * lim(x->0){ exp(-x) I0(x) } = 1.
+   */
+  static const T coeff[] = {
+      -4.41534164647933937950E-18, 3.33079451882223809783E-17,
+      -2.43127984654795469359E-16, 1.71539128555513303061E-15,
+      -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+      -4.85644678311192946090E-13, 2.95505266312963983461E-12,
+      -1.72682629144155570723E-11, 9.67580903537323691224E-11,
+      -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+      -1.30002500998624804212E-8,  6.04699502254191894932E-8,
+      -2.67079385394061173391E-7,  1.11738753912010371815E-6,
+      -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+      -5.75419501008210370398E-5,  1.88502885095841655729E-4,
+      -5.76375574538582365885E-4,  1.63947561694133579842E-3,
+      -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+      -2.37374148058994688156E-2,  4.93052842396707084878E-2,
+      -9.49010970480476444210E-2,  1.71620901522208775349E-1,
+      -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+  return std::make_tuple(coeff, 30);
+}
+
+template 
+inline std::tuple chebyshev_coefficients_i0e_B() {
+  /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
+   * in the inverted interval [8,infinity].
+   *
+   * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
+   */
+  static const T coeff[] = {
+      -7.23318048787475395456E-18, -4.83050448594418207126E-18,
+      4.46562142029675999901E-17,  3.46122286769746109310E-17,
+      -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+      1.77256013305652638360E-15,  3.81168066935262242075E-15,
+      -9.55484669882830764870E-15, -4.15056934728722208663E-14,
+      1.54008621752140982691E-14,  3.85277838274214270114E-13,
+      7.18012445138366623367E-13,  -1.79417853150680611778E-12,
+      -1.32158118404477131188E-11, -3.14991652796324136454E-11,
+      1.18891471078464383424E-11,  4.94060238822496958910E-10,
+      3.39623202570838634515E-9,   2.26666899049817806459E-8,
+      2.04891858946906374183E-7,   2.89137052083475648297E-6,
+      6.88975834691682398426E-5,   3.36911647825569408990E-3,
+      8.04490411014108831608E-1};
+
+  return std::make_tuple(coeff, 25);
+}
+
+template 
+inline typename std::enable_if_t, std::tuple>
+chebyshev_coefficients_i1e_A() {
+  /* Chebyshev coefficients for exp(-x) I1(x)
+   * in the interval [0,8].
+   *
+   * lim(x->0){ exp(-x) I1(x) / x } = 1/2.
+   */
+  static const T coeff[] = {
+      2.77791411276104639959E-18, -2.11142121435816608115E-17,
+      1.55363195773620046921E-16, -1.10559694773538630805E-15,
+      7.60068429473540693410E-15, -5.04218550472791168711E-14,
+      3.22379336594557470981E-13, -1.98397439776494371520E-12,
+      1.17361862988909016308E-11, -6.66348972350202774223E-11,
+      3.62559028155211703701E-10, -1.88724975172282928790E-9,
+      9.38153738649577178388E-9,  -4.44505912879632808065E-8,
+      2.00329475355213526229E-7,  -8.56872026469545474066E-7,
+      3.47025130813767847674E-6,  -1.32731636560394358279E-5,
+      4.78156510755005422638E-5,  -1.61760815825896745588E-4,
+      5.12285956168575772895E-4,  -1.51357245063125314899E-3,
+      4.15642294431288815669E-3,  -1.05640848946261981558E-2,
+      2.47264490306265168283E-2,  -5.29459812080949914269E-2,
+      1.02643658689847095384E-1,  -1.76416518357834055153E-1,
+      2.52587186443633654823E-1};
+  return std::make_tuple(coeff, 29);
+}
+
+template 
+inline typename std::enable_if_t, std::tuple>
+chebyshev_coefficients_i1e_A() {
+  /* Chebyshev coefficients for exp(-x) I1(x)
+   * in the interval [0,8].
+   *
+   * lim(x->0){ exp(-x) I1(x) / x } = 1/2.
+   */
+  static const T coeff[] = {
+      9.38153738649577178388E-9f,
+      -4.44505912879632808065E-8f,
+      2.00329475355213526229E-7f,
+      -8.56872026469545474066E-7f,
+      3.47025130813767847674E-6f,
+      -1.32731636560394358279E-5f,
+      4.78156510755005422638E-5f,
+      -1.61760815825896745588E-4f,
+      5.12285956168575772895E-4f,
+      -1.51357245063125314899E-3f,
+      4.15642294431288815669E-3f,
+      -1.05640848946261981558E-2f,
+      2.47264490306265168283E-2f,
+      -5.29459812080949914269E-2f,
+      1.02643658689847095384E-1f,
+      -1.76416518357834055153E-1f,
+      2.52587186443633654823E-1f};
+  return std::make_tuple(coeff, 17);
+}
+
+template 
+inline typename std::enable_if_t, std::tuple>
+chebyshev_coefficients_i1e_B() {
+  /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
+   * in the inverted interval [8,infinity].
+   *
+   * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
+   */
+  static const T coeff[] = {
+      7.51729631084210481353E-18,  4.41434832307170791151E-18,
+      -4.65030536848935832153E-17, -3.20952592199342395980E-17,
+      2.96262899764595013876E-16,  3.30820231092092828324E-16,
+      -1.88035477551078244854E-15, -3.81440307243700780478E-15,
+      1.04202769841288027642E-14,  4.27244001671195135429E-14,
+      -2.10154184277266431302E-14, -4.08355111109219731823E-13,
+      -7.19855177624590851209E-13, 2.03562854414708950722E-12,
+      1.41258074366137813316E-11,  3.25260358301548823856E-11,
+      -1.89749581235054123450E-11, -5.58974346219658380687E-10,
+      -3.83538038596423702205E-9,  -2.63146884688951950684E-8,
+      -2.51223623787020892529E-7,  -3.88256480887769039346E-6,
+      -1.10588938762623716291E-4,  -9.76109749136146840777E-3,
+      7.78576235018280120474E-1};
+
+  return std::make_tuple(coeff, 25);
+}
+
+template 
+inline typename std::enable_if_t, std::tuple>
+chebyshev_coefficients_i1e_B() {
+  /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
+   * in the inverted interval [8,infinity].
+   *
+   * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
+   */
+  static const T coeff[] = {
+      -3.83538038596423702205E-9f,
+      -2.63146884688951950684E-8f,
+      -2.51223623787020892529E-7f,
+      -3.88256480887769039346E-6f,
+      -1.10588938762623716291E-4f,
+      -9.76109749136146840777E-3f,
+      7.78576235018280120474E-1f};
+
+  return std::make_tuple(coeff, 7);
+}
+
+template 
+inline typename std::enable_if_t, T>
+calc_i0(T _x) {
+  T x = std::abs(_x);
+
+  if (x <= T{8.0}) {
+    auto [A, len] = chebyshev_coefficients_i0e_A();
+    T y = (x / T{2.0}) - T{2.0};
+    return static_cast(std::exp(x) * chbevl(y, A, len));
+  }
+  auto [B, len] = chebyshev_coefficients_i0e_B();
+  return std::exp(x) * chbevl(T{32.0} / x - T{2.0}, B, len) / std::sqrt(x);
+}
+
+// Upcast bfloat16/half input to float for numerical accuracy purposes
+inline c10::BFloat16 calc_i0(c10::BFloat16 a) { return calc_i0(static_cast(a)); }
+inline c10::Half calc_i0(c10::Half a) { return calc_i0(static_cast(a)); }
+
+/*
+ * This function is derived from the implementation of the i1 function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Computes an approximation of the first order modified Bessel function of the first kind.
+ * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion.
+ * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value
+ * of all inputs to convert them into the domain of the approximation.
+ */
+template 
+inline typename std::enable_if_t, T>
+calc_i1(T _x) {
+  T x = std::abs(_x);
+
+  if (x <= T{8.0}) {
+    auto [A, len] = chebyshev_coefficients_i1e_A();
+    T y = (x / T{2.0}) - T{2.0};
+    const T out = std::exp(x) * x * chbevl(y, A, len);
+    return (_x < T{0.0}) ? -out : out;
+  }
+  auto [B, len] = chebyshev_coefficients_i1e_B();
+  const T out = (std::exp(x) * chbevl(T{32.0} / x - T{2.0}, B, len)) / std::sqrt(x);
+  return (_x < T{0.0}) ? -out : out;
+}
+
+// Upcast bfloat16/half input to float for numerical accuracy purposes
+inline c10::BFloat16 calc_i1(c10::BFloat16 a) { return calc_i1(static_cast(a)); }
+inline c10::Half calc_i1(c10::Half a) { return calc_i1(static_cast(a)); }
+
+
+/*
+ * This function is derived from the implementation of the i1e function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Computes an approximation of the exponentially scaled first order modified Bessel function of the first kind.
+ * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion.
+ * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value
+ * of all inputs to convert them into the domain of the approximation.
+ */
+template 
+inline typename std::enable_if_t, T>
+calc_i1e(T _x) {
+  T x = std::abs(_x);
+
+  if (x <= T{8.0}) {
+    auto [A, len] = chebyshev_coefficients_i1e_A();
+    T y = (x / T{2.0}) - T{2.0};
+    const T out = chbevl(y, A, len) * x;
+    return (_x < T{0.0}) ? -out : out;
+  }
+  auto [B, len] = chebyshev_coefficients_i1e_B();
+  const auto out = chbevl(T{32.0} / x - T{2.0}, B, len) / std::sqrt(x);
+  return (_x < T{0.0}) ? -out : out;
+}
+
+// Upcast bfloat16/half input to float for numerical accuracy purposes
+inline c10::BFloat16 calc_i1e(c10::BFloat16 a) { return calc_i1e(static_cast(a)); }
+inline c10::Half calc_i1e(c10::Half a) { return calc_i1e(static_cast(a)); }
+
+
+/*
+ * This function is derived from the implementation of the i1e function in the Cephes Math Library.
+ * See note [3-Clause BSD License for the Cephes Math Library].
+ *
+ * Computes the argument, x, for which the area under the Gaussian probability density function
+ * (integrated from minus infinity to x) is equal to y.
+ */
+template 
+inline C10_HOST_DEVICE T calc_ndtri(T y0) {
+
+  /* sqrt(2pi) */
+  constexpr T s2pi = 2.50662827463100050242E0;
+  constexpr T one = 1;
+  constexpr T zero = 0;
+
+  /* approximation for 0 <= |y - 0.5| <= 3/8 */
+  static const T P0[5] = {
+      -5.99633501014107895267E1,
+      9.80010754185999661536E1,
+      -5.66762857469070293439E1,
+      1.39312609387279679503E1,
+      -1.23916583867381258016E0,
+  };
+
+  static const T Q0[9] = {
+      1.00000000000000000000E0,
+      1.95448858338141759834E0,
+      4.67627912898881538453E0,
+      8.63602421390890590575E1,
+      -2.25462687854119370527E2,
+      2.00260212380060660359E2,
+      -8.20372256168333339912E1,
+      1.59056225126211695515E1,
+      -1.18331621121330003142E0,
+  };
+
+  /* Approximation for interval z = sqrt(-2 log y ) between 2 and 8
+  * i.e., y between exp(-2) = .135 and exp(-32) = 1.27e-14.
+  */
+  static const T P1[9] = {
+      4.05544892305962419923E0,
+      3.15251094599893866154E1,
+      5.71628192246421288162E1,
+      4.40805073893200834700E1,
+      1.46849561928858024014E1,
+      2.18663306850790267539E0,
+      -1.40256079171354495875E-1,
+      -3.50424626827848203418E-2,
+      -8.57456785154685413611E-4,
+  };
+
+  static const T Q1[9] = {
+      1.00000000000000000000E0,
+      1.57799883256466749731E1,
+      4.53907635128879210584E1,
+      4.13172038254672030440E1,
+      1.50425385692907503408E1,
+      2.50464946208309415979E0,
+      -1.42182922854787788574E-1,
+      -3.80806407691578277194E-2,
+      -9.33259480895457427372E-4,
+  };
+
+  /* Approximation for interval z = sqrt(-2 log y ) between 8 and 64
+  * i.e., y between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890.
+  */
+
+  static const T P2[9] = {
+      3.23774891776946035970E0,
+      6.91522889068984211695E0,
+      3.93881025292474443415E0,
+      1.33303460815807542389E0,
+      2.01485389549179081538E-1,
+      1.23716634817820021358E-2,
+      3.01581553508235416007E-4,
+      2.65806974686737550832E-6,
+      6.23974539184983293730E-9,
+  };
+
+  static const T Q2[9] = {
+      1.00000000000000000000E0,
+      6.02427039364742014255E0,
+      3.67983563856160859403E0,
+      1.37702099489081330271E0,
+      2.16236993594496635890E-1,
+      1.34204006088543189037E-2,
+      3.28014464682127739104E-4,
+      2.89247864745380683936E-6,
+      6.79019408009981274425E-9,
+  };
+
+  if (y0 == zero) {
+    return -std::numeric_limits::infinity();
+  }
+  if (y0 == one) {
+    return std::numeric_limits::infinity();
+  }
+  if (y0 < zero || y0 > one) {
+    return std::numeric_limits::quiet_NaN();
+  }
+  bool code = true;
+  T y = y0;
+  if (y > one - T{0.13533528323661269189}) { /* 0.135... = exp(-2) */
+    y = one - y;
+    code = false;
+  }
+
+  if (y > T{0.13533528323661269189}) {
+    y = y - T{0.5};
+    const T y2 = y * y;
+    T x = y + y * (y2 * polevl(y2, P0, 4) / polevl(y2, Q0, 8));
+    return (x * s2pi);
+  }
+
+  T x = ::sqrt(T{-2.0} * ::log(y));
+  const T x0 = x - ::log(x) / x;
+
+  const T z = one / x;
+  T x1;
+  if (x < T{8.0}) /* y > exp(-32) = 1.2664165549e-14 */
+  {
+    x1 = z * polevl(z, P1, 8) / polevl(z, Q1, 8);
+  } else {
+    x1 = z * polevl(z, P2, 8) / polevl(z, Q2, 8);
+  }
+  x = x0 - x1;
+  if (code) {
+    x = -x;
+  }
+  return x;
+}
+
+/* The next function is taken from http://ab-initio.mit.edu/Faddeev */
+
+/* Copyright (c) 2012 Massachusetts Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/* erfcx(x) = exp(x^2) erfc(x) function, for real x, written by
+   Steven G. Johnson, October 2012.
+
+   This function combines a few different ideas.
+
+   First, for x > 50, it uses a continued-fraction expansion (same as
+   for the Faddeeva function, but with algebraic simplifications for z=i*x).
+
+   Second, for 0 <= x <= 50, it uses Chebyshev polynomial approximations,
+   but with two twists:
+
+      a) It maps x to y = 4 / (4+x) in [0,1].  This simple transformation,
+         inspired by a similar transformation in the octave-forge/specfun
+         erfcx by Soren Hauberg, results in much faster Chebyshev convergence
+         than other simple transformations I have examined.
+
+      b) Instead of using a single Chebyshev polynomial for the entire
+         [0,1] y interval, we break the interval up into 100 equal
+         subintervals, with a switch/lookup table, and use much lower
+         degree Chebyshev polynomials in each subinterval. This greatly
+         improves performance in my tests.
+
+   For x < 0, we use the relationship erfcx(-x) = 2 exp(x^2) - erfc(x),
+   with the usual checks for overflow etcetera.
+
+   Performance-wise, it seems to be substantially faster than either
+   the SLATEC DERFC function [or an erfcx function derived therefrom]
+   or Cody's CALERF function (from netlib.org/specfun), while
+   retaining near machine precision in accuracy.  */
+
+/* Given y100=100*y, where y = 4/(4+x) for x >= 0, compute erfc(x).
+
+   Uses a look-up table of 100 different Chebyshev polynomials
+   for y intervals [0,0.01], [0.01,0.02], ...., [0.99,1], generated
+   with the help of Maple and a little shell script.   This allows
+   the Chebyshev polynomials to be of significantly lower degree (about 1/4)
+   compared to fitting the whole [0,1] interval with a single polynomial. */
+
+
+template 
+C10_HOST_DEVICE  inline typename std::enable_if_t, T>
+erfcx_y100(T y100)
+{
+  switch (static_cast(y100)) {
+case 0: {
+T t = 2*y100 - 1;
+return 0.70878032454106438663e-3 + (0.71234091047026302958e-3 + (0.35779077297597742384e-5 + (0.17403143962587937815e-7 + (0.81710660047307788845e-10 + (0.36885022360434957634e-12 + 0.15917038551111111111e-14 * t) * t) * t) * t) * t) * t;
+}
+case 1: {
+T t = 2*y100 - 3;
+return 0.21479143208285144230e-2 + (0.72686402367379996033e-3 + (0.36843175430938995552e-5 + (0.18071841272149201685e-7 + (0.85496449296040325555e-10 + (0.38852037518534291510e-12 + 0.16868473576888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 2: {
+T t = 2*y100 - 5;
+return 0.36165255935630175090e-2 + (0.74182092323555510862e-3 + (0.37948319957528242260e-5 + (0.18771627021793087350e-7 + (0.89484715122415089123e-10 + (0.40935858517772440862e-12 + 0.17872061464888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 3: {
+T t = 2*y100 - 7;
+return 0.51154983860031979264e-2 + (0.75722840734791660540e-3 + (0.39096425726735703941e-5 + (0.19504168704300468210e-7 + (0.93687503063178993915e-10 + (0.43143925959079664747e-12 + 0.18939926435555555556e-14 * t) * t) * t) * t) * t) * t;
+}
+case 4: {
+T t = 2*y100 - 9;
+return 0.66457513172673049824e-2 + (0.77310406054447454920e-3 + (0.40289510589399439385e-5 + (0.20271233238288381092e-7 + (0.98117631321709100264e-10 + (0.45484207406017752971e-12 + 0.20076352213333333333e-14 * t) * t) * t) * t) * t) * t;
+}
+case 5: {
+T t = 2*y100 - 11;
+return 0.82082389970241207883e-2 + (0.78946629611881710721e-3 + (0.41529701552622656574e-5 + (0.21074693344544655714e-7 + (0.10278874108587317989e-9 + (0.47965201390613339638e-12 + 0.21285907413333333333e-14 * t) * t) * t) * t) * t) * t;
+}
+case 6: {
+T t = 2*y100 - 13;
+return 0.98039537275352193165e-2 + (0.80633440108342840956e-3 + (0.42819241329736982942e-5 + (0.21916534346907168612e-7 + (0.10771535136565470914e-9 + (0.50595972623692822410e-12 + 0.22573462684444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 7: {
+T t = 2*y100 - 15;
+return 0.11433927298290302370e-1 + (0.82372858383196561209e-3 + (0.44160495311765438816e-5 + (0.22798861426211986056e-7 + (0.11291291745879239736e-9 + (0.53386189365816880454e-12 + 0.23944209546666666667e-14 * t) * t) * t) * t) * t) * t;
+}
+case 8: {
+T t = 2*y100 - 17;
+return 0.13099232878814653979e-1 + (0.84167002467906968214e-3 + (0.45555958988457506002e-5 + (0.23723907357214175198e-7 + (0.11839789326602695603e-9 + (0.56346163067550237877e-12 + 0.25403679644444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 9: {
+T t = 2*y100 - 19;
+return 0.14800987015587535621e-1 + (0.86018092946345943214e-3 + (0.47008265848816866105e-5 + (0.24694040760197315333e-7 + (0.12418779768752299093e-9 + (0.59486890370320261949e-12 + 0.26957764568888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 10: {
+T t = 2*y100 - 21;
+return 0.16540351739394069380e-1 + (0.87928458641241463952e-3 + (0.48520195793001753903e-5 + (0.25711774900881709176e-7 + (0.13030128534230822419e-9 + (0.62820097586874779402e-12 + 0.28612737351111111111e-14 * t) * t) * t) * t) * t) * t;
+}
+case 11: {
+T t = 2*y100 - 23;
+return 0.18318536789842392647e-1 + (0.89900542647891721692e-3 + (0.50094684089553365810e-5 + (0.26779777074218070482e-7 + (0.13675822186304615566e-9 + (0.66358287745352705725e-12 + 0.30375273884444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 12: {
+T t = 2*y100 - 25;
+return 0.20136801964214276775e-1 + (0.91936908737673676012e-3 + (0.51734830914104276820e-5 + (0.27900878609710432673e-7 + (0.14357976402809042257e-9 + (0.70114790311043728387e-12 + 0.32252476000000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 13: {
+T t = 2*y100 - 27;
+return 0.21996459598282740954e-1 + (0.94040248155366777784e-3 + (0.53443911508041164739e-5 + (0.29078085538049374673e-7 + (0.15078844500329731137e-9 + (0.74103813647499204269e-12 + 0.34251892320000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 14: {
+T t = 2*y100 - 29;
+return 0.23898877187226319502e-1 + (0.96213386835900177540e-3 + (0.55225386998049012752e-5 + (0.30314589961047687059e-7 + (0.15840826497296335264e-9 + (0.78340500472414454395e-12 + 0.36381553564444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 15: {
+T t = 2*y100 - 31;
+return 0.25845480155298518485e-1 + (0.98459293067820123389e-3 + (0.57082915920051843672e-5 + (0.31613782169164830118e-7 + (0.16646478745529630813e-9 + (0.82840985928785407942e-12 + 0.38649975768888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 16: {
+T t = 2*y100 - 33;
+return 0.27837754783474696598e-1 + (0.10078108563256892757e-2 + (0.59020366493792212221e-5 + (0.32979263553246520417e-7 + (0.17498524159268458073e-9 + (0.87622459124842525110e-12 + 0.41066206488888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 17: {
+T t = 2*y100 - 35;
+return 0.29877251304899307550e-1 + (0.10318204245057349310e-2 + (0.61041829697162055093e-5 + (0.34414860359542720579e-7 + (0.18399863072934089607e-9 + (0.92703227366365046533e-12 + 0.43639844053333333334e-14 * t) * t) * t) * t) * t) * t;
+}
+case 18: {
+T t = 2*y100 - 37;
+return 0.31965587178596443475e-1 + (0.10566560976716574401e-2 + (0.63151633192414586770e-5 + (0.35924638339521924242e-7 + (0.19353584758781174038e-9 + (0.98102783859889264382e-12 + 0.46381060817777777779e-14 * t) * t) * t) * t) * t) * t;
+}
+case 19: {
+T t = 2*y100 - 39;
+return 0.34104450552588334840e-1 + (0.10823541191350532574e-2 + (0.65354356159553934436e-5 + (0.37512918348533521149e-7 + (0.20362979635817883229e-9 + (0.10384187833037282363e-11 + 0.49300625262222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 20: {
+T t = 2*y100 - 41;
+return 0.36295603928292425716e-1 + (0.11089526167995268200e-2 + (0.67654845095518363577e-5 + (0.39184292949913591646e-7 + (0.21431552202133775150e-9 + (0.10994259106646731797e-11 + 0.52409949102222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 21: {
+T t = 2*y100 - 43;
+return 0.38540888038840509795e-1 + (0.11364917134175420009e-2 + (0.70058230641246312003e-5 + (0.40943644083718586939e-7 + (0.22563034723692881631e-9 + (0.11642841011361992885e-11 + 0.55721092871111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 22: {
+T t = 2*y100 - 45;
+return 0.40842225954785960651e-1 + (0.11650136437945673891e-2 + (0.72569945502343006619e-5 + (0.42796161861855042273e-7 + (0.23761401711005024162e-9 + (0.12332431172381557035e-11 + 0.59246802364444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 23: {
+T t = 2*y100 - 47;
+return 0.43201627431540222422e-1 + (0.11945628793917272199e-2 + (0.75195743532849206263e-5 + (0.44747364553960993492e-7 + (0.25030885216472953674e-9 + (0.13065684400300476484e-11 + 0.63000532853333333334e-14 * t) * t) * t) * t) * t) * t;
+}
+case 24: {
+T t = 2*y100 - 49;
+return 0.45621193513810471438e-1 + (0.12251862608067529503e-2 + (0.77941720055551920319e-5 + (0.46803119830954460212e-7 + (0.26375990983978426273e-9 + (0.13845421370977119765e-11 + 0.66996477404444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 25: {
+T t = 2*y100 - 51;
+return 0.48103121413299865517e-1 + (0.12569331386432195113e-2 + (0.80814333496367673980e-5 + (0.48969667335682018324e-7 + (0.27801515481905748484e-9 + (0.14674637611609884208e-11 + 0.71249589351111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 26: {
+T t = 2*y100 - 53;
+return 0.50649709676983338501e-1 + (0.12898555233099055810e-2 + (0.83820428414568799654e-5 + (0.51253642652551838659e-7 + (0.29312563849675507232e-9 + (0.15556512782814827846e-11 + 0.75775607822222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 27: {
+T t = 2*y100 - 55;
+return 0.53263363664388864181e-1 + (0.13240082443256975769e-2 + (0.86967260015007658418e-5 + (0.53662102750396795566e-7 + (0.30914568786634796807e-9 + (0.16494420240828493176e-11 + 0.80591079644444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 28: {
+T t = 2*y100 - 57;
+return 0.55946601353500013794e-1 + (0.13594491197408190706e-2 + (0.90262520233016380987e-5 + (0.56202552975056695376e-7 + (0.32613310410503135996e-9 + (0.17491936862246367398e-11 + 0.85713381688888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 29: {
+T t = 2*y100 - 59;
+return 0.58702059496154081813e-1 + (0.13962391363223647892e-2 + (0.93714365487312784270e-5 + (0.58882975670265286526e-7 + (0.34414937110591753387e-9 + (0.18552853109751857859e-11 + 0.91160736711111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 30: {
+T t = 2*y100 - 61;
+return 0.61532500145144778048e-1 + (0.14344426411912015247e-2 + (0.97331446201016809696e-5 + (0.61711860507347175097e-7 + (0.36325987418295300221e-9 + (0.19681183310134518232e-11 + 0.96952238400000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 31: {
+T t = 2*y100 - 63;
+return 0.64440817576653297993e-1 + (0.14741275456383131151e-2 + (0.10112293819576437838e-4 + (0.64698236605933246196e-7 + (0.38353412915303665586e-9 + (0.20881176114385120186e-11 + 0.10310784480000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 32: {
+T t = 2*y100 - 65;
+return 0.67430045633130393282e-1 + (0.15153655418916540370e-2 + (0.10509857606888328667e-4 + (0.67851706529363332855e-7 + (0.40504602194811140006e-9 + (0.22157325110542534469e-11 + 0.10964842115555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 33: {
+T t = 2*y100 - 67;
+return 0.70503365513338850709e-1 + (0.15582323336495709827e-2 + (0.10926868866865231089e-4 + (0.71182482239613507542e-7 + (0.42787405890153386710e-9 + (0.23514379522274416437e-11 + 0.11659571751111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 34: {
+T t = 2*y100 - 69;
+return 0.73664114037944596353e-1 + (0.16028078812438820413e-2 + (0.11364423678778207991e-4 + (0.74701423097423182009e-7 + (0.45210162777476488324e-9 + (0.24957355004088569134e-11 + 0.12397238257777777778e-13 * t) * t) * t) * t) * t) * t;
+}
+case 35: {
+T t = 2*y100 - 71;
+return 0.76915792420819562379e-1 + (0.16491766623447889354e-2 + (0.11823685320041302169e-4 + (0.78420075993781544386e-7 + (0.47781726956916478925e-9 + (0.26491544403815724749e-11 + 0.13180196462222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 36: {
+T t = 2*y100 - 73;
+return 0.80262075578094612819e-1 + (0.16974279491709504117e-2 + (0.12305888517309891674e-4 + (0.82350717698979042290e-7 + (0.50511496109857113929e-9 + (0.28122528497626897696e-11 + 0.14010889635555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 37: {
+T t = 2*y100 - 75;
+return 0.83706822008980357446e-1 + (0.17476561032212656962e-2 + (0.12812343958540763368e-4 + (0.86506399515036435592e-7 + (0.53409440823869467453e-9 + (0.29856186620887555043e-11 + 0.14891851591111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 38: {
+T t = 2*y100 - 77;
+return 0.87254084284461718231e-1 + (0.17999608886001962327e-2 + (0.13344443080089492218e-4 + (0.90900994316429008631e-7 + (0.56486134972616465316e-9 + (0.31698707080033956934e-11 + 0.15825697795555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 39: {
+T t = 2*y100 - 79;
+return 0.90908120182172748487e-1 + (0.18544478050657699758e-2 + (0.13903663143426120077e-4 + (0.95549246062549906177e-7 + (0.59752787125242054315e-9 + (0.33656597366099099413e-11 + 0.16815130613333333333e-13 * t) * t) * t) * t) * t) * t;
+}
+case 40: {
+T t = 2*y100 - 81;
+return 0.94673404508075481121e-1 + (0.19112284419887303347e-2 + (0.14491572616545004930e-4 + (0.10046682186333613697e-6 + (0.63221272959791000515e-9 + (0.35736693975589130818e-11 + 0.17862931591111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 41: {
+T t = 2*y100 - 83;
+return 0.98554641648004456555e-1 + (0.19704208544725622126e-2 + (0.15109836875625443935e-4 + (0.10567036667675984067e-6 + (0.66904168640019354565e-9 + (0.37946171850824333014e-11 + 0.18971959040000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 42: {
+T t = 2*y100 - 85;
+return 0.10255677889470089531e0 + (0.20321499629472857418e-2 + (0.15760224242962179564e-4 + (0.11117756071353507391e-6 + (0.70814785110097658502e-9 + (0.40292553276632563925e-11 + 0.20145143075555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 43: {
+T t = 2*y100 - 87;
+return 0.10668502059865093318e0 + (0.20965479776148731610e-2 + (0.16444612377624983565e-4 + (0.11700717962026152749e-6 + (0.74967203250938418991e-9 + (0.42783716186085922176e-11 + 0.21385479360000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 44: {
+T t = 2*y100 - 89;
+return 0.11094484319386444474e0 + (0.21637548491908170841e-2 + (0.17164995035719657111e-4 + (0.12317915750735938089e-6 + (0.79376309831499633734e-9 + (0.45427901763106353914e-11 + 0.22696025653333333333e-13 * t) * t) * t) * t) * t) * t;
+}
+case 45: {
+T t = 2*y100 - 91;
+return 0.11534201115268804714e0 + (0.22339187474546420375e-2 + (0.17923489217504226813e-4 + (0.12971465288245997681e-6 + (0.84057834180389073587e-9 + (0.48233721206418027227e-11 + 0.24079890062222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 46: {
+T t = 2*y100 - 93;
+return 0.11988259392684094740e0 + (0.23071965691918689601e-2 + (0.18722342718958935446e-4 + (0.13663611754337957520e-6 + (0.89028385488493287005e-9 + (0.51210161569225846701e-11 + 0.25540227111111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 47: {
+T t = 2*y100 - 95;
+return 0.12457298393509812907e0 + (0.23837544771809575380e-2 + (0.19563942105711612475e-4 + (0.14396736847739470782e-6 + (0.94305490646459247016e-9 + (0.54366590583134218096e-11 + 0.27080225920000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 48: {
+T t = 2*y100 - 97;
+return 0.12941991566142438816e0 + (0.24637684719508859484e-2 + (0.20450821127475879816e-4 + (0.15173366280523906622e-6 + (0.99907632506389027739e-9 + (0.57712760311351625221e-11 + 0.28703099555555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 49: {
+T t = 2*y100 - 99;
+return 0.13443048593088696613e0 + (0.25474249981080823877e-2 + (0.21385669591362915223e-4 + (0.15996177579900443030e-6 + (0.10585428844575134013e-8 + (0.61258809536787882989e-11 + 0.30412080142222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 50: {
+T t = 2*y100 - 101;
+return 0.13961217543434561353e0 + (0.26349215871051761416e-2 + (0.22371342712572567744e-4 + (0.16868008199296822247e-6 + (0.11216596910444996246e-8 + (0.65015264753090890662e-11 + 0.32210394506666666666e-13 * t) * t) * t) * t) * t) * t;
+}
+case 51: {
+T t = 2*y100 - 103;
+return 0.14497287157673800690e0 + (0.27264675383982439814e-2 + (0.23410870961050950197e-4 + (0.17791863939526376477e-6 + (0.11886425714330958106e-8 + (0.68993039665054288034e-11 + 0.34101266222222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 52: {
+T t = 2*y100 - 105;
+return 0.15052089272774618151e0 + (0.28222846410136238008e-2 + (0.24507470422713397006e-4 + (0.18770927679626136909e-6 + (0.12597184587583370712e-8 + (0.73203433049229821618e-11 + 0.36087889048888888890e-13 * t) * t) * t) * t) * t) * t;
+}
+case 53: {
+T t = 2*y100 - 107;
+return 0.15626501395774612325e0 + (0.29226079376196624949e-2 + (0.25664553693768450545e-4 + (0.19808568415654461964e-6 + (0.13351257759815557897e-8 + (0.77658124891046760667e-11 + 0.38173420035555555555e-13 * t) * t) * t) * t) * t) * t;
+}
+case 54: {
+T t = 2*y100 - 109;
+return 0.16221449434620737567e0 + (0.30276865332726475672e-2 + (0.26885741326534564336e-4 + (0.20908350604346384143e-6 + (0.14151148144240728728e-8 + (0.82369170665974313027e-11 + 0.40360957457777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 55: {
+T t = 2*y100 - 111;
+return 0.16837910595412130659e0 + (0.31377844510793082301e-2 + (0.28174873844911175026e-4 + (0.22074043807045782387e-6 + (0.14999481055996090039e-8 + (0.87348993661930809254e-11 + 0.42653528977777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 56: {
+T t = 2*y100 - 113;
+return 0.17476916455659369953e0 + (0.32531815370903068316e-2 + (0.29536024347344364074e-4 + (0.23309632627767074202e-6 + (0.15899007843582444846e-8 + (0.92610375235427359475e-11 + 0.45054073102222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 57: {
+T t = 2*y100 - 115;
+return 0.18139556223643701364e0 + (0.33741744168096996041e-2 + (0.30973511714709500836e-4 + (0.24619326937592290996e-6 + (0.16852609412267750744e-8 + (0.98166442942854895573e-11 + 0.47565418097777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 58: {
+T t = 2*y100 - 117;
+return 0.18826980194443664549e0 + (0.35010775057740317997e-2 + (0.32491914440014267480e-4 + (0.26007572375886319028e-6 + (0.17863299617388376116e-8 + (0.10403065638343878679e-10 + 0.50190265831111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 59: {
+T t = 2*y100 - 119;
+return 0.19540403413693967350e0 + (0.36342240767211326315e-2 + (0.34096085096200907289e-4 + (0.27479061117017637474e-6 + (0.18934228504790032826e-8 + (0.11021679075323598664e-10 + 0.52931171733333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 60: {
+T t = 2*y100 - 121;
+return 0.20281109560651886959e0 + (0.37739673859323597060e-2 + (0.35791165457592409054e-4 + (0.29038742889416172404e-6 + (0.20068685374849001770e-8 + (0.11673891799578381999e-10 + 0.55790523093333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 61: {
+T t = 2*y100 - 123;
+return 0.21050455062669334978e0 + (0.39206818613925652425e-2 + (0.37582602289680101704e-4 + (0.30691836231886877385e-6 + (0.21270101645763677824e-8 + (0.12361138551062899455e-10 + 0.58770520160000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 62: {
+T t = 2*y100 - 125;
+return 0.21849873453703332479e0 + (0.40747643554689586041e-2 + (0.39476163820986711501e-4 + (0.32443839970139918836e-6 + (0.22542053491518680200e-8 + (0.13084879235290858490e-10 + 0.61873153262222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 63: {
+T t = 2*y100 - 127;
+return 0.22680879990043229327e0 + (0.42366354648628516935e-2 + (0.41477956909656896779e-4 + (0.34300544894502810002e-6 + (0.23888264229264067658e-8 + (0.13846596292818514601e-10 + 0.65100183751111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 64: {
+T t = 2*y100 - 129;
+return 0.23545076536988703937e0 + (0.44067409206365170888e-2 + (0.43594444916224700881e-4 + (0.36268045617760415178e-6 + (0.25312606430853202748e-8 + (0.14647791812837903061e-10 + 0.68453122631111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 65: {
+T t = 2*y100 - 131;
+return 0.24444156740777432838e0 + (0.45855530511605787178e-2 + (0.45832466292683085475e-4 + (0.38352752590033030472e-6 + (0.26819103733055603460e-8 + (0.15489984390884756993e-10 + 0.71933206364444444445e-13 * t) * t) * t) * t) * t) * t;
+}
+case 66: {
+T t = 2*y100 - 133;
+return 0.25379911500634264643e0 + (0.47735723208650032167e-2 + (0.48199253896534185372e-4 + (0.40561404245564732314e-6 + (0.28411932320871165585e-8 + (0.16374705736458320149e-10 + 0.75541379822222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 67: {
+T t = 2*y100 - 135;
+return 0.26354234756393613032e0 + (0.49713289477083781266e-2 + (0.50702455036930367504e-4 + (0.42901079254268185722e-6 + (0.30095422058900481753e-8 + (0.17303497025347342498e-10 + 0.79278273368888888890e-13 * t) * t) * t) * t) * t) * t;
+}
+case 68: {
+T t = 2*y100 - 137;
+return 0.27369129607732343398e0 + (0.51793846023052643767e-2 + (0.53350152258326602629e-4 + (0.45379208848865015485e-6 + (0.31874057245814381257e-8 + (0.18277905010245111046e-10 + 0.83144182364444444445e-13 * t) * t) * t) * t) * t) * t;
+}
+case 69: {
+T t = 2*y100 - 139;
+return 0.28426714781640316172e0 + (0.53983341916695141966e-2 + (0.56150884865255810638e-4 + (0.48003589196494734238e-6 + (0.33752476967570796349e-8 + (0.19299477888083469086e-10 + 0.87139049137777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 70: {
+T t = 2*y100 - 141;
+return 0.29529231465348519920e0 + (0.56288077305420795663e-2 + (0.59113671189913307427e-4 + (0.50782393781744840482e-6 + (0.35735475025851713168e-8 + (0.20369760937017070382e-10 + 0.91262442613333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 71: {
+T t = 2*y100 - 143;
+return 0.30679050522528838613e0 + (0.58714723032745403331e-2 + (0.62248031602197686791e-4 + (0.53724185766200945789e-6 + (0.37827999418960232678e-8 + (0.21490291930444538307e-10 + 0.95513539182222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 72: {
+T t = 2*y100 - 145;
+return 0.31878680111173319425e0 + (0.61270341192339103514e-2 + (0.65564012259707640976e-4 + (0.56837930287837738996e-6 + (0.40035151353392378882e-8 + (0.22662596341239294792e-10 + 0.99891109760000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 73: {
+T t = 2*y100 - 147;
+return 0.33130773722152622027e0 + (0.63962406646798080903e-2 + (0.69072209592942396666e-4 + (0.60133006661885941812e-6 + (0.42362183765883466691e-8 + (0.23888182347073698382e-10 + 0.10439349811555555556e-12 * t) * t) * t) * t) * t) * t;
+}
+case 74: {
+T t = 2*y100 - 149;
+return 0.34438138658041336523e0 + (0.66798829540414007258e-2 + (0.72783795518603561144e-4 + (0.63619220443228800680e-6 + (0.44814499336514453364e-8 + (0.25168535651285475274e-10 + 0.10901861383111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 75: {
+T t = 2*y100 - 151;
+return 0.35803744972380175583e0 + (0.69787978834882685031e-2 + (0.76710543371454822497e-4 + (0.67306815308917386747e-6 + (0.47397647975845228205e-8 + (0.26505114141143050509e-10 + 0.11376390933333333333e-12 * t) * t) * t) * t) * t) * t;
+}
+case 76: {
+T t = 2*y100 - 153;
+return 0.37230734890119724188e0 + (0.72938706896461381003e-2 + (0.80864854542670714092e-4 + (0.71206484718062688779e-6 + (0.50117323769745883805e-8 + (0.27899342394100074165e-10 + 0.11862637614222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 77: {
+T t = 2*y100 - 155;
+return 0.38722432730555448223e0 + (0.76260375162549802745e-2 + (0.85259785810004603848e-4 + (0.75329383305171327677e-6 + (0.52979361368388119355e-8 + (0.29352606054164086709e-10 + 0.12360253370666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 78: {
+T t = 2*y100 - 157;
+return 0.40282355354616940667e0 + (0.79762880915029728079e-2 + (0.89909077342438246452e-4 + (0.79687137961956194579e-6 + (0.55989731807360403195e-8 + (0.30866246101464869050e-10 + 0.12868841946666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 79: {
+T t = 2*y100 - 159;
+return 0.41914223158913787649e0 + (0.83456685186950463538e-2 + (0.94827181359250161335e-4 + (0.84291858561783141014e-6 + (0.59154537751083485684e-8 + (0.32441553034347469291e-10 + 0.13387957943111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 80: {
+T t = 2*y100 - 161;
+return 0.43621971639463786896e0 + (0.87352841828289495773e-2 + (0.10002929142066799966e-3 + (0.89156148280219880024e-6 + (0.62480008150788597147e-8 + (0.34079760983458878910e-10 + 0.13917107176888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 81: {
+T t = 2*y100 - 163;
+return 0.45409763548534330981e0 + (0.91463027755548240654e-2 + (0.10553137232446167258e-3 + (0.94293113464638623798e-6 + (0.65972492312219959885e-8 + (0.35782041795476563662e-10 + 0.14455745872000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 82: {
+T t = 2*y100 - 165;
+return 0.47282001668512331468e0 + (0.95799574408860463394e-2 + (0.11135019058000067469e-3 + (0.99716373005509038080e-6 + (0.69638453369956970347e-8 + (0.37549499088161345850e-10 + 0.15003280712888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 83: {
+T t = 2*y100 - 167;
+return 0.49243342227179841649e0 + (0.10037550043909497071e-1 + (0.11750334542845234952e-3 + (0.10544006716188967172e-5 + (0.73484461168242224872e-8 + (0.39383162326435752965e-10 + 0.15559069118222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 84: {
+T t = 2*y100 - 169;
+return 0.51298708979209258326e0 + (0.10520454564612427224e-1 + (0.12400930037494996655e-3 + (0.11147886579371265246e-5 + (0.77517184550568711454e-8 + (0.41283980931872622611e-10 + 0.16122419680000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 85: {
+T t = 2*y100 - 171;
+return 0.53453307979101369843e0 + (0.11030120618800726938e-1 + (0.13088741519572269581e-3 + (0.11784797595374515432e-5 + (0.81743383063044825400e-8 + (0.43252818449517081051e-10 + 0.16692592640000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 86: {
+T t = 2*y100 - 173;
+return 0.55712643071169299478e0 + (0.11568077107929735233e-1 + (0.13815797838036651289e-3 + (0.12456314879260904558e-5 + (0.86169898078969313597e-8 + (0.45290446811539652525e-10 + 0.17268801084444444444e-12 * t) * t) * t) * t) * t) * t;
+}
+case 87: {
+T t = 2*y100 - 175;
+return 0.58082532122519320968e0 + (0.12135935999503877077e-1 + (0.14584223996665838559e-3 + (0.13164068573095710742e-5 + (0.90803643355106020163e-8 + (0.47397540713124619155e-10 + 0.17850211608888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 88: {
+T t = 2*y100 - 177;
+return 0.60569124025293375554e0 + (0.12735396239525550361e-1 + (0.15396244472258863344e-3 + (0.13909744385382818253e-5 + (0.95651595032306228245e-8 + (0.49574672127669041550e-10 + 0.18435945564444444444e-12 * t) * t) * t) * t) * t) * t;
+}
+case 89: {
+T t = 2*y100 - 179;
+return 0.63178916494715716894e0 + (0.13368247798287030927e-1 + (0.16254186562762076141e-3 + (0.14695084048334056083e-5 + (0.10072078109604152350e-7 + (0.51822304995680707483e-10 + 0.19025081422222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 90: {
+T t = 2*y100 - 181;
+return 0.65918774689725319200e0 + (0.14036375850601992063e-1 + (0.17160483760259706354e-3 + (0.15521885688723188371e-5 + (0.10601827031535280590e-7 + (0.54140790105837520499e-10 + 0.19616655146666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 91: {
+T t = 2*y100 - 183;
+return 0.68795950683174433822e0 + (0.14741765091365869084e-1 + (0.18117679143520433835e-3 + (0.16392004108230585213e-5 + (0.11155116068018043001e-7 + (0.56530360194925690374e-10 + 0.20209663662222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 92: {
+T t = 2*y100 - 185;
+return 0.71818103808729967036e0 + (0.15486504187117112279e-1 + (0.19128428784550923217e-3 + (0.17307350969359975848e-5 + (0.11732656736113607751e-7 + (0.58991125287563833603e-10 + 0.20803065333333333333e-12 * t) * t) * t) * t) * t) * t;
+}
+case 93: {
+T t = 2*y100 - 187;
+return 0.74993321911726254661e0 + (0.16272790364044783382e-1 + (0.20195505163377912645e-3 + (0.18269894883203346953e-5 + (0.12335161021630225535e-7 + (0.61523068312169087227e-10 + 0.21395783431111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 94: {
+T t = 2*y100 - 189;
+return 0.78330143531283492729e0 + (0.17102934132652429240e-1 + (0.21321800585063327041e-3 + (0.19281661395543913713e-5 + (0.12963340087354341574e-7 + (0.64126040998066348872e-10 + 0.21986708942222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 95: {
+T t = 2*y100 - 191;
+return 0.81837581041023811832e0 + (0.17979364149044223802e-1 + (0.22510330592753129006e-3 + (0.20344732868018175389e-5 + (0.13617902941839949718e-7 + (0.66799760083972474642e-10 + 0.22574701262222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 96: {
+T t = 2*y100 - 193;
+return 0.85525144775685126237e0 + (0.18904632212547561026e-1 + (0.23764237370371255638e-3 + (0.21461248251306387979e-5 + (0.14299555071870523786e-7 + (0.69543803864694171934e-10 + 0.23158593688888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 97: {
+T t = 2*y100 - 195;
+return 0.89402868170849933734e0 + (0.19881418399127202569e-1 + (0.25086793128395995798e-3 + (0.22633402747585233180e-5 + (0.15008997042116532283e-7 + (0.72357609075043941261e-10 + 0.23737194737777777778e-12 * t) * t) * t) * t) * t) * t;
+}
+case 98: {
+T t = 2*y100 - 197;
+return 0.93481333942870796363e0 + (0.20912536329780368893e-1 + (0.26481403465998477969e-3 + (0.23863447359754921676e-5 + (0.15746923065472184451e-7 + (0.75240468141720143653e-10 + 0.24309291271111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 99: {
+T t = 2*y100 - 199;
+return 0.97771701335885035464e0 + (0.22000938572830479551e-1 + (0.27951610702682383001e-3 + (0.25153688325245314530e-5 + (0.16514019547822821453e-7 + (0.78191526829368231251e-10 + 0.24873652355555555556e-12 * t) * t) * t) * t) * t) * t;
+}
+  }
+  // we only get here if y = 1, i.e. |x| < 4*eps, in which case
+  // erfcx is within 1e-15 of 1..
+  return 1.0;
+}
+
+template 
+C10_HOST_DEVICE inline typename std::enable_if_t, T>
+calc_erfcx(T x)
+{
+  if (at::_isnan(x)) {
+    return x;
+  }
+
+  if (x >= 0) {
+    if (x > 50) { // continued-fraction expansion is faster
+      const T ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+      if (x > 5e7) { // 1-term expansion, important to avoid overflow
+        return ispi / x;
+      }
+      /* 5-term expansion (rely on compiler for CSE), simplified from:
+                ispi / (x+0.5/(x+1/(x+1.5/(x+2/x))))  */
+      return ispi*((x*x) * (x*x+4.5) + 2) / (x * ((x*x) * (x*x+5) + 3.75));
+    }
+    return erfcx_y100(400/(4+x));
+  }
+  else {
+    if (x < -26.7) {
+      return std::numeric_limits::infinity();
+    }
+    else if (x < -6.1) {
+      return 2*exp(x*x);
+    }
+    else {
+      return 2*exp(x*x) - erfcx_y100(400/(4-x));
+    }
+  }
+}
+
+/*
+ * Logarithm of Gaussian cumulative distribution function.
+
+ * This implementation of log_ndtr and its helper functions
+ * follow SciPy's implementation
+ * See NOTICE for the licenses.
+ */
+template 
+inline C10_HOST_DEVICE T calc_log_ndtr(T x) {
+  T t = x * c10::frac_sqrt_2;
+  if (x < T{-1.0}) {
+    return std::log(calc_erfcx(-t) / 2) - t * t;
+  } else {
+    return std::log1p(-std::erfc(t) / 2);
+  }
+}
+
+template
+inline C10_HOST_DEVICE T airy_ai_forward(T x) {
+    static const T AN[] = {
+            +3.46538101525629032477e-01,
+            +1.20075952739645805542e+01,
+            +7.62796053615234516538e+01,
+            +1.68089224934630576269e+02,
+            +1.59756391350164413639e+02,
+            +7.05360906840444183113e+01,
+            +1.40264691163389668864e+01,
+            +9.99999999999999995305e-01,
+    };
+
+    static const T AD[] = {
+            +5.67594532638770212846e-01,
+            +1.47562562584847203173e+01,
+            +8.45138970141474626562e+01,
+            +1.77318088145400459522e+02,
+            +1.64234692871529701831e+02,
+            +7.14778400825575695274e+01,
+            +1.40959135607834029598e+01,
+            +1.00000000000000000470e+00,
+    };
+
+    static const T AFN[] = {
+            -1.31696323418331795333e-01,
+            -6.26456544431912369773e-01,
+            -6.93158036036933542233e-01,
+            -2.79779981545119124951e-01,
+            -4.91900132609500318020e-02,
+            -4.06265923594885404393e-03,
+            -1.59276496239262096340e-04,
+            -2.77649108155232920844e-06,
+            -1.67787698489114633780e-08,
+    };
+
+    static const T AFD[] = {
+            +1.33560420706553243746e+01,
+            +3.26825032795224613948e+01,
+            +2.67367040941499554804e+01,
+            +9.18707402907259625840e+00,
+            +1.47529146771666414581e+00,
+            +1.15687173795188044134e-01,
+            +4.40291641615211203805e-03,
+            +7.54720348287414296618e-05,
+            +4.51850092970580378464e-07,
+    };
+
+    static const T AGN[] = {
+            +1.97339932091685679179e-02,
+            +3.91103029615688277255e-01,
+            +1.06579897599595591108e+00,
+            +9.39169229816650230044e-01,
+            +3.51465656105547619242e-01,
+            +6.33888919628925490927e-02,
+            +5.85804113048388458567e-03,
+            +2.82851600836737019778e-04,
+            +6.98793669997260967291e-06,
+            +8.11789239554389293311e-08,
+            +3.41551784765923618484e-10,
+    };
+
+    static const T AGD[] = {
+            +9.30892908077441974853e+00,
+            +1.98352928718312140417e+01,
+            +1.55646628932864612953e+01,
+            +5.47686069422975497931e+00,
+            +9.54293611618961883998e-01,
+            +8.64580826352392193095e-02,
+            +4.12656523824222607191e-03,
+            +1.01259085116509135510e-04,
+            +1.17166733214413521882e-06,
+            +4.91834570062930015649e-09,
+    };
+
+    int domain_flag = 0;
+
+    T ai;
+
+    if (std::isinf(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    if (x > T(103.892)) {
+        return T(0.0);
+    }
+
+    T f;
+    T g;
+    T k;
+
+    if (x < T(-2.09)) {
+        T z = T(1.0) / (T(-2.0) * x * std::sqrt(-x) / T(3.0));
+
+        T afn = 0.0;
+
+        for (uint8_t index = 0; index <= 8; index++) {
+            afn = afn * (z * z) + AFN[index];
+        }
+
+        T afd = 0.0;
+
+        for (uint8_t index = 0; index <= 8; index++) {
+            afd = afd * (z * z) + AFD[index];
+        }
+
+        T agn = 0.0;
+
+        for (uint8_t index = 0; index <= 10 + 0; index++) {
+            agn = agn * (z * z) + AGN[index];
+        }
+
+        T agd = 0.0;
+
+        for (uint8_t index = 0; index <= 10 - 1; index++) {
+            agd = agd * (z * z) + AGD[index];
+        }
+
+        T t = T(-2.0) * x * std::sqrt(-x) / T(3.0) + T(0.25) * c10::pi;
+
+        return T(5.64189583547756286948e-01) / std::sqrt(std::sqrt(-x)) * (std::sin(t) * (T(1.0) + z * z * afn / afd) - std::cos(t) * (z * agn / agd));
+    }
+
+    if (x >= T(2.09)) {
+        domain_flag = 5;
+
+        T zeta = T(2.0) * x * std::sqrt(x) / T(3.0);
+
+        T an = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            an = an * (T(1.0) / zeta) + AN[index];
+        }
+
+        T ad = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            ad = ad * (T(1.0) / zeta) + AD[index];
+        }
+
+        ai = T(5.64189583547756286948e-01) * (an / ad) / (T(2.0) * std::sqrt(std::sqrt(x)) * std::exp(zeta));
+
+        if (x > T(8.3203353)) {
+            return ai;
+        }
+    }
+
+    f = 1.0;
+    g = x;
+    k = 1.0;
+
+    T m = 1.0;
+    T n = x;
+    T t = 1.0;
+    T z = x * x * x;
+
+    while (t > std::numeric_limits::epsilon()) {
+        m *= z;
+        k += T(1.0);
+        m /= k;
+        n *= z;
+        k += T(1.0);
+        n /= k;
+        m /= k;
+        f += m;
+        k += T(1.0);
+        n /= k;
+        g += n;
+
+        t = std::abs(m / f);
+    }
+
+    if ((domain_flag & 1) == 0) {
+        return T(0.355028053887817239260) * f - T(0.258819403792806798405) * g;
+    }
+
+    return ai;
+} // T airy_ai(T x)
+
+template
+inline C10_HOST_DEVICE T bessel_j0_forward(T x) {
+    static const T PP[] = {
+            +7.96936729297347051624e-04,
+            +8.28352392107440799803e-02,
+            +1.23953371646414299388e+00,
+            +5.44725003058768775090e+00,
+            +8.74716500199817011941e+00,
+            +5.30324038235394892183e+00,
+            +9.99999999999999997821e-01,
+    };
+
+    static const T PQ[] = {
+            +9.24408810558863637013e-04,
+            +8.56288474354474431428e-02,
+            +1.25352743901058953537e+00,
+            +5.47097740330417105182e+00,
+            +8.76190883237069594232e+00,
+            +5.30605288235394617618e+00,
+            +1.00000000000000000218e+00,
+    };
+
+    static const T QP[] = {
+            -1.13663838898469149931e-02,
+            -1.28252718670509318512e+00,
+            -1.95539544257735972385e+01,
+            -9.32060152123768231369e+01,
+            -1.77681167980488050595e+02,
+            -1.47077505154951170175e+02,
+            -5.14105326766599330220e+01,
+            -6.05014350600728481186e+00,
+    };
+
+    static const T QQ[] = {
+            +6.43178256118178023184e+01,
+            +8.56430025976980587198e+02,
+            +3.88240183605401609683e+03,
+            +7.24046774195652478189e+03,
+            +5.93072701187316984827e+03,
+            +2.06209331660327847417e+03,
+            +2.42005740240291393179e+02,
+    };
+
+    static const T RP[] = {
+            -4.79443220978201773821e+09,
+            +1.95617491946556577543e+12,
+            -2.49248344360967716204e+14,
+            +9.70862251047306323952e+15,
+    };
+
+    static const T RQ[] = {
+            +4.99563147152651017219e+02,
+            +1.73785401676374683123e+05,
+            +4.84409658339962045305e+07,
+            +1.11855537045356834862e+10,
+            +2.11277520115489217587e+12,
+            +3.10518229857422583814e+14,
+            +3.18121955943204943306e+16,
+            +1.71086294081043136091e+18,
+    };
+
+    if (x < T(0)) {
+        x = -x;
+    }
+
+    if (x <= T(5.0)) {
+        if (x < T(0.00001)) {
+            return T(1.0) - x * x / T(4.0);
+        }
+
+        T rp = 0.0;
+
+        for (uint8_t index = 0; index <= 3; index++) {
+            rp = rp * (x * x) + RP[index];
+        }
+
+        T rq = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            rq = rq * (x * x) + RQ[index];
+        }
+
+        return (x * x - T(5.78318596294678452118e+00)) * (x * x - T(3.04712623436620863991e+01)) * rp / rq;
+    }
+
+    T pp = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pp = pp * (T(25.0) / (x * x)) + PP[index];
+    }
+
+    T pq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pq = pq * (T(25.0) / (x * x)) + PQ[index];
+    }
+
+    T qp = 0.0;
+
+    for (uint8_t index = 0; index <= 7; index++) {
+        qp = qp * (T(25.0) / (x * x)) + QP[index];
+    }
+
+    T qq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        qq = qq * (T(25.0) / (x * x)) + QQ[index];
+    }
+
+    return (pp / pq * std::cos(x - T(0.785398163397448309615660845819875721)) - T(5.0) / x * (qp / qq) * std::sin(x - T(0.785398163397448309615660845819875721))) * T(0.797884560802865355879892119868763737) / std::sqrt(x);
+} // bessel_j0_forward(T x)
+
+template
+inline C10_HOST_DEVICE T bessel_j1_forward(T x) {
+    static const T PP[] = {
+            +7.62125616208173112003e-04,
+            +7.31397056940917570436e-02,
+            +1.12719608129684925192e+00,
+            +5.11207951146807644818e+00,
+            +8.42404590141772420927e+00,
+            +5.21451598682361504063e+00,
+            +1.00000000000000000254e+00,
+    };
+
+    static const T PQ[] = {
+            +5.71323128072548699714e-04,
+            +6.88455908754495404082e-02,
+            +1.10514232634061696926e+00,
+            +5.07386386128601488557e+00,
+            +8.39985554327604159757e+00,
+            +5.20982848682361821619e+00,
+            +9.99999999999999997461e-01,
+    };
+
+    static const T QP[] = {
+            +5.10862594750176621635e-02,
+            +4.98213872951233449420e+00,
+            +7.58238284132545283818e+01,
+            +3.66779609360150777800e+02,
+            +7.10856304998926107277e+02,
+            +5.97489612400613639965e+02,
+            +2.11688757100572135698e+02,
+            +2.52070205858023719784e+01,
+    };
+
+    static const T QQ[] = {
+            +7.42373277035675149943e+01,
+            +1.05644886038262816351e+03,
+            +4.98641058337653607651e+03,
+            +9.56231892404756170795e+03,
+            +7.99704160447350683650e+03,
+            +2.82619278517639096600e+03,
+            +3.36093607810698293419e+02,
+    };
+
+    static const T RP[] = {
+            -8.99971225705559398224e+08,
+            +4.52228297998194034323e+11,
+            -7.27494245221818276015e+13,
+            +3.68295732863852883286e+15,
+    };
+
+    static const T RQ[] = {
+            +6.20836478118054335476e+02,
+            +2.56987256757748830383e+05,
+            +8.35146791431949253037e+07,
+            +2.21511595479792499675e+10,
+            +4.74914122079991414898e+12,
+            +7.84369607876235854894e+14,
+            +8.95222336184627338078e+16,
+            +5.32278620332680085395e+18,
+    };
+
+    if (x < T(0.0)) {
+        return -bessel_j1_forward(-x);
+    }
+
+    if (x <= T(5.0)) {
+        T rp = 0.0;
+
+        for (uint8_t index = 0; index <= 3; index++) {
+            rp = rp * (x * x) + RP[index];
+        }
+
+        T rq = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            rq = rq * (x * x) + RQ[index];
+        }
+
+        return rp / rq * x * (x * x - T(1.46819706421238932572e+01)) * (x * x - T(4.92184563216946036703e+01));
+    }
+
+    T pp = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pp = pp * (T(5.0) / x * (T(5.0) / x)) + PP[index];
+    }
+
+    T pq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pq = pq * (T(5.0) / x * (T(5.0) / x)) + PQ[index];
+    }
+
+    T qp = 0.0;
+
+    for (uint8_t index = 0; index <= 7; index++) {
+        qp = qp * (T(5.0) / x * (T(5.0) / x)) + QP[index];
+    }
+
+    T qq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        qq = qq * (T(5.0) / x * (T(5.0) / x)) + QQ[index];
+    }
+
+    return (pp / pq * std::cos(x - T(2.356194490192344928846982537459627163)) - T(5.0) / x * (qp / qq) * std::sin(x - T(2.356194490192344928846982537459627163))) * T(0.797884560802865355879892119868763737) / std::sqrt(x);
+} // bessel_j1_forward(T x)
+
+template
+inline C10_HOST_DEVICE T bessel_y0_forward(T x) {
+    static const T PP[] = {
+            +7.96936729297347051624e-04,
+            +8.28352392107440799803e-02,
+            +1.23953371646414299388e+00,
+            +5.44725003058768775090e+00,
+            +8.74716500199817011941e+00,
+            +5.30324038235394892183e+00,
+            +9.99999999999999997821e-01,
+    };
+
+    static const T PQ[] = {
+            +9.24408810558863637013e-04,
+            +8.56288474354474431428e-02,
+            +1.25352743901058953537e+00,
+            +5.47097740330417105182e+00,
+            +8.76190883237069594232e+00,
+            +5.30605288235394617618e+00,
+            +1.00000000000000000218e+00,
+    };
+
+    static const T QP[] = {
+            -1.13663838898469149931e-02,
+            -1.28252718670509318512e+00,
+            -1.95539544257735972385e+01,
+            -9.32060152123768231369e+01,
+            -1.77681167980488050595e+02,
+            -1.47077505154951170175e+02,
+            -5.14105326766599330220e+01,
+            -6.05014350600728481186e+00,
+    };
+
+    static const T QQ[] = {
+            +6.43178256118178023184e+01,
+            +8.56430025976980587198e+02,
+            +3.88240183605401609683e+03,
+            +7.24046774195652478189e+03,
+            +5.93072701187316984827e+03,
+            +2.06209331660327847417e+03,
+            +2.42005740240291393179e+02,
+    };
+
+    static const T YP[] = {
+            +1.55924367855235737965e+04,
+            -1.46639295903971606143e+07,
+            +5.43526477051876500413e+09,
+            -9.82136065717911466409e+11,
+            +8.75906394395366999549e+13,
+            -3.46628303384729719441e+15,
+            +4.42733268572569800351e+16,
+            -1.84950800436986690637e+16,
+    };
+
+    static const T YQ[] = {
+            +1.04128353664259848412e+03,
+            +6.26107330137134956842e+05,
+            +2.68919633393814121987e+08,
+            +8.64002487103935000337e+10,
+            +2.02979612750105546709e+13,
+            +3.17157752842975028269e+15,
+            +2.50596256172653059228e+17,
+    };
+
+    if (x <= T(5.0)) {
+        if (x == T(0.0)) {
+            return -std::numeric_limits::infinity();
+        }
+
+        if (x < T(0.0)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        T yp = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            yp = yp * (x * x) + YP[index];
+        }
+
+        T yq = 0.0;
+
+        for (uint8_t index = 0; index <= 6; index++) {
+            yq = yq * (x * x) + YQ[index];
+        }
+
+        return yp / yq + (T(0.636619772367581343075535053490057448) * std::log(x) * bessel_j0_forward(x));
+    }
+
+    T pp = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pp = pp * (T(25.0) / (x * x)) + PP[index];
+    }
+
+    T pq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pq = pq * (T(25.0) / (x * x)) + PQ[index];
+    }
+
+    T qp = 0.0;
+
+    for (uint8_t index = 0; index <= 7; index++) {
+        qp = qp * (T(25.0) / (x * x)) + QP[index];
+    }
+
+    T qq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        qq = qq * (T(25.0) / (x * x)) + QQ[index];
+    }
+
+    return (pp / pq * std::sin(x - T(0.785398163397448309615660845819875721)) + T(5.0) / x * (qp / qq) * std::cos(x - T(0.785398163397448309615660845819875721))) * T(0.797884560802865355879892119868763737) / std::sqrt(x);
+} // bessel_y0_forward(T x)
+
+template
+inline C10_HOST_DEVICE T bessel_y1_forward(T x) {
+    static const T PP[] = {
+            +7.62125616208173112003e-04,
+            +7.31397056940917570436e-02,
+            +1.12719608129684925192e+00,
+            +5.11207951146807644818e+00,
+            +8.42404590141772420927e+00,
+            +5.21451598682361504063e+00,
+            +1.00000000000000000254e+00,
+    };
+
+    static const T PQ[] = {
+            +5.71323128072548699714e-04,
+            +6.88455908754495404082e-02,
+            +1.10514232634061696926e+00,
+            +5.07386386128601488557e+00,
+            +8.39985554327604159757e+00,
+            +5.20982848682361821619e+00,
+            +9.99999999999999997461e-01,
+    };
+
+    static const T QP[] = {
+            +5.10862594750176621635e-02,
+            +4.98213872951233449420e+00,
+            +7.58238284132545283818e+01,
+            +3.66779609360150777800e+02,
+            +7.10856304998926107277e+02,
+            +5.97489612400613639965e+02,
+            +2.11688757100572135698e+02,
+            +2.52070205858023719784e+01,
+    };
+
+    static const T QQ[] = {
+            +7.42373277035675149943e+01,
+            +1.05644886038262816351e+03,
+            +4.98641058337653607651e+03,
+            +9.56231892404756170795e+03,
+            +7.99704160447350683650e+03,
+            +2.82619278517639096600e+03,
+            +3.36093607810698293419e+02,
+    };
+
+    static const T YP[] = {
+            +1.26320474790178026440e+09,
+            -6.47355876379160291031e+11,
+            +1.14509511541823727583e+14,
+            -8.12770255501325109621e+15,
+            +2.02439475713594898196e+17,
+            -7.78877196265950026825e+17,
+    };
+
+    static const T YQ[] = {
+            +5.94301592346128195359e+02,
+            +2.35564092943068577943e+05,
+            +7.34811944459721705660e+07,
+            +1.87601316108706159478e+10,
+            +3.88231277496238566008e+12,
+            +6.20557727146953693363e+14,
+            +6.87141087355300489866e+16,
+            +3.97270608116560655612e+18,
+    };
+
+    if (x <= T(5.0)) {
+        if (x == T(0.0)) {
+            return -std::numeric_limits::infinity();
+        }
+
+        if (x <= T(0.0)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        T yp = 0.0;
+
+        for (uint8_t index = 0; index <= 5; index++) {
+            yp = yp * (x * x) + YP[index];
+        }
+
+        T yq = 0.0;
+
+        for (uint8_t index = 0; index <= 7; index++) {
+            yq = yq * (x * x) + YQ[index];
+        }
+
+        return x * (yp / yq) + (T(0.636619772367581343075535053490057448) * (bessel_j1_forward(x) * std::log(x) - T(1.0) / x));
+    }
+
+    T pp = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pp = pp * (T(5.0) / x * (T(5.0) / x)) + PP[index];
+    }
+
+    T pq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        pq = pq * (T(5.0) / x * (T(5.0) / x)) + PQ[index];
+    }
+
+    T qp = 0.0;
+
+    for (uint8_t index = 0; index <= 7; index++) {
+        qp = qp * (T(5.0) / x * (T(5.0) / x)) + QP[index];
+    }
+
+    T qq = 0.0;
+
+    for (uint8_t index = 0; index <= 6; index++) {
+        qq = qq * (T(5.0) / x * (T(5.0) / x)) + QQ[index];
+    }
+
+    return (pp / pq * std::sin(x - T(2.356194490192344928846982537459627163)) + T(5.0) / x * (qp / qq) * std::cos(x - T(2.356194490192344928846982537459627163))) * T(0.797884560802865355879892119868763737) / std::sqrt(x);
+} // bessel_y1_forward(T x)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_t_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(1.0)) {
+        if (x > T(0.0) || n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if ((n > 6) && (std::abs(x) < T(1.0))) {
+        return std::cos(n * std::acos(x));
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x;
+    }
+
+    T p = T(1.0);
+    T q = x;
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // chebyshev_polynomial_t_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_t_forward(T x, T n) {
+    return chebyshev_polynomial_t_forward(x, static_cast(n));
+} // chebyshev_polynomial_t_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_u_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(1.0)) {
+        if (x > T(0.0) || n % 2 == 0) {
+            return n + 1;
+        }
+
+        return -(n + 1);
+    }
+
+    if ((n > 8) && (std::abs(x) < T(1.0))) {
+        if (std::sin(std::acos(x)) != T(0.0)) {
+            return std::sin((n + 1) * std::acos(x)) / std::sin(std::acos(x));
+        }
+
+        return (n + 1) * std::cos((n + 1) * std::acos(x)) / x;
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x;
+    }
+
+    T p = T(1.0);
+    T q = x + x;
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // chebyshev_polynomial_u_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_u_forward(T x, T n) {
+    return chebyshev_polynomial_u_forward(x, static_cast(n));
+} // chebyshev_polynomial_u_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_v_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(1.0)) {
+        if (x > T(0.0)) {
+            return T(1.0);
+        }
+
+        if (n % 2 == 0) {
+            return n + n + 1;
+        }
+
+        return -(n + n + 1);
+    }
+
+    if ((n > 8) && (std::abs(x) < T(1.0))) {
+        if (std::sin(std::acos(x) / T(2.0)) != T(1.0)) {
+            return std::cos((n + T(0.5)) * std::acos(x)) / std::cos(std::acos(x) / T(2.0));
+        }
+
+        if (n % 2 == 0) {
+            return n + n + 1;
+        }
+
+        return -(n + n + 1);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x - T(1.0);
+    }
+
+    T p = T(1.0);
+    T q = x + x - T(1.0);
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // chebyshev_polynomial_v_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_v_forward(T x, T n) {
+    return chebyshev_polynomial_v_forward(x, static_cast(n));
+} // chebyshev_polynomial_v_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_w_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(1.0)) {
+        if (x > T(0.0)) {
+            return n + n + 1;
+        }
+
+        if (n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if ((n > 8) && (std::abs(x) < T(1.0))) {
+        if (std::cos(std::acos(x) / T(2.0)) != T(1.0)) {
+            return std::sin((n + T(0.5)) * std::acos(x)) / std::sin(std::acos(x) / T(2.0));
+        }
+
+        if (x > T(0.0)) {
+            return n + n + 1;
+        }
+
+        if (n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x + T(1.0);
+    }
+
+    T p = T(1.0);
+    T q = x + x + T(1.0);
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // chebyshev_polynomial_w_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T chebyshev_polynomial_w_forward(T x, T n) {
+    return chebyshev_polynomial_w_forward(x, static_cast(n));
+} // chebyshev_polynomial_w_forward(T x, T n)
+
+template
+constexpr auto getHermitianLimit() {
+    if constexpr (std::is_same_v) {
+        return 128;
+    } else if constexpr (std::is_same_v) {
+        return 512;
+    } else {
+        return 1024;
+    }
+}
+
+template
+inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x;
+    }
+
+    if (n > getHermitianLimit()) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p = T(1.0);
+    T q = x + x;
+    T r = T(0.0);
+
+    for (int64_t k = 2; k < n + n; k += 2) {
+        r = (x + x) * q - k * p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // hermite_polynomial_h_forward(T x, int64_t n)
+
+template, int> = 0>
+inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, T n) {
+    return hermite_polynomial_h_forward(x, static_cast(n));
+} // hermite_polynomial_h_forward(T x, T n)
+
+template, int> = 0>
+__ubsan_ignore_float_cast_overflow__ inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, T n) {
+    return hermite_polynomial_h_forward(x, (!std::isinf(n) && !std::isnan(n)) ? static_cast(n) : static_cast(-1));
+} // hermite_polynomial_h_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T hermite_polynomial_he_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x;
+    }
+
+    if (n > getHermitianLimit()) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p = T(1.0);
+    T q = x;
+    T r;
+
+    for (int64_t k = 1; k < n; k++) {
+        r = x * q - k * p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // hermite_polynomial_he_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T hermite_polynomial_he_forward(T x, T n) {
+    return hermite_polynomial_he_forward(x, static_cast(n));
+} // hermite_polynomial_he_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T laguerre_polynomial_l_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(0.0)) {
+        return T(1.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return T(1.0) - x;
+    }
+
+    T p = T(1.0);
+    T q = T(1.0) - x;
+    T r;
+
+    for (int64_t k = 1; k < n; k++) {
+        r = (((k + k) + (T(1.0) - x)) * q - k * p) / (k + 1);
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // laguerre_polynomial_l_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T laguerre_polynomial_l_forward(T x, T n) {
+    return laguerre_polynomial_l_forward(x, static_cast(n));
+} // laguerre_polynomial_l_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T legendre_polynomial_p_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) == T(1.0)) {
+        if (x > T(0.0) || n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x;
+    }
+
+    T p = T(1.0);
+    T q = x;
+    T r;
+
+    for (int64_t k = 1; k < n; k++) {
+        r = ((k + k + 1) * x * q - k * p) / (k + 1);
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // legendre_polynomial_p_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T legendre_polynomial_p_forward(T x, T n) {
+    return legendre_polynomial_p_forward(x, static_cast(n));
+} // legendre_polynomial_p_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T modified_bessel_i0_forward(T x) {
+    static const T A[] = {
+            -4.41534164647933937950e-18,
+            +3.33079451882223809783e-17,
+            -2.43127984654795469359e-16,
+            +1.71539128555513303061e-15,
+            -1.16853328779934516808e-14,
+            +7.67618549860493561688e-14,
+            -4.85644678311192946090e-13,
+            +2.95505266312963983461e-12,
+            -1.72682629144155570723e-11,
+            +9.67580903537323691224e-11,
+            -5.18979560163526290666e-10,
+            +2.65982372468238665035e-09,
+            -1.30002500998624804212e-08,
+            +6.04699502254191894932e-08,
+            -2.67079385394061173391e-07,
+            +1.11738753912010371815e-06,
+            -4.41673835845875056359e-06,
+            +1.64484480707288970893e-05,
+            -5.75419501008210370398e-05,
+            +1.88502885095841655729e-04,
+            -5.76375574538582365885e-04,
+            +1.63947561694133579842e-03,
+            -4.32430999505057594430e-03,
+            +1.05464603945949983183e-02,
+            -2.37374148058994688156e-02,
+            +4.93052842396707084878e-02,
+            -9.49010970480476444210e-02,
+            +1.71620901522208775349e-01,
+            -3.04682672343198398683e-01,
+            +6.76795274409476084995e-01,
+    };
+
+    static const T B[] = {
+            -7.23318048787475395456e-18,
+            -4.83050448594418207126e-18,
+            +4.46562142029675999901e-17,
+            +3.46122286769746109310e-17,
+            -2.82762398051658348494e-16,
+            -3.42548561967721913462e-16,
+            +1.77256013305652638360e-15,
+            +3.81168066935262242075e-15,
+            -9.55484669882830764870e-15,
+            -4.15056934728722208663e-14,
+            +1.54008621752140982691e-14,
+            +3.85277838274214270114e-13,
+            +7.18012445138366623367e-13,
+            -1.79417853150680611778e-12,
+            -1.32158118404477131188e-11,
+            -3.14991652796324136454e-11,
+            +1.18891471078464383424e-11,
+            +4.94060238822496958910e-10,
+            +3.39623202570838634515e-09,
+            +2.26666899049817806459e-08,
+            +2.04891858946906374183e-07,
+            +2.89137052083475648297e-06,
+            +6.88975834691682398426e-05,
+            +3.36911647825569408990e-03,
+            +8.04490411014108831608e-01,
+    };
+
+    T p;
+    T q = 0.0;
+
+    if (std::abs(x) <= T(8.0)) {
+        T a = A[0];
+
+        for (uint8_t index = 1; index < 30; index++) {
+            p = q;
+            q = a;
+            a = ((std::abs(x) / T(2.0)) - T(2.0)) * q - p + A[index];
+        }
+
+        return std::exp(std::abs(x)) * (T(0.5) * (a - p));
+    }
+
+    T b = B[0];
+
+    for (uint8_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(32.0) / std::abs(x) - T(2.0)) * q - p + B[index];
+    }
+
+    return std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x));
+} // modified_bessel_i0_forward(T x)
+
+template
+inline C10_HOST_DEVICE T modified_bessel_i1_forward(T x) {
+    static const T A[] = {
+            +2.77791411276104639959e-18,
+            -2.11142121435816608115e-17,
+            +1.55363195773620046921e-16,
+            -1.10559694773538630805e-15,
+            +7.60068429473540693410e-15,
+            -5.04218550472791168711e-14,
+            +3.22379336594557470981e-13,
+            -1.98397439776494371520e-12,
+            +1.17361862988909016308e-11,
+            -6.66348972350202774223e-11,
+            +3.62559028155211703701e-10,
+            -1.88724975172282928790e-09,
+            +9.38153738649577178388e-09,
+            -4.44505912879632808065e-08,
+            +2.00329475355213526229e-07,
+            -8.56872026469545474066e-07,
+            +3.47025130813767847674e-06,
+            -1.32731636560394358279e-05,
+            +4.78156510755005422638e-05,
+            -1.61760815825896745588e-04,
+            +5.12285956168575772895e-04,
+            -1.51357245063125314899e-03,
+            +4.15642294431288815669e-03,
+            -1.05640848946261981558e-02,
+            +2.47264490306265168283e-02,
+            -5.29459812080949914269e-02,
+            +1.02643658689847095384e-01,
+            -1.76416518357834055153e-01,
+            +2.52587186443633654823e-01,
+    };
+
+    static const T B[] = {
+            +7.51729631084210481353e-18,
+            +4.41434832307170791151e-18,
+            -4.65030536848935832153e-17,
+            -3.20952592199342395980e-17,
+            +2.96262899764595013876e-16,
+            +3.30820231092092828324e-16,
+            -1.88035477551078244854e-15,
+            -3.81440307243700780478e-15,
+            +1.04202769841288027642e-14,
+            +4.27244001671195135429e-14,
+            -2.10154184277266431302e-14,
+            -4.08355111109219731823e-13,
+            -7.19855177624590851209e-13,
+            +2.03562854414708950722e-12,
+            +1.41258074366137813316e-11,
+            +3.25260358301548823856e-11,
+            -1.89749581235054123450e-11,
+            -5.58974346219658380687e-10,
+            -3.83538038596423702205e-09,
+            -2.63146884688951950684e-08,
+            -2.51223623787020892529e-07,
+            -3.88256480887769039346e-06,
+            -1.10588938762623716291e-04,
+            -9.76109749136146840777e-03,
+            +7.78576235018280120474e-01,
+    };
+
+    T p;
+    T q = 0.0;
+
+    if (std::abs(x) <= T(8.0)) {
+        T a = A[0];
+
+        for (uint8_t index = 1; index < 29; index++) {
+            p = q;
+            q = a;
+            a = ((std::abs(x) / T(2.0)) - T(2.0)) * q - p + A[index];
+        }
+
+        if (x < T(0.0)) {
+            return -(T(0.5) * (a - p) * std::abs(x) * std::exp(std::abs(x)));
+        }
+
+        return T(0.5) * (a - p) * std::abs(x) * std::exp(std::abs(x));
+    }
+
+    T b = B[0];
+
+    for (uint8_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(32.0) / std::abs(x) - T(2.0)) * q - p + B[index];
+    }
+
+    if (x < T(0.0)) {
+        return -(std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x)));
+    }
+
+    return std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x));
+} // modified_bessel_i1_forward(T x)
+
+template
+inline C10_HOST_DEVICE T modified_bessel_k0_forward(T x) {
+    static const T A[] = {
+            +1.37446543561352307156e-16,
+            +4.25981614279661018399e-14,
+            +1.03496952576338420167e-11,
+            +1.90451637722020886025e-09,
+            +2.53479107902614945675e-07,
+            +2.28621210311945178607e-05,
+            +1.26461541144692592338e-03,
+            +3.59799365153615016266e-02,
+            +3.44289899924628486886e-01,
+            -5.35327393233902768720e-01,
+    };
+
+    static const T B[] = {
+            +5.30043377268626276149e-18,
+            -1.64758043015242134646e-17,
+            +5.21039150503902756861e-17,
+            -1.67823109680541210385e-16,
+            +5.51205597852431940784e-16,
+            -1.84859337734377901440e-15,
+            +6.34007647740507060557e-15,
+            -2.22751332699166985548e-14,
+            +8.03289077536357521100e-14,
+            -2.98009692317273043925e-13,
+            +1.14034058820847496303e-12,
+            -4.51459788337394416547e-12,
+            +1.85594911495471785253e-11,
+            -7.95748924447710747776e-11,
+            +3.57739728140030116597e-10,
+            -1.69753450938905987466e-09,
+            +8.57403401741422608519e-09,
+            -4.66048989768794782956e-08,
+            +2.76681363944501510342e-07,
+            -1.83175552271911948767e-06,
+            +1.39498137188764993662e-05,
+            -1.28495495816278026384e-04,
+            +1.56988388573005337491e-03,
+            -3.14481013119645005427e-02,
+            +2.44030308206595545468e+00,
+    };
+
+    if (x == T(0.0)) {
+        return std::numeric_limits::infinity();
+    }
+
+    if (x < T(0.0)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p;
+    T q = 0.0;
+
+    if (x <= T(2.0)) {
+        T a = A[0];
+
+        for (uint8_t index = 1; index < 10; index++) {
+            p = q;
+            q = a;
+            a = (x * x - T(2.0)) * q - p + A[index];
+        }
+
+        return T(0.5) * (a - p) - std::log(0.5 * x) * modified_bessel_i0_forward(x);
+    }
+
+    T b = B[0];
+
+    for (uint8_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(8.0) / x - T(2.0)) * q - p + B[index];
+    }
+
+    return std::exp(-x) * (T(0.5) * (b - p)) / std::sqrt(x);
+} // modified_bessel_k0_forward(T x)
+
+template
+inline C10_HOST_DEVICE T modified_bessel_k1_forward(T x) {
+    static const T A[] = {
+            -7.02386347938628759343e-18,
+            -2.42744985051936593393e-15,
+            -6.66690169419932900609e-13,
+            -1.41148839263352776110e-10,
+            -2.21338763073472585583e-08,
+            -2.43340614156596823496e-06,
+            -1.73028895751305206302e-04,
+            -6.97572385963986435018e-03,
+            -1.22611180822657148235e-01,
+            -3.53155960776544875667e-01,
+            +1.52530022733894777053e+00,
+    };
+
+    static const T B[] = {
+            -5.75674448366501715755e-18,
+            +1.79405087314755922667e-17,
+            -5.68946255844285935196e-17,
+            +1.83809354436663880070e-16,
+            -6.05704724837331885336e-16,
+            +2.03870316562433424052e-15,
+            -7.01983709041831346144e-15,
+            +2.47715442448130437068e-14,
+            -8.97670518232499435011e-14,
+            +3.34841966607842919884e-13,
+            -1.28917396095102890680e-12,
+            +5.13963967348173025100e-12,
+            -2.12996783842756842877e-11,
+            +9.21831518760500529508e-11,
+            -4.19035475934189648750e-10,
+            +2.01504975519703286596e-09,
+            -1.03457624656780970260e-08,
+            +5.74108412545004946722e-08,
+            -3.50196060308781257119e-07,
+            +2.40648494783721712015e-06,
+            -1.93619797416608296024e-05,
+            +1.95215518471351631108e-04,
+            -2.85781685962277938680e-03,
+            +1.03923736576817238437e-01,
+            +2.72062619048444266945e+00,
+    };
+
+    if (x == T(0.0)) {
+        return std::numeric_limits::infinity();
+    }
+
+    if (x < T(0.0)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p;
+    T q = 0.0;
+
+    if (x <= T(2.0)) {
+        T a = A[0];
+
+        for (uint8_t index = 1; index < 11; index++) {
+            p = q;
+            q = a;
+            a = (x * x - T(2.0)) * q - p + A[index];
+        }
+
+        return std::log(T(0.5) * x) * modified_bessel_i1_forward(x) + T(0.5) * (a - p) / x;
+    }
+
+    T b = B[0];
+
+    for (uint8_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(8.0) / x - T(2.0)) * q - p + B[index];
+    }
+
+    return std::exp(-x) * (T(0.5) * (b - p)) / std::sqrt(x);
+} // modified_bessel_k1_forward(T x)
+
+template
+inline C10_HOST_DEVICE T scaled_modified_bessel_k0_forward(T x) {
+    static const T A[] = {
+            +1.37446543561352307156e-16,
+            +4.25981614279661018399e-14,
+            +1.03496952576338420167e-11,
+            +1.90451637722020886025e-09,
+            +2.53479107902614945675e-07,
+            +2.28621210311945178607e-05,
+            +1.26461541144692592338e-03,
+            +3.59799365153615016266e-02,
+            +3.44289899924628486886e-01,
+            -5.35327393233902768720e-01,
+    };
+
+    static const T B[] = {
+            +5.30043377268626276149e-18,
+            -1.64758043015242134646e-17,
+            +5.21039150503902756861e-17,
+            -1.67823109680541210385e-16,
+            +5.51205597852431940784e-16,
+            -1.84859337734377901440e-15,
+            +6.34007647740507060557e-15,
+            -2.22751332699166985548e-14,
+            +8.03289077536357521100e-14,
+            -2.98009692317273043925e-13,
+            +1.14034058820847496303e-12,
+            -4.51459788337394416547e-12,
+            +1.85594911495471785253e-11,
+            -7.95748924447710747776e-11,
+            +3.57739728140030116597e-10,
+            -1.69753450938905987466e-09,
+            +8.57403401741422608519e-09,
+            -4.66048989768794782956e-08,
+            +2.76681363944501510342e-07,
+            -1.83175552271911948767e-06,
+            +1.39498137188764993662e-05,
+            -1.28495495816278026384e-04,
+            +1.56988388573005337491e-03,
+            -3.14481013119645005427e-02,
+            +2.44030308206595545468e+00,
+    };
+
+    if (x == T(0.0)) {
+        return std::numeric_limits::infinity();
+    }
+
+    if (x < T(0.0)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p;
+    T q = 0.0;
+
+    if (x <= T(2.0)) {
+        T a = A[0];
+
+        for (uint64_t index = 1; index < 10; index++) {
+            p = q;
+            q = a;
+            a = (x * x - T(2.0)) * q - p + A[index];
+        }
+
+        return (T(0.5) * (a - p) - std::log(T(0.5) * x) * modified_bessel_i0_forward(x)) * std::exp(x);
+    }
+
+    T b = B[0];
+
+    for (uint64_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(8.0) / x - T(2.0)) * q - p + B[index];
+    }
+
+    return T(0.5) * (b - p) / std::sqrt(x);
+} // T scaled_modified_bessel_k0_forward(T x)
+
+template
+inline C10_HOST_DEVICE T scaled_modified_bessel_k1_forward(T x) {
+    static const T A[] = {
+            -7.02386347938628759343e-18,
+            -2.42744985051936593393e-15,
+            -6.66690169419932900609e-13,
+            -1.41148839263352776110e-10,
+            -2.21338763073472585583e-08,
+            -2.43340614156596823496e-06,
+            -1.73028895751305206302e-04,
+            -6.97572385963986435018e-03,
+            -1.22611180822657148235e-01,
+            -3.53155960776544875667e-01,
+            +1.52530022733894777053e+00,
+    };
+
+    static const T B[] = {
+            -5.75674448366501715755e-18,
+            +1.79405087314755922667e-17,
+            -5.68946255844285935196e-17,
+            +1.83809354436663880070e-16,
+            -6.05704724837331885336e-16,
+            +2.03870316562433424052e-15,
+            -7.01983709041831346144e-15,
+            +2.47715442448130437068e-14,
+            -8.97670518232499435011e-14,
+            +3.34841966607842919884e-13,
+            -1.28917396095102890680e-12,
+            +5.13963967348173025100e-12,
+            -2.12996783842756842877e-11,
+            +9.21831518760500529508e-11,
+            -4.19035475934189648750e-10,
+            +2.01504975519703286596e-09,
+            -1.03457624656780970260e-08,
+            +5.74108412545004946722e-08,
+            -3.50196060308781257119e-07,
+            +2.40648494783721712015e-06,
+            -1.93619797416608296024e-05,
+            +1.95215518471351631108e-04,
+            -2.85781685962277938680e-03,
+            +1.03923736576817238437e-01,
+            +2.72062619048444266945e+00,
+    };
+
+    if (x == T(0.0)) {
+        return std::numeric_limits::infinity();
+    }
+
+    if (x < T(0.0)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    T p;
+    T q = 0.0;
+
+    if (x <= T(2.0)) {
+        T a = A[0];
+
+        for (uint64_t index = 1; index < 11; index++) {
+            p = q;
+            q = a;
+            a = (x * x - T(2.0)) * q - p + A[index];
+        }
+
+        return (std::log(T(0.5) * x) * modified_bessel_i1_forward(x) + T(0.5) * (a - p) / x) * std::exp(x);
+    }
+
+    T b = B[0];
+
+    for (uint64_t index = 1; index < 25; index++) {
+        p = q;
+        q = b;
+        b = (T(8.0) / x - T(2.0)) * q - p + B[index];
+    }
+
+    return (T(0.5) * (b - p) / std::sqrt(x));
+} // T scaled_modified_bessel_k1_forward(T x)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_t_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (x == T(1.0)) {
+        return T(1.0);
+    }
+
+    if (x == T(0.0)) {
+        if (n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) {
+        return std::cos(n * std::acos(x + x - T(1.0)));
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x - T(1.0);
+    }
+
+    T p = T(1.0);
+    T q = x + x - T(1.0);
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // shifted_chebyshev_polynomial_t_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_t_forward(T x, T n) {
+    return shifted_chebyshev_polynomial_t_forward(x, static_cast(n));
+} // shifted_chebyshev_polynomial_t_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_u_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (x == T(1.0)) {
+        return n + 1;
+    }
+
+    if (x == T(0.0)) {
+        if (n % 2 == 0) {
+            return n + 1;
+        }
+
+        return -(n + 1);
+    }
+
+    if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) {
+        if (std::sin(std::acos(x + x - T(1.0))) != T(0.0)) {
+            return std::sin((n + 1) * std::acos(x + x - T(1.0))) / std::sin(std::acos(x + x - T(1.0)));
+        }
+
+        return (n + 1) * std::cos((n + 1) * std::acos(x + x - T(1.0))) / (x + x - T(1.0));
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x - T(1.0) + (x + x - T(1.0));
+    }
+
+    T p = T(1.0);
+    T q = x + x - T(1.0) + (x + x - T(1.0));
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // shifted_chebyshev_polynomial_u_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_u_forward(T x, T n) {
+    return shifted_chebyshev_polynomial_u_forward(x, static_cast(n));
+} // shifted_chebyshev_polynomial_u_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_v_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (x == T(1.0)) {
+        return T(1.0);
+    }
+
+    if (x == T(0.0)) {
+        if (n % 2 == 0) {
+            return (n + n + 1);
+        }
+
+        return -(n + n + 1);
+    }
+
+    if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) {
+        if (std::sin(std::acos(x + x - T(1.0)) / T(2.0)) != T(1.0)) {
+            return std::cos(((n) + T(0.5)) * std::acos(x + x - T(1.0))) / std::cos(std::acos(x + x - T(1.0)) / T(2.0));
+        }
+
+        if (n % 2 == 0) {
+            return n + n + 1;
+        }
+
+        return -(n + n + 1);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x - T(1.0) + (x + x - T(1.0)) - T(1.0);
+    }
+
+    T p = T(1.0);
+    T q = x + x - T(1.0) + (x + x - T(1.0)) - T(1.0);
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // shifted_chebyshev_polynomial_v_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_v_forward(T x, T n) {
+    return shifted_chebyshev_polynomial_v_forward(x, static_cast(n));
+} // shifted_chebyshev_polynomial_v_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_w_forward(T x, int64_t n) {
+    if (n < 0) {
+        return T(0.0);
+    }
+
+    if (x == T(1.0)) {
+        return n + n + 1;
+    }
+
+    if (x == T(0.0)) {
+        if (n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if ((n > 4) && (std::abs(x + x - T(1.0)) < T(1.0))) {
+        if (std::cos(std::acos(x + x - T(1.0)) / T(2.0)) != T(1.0)) {
+            return std::sin((n + T(0.5)) * std::acos(x + x - T(1.0))) / std::sin(std::acos(x + x - T(1.0)) / T(2.0));
+        }
+
+        if (n % 2 == 0) {
+            return T(1.0);
+        }
+
+        return T(-1.0);
+    }
+
+    if (n == 0) {
+        return T(1.0);
+    }
+
+    if (n == 1) {
+        return x + x - T(1.0) + (x + x - T(1.0)) + T(1.0);
+    }
+
+    T p = T(1.0);
+    T q = x + x - T(1.0) + (x + x - T(1.0)) + T(1.0);
+    T r;
+
+    for (int64_t k = 2; k <= n; k++) {
+        r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p;
+        p = q;
+        q = r;
+    }
+
+    return r;
+} // shifted_chebyshev_polynomial_w_forward(T x, int64_t n)
+
+template
+inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_w_forward(T x, T n) {
+    return shifted_chebyshev_polynomial_w_forward(x, static_cast(n));
+} // shifted_chebyshev_polynomial_w_forward(T x, T n)
+
+template
+inline C10_HOST_DEVICE T spherical_bessel_j0_forward(T x) {
+    if (std::isinf(x)) {
+        return T(0.0);
+    }
+
+    if (std::abs(x) < T(0.5)) {
+        return T(1.0) + x * x * (T(-1.0) / T(6.0) + x * x * (T(1.0) / T(120.0) + x * x * (T(-1.0) / T(5040.0) + x * x * (T(1.0) / T(362880.0) + x * x * (T(-1.0) / T(39916800.0) + x * x * (T(1.0) / T(6227020800.0)))))));
+    }
+
+    return std::sin(x) / x;
+} // T spherical_bessel_j0_forward(T x)
+
+C10_CLANG_DIAGNOSTIC_POP()
diff --git a/shared/package-files/b6/b686db45cfe6c2563ef16d10958c7141083be6c3cefb6e672f347d3f0f48c7b4/event.py b/shared/package-files/b6/b686db45cfe6c2563ef16d10958c7141083be6c3cefb6e672f347d3f0f48c7b4/event.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f597c66a41f835fb4a7c58438c788b5025b8383
--- /dev/null
+++ b/shared/package-files/b6/b686db45cfe6c2563ef16d10958c7141083be6c3cefb6e672f347d3f0f48c7b4/event.py
@@ -0,0 +1,45 @@
+import torch
+
+
+class Event:
+    r"""Wrapper around an MPS event.
+
+    MPS events are synchronization markers that can be used to monitor the
+    device's progress, to accurately measure timing, and to synchronize MPS streams.
+
+    Args:
+        enable_timing (bool, optional): indicates if the event should measure time
+            (default: ``False``)
+    """
+
+    def __init__(self, enable_timing: bool = False) -> None:
+        self.__eventId = torch._C._mps_acquireEvent(enable_timing)
+
+    def __del__(self) -> None:
+        # checks if torch._C is already destroyed
+        if hasattr(torch._C, "_mps_releaseEvent") and self.__eventId > 0:
+            torch._C._mps_releaseEvent(self.__eventId)
+
+    def record(self) -> None:
+        r"""Records the event in the default stream."""
+        torch._C._mps_recordEvent(self.__eventId)
+
+    def wait(self) -> None:
+        r"""Makes all future work submitted to the default stream wait for this event."""
+        torch._C._mps_waitForEvent(self.__eventId)
+
+    def query(self) -> bool:
+        r"""Returns True if all work currently captured by event has completed."""
+        return torch._C._mps_queryEvent(self.__eventId)
+
+    def synchronize(self) -> None:
+        r"""Waits until the completion of all work currently captured in this event.
+        This prevents the CPU thread from proceeding until the event completes.
+        """
+        torch._C._mps_synchronizeEvent(self.__eventId)
+
+    def elapsed_time(self, end_event: "Event") -> float:
+        r"""Returns the time elapsed in milliseconds after the event was
+        recorded and before the end_event was recorded.
+        """
+        return torch._C._mps_elapsedTimeOfEvents(self.__eventId, end_event.__eventId)
diff --git a/shared/package-files/b6/b688b5f1cc03a47840a72a14aadbf5079f3a808f833eb9cc9b0002ee72ca326e/_pass.py b/shared/package-files/b6/b688b5f1cc03a47840a72a14aadbf5079f3a808f833eb9cc9b0002ee72ca326e/_pass.py
new file mode 100644
index 0000000000000000000000000000000000000000..5246788756f3ed67cd697b489d89045767ffde5e
--- /dev/null
+++ b/shared/package-files/b6/b688b5f1cc03a47840a72a14aadbf5079f3a808f833eb9cc9b0002ee72ca326e/_pass.py
@@ -0,0 +1,323 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import abc
+import contextlib
+import dataclasses
+import difflib
+import io
+import logging
+import sys
+from typing import Any, Callable, TYPE_CHECKING
+
+import torch
+import torch.fx
+from torch._subclasses.fake_tensor import unset_fake_temporarily
+from torch.onnx._internal.fx import diagnostics, onnxfunction_dispatcher
+
+
+if TYPE_CHECKING:
+    from torch._subclasses import fake_tensor
+
+
+@dataclasses.dataclass
+class PackageInfo:
+    package_name: str
+    version: str | None
+    commit_hash: str | None
+
+    def to_onnx_domain_string(self) -> str:
+        return ".".join(
+            filter(None, ("pkg", self.package_name, self.version, self.commit_hash))
+        )
+
+    @classmethod
+    def from_python_class(cls, python_class_name: type | str) -> PackageInfo:
+        if isinstance(python_class_name, type):
+            python_class_name = python_class_name.__module__
+        package_name = python_class_name.split(".")[0]
+        package = __import__(package_name)
+        version = getattr(package, "__version__", None)
+        # TODO: Figure out how to retrieve commit hash.
+        commit_hash = None
+        return cls(package_name, version, commit_hash)
+
+
+@dataclasses.dataclass
+class GraphModuleOnnxMeta:
+    package_info: PackageInfo
+
+
+@contextlib.contextmanager
+def _patch_difflib_sequence_matcher_init():
+    """Context patching `difflib.SequenceMatcher` for fx readable graph.
+
+    Under this context, the `autojunk` argument of `difflib.SequenceMatcher` will always
+    be considered as `False`. This is to prevent `difflib.SequenceMatcher` recognizing
+    stacktrace messages in fx readable graph as junk, as these messages tend to be long (>200)
+    and repeat multiple times, which falls under the junk filter criteria.
+
+    `difflib.SequenceMatcher` is used underneath by all sorts of diffing functions
+    in `difflib`, including `difflib.unified_diff`, `difflib.ndiff`, `difflib.context_diff`.
+    Unfortunately, there is no way to pass `autojunk` argument to these functions, and
+    they all default to `True`. This context patching will affect all of them.
+
+    `Reference: Automatic junk heuristic `_
+    """
+    original_init = difflib.SequenceMatcher.__init__
+
+    def patched_init(self, isjunk=None, a="", b="", autojunk=True):
+        original_init(self, isjunk, a, b, autojunk=False)
+
+    difflib.SequenceMatcher.__init__ = patched_init  # type: ignore[assignment]
+    try:
+        yield
+    finally:
+        difflib.SequenceMatcher.__init__ = original_init  # type: ignore[assignment]
+
+
+def _unified_diff(a: str, b: str) -> str:
+    """Return a string containing the unified diff of two strings.
+
+    This function calls a patched version of `difflib.unified_diff` with `autojunk` set
+    to `False` for `difflib.SequenceMatcher` class. More details can be found in
+    `_patch_difflib_sequence_matcher_init` function.
+
+    Args:
+        a: The first string.
+        b: The second string.
+
+    Returns:
+        The unified diff of the two strings. If there is no diff, return "".
+
+    Example::
+
+        >>> a = '''class GraphModule(torch.nn.Module):
+        ...     def forward(self, input_ids : torch.Tensor, attention_mask : torch.Tensor):
+        ...         # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
+        ...         view = input_ids.view(-1, 3);  input_ids = None
+        ... '''
+        >>> b = '''class (torch.nn.Module):
+        ...     def forward(self, input_ids: i64[1, 3], attention_mask: i64[1, 3]):
+        ...         # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
+        ...         view: i64[1, 3] = torch.ops.aten.view.default(input_ids, [-1, 3]);  input_ids = None
+        ... '''
+        >>> print(_unified_diff(a, b))
+        ---
+        +++
+        @@ -1,4 +1,4 @@
+        -class GraphModule(torch.nn.Module):
+        -    def forward(self, input_ids : torch.Tensor, attention_mask : torch.Tensor):
+        +class (torch.nn.Module):
+        +    def forward(self, input_ids: i64[1, 3], attention_mask: i64[1, 3]):
+                # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
+        -        view = input_ids.view(-1, 3);  input_ids = None
+        +        view: i64[1, 3] = torch.ops.aten.view.default(input_ids, [-1, 3]);  input_ids = None
+    """
+
+    a_list = a.splitlines(keepends=True)
+    b_list = b.splitlines(keepends=True)
+
+    with _patch_difflib_sequence_matcher_init():
+        # Set `n` to `sys.maxsize` to show entire graph when there is a diff.
+        diff = "".join(difflib.unified_diff(a_list, b_list, n=sys.maxsize))
+
+    if not diff:
+        return ""
+    return diff
+
+
+def _transform_diagnose_call_message_formatter(
+    run: Callable,
+    self: Transform,
+    *args: Any,
+    **kwargs: Any,
+) -> str:
+    return f"Running {self.__class__.__name__} pass. "
+
+
+def maybe_fx_graph_tabular(graph: torch.fx.Graph) -> str | None:
+    """Return the Graph nodes in tabular format. Equivalent to stdout of `graph.print_tabular()`.
+    If `tabulate` is not installed, return `None`.
+
+    Args:
+        graph: The Graph to print.
+
+    Returns:
+        The Graph printed in a tabular format. None if `tabulate` is not installed.
+    """
+    f = io.StringIO()
+    with contextlib.redirect_stdout(f):
+        try:
+            graph.print_tabular()
+        except ImportError:
+            return None
+    return f.getvalue()
+
+
+class Transform(abc.ABC):
+    """Base class for FX graph transformations to be used by FX-ONNX exporter.
+
+    Similar to `FX Interpreter `_,
+    specializations of this class execute the FX graph Node-by-Node.
+    Methods in the `Transform` class can be overridden to customize the behavior of the model.
+    This pattern can be useful for many things, including writing code transformations as well as analysis passes.
+
+    The following methods can be overridden::
+
+        _run()
+            +-- run_node()
+                +-- placeholder()
+                +-- get_attr()
+                +-- call_function()
+                +-- call_method()
+                +-- call_module()
+                +-- output()
+
+    One important aspect to note is that if the transformation modifies the model input and/or output signature,
+    (e.g. additional inputs/outputs are added to the model), :class:`InputAdaptStep` and/or :class:`OutputAdaptStep`
+    are needed to reconcile :attr:`ONNXProgram.model_proto`.
+    That is, the model signature and the model representation must match.
+
+    As an additional feature, this class provides builtin support for transformation recording using the diagnostics.
+    The granularity of overriding is up to the user. And it affects the granularity of
+    the diagnostics information. For example, if `_run()` is overridden, the
+    diagnostics information will only contain graph level transformation. Instead,
+    if `call_function()` is overridden, the diagnostics information will additionally
+    contain the node level information of `call_function()`.
+
+    TODO(bowbao): Add more overridable methods in call hierarchy
+    TODO(bowbao): Create an example once more overridable methods are added.
+    """
+
+    diagnostic_context: diagnostics.DiagnosticContext
+    """The diagnostic context for recording diagnostics."""
+
+    module: torch.fx.GraphModule
+    """The module to be transformed."""
+
+    fake_mode: fake_tensor.FakeTensorMode | None
+    """The existing fake mode detected from `self.module`."""
+
+    def __init__(
+        self,
+        diagnostic_context: diagnostics.DiagnosticContext,
+        module: torch.fx.GraphModule,
+    ):
+        """Initialize the transform.
+
+        Args:
+            diagnostic_context: The diagnostic context for recording diagnostics.
+            module: The module to be transformed.
+        """
+        self.diagnostic_context = diagnostic_context
+        self.module = module
+        self.fake_mode = self._detect_fake_mode()
+
+    def _detect_fake_mode(self) -> fake_tensor.FakeTensorMode | None:
+        """Detect fake mode from the graph.
+
+        Scan through all nodes in graph and their meta['val'] to detect fake mode.
+        """
+        fake_tensors = [node.meta.get("val") for node in self.module.graph.nodes]
+        with unset_fake_temporarily():
+            return torch._dynamo.utils.detect_fake_mode(fake_tensors)
+
+    def _maybe_fakefy_args(
+        self, fake_mode: fake_tensor.FakeTensorMode | None, *args: Any
+    ) -> tuple[Any, ...]:
+        if fake_mode is None:
+            return args
+        # NB: This should hit the cache if tensors were fakefied before.
+        # E.g., when the fx graph is produced by Dynamo.
+        return tuple(
+            fake_mode.from_tensor(t) if isinstance(t, torch.Tensor) else t for t in args
+        )
+
+    @abc.abstractmethod
+    def _run(self, *args, **kwargs) -> torch.fx.GraphModule: ...
+
+    @diagnostics.diagnose_call(
+        diagnostics.rules.fx_pass,
+        diagnostic_message_formatter=_transform_diagnose_call_message_formatter,
+    )
+    def run(self, *args, **kwargs) -> torch.fx.GraphModule:
+        """Run the transform on `self.module`.
+
+        Note that this method may or may not mutate `self.module`, and the returned
+        `GraphModule` could be either `self.module` or a new `GraphModule`.
+
+        Args:
+            *args: Positional arguments for `self.module` to run.
+            **kwargs: Keyword arguments for `self.module` to run.
+        """
+        diagnostic = self.diagnostic_context.inflight_diagnostic(
+            rule=diagnostics.rules.fx_pass
+        )
+        diagnostic.info(
+            "For detailed logging of graph modifications by this pass, either set "
+            "`DiagnosticOptions.verbosity_level` to `logging.DEBUG` or use the environment variable "
+            "`TORCH_LOGS='onnx_diagnostics'`."
+        )
+
+        # Gather graph information before transform.
+        graph_diff_log_level = logging.DEBUG
+        if diagnostic.logger.isEnabledFor(graph_diff_log_level):
+            # Cannot use LazyString because the graph may have been mutated at evaluation time.
+            old_readable_graph = self.module.print_readable(print_output=False)
+            old_tabular = maybe_fx_graph_tabular(self.module.graph)
+        else:
+            # Set to empty string to avoid unbound warning. This value should never be
+            # used since the log level is not enabled.
+            old_readable_graph = ""
+            old_tabular = ""
+
+        module = self._run(*args, **kwargs)
+
+        # Gather graph information after transform.
+        if diagnostic.logger.isEnabledFor(graph_diff_log_level):
+            new_readable_graph = module.print_readable(print_output=False)
+            new_tabular = maybe_fx_graph_tabular(module.graph)
+
+            with diagnostic.log_section(graph_diff_log_level, "Graph diff:"):
+                diagnostic.log(
+                    graph_diff_log_level,
+                    "```\n%s\n```",
+                    diagnostics.LazyString(
+                        _unified_diff, old_readable_graph, new_readable_graph
+                    ),
+                )
+
+            with diagnostic.log_section(graph_diff_log_level, "Tabular diff:"):
+                if old_tabular is None or new_tabular is None:
+                    diagnostic.log(
+                        graph_diff_log_level,
+                        "Tabular diff is not available because `tabulate` is not installed.",
+                    )
+                else:
+                    diagnostic.log(
+                        graph_diff_log_level,
+                        "```\n%s\n```",
+                        diagnostics.LazyString(_unified_diff, old_tabular, new_tabular),
+                    )
+
+        return module
+
+
+class AnalysisResult(abc.ABC):  # noqa: B024
+    ...
+
+
+class Analysis(abc.ABC):
+    def __init__(
+        self,
+        diagnostic_context: diagnostics.DiagnosticContext,
+        module: torch.fx.GraphModule,
+        onnxfunction_dispatcher: onnxfunction_dispatcher.OnnxFunctionDispatcher,
+    ):
+        self.diagnostic_context = diagnostic_context
+        self.module = module
+        self.onnxfunction_dispatcher = onnxfunction_dispatcher
+
+    @abc.abstractmethod
+    def analyze(self, diagnostic_level: diagnostics.infra.Level) -> AnalysisResult: ...
diff --git a/shared/package-files/b6/b68cdf7b6488c9b3faf4ea9bd00c1596aefd5064954edee83af32a94d384fa9e/_log.cpython-311.pyc b/shared/package-files/b6/b68cdf7b6488c9b3faf4ea9bd00c1596aefd5064954edee83af32a94d384fa9e/_log.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fc73295e0d95f6ee1430eaba60ca1849be50352
Binary files /dev/null and b/shared/package-files/b6/b68cdf7b6488c9b3faf4ea9bd00c1596aefd5064954edee83af32a94d384fa9e/_log.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b68f0b98d92188fd000a1f95ba7fa17da3272c5484734985d8e9999d09a2844f/mathematica.py b/shared/package-files/b6/b68f0b98d92188fd000a1f95ba7fa17da3272c5484734985d8e9999d09a2844f/mathematica.py
new file mode 100644
index 0000000000000000000000000000000000000000..064925ec1a9a477d7509110c57311239bac9fcaf
--- /dev/null
+++ b/shared/package-files/b6/b68f0b98d92188fd000a1f95ba7fa17da3272c5484734985d8e9999d09a2844f/mathematica.py
@@ -0,0 +1,353 @@
+"""
+Mathematica code printer
+"""
+
+from __future__ import annotations
+from typing import Any
+
+from sympy.core import Basic, Expr, Float
+from sympy.core.sorting import default_sort_key
+
+from sympy.printing.codeprinter import CodePrinter
+from sympy.printing.precedence import precedence
+
+# Used in MCodePrinter._print_Function(self)
+known_functions = {
+    "exp": [(lambda x: True, "Exp")],
+    "log": [(lambda x: True, "Log")],
+    "sin": [(lambda x: True, "Sin")],
+    "cos": [(lambda x: True, "Cos")],
+    "tan": [(lambda x: True, "Tan")],
+    "cot": [(lambda x: True, "Cot")],
+    "sec": [(lambda x: True, "Sec")],
+    "csc": [(lambda x: True, "Csc")],
+    "asin": [(lambda x: True, "ArcSin")],
+    "acos": [(lambda x: True, "ArcCos")],
+    "atan": [(lambda x: True, "ArcTan")],
+    "acot": [(lambda x: True, "ArcCot")],
+    "asec": [(lambda x: True, "ArcSec")],
+    "acsc": [(lambda x: True, "ArcCsc")],
+    "sinh": [(lambda x: True, "Sinh")],
+    "cosh": [(lambda x: True, "Cosh")],
+    "tanh": [(lambda x: True, "Tanh")],
+    "coth": [(lambda x: True, "Coth")],
+    "sech": [(lambda x: True, "Sech")],
+    "csch": [(lambda x: True, "Csch")],
+    "asinh": [(lambda x: True, "ArcSinh")],
+    "acosh": [(lambda x: True, "ArcCosh")],
+    "atanh": [(lambda x: True, "ArcTanh")],
+    "acoth": [(lambda x: True, "ArcCoth")],
+    "asech": [(lambda x: True, "ArcSech")],
+    "acsch": [(lambda x: True, "ArcCsch")],
+    "sinc": [(lambda x: True, "Sinc")],
+    "conjugate": [(lambda x: True, "Conjugate")],
+    "Max": [(lambda *x: True, "Max")],
+    "Min": [(lambda *x: True, "Min")],
+    "erf": [(lambda x: True, "Erf")],
+    "erf2": [(lambda *x: True, "Erf")],
+    "erfc": [(lambda x: True, "Erfc")],
+    "erfi": [(lambda x: True, "Erfi")],
+    "erfinv": [(lambda x: True, "InverseErf")],
+    "erfcinv": [(lambda x: True, "InverseErfc")],
+    "erf2inv": [(lambda *x: True, "InverseErf")],
+    "expint": [(lambda *x: True, "ExpIntegralE")],
+    "Ei": [(lambda x: True, "ExpIntegralEi")],
+    "fresnelc": [(lambda x: True, "FresnelC")],
+    "fresnels": [(lambda x: True, "FresnelS")],
+    "gamma": [(lambda x: True, "Gamma")],
+    "uppergamma": [(lambda *x: True, "Gamma")],
+    "polygamma": [(lambda *x: True, "PolyGamma")],
+    "loggamma": [(lambda x: True, "LogGamma")],
+    "beta": [(lambda *x: True, "Beta")],
+    "Ci": [(lambda x: True, "CosIntegral")],
+    "Si": [(lambda x: True, "SinIntegral")],
+    "Chi": [(lambda x: True, "CoshIntegral")],
+    "Shi": [(lambda x: True, "SinhIntegral")],
+    "li": [(lambda x: True, "LogIntegral")],
+    "factorial": [(lambda x: True, "Factorial")],
+    "factorial2": [(lambda x: True, "Factorial2")],
+    "subfactorial": [(lambda x: True, "Subfactorial")],
+    "catalan": [(lambda x: True, "CatalanNumber")],
+    "harmonic": [(lambda *x: True, "HarmonicNumber")],
+    "lucas": [(lambda x: True, "LucasL")],
+    "RisingFactorial": [(lambda *x: True, "Pochhammer")],
+    "FallingFactorial": [(lambda *x: True, "FactorialPower")],
+    "laguerre": [(lambda *x: True, "LaguerreL")],
+    "assoc_laguerre": [(lambda *x: True, "LaguerreL")],
+    "hermite": [(lambda *x: True, "HermiteH")],
+    "jacobi": [(lambda *x: True, "JacobiP")],
+    "gegenbauer": [(lambda *x: True, "GegenbauerC")],
+    "chebyshevt": [(lambda *x: True, "ChebyshevT")],
+    "chebyshevu": [(lambda *x: True, "ChebyshevU")],
+    "legendre": [(lambda *x: True, "LegendreP")],
+    "assoc_legendre": [(lambda *x: True, "LegendreP")],
+    "mathieuc": [(lambda *x: True, "MathieuC")],
+    "mathieus": [(lambda *x: True, "MathieuS")],
+    "mathieucprime": [(lambda *x: True, "MathieuCPrime")],
+    "mathieusprime": [(lambda *x: True, "MathieuSPrime")],
+    "stieltjes": [(lambda x: True, "StieltjesGamma")],
+    "elliptic_e": [(lambda *x: True, "EllipticE")],
+    "elliptic_f": [(lambda *x: True, "EllipticE")],
+    "elliptic_k": [(lambda x: True, "EllipticK")],
+    "elliptic_pi": [(lambda *x: True, "EllipticPi")],
+    "zeta": [(lambda *x: True, "Zeta")],
+    "dirichlet_eta": [(lambda x: True, "DirichletEta")],
+    "riemann_xi": [(lambda x: True, "RiemannXi")],
+    "besseli": [(lambda *x: True, "BesselI")],
+    "besselj": [(lambda *x: True, "BesselJ")],
+    "besselk": [(lambda *x: True, "BesselK")],
+    "bessely": [(lambda *x: True, "BesselY")],
+    "hankel1": [(lambda *x: True, "HankelH1")],
+    "hankel2": [(lambda *x: True, "HankelH2")],
+    "airyai": [(lambda x: True, "AiryAi")],
+    "airybi": [(lambda x: True, "AiryBi")],
+    "airyaiprime": [(lambda x: True, "AiryAiPrime")],
+    "airybiprime": [(lambda x: True, "AiryBiPrime")],
+    "polylog": [(lambda *x: True, "PolyLog")],
+    "lerchphi": [(lambda *x: True, "LerchPhi")],
+    "gcd": [(lambda *x: True, "GCD")],
+    "lcm": [(lambda *x: True, "LCM")],
+    "jn": [(lambda *x: True, "SphericalBesselJ")],
+    "yn": [(lambda *x: True, "SphericalBesselY")],
+    "hyper": [(lambda *x: True, "HypergeometricPFQ")],
+    "meijerg": [(lambda *x: True, "MeijerG")],
+    "appellf1": [(lambda *x: True, "AppellF1")],
+    "DiracDelta": [(lambda x: True, "DiracDelta")],
+    "Heaviside": [(lambda x: True, "HeavisideTheta")],
+    "KroneckerDelta": [(lambda *x: True, "KroneckerDelta")],
+    "sqrt": [(lambda x: True, "Sqrt")],  # For automatic rewrites
+}
+
+
+class MCodePrinter(CodePrinter):
+    """A printer to convert Python expressions to
+    strings of the Wolfram's Mathematica code
+    """
+    printmethod = "_mcode"
+    language = "Wolfram Language"
+
+    _default_settings: dict[str, Any] = dict(CodePrinter._default_settings, **{
+        'precision': 15,
+        'user_functions': {},
+    })
+
+    _number_symbols: set[tuple[Expr, Float]] = set()
+    _not_supported: set[Basic] = set()
+
+    def __init__(self, settings={}):
+        """Register function mappings supplied by user"""
+        CodePrinter.__init__(self, settings)
+        self.known_functions = dict(known_functions)
+        userfuncs = settings.get('user_functions', {}).copy()
+        for k, v in userfuncs.items():
+            if not isinstance(v, list):
+                userfuncs[k] = [(lambda *x: True, v)]
+        self.known_functions.update(userfuncs)
+
+    def _format_code(self, lines):
+        return lines
+
+    def _print_Pow(self, expr):
+        PREC = precedence(expr)
+        return '%s^%s' % (self.parenthesize(expr.base, PREC),
+                          self.parenthesize(expr.exp, PREC))
+
+    def _print_Mul(self, expr):
+        PREC = precedence(expr)
+        c, nc = expr.args_cnc()
+        res = super()._print_Mul(expr.func(*c))
+        if nc:
+            res += '*'
+            res += '**'.join(self.parenthesize(a, PREC) for a in nc)
+        return res
+
+    def _print_Relational(self, expr):
+        lhs_code = self._print(expr.lhs)
+        rhs_code = self._print(expr.rhs)
+        op = expr.rel_op
+        return "{} {} {}".format(lhs_code, op, rhs_code)
+
+    # Primitive numbers
+    def _print_Zero(self, expr):
+        return '0'
+
+    def _print_One(self, expr):
+        return '1'
+
+    def _print_NegativeOne(self, expr):
+        return '-1'
+
+    def _print_Half(self, expr):
+        return '1/2'
+
+    def _print_ImaginaryUnit(self, expr):
+        return 'I'
+
+
+    # Infinity and invalid numbers
+    def _print_Infinity(self, expr):
+        return 'Infinity'
+
+    def _print_NegativeInfinity(self, expr):
+        return '-Infinity'
+
+    def _print_ComplexInfinity(self, expr):
+        return 'ComplexInfinity'
+
+    def _print_NaN(self, expr):
+        return 'Indeterminate'
+
+
+    # Mathematical constants
+    def _print_Exp1(self, expr):
+        return 'E'
+
+    def _print_Pi(self, expr):
+        return 'Pi'
+
+    def _print_GoldenRatio(self, expr):
+        return 'GoldenRatio'
+
+    def _print_TribonacciConstant(self, expr):
+        expanded = expr.expand(func=True)
+        PREC = precedence(expr)
+        return self.parenthesize(expanded, PREC)
+
+    def _print_EulerGamma(self, expr):
+        return 'EulerGamma'
+
+    def _print_Catalan(self, expr):
+        return 'Catalan'
+
+
+    def _print_list(self, expr):
+        return '{' + ', '.join(self.doprint(a) for a in expr) + '}'
+    _print_tuple = _print_list
+    _print_Tuple = _print_list
+
+    def _print_ImmutableDenseMatrix(self, expr):
+        return self.doprint(expr.tolist())
+
+    def _print_ImmutableSparseMatrix(self, expr):
+
+        def print_rule(pos, val):
+            return '{} -> {}'.format(
+            self.doprint((pos[0]+1, pos[1]+1)), self.doprint(val))
+
+        def print_data():
+            items = sorted(expr.todok().items(), key=default_sort_key)
+            return '{' + \
+                ', '.join(print_rule(k, v) for k, v in items) + \
+                '}'
+
+        def print_dims():
+            return self.doprint(expr.shape)
+
+        return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
+
+    def _print_ImmutableDenseNDimArray(self, expr):
+        return self.doprint(expr.tolist())
+
+    def _print_ImmutableSparseNDimArray(self, expr):
+        def print_string_list(string_list):
+            return '{' + ', '.join(a for a in string_list) + '}'
+
+        def to_mathematica_index(*args):
+            """Helper function to change Python style indexing to
+            Pathematica indexing.
+
+            Python indexing (0, 1 ... n-1)
+            -> Mathematica indexing (1, 2 ... n)
+            """
+            return tuple(i + 1 for i in args)
+
+        def print_rule(pos, val):
+            """Helper function to print a rule of Mathematica"""
+            return '{} -> {}'.format(self.doprint(pos), self.doprint(val))
+
+        def print_data():
+            """Helper function to print data part of Mathematica
+            sparse array.
+
+            It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
+            from
+            https://reference.wolfram.com/language/ref/SparseArray.html
+
+            ``data`` must be formatted with rule.
+            """
+            return print_string_list(
+                [print_rule(
+                    to_mathematica_index(*(expr._get_tuple_index(key))),
+                    value)
+                for key, value in sorted(expr._sparse_array.items())]
+            )
+
+        def print_dims():
+            """Helper function to print dimensions part of Mathematica
+            sparse array.
+
+            It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
+            from
+            https://reference.wolfram.com/language/ref/SparseArray.html
+            """
+            return self.doprint(expr.shape)
+
+        return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
+
+    def _print_Function(self, expr):
+        if expr.func.__name__ in self.known_functions:
+            cond_mfunc = self.known_functions[expr.func.__name__]
+            for cond, mfunc in cond_mfunc:
+                if cond(*expr.args):
+                    return "%s[%s]" % (mfunc, self.stringify(expr.args, ", "))
+        elif expr.func.__name__ in self._rewriteable_functions:
+            # Simple rewrite to supported function possible
+            target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
+            if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
+                return self._print(expr.rewrite(target_f))
+        return expr.func.__name__ + "[%s]" % self.stringify(expr.args, ", ")
+
+    _print_MinMaxBase = _print_Function
+
+    def _print_LambertW(self, expr):
+        if len(expr.args) == 1:
+            return "ProductLog[{}]".format(self._print(expr.args[0]))
+        return "ProductLog[{}, {}]".format(
+            self._print(expr.args[1]), self._print(expr.args[0]))
+
+    def _print_atan2(self, expr):
+        return "ArcTan[{}, {}]".format(
+            self._print(expr.args[1]), self._print(expr.args[0]))
+
+    def _print_Integral(self, expr):
+        if len(expr.variables) == 1 and not expr.limits[0][1:]:
+            args = [expr.args[0], expr.variables[0]]
+        else:
+            args = expr.args
+        return "Hold[Integrate[" + ', '.join(self.doprint(a) for a in args) + "]]"
+
+    def _print_Sum(self, expr):
+        return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"
+
+    def _print_Derivative(self, expr):
+        dexpr = expr.expr
+        dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
+        return "Hold[D[" + ', '.join(self.doprint(a) for a in [dexpr] + dvars) + "]]"
+
+
+    def _get_comment(self, text):
+        return "(* {} *)".format(text)
+
+
+def mathematica_code(expr, **settings):
+    r"""Converts an expr to a string of the Wolfram Mathematica code
+
+    Examples
+    ========
+
+    >>> from sympy import mathematica_code as mcode, symbols, sin
+    >>> x = symbols('x')
+    >>> mcode(sin(x).series(x).removeO())
+    '(1/120)*x^5 - 1/6*x^3 + x'
+    """
+    return MCodePrinter(settings).doprint(expr)
diff --git a/shared/package-files/b6/b69146ccc752a8fdc1a6b7d9c28c6c64cdac4fa3721da6e6fab01d67b974b508/hts.c b/shared/package-files/b6/b69146ccc752a8fdc1a6b7d9c28c6c64cdac4fa3721da6e6fab01d67b974b508/hts.c
new file mode 100644
index 0000000000000000000000000000000000000000..a8a8bead21c2b921c4baea8892d2eb39251b3fd4
--- /dev/null
+++ b/shared/package-files/b6/b69146ccc752a8fdc1a6b7d9c28c6c64cdac4fa3721da6e6fab01d67b974b508/hts.c
@@ -0,0 +1,5152 @@
+/*  hts.c -- format-neutral I/O, indexing, and iterator API functions.
+
+    Copyright (C) 2008, 2009, 2012-2024 Genome Research Ltd.
+    Copyright (C) 2012, 2013 Broad Institute.
+
+    Author: Heng Li 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef HAVE_LIBLZMA
+#ifdef HAVE_LZMA_H
+#include 
+#else
+#include "os/lzma_stub.h"
+#endif
+#endif
+
+#include "htslib/hts.h"
+#include "htslib/bgzf.h"
+#include "cram/cram.h"
+#include "htslib/hfile.h"
+#include "htslib/hts_endian.h"
+#include "version.h"
+#include "config_vars.h"
+#include "hts_internal.h"
+#include "hfile_internal.h"
+#include "sam_internal.h"
+#include "htslib/hts_expr.h"
+#include "htslib/hts_os.h" // drand48
+
+#include "htslib/khash.h"
+#include "htslib/kseq.h"
+#include "htslib/ksort.h"
+#include "htslib/tbx.h"
+#if defined(HAVE_EXTERNAL_LIBHTSCODECS)
+#include 
+#else
+#include "htscodecs/htscodecs/htscodecs.h"
+#endif
+
+#ifndef EFTYPE
+#define EFTYPE ENOEXEC
+#endif
+
+KHASH_INIT2(s2i,, kh_cstr_t, int64_t, 1, kh_str_hash_func, kh_str_hash_equal)
+
+HTSLIB_EXPORT
+int hts_verbose = HTS_LOG_WARNING;
+
+const char *hts_version(void)
+{
+    return HTS_VERSION_TEXT;
+}
+
+unsigned int hts_features(void) {
+    unsigned int feat = HTS_FEATURE_HTSCODECS; // Always present
+
+#ifdef PACKAGE_URL
+    feat |= HTS_FEATURE_CONFIGURE;
+#endif
+
+#ifdef ENABLE_PLUGINS
+    feat |= HTS_FEATURE_PLUGINS;
+#endif
+
+#ifdef HAVE_LIBCURL
+    feat |= HTS_FEATURE_LIBCURL;
+#endif
+
+#ifdef ENABLE_S3
+    feat |= HTS_FEATURE_S3;
+#endif
+
+#ifdef ENABLE_GCS
+    feat |= HTS_FEATURE_GCS;
+#endif
+
+#ifdef HAVE_LIBDEFLATE
+    feat |= HTS_FEATURE_LIBDEFLATE;
+#endif
+
+#ifdef HAVE_LIBLZMA
+    feat |= HTS_FEATURE_LZMA;
+#endif
+
+#ifdef HAVE_LIBBZ2
+    feat |= HTS_FEATURE_BZIP2;
+#endif
+
+    return feat;
+}
+
+const char *hts_test_feature(unsigned int id) {
+    unsigned int feat = hts_features();
+
+    switch (id) {
+    case HTS_FEATURE_CONFIGURE:
+        return feat & HTS_FEATURE_CONFIGURE ? "yes" : NULL;
+    case HTS_FEATURE_PLUGINS:
+        return feat & HTS_FEATURE_PLUGINS ? "yes" : NULL;
+    case HTS_FEATURE_LIBCURL:
+        return feat & HTS_FEATURE_LIBCURL ? "yes" : NULL;
+    case HTS_FEATURE_S3:
+        return feat & HTS_FEATURE_S3 ? "yes" : NULL;
+    case HTS_FEATURE_GCS:
+        return feat & HTS_FEATURE_GCS ? "yes" : NULL;
+    case HTS_FEATURE_LIBDEFLATE:
+        return feat & HTS_FEATURE_LIBDEFLATE ? "yes" : NULL;
+    case HTS_FEATURE_BZIP2:
+        return feat & HTS_FEATURE_BZIP2 ? "yes" : NULL;
+    case HTS_FEATURE_LZMA:
+        return feat & HTS_FEATURE_LZMA ? "yes" : NULL;
+
+    case HTS_FEATURE_HTSCODECS:
+        return htscodecs_version();
+
+    case HTS_FEATURE_CC:
+        return HTS_CC;
+    case HTS_FEATURE_CFLAGS:
+        return HTS_CFLAGS;
+    case HTS_FEATURE_LDFLAGS:
+        return HTS_LDFLAGS;
+    case HTS_FEATURE_CPPFLAGS:
+        return HTS_CPPFLAGS;
+
+    default:
+        fprintf(stderr, "Unknown feature code: %u\n", id);
+    }
+
+    return NULL;
+}
+
+// Note this implementation also means we can just "strings" the library
+// to find the configuration parameters.
+const char *hts_feature_string(void) {
+    static char config[1200];
+    const char *flags=
+
+#ifdef PACKAGE_URL
+    "build=configure "
+#else
+    "build=Makefile "
+#endif
+
+#ifdef HAVE_LIBCURL
+    "libcurl=yes "
+#else
+    "libcurl=no "
+#endif
+
+#ifdef ENABLE_S3
+    "S3=yes "
+#else
+    "S3=no "
+#endif
+
+#ifdef ENABLE_GCS
+    "GCS=yes "
+#else
+    "GCS=no "
+#endif
+
+#ifdef HAVE_LIBDEFLATE
+    "libdeflate=yes "
+#else
+    "libdeflate=no "
+#endif
+
+#ifdef HAVE_LIBLZMA
+    "lzma=yes "
+#else
+    "lzma=no "
+#endif
+
+#ifdef HAVE_LIBBZ2
+    "bzip2=yes "
+#else
+    "bzip2=no "
+#endif
+
+// "plugins=" must stay at the end as it is followed by "plugin-path="
+#ifdef ENABLE_PLUGINS
+    "plugins=yes";
+#else
+    "plugins=no";
+#endif
+
+#ifdef ENABLE_PLUGINS
+    snprintf(config, sizeof(config),
+             "%s plugin-path=%.1000s htscodecs=%.40s",
+             flags, hts_plugin_path(), htscodecs_version());
+#else
+    snprintf(config, sizeof(config),
+             "%s htscodecs=%.40s",
+             flags, htscodecs_version());
+#endif
+    return config;
+}
+
+
+HTSLIB_EXPORT
+const unsigned char seq_nt16_table[256] = {
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+     1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15,
+    15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
+    15,15, 5, 6,  8,15, 7, 9, 15,10,15,15, 15,15,15,15,
+    15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
+    15,15, 5, 6,  8,15, 7, 9, 15,10,15,15, 15,15,15,15,
+
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+    15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15
+};
+
+HTSLIB_EXPORT
+const char seq_nt16_str[] = "=ACMGRSVTWYHKDBN";
+
+HTSLIB_EXPORT
+const int seq_nt16_int[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 };
+
+/**********************
+ *** Basic file I/O ***
+ **********************/
+
+static enum htsFormatCategory format_category(enum htsExactFormat fmt)
+{
+    switch (fmt) {
+    case bam:
+    case sam:
+    case cram:
+    case fastq_format:
+    case fasta_format:
+        return sequence_data;
+
+    case vcf:
+    case bcf:
+        return variant_data;
+
+    case bai:
+    case crai:
+    case csi:
+    case fai_format:
+    case fqi_format:
+    case gzi:
+    case tbi:
+        return index_file;
+
+    case bed:
+    case d4_format:
+        return region_list;
+
+    case htsget:
+    case hts_crypt4gh_format:
+        return unknown_category;
+
+    case unknown_format:
+    case binary_format:
+    case text_format:
+    case empty_format:
+    case format_maximum:
+        break;
+    }
+
+    return unknown_category;
+}
+
+// Decompress several hundred bytes by peeking at the file, which must be
+// positioned at the start of a GZIP block.
+static ssize_t
+decompress_peek_gz(hFILE *fp, unsigned char *dest, size_t destsize)
+{
+    unsigned char buffer[2048];
+    z_stream zs;
+    ssize_t npeek = hpeek(fp, buffer, sizeof buffer);
+
+    if (npeek < 0) return -1;
+
+    zs.zalloc = NULL;
+    zs.zfree = NULL;
+    zs.next_in = buffer;
+    zs.avail_in = npeek;
+    zs.next_out = dest;
+    zs.avail_out = destsize;
+    if (inflateInit2(&zs, 31) != Z_OK) return -1;
+
+    int ret;
+    const unsigned char *last_in = buffer;
+    while (zs.avail_out > 0) {
+        ret = inflate(&zs, Z_SYNC_FLUSH);
+        if (ret == Z_STREAM_END) {
+            if (last_in == zs.next_in)
+                break; // Paranoia to avoid potential looping. Shouldn't happen
+            else
+                last_in = zs.next_in;
+            inflateReset(&zs);
+        } else if (ret != Z_OK) {
+            // eg Z_BUF_ERROR due to avail_in/out becoming zero
+            break;
+        }
+    }
+
+    // NB: zs.total_out is changed by inflateReset, so use pointer diff instead
+    destsize = zs.next_out - dest;
+    inflateEnd(&zs);
+
+    return destsize;
+}
+
+#ifdef HAVE_LIBLZMA
+// Similarly decompress a portion by peeking at the file, which must be
+// positioned at the start of the file.
+static ssize_t
+decompress_peek_xz(hFILE *fp, unsigned char *dest, size_t destsize)
+{
+    unsigned char buffer[2048];
+    ssize_t npeek = hpeek(fp, buffer, sizeof buffer);
+    if (npeek < 0) return -1;
+
+    lzma_stream ls = LZMA_STREAM_INIT;
+    if (lzma_stream_decoder(&ls, lzma_easy_decoder_memusage(9), 0) != LZMA_OK)
+        return -1;
+
+    ls.next_in = buffer;
+    ls.avail_in = npeek;
+    ls.next_out = dest;
+    ls.avail_out = destsize;
+
+    int r = lzma_code(&ls, LZMA_RUN);
+    if (! (r == LZMA_OK || r == LZMA_STREAM_END)) {
+        lzma_end(&ls);
+        return -1;
+    }
+
+    destsize = ls.total_out;
+    lzma_end(&ls);
+
+    return destsize;
+}
+#endif
+
+// Parse "x.y" text, taking care because the string is not NUL-terminated
+// and filling in major/minor only when the digits are followed by a delimiter,
+// so we don't misread "1.10" as "1.1" due to reaching the end of the buffer.
+static void
+parse_version(htsFormat *fmt, const unsigned char *u, const unsigned char *ulim)
+{
+    const char *s    = (const char *) u;
+    const char *slim = (const char *) ulim;
+    short v;
+
+    fmt->version.major = fmt->version.minor = -1;
+
+    for (v = 0; s < slim && isdigit_c(*s); s++)
+        v = 10 * v + *s - '0';
+
+    if (s < slim) {
+        fmt->version.major = v;
+        if (*s == '.') {
+            s++;
+            for (v = 0; s < slim && isdigit_c(*s); s++)
+                v = 10 * v + *s - '0';
+            if (s < slim)
+                fmt->version.minor = v;
+        }
+        else
+            fmt->version.minor = 0;
+    }
+}
+
+static int
+cmp_nonblank(const char *key, const unsigned char *u, const unsigned char *ulim)
+{
+    const unsigned char *ukey = (const unsigned char *) key;
+
+    while (*ukey)
+        if (u >= ulim) return +1;
+        else if (isspace_c(*u)) u++;
+        else if (*u != *ukey) return (*ukey < *u)? -1 : +1;
+        else u++, ukey++;
+
+    return 0;
+}
+
+static int is_text_only(const unsigned char *u, const unsigned char *ulim)
+{
+    for (; u < ulim; u++)
+        if (! (*u >= ' ' || *u == '\t' || *u == '\r' || *u == '\n'))
+            return 0;
+
+    return 1;
+}
+
+static inline int
+alternate_zeros(const unsigned char *u, const unsigned char *ulim)
+{
+    for (; u < ulim; u += 2)
+        if (*u != '\0') return 0;
+    return 1;
+}
+
+static int is_utf16_text(const unsigned char *u, const unsigned char *ulim)
+{
+    if (ulim - u >= 6 &&
+        ((u[0] == 0xfe && u[1] == 0xff && alternate_zeros(u+2, ulim)) ||
+         (u[0] == 0xff && u[1] == 0xfe && alternate_zeros(u+3, ulim))))
+        return 2;
+    else if (ulim - u >= 8 &&
+             (alternate_zeros(u, ulim) || alternate_zeros(u+1, ulim)))
+        return 1;
+    else
+        return 0;
+}
+
+static int is_fastaq(const unsigned char *u, const unsigned char *ulim)
+{
+    const unsigned char *eol = memchr(u, '\n', ulim - u);
+
+    // Check that the first line is entirely textual
+    if (! is_text_only(u, eol? eol : ulim)) return 0;
+
+    // If the first line is very long, consider the file to indeed be FASTA/Q
+    if (eol == NULL) return 1;
+
+    u = eol+1; // Now points to the first character of the second line
+
+    // Scan over all base-encoding letters (including 'N' but not SEQ's '=')
+    while (u < ulim && (seq_nt16_table[*u] != 15 || toupper(*u) == 'N')) {
+        if (*u == '=') return 0;
+        u++;
+    }
+
+    return (u == ulim || *u == '\r' || *u == '\n')? 1 : 0;
+}
+
+// Parse tab-delimited text, filling in a string of column types and returning
+// the number of columns spotted (within [u,ulim), and up to column_len) or -1
+// if non-printable characters were seen.  Column types:
+//     i: integer, s: strand sign, C: CIGAR, O: SAM optional field, Z: anything
+static int
+parse_tabbed_text(char *columns, int column_len,
+                  const unsigned char *u, const unsigned char *ulim,
+                  int *complete)
+{
+    const char *str  = (const char *) u;
+    const char *slim = (const char *) ulim;
+    const char *s;
+    int ncolumns = 0;
+
+    enum { digit = 1, leading_sign = 2, cigar_operator = 4, other = 8 };
+    unsigned seen = 0;
+    *complete = 0;
+
+    for (s = str; s < slim; s++)
+        if (*s >= ' ') {
+            if (isdigit_c(*s))
+                seen |= digit;
+            else if ((*s == '+' || *s == '-') && s == str)
+                seen |= leading_sign;
+            else if (strchr(BAM_CIGAR_STR, *s) && s > str && isdigit_c(s[-1]))
+                seen |= cigar_operator;
+            else
+                seen |= other;
+        }
+        else if (*s == '\t' || *s == '\r' || *s == '\n') {
+            size_t len = s - str;
+            char type;
+
+            if (seen == digit || seen == (leading_sign|digit)) type = 'i';
+            else if (seen == (digit|cigar_operator)) type = 'C';
+            else if (len == 1)
+                switch (str[0]) {
+                case '*': type = 'C'; break;
+                case '+': case '-': case '.': type = 's'; break;
+                default: type = 'Z'; break;
+                }
+            else if (len >= 5 && str[2] == ':' && str[4] == ':') type = 'O';
+            else type = 'Z';
+
+            columns[ncolumns++] = type;
+            if (*s != '\t' || ncolumns >= column_len - 1) {
+                *complete = 1; // finished the line or more columns than needed
+                break;
+            }
+
+            str = s + 1;
+            seen = 0;
+        }
+        else return -1;
+
+    columns[ncolumns] = '\0';
+    return ncolumns;
+}
+
+// Match COLUMNS as a prefix against PATTERN (so COLUMNS may run out first).
+// Returns len(COLUMNS) (modulo '+'), or 0 if there is a mismatched entry.
+static int colmatch(const char *columns, const char *pattern)
+{
+    int i;
+    for (i = 0; columns[i] != '\0'; i++) {
+        if (pattern[i] == '+') return i;
+        if (! (columns[i] == pattern[i] || pattern[i] == 'Z')) return 0;
+    }
+
+    return i;
+}
+
+int hts_detect_format(hFILE *hfile, htsFormat *fmt)
+{
+    return hts_detect_format2(hfile, NULL, fmt);
+}
+
+int hts_detect_format2(hFILE *hfile, const char *fname, htsFormat *fmt)
+{
+    char extension[HTS_MAX_EXT_LEN], columns[24];
+    unsigned char s[1024];
+    int complete = 0;
+    ssize_t len = hpeek(hfile, s, 18);
+    if (len < 0) return -1;
+
+    fmt->category = unknown_category;
+    fmt->format = unknown_format;
+    fmt->version.major = fmt->version.minor = -1;
+    fmt->compression = no_compression;
+    fmt->compression_level = -1;
+    fmt->specific = NULL;
+
+    if (len >= 2 && s[0] == 0x1f && s[1] == 0x8b) {
+        // The stream is either gzip-compressed or BGZF-compressed.
+        // Determine which, and decompress the first few records or lines.
+        fmt->compression = gzip;
+        if (len >= 18 && (s[3] & 4)) {
+            if (memcmp(&s[12], "BC\2\0", 4) == 0)
+                fmt->compression = bgzf;
+            else if (memcmp(&s[12], "RAZF", 4) == 0)
+                fmt->compression = razf_compression;
+        }
+        if (len >= 9 && s[2] == 8)
+            fmt->compression_level = (s[8] == 2)? 9 : (s[8] == 4)? 1 : -1;
+
+        len = decompress_peek_gz(hfile, s, sizeof s);
+    }
+    else if (len >= 10 && memcmp(s, "BZh", 3) == 0 &&
+             (memcmp(&s[4], "\x31\x41\x59\x26\x53\x59", 6) == 0 ||
+              memcmp(&s[4], "\x17\x72\x45\x38\x50\x90", 6) == 0)) {
+        fmt->compression = bzip2_compression;
+        fmt->compression_level = s[3] - '0';
+        // Decompressing via libbz2 produces no output until it has a whole
+        // block (of size 100Kb x level), which is too large for peeking.
+        // So unfortunately we can recognise bzip2 but not the contents,
+        // except that \x1772... magic indicates the stream is empty.
+        if (s[4] == '\x31') return 0;
+        else len = 0;
+    }
+    else if (len >= 6 && memcmp(s, "\xfd""7zXZ\0", 6) == 0) {
+        fmt->compression = xz_compression;
+#ifdef HAVE_LIBLZMA
+        len = decompress_peek_xz(hfile, s, sizeof s);
+#else
+        // Without liblzma, we can't recognise the decompressed contents.
+        return 0;
+#endif
+    }
+    else if (len >= 4 && memcmp(s, "\x28\xb5\x2f\xfd", 4) == 0) {
+        fmt->compression = zstd_compression;
+        return 0;
+    }
+    else {
+        len = hpeek(hfile, s, sizeof s);
+    }
+    if (len < 0) return -1;
+
+    if (len == 0) {
+        fmt->format = empty_format;
+        return 0;
+    }
+
+    // We avoid using filename extensions wherever possible (as filenames are
+    // not always available), but in a few cases they must be considered:
+    //  - FASTA/Q indexes are simply tab-separated text; files that match these
+    //    patterns but not the fai/fqi extension are usually generic BED files
+    //  - GZI indexes have no magic numbers so can only be detected by filename
+    if (fname && strcmp(fname, "-") != 0) {
+        char *s;
+        if (find_file_extension(fname, extension) < 0) extension[0] = '\0';
+        for (s = extension; *s; s++) *s = tolower_c(*s);
+    }
+    else extension[0] = '\0';
+
+    if (len >= 6 && memcmp(s,"CRAM",4) == 0 && s[4]>=1 && s[4]<=7 && s[5]<=7) {
+        fmt->category = sequence_data;
+        fmt->format = cram;
+        fmt->version.major = s[4], fmt->version.minor = s[5];
+        fmt->compression = custom;
+        return 0;
+    }
+    else if (len >= 4 && s[3] <= '\4') {
+        if (memcmp(s, "BAM\1", 4) == 0) {
+            fmt->category = sequence_data;
+            fmt->format = bam;
+            // TODO Decompress enough to pick version from @HD-VN header
+            fmt->version.major = 1, fmt->version.minor = -1;
+            return 0;
+        }
+        else if (memcmp(s, "BAI\1", 4) == 0) {
+            fmt->category = index_file;
+            fmt->format = bai;
+            fmt->version.major = -1, fmt->version.minor = -1;
+            return 0;
+        }
+        else if (memcmp(s, "BCF\4", 4) == 0) {
+            fmt->category = variant_data;
+            fmt->format = bcf;
+            fmt->version.major = 1, fmt->version.minor = -1;
+            return 0;
+        }
+        else if (memcmp(s, "BCF\2", 4) == 0) {
+            fmt->category = variant_data;
+            fmt->format = bcf;
+            fmt->version.major = s[3];
+            fmt->version.minor = (len >= 5 && s[4] <= 2)? s[4] : 0;
+            return 0;
+        }
+        else if (memcmp(s, "CSI\1", 4) == 0) {
+            fmt->category = index_file;
+            fmt->format = csi;
+            fmt->version.major = 1, fmt->version.minor = -1;
+            return 0;
+        }
+        else if (memcmp(s, "TBI\1", 4) == 0) {
+            fmt->category = index_file;
+            fmt->format = tbi;
+            return 0;
+        }
+        // GZI indexes have no magic numbers, so must be recognised solely by
+        // filename extension.
+        else if (strcmp(extension, "gzi") == 0) {
+            fmt->category = index_file;
+            fmt->format = gzi;
+            return 0;
+        }
+    }
+    else if (len >= 16 && memcmp(s, "##fileformat=VCF", 16) == 0) {
+        fmt->category = variant_data;
+        fmt->format = vcf;
+        if (len >= 21 && s[16] == 'v')
+            parse_version(fmt, &s[17], &s[len]);
+        return 0;
+    }
+    else if (len >= 4 && s[0] == '@' &&
+             (memcmp(s, "@HD\t", 4) == 0 || memcmp(s, "@SQ\t", 4) == 0 ||
+              memcmp(s, "@RG\t", 4) == 0 || memcmp(s, "@PG\t", 4) == 0 ||
+              memcmp(s, "@CO\t", 4) == 0)) {
+        fmt->category = sequence_data;
+        fmt->format = sam;
+        // @HD-VN is not guaranteed to be the first tag, but then @HD is
+        // not guaranteed to be present at all...
+        if (len >= 9 && memcmp(s, "@HD\tVN:", 7) == 0)
+            parse_version(fmt, &s[7], &s[len]);
+        else
+            fmt->version.major = 1, fmt->version.minor = -1;
+        return 0;
+    }
+    else if (len >= 8 && memcmp(s, "d4\xdd\xdd", 4) == 0) {
+        fmt->category = region_list;
+        fmt->format = d4_format;
+        // How to decode the D4 Format Version bytes is not yet specified
+        // so we don't try to set fmt->version.{major,minor}.
+        return 0;
+    }
+    else if (cmp_nonblank("{\"htsget\":", s, &s[len]) == 0) {
+        fmt->category = unknown_category;
+        fmt->format = htsget;
+        return 0;
+    }
+    else if (len > 8 && memcmp(s, "crypt4gh", 8) == 0) {
+        fmt->category = unknown_category;
+        fmt->format = hts_crypt4gh_format;
+        return 0;
+    }
+    else if (len >= 1 && s[0] == '>' && is_fastaq(s, &s[len])) {
+        fmt->category = sequence_data;
+        fmt->format = fasta_format;
+        return 0;
+    }
+    else if (len >= 1 && s[0] == '@' && is_fastaq(s, &s[len])) {
+        fmt->category = sequence_data;
+        fmt->format = fastq_format;
+        return 0;
+    }
+    else if (parse_tabbed_text(columns, sizeof columns, s,
+                               &s[len], &complete) > 0) {
+        // A complete SAM line is at least 11 columns.  On unmapped long reads may
+        // be missing two.  (On mapped long reads we must have an @ header so long
+        // CIGAR is irrelevant.)
+        if (colmatch(columns, "ZiZiiCZiiZZOOOOOOOOOOOOOOOOOOOO+")
+            >= 9 + 2*complete) {
+            fmt->category = sequence_data;
+            fmt->format = sam;
+            fmt->version.major = 1, fmt->version.minor = -1;
+            return 0;
+        }
+        else if (fmt->compression == gzip && colmatch(columns, "iiiiii") == 6) {
+            fmt->category = index_file;
+            fmt->format = crai;
+            return 0;
+        }
+        else if (strstr(extension, "fqi") && colmatch(columns, "Ziiiii") == 6) {
+            fmt->category = index_file;
+            fmt->format = fqi_format;
+            return 0;
+        }
+        else if (strstr(extension, "fai") && colmatch(columns, "Ziiii") == 5) {
+            fmt->category = index_file;
+            fmt->format = fai_format;
+            return 0;
+        }
+        else if (colmatch(columns, "Zii+") >= 3) {
+            fmt->category = region_list;
+            fmt->format = bed;
+            return 0;
+        }
+    }
+
+    // Arbitrary text files can be read using hts_getline().
+    if (is_text_only(s, &s[len])) fmt->format = text_format;
+
+    // Nothing recognised: leave unset fmt-> fields as unknown.
+    return 0;
+}
+
+char *hts_format_description(const htsFormat *format)
+{
+    kstring_t str = { 0, 0, NULL };
+
+    switch (format->format) {
+    case sam:   kputs("SAM", &str); break;
+    case bam:   kputs("BAM", &str); break;
+    case cram:  kputs("CRAM", &str); break;
+    case fasta_format:  kputs("FASTA", &str); break;
+    case fastq_format:  kputs("FASTQ", &str); break;
+    case vcf:   kputs("VCF", &str); break;
+    case bcf:
+        if (format->version.major == 1) kputs("Legacy BCF", &str);
+        else kputs("BCF", &str);
+        break;
+    case bai:   kputs("BAI", &str); break;
+    case crai:  kputs("CRAI", &str); break;
+    case csi:   kputs("CSI", &str); break;
+    case fai_format:    kputs("FASTA-IDX", &str); break;
+    case fqi_format:    kputs("FASTQ-IDX", &str); break;
+    case gzi:   kputs("GZI", &str); break;
+    case tbi:   kputs("Tabix", &str); break;
+    case bed:   kputs("BED", &str); break;
+    case d4_format:     kputs("D4", &str); break;
+    case htsget: kputs("htsget", &str); break;
+    case hts_crypt4gh_format: kputs("crypt4gh", &str); break;
+    case empty_format:  kputs("empty", &str); break;
+    default:    kputs("unknown", &str); break;
+    }
+
+    if (format->version.major >= 0) {
+        kputs(" version ", &str);
+        kputw(format->version.major, &str);
+        if (format->version.minor >= 0) {
+            kputc('.', &str);
+            kputw(format->version.minor, &str);
+        }
+    }
+
+    switch (format->compression) {
+    case bzip2_compression:  kputs(" bzip2-compressed", &str); break;
+    case razf_compression:   kputs(" legacy-RAZF-compressed", &str); break;
+    case xz_compression:     kputs(" XZ-compressed", &str); break;
+    case zstd_compression:   kputs(" Zstandard-compressed", &str); break;
+    case custom: kputs(" compressed", &str); break;
+    case gzip:   kputs(" gzip-compressed", &str); break;
+
+    case bgzf:
+        switch (format->format) {
+        case bam:
+        case bcf:
+        case csi:
+        case tbi:
+            // These are by definition BGZF, so just use the generic term
+            kputs(" compressed", &str);
+            break;
+        default:
+            kputs(" BGZF-compressed", &str);
+            break;
+        }
+        break;
+
+    case no_compression:
+        switch (format->format) {
+        case bam:
+        case bcf:
+        case cram:
+        case csi:
+        case tbi:
+            // These are normally compressed, so emphasise that this one isn't
+            kputs(" uncompressed", &str);
+            break;
+        default:
+            break;
+        }
+        break;
+
+    default: break;
+    }
+
+    switch (format->category) {
+    case sequence_data: kputs(" sequence", &str); break;
+    case variant_data:  kputs(" variant calling", &str); break;
+    case index_file:    kputs(" index", &str); break;
+    case region_list:   kputs(" genomic region", &str); break;
+    default: break;
+    }
+
+    if (format->compression == no_compression)
+        switch (format->format) {
+        case text_format:
+        case sam:
+        case crai:
+        case vcf:
+        case bed:
+        case fai_format:
+        case fqi_format:
+        case fasta_format:
+        case fastq_format:
+        case htsget:
+            kputs(" text", &str);
+            break;
+
+        case empty_format:
+            break;
+
+        default:
+            kputs(" data", &str);
+            break;
+        }
+    else
+        kputs(" data", &str);
+
+    return ks_release(&str);
+}
+
+htsFile *hts_open_format(const char *fn, const char *mode, const htsFormat *fmt)
+{
+    char smode[101], *cp, *cp2, *mode_c, *uncomp = NULL;
+    htsFile *fp = NULL;
+    hFILE *hfile = NULL;
+    char fmt_code = '\0';
+    // see enum htsExactFormat in htslib/hts.h
+    const char format_to_mode[] = "\0g\0\0b\0c\0\0b\0g\0\0\0\0\0Ff\0\0";
+
+    strncpy(smode, mode, 99);
+    smode[99]=0;
+    if ((cp = strchr(smode, ',')))
+        *cp = '\0';
+
+    // Migrate format code (b or c) to the end of the smode buffer.
+    for (cp2 = cp = smode; *cp; cp++) {
+        if (*cp == 'b')
+            fmt_code = 'b';
+        else if (*cp == 'c')
+            fmt_code = 'c';
+        else {
+            *cp2++ = *cp;
+            // Cache the uncompress flag 'u' pos if present
+            if (!uncomp && (*cp == 'u')) {
+                uncomp = cp2 - 1;
+            }
+        }
+    }
+    mode_c = cp2;
+    *cp2++ = fmt_code;
+    *cp2++ = 0;
+
+    // Set or reset the format code if opts->format is used
+    if (fmt && fmt->format > unknown_format
+        && fmt->format < sizeof(format_to_mode)) {
+        *mode_c = format_to_mode[fmt->format];
+    }
+
+    // Uncompressed bam/bcf is not supported, change 'u' to '0' on write
+    if (uncomp && *mode_c == 'b' && (strchr(smode, 'w') || strchr(smode, 'a'))) {
+        *uncomp = '0';
+    }
+
+    // If we really asked for a compressed text format then mode_c above will
+    // point to nul.  We set to 'z' to enable bgzf.
+    if (strchr(mode, 'w') && fmt && fmt->compression == bgzf) {
+        if (fmt->format == sam || fmt->format == vcf || fmt->format == text_format)
+            *mode_c = 'z';
+    }
+
+    char *rmme = NULL, *fnidx = strstr(fn, HTS_IDX_DELIM);
+    if ( fnidx ) {
+        rmme = strdup(fn);
+        if ( !rmme ) goto error;
+        rmme[fnidx-fn] = 0;
+        fn = rmme;
+    }
+
+    hfile = hopen(fn, smode);
+    if (hfile == NULL) goto error;
+
+    fp = hts_hopen(hfile, fn, smode);
+    if (fp == NULL) goto error;
+
+    // Compensate for the loss of exactness in htsExactFormat.
+    // hts_hopen returns generics such as binary or text, but we
+    // have been given something explicit here so use that instead.
+    if (fp->is_write && fmt &&
+        (fmt->format == bam || fmt->format == sam ||
+         fmt->format == vcf || fmt->format == bcf ||
+         fmt->format == bed || fmt->format == fasta_format ||
+         fmt->format == fastq_format))
+        fp->format.format = fmt->format;
+
+    if (fmt && fmt->specific) {
+        if (hts_opt_apply(fp, fmt->specific) != 0) {
+            if (((hts_opt*)fmt->specific)->opt == CRAM_OPT_REFERENCE &&
+                (errno == ENOENT || errno == EIO || errno == EBADF ||
+                  errno == EACCES || errno == EISDIR)) {
+                /* error during reference file operation
+                 for these specific errors, set the error as EINVAL */
+                errno = EINVAL;
+            }
+            goto error;
+        }
+    }
+    if ( rmme ) free(rmme);
+    return fp;
+
+error:
+    hts_log_error("Failed to open file \"%s\"%s%s", fn,
+                  errno ? " : " : "", errno ? strerror(errno) : "");
+    if ( rmme ) free(rmme);
+
+    if (hfile)
+        hclose_abruptly(hfile);
+
+    return NULL;
+}
+
+htsFile *hts_open(const char *fn, const char *mode) {
+    return hts_open_format(fn, mode, NULL);
+}
+
+/*
+ * Splits str into a prefix, delimiter ('\0' or delim), and suffix, writing
+ * the prefix in lowercase into buf and returning a pointer to the suffix.
+ * On return, buf is always NUL-terminated; thus assumes that the "keyword"
+ * prefix should be one of several known values of maximum length buflen-2.
+ * (If delim is not found, returns a pointer to the '\0'.)
+ */
+static const char *
+scan_keyword(const char *str, char delim, char *buf, size_t buflen)
+{
+    size_t i = 0;
+    while (*str && *str != delim) {
+        if (i < buflen-1) buf[i++] = tolower_c(*str);
+        str++;
+    }
+
+    buf[i] = '\0';
+    return *str? str+1 : str;
+}
+
+/*
+ * Parses arg and appends it to the option list.
+ *
+ * Returns 0 on success;
+ *        -1 on failure.
+ */
+int hts_opt_add(hts_opt **opts, const char *c_arg) {
+    hts_opt *o, *t;
+    char *val;
+
+    /*
+     * IMPORTANT!!!
+     * If you add another string option here, don't forget to also add
+     * it to the case statement in hts_opt_apply.
+     */
+
+    if (!c_arg)
+        return -1;
+
+    if (!(o =  malloc(sizeof(*o))))
+        return -1;
+
+    if (!(o->arg = strdup(c_arg))) {
+        free(o);
+        return -1;
+    }
+
+    if (!(val = strchr(o->arg, '=')))
+        val = "1"; // assume boolean
+    else
+        *val++ = '\0';
+
+    if (strcmp(o->arg, "decode_md") == 0 ||
+        strcmp(o->arg, "DECODE_MD") == 0)
+        o->opt = CRAM_OPT_DECODE_MD, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "verbosity") == 0 ||
+             strcmp(o->arg, "VERBOSITY") == 0)
+        o->opt = CRAM_OPT_VERBOSITY, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "seqs_per_slice") == 0 ||
+             strcmp(o->arg, "SEQS_PER_SLICE") == 0)
+        o->opt = CRAM_OPT_SEQS_PER_SLICE, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "bases_per_slice") == 0 ||
+             strcmp(o->arg, "BASES_PER_SLICE") == 0)
+        o->opt = CRAM_OPT_BASES_PER_SLICE, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "slices_per_container") == 0 ||
+             strcmp(o->arg, "SLICES_PER_CONTAINER") == 0)
+        o->opt = CRAM_OPT_SLICES_PER_CONTAINER, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "embed_ref") == 0 ||
+             strcmp(o->arg, "EMBED_REF") == 0)
+        o->opt = CRAM_OPT_EMBED_REF, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "no_ref") == 0 ||
+             strcmp(o->arg, "NO_REF") == 0)
+        o->opt = CRAM_OPT_NO_REF, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "pos_delta") == 0 ||
+             strcmp(o->arg, "POS_DELTA") == 0)
+        o->opt = CRAM_OPT_POS_DELTA, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "ignore_md5") == 0 ||
+             strcmp(o->arg, "IGNORE_MD5") == 0)
+        o->opt = CRAM_OPT_IGNORE_MD5, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_bzip2") == 0 ||
+             strcmp(o->arg, "USE_BZIP2") == 0)
+        o->opt = CRAM_OPT_USE_BZIP2, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_rans") == 0 ||
+             strcmp(o->arg, "USE_RANS") == 0)
+        o->opt = CRAM_OPT_USE_RANS, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_lzma") == 0 ||
+             strcmp(o->arg, "USE_LZMA") == 0)
+        o->opt = CRAM_OPT_USE_LZMA, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_tok") == 0 ||
+             strcmp(o->arg, "USE_TOK") == 0)
+        o->opt = CRAM_OPT_USE_TOK, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_fqz") == 0 ||
+             strcmp(o->arg, "USE_FQZ") == 0)
+        o->opt = CRAM_OPT_USE_FQZ, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "use_arith") == 0 ||
+             strcmp(o->arg, "USE_ARITH") == 0)
+        o->opt = CRAM_OPT_USE_ARITH, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "fast") == 0 ||
+             strcmp(o->arg, "FAST") == 0)
+        o->opt = HTS_OPT_PROFILE, o->val.i = HTS_PROFILE_FAST;
+
+    else if (strcmp(o->arg, "normal") == 0 ||
+             strcmp(o->arg, "NORMAL") == 0)
+        o->opt = HTS_OPT_PROFILE, o->val.i = HTS_PROFILE_NORMAL;
+
+    else if (strcmp(o->arg, "small") == 0 ||
+             strcmp(o->arg, "SMALL") == 0)
+        o->opt = HTS_OPT_PROFILE, o->val.i = HTS_PROFILE_SMALL;
+
+    else if (strcmp(o->arg, "archive") == 0 ||
+             strcmp(o->arg, "ARCHIVE") == 0)
+        o->opt = HTS_OPT_PROFILE, o->val.i = HTS_PROFILE_ARCHIVE;
+
+    else if (strcmp(o->arg, "reference") == 0 ||
+             strcmp(o->arg, "REFERENCE") == 0)
+        o->opt = CRAM_OPT_REFERENCE, o->val.s = val;
+
+    else if (strcmp(o->arg, "version") == 0 ||
+             strcmp(o->arg, "VERSION") == 0)
+        o->opt = CRAM_OPT_VERSION, o->val.s =val;
+
+    else if (strcmp(o->arg, "multi_seq_per_slice") == 0 ||
+             strcmp(o->arg, "MULTI_SEQ_PER_SLICE") == 0)
+        o->opt = CRAM_OPT_MULTI_SEQ_PER_SLICE, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "nthreads") == 0 ||
+             strcmp(o->arg, "NTHREADS") == 0)
+        o->opt = HTS_OPT_NTHREADS, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "cache_size") == 0 ||
+             strcmp(o->arg, "CACHE_SIZE") == 0) {
+        char *endp;
+        o->opt = HTS_OPT_CACHE_SIZE;
+        o->val.i = strtol(val, &endp, 0);
+        // NB: Doesn't support floats, eg 1.5g
+        // TODO: extend hts_parse_decimal? See also samtools sort.
+        switch (*endp) {
+        case 'g': case 'G': o->val.i *= 1024; // fall through
+        case 'm': case 'M': o->val.i *= 1024; // fall through
+        case 'k': case 'K': o->val.i *= 1024; break;
+        case '\0': break;
+        default:
+            hts_log_error("Unrecognised cache size suffix '%c'", *endp);
+            free(o->arg);
+            free(o);
+            return -1;
+        }
+    }
+
+    else if (strcmp(o->arg, "required_fields") == 0 ||
+             strcmp(o->arg, "REQUIRED_FIELDS") == 0)
+        o->opt = CRAM_OPT_REQUIRED_FIELDS, o->val.i = strtol(val, NULL, 0);
+
+    else if (strcmp(o->arg, "lossy_names") == 0 ||
+             strcmp(o->arg, "LOSSY_NAMES") == 0)
+        o->opt = CRAM_OPT_LOSSY_NAMES, o->val.i = strtol(val, NULL, 0);
+
+    else if (strcmp(o->arg, "name_prefix") == 0 ||
+             strcmp(o->arg, "NAME_PREFIX") == 0)
+        o->opt = CRAM_OPT_PREFIX, o->val.s = val;
+
+    else if (strcmp(o->arg, "store_md") == 0 ||
+             strcmp(o->arg, "store_md") == 0)
+        o->opt = CRAM_OPT_STORE_MD, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "store_nm") == 0 ||
+             strcmp(o->arg, "store_nm") == 0)
+        o->opt = CRAM_OPT_STORE_NM, o->val.i = atoi(val);
+
+    else if (strcmp(o->arg, "block_size") == 0 ||
+             strcmp(o->arg, "BLOCK_SIZE") == 0)
+        o->opt = HTS_OPT_BLOCK_SIZE, o->val.i = strtol(val, NULL, 0);
+
+    else if (strcmp(o->arg, "level") == 0 ||
+             strcmp(o->arg, "LEVEL") == 0)
+        o->opt = HTS_OPT_COMPRESSION_LEVEL, o->val.i = strtol(val, NULL, 0);
+
+    else if (strcmp(o->arg, "filter") == 0 ||
+             strcmp(o->arg, "FILTER") == 0)
+        o->opt = HTS_OPT_FILTER, o->val.s = val;
+
+    else if (strcmp(o->arg, "fastq_aux") == 0 ||
+        strcmp(o->arg, "FASTQ_AUX") == 0)
+        o->opt = FASTQ_OPT_AUX, o->val.s = val;
+
+    else if (strcmp(o->arg, "fastq_barcode") == 0 ||
+        strcmp(o->arg, "FASTQ_BARCODE") == 0)
+        o->opt = FASTQ_OPT_BARCODE, o->val.s = val;
+
+    else if (strcmp(o->arg, "fastq_rnum") == 0 ||
+        strcmp(o->arg, "FASTQ_RNUM") == 0)
+        o->opt = FASTQ_OPT_RNUM, o->val.i = 1;
+
+    else if (strcmp(o->arg, "fastq_casava") == 0 ||
+        strcmp(o->arg, "FASTQ_CASAVA") == 0)
+        o->opt = FASTQ_OPT_CASAVA, o->val.i = 1;
+
+    else if (strcmp(o->arg, "fastq_name2") == 0 ||
+        strcmp(o->arg, "FASTQ_NAME2") == 0)
+        o->opt = FASTQ_OPT_NAME2, o->val.i = 1;
+
+    else {
+        hts_log_error("Unknown option '%s'", o->arg);
+        free(o->arg);
+        free(o);
+        return -1;
+    }
+
+    o->next = NULL;
+
+    // Append; assumes small list.
+    if (*opts) {
+        t = *opts;
+        while (t->next)
+            t = t->next;
+        t->next = o;
+    } else {
+        *opts = o;
+    }
+
+    return 0;
+}
+
+/*
+ * Applies an hts_opt option list to a given htsFile.
+ *
+ * Returns 0 on success
+ *        -1 on failure
+ */
+int hts_opt_apply(htsFile *fp, hts_opt *opts) {
+    hts_opt *last = NULL;
+
+    for (; opts;  opts = (last=opts)->next) {
+        switch (opts->opt) {
+            case CRAM_OPT_REFERENCE:
+                if (!(fp->fn_aux = strdup(opts->val.s)))
+                    return -1;
+                // fall through
+            case CRAM_OPT_VERSION:
+            case CRAM_OPT_PREFIX:
+            case HTS_OPT_FILTER:
+            case FASTQ_OPT_AUX:
+            case FASTQ_OPT_BARCODE:
+                if (hts_set_opt(fp,  opts->opt,  opts->val.s) != 0)
+                    return -1;
+                break;
+            default:
+                if (hts_set_opt(fp,  opts->opt,  opts->val.i) != 0)
+                    return -1;
+                break;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Frees an hts_opt list.
+ */
+void hts_opt_free(hts_opt *opts) {
+    hts_opt *last = NULL;
+    while (opts) {
+        opts = (last=opts)->next;
+        free(last->arg);
+        free(last);
+    }
+}
+
+
+/*
+ * Tokenise options as (key(=value)?,)*(key(=value)?)?
+ * NB: No provision for ',' appearing in the value!
+ * Add backslashing rules?
+ *
+ * This could be used as part of a general command line option parser or
+ * as a string concatenated onto the file open mode.
+ *
+ * Returns 0 on success
+ *        -1 on failure.
+ */
+int hts_parse_opt_list(htsFormat *fmt, const char *str) {
+    while (str && *str) {
+        const char *str_start;
+        int len;
+        char arg[8001];
+
+        while (*str && *str == ',')
+            str++;
+
+        for (str_start = str; *str && *str != ','; str++);
+        len = str - str_start;
+
+        // Produce a nul terminated copy of the option
+        strncpy(arg, str_start, len < 8000 ? len : 8000);
+        arg[len < 8000 ? len : 8000] = '\0';
+
+        if (hts_opt_add((hts_opt **)&fmt->specific, arg) != 0)
+            return -1;
+
+        if (*str)
+            str++;
+    }
+
+    return 0;
+}
+
+/*
+ * Accepts a string file format (sam, bam, cram, vcf, bam) optionally
+ * followed by a comma separated list of key=value options and splits
+ * these up into the fields of htsFormat struct.
+ *
+ * format is assumed to be already initialised, either to blank
+ * "unknown" values or via previous hts_opt_add calls.
+ *
+ * Returns 0 on success
+ *        -1 on failure.
+ */
+int hts_parse_format(htsFormat *format, const char *str) {
+    char fmt[9];
+    const char *cp = scan_keyword(str, ',', fmt, sizeof fmt);
+
+    format->version.minor = 0; // unknown
+    format->version.major = 0; // unknown
+
+    if (strcmp(fmt, "sam") == 0) {
+        format->category          = sequence_data;
+        format->format            = sam;
+        format->compression       = no_compression;
+        format->compression_level = 0;
+    } else if (strcmp(fmt, "sam.gz") == 0) {
+        format->category          = sequence_data;
+        format->format            = sam;
+        format->compression       = bgzf;
+        format->compression_level = -1;
+    } else if (strcmp(fmt, "bam") == 0) {
+        format->category          = sequence_data;
+        format->format            = bam;
+        format->compression       = bgzf;
+        format->compression_level = -1;
+    } else if (strcmp(fmt, "cram") == 0) {
+        format->category          = sequence_data;
+        format->format            = cram;
+        format->compression       = custom;
+        format->compression_level = -1;
+    } else if (strcmp(fmt, "vcf") == 0) {
+        format->category          = variant_data;
+        format->format            = vcf;
+        format->compression       = no_compression;
+        format->compression_level = 0;
+    } else if (strcmp(fmt, "bcf") == 0) {
+        format->category          = variant_data;
+        format->format            = bcf;
+        format->compression       = bgzf;
+        format->compression_level = -1;
+    } else if (strcmp(fmt, "fastq") == 0 || strcmp(fmt, "fq") == 0) {
+        format->category          = sequence_data;
+        format->format            = fastq_format;
+        format->compression       = no_compression;
+        format->compression_level = 0;
+    } else if (strcmp(fmt, "fastq.gz") == 0 || strcmp(fmt, "fq.gz") == 0) {
+        format->category          = sequence_data;
+        format->format            = fastq_format;
+        format->compression       = bgzf;
+        format->compression_level = 0;
+    } else if (strcmp(fmt, "fasta") == 0 || strcmp(fmt, "fa") == 0) {
+        format->category          = sequence_data;
+        format->format            = fasta_format;
+        format->compression       = no_compression;
+        format->compression_level = 0;
+    } else if (strcmp(fmt, "fasta.gz") == 0 || strcmp(fmt, "fa.gz") == 0) {
+        format->category          = sequence_data;
+        format->format            = fasta_format;
+        format->compression       = bgzf;
+        format->compression_level = 0;
+    } else {
+        return -1;
+    }
+
+    return hts_parse_opt_list(format, cp);
+}
+
+
+/*
+ * Tokenise options as (key(=value)?,)*(key(=value)?)?
+ * NB: No provision for ',' appearing in the value!
+ * Add backslashing rules?
+ *
+ * This could be used as part of a general command line option parser or
+ * as a string concatenated onto the file open mode.
+ *
+ * Returns 0 on success
+ *        -1 on failure.
+ */
+static int hts_process_opts(htsFile *fp, const char *opts) {
+    htsFormat fmt;
+
+    fmt.specific = NULL;
+    if (hts_parse_opt_list(&fmt, opts) != 0)
+        return -1;
+
+    if (hts_opt_apply(fp, fmt.specific) != 0) {
+        hts_opt_free(fmt.specific);
+        return -1;
+    }
+
+    hts_opt_free(fmt.specific);
+
+    return 0;
+}
+
+static int hts_crypt4gh_redirect(const char *fn, const char *mode,
+                                 hFILE **hfile_ptr, htsFile *fp) {
+    hFILE *hfile1 = *hfile_ptr;
+    hFILE *hfile2 = NULL;
+    char fn_buf[512], *fn2 = fn_buf;
+    char mode2[102]; // Size set by sizeof(simple_mode) in hts_hopen()
+    const char *prefix = "crypt4gh:";
+    size_t fn2_len = strlen(prefix) + strlen(fn) + 1;
+    int ret = -1;
+
+    if (fn2_len > sizeof(fn_buf)) {
+        if (fn2_len >= INT_MAX) // Silence gcc format-truncation warning
+            return -1;
+        fn2 = malloc(fn2_len);
+        if (!fn2) return -1;
+    }
+
+    // Reopen fn using the crypt4gh plug-in (if available)
+    snprintf(fn2, fn2_len, "%s%s", prefix, fn);
+    snprintf(mode2, sizeof(mode2), "%s%s", mode, strchr(mode, ':') ? "" : ":");
+    hfile2 = hopen(fn2, mode2, "parent", hfile1, NULL);
+    if (hfile2) {
+        // Replace original hfile with the new one.  The original is now
+        // enclosed within hfile2
+        *hfile_ptr = hfile2;
+        ret = 0;
+    }
+
+    if (fn2 != fn_buf)
+        free(fn2);
+    return ret;
+}
+
+htsFile *hts_hopen(hFILE *hfile, const char *fn, const char *mode)
+{
+    hFILE *hfile_orig = hfile;
+    hFILE *hfile_cleanup = hfile;
+    htsFile *fp = (htsFile*)calloc(1, sizeof(htsFile));
+    char simple_mode[101], *cp, *opts;
+    simple_mode[100] = '\0';
+
+    if (fp == NULL) goto error;
+
+    fp->fn = strdup(fn);
+    fp->is_be = ed_is_big();
+
+    // Split mode into simple_mode,opts strings
+    if ((cp = strchr(mode, ','))) {
+        strncpy(simple_mode, mode, cp-mode <= 100 ? cp-mode : 100);
+        simple_mode[cp-mode] = '\0';
+        opts = cp+1;
+    } else {
+        strncpy(simple_mode, mode, 100);
+        opts = NULL;
+    }
+
+    if (strchr(simple_mode, 'r')) {
+        const int max_loops = 5; // Should be plenty
+        int loops = 0;
+        if (hts_detect_format2(hfile, fn, &fp->format) < 0) goto error;
+
+        // Deal with formats that re-direct an underlying file via a plug-in.
+        // Loops as we may have crypt4gh served via htsget, or
+        // crypt4gh-in-crypt4gh.
+
+        while (fp->format.format == htsget ||
+               fp->format.format == hts_crypt4gh_format) {
+            // Ensure we don't get stuck in an endless redirect loop
+            if (++loops > max_loops) {
+                errno = ELOOP;
+                goto error;
+            }
+
+            if (fp->format.format == htsget) {
+                hFILE *hfile2 = hopen_htsget_redirect(hfile, simple_mode);
+                if (hfile2 == NULL) goto error;
+
+                if (hfile != hfile_cleanup) {
+                    // Close the result of an earlier redirection
+                    hclose_abruptly(hfile);
+                }
+
+                hfile = hfile2;
+            }
+            else if (fp->format.format == hts_crypt4gh_format) {
+                int should_preserve = (hfile == hfile_orig);
+                int update_cleanup = (hfile == hfile_cleanup);
+                if (hts_crypt4gh_redirect(fn, simple_mode, &hfile, fp) < 0)
+                    goto error;
+                if (should_preserve) {
+                    // The original hFILE is now contained in a crypt4gh
+                    // wrapper.  Should we need to close the wrapper due
+                    // to a later error, we need to prevent the wrapped
+                    // handle from being closed as the caller will see
+                    // this function return NULL and try to clean up itself.
+                    hfile_orig->preserve = 1;
+                }
+                if (update_cleanup) {
+                    // Update handle to close at the end if redirected by htsget
+                    hfile_cleanup = hfile;
+                }
+            }
+
+            // Re-detect format against the result of the redirection
+            if (hts_detect_format2(hfile, fn, &fp->format) < 0) goto error;
+        }
+    }
+    else if (strchr(simple_mode, 'w') || strchr(simple_mode, 'a')) {
+        htsFormat *fmt = &fp->format;
+        fp->is_write = 1;
+
+        if (strchr(simple_mode, 'b')) fmt->format = binary_format;
+        else if (strchr(simple_mode, 'c')) fmt->format = cram;
+        else if (strchr(simple_mode, 'f')) fmt->format = fastq_format;
+        else if (strchr(simple_mode, 'F')) fmt->format = fasta_format;
+        else fmt->format = text_format;
+
+        if (strchr(simple_mode, 'z')) fmt->compression = bgzf;
+        else if (strchr(simple_mode, 'g')) fmt->compression = gzip;
+        else if (strchr(simple_mode, 'u')) fmt->compression = no_compression;
+        else {
+            // No compression mode specified, set to the default for the format
+            switch (fmt->format) {
+            case binary_format: fmt->compression = bgzf; break;
+            case cram: fmt->compression = custom; break;
+            case fastq_format: fmt->compression = no_compression; break;
+            case fasta_format: fmt->compression = no_compression; break;
+            case text_format: fmt->compression = no_compression; break;
+            default: abort();
+            }
+        }
+
+        // Fill in category (if determinable; e.g. 'b' could be BAM or BCF)
+        fmt->category = format_category(fmt->format);
+
+        fmt->version.major = fmt->version.minor = -1;
+        fmt->compression_level = -1;
+        fmt->specific = NULL;
+    }
+    else { errno = EINVAL; goto error; }
+
+    switch (fp->format.format) {
+    case binary_format:
+    case bam:
+    case bcf:
+        fp->fp.bgzf = bgzf_hopen(hfile, simple_mode);
+        if (fp->fp.bgzf == NULL) goto error;
+        fp->is_bin = fp->is_bgzf = 1;
+        break;
+
+    case cram:
+        fp->fp.cram = cram_dopen(hfile, fn, simple_mode);
+        if (fp->fp.cram == NULL) goto error;
+        if (!fp->is_write)
+            cram_set_option(fp->fp.cram, CRAM_OPT_DECODE_MD, -1); // auto
+        fp->is_cram = 1;
+        break;
+
+    case empty_format:
+    case text_format:
+    case bed:
+    case fasta_format:
+    case fastq_format:
+    case sam:
+    case vcf:
+        if (fp->format.compression != no_compression) {
+            fp->fp.bgzf = bgzf_hopen(hfile, simple_mode);
+            if (fp->fp.bgzf == NULL) goto error;
+            fp->is_bgzf = 1;
+        }
+        else
+            fp->fp.hfile = hfile;
+        break;
+
+    default:
+        errno = EFTYPE;
+        goto error;
+    }
+
+    if (opts)
+        hts_process_opts(fp, opts);
+
+    // Allow original file to close if it was preserved earlier by crypt4gh
+    hfile_orig->preserve = 0;
+
+    // If redirecting via htsget, close the original hFILE now (pedantically
+    // we would instead close it in hts_close(), but this a simplifying
+    // optimisation)
+    if (hfile != hfile_cleanup) hclose_abruptly(hfile_cleanup);
+
+    return fp;
+
+error:
+    hts_log_error("Failed to open file %s", fn);
+
+    // If redirecting, close the failed redirection hFILE that we have opened
+    if (hfile != hfile_orig) hclose_abruptly(hfile);
+    hfile_orig->preserve = 0; // Allow caller to close the original hfile
+
+    if (fp) {
+        free(fp->fn);
+        free(fp->fn_aux);
+        free(fp);
+    }
+    return NULL;
+}
+
+static int hts_idx_close_otf_fp(hts_idx_t *idx);
+
+int hts_close(htsFile *fp)
+{
+    int ret = 0, save;
+    if (!fp) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    switch (fp->format.format) {
+    case binary_format:
+    case bam:
+    case bcf:
+        ret = bgzf_close(fp->fp.bgzf);
+        break;
+
+    case cram:
+        if (!fp->is_write) {
+            switch (cram_eof(fp->fp.cram)) {
+            case 2:
+                hts_log_warning("EOF marker is absent. The input is probably truncated");
+                break;
+            case 0:  /* not at EOF, but may not have wanted all seqs */
+            default: /* case 1, expected EOF */
+                break;
+            }
+        }
+        ret = cram_close(fp->fp.cram);
+        break;
+
+    case empty_format:
+    case text_format:
+    case bed:
+    case fasta_format:
+    case fastq_format:
+    case sam:
+    case vcf:
+        if (fp->format.format == sam)
+            ret = sam_state_destroy(fp);
+        else if (fp->format.format == fastq_format ||
+                 fp->format.format == fasta_format)
+            fastq_state_destroy(fp);
+
+        if (fp->format.compression != no_compression)
+            ret |= bgzf_close(fp->fp.bgzf);
+        else
+            ret |= hclose(fp->fp.hfile);
+        break;
+
+    default:
+        ret = -1;
+        break;
+    }
+
+    if (fp->idx) {
+        // Close deferred index file handle, if present.
+        // Unfortunately this means errors on the index will get mixed with
+        // those on the main file, but as we only have the EOF block left to
+        // write it hopefully won't happen that often.
+        ret |= hts_idx_close_otf_fp(fp->idx);
+    }
+
+    save = errno;
+    sam_hdr_destroy(fp->bam_header);
+    hts_idx_destroy(fp->idx);
+    hts_filter_free(fp->filter);
+    free(fp->fn);
+    free(fp->fn_aux);
+    free(fp->line.s);
+    free(fp);
+    errno = save;
+    return ret;
+}
+
+int hts_flush(htsFile *fp)
+{
+    if (fp == NULL) return 0;
+
+    switch (fp->format.format) {
+    case binary_format:
+    case bam:
+    case bcf:
+        return bgzf_flush(fp->fp.bgzf);
+
+    case cram:
+        return cram_flush(fp->fp.cram);
+
+    case empty_format:
+    case text_format:
+    case bed:
+    case fasta_format:
+    case fastq_format:
+    case sam:
+    case vcf:
+        if (fp->format.compression != no_compression)
+            return bgzf_flush(fp->fp.bgzf);
+        else
+            return hflush(fp->fp.hfile);
+
+    default:
+        break;
+    }
+
+    return 0;
+}
+
+const htsFormat *hts_get_format(htsFile *fp)
+{
+    return fp? &fp->format : NULL;
+}
+
+const char *hts_format_file_extension(const htsFormat *format) {
+    if (!format)
+        return "?";
+
+    switch (format->format) {
+    case sam:  return "sam";
+    case bam:  return "bam";
+    case bai:  return "bai";
+    case cram: return "cram";
+    case crai: return "crai";
+    case vcf:  return "vcf";
+    case bcf:  return "bcf";
+    case csi:  return "csi";
+    case fai_format:   return "fai";
+    case fqi_format:   return "fqi";
+    case gzi:  return "gzi";
+    case tbi:  return "tbi";
+    case bed:  return "bed";
+    case d4_format:    return "d4";
+    case fasta_format: return "fa";
+    case fastq_format: return "fq";
+    default:   return "?";
+    }
+}
+
+static hFILE *hts_hfile(htsFile *fp) {
+    switch (fp->format.format) {
+    case binary_format:// fall through
+    case bcf:          // fall through
+    case bam:          return bgzf_hfile(fp->fp.bgzf);
+    case cram:         return cram_hfile(fp->fp.cram);
+    case text_format:  // fall through
+    case vcf:          // fall through
+    case fastq_format: // fall through
+    case fasta_format: // fall through
+    case sam:          return fp->format.compression != no_compression
+                              ? bgzf_hfile(fp->fp.bgzf)
+                              : fp->fp.hfile;
+    default:           return NULL;
+    }
+}
+
+int hts_set_opt(htsFile *fp, enum hts_fmt_option opt, ...) {
+    int r;
+    va_list args;
+
+    switch (opt) {
+    case HTS_OPT_NTHREADS: {
+        va_start(args, opt);
+        int nthreads = va_arg(args, int);
+        va_end(args);
+        return hts_set_threads(fp, nthreads);
+    }
+
+    case HTS_OPT_BLOCK_SIZE: {
+        hFILE *hf = hts_hfile(fp);
+
+        if (hf) {
+            va_start(args, opt);
+            if (hfile_set_blksize(hf, va_arg(args, int)) != 0)
+                hts_log_warning("Failed to change block size");
+            va_end(args);
+        }
+        else {
+            // To do - implement for vcf/bcf.
+            hts_log_warning("Cannot change block size for this format");
+        }
+
+        return 0;
+    }
+
+    case HTS_OPT_THREAD_POOL: {
+        va_start(args, opt);
+        htsThreadPool *p = va_arg(args, htsThreadPool *);
+        va_end(args);
+        return hts_set_thread_pool(fp, p);
+    }
+
+    case HTS_OPT_CACHE_SIZE: {
+        va_start(args, opt);
+        int cache_size = va_arg(args, int);
+        va_end(args);
+        hts_set_cache_size(fp, cache_size);
+        return 0;
+    }
+
+    case FASTQ_OPT_CASAVA:
+    case FASTQ_OPT_RNUM:
+    case FASTQ_OPT_NAME2:
+        if (fp->format.format == fastq_format ||
+            fp->format.format == fasta_format)
+            return fastq_state_set(fp, opt);
+        return 0;
+
+    case FASTQ_OPT_AUX:
+        if (fp->format.format == fastq_format ||
+            fp->format.format == fasta_format) {
+            va_start(args, opt);
+            char *list = va_arg(args, char *);
+            va_end(args);
+            return fastq_state_set(fp, opt, list);
+        }
+        return 0;
+
+    case FASTQ_OPT_BARCODE:
+        if (fp->format.format == fastq_format ||
+            fp->format.format == fasta_format) {
+            va_start(args, opt);
+            char *bc = va_arg(args, char *);
+            va_end(args);
+            return fastq_state_set(fp, opt, bc);
+        }
+        return 0;
+
+    // Options below here flow through to cram_set_voption
+    case HTS_OPT_COMPRESSION_LEVEL: {
+        va_start(args, opt);
+        int level = va_arg(args, int);
+        va_end(args);
+        if (fp->is_bgzf)
+            fp->fp.bgzf->compress_level = level;
+        else if (fp->format.format == cram)
+            return cram_set_option(fp->fp.cram, opt, level);
+        return 0;
+    }
+
+    case HTS_OPT_FILTER: {
+        va_start(args, opt);
+        char *expr = va_arg(args, char *);
+        va_end(args);
+        return hts_set_filter_expression(fp, expr);
+    }
+
+    case HTS_OPT_PROFILE: {
+        va_start(args, opt);
+        enum hts_profile_option prof = va_arg(args, int);
+        va_end(args);
+        if (fp->is_bgzf) {
+            switch (prof) {
+#ifdef HAVE_LIBDEFLATE
+            case HTS_PROFILE_FAST:    fp->fp.bgzf->compress_level =  2; break;
+            case HTS_PROFILE_NORMAL:  fp->fp.bgzf->compress_level = -1; break;
+            case HTS_PROFILE_SMALL:   fp->fp.bgzf->compress_level = 10; break;
+            case HTS_PROFILE_ARCHIVE: fp->fp.bgzf->compress_level = 12; break;
+#else
+            case HTS_PROFILE_FAST:    fp->fp.bgzf->compress_level =  1; break;
+            case HTS_PROFILE_NORMAL:  fp->fp.bgzf->compress_level = -1; break;
+            case HTS_PROFILE_SMALL:   fp->fp.bgzf->compress_level =  8; break;
+            case HTS_PROFILE_ARCHIVE: fp->fp.bgzf->compress_level =  9; break;
+#endif
+            }
+        } // else CRAM manages this in its own way
+        break;
+    }
+
+    default:
+        break;
+    }
+
+    if (fp->format.format != cram)
+        return 0;
+
+    va_start(args, opt);
+    r = cram_set_voption(fp->fp.cram, opt, args);
+    va_end(args);
+
+    return r;
+}
+
+BGZF *hts_get_bgzfp(htsFile *fp);
+
+int hts_set_threads(htsFile *fp, int n)
+{
+    if (fp->format.format == sam) {
+        return sam_set_threads(fp, n);
+    } else if (fp->format.compression == bgzf) {
+        return bgzf_mt(hts_get_bgzfp(fp), n, 256/*unused*/);
+    } else if (fp->format.format == cram) {
+        return hts_set_opt(fp, CRAM_OPT_NTHREADS, n);
+    }
+    else return 0;
+}
+
+int hts_set_thread_pool(htsFile *fp, htsThreadPool *p) {
+    if (fp->format.format == sam || fp->format.format == text_format) {
+        return sam_set_thread_pool(fp, p);
+    } else if (fp->format.compression == bgzf) {
+        return bgzf_thread_pool(hts_get_bgzfp(fp), p->pool, p->qsize);
+    } else if (fp->format.format == cram) {
+        return hts_set_opt(fp, CRAM_OPT_THREAD_POOL, p);
+    }
+    else return 0;
+}
+
+void hts_set_cache_size(htsFile *fp, int n)
+{
+    if (fp->format.compression == bgzf)
+        bgzf_set_cache_size(hts_get_bgzfp(fp), n);
+}
+
+int hts_set_fai_filename(htsFile *fp, const char *fn_aux)
+{
+    free(fp->fn_aux);
+    if (fn_aux) {
+        fp->fn_aux = strdup(fn_aux);
+        if (fp->fn_aux == NULL) return -1;
+    }
+    else fp->fn_aux = NULL;
+
+    if (fp->format.format == cram)
+        if (cram_set_option(fp->fp.cram, CRAM_OPT_REFERENCE, fp->fn_aux))
+            return -1;
+
+    return 0;
+}
+
+int hts_set_filter_expression(htsFile *fp, const char *expr)
+{
+    if (fp->filter)
+        hts_filter_free(fp->filter);
+
+    if (!expr)
+        return 0;
+
+    return (fp->filter = hts_filter_init(expr))
+        ? 0 : -1;
+}
+
+hFILE *hts_open_tmpfile(const char *fname, const char *mode, kstring_t *tmpname)
+{
+    int pid = (int) getpid();
+    unsigned ptr = (uintptr_t) tmpname;
+    int n = 0;
+    hFILE *fp = NULL;
+
+    do {
+        // Attempt to further uniquify the temporary filename
+        unsigned t = ((unsigned) time(NULL)) ^ ((unsigned) clock()) ^ ptr;
+        n++;
+
+        ks_clear(tmpname);
+        if (ksprintf(tmpname, "%s.tmp_%d_%d_%u", fname, pid, n, t) < 0) break;
+
+        fp = hopen(tmpname->s, mode);
+    } while (fp == NULL && errno == EEXIST && n < 100);
+
+    return fp;
+}
+
+int hts_is_utf16_text(const kstring_t *str)
+{
+    const unsigned char *u = (const unsigned char *) (str->s);
+    return (str->l > 0 && str->s)? is_utf16_text(u, u + str->l) : 0;
+}
+
+// For VCF/BCF backward sweeper. Not exposing these functions because their
+// future is uncertain. Things will probably have to change with hFILE...
+BGZF *hts_get_bgzfp(htsFile *fp)
+{
+    if (fp->is_bgzf)
+        return fp->fp.bgzf;
+    else
+        return NULL;
+}
+int hts_useek(htsFile *fp, off_t uoffset, int where)
+{
+    if (fp->is_bgzf)
+        return bgzf_useek(fp->fp.bgzf, uoffset, where);
+    else
+        return (hseek(fp->fp.hfile, uoffset, SEEK_SET) >= 0)? 0 : -1;
+}
+off_t hts_utell(htsFile *fp)
+{
+    if (fp->is_bgzf)
+        return bgzf_utell(fp->fp.bgzf);
+    else
+        return htell(fp->fp.hfile);
+}
+
+int hts_getline(htsFile *fp, int delimiter, kstring_t *str)
+{
+    int ret;
+    if (! (delimiter == KS_SEP_LINE || delimiter == '\n')) {
+        hts_log_error("Unexpected delimiter %d", delimiter);
+        abort();
+    }
+
+    switch (fp->format.compression) {
+    case no_compression:
+        str->l = 0;
+        ret = kgetline2(str, (kgets_func2 *) hgetln, fp->fp.hfile);
+        if (ret >= 0) ret = (str->l <= INT_MAX)? (int) str->l : INT_MAX;
+        else if (herrno(fp->fp.hfile)) ret = -2, errno = herrno(fp->fp.hfile);
+        else ret = -1;
+        break;
+
+    case gzip:
+    case bgzf:
+        ret = bgzf_getline(fp->fp.bgzf, '\n', str);
+        break;
+
+    default:
+        abort();
+    }
+
+    ++fp->lineno;
+    return ret;
+}
+
+char **hts_readlist(const char *string, int is_file, int *_n)
+{
+    unsigned int m = 0, n = 0;
+    char **s = 0, **s_new;
+    if ( is_file )
+    {
+        BGZF *fp = bgzf_open(string, "r");
+        if ( !fp ) return NULL;
+
+        kstring_t str;
+        int ret;
+        str.s = 0; str.l = str.m = 0;
+        while ((ret = bgzf_getline(fp, '\n', &str)) >= 0)
+        {
+            if (str.l == 0) continue;
+            if (n == 0 && hts_is_utf16_text(&str))
+                hts_log_warning("'%s' appears to be encoded as UTF-16", string);
+            if (hts_resize(char*, n + 1, &m, &s, 0) < 0)
+                goto err;
+            s[n] = strdup(str.s);
+            if (!s[n])
+                goto err;
+            n++;
+        }
+        if (ret < -1) // Read error
+            goto err;
+        bgzf_close(fp);
+        free(str.s);
+    }
+    else
+    {
+        const char *q = string, *p = string;
+        while ( 1 )
+        {
+            if (*p == ',' || *p == 0)
+            {
+                if (hts_resize(char*, n + 1, &m, &s, 0) < 0)
+                    goto err;
+                s[n] = (char*)calloc(p - q + 1, 1);
+                if (!s[n])
+                    goto err;
+                strncpy(s[n++], q, p - q);
+                q = p + 1;
+            }
+            if ( !*p ) break;
+            p++;
+        }
+    }
+    // Try to shrink s to the minimum size needed
+    s_new = (char**)realloc(s, n * sizeof(char*));
+    if (!s_new)
+        goto err;
+
+    s = s_new;
+    assert(n < INT_MAX); // hts_resize() should ensure this
+    *_n = n;
+    return s;
+
+ err:
+    for (m = 0; m < n; m++)
+        free(s[m]);
+    free(s);
+    return NULL;
+}
+
+char **hts_readlines(const char *fn, int *_n)
+{
+    unsigned int m = 0, n = 0;
+    char **s = 0, **s_new;
+    BGZF *fp = bgzf_open(fn, "r");
+    if ( fp ) { // read from file
+        kstring_t str;
+        int ret;
+        str.s = 0; str.l = str.m = 0;
+        while ((ret = bgzf_getline(fp, '\n', &str)) >= 0) {
+            if (str.l == 0) continue;
+            if (n == 0 && hts_is_utf16_text(&str))
+                hts_log_warning("'%s' appears to be encoded as UTF-16", fn);
+            if (hts_resize(char *, n + 1, &m, &s, 0) < 0)
+                goto err;
+            s[n] = strdup(str.s);
+            if (!s[n])
+                goto err;
+            n++;
+        }
+        if (ret < -1) // Read error
+            goto err;
+        bgzf_close(fp);
+        free(str.s);
+    } else if (*fn == ':') { // read from string
+        const char *q, *p;
+        for (q = p = fn + 1;; ++p)
+            if (*p == ',' || *p == 0) {
+                if (hts_resize(char *, n + 1, &m, &s, 0) < 0)
+                    goto err;
+                s[n] = (char*)calloc(p - q + 1, 1);
+                if (!s[n])
+                    goto err;
+                strncpy(s[n++], q, p - q);
+                q = p + 1;
+                if (*p == 0) break;
+            }
+    } else return 0;
+    // Try to shrink s to the minimum size needed
+    s_new = (char**)realloc(s, n * sizeof(char*));
+    if (!s_new)
+        goto err;
+
+    s = s_new;
+    assert(n < INT_MAX); // hts_resize() should ensure this
+    *_n = n;
+    return s;
+
+ err:
+    for (m = 0; m < n; m++)
+        free(s[m]);
+    free(s);
+    return NULL;
+}
+
+// DEPRECATED: To be removed in a future HTSlib release
+int hts_file_type(const char *fname)
+{
+    int len = strlen(fname);
+    if ( !strcasecmp(".vcf.gz",fname+len-7) ) return FT_VCF_GZ;
+    if ( !strcasecmp(".vcf",fname+len-4) ) return FT_VCF;
+    if ( !strcasecmp(".bcf",fname+len-4) ) return FT_BCF_GZ;
+    if ( !strcmp("-",fname) ) return FT_STDIN;
+
+    hFILE *f = hopen(fname, "r");
+    if (f == NULL) return 0;
+
+    htsFormat fmt;
+    if (hts_detect_format2(f, fname, &fmt) < 0) { hclose_abruptly(f); return 0; }
+    if (hclose(f) < 0) return 0;
+
+    switch (fmt.format) {
+    case vcf: return (fmt.compression == no_compression)? FT_VCF : FT_VCF_GZ;
+    case bcf: return (fmt.compression == no_compression)? FT_BCF : FT_BCF_GZ;
+    default:  return 0;
+    }
+}
+
+int hts_check_EOF(htsFile *fp)
+{
+    if (fp->format.compression == bgzf)
+        return bgzf_check_EOF(hts_get_bgzfp(fp));
+    else if (fp->format.format == cram)
+        return cram_check_EOF(fp->fp.cram);
+    else
+        return 3;
+}
+
+
+/****************
+ *** Indexing ***
+ ****************/
+
+#define HTS_MIN_MARKER_DIST 0x10000
+
+// Finds the special meta bin
+//  ((1<<(3 * n_lvls + 3)) - 1) / 7 + 1
+#define META_BIN(idx) ((idx)->n_bins + 1)
+
+#define pair64_lt(a,b) ((a).u < (b).u)
+#define pair64max_lt(a,b) ((a).u < (b).u || \
+                           ((a).u == (b).u && (a).max < (b).max))
+
+KSORT_INIT_STATIC(_off, hts_pair64_t, pair64_lt)
+KSORT_INIT_STATIC(_off_max, hts_pair64_max_t, pair64max_lt)
+
+typedef struct {
+    int32_t m, n;
+    uint64_t loff;
+    hts_pair64_t *list;
+} bins_t;
+
+KHASH_MAP_INIT_INT(bin, bins_t)
+typedef khash_t(bin) bidx_t;
+
+typedef struct {
+    hts_pos_t n, m;
+    uint64_t *offset;
+} lidx_t;
+
+struct hts_idx_t {
+    int fmt, min_shift, n_lvls, n_bins;
+    uint32_t l_meta;
+    int32_t n, m;
+    uint64_t n_no_coor;
+    bidx_t **bidx;
+    lidx_t *lidx;
+    uint8_t *meta; // MUST have a terminating NUL on the end
+    int tbi_n, last_tbi_tid;
+    struct {
+        uint32_t last_bin, save_bin;
+        hts_pos_t last_coor;
+        int last_tid, save_tid, finished;
+        uint64_t last_off, save_off;
+        uint64_t off_beg, off_end;
+        uint64_t n_mapped, n_unmapped;
+    } z; // keep internal states
+    BGZF *otf_fp;  // Index on-the-fly output file
+};
+
+static char * idx_format_name(int fmt) {
+    switch (fmt) {
+        case HTS_FMT_CSI: return "csi";
+        case HTS_FMT_BAI: return "bai";
+        case HTS_FMT_TBI: return "tbi";
+        case HTS_FMT_CRAI: return "crai";
+        default: return "unknown";
+    }
+}
+
+#ifdef DEBUG_INDEX
+static void idx_dump(const hts_idx_t *idx) {
+    int i;
+    int64_t j;
+
+    if (!idx) fprintf(stderr, "Null index\n");
+
+    fprintf(stderr, "format='%s', min_shift=%d, n_lvls=%d, n_bins=%d, l_meta=%u ",
+            idx_format_name(idx->fmt), idx->min_shift, idx->n_lvls, idx->n_bins, idx->l_meta);
+    fprintf(stderr, "n=%d, m=%d, n_no_coor=%"PRIu64"\n", idx->n, idx->m, idx->n_no_coor);
+    for (i = 0; i < idx->n; i++) {
+        bidx_t *bidx = idx->bidx[i];
+        lidx_t *lidx = &idx->lidx[i];
+        if (bidx) {
+            fprintf(stderr, "======== BIN Index - tid=%d, n_buckets=%d, size=%d\n", i, bidx->n_buckets, bidx->size);
+            int b;
+            for (b = 0; b < META_BIN(idx); b++) {
+                khint_t k;
+                if ((k = kh_get(bin, bidx, b)) != kh_end(bidx)) {
+                    bins_t *entries = &kh_value(bidx, k);
+                    int l = hts_bin_level(b);
+                    int64_t bin_width = 1LL << ((idx->n_lvls - l) * 3 + idx->min_shift);
+                    fprintf(stderr, "\tbin=%d, level=%d, parent=%d, n_chunks=%d, loff=%"PRIu64", interval=[%"PRId64" - %"PRId64"]\n",
+                        b, l, hts_bin_parent(b), entries->n, entries->loff, (b-hts_bin_first(l))*bin_width+1, (b+1-hts_bin_first(l))*bin_width);
+                    for (j = 0; j < entries->n; j++)
+                        fprintf(stderr, "\t\tchunk=%"PRId64", u=%"PRIu64", v=%"PRIu64"\n", j, entries->list[j].u, entries->list[j].v);
+                }
+            }
+        }
+        if (lidx) {
+            fprintf(stderr, "======== LINEAR Index - tid=%d, n_values=%"PRId64"\n", i, lidx->n);
+            for (j = 0; j < lidx->n; j++) {
+                fprintf(stderr, "\t\tentry=%"PRId64", offset=%"PRIu64", interval=[%"PRId64" - %"PRId64"]\n",
+                    j, lidx->offset[j], j*(1<min_shift)+1, (j+1)*(1<min_shift));
+            }
+        }
+    }
+}
+#endif
+
+static inline int insert_to_b(bidx_t *b, int bin, uint64_t beg, uint64_t end)
+{
+    khint_t k;
+    bins_t *l;
+    int absent;
+    k = kh_put(bin, b, bin, &absent);
+    if (absent < 0) return -1; // Out of memory
+    l = &kh_value(b, k);
+    if (absent) {
+        l->m = 1; l->n = 0;
+        l->list = (hts_pair64_t*)calloc(l->m, sizeof(hts_pair64_t));
+        if (!l->list) {
+            kh_del(bin, b, k);
+            return -1;
+        }
+    } else if (l->n == l->m) {
+        uint32_t new_m = l->m ? l->m << 1 : 1;
+        hts_pair64_t *new_list = realloc(l->list, new_m * sizeof(hts_pair64_t));
+        if (!new_list) return -1;
+        l->list = new_list;
+        l->m = new_m;
+    }
+    l->list[l->n].u = beg;
+    l->list[l->n++].v = end;
+    return 0;
+}
+
+static inline int insert_to_l(lidx_t *l, int64_t _beg, int64_t _end, uint64_t offset, int min_shift)
+{
+    int i;
+    hts_pos_t beg, end;
+    beg = _beg >> min_shift;
+    end = (_end - 1) >> min_shift;
+    if (l->m < end + 1) {
+        size_t new_m = l->m * 2 > end + 1 ? l->m * 2 : end + 1;
+        uint64_t *new_offset;
+
+        new_offset = (uint64_t*)realloc(l->offset, new_m * sizeof(uint64_t));
+        if (!new_offset) return -1;
+
+        // fill unused memory with (uint64_t)-1
+        memset(new_offset + l->m, 0xff, sizeof(uint64_t) * (new_m - l->m));
+        l->m = new_m;
+        l->offset = new_offset;
+    }
+    for (i = beg; i <= end; ++i) {
+        if (l->offset[i] == (uint64_t)-1) l->offset[i] = offset;
+    }
+    if (l->n < end + 1) l->n = end + 1;
+    return 0;
+}
+
+hts_idx_t *hts_idx_init(int n, int fmt, uint64_t offset0, int min_shift, int n_lvls)
+{
+    hts_idx_t *idx;
+    idx = (hts_idx_t*)calloc(1, sizeof(hts_idx_t));
+    if (idx == NULL) return NULL;
+    idx->fmt = fmt;
+    idx->min_shift = min_shift;
+    idx->n_lvls = n_lvls;
+    idx->n_bins = ((1<<(3 * n_lvls + 3)) - 1) / 7;
+    idx->z.save_tid = idx->z.last_tid = -1;
+    idx->z.save_bin = idx->z.last_bin = 0xffffffffu;
+    idx->z.save_off = idx->z.last_off = idx->z.off_beg = idx->z.off_end = offset0;
+    idx->z.last_coor = 0xffffffffu;
+    if (n) {
+        idx->n = idx->m = n;
+        idx->bidx = (bidx_t**)calloc(n, sizeof(bidx_t*));
+        if (idx->bidx == NULL) { free(idx); return NULL; }
+        idx->lidx = (lidx_t*) calloc(n, sizeof(lidx_t));
+        if (idx->lidx == NULL) { free(idx->bidx); free(idx); return NULL; }
+    }
+    idx->tbi_n = -1;
+    idx->last_tbi_tid = -1;
+    idx->otf_fp = NULL;
+    return idx;
+}
+
+static void update_loff(hts_idx_t *idx, int i, int free_lidx)
+{
+    bidx_t *bidx = idx->bidx[i];
+    lidx_t *lidx = &idx->lidx[i];
+    khint_t k;
+    int l;
+    // the last entry is always valid
+    for (l=lidx->n-2; l >= 0; l--) {
+        if (lidx->offset[l] == (uint64_t)-1)
+            lidx->offset[l] = lidx->offset[l+1];
+    }
+    if (bidx == 0) return;
+    for (k = kh_begin(bidx); k != kh_end(bidx); ++k) // set loff
+        if (kh_exist(bidx, k))
+        {
+            if ( kh_key(bidx, k) < idx->n_bins )
+            {
+                int bot_bin = hts_bin_bot(kh_key(bidx, k), idx->n_lvls);
+                // disable linear index if bot_bin out of bounds
+                kh_val(bidx, k).loff = bot_bin < lidx->n ? lidx->offset[bot_bin] : 0;
+            }
+            else
+                kh_val(bidx, k).loff = 0;
+        }
+    if (free_lidx) {
+        free(lidx->offset);
+        lidx->m = lidx->n = 0;
+        lidx->offset = 0;
+    }
+}
+
+static int compress_binning(hts_idx_t *idx, int i)
+{
+    bidx_t *bidx = idx->bidx[i];
+    khint_t k;
+    int l, m;
+    if (bidx == 0) return 0;
+    // merge a bin to its parent if the bin is too small
+    for (l = idx->n_lvls; l > 0; --l) {
+        unsigned start = hts_bin_first(l);
+        for (k = kh_begin(bidx); k != kh_end(bidx); ++k) {
+            bins_t *p, *q;
+            if (!kh_exist(bidx, k) || kh_key(bidx, k) >= idx->n_bins || kh_key(bidx, k) < start) continue;
+            p = &kh_value(bidx, k);
+            if (l < idx->n_lvls && p->n > 1) ks_introsort(_off, p->n, p->list);
+            if ((p->list[p->n - 1].v>>16) - (p->list[0].u>>16) < HTS_MIN_MARKER_DIST) {
+                khint_t kp;
+                kp = kh_get(bin, bidx, hts_bin_parent(kh_key(bidx, k)));
+                if (kp == kh_end(bidx)) continue;
+                q = &kh_val(bidx, kp);
+                if (q->n + p->n > q->m) {
+                    uint32_t new_m = q->n + p->n;
+                    hts_pair64_t *new_list;
+                    kroundup32(new_m);
+                    if (new_m > INT32_MAX) return -1; // Limited by index format
+                    new_list = realloc(q->list, new_m * sizeof(*new_list));
+                    if (!new_list) return -1;
+                    q->m = new_m;
+                    q->list = new_list;
+                }
+                memcpy(q->list + q->n, p->list, p->n * sizeof(hts_pair64_t));
+                q->n += p->n;
+                free(p->list);
+                kh_del(bin, bidx, k);
+            }
+        }
+    }
+    k = kh_get(bin, bidx, 0);
+    if (k != kh_end(bidx)) ks_introsort(_off, kh_val(bidx, k).n, kh_val(bidx, k).list);
+    // merge adjacent chunks that start from the same BGZF block
+    for (k = kh_begin(bidx); k != kh_end(bidx); ++k) {
+        bins_t *p;
+        if (!kh_exist(bidx, k) || kh_key(bidx, k) >= idx->n_bins) continue;
+        p = &kh_value(bidx, k);
+        for (l = 1, m = 0; l < p->n; ++l) {
+            if (p->list[m].v>>16 >= p->list[l].u>>16) {
+                if (p->list[m].v < p->list[l].v) p->list[m].v = p->list[l].v;
+            } else p->list[++m] = p->list[l];
+        }
+        p->n = m + 1;
+    }
+    return 0;
+}
+
+int hts_idx_finish(hts_idx_t *idx, uint64_t final_offset)
+{
+    int i, ret = 0;
+    if (idx == NULL || idx->z.finished) return 0; // do not run this function on an empty index or multiple times
+    if (idx->z.save_tid >= 0) {
+        ret |= insert_to_b(idx->bidx[idx->z.save_tid], idx->z.save_bin, idx->z.save_off, final_offset);
+        ret |= insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.off_beg, final_offset);
+        ret |= insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx), idx->z.n_mapped, idx->z.n_unmapped);
+    }
+    for (i = 0; i < idx->n; ++i) {
+        update_loff(idx, i, (idx->fmt == HTS_FMT_CSI));
+        ret |= compress_binning(idx, i);
+    }
+    idx->z.finished = 1;
+
+    return ret;
+}
+
+static inline hts_pos_t hts_idx_maxpos(const hts_idx_t *idx)
+{
+    return hts_bin_maxpos(idx->min_shift, idx->n_lvls);
+}
+
+int hts_idx_check_range(hts_idx_t *idx, int tid, hts_pos_t beg, hts_pos_t end)
+{
+    hts_pos_t maxpos = hts_idx_maxpos(idx);
+    if (tid < 0 || (beg <= maxpos && end <= maxpos))
+        return 0;
+
+    if (idx->fmt == HTS_FMT_CSI) {
+        hts_log_error("Region %"PRIhts_pos"..%"PRIhts_pos" "
+                      "cannot be stored in a csi index with these parameters. "
+                      "Please use a larger min_shift or depth",
+                      beg, end);
+    } else {
+        hts_log_error("Region %"PRIhts_pos"..%"PRIhts_pos
+                      " cannot be stored in a %s index. Try using a csi index",
+                      beg, end, idx_format_name(idx->fmt));
+    }
+    errno = ERANGE;
+    return -1;
+}
+
+int hts_idx_push(hts_idx_t *idx, int tid, hts_pos_t beg, hts_pos_t end, uint64_t offset, int is_mapped)
+{
+    int bin;
+    if (tid<0) beg = -1, end = 0;
+    if (hts_idx_check_range(idx, tid, beg, end) < 0)
+        return -1;
+    if (tid >= idx->m) { // enlarge the index
+        uint32_t new_m = idx->m * 2 > tid + 1 ? idx->m * 2 : tid + 1;
+        bidx_t **new_bidx;
+        lidx_t *new_lidx;
+
+        new_bidx = (bidx_t**)realloc(idx->bidx, new_m * sizeof(bidx_t*));
+        if (!new_bidx) return -1;
+        idx->bidx = new_bidx;
+
+        new_lidx = (lidx_t*) realloc(idx->lidx, new_m * sizeof(lidx_t));
+        if (!new_lidx) return -1;
+        idx->lidx = new_lidx;
+
+        memset(&idx->bidx[idx->m], 0, (new_m - idx->m) * sizeof(bidx_t*));
+        memset(&idx->lidx[idx->m], 0, (new_m - idx->m) * sizeof(lidx_t));
+        idx->m = new_m;
+    }
+    if (idx->n < tid + 1) idx->n = tid + 1;
+    if (idx->z.finished) return 0;
+    if (idx->z.last_tid != tid || (idx->z.last_tid >= 0 && tid < 0)) { // change of chromosome
+        if ( tid>=0 && idx->n_no_coor )
+        {
+            hts_log_error("NO_COOR reads not in a single block at the end %d %d", tid, idx->z.last_tid);
+            return -1;
+        }
+        if (tid>=0 && idx->bidx[tid] != 0)
+        {
+            hts_log_error("Chromosome blocks not continuous");
+            return -1;
+        }
+        idx->z.last_tid = tid;
+        idx->z.last_bin = 0xffffffffu;
+    } else if (tid >= 0 && idx->z.last_coor > beg) { // test if positions are out of order
+        hts_log_error("Unsorted positions on sequence #%d: %"PRIhts_pos" followed by %"PRIhts_pos, tid+1, idx->z.last_coor+1, beg+1);
+        return -1;
+    }
+    if (end < beg) {
+        // Malformed ranges are errors. (Empty ranges (beg==end) are unusual but acceptable.)
+        hts_log_error("Invalid record on sequence #%d: end %"PRId64" < begin %"PRId64, tid+1, end, beg+1);
+        return -1;
+    }
+    if ( tid>=0 )
+    {
+        if (idx->bidx[tid] == 0) idx->bidx[tid] = kh_init(bin);
+        // shoehorn [-1,0) (VCF POS=0) into the leftmost bottom-level bin
+        if (beg < 0)  beg = 0;
+        if (end <= 0) end = 1;
+        // idx->z.last_off points to the start of the current record
+        if (insert_to_l(&idx->lidx[tid], beg, end,
+                        idx->z.last_off, idx->min_shift) < 0) return -1;
+    }
+    else idx->n_no_coor++;
+    bin = hts_reg2bin(beg, end, idx->min_shift, idx->n_lvls);
+    if ((int)idx->z.last_bin != bin) { // then possibly write the binning index
+        if (idx->z.save_bin != 0xffffffffu) { // save_bin==0xffffffffu only happens to the first record
+            if (insert_to_b(idx->bidx[idx->z.save_tid], idx->z.save_bin,
+                            idx->z.save_off, idx->z.last_off) < 0) return -1;
+        }
+        if (idx->z.last_bin == 0xffffffffu && idx->z.save_bin != 0xffffffffu) { // change of chr; keep meta information
+            idx->z.off_end = idx->z.last_off;
+            if (insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx),
+                            idx->z.off_beg, idx->z.off_end) < 0) return -1;
+            if (insert_to_b(idx->bidx[idx->z.save_tid], META_BIN(idx),
+                            idx->z.n_mapped, idx->z.n_unmapped) < 0) return -1;
+            idx->z.n_mapped = idx->z.n_unmapped = 0;
+            idx->z.off_beg = idx->z.off_end;
+        }
+        idx->z.save_off = idx->z.last_off;
+        idx->z.save_bin = idx->z.last_bin = bin;
+        idx->z.save_tid = tid;
+    }
+    if (is_mapped) ++idx->z.n_mapped;
+    else ++idx->z.n_unmapped;
+    idx->z.last_off = offset;
+    idx->z.last_coor = beg;
+    return 0;
+}
+
+// Needed for TBI only.  Ensure 'tid' with 'name' is in the index meta data.
+// idx->meta needs to have been initialised first with an appropriate Tabix
+// configuration via hts_idx_set_meta.
+//
+// NB number of references (first 4 bytes of tabix header) aren't in
+// idx->meta, but held in idx->n instead.
+int hts_idx_tbi_name(hts_idx_t *idx, int tid, const char *name) {
+    // Horrid - we have to map incoming tid to a tbi alternative tid.
+    // This is because TBI counts tids by "covered" refs while everything
+    // else counts by Nth SQ/contig record in header.
+    if (tid == idx->last_tbi_tid || tid < 0 || !name)
+        return idx->tbi_n;
+
+    uint32_t len = strlen(name)+1;
+    uint8_t *tmp = (uint8_t *)realloc(idx->meta, idx->l_meta + len);
+    if (!tmp)
+        return -1;
+
+    // Append name
+    idx->meta = tmp;
+    strcpy((char *)idx->meta + idx->l_meta, name);
+    idx->l_meta += len;
+
+    // Update seq length
+    u32_to_le(le_to_u32(idx->meta+24)+len, idx->meta+24);
+
+    idx->last_tbi_tid = tid;
+    return ++idx->tbi_n;
+}
+
+// When doing samtools index we have a read_bam / hts_idx_push(bgzf_tell())
+// loop.  idx->z.last_off is the previous bzgf_tell location, so we know
+// the location the current bam record started at as well as where it ends.
+//
+// When building an index on the fly via a write_bam / hts_idx_push loop,
+// this isn't quite identical as we may amend the virtual coord returned
+// by bgzf_tell to the start of a new block if the next bam struct doesn't
+// fit.  It's essentially the same thing, but for bit-identical indices
+// we need to amend the idx->z.last_off when we know we're starting a new
+// block.
+void hts_idx_amend_last(hts_idx_t *idx, uint64_t offset)
+{
+    idx->z.last_off = offset;
+}
+
+void hts_idx_destroy(hts_idx_t *idx)
+{
+    khint_t k;
+    int i;
+    if (idx == 0) return;
+
+    // For HTS_FMT_CRAI, idx actually points to a different type -- see sam.c
+    if (idx->fmt == HTS_FMT_CRAI) {
+        hts_cram_idx_t *cidx = (hts_cram_idx_t *) idx;
+        cram_index_free(cidx->cram);
+        free(cidx);
+        return;
+    }
+
+    for (i = 0; i < idx->m; ++i) {
+        bidx_t *bidx = idx->bidx[i];
+        free(idx->lidx[i].offset);
+        if (bidx == 0) continue;
+        for (k = kh_begin(bidx); k != kh_end(bidx); ++k)
+            if (kh_exist(bidx, k))
+                free(kh_value(bidx, k).list);
+        kh_destroy(bin, bidx);
+    }
+    free(idx->bidx); free(idx->lidx); free(idx->meta);
+    free(idx);
+}
+
+int hts_idx_fmt(hts_idx_t *idx) {
+    return idx->fmt;
+}
+
+// The optimizer eliminates these ed_is_big() calls; still it would be good to
+// TODO Determine endianness at configure- or compile-time
+
+static inline ssize_t HTS_RESULT_USED idx_write_int32(BGZF *fp, int32_t x)
+{
+    if (ed_is_big()) x = ed_swap_4(x);
+    return bgzf_write(fp, &x, sizeof x);
+}
+
+static inline ssize_t HTS_RESULT_USED idx_write_uint32(BGZF *fp, uint32_t x)
+{
+    if (ed_is_big()) x = ed_swap_4(x);
+    return bgzf_write(fp, &x, sizeof x);
+}
+
+static inline ssize_t HTS_RESULT_USED idx_write_uint64(BGZF *fp, uint64_t x)
+{
+    if (ed_is_big()) x = ed_swap_8(x);
+    return bgzf_write(fp, &x, sizeof x);
+}
+
+static inline void swap_bins(bins_t *p)
+{
+    int i;
+    for (i = 0; i < p->n; ++i) {
+        ed_swap_8p(&p->list[i].u);
+        ed_swap_8p(&p->list[i].v);
+    }
+}
+
+static int need_idx_ugly_delay_hack(const hts_idx_t *idx)
+{
+    // Ugly hack for on-the-fly BAI indexes.  As these are uncompressed,
+    // we need to delay writing a few bytes of data until file close
+    // so that we have something to force a modification time update.
+    //
+    // (For compressed indexes like CSI, the BGZF EOF block serves the same
+    // purpose).
+    return idx->otf_fp && !idx->otf_fp->is_compressed;
+}
+
+static int idx_save_core(const hts_idx_t *idx, BGZF *fp, int fmt)
+{
+    int32_t i, j;
+
+    #define check(ret) if ((ret) < 0) return -1
+
+    // VCF TBI/CSI only writes IDs for non-empty bins (ie covered references)
+    //
+    // NOTE: CSI meta is undefined in spec, so this code has an assumption
+    // that we're only using it for Tabix data.
+    int nids = idx->n;
+    if (idx->meta && idx->l_meta >= 4 && le_to_u32(idx->meta) == TBX_VCF) {
+        for (i = nids = 0; i < idx->n; ++i) {
+            if (idx->bidx[i])
+                nids++;
+        }
+    }
+    check(idx_write_int32(fp, nids));
+    if (fmt == HTS_FMT_TBI && idx->l_meta)
+        check(bgzf_write(fp, idx->meta, idx->l_meta));
+
+    for (i = 0; i < idx->n; ++i) {
+        khint_t k;
+        bidx_t *bidx = idx->bidx[i];
+        lidx_t *lidx = &idx->lidx[i];
+
+        // write binning index
+        if (nids == idx->n || bidx)
+            check(idx_write_int32(fp, bidx? kh_size(bidx) : 0));
+        if (bidx)
+            for (k = kh_begin(bidx); k != kh_end(bidx); ++k)
+                if (kh_exist(bidx, k)) {
+                    bins_t *p = &kh_value(bidx, k);
+                    check(idx_write_uint32(fp, kh_key(bidx, k)));
+                    if (fmt == HTS_FMT_CSI) check(idx_write_uint64(fp, p->loff));
+                    //int j;for(j=0;jn;++j)fprintf(stderr,"%d,%llx,%d,%llx:%llx\n",kh_key(bidx,k),kh_val(bidx, k).loff,j,p->list[j].u,p->list[j].v);
+                    check(idx_write_int32(fp, p->n));
+                    for (j = 0; j < p->n; ++j) {
+                        //fprintf(stderr, "\t%ld\t%ld\n", p->list[j].u, p->list[j].v);
+                        check(idx_write_uint64(fp, p->list[j].u));
+                        check(idx_write_uint64(fp, p->list[j].v));
+                    }
+                }
+
+        // write linear index
+        if (fmt != HTS_FMT_CSI) {
+            check(idx_write_int32(fp, lidx->n));
+            for (j = 0; j < lidx->n; ++j)
+                check(idx_write_uint64(fp, lidx->offset[j]));
+        }
+    }
+
+    if (!need_idx_ugly_delay_hack(idx)) {
+        // Write this for compressed (CSI) indexes, but for BAI we
+        // need to save a bit for later.  See hts_idx_close_otf_fp()
+        check(idx_write_uint64(fp, idx->n_no_coor));
+    }
+
+#ifdef DEBUG_INDEX
+    idx_dump(idx);
+#endif
+
+    return 0;
+    #undef check
+}
+
+int hts_idx_save(const hts_idx_t *idx, const char *fn, int fmt)
+{
+    int ret, save;
+    if (idx == NULL || fn == NULL) { errno = EINVAL; return -1; }
+    char *fnidx = (char*)calloc(1, strlen(fn) + 5);
+    if (fnidx == NULL) return -1;
+
+    strcpy(fnidx, fn);
+    switch (fmt) {
+    case HTS_FMT_BAI: strcat(fnidx, ".bai"); break;
+    case HTS_FMT_CSI: strcat(fnidx, ".csi"); break;
+    case HTS_FMT_TBI: strcat(fnidx, ".tbi"); break;
+    default: abort();
+    }
+
+    ret = hts_idx_save_as(idx, fn, fnidx, fmt);
+    save = errno;
+    free(fnidx);
+    errno = save;
+    return ret;
+}
+
+static int hts_idx_write_out(const hts_idx_t *idx, BGZF *fp, int fmt)
+{
+    #define check(ret) if ((ret) < 0) return -1
+
+    if (fmt == HTS_FMT_CSI) {
+        check(bgzf_write(fp, "CSI\1", 4));
+        check(idx_write_int32(fp, idx->min_shift));
+        check(idx_write_int32(fp, idx->n_lvls));
+        check(idx_write_uint32(fp, idx->l_meta));
+        if (idx->l_meta) check(bgzf_write(fp, idx->meta, idx->l_meta));
+    } else if (fmt == HTS_FMT_TBI) {
+        check(bgzf_write(fp, "TBI\1", 4));
+    } else if (fmt == HTS_FMT_BAI) {
+        check(bgzf_write(fp, "BAI\1", 4));
+    } else abort();
+
+    check(idx_save_core(idx, fp, fmt));
+
+    #undef check
+    return 0;
+}
+
+int hts_idx_save_as(const hts_idx_t *idx, const char *fn, const char *fnidx, int fmt)
+{
+    BGZF *fp;
+
+    if (fnidx == NULL)
+        return hts_idx_save(idx, fn, fmt);
+
+    fp = bgzf_open(fnidx, (fmt == HTS_FMT_BAI)? "wu" : "w");
+    if (fp == NULL) return -1;
+
+    if (hts_idx_write_out(idx, fp, fmt) < 0) {
+        int save_errno = errno;
+        bgzf_close(fp);
+        errno = save_errno;
+        return -1;
+    }
+
+    return bgzf_close(fp);
+}
+
+// idx_save for on-the-fly indexes.  Mostly duplicated from above, except
+// idx is not const because we want to store the file handle in it, and
+// the index file handle is not closed.  This allows the index file to be
+// closed after the EOF block on the indexed file has been written out,
+// so the modification times on the two files will be in the correct order.
+int hts_idx_save_but_not_close(hts_idx_t *idx, const char *fnidx, int fmt)
+{
+    idx->otf_fp = bgzf_open(fnidx, (fmt == HTS_FMT_BAI)? "wu" : "w");
+    if (idx->otf_fp == NULL) return -1;
+
+    if (hts_idx_write_out(idx, idx->otf_fp, fmt) < 0) {
+        int save_errno = errno;
+        bgzf_close(idx->otf_fp);
+        idx->otf_fp = NULL;
+        errno = save_errno;
+        return -1;
+    }
+
+    return bgzf_flush(idx->otf_fp);
+}
+
+static int hts_idx_close_otf_fp(hts_idx_t *idx)
+{
+    if (idx && idx->otf_fp) {
+        int ret = 0;
+        if (need_idx_ugly_delay_hack(idx)) {
+            // BAI index - write out the bytes we deferred earlier
+            ret = idx_write_uint64(idx->otf_fp, idx->n_no_coor) < 0;
+        }
+        ret |= bgzf_close(idx->otf_fp) < 0;
+        idx->otf_fp = NULL;
+        return ret == 0 ? 0 : -1;
+    }
+    return 0;
+}
+
+static int idx_read_core(hts_idx_t *idx, BGZF *fp, int fmt)
+{
+    int32_t i, n, is_be;
+    is_be = ed_is_big();
+    if (idx == NULL) return -4;
+    for (i = 0; i < idx->n; ++i) {
+        bidx_t *h;
+        lidx_t *l = &idx->lidx[i];
+        uint32_t key;
+        int j, absent;
+        bins_t *p;
+        h = idx->bidx[i] = kh_init(bin);
+        if (bgzf_read(fp, &n, 4) != 4) return -1;
+        if (is_be) ed_swap_4p(&n);
+        if (n < 0) return -3;
+        for (j = 0; j < n; ++j) {
+            khint_t k;
+            if (bgzf_read(fp, &key, 4) != 4) return -1;
+            if (is_be) ed_swap_4p(&key);
+            k = kh_put(bin, h, key, &absent);
+            if (absent <  0) return -2; // No memory
+            if (absent == 0) return -3; // Duplicate bin number
+            p = &kh_val(h, k);
+            if (fmt == HTS_FMT_CSI) {
+                if (bgzf_read(fp, &p->loff, 8) != 8) return -1;
+                if (is_be) ed_swap_8p(&p->loff);
+            } else p->loff = 0;
+            if (bgzf_read(fp, &p->n, 4) != 4) return -1;
+            if (is_be) ed_swap_4p(&p->n);
+            if (p->n < 0) return -3;
+            if ((size_t) p->n > SIZE_MAX / sizeof(hts_pair64_t)) return -2;
+            p->m = p->n;
+            p->list = (hts_pair64_t*)malloc(p->m * sizeof(hts_pair64_t));
+            if (p->list == NULL) return -2;
+            if (bgzf_read(fp, p->list, ((size_t) p->n)<<4) != ((size_t) p->n)<<4) return -1;
+            if (is_be) swap_bins(p);
+        }
+        if (fmt != HTS_FMT_CSI) { // load linear index
+            int j, k;
+            uint32_t x;
+            if (bgzf_read(fp, &x, 4) != 4) return -1;
+            if (is_be) ed_swap_4p(&x);
+            l->n = x;
+            if (l->n < 0) return -3;
+            if ((size_t) l->n > SIZE_MAX / sizeof(uint64_t)) return -2;
+            l->m = l->n;
+            l->offset = (uint64_t*)malloc(l->n * sizeof(uint64_t));
+            if (l->offset == NULL) return -2;
+            if (bgzf_read(fp, l->offset, l->n << 3) != l->n << 3) return -1;
+            if (is_be) for (j = 0; j < l->n; ++j) ed_swap_8p(&l->offset[j]);
+            for (k = j = 0; j < l->n && l->offset[j] == 0; k = ++j); // stop at the first non-zero entry
+            for (j = l->n-1; j > k; j--) // fill missing values; may happen given older samtools and tabix
+                if (l->offset[j-1] == 0) l->offset[j-1] = l->offset[j];
+            update_loff(idx, i, 0);
+        }
+    }
+    if (bgzf_read(fp, &idx->n_no_coor, 8) != 8) idx->n_no_coor = 0;
+    if (is_be) ed_swap_8p(&idx->n_no_coor);
+#ifdef DEBUG_INDEX
+    idx_dump(idx);
+#endif
+
+    return 0;
+}
+
+static hts_idx_t *idx_read(const char *fn)
+{
+    uint8_t magic[4];
+    int i, is_be;
+    hts_idx_t *idx = NULL;
+    uint8_t *meta = NULL;
+    BGZF *fp = bgzf_open(fn, "r");
+    if (fp == NULL) return NULL;
+    is_be = ed_is_big();
+    if (bgzf_read(fp, magic, 4) != 4) goto fail;
+
+    if (memcmp(magic, "CSI\1", 4) == 0) {
+        uint32_t x[3], n;
+        if (bgzf_read(fp, x, 12) != 12) goto fail;
+        if (is_be) for (i = 0; i < 3; ++i) ed_swap_4p(&x[i]);
+        if (x[2]) {
+            if (SIZE_MAX - x[2] < 1) goto fail; // Prevent possible overflow
+            if ((meta = (uint8_t*)malloc((size_t) x[2] + 1)) == NULL) goto fail;
+            if (bgzf_read(fp, meta, x[2]) != x[2]) goto fail;
+            // Prevent possible strlen past the end in tbx_index_load2
+            meta[x[2]] = '\0';
+        }
+        if (bgzf_read(fp, &n, 4) != 4) goto fail;
+        if (is_be) ed_swap_4p(&n);
+        if (n > INT32_MAX) goto fail;
+        if ((idx = hts_idx_init(n, HTS_FMT_CSI, 0, x[0], x[1])) == NULL) goto fail;
+        idx->l_meta = x[2];
+        idx->meta = meta;
+        meta = NULL;
+        if (idx_read_core(idx, fp, HTS_FMT_CSI) < 0) goto fail;
+    }
+    else if (memcmp(magic, "TBI\1", 4) == 0) {
+        uint8_t x[8 * 4];
+        uint32_t n;
+        // Read file header
+        if (bgzf_read(fp, x, sizeof(x)) != sizeof(x)) goto fail;
+        n = le_to_u32(&x[0]); // location of n_ref
+        if (n > INT32_MAX) goto fail;
+        if ((idx = hts_idx_init(n, HTS_FMT_TBI, 0, 14, 5)) == NULL) goto fail;
+        n = le_to_u32(&x[7*4]); // location of l_nm
+        if (n > UINT32_MAX - 29) goto fail; // Prevent possible overflow
+        idx->l_meta = 28 + n;
+        if ((idx->meta = (uint8_t*)malloc(idx->l_meta + 1)) == NULL) goto fail;
+        // copy format, col_seq, col_beg, col_end, meta, skip, l_nm
+        // N.B. left in little-endian byte order.
+        memcpy(idx->meta, &x[1*4], 28);
+        // Read in sequence names.
+        if (bgzf_read(fp, idx->meta + 28, n) != n) goto fail;
+        // Prevent possible strlen past the end in tbx_index_load2
+        idx->meta[idx->l_meta] = '\0';
+        if (idx_read_core(idx, fp, HTS_FMT_TBI) < 0) goto fail;
+    }
+    else if (memcmp(magic, "BAI\1", 4) == 0) {
+        uint32_t n;
+        if (bgzf_read(fp, &n, 4) != 4) goto fail;
+        if (is_be) ed_swap_4p(&n);
+        if (n > INT32_MAX) goto fail;
+        if ((idx = hts_idx_init(n, HTS_FMT_BAI, 0, 14, 5)) == NULL) goto fail;
+        if (idx_read_core(idx, fp, HTS_FMT_BAI) < 0) goto fail;
+    }
+    else { errno = EINVAL; goto fail; }
+
+    bgzf_close(fp);
+    return idx;
+
+fail:
+    bgzf_close(fp);
+    hts_idx_destroy(idx);
+    free(meta);
+    return NULL;
+}
+
+int hts_idx_set_meta(hts_idx_t *idx, uint32_t l_meta, uint8_t *meta,
+                      int is_copy)
+{
+    uint8_t *new_meta = meta;
+    if (is_copy) {
+        size_t l = l_meta;
+        if (l > SIZE_MAX - 1) {
+            errno = ENOMEM;
+            return -1;
+        }
+        new_meta = malloc(l + 1);
+        if (!new_meta) return -1;
+        memcpy(new_meta, meta, l);
+        // Prevent possible strlen past the end in tbx_index_load2
+        new_meta[l] = '\0';
+    }
+    if (idx->meta) free(idx->meta);
+    idx->l_meta = l_meta;
+    idx->meta = new_meta;
+    return 0;
+}
+
+uint8_t *hts_idx_get_meta(hts_idx_t *idx, uint32_t *l_meta)
+{
+    *l_meta = idx->l_meta;
+    return idx->meta;
+}
+
+const char **hts_idx_seqnames(const hts_idx_t *idx, int *n, hts_id2name_f getid, void *hdr)
+{
+    if ( !idx || !idx->n )
+    {
+        *n = 0;
+        return NULL;
+    }
+
+    int tid = 0, i;
+    const char **names = (const char**) calloc(idx->n,sizeof(const char*));
+    for (i=0; in; i++)
+    {
+        bidx_t *bidx = idx->bidx[i];
+        if ( !bidx ) continue;
+        names[tid++] = getid(hdr,i);
+    }
+    *n = tid;
+    return names;
+}
+
+int hts_idx_nseq(const hts_idx_t *idx) {
+    if (!idx) return -1;
+    return idx->n;
+}
+
+int hts_idx_get_stat(const hts_idx_t* idx, int tid, uint64_t* mapped, uint64_t* unmapped)
+{
+    if (!idx) return -1;
+    if ( idx->fmt == HTS_FMT_CRAI ) {
+        *mapped = 0; *unmapped = 0;
+        return -1;
+    }
+
+    bidx_t *h = idx->bidx[tid];
+    if (!h) return -1;
+    khint_t k = kh_get(bin, h, META_BIN(idx));
+    if (k != kh_end(h)) {
+        *mapped = kh_val(h, k).list[1].u;
+        *unmapped = kh_val(h, k).list[1].v;
+        return 0;
+    } else {
+        *mapped = 0; *unmapped = 0;
+        return -1;
+    }
+}
+
+uint64_t hts_idx_get_n_no_coor(const hts_idx_t* idx)
+{
+    if (idx->fmt == HTS_FMT_CRAI) return 0;
+    return idx->n_no_coor;
+}
+
+/****************
+ *** Iterator ***
+ ****************/
+
+// Note: even with 32-bit hts_pos_t, end needs to be 64-bit here due to 1LL<>s); e = t + (end>>s);
+        for (i = b; i <= e; ++i) {
+            if (kh_get(bin, bidx, i) != kh_end(bidx)) {
+                assert(itr->bins.n < itr->bins.m);
+                itr->bins.a[itr->bins.n++] = i;
+            }
+        }
+    }
+    return itr->bins.n;
+}
+
+static inline int reg2bins_wide(int64_t beg, int64_t end, hts_itr_t *itr, int min_shift, int n_lvls, bidx_t *bidx)
+{
+    khint_t i;
+    hts_pos_t max_shift = 3 * n_lvls + min_shift;
+    --end;
+    if (beg < 0) beg = 0;
+    for (i = kh_begin(bidx); i != kh_end(bidx); i++) {
+        if (!kh_exist(bidx, i)) continue;
+        hts_pos_t bin = (hts_pos_t) kh_key(bidx, i);
+        int level = hts_bin_level(bin);
+        if (level > n_lvls) continue; // Dodgy index?
+        hts_pos_t first = hts_bin_first(level);
+        hts_pos_t beg_at_level = first + (beg >> (max_shift - 3 * level));
+        hts_pos_t end_at_level = first + (end >> (max_shift - 3 * level));
+        if (beg_at_level <= bin && bin <= end_at_level) {
+            assert(itr->bins.n < itr->bins.m);
+            itr->bins.a[itr->bins.n++] = bin;
+        }
+    }
+    return itr->bins.n;
+}
+
+static inline int reg2bins(int64_t beg, int64_t end, hts_itr_t *itr, int min_shift, int n_lvls, bidx_t *bidx)
+{
+    int l, t, s = min_shift + (n_lvls<<1) + n_lvls;
+    size_t reg_bin_count = 0, hash_bin_count = kh_n_buckets(bidx), max_bins;
+    hts_pos_t end1;
+    if (end >= 1LL<= end) return 0;
+    end1 = end - 1;
+
+    // Count bins to see if it's faster to iterate through the hash table
+    // or the set of bins covering the region
+    for (l = 0, t = 0; l <= n_lvls; s -= 3, t += 1<<((l<<1)+l), ++l) {
+        reg_bin_count += (end1 >> s) - (beg >> s) + 1;
+    }
+    max_bins = reg_bin_count < kh_size(bidx) ? reg_bin_count : kh_size(bidx);
+    if (itr->bins.m - itr->bins.n < max_bins) {
+        // Worst-case memory usage.  May be wasteful on very sparse
+        // data, but the bin list usually won't be too big anyway.
+        size_t new_m = max_bins + itr->bins.n;
+        if (new_m > INT_MAX || new_m > SIZE_MAX / sizeof(int)) {
+            errno = ENOMEM;
+            return -1;
+        }
+        int *new_a = realloc(itr->bins.a, new_m * sizeof(*new_a));
+        if (!new_a) return -1;
+        itr->bins.a = new_a;
+        itr->bins.m = new_m;
+    }
+    if (reg_bin_count < hash_bin_count) {
+        return reg2bins_narrow(beg, end, itr, min_shift, n_lvls, bidx);
+    } else {
+        return reg2bins_wide(beg, end, itr, min_shift, n_lvls, bidx);
+    }
+}
+
+static inline int add_to_interval(hts_itr_t *iter, bins_t *bin,
+                                  int tid, uint32_t interval,
+                                  uint64_t min_off, uint64_t max_off)
+{
+    hts_pair64_max_t *off;
+    int j;
+
+    if (!bin->n)
+        return 0;
+    off = realloc(iter->off, (iter->n_off + bin->n) * sizeof(*off));
+    if (!off)
+        return -2;
+
+    iter->off = off;
+    for (j = 0; j < bin->n; ++j) {
+        if (bin->list[j].v > min_off && bin->list[j].u < max_off) {
+            iter->off[iter->n_off].u = min_off > bin->list[j].u
+                ? min_off : bin->list[j].u;
+            iter->off[iter->n_off].v = max_off < bin->list[j].v
+                ? max_off : bin->list[j].v;
+            // hts_pair64_max_t::max is now used to link
+            // file offsets to region list entries.
+            // The iterator can use this to decide if it
+            // can skip some file regions.
+            iter->off[iter->n_off].max = ((uint64_t) tid << 32) | interval;
+            iter->n_off++;
+        }
+    }
+    return 0;
+}
+
+static inline int reg2intervals_narrow(hts_itr_t *iter, const bidx_t *bidx,
+                                       int tid, int64_t beg, int64_t end,
+                                       uint32_t interval,
+                                       uint64_t min_off, uint64_t max_off,
+                                       int min_shift, int n_lvls)
+{
+    int l, t, s = min_shift + n_lvls * 3;
+    hts_pos_t b, e, i;
+
+    for (--end, l = 0, t = 0; l <= n_lvls; s -= 3, t += 1<<((l<<1)+l), ++l) {
+        b = t + (beg>>s); e = t + (end>>s);
+        for (i = b; i <= e; ++i) {
+            khint_t k = kh_get(bin, bidx, i);
+            if (k != kh_end(bidx)) {
+                bins_t *bin = &kh_value(bidx, k);
+                int res = add_to_interval(iter, bin, tid, interval, min_off, max_off);
+                if (res < 0)
+                    return res;
+            }
+        }
+    }
+    return 0;
+}
+
+static inline int reg2intervals_wide(hts_itr_t *iter, const bidx_t *bidx,
+                                       int tid, int64_t beg, int64_t end,
+                                       uint32_t interval,
+                                       uint64_t min_off, uint64_t max_off,
+                                       int min_shift, int n_lvls)
+{
+    khint_t i;
+    hts_pos_t max_shift = 3 * n_lvls + min_shift;
+    --end;
+    if (beg < 0) beg = 0;
+    for (i = kh_begin(bidx); i != kh_end(bidx); i++) {
+        if (!kh_exist(bidx, i)) continue;
+        hts_pos_t bin = (hts_pos_t) kh_key(bidx, i);
+        int level = hts_bin_level(bin);
+        if (level > n_lvls) continue; // Dodgy index?
+        hts_pos_t first = hts_bin_first(level);
+        hts_pos_t beg_at_level = first + (beg >> (max_shift - 3 * level));
+        hts_pos_t end_at_level = first + (end >> (max_shift - 3 * level));
+        if (beg_at_level <= bin && bin <= end_at_level) {
+            bins_t *bin = &kh_value(bidx, i);
+            int res = add_to_interval(iter, bin, tid, interval, min_off, max_off);
+            if (res < 0)
+                return res;
+        }
+    }
+    return 0;
+}
+
+static inline int reg2intervals(hts_itr_t *iter, const hts_idx_t *idx, int tid, int64_t beg, int64_t end, uint32_t interval, uint64_t min_off, uint64_t max_off, int min_shift, int n_lvls)
+{
+    int l, t, s;
+    int i, j;
+    hts_pos_t end1;
+    bidx_t *bidx;
+    int start_n_off;
+    size_t reg_bin_count = 0, hash_bin_count;
+    int res;
+
+    if (!iter || !idx || (bidx = idx->bidx[tid]) == NULL || beg > end)
+        return -1;
+
+    hash_bin_count = kh_n_buckets(bidx);
+
+    s = min_shift + (n_lvls<<1) + n_lvls;
+    if (end >= 1LL<> s) - (beg >> s) + 1;
+    }
+
+    start_n_off = iter->n_off;
+
+    // Populate iter->off with the intervals for this region
+    if (reg_bin_count < hash_bin_count) {
+        res = reg2intervals_narrow(iter, bidx, tid, beg, end, interval,
+                                   min_off, max_off, min_shift, n_lvls);
+    } else {
+        res = reg2intervals_wide(iter, bidx, tid, beg, end, interval,
+                                 min_off, max_off, min_shift, n_lvls);
+    }
+    if (res < 0)
+        return res;
+
+    if (iter->n_off - start_n_off > 1) {
+        ks_introsort(_off_max, iter->n_off - start_n_off, iter->off + start_n_off);
+        for (i = start_n_off, j = start_n_off + 1; j < iter->n_off; j++) {
+            if (iter->off[i].v >= iter->off[j].u) {
+                if (iter->off[i].v < iter->off[j].v)
+                    iter->off[i].v = iter->off[j].v;
+            } else {
+                i++;
+                if (i < j)
+                    iter->off[i] = iter->off[j];
+            }
+        }
+        iter->n_off = i + 1;
+    }
+
+    return iter->n_off;
+}
+
+static int compare_regions(const void *r1, const void *r2) {
+    hts_reglist_t *reg1 = (hts_reglist_t *)r1;
+    hts_reglist_t *reg2 = (hts_reglist_t *)r2;
+
+    if (reg1->tid < 0 && reg2->tid >= 0)
+        return 1;
+    else if (reg1->tid >= 0 && reg2->tid < 0)
+        return -1;
+    else
+        return reg1->tid - reg2->tid;
+}
+
+uint64_t hts_itr_off(const hts_idx_t* idx, int tid) {
+
+    int i;
+    bidx_t* bidx;
+    uint64_t off0 = (uint64_t) -1;
+    khint_t k;
+    switch (tid) {
+    case HTS_IDX_START:
+        // Find the smallest offset, note that sequence ids may not be ordered sequentially
+        for (i = 0; i < idx->n; i++) {
+            bidx = idx->bidx[i];
+            k = kh_get(bin, bidx, META_BIN(idx));
+            if (k == kh_end(bidx))
+                continue;
+
+            if (off0 > kh_val(bidx, k).list[0].u)
+                off0 = kh_val(bidx, k).list[0].u;
+        }
+        if (off0 == (uint64_t) -1 && idx->n_no_coor)
+            off0 = 0;
+        // only no-coor reads in this bam
+        break;
+    case HTS_IDX_NOCOOR:
+        /* No-coor reads sort after all of the mapped reads.  The position
+           is not stored in the index itself, so need to find the end
+           offset for the last mapped read.  A loop is needed here in
+           case references at the end of the file have no mapped reads,
+           or sequence ids are not ordered sequentially.
+           See issue samtools#568 and commits b2aab8, 60c22d and cc207d. */
+        for (i = 0; i < idx->n; i++) {
+            bidx = idx->bidx[i];
+            k = kh_get(bin, bidx, META_BIN(idx));
+            if (k != kh_end(bidx)) {
+                if (off0 == (uint64_t) -1 || off0 < kh_val(bidx, k).list[0].v) {
+                    off0 = kh_val(bidx, k).list[0].v;
+                }
+            }
+        }
+        if (off0 == (uint64_t) -1 && idx->n_no_coor)
+            off0 = 0;
+        // only no-coor reads in this bam
+        break;
+    case HTS_IDX_REST:
+        off0 = 0;
+        break;
+    case HTS_IDX_NONE:
+        off0 = 0;
+        break;
+    }
+
+    return off0;
+}
+
+hts_itr_t *hts_itr_query(const hts_idx_t *idx, int tid, hts_pos_t beg, hts_pos_t end, hts_readrec_func *readrec)
+{
+    int i, n_off, l, bin;
+    hts_pair64_max_t *off;
+    khint_t k;
+    bidx_t *bidx;
+    uint64_t min_off, max_off;
+    hts_pos_t idx_maxpos;
+    hts_itr_t *iter;
+    uint32_t unmapped = 0, rel_off;
+
+    // It's possible to call this function with NULL idx iff
+    // tid is one of the special values HTS_IDX_REST or HTS_IDX_NONE
+    if (!idx && !(tid == HTS_IDX_REST || tid == HTS_IDX_NONE)) {
+        errno = EINVAL;
+        return NULL;
+    }
+
+    iter = (hts_itr_t*)calloc(1, sizeof(hts_itr_t));
+    if (iter) {
+        if (tid < 0) {
+            uint64_t off = hts_itr_off(idx, tid);
+            if (off != (uint64_t) -1) {
+                iter->read_rest = 1;
+                iter->curr_off = off;
+                iter->readrec = readrec;
+                if (tid == HTS_IDX_NONE)
+                    iter->finished = 1;
+            } else {
+                free(iter);
+                iter = NULL;
+            }
+        } else if (tid >= idx->n || (bidx = idx->bidx[tid]) == NULL) {
+            iter->finished = 1;
+        } else {
+            if (beg < 0) beg = 0;
+            if (end < beg) {
+              free(iter);
+              return NULL;
+            }
+
+            k = kh_get(bin, bidx, META_BIN(idx));
+            if (k != kh_end(bidx))
+                unmapped = kh_val(bidx, k).list[1].v;
+            else
+                unmapped = 1;
+
+            iter->tid = tid, iter->beg = beg, iter->end = end; iter->i = -1;
+            iter->readrec = readrec;
+
+            if ( !kh_size(bidx) ) { iter->finished = 1; return iter; }
+
+            idx_maxpos = hts_idx_maxpos(idx);
+            if (beg >= idx_maxpos) { iter->finished = 1; return iter; }
+
+            rel_off = beg>>idx->min_shift;
+            // compute min_off
+            bin = hts_bin_first(idx->n_lvls) + rel_off;
+            do {
+                int first;
+                k = kh_get(bin, bidx, bin);
+                if (k != kh_end(bidx)) break;
+                first = (hts_bin_parent(bin)<<3) + 1;
+                if (bin > first) --bin;
+                else bin = hts_bin_parent(bin);
+            } while (bin);
+            if (bin == 0) k = kh_get(bin, bidx, bin);
+            min_off = k != kh_end(bidx)? kh_val(bidx, k).loff : 0;
+            // min_off can be calculated more accurately if the
+            // linear index is available
+            if (idx->lidx[tid].offset
+                && rel_off < idx->lidx[tid].n) {
+                if (min_off < idx->lidx[tid].offset[rel_off])
+                    min_off = idx->lidx[tid].offset[rel_off];
+                if (unmapped) {
+                    // unmapped reads are not covered by the linear index,
+                    // so search backwards for a smaller offset
+                    int tmp_off;
+                    for (tmp_off = rel_off-1; tmp_off >= 0; tmp_off--) {
+                        if (idx->lidx[tid].offset[tmp_off] < min_off) {
+                            min_off = idx->lidx[tid].offset[tmp_off];
+                            break;
+                        }
+                    }
+                    // if the search went too far back or no satisfactory entry
+                    // was found, revert to the bin index loff value
+                    if (k != kh_end(bidx) && (min_off < kh_val(bidx, k).loff || tmp_off < 0))
+                        min_off = kh_val(bidx, k).loff;
+                }
+            } else if (unmapped) { //CSI index
+                if (k != kh_end(bidx))
+                    min_off = kh_val(bidx, k).loff;
+            }
+
+            // compute max_off: a virtual offset from a bin to the right of end
+            // First check if end lies within the range of the index (it won't
+            // if it's HTS_POS_MAX)
+            if (end <= idx_maxpos) {
+                bin = hts_bin_first(idx->n_lvls) + ((end-1) >> idx->min_shift) + 1;
+                if (bin >= idx->n_bins) bin = 0;
+                while (1) {
+                    // search for an extant bin by moving right, but moving up to the
+                    // parent whenever we get to a first child (which also covers falling
+                    // off the RHS, which wraps around and immediately goes up to bin 0)
+                    while (bin % 8 == 1) bin = hts_bin_parent(bin);
+                    if (bin == 0) { max_off = UINT64_MAX; break; }
+                    k = kh_get(bin, bidx, bin);
+                    if (k != kh_end(bidx) && kh_val(bidx, k).n > 0) { max_off = kh_val(bidx, k).list[0].u; break; }
+                    bin++;
+                }
+            } else {
+                // Searching to end of reference
+                max_off = UINT64_MAX;
+            }
+
+            // retrieve bins
+            if (reg2bins(beg, end, iter, idx->min_shift, idx->n_lvls, bidx) < 0) {
+                hts_itr_destroy(iter);
+                return NULL;
+            }
+
+            for (i = n_off = 0; i < iter->bins.n; ++i)
+                if ((k = kh_get(bin, bidx, iter->bins.a[i])) != kh_end(bidx))
+                    n_off += kh_value(bidx, k).n;
+            if (n_off == 0) {
+                // No overlapping bins means the iterator has already finished.
+                iter->finished = 1;
+                return iter;
+            }
+            off = calloc(n_off, sizeof(*off));
+            for (i = n_off = 0; i < iter->bins.n; ++i) {
+                if ((k = kh_get(bin, bidx, iter->bins.a[i])) != kh_end(bidx)) {
+                    int j;
+                    bins_t *p = &kh_value(bidx, k);
+                    for (j = 0; j < p->n; ++j)
+                        if (p->list[j].v > min_off && p->list[j].u < max_off) {
+                            off[n_off].u = min_off > p->list[j].u
+                                ? min_off : p->list[j].u;
+                            off[n_off].v = max_off < p->list[j].v
+                                ? max_off : p->list[j].v;
+                            // hts_pair64_max_t::max is now used to link
+                            // file offsets to region list entries.
+                            // The iterator can use this to decide if it
+                            // can skip some file regions.
+                            off[n_off].max = ((uint64_t) tid << 32) | j;
+                            n_off++;
+                        }
+                }
+            }
+
+            if (n_off == 0) {
+                free(off);
+                iter->finished = 1;
+                return iter;
+            }
+            ks_introsort(_off_max, n_off, off);
+            // resolve completely contained adjacent blocks
+            for (i = 1, l = 0; i < n_off; ++i)
+                if (off[l].v < off[i].v) off[++l] = off[i];
+            n_off = l + 1;
+            // resolve overlaps between adjacent blocks; this may happen due to the merge in indexing
+            for (i = 1; i < n_off; ++i)
+                if (off[i-1].v >= off[i].u) off[i-1].v = off[i].u;
+            // merge adjacent blocks
+            for (i = 1, l = 0; i < n_off; ++i) {
+                if (off[l].v>>16 == off[i].u>>16) off[l].v = off[i].v;
+                else off[++l] = off[i];
+            }
+            n_off = l + 1;
+            iter->n_off = n_off; iter->off = off;
+        }
+    }
+
+    return iter;
+}
+
+int hts_itr_multi_bam(const hts_idx_t *idx, hts_itr_t *iter)
+{
+    int i, j, bin;
+    khint_t k;
+    bidx_t *bidx;
+    uint64_t min_off, max_off, t_off = (uint64_t)-1;
+    int tid;
+    hts_pos_t beg, end, idx_maxpos;
+    hts_reglist_t *curr_reg;
+    uint32_t unmapped = 0, rel_off;
+
+    if (!idx || !iter || !iter->multi)
+        return -1;
+
+    iter->i = -1;
+    for (i=0; in_reg; i++) {
+
+        curr_reg = &iter->reg_list[i];
+        tid = curr_reg->tid;
+
+        if (tid < 0) {
+            t_off = hts_itr_off(idx, tid);
+            if (t_off != (uint64_t)-1) {
+                switch (tid) {
+                case HTS_IDX_NONE:
+                    iter->finished = 1;
+                    // fall through
+                case HTS_IDX_START:
+                case HTS_IDX_REST:
+                    iter->curr_off = t_off;
+                    iter->n_reg = 0;
+                    iter->reg_list = NULL;
+                    iter->read_rest = 1;
+                    return 0;
+                case HTS_IDX_NOCOOR:
+                    iter->nocoor = 1;
+                    iter->nocoor_off = t_off;
+                }
+            }
+        } else {
+            if (tid >= idx->n || (bidx = idx->bidx[tid]) == NULL || !kh_size(bidx))
+                continue;
+
+            k = kh_get(bin, bidx, META_BIN(idx));
+            if (k != kh_end(bidx))
+                unmapped = kh_val(bidx, k).list[1].v;
+            else
+                unmapped = 1;
+
+            idx_maxpos = hts_idx_maxpos(idx);
+
+            for(j=0; jcount; j++) {
+                hts_pair32_t *curr_intv = &curr_reg->intervals[j];
+                if (curr_intv->end < curr_intv->beg)
+                    continue;
+
+                beg = curr_intv->beg;
+                end = curr_intv->end;
+                if (beg >= idx_maxpos)
+                    continue;
+                rel_off = beg>>idx->min_shift;
+
+                /* Compute 'min_off' by searching the lowest level bin containing 'beg'.
+                       If the computed bin is not in the index, try the next bin to the
+                       left, belonging to the same parent. If it is the first sibling bin,
+                       try the parent bin. */
+                bin = hts_bin_first(idx->n_lvls) + rel_off;
+                do {
+                    int first;
+                    k = kh_get(bin, bidx, bin);
+                    if (k != kh_end(bidx)) break;
+                    first = (hts_bin_parent(bin)<<3) + 1;
+                    if (bin > first) --bin;
+                    else bin = hts_bin_parent(bin);
+                } while (bin);
+                if (bin == 0)
+                    k = kh_get(bin, bidx, bin);
+                min_off = k != kh_end(bidx)? kh_val(bidx, k).loff : 0;
+                // min_off can be calculated more accurately if the
+                // linear index is available
+                if (idx->lidx[tid].offset
+                    && rel_off < idx->lidx[tid].n) {
+                    if (min_off < idx->lidx[tid].offset[rel_off])
+                        min_off = idx->lidx[tid].offset[rel_off];
+                    if (unmapped) {
+                        int tmp_off;
+                        for (tmp_off = rel_off-1; tmp_off >= 0; tmp_off--) {
+                            if (idx->lidx[tid].offset[tmp_off] < min_off) {
+                                min_off = idx->lidx[tid].offset[tmp_off];
+                                break;
+                            }
+                        }
+
+                        if (k != kh_end(bidx) && (min_off < kh_val(bidx, k).loff || tmp_off < 0))
+                            min_off = kh_val(bidx, k).loff;
+                    }
+                } else if (unmapped) { //CSI index
+                    if (k != kh_end(bidx))
+                        min_off = kh_val(bidx, k).loff;
+                }
+
+                // compute max_off: a virtual offset from a bin to the right of end
+                // First check if end lies within the range of the index (it
+                // won't if it's HTS_POS_MAX)
+                if (end <= idx_maxpos) {
+                    bin = hts_bin_first(idx->n_lvls) + ((end-1) >> idx->min_shift) + 1;
+                    if (bin >= idx->n_bins) bin = 0;
+                    while (1) {
+                        // search for an extant bin by moving right, but moving up to the
+                        // parent whenever we get to a first child (which also covers falling
+                        // off the RHS, which wraps around and immediately goes up to bin 0)
+                        while (bin % 8 == 1) bin = hts_bin_parent(bin);
+                        if (bin == 0) { max_off = UINT64_MAX; break; }
+                        k = kh_get(bin, bidx, bin);
+                        if (k != kh_end(bidx) && kh_val(bidx, k).n > 0) {
+                            max_off = kh_val(bidx, k).list[0].u;
+                            break;
+                        }
+                        bin++;
+                    }
+                } else {
+                    // Searching to end of reference
+                    max_off = UINT64_MAX;
+                }
+
+                //convert coordinates to file offsets
+                if (reg2intervals(iter, idx, tid, beg, end, j,
+                                  min_off, max_off,
+                                  idx->min_shift, idx->n_lvls) < 0) {
+                    return -1;
+                }
+            }
+        }
+    }
+
+    if (iter->n_off > 1)
+        ks_introsort(_off_max, iter->n_off, iter->off);
+
+    if(!iter->n_off && !iter->nocoor)
+        iter->finished = 1;
+
+    return 0;
+}
+
+int hts_itr_multi_cram(const hts_idx_t *idx, hts_itr_t *iter)
+{
+    const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
+    int tid, i, n_off = 0;
+    uint32_t j;
+    hts_pos_t beg, end;
+    hts_reglist_t *curr_reg;
+    hts_pair32_t *curr_intv;
+    hts_pair64_max_t *off = NULL, *tmp;
+    cram_index *e = NULL;
+
+    if (!cidx || !iter || !iter->multi)
+        return -1;
+
+    iter->is_cram = 1;
+    iter->read_rest = 0;
+    iter->off = NULL;
+    iter->n_off = 0;
+    iter->curr_off = 0;
+    iter->i = -1;
+
+    for (i=0; in_reg; i++) {
+
+        curr_reg = &iter->reg_list[i];
+        tid = curr_reg->tid;
+
+        if (tid >= 0) {
+            tmp = realloc(off, (n_off + curr_reg->count) * sizeof(*off));
+            if (!tmp)
+                goto err;
+            off = tmp;
+
+            for (j=0; j < curr_reg->count; j++) {
+                curr_intv = &curr_reg->intervals[j];
+                if (curr_intv->end < curr_intv->beg)
+                    continue;
+
+                beg = curr_intv->beg;
+                end = curr_intv->end;
+
+/* First, fetch the container overlapping 'beg' and assign its file offset to u, then
+ * find the container overlapping 'end' and assign the relative end of the slice to v.
+ * The cram_ptell function will adjust with the container offset, which is not stored
+ * in the index.
+ */
+                e = cram_index_query(cidx->cram, tid, beg+1, NULL);
+                if (e) {
+                    off[n_off].u = e->offset;
+                    // hts_pair64_max_t::max is now used to link
+                    // file offsets to region list entries.
+                    // The iterator can use this to decide if it
+                    // can skip some file regions.
+                    off[n_off].max = ((uint64_t) tid << 32) | j;
+
+                    if (end >= HTS_POS_MAX) {
+                       e = cram_index_last(cidx->cram, tid, NULL);
+                    } else {
+                       e = cram_index_query_last(cidx->cram, tid, end+1);
+                    }
+
+                    if (e) {
+                        off[n_off++].v = e->e_next
+                            ? e->e_next->offset
+                            : e->offset + e->slice + e->len;
+                    } else {
+                        hts_log_warning("Could not set offset end for region %d:%"PRIhts_pos"-%"PRIhts_pos". Skipping", tid, beg, end);
+                    }
+                }
+            }
+        } else {
+            switch (tid) {
+                case HTS_IDX_NOCOOR:
+                    e = cram_index_query(cidx->cram, tid, 1, NULL);
+                    if (e) {
+                        iter->nocoor = 1;
+                        iter->nocoor_off = e->offset;
+                    } else {
+                        hts_log_warning("No index entry for NOCOOR region");
+                    }
+                    break;
+                case HTS_IDX_START:
+                    e = cram_index_query(cidx->cram, tid, 1, NULL);
+                    if (e) {
+                        iter->read_rest = 1;
+                        tmp = realloc(off, sizeof(*off));
+                        if (!tmp)
+                            goto err;
+                        off = tmp;
+                        off[0].u = e->offset;
+                        off[0].v = 0;
+                        n_off=1;
+                    } else {
+                        hts_log_warning("No index entries");
+                    }
+                    break;
+                case HTS_IDX_REST:
+                    break;
+                case HTS_IDX_NONE:
+                    iter->finished = 1;
+                    break;
+                default:
+                    hts_log_error("Query with tid=%d not implemented for CRAM files", tid);
+            }
+        }
+    }
+
+    if (n_off) {
+        ks_introsort(_off_max, n_off, off);
+        iter->n_off = n_off; iter->off = off;
+    }
+
+    if(!n_off && !iter->nocoor)
+        iter->finished = 1;
+
+    return 0;
+
+ err:
+    free(off);
+    return -1;
+}
+
+void hts_itr_destroy(hts_itr_t *iter)
+{
+    if (iter) {
+        if (iter->multi) {
+            hts_reglist_free(iter->reg_list, iter->n_reg);
+        } else {
+            free(iter->bins.a);
+        }
+
+        if (iter->off)
+            free(iter->off);
+        free(iter);
+    }
+}
+
+static inline unsigned long long push_digit(unsigned long long i, char c)
+{
+    // ensure subtraction occurs first, avoiding overflow for >= MAX-48 or so
+    int digit = c - '0';
+    return 10 * i + digit;
+}
+
+long long hts_parse_decimal(const char *str, char **strend, int flags)
+{
+    unsigned long long n = 0;
+    int digits = 0, decimals = 0, e = 0, lost = 0;
+    char sign = '+', esign = '+';
+    const char *s, *str_orig = str;
+
+    while (isspace_c(*str)) str++;
+    s = str;
+
+    if (*s == '+' || *s == '-') sign = *s++;
+    while (*s)
+        if (isdigit_c(*s)) digits++, n = push_digit(n, *s++);
+        else if (*s == ',' && (flags & HTS_PARSE_THOUSANDS_SEP)) s++;
+        else break;
+
+    if (*s == '.') {
+        s++;
+        while (isdigit_c(*s)) decimals++, digits++, n = push_digit(n, *s++);
+    }
+
+    switch (*s) {
+    case 'e': case 'E':
+        s++;
+        if (*s == '+' || *s == '-') esign = *s++;
+        while (isdigit_c(*s)) e = push_digit(e, *s++);
+        if (esign == '-') e = -e;
+        break;
+
+    case 'k': case 'K': e += 3; s++; break;
+    case 'm': case 'M': e += 6; s++; break;
+    case 'g': case 'G': e += 9; s++; break;
+    }
+
+    e -= decimals;
+    while (e > 0) n *= 10, e--;
+    while (e < 0) lost += n % 10, n /= 10, e++;
+
+    if (lost > 0) {
+        hts_log_warning("Discarding fractional part of %.*s", (int)(s - str), str);
+    }
+
+    if (strend) {
+        // Set to the original input str pointer if not valid number syntax
+        *strend = (digits > 0)? (char *)s : (char *)str_orig;
+    } else if (digits == 0) {
+        hts_log_warning("Invalid numeric value %.8s[truncated]", str);
+    } else if (*s) {
+        if ((flags & HTS_PARSE_THOUSANDS_SEP) || (!(flags & HTS_PARSE_THOUSANDS_SEP) && *s != ','))
+            hts_log_warning("Ignoring unknown characters after %.*s[%s]", (int)(s - str), str, s);
+    }
+
+    return (sign == '+')? n : -n;
+}
+
+static void *hts_memrchr(const void *s, int c, size_t n) {
+    size_t i;
+    unsigned char *u = (unsigned char *)s;
+    for (i = n; i > 0; i--) {
+        if (u[i-1] == c)
+            return u+i-1;
+    }
+
+    return NULL;
+}
+
+/*
+ * A variant of hts_parse_reg which is reference-id aware.  It uses
+ * the iterator name2id callbacks to validate the region tokenisation works.
+ *
+ * This is necessary due to GRCh38 HLA additions which have reference names
+ * like "HLA-DRB1*12:17".
+ *
+ * All parameters are mandatory.
+ *
+ * To work around ambiguous parsing issues, eg both "chr1" and "chr1:100-200"
+ * are reference names, we may quote using curly braces.
+ * Thus "{chr1}:100-200" and "{chr1:100-200}" disambiguate the above example.
+ *
+ * Flags are used to control how parsing works, and can be one of the below.
+ *
+ * HTS_PARSE_LIST:
+ *     If present, the region is assmed to be a comma separated list and
+ *     position parsing will not contain commas (this implicitly
+ *     clears HTS_PARSE_THOUSANDS_SEP in the call to hts_parse_decimal).
+ *     On success the return pointer will be the start of the next region, ie
+ *     the character after the comma.  (If *ret != '\0' then the caller can
+ *     assume another region is present in the list.)
+ *
+ *     If not set then positions may contain commas.  In this case the return
+ *     value should point to the end of the string, or NULL on failure.
+ *
+ * HTS_PARSE_ONE_COORD:
+ *     If present, X:100 is treated as the single base pair region X:100-100.
+ *     In this case X:-100 is shorthand for X:1-100 and X:100- is X:100-.
+ *     (This is the standard bcftools region convention.)
+ *
+ *     When not set X:100 is considered to be X:100- where  is
+ *     the end of chromosome X (set to HTS_POS_MAX here).  X:100- and X:-100
+ *     are invalid.
+ *     (This is the standard samtools region convention.)
+ *
+ * Note the supplied string expects 1 based inclusive coordinates, but the
+ * returned coordinates start from 0 and are half open, so pos0 is valid
+ * for use in e.g. "for (pos0 = beg; pos0 < end; pos0++) {...}"
+ *
+ * On success a pointer to the byte after the end of the entire region
+ *            specifier is returned (plus any trailing comma), and tid,
+ *            beg & end will be set.
+ * On failure NULL is returned.
+ */
+const char *hts_parse_region(const char *s, int *tid, hts_pos_t *beg,
+                             hts_pos_t *end, hts_name2id_f getid, void *hdr,
+                             int flags)
+{
+    if (!s || !tid || !beg || !end || !getid)
+        return NULL;
+
+    size_t s_len = strlen(s);
+    kstring_t ks = { 0, 0, NULL };
+
+    const char *colon = NULL, *comma = NULL;
+    int quoted = 0;
+
+    if (flags & HTS_PARSE_LIST)
+        flags &= ~HTS_PARSE_THOUSANDS_SEP;
+    else
+        flags |= HTS_PARSE_THOUSANDS_SEP;
+
+    const char *s_end = s + s_len;
+
+    // Braced quoting of references is permitted to resolve ambiguities.
+    if (*s == '{') {
+        const char *close = memchr(s, '}', s_len);
+        if (!close) {
+            hts_log_error("Mismatching braces in \"%s\"", s);
+            *tid = -1;
+            return NULL;
+        }
+        s++;
+        s_len--;
+        if (close[1] == ':')
+            colon = close+1;
+        quoted = 1; // number of trailing characters to trim
+
+        // Truncate to this item only, if appropriate.
+        if (flags & HTS_PARSE_LIST) {
+            comma = strchr(close, ',');
+            if (comma) {
+                s_len = comma-s;
+                s_end = comma+1;
+            }
+        }
+    } else {
+        // Truncate to this item only, if appropriate.
+        if (flags & HTS_PARSE_LIST) {
+            comma = strchr(s, ',');
+            if (comma) {
+                s_len = comma-s;
+                s_end = comma+1;
+            }
+        }
+
+        colon = hts_memrchr(s, ':', s_len);
+    }
+
+    // No colon is simplest case; just check and return.
+    if (colon == NULL) {
+        *beg = 0; *end = HTS_POS_MAX;
+        kputsn(s, s_len-quoted, &ks); // convert to nul terminated string
+        if (!ks.s) {
+            *tid = -2;
+            return NULL;
+        }
+
+        *tid = getid(hdr, ks.s);
+        free(ks.s);
+
+        return *tid >= 0 ? s_end : NULL;
+    }
+
+    // Has a colon, but check whole name first.
+    if (!quoted) {
+        *beg = 0; *end = HTS_POS_MAX;
+        kputsn(s, s_len, &ks); // convert to nul terminated string
+        if (!ks.s) {
+            *tid = -2;
+            return NULL;
+        }
+        if ((*tid = getid(hdr, ks.s)) >= 0) {
+            // Entire name matches, but also check this isn't
+            // ambiguous.  eg we have ref chr1 and ref chr1:100-200
+            // both present.
+            ks.l = 0;
+            kputsn(s, colon-s, &ks); // convert to nul terminated string
+            if (!ks.s) {
+                *tid = -2;
+                return NULL;
+            }
+            if (getid(hdr, ks.s) >= 0) {
+                free(ks.s);
+                *tid = -1;
+                hts_log_error("Range is ambiguous. "
+                              "Use {%s} or {%.*s}%s instead",
+                              s, (int)(colon-s), s, colon);
+                return NULL;
+            }
+            free(ks.s);
+
+            return s_end;
+        }
+        if (*tid < -1) // Failed to parse header
+            return NULL;
+    }
+
+    // Quoted, or unquoted and whole string isn't a name.
+    // Check the pre-colon part is valid.
+    ks.l = 0;
+    kputsn(s, colon-s-quoted, &ks); // convert to nul terminated string
+    if (!ks.s) {
+        *tid = -2;
+        return NULL;
+    }
+    *tid = getid(hdr, ks.s);
+    free(ks.s);
+    if (*tid < 0)
+        return NULL;
+
+    // Finally parse the post-colon coordinates
+    char *hyphen;
+    *beg = hts_parse_decimal(colon+1, &hyphen, flags) - 1;
+    if (*beg < 0) {
+        if (*beg != -1 && *hyphen == '-' && colon[1] != '\0') {
+            // User specified zero, but we're 1-based.
+            hts_log_error("Coordinates must be > 0");
+            return NULL;
+        }
+        if (isdigit_c(*hyphen) || *hyphen == '\0' || *hyphen == ',') {
+            // interpret chr:-100 as chr:1-100
+            *end = *beg==-1 ? HTS_POS_MAX : -(*beg+1);
+            *beg = 0;
+            return s_end;
+        } else if (*beg < -1) {
+            hts_log_error("Unexpected string \"%s\" after region", hyphen);
+            return NULL;
+        }
+    }
+
+    if (*hyphen == '\0' || ((flags & HTS_PARSE_LIST) && *hyphen == ',')) {
+        *end = flags & HTS_PARSE_ONE_COORD ? *beg+1 : HTS_POS_MAX;
+    } else if (*hyphen == '-') {
+        *end = hts_parse_decimal(hyphen+1, &hyphen, flags);
+        if (*hyphen != '\0' && *hyphen != ',') {
+            hts_log_error("Unexpected string \"%s\" after region", hyphen);
+            return NULL;
+        }
+    } else {
+        hts_log_error("Unexpected string \"%s\" after region", hyphen);
+        return NULL;
+    }
+
+    if (*end == 0)
+        *end = HTS_POS_MAX; // interpret chr:100- as chr:100-
+
+    if (*beg >= *end) return NULL;
+
+    return s_end;
+}
+
+// Next release we should mark this as deprecated?
+// Use hts_parse_region above instead.
+const char *hts_parse_reg64(const char *s, hts_pos_t *beg, hts_pos_t *end)
+{
+    char *hyphen;
+    const char *colon = strrchr(s, ':');
+    if (colon == NULL) {
+        *beg = 0; *end = HTS_POS_MAX;
+        return s + strlen(s);
+    }
+
+    *beg = hts_parse_decimal(colon+1, &hyphen, HTS_PARSE_THOUSANDS_SEP) - 1;
+    if (*beg < 0) *beg = 0;
+
+    if (*hyphen == '\0') *end = HTS_POS_MAX;
+    else if (*hyphen == '-') *end = hts_parse_decimal(hyphen+1, NULL, HTS_PARSE_THOUSANDS_SEP);
+    else return NULL;
+
+    if (*beg >= *end) return NULL;
+    return colon;
+}
+
+const char *hts_parse_reg(const char *s, int *beg, int *end)
+{
+    hts_pos_t beg64 = 0, end64 = 0;
+    const char *colon = hts_parse_reg64(s, &beg64, &end64);
+    if (beg64 > INT_MAX) {
+        hts_log_error("Position %"PRId64" too large", beg64);
+        return NULL;
+    }
+    if (end64 > INT_MAX) {
+        if (end64 == HTS_POS_MAX) {
+            end64 = INT_MAX;
+        } else {
+            hts_log_error("Position %"PRId64" too large", end64);
+            return NULL;
+        }
+    }
+    *beg = beg64;
+    *end = end64;
+    return colon;
+}
+
+hts_itr_t *hts_itr_querys(const hts_idx_t *idx, const char *reg, hts_name2id_f getid, void *hdr, hts_itr_query_func *itr_query, hts_readrec_func *readrec)
+{
+    int tid;
+    hts_pos_t beg, end;
+
+    if (strcmp(reg, ".") == 0)
+        return itr_query(idx, HTS_IDX_START, 0, 0, readrec);
+    else if (strcmp(reg, "*") == 0)
+        return itr_query(idx, HTS_IDX_NOCOOR, 0, 0, readrec);
+
+    if (!hts_parse_region(reg, &tid, &beg, &end, getid, hdr, HTS_PARSE_THOUSANDS_SEP))
+        return NULL;
+
+    return itr_query(idx, tid, beg, end, readrec);
+}
+
+hts_itr_t *hts_itr_regions(const hts_idx_t *idx, hts_reglist_t *reglist, int count, hts_name2id_f getid, void *hdr, hts_itr_multi_query_func *itr_specific, hts_readrec_func *readrec, hts_seek_func *seek, hts_tell_func *tell) {
+
+    int i;
+
+    if (!reglist)
+        return NULL;
+
+    hts_itr_t *itr = (hts_itr_t*)calloc(1, sizeof(hts_itr_t));
+    if (itr) {
+        itr->n_reg = count;
+        itr->readrec = readrec;
+        itr->seek = seek;
+        itr->tell = tell;
+        itr->reg_list = reglist;
+        itr->finished = 0;
+        itr->nocoor = 0;
+        itr->multi = 1;
+
+        for (i = 0; i < itr->n_reg; i++) {
+            if (itr->reg_list[i].reg) {
+                if (!strcmp(itr->reg_list[i].reg, ".")) {
+                    itr->reg_list[i].tid = HTS_IDX_START;
+                    continue;
+                }
+
+                if (!strcmp(itr->reg_list[i].reg, "*")) {
+                    itr->reg_list[i].tid = HTS_IDX_NOCOOR;
+                    continue;
+                }
+
+                itr->reg_list[i].tid = getid(hdr, reglist[i].reg);
+                if (itr->reg_list[i].tid < 0) {
+                    if (itr->reg_list[i].tid < -1) {
+                        hts_log_error("Failed to parse header");
+                        hts_itr_destroy(itr);
+                        return NULL;
+                    } else {
+                        hts_log_warning("Region '%s' specifies an unknown reference name. Continue anyway", reglist[i].reg);
+                    }
+                }
+            }
+        }
+
+        qsort(itr->reg_list, itr->n_reg, sizeof(hts_reglist_t), compare_regions);
+        if (itr_specific(idx, itr) != 0) {
+            hts_log_error("Failed to create the multi-region iterator!");
+            hts_itr_destroy(itr);
+            itr = NULL;
+        }
+    }
+
+    return itr;
+}
+
+int hts_itr_next(BGZF *fp, hts_itr_t *iter, void *r, void *data)
+{
+    int ret, tid;
+    hts_pos_t beg, end;
+    if (iter == NULL || iter->finished) return -1;
+    if (iter->read_rest) {
+        if (iter->curr_off) { // seek to the start
+            if (bgzf_seek(fp, iter->curr_off, SEEK_SET) < 0) {
+                hts_log_error("Failed to seek to offset %"PRIu64"%s%s",
+                              iter->curr_off,
+                              errno ? ": " : "", strerror(errno));
+                return -2;
+            }
+            iter->curr_off = 0; // only seek once
+        }
+        ret = iter->readrec(fp, data, r, &tid, &beg, &end);
+        if (ret < 0) iter->finished = 1;
+        iter->curr_tid = tid;
+        iter->curr_beg = beg;
+        iter->curr_end = end;
+        return ret;
+    }
+    // A NULL iter->off should always be accompanied by iter->finished.
+    assert(iter->off != NULL);
+    for (;;) {
+        if (iter->curr_off == 0 || iter->curr_off >= iter->off[iter->i].v) { // then jump to the next chunk
+            if (iter->i == iter->n_off - 1) { ret = -1; break; } // no more chunks
+            if (iter->i < 0 || iter->off[iter->i].v != iter->off[iter->i+1].u) { // not adjacent chunks; then seek
+                if (bgzf_seek(fp, iter->off[iter->i+1].u, SEEK_SET) < 0) {
+                    hts_log_error("Failed to seek to offset %"PRIu64"%s%s",
+                                  iter->off[iter->i+1].u,
+                                  errno ? ": " : "", strerror(errno));
+                    return -2;
+                }
+                iter->curr_off = bgzf_tell(fp);
+            }
+            ++iter->i;
+        }
+        if ((ret = iter->readrec(fp, data, r, &tid, &beg, &end)) >= 0) {
+            iter->curr_off = bgzf_tell(fp);
+            if (tid != iter->tid || beg >= iter->end) { // no need to proceed
+                ret = -1; break;
+            } else if (end > iter->beg && iter->end > beg) {
+                iter->curr_tid = tid;
+                iter->curr_beg = beg;
+                iter->curr_end = end;
+                return ret;
+            }
+        } else break; // end of file or error
+    }
+    iter->finished = 1;
+    return ret;
+}
+
+int hts_itr_multi_next(htsFile *fd, hts_itr_t *iter, void *r)
+{
+    void *fp;
+    int ret, tid, i, cr, ci;
+    hts_pos_t beg, end;
+    hts_reglist_t *found_reg;
+
+    if (iter == NULL || iter->finished) return -1;
+
+    if (iter->is_cram) {
+        fp = fd->fp.cram;
+    } else {
+        fp = fd->fp.bgzf;
+    }
+
+    if (iter->read_rest) {
+        if (iter->curr_off) { // seek to the start
+            if (iter->seek(fp, iter->curr_off, SEEK_SET) < 0) {
+                hts_log_error("Seek at offset %" PRIu64 " failed.", iter->curr_off);
+                return -1;
+            }
+            iter->curr_off = 0; // only seek once
+        }
+
+        ret = iter->readrec(fp, fd, r, &tid, &beg, &end);
+        if (ret < 0)
+            iter->finished = 1;
+
+        iter->curr_tid = tid;
+        iter->curr_beg = beg;
+        iter->curr_end = end;
+
+        return ret;
+    }
+    // A NULL iter->off should always be accompanied by iter->finished.
+    assert(iter->off != NULL || iter->nocoor != 0);
+
+    int next_range = 0;
+    for (;;) {
+        // Note that due to the way bam indexing works, iter->off may contain
+        // file chunks that are not actually needed as they contain data
+        // beyond the end of the requested region.  These are filtered out
+        // by comparing the tid and index into hts_reglist_t::intervals
+        // (packed for reasons of convenience into iter->off[iter->i].max)
+        // associated with the file region with iter->curr_tid and
+        // iter->curr_intv.
+
+        if (next_range
+            || iter->curr_off == 0
+            || iter->i >= iter->n_off
+            || iter->curr_off >= iter->off[iter->i].v
+            || (iter->off[iter->i].max >> 32 == iter->curr_tid
+                && (iter->off[iter->i].max & 0xffffffff) < iter->curr_intv)) {
+
+            // Jump to the next chunk.  It may be necessary to skip more
+            // than one as the iter->off list can include overlapping entries.
+            do {
+                iter->i++;
+            } while (iter->i < iter->n_off
+                     && (iter->curr_off >= iter->off[iter->i].v
+                         || (iter->off[iter->i].max >> 32 == iter->curr_tid
+                             && (iter->off[iter->i].max & 0xffffffff) < iter->curr_intv)));
+
+            if (iter->is_cram && iter->i < iter->n_off) {
+                // Ensure iter->curr_reg is correct.
+                //
+                // We need this for CRAM as we shortcut some of the later
+                // logic by getting an end-of-range and continuing to the
+                // next offset.
+                //
+                // We cannot do this for BAM (and fortunately do not need to
+                // either) because in BAM world a query to genomic positions
+                // GX and GY leading to a seek offsets PX and PY may have
+                // GX > GY and PX < PY.  (This is due to the R-tree and falling
+                // between intervals, bumping up to a higher bin.)
+                // CRAM strictly follows PX >= PY if GX >= GY, so this logic
+                // works.
+                int want_tid = iter->off[iter->i].max >> 32;
+                if (!(iter->curr_reg < iter->n_reg &&
+                      iter->reg_list[iter->curr_reg].tid == want_tid)) {
+                    int j;
+                    for (j = 0; j < iter->n_reg; j++)
+                        if (iter->reg_list[j].tid == want_tid)
+                            break;
+                    if (j == iter->n_reg)
+                        return -1;
+                    iter->curr_reg = j;
+                    iter->curr_tid = iter->reg_list[iter->curr_reg].tid;
+                };
+                iter->curr_intv = iter->off[iter->i].max & 0xffffffff;
+            }
+
+            if (iter->i >= iter->n_off) { // no more chunks, except NOCOORs
+                if (iter->nocoor) {
+                    next_range = 0;
+                    if (iter->seek(fp, iter->nocoor_off, SEEK_SET) < 0) {
+                        hts_log_error("Seek at offset %" PRIu64 " failed.", iter->nocoor_off);
+                        return -1;
+                    }
+                    if (iter->is_cram) {
+                        cram_range r = { HTS_IDX_NOCOOR };
+                        cram_set_option(fp, CRAM_OPT_RANGE_NOSEEK, &r);
+                    }
+
+                    // The first slice covering the unmapped reads might
+                    // contain a few mapped reads, so scroll
+                    // forward until finding the first unmapped read.
+                    do {
+                        ret = iter->readrec(fp, fd, r, &tid, &beg, &end);
+                    } while (tid >= 0 && ret >=0);
+
+                    if (ret < 0)
+                        iter->finished = 1;
+                    else
+                        iter->read_rest = 1;
+
+                    iter->curr_off = 0; // don't seek any more
+                    iter->curr_tid = tid;
+                    iter->curr_beg = beg;
+                    iter->curr_end = end;
+
+                    return ret;
+                } else {
+                    ret = -1; break;
+                }
+            } else if (iter->i < iter->n_off) {
+                // New chunk may overlap the last one, so ensure we
+                // only seek forwards.
+                if (iter->curr_off < iter->off[iter->i].u || next_range) {
+                    iter->curr_off = iter->off[iter->i].u;
+
+                    // CRAM has the capability of setting an end location.
+                    // This means multi-threaded decodes can stop once they
+                    // reach that point, rather than pointlessly decoding
+                    // more slices than we'll be using.
+                    //
+                    // We have to be careful here.  Whenever we set the cram
+                    // range we need a corresponding seek in order to ensure
+                    // we can safely decode at that offset.  We use next_range
+                    // var to ensure this is always true; this is set on
+                    // end-of-range condition. It's never modified for BAM.
+                    if (iter->is_cram) {
+                        // Next offset.[uv] tuple, but it's already been
+                        // included in our cram range, so don't seek and don't
+                        // reset range so we can efficiently multi-thread.
+                        if (next_range || iter->curr_off >= iter->end) {
+                            if (iter->seek(fp, iter->curr_off, SEEK_SET) < 0) {
+                                hts_log_error("Seek at offset %" PRIu64
+                                        " failed.", iter->curr_off);
+                                return -1;
+                            }
+
+                            // Find the genomic range matching this interval.
+                            int j;
+                            hts_reglist_t *rl = &iter->reg_list[iter->curr_reg];
+                            cram_range r = {
+                                    rl->tid,
+                                    rl->intervals[iter->curr_intv].beg,
+                                    rl->intervals[iter->curr_intv].end
+                            };
+
+                            // Expand it up to cover neighbouring intervals.
+                            // Note we can only have a single chromosome in a
+                            // range, so if we detect our blocks span chromosomes
+                            // or we have a multi-ref mode slice, we just use
+                            // HTS_IDX_START refid instead.  This doesn't actually
+                            // seek (due to CRAM_OPT_RANGE_NOSEEK) and is simply
+                            // and indicator of decoding with no end limit.
+                            //
+                            // That isn't as efficient as it could be, but it's
+                            // no poorer than before and it works.
+                            int tid = r.refid;
+                            int64_t end = r.end;
+                            int64_t v = iter->off[iter->i].v;
+                            j = iter->i+1;
+                            while (j < iter->n_off) {
+                                if (iter->off[j].u > v)
+                                    break;
+
+                                uint64_t max = iter->off[j].max;
+                                if ((max>>32) != tid) {
+                                    tid = HTS_IDX_START; // => no range limit
+                                } else {
+                                    if (end < rl->intervals[max & 0xffffffff].end)
+                                        end = rl->intervals[max & 0xffffffff].end;
+                                }
+                                if (v < iter->off[j].v)
+                                    v = iter->off[j].v;
+                                j++;
+                            }
+                            r.refid = tid;
+                            r.end = end;
+
+                            // Remember maximum 'v' here so we don't do
+                            // unnecessary subsequent seeks for the next
+                            // regions.  We can't change curr_off, but
+                            // beg/end are used only by single region iterator so
+                            // we cache it there to avoid changing the struct.
+                            iter->end = v;
+
+                            cram_set_option(fp, CRAM_OPT_RANGE_NOSEEK, &r);
+                            next_range = 0;
+                        }
+                    } else { // Not CRAM
+                        if (iter->seek(fp, iter->curr_off, SEEK_SET) < 0) {
+                            hts_log_error("Seek at offset %" PRIu64 " failed.",
+                                          iter->curr_off);
+                            return -1;
+                        }
+                    }
+                }
+            }
+        }
+
+        ret = iter->readrec(fp, fd, r, &tid, &beg, &end);
+        if (ret < 0) {
+            if (iter->is_cram && cram_eof(fp)) {
+                // Skip to end of range
+                //
+                // We should never be adjusting curr_off manually unless
+                // we also can guarantee we'll be doing a seek after to
+                // a new location.  Otherwise we'll be reading wrong offset
+                // for the next container.
+                //
+                // We ensure this by adjusting our CRAM_OPT_RANGE
+                // accordingly above, but to double check we also
+                // set the skipped_block flag to enforce a seek also.
+                iter->curr_off = iter->off[iter->i].v;
+                next_range = 1;
+
+                // Next region
+                if (++iter->curr_intv >= iter->reg_list[iter->curr_reg].count){
+                    if (++iter->curr_reg >= iter->n_reg)
+                        break;
+                    iter->curr_intv = 0;
+                    iter->curr_tid = iter->reg_list[iter->curr_reg].tid;
+                }
+                continue;
+            } else {
+                break;
+            }
+        }
+
+        iter->curr_off = iter->tell(fp);
+
+        if (tid != iter->curr_tid) {
+            hts_reglist_t key;
+            key.tid = tid;
+
+            found_reg = (hts_reglist_t *)bsearch(&key, iter->reg_list,
+                                                 iter->n_reg,
+                                                 sizeof(hts_reglist_t),
+                                                 compare_regions);
+            if (!found_reg)
+                continue;
+
+            iter->curr_reg = (found_reg - iter->reg_list);
+            iter->curr_tid = tid;
+            iter->curr_intv = 0;
+        }
+
+        cr = iter->curr_reg;
+        ci = iter->curr_intv;
+
+        for (i = ci; i < iter->reg_list[cr].count; i++) {
+            if (end > iter->reg_list[cr].intervals[i].beg &&
+                iter->reg_list[cr].intervals[i].end > beg) {
+                iter->curr_beg = beg;
+                iter->curr_end = end;
+                iter->curr_intv = i;
+
+                return ret;
+            }
+
+            // Check if the read starts beyond intervals[i].end
+            // If so, the interval is finished so move on to the next.
+            if (beg > iter->reg_list[cr].intervals[i].end)
+                iter->curr_intv = i + 1;
+
+            // No need to keep searching if the read ends before intervals[i].beg
+            if (end < iter->reg_list[cr].intervals[i].beg)
+                break;
+        }
+    }
+    iter->finished = 1;
+
+    return ret;
+}
+
+/**********************
+ *** Retrieve index ***
+ **********************/
+// Local_fn and local_len will return a sub-region of 'fn'.
+// Eg http://elsewhere/dir/foo.bam.bai?a=b may return
+// foo.bam.bai via local_fn and local_len.
+//
+// Returns -1 if index couldn't be opened.
+//         -2 on other errors
+static int idx_test_and_fetch(const char *fn, const char **local_fn, int *local_len, int download)
+{
+    hFILE *remote_hfp = NULL;
+    hFILE *local_fp = NULL;
+    int save_errno;
+    htsFormat fmt;
+    kstring_t s = KS_INITIALIZE;
+    kstring_t tmps = KS_INITIALIZE;
+
+    if (hisremote(fn)) {
+        const int buf_size = 1 * 1024 * 1024;
+        int l;
+        const char *p, *e;
+        // Ignore ?# params: eg any file.fmt?param=val, except for S3 URLs
+        e = fn + ((strncmp(fn, "s3://", 5) && strncmp(fn, "s3+http://", 10) && strncmp(fn, "s3+https://", 11)) ? strcspn(fn, "?#") : strcspn(fn, "?"));
+        // Find the previous slash from there.
+        p = e;
+        while (p > fn && *p != '/') p--;
+        if (*p == '/') p++;
+
+        // Attempt to open local file first
+        kputsn(p, e-p, &s);
+        if (access(s.s, R_OK) == 0)
+        {
+            free(s.s);
+            *local_fn = p;
+            *local_len = e-p;
+            return 0;
+        }
+
+        // Attempt to open remote file. Stay quiet on failure, it is OK to fail when trying first .csi then .bai or .tbi index.
+        if ((remote_hfp = hopen(fn, "r")) == 0) {
+            hts_log_info("Failed to open index file '%s'", fn);
+            free(s.s);
+            return -1;
+        }
+        if (hts_detect_format2(remote_hfp, fn, &fmt)) {
+            hts_log_error("Failed to detect format of index file '%s'", fn);
+            goto fail;
+        }
+        if (fmt.category != index_file || (fmt.format != bai &&  fmt.format != csi && fmt.format != tbi
+                && fmt.format != crai && fmt.format != fai_format)) {
+            hts_log_error("Format of index file '%s' is not supported", fn);
+            goto fail;
+        }
+
+        if (download) {
+            if ((local_fp = hts_open_tmpfile(s.s, "wx", &tmps)) == NULL) {
+                hts_log_error("Failed to create file %s in the working directory", p);
+                goto fail;
+            }
+            hts_log_info("Downloading file %s to local directory", fn);
+            uint8_t *buf = (uint8_t*)calloc(buf_size, 1);
+            if (!buf) {
+                hts_log_error("%s", strerror(errno));
+                goto fail;
+            }
+            while ((l = hread(remote_hfp, buf, buf_size)) > 0) {
+                if (hwrite(local_fp, buf, l) != l) {
+                    hts_log_error("Failed to write data to %s : %s",
+                            fn, strerror(errno));
+                    free(buf);
+                    goto fail;
+                }
+            }
+            free(buf);
+            if (l < 0) {
+                hts_log_error("Error reading \"%s\"", fn);
+                goto fail;
+            }
+            if (hclose(local_fp) < 0) {
+                hts_log_error("Error closing %s : %s", fn, strerror(errno));
+                local_fp = NULL;
+                goto fail;
+            }
+            local_fp = NULL;
+            if (rename(tmps.s, s.s) < 0) {
+                hts_log_error("Error renaming %s : %s", tmps.s, strerror(errno));
+                goto fail;
+            }
+            ks_clear(&tmps);
+
+            *local_fn = p;
+            *local_len = e-p;
+        } else {
+            *local_fn = fn;
+            *local_len = e-fn;
+        }
+
+        if (hclose(remote_hfp) != 0) {
+            hts_log_error("Failed to close remote file %s", fn);
+        }
+
+        free(tmps.s);
+        free(s.s);
+        return 0;
+    } else {
+        hFILE *local_hfp;
+        if ((local_hfp = hopen(fn, "r")) == 0) return -1;
+        hclose_abruptly(local_hfp);
+        *local_fn = fn;
+        *local_len = strlen(fn);
+        return 0;
+    }
+
+ fail:
+    save_errno = errno;
+    if (remote_hfp) hclose_abruptly(remote_hfp);
+    if (local_fp) hclose_abruptly(local_fp);
+    if (tmps.l > 0) unlink(tmps.s);
+    free(tmps.s);
+    free(s.s);
+    errno = save_errno;
+    return -2;
+}
+
+/*
+ * Check the existence of a local index file using part of the alignment
+ * file name.
+ *
+ * For a filename fn of fn.fmt (eg fn.bam or fn.cram) the order of checks is
+ * fn.fmt.csi,  fn.csi,
+ * fn.fmt.bai,  fn.bai  - if fmt is HTS_FMT_BAI
+ * fn.fmt.tbi,  fn.tbi  - if fmt is HTS_FMT_TBI
+ * fn.fmt.crai, fn.crai - if fmt is HTS_FMT_CRAI
+ * fn.fmt.fai           - if fmt is HTS_FMT_FAI
+ *   also .gzi if fmt is ".gz"
+ *
+ * @param fn    - pointer to the file name
+ * @param fmt   - one of the HTS_FMT index formats
+ * @param fnidx - pointer to the index file name placeholder
+ * @return        1 for success, 0 for failure
+ */
+int hts_idx_check_local(const char *fn, int fmt, char **fnidx) {
+    int i, l_fn, l_ext;
+    const char *fn_tmp = NULL;
+    char *fnidx_tmp;
+    const char *csi_ext = ".csi";
+    const char *bai_ext = ".bai";
+    const char *tbi_ext = ".tbi";
+    const char *crai_ext = ".crai";
+    const char *fai_ext = ".fai";
+    const char *gzi_ext = ".gzi";
+
+    if (!fn)
+        return 0;
+
+    if (hisremote(fn)) {
+        for (i = strlen(fn) - 1; i >= 0; --i)
+            if (fn[i] == '/') {
+                fn_tmp = (char *)&fn[i+1];
+                break;
+            }
+    } else {
+        // Borrowed from hopen_fd_fileuri()
+        if (strncmp(fn, "file://localhost/", 17) == 0) fn_tmp = fn + 16;
+        else if (strncmp(fn, "file:///", 8) == 0) fn_tmp = fn + 7;
+        else fn_tmp = fn;
+#if defined(_WIN32) || defined(__MSYS__)
+        // For cases like C:/foo
+        if (fn_tmp[0] == '/' && fn_tmp[1] && fn_tmp[2] == ':' && fn_tmp[3] == '/')
+            fn_tmp++;
+#endif
+    }
+
+    if (!fn_tmp) return 0;
+    hts_log_info("Using alignment file '%s'", fn_tmp);
+    l_fn = strlen(fn_tmp); l_ext = 5;
+    fnidx_tmp = (char*)calloc(l_fn + l_ext + 1, 1);
+    if (!fnidx_tmp) return 0;
+
+    struct stat sbuf;
+
+    // Try alignment.bam.csi first
+    strcpy(fnidx_tmp, fn_tmp); strcpy(fnidx_tmp + l_fn, csi_ext);
+    if(stat(fnidx_tmp, &sbuf) == 0) {
+        *fnidx = fnidx_tmp;
+        return 1;
+    } else { // Then try alignment.csi
+        for (i = l_fn - 1; i > 0; --i)
+            if (fnidx_tmp[i] == '.') {
+                strcpy(fnidx_tmp + i, csi_ext);
+                if(stat(fnidx_tmp, &sbuf) == 0) {
+                    *fnidx = fnidx_tmp;
+                    return 1;
+                }
+                break;
+            }
+    }
+    if (fmt == HTS_FMT_BAI) {
+        // Next, try alignment.bam.bai
+        strcpy(fnidx_tmp, fn_tmp); strcpy(fnidx_tmp + l_fn, bai_ext);
+        if(stat(fnidx_tmp, &sbuf) == 0) {
+            *fnidx = fnidx_tmp;
+            return 1;
+        } else { // And finally, try alignment.bai
+            for (i = l_fn - 1; i > 0; --i)
+                if (fnidx_tmp[i] == '.') {
+                    strcpy(fnidx_tmp + i, bai_ext);
+                    if(stat(fnidx_tmp, &sbuf) == 0) {
+                        *fnidx = fnidx_tmp;
+                        return 1;
+                    }
+                    break;
+                }
+        }
+    } else if (fmt == HTS_FMT_TBI) { // Or .tbi
+        strcpy(fnidx_tmp, fn_tmp); strcpy(fnidx_tmp + l_fn, tbi_ext);
+        if(stat(fnidx_tmp, &sbuf) == 0) {
+            *fnidx = fnidx_tmp;
+            return 1;
+        } else {
+            for (i = l_fn - 1; i > 0; --i)
+                if (fnidx_tmp[i] == '.') {
+                    strcpy(fnidx_tmp + i, tbi_ext);
+                    if(stat(fnidx_tmp, &sbuf) == 0) {
+                        *fnidx = fnidx_tmp;
+                        return 1;
+                    }
+                    break;
+                }
+        }
+    } else if (fmt == HTS_FMT_CRAI) { // Or .crai
+        strcpy(fnidx_tmp, fn_tmp); strcpy(fnidx_tmp + l_fn, crai_ext);
+        if(stat(fnidx_tmp, &sbuf) == 0) {
+            *fnidx = fnidx_tmp;
+            return 1;
+        } else {
+            for (i = l_fn - 1; i > 0; --i)
+                if (fnidx_tmp[i] == '.') {
+                    strcpy(fnidx_tmp + i, crai_ext);
+                    if(stat(fnidx_tmp, &sbuf) == 0) {
+                        *fnidx = fnidx_tmp;
+                        return 1;
+                    }
+                    break;
+                }
+        }
+    } else if (fmt == HTS_FMT_FAI) { // Or .fai
+        // Check .gzi if we have a .gz file
+        strcpy(fnidx_tmp, fn_tmp);
+        int gzi_ok = 1;
+        if ((l_fn > 3 && strcmp(fn_tmp+l_fn-3, ".gz") == 0) ||
+            (l_fn > 5 && strcmp(fn_tmp+l_fn-5, ".bgzf") == 0)) {
+            strcpy(fnidx_tmp + l_fn, gzi_ext);
+            gzi_ok = stat(fnidx_tmp, &sbuf)==0;
+        }
+
+        // Now check for .fai.  Occurs second as we're returning this
+        // in *fnidx irrespective of whether we did gzi check.
+        strcpy(fnidx_tmp + l_fn, fai_ext);
+        *fnidx = fnidx_tmp;
+        if (stat(fnidx_tmp, &sbuf) == 0)
+            return gzi_ok;
+        else
+            return 0;
+    }
+
+    free(fnidx_tmp);
+    return 0;
+}
+
+static char *idx_filename(const char *fn, const char *ext, int download) {
+    int ret, local_len;
+    char *fnidx;
+    const char *local_fn = NULL;
+    kstring_t buffer = KS_INITIALIZE;
+
+    // First try : append `ext` to `fn`
+    if (!(fnidx = haddextension(&buffer, fn, 0, ext))) {
+        free(buffer.s);
+        return NULL;
+    }
+    if ((ret = idx_test_and_fetch(fnidx, &local_fn, &local_len, download)) == -1) {
+        // Second try : replace suffix of `fn` with `ext`
+        if (!(fnidx = haddextension(&buffer, fn, 1, ext))) {
+            free(buffer.s);
+            return NULL;
+        }
+        ret = idx_test_and_fetch(fnidx, &local_fn, &local_len, download);
+    }
+
+    if (ret < 0) {
+        free(buffer.s);
+        return NULL;
+    }
+
+    memmove(fnidx, local_fn, local_len);
+    fnidx[local_len] = 0;
+    return fnidx;
+}
+
+char *hts_idx_getfn(const char *fn, const char *ext)
+{
+    return idx_filename(fn, ext, HTS_IDX_SAVE_REMOTE);
+}
+
+char *hts_idx_locatefn(const char *fn, const char *ext)
+{
+    return idx_filename(fn, ext, 0);
+}
+
+static hts_idx_t *idx_find_and_load(const char *fn, int fmt, int flags)
+{
+    char *fnidx = strstr(fn, HTS_IDX_DELIM);
+    hts_idx_t *idx;
+
+    if ( fnidx ) {
+        char *fn2 = strdup(fn);
+        if (!fn2) {
+            hts_log_error("%s", strerror(errno));
+            return NULL;
+        }
+        fn2[fnidx - fn] = '\0';
+        fnidx += strlen(HTS_IDX_DELIM);
+        idx = hts_idx_load3(fn2, fnidx, fmt, flags);
+        free(fn2);
+        return idx;
+    }
+
+    if (hts_idx_check_local(fn, fmt, &fnidx) == 0 && hisremote(fn)) {
+        if (flags & HTS_IDX_SAVE_REMOTE) {
+            fnidx = idx_filename(fn, ".csi", HTS_IDX_SAVE_REMOTE);
+            if (!fnidx) {
+                switch (fmt) {
+                case HTS_FMT_BAI: fnidx = idx_filename(fn, ".bai", HTS_IDX_SAVE_REMOTE); break;
+                case HTS_FMT_TBI: fnidx = idx_filename(fn, ".tbi", HTS_IDX_SAVE_REMOTE); break;
+                default: break;
+                }
+            }
+        } else {
+            fnidx = idx_filename(fn, ".csi", 0);
+            if (!fnidx) {
+                switch (fmt) {
+                case HTS_FMT_BAI: fnidx = idx_filename(fn, ".bai", 0); break;
+                case HTS_FMT_TBI: fnidx = idx_filename(fn, ".tbi", 0); break;
+                default: break;
+                }
+            }
+        }
+    }
+    if (!fnidx) {
+        if (!(flags & HTS_IDX_SILENT_FAIL))
+            hts_log_error("Could not retrieve index file for '%s'", fn);
+        return 0;
+    }
+
+    if (flags & HTS_IDX_SAVE_REMOTE)
+        idx = hts_idx_load3(fn, fnidx, fmt, flags);
+    else
+        idx = idx_read(fnidx);
+    free(fnidx);
+    return idx;
+}
+
+hts_idx_t *hts_idx_load(const char *fn, int fmt) {
+    return idx_find_and_load(fn, fmt, 1);
+}
+
+hts_idx_t *hts_idx_load2(const char *fn, const char *fnidx)
+{
+    return hts_idx_load3(fn, fnidx, 0, 0);
+}
+
+hts_idx_t *hts_idx_load3(const char *fn, const char *fnidx, int fmt, int flags)
+{
+    const char *local_fn = NULL;
+    char *local_fnidx = NULL;
+    int local_len;
+    if (!fnidx)
+        return idx_find_and_load(fn, fmt, flags);
+
+    // Check that the index file is up to date, the main file might have changed
+    struct stat stat_idx,stat_main;
+    int remote_fn = hisremote(fn), remote_fnidx = hisremote(fnidx);
+    if ( !remote_fn && !remote_fnidx
+         && !stat(fn, &stat_main) && !stat(fnidx, &stat_idx) )
+    {
+        if ( stat_idx.st_mtime < stat_main.st_mtime )
+            hts_log_warning("The index file is older than the data file: %s", fnidx);
+    }
+
+    if (remote_fnidx && (flags & HTS_IDX_SAVE_REMOTE))
+    {
+        int ret = idx_test_and_fetch(fnidx, &local_fn, &local_len, 1);
+        if (ret == 0) {
+            local_fnidx = strdup(local_fn);
+            if (local_fnidx) {
+                local_fnidx[local_len] = '\0';
+                fnidx = local_fnidx;
+            }
+        }
+    }
+
+    hts_idx_t *idx = idx_read(fnidx);
+    if (!idx && !(flags & HTS_IDX_SILENT_FAIL))
+        hts_log_error("Could not load local index file '%s'%s%s", fnidx,
+                      errno ? " : " : "", errno ? strerror(errno) : "");
+
+
+    free(local_fnidx);
+
+    return idx;
+}
+
+
+
+/**********************
+ ***     Memory     ***
+ **********************/
+
+/* For use with hts_expand macros *only* */
+HTSLIB_EXPORT
+size_t hts_realloc_or_die(size_t n, size_t m, size_t m_sz, size_t size,
+                          int clear, void **ptr, const char *func) {
+    /* If new_m and size are both below this limit, multiplying them
+       together can't overflow */
+    const size_t safe = (size_t) 1 << (sizeof(size_t) * 4);
+    void *new_ptr;
+    size_t bytes, new_m;
+
+    new_m = n;
+    kroundup_size_t(new_m);
+
+    bytes = size * new_m;
+
+    /* Check for overflow.  Both ensure that new_m will fit in m (we make the
+       pessimistic assumption that m is signed), and that bytes has not
+       wrapped around. */
+    if (new_m > (((size_t) 1 << (m_sz * 8 - 1)) - 1)
+        || ((size > safe || new_m > safe)
+            && bytes / new_m != size)) {
+        errno = ENOMEM;
+        goto die;
+    }
+
+    new_ptr = realloc(*ptr, bytes);
+    if (new_ptr == NULL) goto die;
+
+    if (clear) {
+        if (new_m > m) {
+            memset((char *) new_ptr + m * size, 0, (new_m - m) * size);
+        }
+    }
+
+    *ptr = new_ptr;
+
+    return new_m;
+
+ die:
+    hts_log_error("%s", strerror(errno));
+    exit(1);
+}
+
+/*
+ * Companion to hts_resize() macro that does the actual allocation.
+ *
+ * Somewhat complicated as hts_resize() needs to write the new allocated
+ * size back into *size_in_out, and the value pointed to may either be
+ * int32_t, uint32_t or size_t depending on which array is being resized.
+ * This is solved by making `size_in_out` a void pointer, getting the macro
+ * to pass in the size of the item pointed to (in `size_sz`) and then using
+ * an appropriate cast (based on the value of size_sz).  The function
+ * ensures that the maximum size will be storable in a signed type of
+ * the given size so storing to an int32_t should work correctly.
+ *
+ * Assumes that sizeof(uint32_t) and sizeof(int32_t) is 4,
+ * sizeof(uint64_t) and sizeof(int64_t) is 8 and sizeof(size_t) is
+ * either 4 or 8.  It also assumes casting from unsigned to signed will
+ * work as long as the top bit isn't set.
+ */
+
+int hts_resize_array_(size_t item_size, size_t num, size_t size_sz,
+                      void *size_in_out, void **ptr_in_out, int flags,
+                      const char *func) {
+    /* If new_size and item_size are both below this limit, multiplying them
+       together can't overflow */
+    const size_t safe = (size_t) 1 << (sizeof(size_t) * 4);
+    void *new_ptr;
+    size_t bytes, new_size;
+
+    new_size = num;
+    kroundup_size_t(new_size);
+    bytes = item_size * new_size;
+
+    /* Check for overflow.  Both ensure that alloc will fit in alloc_in_out (we
+       make the pessimistic assumption that *alloc_in_out is signed), and that
+       bytes has not wrapped around. */
+
+    if ((new_size > (((size_t) 1 << (size_sz * 8 - 1)) - 1))
+        || (((item_size > safe) || (new_size > safe))
+            && bytes / new_size != item_size)) {
+        hts_log(HTS_LOG_ERROR, func, "Memory allocation too large");
+        errno = ENOMEM;
+        return -1;
+    }
+
+    new_ptr = realloc(*ptr_in_out, bytes);
+    if (new_ptr == NULL) {
+        int save_errno = errno;
+        hts_log(HTS_LOG_ERROR, func, "%s", strerror(errno));
+        errno = save_errno;
+        return -1;
+    }
+
+    if (flags & HTS_RESIZE_CLEAR) {
+        size_t old_size;
+        switch (size_sz) {
+        case 4: old_size = *((uint32_t *) size_in_out); break;
+        case 8: old_size = *((uint64_t *) size_in_out); break;
+        default: abort();
+        }
+        if (new_size > old_size) {
+            memset((char *) new_ptr + old_size * item_size, 0,
+                   (new_size - old_size) * item_size);
+        }
+    }
+
+    switch (size_sz) {
+    case 4: *((uint32_t *) size_in_out) = new_size; break;
+    case 8: *((uint64_t *) size_in_out) = new_size; break;
+    default: abort();
+    }
+
+    *ptr_in_out = new_ptr;
+    return 0;
+}
+
+void hts_lib_shutdown(void)
+{
+    hfile_shutdown(1);
+}
+
+void hts_free(void *ptr) {
+    free(ptr);
+}
+
+void hts_set_log_level(enum htsLogLevel level)
+{
+    hts_verbose = level;
+}
+
+enum htsLogLevel hts_get_log_level(void)
+{
+    return hts_verbose;
+}
+
+static char get_severity_tag(enum htsLogLevel severity)
+{
+    switch (severity) {
+    case HTS_LOG_ERROR:
+        return 'E';
+    case HTS_LOG_WARNING:
+        return 'W';
+    case HTS_LOG_INFO:
+        return 'I';
+    case HTS_LOG_DEBUG:
+        return 'D';
+    case HTS_LOG_TRACE:
+        return 'T';
+    default:
+        break;
+    }
+
+    return '*';
+}
+
+void hts_log(enum htsLogLevel severity, const char *context, const char *format, ...)
+{
+    int save_errno = errno;
+    if (severity <= hts_verbose) {
+        va_list argptr;
+
+        fprintf(stderr, "[%c::%s] ", get_severity_tag(severity), context);
+
+        va_start(argptr, format);
+        vfprintf(stderr, format, argptr);
+        va_end(argptr);
+
+        fprintf(stderr, "\n");
+    }
+    errno = save_errno;
+}
diff --git a/shared/package-files/b6/b6a03eea1474ecb6ac7cfcd891e77c46c3a1e9f80a8128636699a11e9bf53b61/_nested_tensor_from_mask_native.h b/shared/package-files/b6/b6a03eea1474ecb6ac7cfcd891e77c46c3a1e9f80a8128636699a11e9bf53b61/_nested_tensor_from_mask_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..886edb0166a9b6b6c79ed27da1069be53ff416ad
--- /dev/null
+++ b/shared/package-files/b6/b6a03eea1474ecb6ac7cfcd891e77c46c3a1e9f80a8128636699a11e9bf53b61/_nested_tensor_from_mask_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & _nested_tensor_from_mask_out(const at::Tensor & t, const at::Tensor & mask, bool mask_check, at::Tensor & out);
+TORCH_API at::Tensor NestedTensor_nested_tensor_from_mask(const at::Tensor & t, const at::Tensor & mask, bool mask_check=true);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b6/b6ae2bb06402517284f96a92249902ecb0c3ba5038177027c5076b86bd01ede7/arctan2.h b/shared/package-files/b6/b6ae2bb06402517284f96a92249902ecb0c3ba5038177027c5076b86bd01ede7/arctan2.h
new file mode 100644
index 0000000000000000000000000000000000000000..d6308acb4246fc3219099d70388744b809bf8ba3
--- /dev/null
+++ b/shared/package-files/b6/b6ae2bb06402517284f96a92249902ecb0c3ba5038177027c5076b86bd01ede7/arctan2.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::arctan2(Tensor self, Tensor other) -> Tensor
+inline at::Tensor arctan2(const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::arctan2::call(self, other);
+}
+
+// aten::arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & arctan2_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::arctan2_out::call(self, other, out);
+}
+// aten::arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & arctan2_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) {
+    return at::_ops::arctan2_out::call(self, other, out);
+}
+
+}
diff --git a/shared/package-files/b6/b6b467f1557f213297ba56705662c08949783283a8210fe7b1000ea44f28c32a/special_ndtr_ops.h b/shared/package-files/b6/b6b467f1557f213297ba56705662c08949783283a8210fe7b1000ea44f28c32a/special_ndtr_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..d9ca5deec458b88a2cce1659bd5517ca2638333d
--- /dev/null
+++ b/shared/package-files/b6/b6b467f1557f213297ba56705662c08949783283a8210fe7b1000ea44f28c32a/special_ndtr_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API special_ndtr {
+  using schema = at::Tensor (const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_ndtr";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "special_ndtr(Tensor self) -> Tensor";
+  static at::Tensor call(const at::Tensor & self);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
+};
+
+struct TORCH_API special_ndtr_out {
+  using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_ndtr";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "special_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b6/b6b4a61b3c5769ca2169e183ecec107536d51001236b1c664e16cbdfd7f4a492/_linalg_det_native.h b/shared/package-files/b6/b6b4a61b3c5769ca2169e183ecec107536d51001236b1c664e16cbdfd7f4a492/_linalg_det_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..b7f493220d205fa8e9fe3766d15505f38d938ce5
--- /dev/null
+++ b/shared/package-files/b6/b6b4a61b3c5769ca2169e183ecec107536d51001236b1c664e16cbdfd7f4a492/_linalg_det_native.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured__linalg_det_out : public at::meta::structured__linalg_det {
+void impl(const at::Tensor & A, const at::Tensor & result, const at::Tensor & LU, const at::Tensor & pivots);
+};
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b6/b6b76d82e1263ed17377e1c991d5c2e783155549f2dd90b063385443a8d09436/test_pyshell.cpython-311.pyc b/shared/package-files/b6/b6b76d82e1263ed17377e1c991d5c2e783155549f2dd90b063385443a8d09436/test_pyshell.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89487becdd187b4d03e6a08313a2a60dd9ef36a2
Binary files /dev/null and b/shared/package-files/b6/b6b76d82e1263ed17377e1c991d5c2e783155549f2dd90b063385443a8d09436/test_pyshell.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b6c6cab16fc9c2320361c47a93299311e4d1e5583790468a2d016bbc51263ee6/NamedTensor.h b/shared/package-files/b6/b6c6cab16fc9c2320361c47a93299311e4d1e5583790468a2d016bbc51263ee6/NamedTensor.h
new file mode 100644
index 0000000000000000000000000000000000000000..81998e160185aba0561404e637ff20a2d18d4869
--- /dev/null
+++ b/shared/package-files/b6/b6c6cab16fc9c2320361c47a93299311e4d1e5583790468a2d016bbc51263ee6/NamedTensor.h
@@ -0,0 +1,143 @@
+#pragma once
+
+#include 
+#include 
+
+namespace at {
+
+class TensorBase;
+
+// XXX: This file exists because TensorImpl is in c10, but Dimname is in ATen.
+// Due to the c10/ATen library split, TensorImpl cannot depend on Dimname,
+// so we have a couple of workarounds.
+//
+// In the long term, we'll move Dimname to c10 and everything in this file
+// can be refactored out. The main blocker for that is that "c10::Symbol"
+// actually exists outside of c10 and needs to be moved in.
+
+// TensorImpl has a unique_ptr field.
+// XXX: Ideally we would just put std::optional> into TensorImpl.
+//
+// This class has an important invariant: there must be at least ONE
+// non-wildcard
+struct TORCH_API NamedTensorMeta final : public c10::NamedTensorMetaInterface {
+  // This enum is to remind people that the invariant on constructors is that
+  // the list of dimnames must have at least one non-wildcard
+  enum HAS_NON_WILDCARD {
+    HasNonWildcard
+  };
+
+  explicit NamedTensorMeta(HAS_NON_WILDCARD, DimnameList names)
+    : names_(names.vec()) {
+    check_invariants();
+  }
+  explicit NamedTensorMeta(HAS_NON_WILDCARD, std::vector&& names)
+    : names_(std::move(names)) {
+    check_invariants();
+  }
+
+  std::unique_ptr clone() const override {
+    return std::make_unique(HasNonWildcard, names_);
+  }
+
+  DimnameList names() const { return names_; }
+
+  // Used for an assertion in TensorImpl.h
+  int64_t slow_dim() const override {
+    return static_cast(names_.size());
+  }
+
+  void check_invariants() const {
+    TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
+      std::any_of(names_.begin(), names_.end(), [](const Dimname& n) { return !n.isWildcard(); }));
+  }
+
+  void set_names(HAS_NON_WILDCARD, DimnameList new_names) {
+    TORCH_INTERNAL_ASSERT(new_names.size() == names_.size());
+    std::copy(new_names.begin(), new_names.end(), names_.begin());
+    check_invariants();
+  }
+
+  void set_names(HAS_NON_WILDCARD, std::vector&& new_names) {
+    TORCH_INTERNAL_ASSERT(new_names.size() == names_.size());
+    names_ = std::move(new_names);
+    check_invariants();
+  }
+
+  // INVARIANT: at least one Dimname is non-WILDCARD
+  std::vector names_;
+};
+
+// When NamesMode is disabled, then all operations ignore tensors' names fields.
+// Concretely speaking, all tensors are treated as having nullopt names.
+struct TORCH_API NamesMode {
+  static bool is_enabled();
+  static void set_enabled(bool enabled);
+};
+
+
+// A RAII, thread local (!) guard that enables or disables names upon
+// construction, and sets it back to the original value upon destruction.
+struct TORCH_API NoNamesGuard {
+  NoNamesGuard() : prev_mode(NamesMode::is_enabled()) {
+    NamesMode::set_enabled(false);
+  }
+  NoNamesGuard(const NoNamesGuard&) = delete;
+  NoNamesGuard(NoNamesGuard&&) = delete;
+  NoNamesGuard& operator=(const NoNamesGuard&) = delete;
+  NoNamesGuard& operator=(NoNamesGuard&&) = delete;
+  ~NoNamesGuard() {
+    if (initialized) {
+      reset();
+    }
+  }
+  void reset() {
+    TORCH_INTERNAL_ASSERT(initialized);
+    NamesMode::set_enabled(prev_mode);
+  }
+ private:
+  bool prev_mode;
+  bool initialized{true};
+};
+
+void check_names_valid_for(const TensorBase& tensor, DimnameList names);
+void check_names_valid_for(size_t tensor_dim, DimnameList names);
+
+// Sets the names of `tensor` to be `names`.
+TORCH_API const TensorBase& internal_set_names_inplace(const TensorBase& tensor, std::optional names);
+TORCH_API const TensorBase& internal_set_names_inplace(const TensorBase& tensor, std::vector&& names, bool validate_names);
+
+constexpr size_t kMaxNamedTensorDim = 64;
+
+DimnameList default_names(size_t len);
+
+namespace impl {
+
+// Some helper functions on TensorImpl. Useful for working with names in TH.
+// XXX: Ideally these would exist as methods on TensorImpl
+TORCH_API void internal_set_names_inplace(TensorImpl* impl, std::optional names, bool validate_names);
+TORCH_API void internal_set_names_inplace(TensorImpl* impl, std::vector&& names, bool validate_names);
+
+void check_names_valid_for(TensorImpl* impl, DimnameList names);
+
+// Returns true if the tensor's names exist and are not all 'None'.
+// Returns false if the tensor's names don't exist (were not allocated),
+// or if all names are 'None'.
+// We treat not-allocated-names the same as allocated names that are all 'None'.
+TORCH_API bool has_names(const TensorImpl* impl);
+
+// Returns the names of the tensor's dimensions.
+// Unnamed tensors are treated as having 'None' in all dimension; this method
+// would return a DimnameList of all 'None's for an unnamed tensor.
+TORCH_API DimnameList get_names(const TensorImpl* impl);
+
+// This is more of an implementation detail; one should use impl::get_names /
+// Tensor::names() whenever possible because it provides a cleaner API.
+// Returns the names of the tensor if they have been allocated; returns nullopt
+// instead if the haven't been. The names of a tensor are not allocated if a
+// tensor is constructed with names=None.
+TORCH_API std::optional get_opt_names(const TensorImpl* impl);
+
+} // namespace impl
+
+} // namespace at
diff --git a/shared/package-files/b6/b6c7a5eb166fbee843cc7c010dec0fb6f27486e0f62ed8f92ab3dce5ab8f2135/test_calltip.cpython-311.pyc b/shared/package-files/b6/b6c7a5eb166fbee843cc7c010dec0fb6f27486e0f62ed8f92ab3dce5ab8f2135/test_calltip.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0897e1358fe06dc80a7879f019cb338ccdc4c5ab
Binary files /dev/null and b/shared/package-files/b6/b6c7a5eb166fbee843cc7c010dec0fb6f27486e0f62ed8f92ab3dce5ab8f2135/test_calltip.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b6d357ca88619928f094eb03603fdf41615c8252a7c0040438159110429d75bb/ops_handler.py b/shared/package-files/b6/b6d357ca88619928f094eb03603fdf41615c8252a7c0040438159110429d75bb/ops_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..692857f260974d16b130435dcd83a0c14115940a
--- /dev/null
+++ b/shared/package-files/b6/b6d357ca88619928f094eb03603fdf41615c8252a7c0040438159110429d75bb/ops_handler.py
@@ -0,0 +1,1181 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import inspect
+import itertools
+import re
+import warnings
+from io import StringIO
+from typing import Any, Callable, Generic, Literal, NamedTuple, Optional, TypeVar, Union
+from unittest.mock import patch
+
+import sympy
+
+import torch
+import torch.utils._pytree as pytree
+
+from ..utils._ordered_set import OrderedSet
+from .utils import IndentedBuffer, reduction_num_outputs, sympy_index_symbol, sympy_str
+
+
+T = TypeVar("T")
+StoreMode = Optional[Literal["atomic_add"]]
+ReductionType = Literal[
+    "argmax",
+    "argmin",
+    "welford_reduce",
+    "welford_combine",
+    "any",
+    "max",
+    "min",
+    "prod",
+    "sum",
+    "xor_sum",
+]
+
+
+def _arg_str(a: object) -> str:
+    if isinstance(a, sympy.Expr):
+        return sympy_str(a)
+    return str(a)
+
+
+# See OpDecompositions for superclass that desugars operations like reciprocal/square.
+class OpsHandler(Generic[T]):
+    """
+    Protocol describing the set of valid operations on ``torch._inductor.virtualized.ops``,
+    as well as the contract for op handlers.  The type T signifies the domain
+    of the abstract analysis AKA what all the functions return / take as arguments
+    anywhere compute occurs.
+
+    While these operators are typically dtype polymorphic (e.g., you can use mul
+    on both integers and floats), they do NOT do promotion and usually return the
+    same dtype as the input.  You are expected to have handled type promotion
+    during ATen decompositions.  Most operators correspond exactly to pointwise
+    operations as defined by torch, so when in doubt about semantics, check the
+    corresponding torch documentation.  These are all scalar operations (so they
+    are defined to operate on a single element at a time.)
+
+    For convenience, many operators take a src_dtype which indicates what the dtype
+    of the input argument is.  Although in principle this can be derived by an
+    analysis, providing this for ops where it is useful helps avoid having to repeatedly
+    recompute dtype in code generation.
+
+    Note that this often describes a class of static methods, for stateless
+    ops handlers.
+
+    Handlers are often defined using metaprogramming (e.g. _initialize_pointwise_overrides),
+    which means you will not get type errors for those methods.  We have tests in
+    test/inductor/test_op_completeness.py which check that all operators are implemented after
+    all the metaprogramming has run.
+    """
+
+    def constant(self, value: Union[bool, float, int], dtype: torch.dtype) -> T:
+        """Produces a scalar constant of type dtype."""
+        raise NotImplementedError
+
+    def load_seed(self, name: str, offset: T) -> T:
+        """Computes inductor_prims.lookup_seed."""
+        raise NotImplementedError
+
+    def rand(self, seed: T, offset: T) -> T:
+        """Computes inductor_prims.random with mode="rand".  offset has dtype int32."""
+        raise NotImplementedError
+
+    def randn(self, seed: T, offset: T) -> T:
+        """Computes inductor_prims.random with mode="randn".  offset has dtype int32."""
+        raise NotImplementedError
+
+    def randint64(self, seed: T, offset: T, low: T, high: T) -> T:
+        """Computes inductor_prims.randint.  offset has dtype int32."""
+        raise NotImplementedError
+
+    def masked(self, mask: T, body: Callable[[], T], other: T) -> T:
+        """
+        Computes body, but only perform loads/stores if the boolean mask
+        evaluates to true.  For example, you would use this if you needed to
+        perform an indirect load that may not be valid on some elements;
+        without masking, invalid accesses can cause IMAs.  When mask is true,
+        the result is the result of body; otherwise it is other. Here, `other`
+        needs to be a constant.
+
+        Contrast this with ops.where, which can multiplex between two values
+        that have been unconditionally computed.
+        """
+        raise NotImplementedError
+
+    def where(self, condition: T, input: T, other: T) -> T:
+        """
+        Computes torch.where: when condition is true, return input; otherwise return other.
+        """
+        raise NotImplementedError
+
+    def index_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> T:
+        """
+        Converts a sympy expression into a scalar of type dtype.  expr is typically
+        an indexing expression, thus the name; however, it can also be used in
+        non-indexing situations.
+        """
+        raise NotImplementedError
+
+    def to_dtype(
+        self,
+        x: T,
+        dtype: torch.dtype,
+        src_dtype: Optional[torch.dtype] = None,
+        use_compute_types: bool = True,
+    ) -> T:
+        """
+        Convert x to dtype.  src_dtype can be optionally set to specify what the original
+        dtype of x was, which can improve code generation (used by torch to(dtype=dtype)).
+        """
+        raise NotImplementedError
+
+    def trunc_to_int(self, x: T, dtype: torch.dtype) -> T:
+        """
+        Convert x to dtype with truncation semantics (similar to how the int
+        constructor works in Python).  In Inductor codegen, this just decays
+        to trunc and then to_dtype, but this composite operation helps
+        roundtrips for Sympy evaluation.
+
+        dtype is taken as an explicit parameter because the desired output
+        dtype is typically the index dtype, which may vary between int32 and
+        int64 depending on if we've shown that all the indexing operations can
+        be done in int32.
+        """
+        raise NotImplementedError
+
+    def ceil_to_int(self, x: T, dtype: torch.dtype) -> T:
+        """
+        Convert x to dtype with ceiling semantics.  See also trunc_to_int.
+        """
+        raise NotImplementedError
+
+    def floor_to_int(self, x: T, dtype: torch.dtype) -> T:
+        """
+        Convert x to dtype with ceiling semantics.  See also trunc_to_int.
+        """
+        raise NotImplementedError
+
+    def round_to_int(self, x: T, dtype: torch.dtype) -> T:
+        """
+        Convert x to dtype with round-to-even semantics.  See also trunc_to_int.
+        """
+        raise NotImplementedError
+
+    def to_dtype_bitcast(self, x: T, dtype: torch.dtype, src_dtype: torch.dtype) -> T:
+        """
+        Reinterpret cast x to dtype (reinterpreting the bits in memory as another dtype.)
+        src_dtype must be the original type of x.
+        """
+        raise NotImplementedError
+
+    def identity(self, x: T) -> T:
+        """
+        Returns x as is.  This is used to trigger CSE.
+        """
+        raise NotImplementedError
+
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # These operations are only available in a "kernel" context.  Check
+    # torch._inductor.codegen.common.CSEProxy for their typical implementation
+    # in op handler (routing to their respective implementations in the kernel
+    # handler)
+    #
+    # Importantly, inside a kernel, indexing and mask variables are available
+    # in scope, which are typically used by sympy.Expr indexing.
+
+    def indirect_indexing(
+        self, x: T, size: sympy.Expr, check: bool = True, wrap_neg=True
+    ) -> sympy.Expr:
+        """
+        Convert an integral x into a sympy.Expr that can be subsequently used in
+        indexing computation.  'size' represents an upper bound on what valid
+        indexes can be; when 'check' is True, we check that the x is in bounds.
+
+        NB: This is typically mandatory to implement for any analysis, because you
+        MUST return a valid sympy.Expr of some sort (even if it's a meaningless symbol).
+        """
+        raise NotImplementedError
+
+    def load(self, name: str, index: sympy.Expr) -> T:
+        """
+        Load from the memory location 'name', offset by some indexing expression 'index'.
+        """
+        raise NotImplementedError
+
+    def store(
+        self,
+        name: str,
+        index: sympy.Expr,
+        value: T,
+        mode: StoreMode = None,
+    ) -> None:
+        """
+        Store 'value' to the memory location 'name' offset by 'expr'.  If
+        specified, 'mode' can require the store to be an atomic addition.
+        """
+        raise NotImplementedError
+
+    # TODO: Better explain how the "collective" semantics of these ops;
+    # remember that the input value is a scalar, you can't reduce on it in the
+    # traditional sense!
+    def reduction(
+        self,
+        dtype: torch.dtype,
+        src_dtype: torch.dtype,
+        reduction_type: ReductionType,
+        value: T,
+    ) -> Union[T, tuple[T, ...]]:
+        """
+        Perform a 'reduction_type' reduction on 'value' of dtype 'src_dtype',
+        using 'dtype' as the accumulation dtype for the reduction.  The result
+        is an intermediate computation which should be stored to the final
+        location using 'ops.store_reduction'.
+
+        Valid reduction types are .  For Welford reduction types, this
+        function returns multiple outputs; consult reduction_num_outputs to
+        determine the amount in metaprogramming applications.
+        """
+        raise NotImplementedError
+
+    # TODO: in practice, this seems to actually return None, but not returning
+    # a T makes common __getattr__ idioms not type correctly.  Figure out if
+    # this should be returning something.
+    def store_reduction(self, name: str, index: sympy.Expr, value: T) -> None:
+        """
+        Store the fully accumulated result of 'reduction' to the memory
+        location 'name' offset by 'expr'.
+        """
+        raise NotImplementedError
+
+    def scan(
+        self,
+        dtypes: tuple[torch.dtype, ...],
+        combine_fn: Callable[[tuple[T, ...], tuple[T, ...]], tuple[T, ...]],
+        values: tuple[T, ...],
+    ) -> tuple[T, ...]:
+        """
+        Perform an associative scan on 'value'.
+        """
+        # TODO: Improve the description with some pseudocode
+        raise NotImplementedError
+
+    def sort(
+        self,
+        dtypes: tuple[torch.dtype, ...],
+        values: tuple[T, ...],
+        stable: bool,
+        descending: bool,
+    ) -> tuple[T, ...]:
+        """
+        Sort values along the reduction dimension.
+        """
+        raise NotImplementedError
+
+    def bucketize(
+        self,
+        values: T,
+        boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr],
+        boundary_indices: T,
+        indexing_dtype: torch.dtype,
+        right: bool,
+        sorter: Optional[tuple[str, sympy.Expr]] = None,
+        sorter_indices: Optional[T] = None,
+    ) -> T:
+        # See [Note: Inductor bucketize op]
+        raise NotImplementedError
+
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # The following ops have semantics that correspond exactly to the torch
+    # operation with the same corresponding name.
+
+    def abs(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def exp(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def exp2(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def expm1(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def sqrt(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def relu(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def minimum(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def maximum(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def cos(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def sin(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def lgamma(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def erf(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def cosh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def sinh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def acos(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def acosh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def asin(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def asinh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def atan2(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def atan(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def atanh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def copysign(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def erfc(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def erfinv(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def frexp(self, x0: T):
+        raise NotImplementedError
+
+    def hypot(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def log10(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def log2(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def nextafter(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def logical_and(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def logical_not(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def logical_or(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def logical_xor(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_and(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_not(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_or(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_xor(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_left_shift(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def bitwise_right_shift(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def rsqrt(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def log1p(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def tan(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def tanh(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def sigmoid(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def signbit(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def fmod(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def log(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def isinf(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def isnan(self, x0: T) -> T:
+        raise NotImplementedError
+
+    # NB: this returns a float, like the torch operation
+    # This rounds half to even to break ties
+    def round(self, x0: T) -> T:
+        raise NotImplementedError
+
+    # NB: this returns a float, like the torch operation
+    def floor(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def sign(self, x0: T) -> T:
+        raise NotImplementedError
+
+    # NB: this returns a float, like the torch operation
+    def trunc(self, x0: T) -> T:
+        raise NotImplementedError
+
+    # NB: this returns a float, like the torch operation
+    def ceil(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def neg(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def reciprocal(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def eq(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def ne(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def lt(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def gt(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def le(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def ge(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def add(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def sub(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def mul(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    # NB: this returns a float, like the torch operation
+    def pow(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def and_(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def or_(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def xor(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    # These are metaprogrammed by MockHandler._init_cls
+    def lshift(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    def rshift(self, x0: T, x1: T) -> T:
+        raise NotImplementedError
+
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # These are "special" operators.  These only exist if the target
+    # language actually supports the operator.  Keep this in sync with
+    # pointwise_overrides_data.
+
+    def airy_ai(self, x: T) -> T:
+        raise NotImplementedError
+
+    def bessel_j0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def bessel_j1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def bessel_y0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def bessel_y1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def digamma(self, x: T) -> T:
+        raise NotImplementedError
+
+    def erfcx(self, x: T) -> T:
+        raise NotImplementedError
+
+    def fma(self, x: T, y: T, z: T) -> T:
+        raise NotImplementedError
+
+    def igamma(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def igammac(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def gammainc(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def gammaincc(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def i0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def i0e(self, x: T) -> T:
+        raise NotImplementedError
+
+    def i1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def i1e(self, x: T) -> T:
+        raise NotImplementedError
+
+    def log_ndtr(self, x: T) -> T:
+        raise NotImplementedError
+
+    def modified_bessel_i0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def modified_bessel_i1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def modified_bessel_k0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def modified_bessel_k1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def ndtr(self, x: T) -> T:
+        raise NotImplementedError
+
+    def ndtri(self, x: T) -> T:
+        raise NotImplementedError
+
+    def polygamma(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def scaled_modified_bessel_k0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def scaled_modified_bessel_k1(self, x: T) -> T:
+        raise NotImplementedError
+
+    def spherical_bessel_j0(self, x: T) -> T:
+        raise NotImplementedError
+
+    def zeta(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def chebyshev_polynomial_t(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def chebyshev_polynomial_u(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def chebyshev_polynomial_v(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def chebyshev_polynomial_w(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def legendre_polynomial_p(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def shifted_chebyshev_polynomial_t(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def shifted_chebyshev_polynomial_u(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def shifted_chebyshev_polynomial_v(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def shifted_chebyshev_polynomial_w(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def hermite_polynomial_h(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def hermite_polynomial_he(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    def laguerre_polynomial_l(self, x: T, y: T) -> T:
+        raise NotImplementedError
+
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # These operators are a bit special, because they are conventionally
+    # natively supported in both Python and C, but the semantics differ so
+    # care must be taken
+
+    def truncdiv(self, x0: T, x1: T) -> T:
+        """C-style trunc division between integers only.  Computes the true
+        division of two numbers and rounds the result to zero.
+        """
+        raise NotImplementedError
+
+    def floordiv(self, x0: T, x1: T) -> T:
+        """Python-style floor division between integers only.  Computes the
+        true division of two numbers and floors the result.  If you want
+        floor division for floats, do regular truediv and floor the result.
+        """
+        raise NotImplementedError
+
+    def truediv(self, x0: T, x1: T) -> T:
+        """True division between floats.  Integer inputs are NOT valid.  To
+        do Python-style (int, int) -> float division, use int_truediv"""
+        raise NotImplementedError
+
+    def int_truediv(self, x0: T, x1: T) -> T:
+        """True division between integers.  This is NOT the same as promoting
+        to float and doing integer division, there is a bespoke algorithm for
+        doing the division in higher precision than the above.
+        """
+        raise NotImplementedError
+
+    def mod(self, x0: T, x1: T) -> T:
+        """C-style modulus, take sign from LHS (x0)."""
+        raise NotImplementedError
+
+    def remainder(self, x0: T, x1: T) -> T:
+        """Python-style modulus, take sign from RHS (x1)."""
+        raise NotImplementedError
+
+    def square(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def check_bounds(
+        self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
+    ) -> None:
+        raise NotImplementedError
+
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # In CUDA, optimized implementations of other mathematical operations are
+    # offered separately via libdevice for double precision computation (in
+    # Triton, these go to tl.math rather than tl).  We lower to these
+    # operators when doing FP64 on CUDA.  Note that some operators
+    # unconditional go to tl.math.
+    #
+    # TODO(ezyang): Is this really the best way to do this?  What if we have
+    # abs internally route to tl.math automatically when given a double
+    # precision input?  One reason is that when doing codegen, we often don't
+    # know what the dtype of the inputs are!  (In principle we do know, but
+    # for many analyses it's not conveniently available.)
+
+    def libdevice_abs(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_exp(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_sqrt(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_cos(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_sin(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_sigmoid(self, x0: T) -> T:
+        raise NotImplementedError
+
+    def libdevice_log(self, x0: T) -> T:
+        raise NotImplementedError
+
+    # halide-only
+    def halide_clamp(self, value: T, size: sympy.Expr, check: bool) -> T:
+        raise NotImplementedError
+
+    # triton-only
+    def inline_asm_elementwise(
+        self,
+        *inputs: T,
+        asm: str,
+        constraints: Optional[str] = None,
+        dtype: torch.dtype = torch.float32,
+        is_pure: bool = True,
+        pack: int = 1,
+    ) -> T:
+        raise NotImplementedError
+
+    def output(self, *args: T) -> None:
+        """This is a fake op used in analysis but not codegen"""
+        raise NotImplementedError
+
+    def placeholder(self, index: int) -> T:
+        """This is a fake op used in analysis but not codegen"""
+        raise NotImplementedError
+
+
+_ignore_op_re = re.compile(r"_.*|paren").fullmatch
+
+
+def list_ops(cls: type[Any]):
+    return OrderedSet([x for x in dir(cls) if not _ignore_op_re(x)])
+
+
+OP_NAMES = list_ops(OpsHandler)
+
+
+class DefaultHandler(OpsHandler[Any]):
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        """
+        Default implementation for all ops.  Override in a subclass to
+        provide generic op behavior.
+
+        Args:
+            name: name of the op, see OpHandler.{name}
+            args: positional args passed to the op
+            kwargs: keyword args passed to the op
+
+        Returns:
+            return value of the op
+
+        """
+        raise NotImplementedError
+
+    def __getattr__(self, name: str) -> Any:
+        def fallback(*args: Any, **kwargs: Any) -> Any:
+            return self._default(name, args, kwargs)
+
+        # would like to remove this function entirely, but it's used in MTIA backend
+        warnings.warn(f"undefined OpHandler.{name}, please add missing op schema")
+        return fallback
+
+    @staticmethod
+    def _call_default(target: str):
+        def call_default(self, *args, **kwargs):
+            return self._default(target, args, kwargs)
+
+        call_default.__name__ = target
+        return call_default
+
+    @classmethod
+    def _init_cls(cls):
+        """
+        Here we codegen many functions of the form:
+
+            def add(self, a, b):
+                return self._default('add', (a, b), {})
+
+        and install them in cls.  This is the same as _call_default above,
+        but is about 1.2x faster since CPython varargs parsing is slow.
+        """
+        code = StringIO()
+        for target in OP_NAMES:
+            sig = inspect.signature(getattr(OpsHandler, target))
+            if all(
+                p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
+                and p.default is inspect.Parameter.empty
+                for p in sig.parameters.values()
+            ):
+                self_arg, *args = sig.parameters.keys()
+                assert self_arg == "self"
+                code.write(
+                    f"""
+                    def {target}(self, {", ".join(args)}):
+                        return self._default({target!r}, ({", ".join(args)}, ), {{}})
+                    """.strip()
+                )
+                code.write("\n\n")
+            else:
+                # slower fallback for ops with default or variadic arguments
+                setattr(cls, target, cls._call_default(target))
+
+        ctx: dict[str, Any] = {}
+        exec(code.getvalue(), ctx)
+        for target, impl in ctx.items():
+            if target in OP_NAMES:
+                setattr(cls, target, impl)
+
+
+DefaultHandler._init_cls()
+
+
+class NoopHandler(DefaultHandler):
+    name = "NoopHandler"
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        return None
+
+    @staticmethod
+    def masked(mask, body, other) -> None:
+        return None
+
+    @staticmethod
+    def frexp(x) -> tuple[None, None]:
+        return (None, None)
+
+    @staticmethod
+    def scan(dtypes, combine_fn, values) -> tuple[None, ...]:
+        return (None,) * len(values)
+
+    @staticmethod
+    def sort(dtypes, values, stable, descending) -> tuple[None, ...]:
+        return (None,) * len(values)
+
+    @staticmethod
+    def indirect_indexing(index_var, size, check=True, wrap_neg=True) -> sympy.Symbol:
+        return sympy.S.Zero
+
+
+class BasicMathOpsMixin:
+    @staticmethod
+    def add(a, b):
+        return f"{a} + {b}"
+
+    @staticmethod
+    def sub(a, b):
+        return f"{a} - {b}"
+
+    @staticmethod
+    def mul(a, b):
+        return f"{a} * {b}"
+
+    @staticmethod
+    def floordiv(a, b):
+        return f"{a} // {b}"
+
+    @staticmethod
+    def truediv(a, b):
+        return f"{a} / {b}"
+
+    @staticmethod
+    def mod(a, b):
+        # careful, depending on target semantics varies
+        return f"{a} % {b}"
+
+    @staticmethod
+    def pow(a, b):
+        return f"{a} ** {b}"
+
+    @staticmethod
+    def lshift(a, b):
+        return f"{a} << {b}"
+
+    @staticmethod
+    def rshift(a, b):
+        return f"{a} >> {b}"
+
+    @staticmethod
+    def and_(a, b):
+        return f"{a} & {b}"
+
+    @staticmethod
+    def or_(a, b):
+        return f"{a} | {b}"
+
+    @staticmethod
+    def xor(a, b):
+        return f"{a} ^ {b}"
+
+    @staticmethod
+    def eq(a, b):
+        return f"{a} == {b}"
+
+    @staticmethod
+    def ne(a, b):
+        return f"{a} != {b}"
+
+    @staticmethod
+    def lt(a, b):
+        return f"{a} < {b}"
+
+    @staticmethod
+    def gt(a, b):
+        return f"{a} > {b}"
+
+    @staticmethod
+    def le(a, b):
+        return f"{a} <= {b}"
+
+    @staticmethod
+    def ge(a, b):
+        return f"{a} >= {b}"
+
+    @staticmethod
+    def neg(a):
+        return f"-{a}"
+
+
+class MockHandler(BasicMathOpsMixin, DefaultHandler):
+    name = "MockHandler"
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        fargs = [*map(_arg_str, args)]
+        for k, v in kwargs.items():
+            fargs.append(f"{k}={_arg_str(v)}")
+        return f"ops.{name}({', '.join(fargs)})"
+
+    @staticmethod
+    def masked(mask, body, other) -> str:
+        return f"ops.masked({mask}, {body()}, {other})"
+
+    @staticmethod
+    def frexp(x):
+        return (f"ops.frexp({x})[0]", f"ops.frexp({x})[1]")
+
+    @staticmethod
+    def scan(dtypes, combine_fn, values):
+        return tuple(
+            f"ops.scan({dtypes}, {combine_fn}, {values})[{i}]"
+            for i in range(len(values))
+        )
+
+    @staticmethod
+    def sort(dtypes, values, stable, descending):
+        return tuple(
+            f"ops.sort({dtypes}, {values}, stable={stable}, descending={descending})[{i}]"
+            for i in range(len(values))
+        )
+
+    @staticmethod
+    def indirect_indexing(index_var, size, check=True, wrap_neg=True) -> sympy.Symbol:
+        return sympy_index_symbol(str(index_var))
+
+
+class KernelFormatterHandler(DefaultHandler):
+    def __init__(self, parent_handler: OpsHandler[Any]):
+        self.parent_handler = parent_handler
+        self._output = IndentedBuffer(1)
+        self.var_counter = itertools.count()
+
+    @staticmethod
+    def ir_to_string(ir_fn, index, rindex=None) -> str:
+        from .ir import FlexibleLayout
+        from .virtualized import V
+
+        args = [index, rindex] if rindex is not None else [index]
+        names = ["index", "rindex"] if rindex is not None else ["index"]
+        formatter = KernelFormatterHandler(MockHandler())
+
+        with formatter._output.indent(-1):
+            formatter._output.writeline(f"def inner_fn({', '.join(names)}):")
+        for name, arg in zip(names, args):
+            if arg:
+                lhs = ", ".join(
+                    [
+                        str("_" if isinstance(v, (int, sympy.Integer)) else v)
+                        for v in arg
+                    ]
+                )
+                formatter._output.writeline(f"{lhs} = {name}")
+
+        with (
+            V.set_ops_handler(formatter),
+            patch.object(FlexibleLayout, "allow_indexing", True),
+        ):
+            result = ir_fn(*args)
+            return formatter.getvalue(result)
+
+    def indirect_indexing(self, *args, **kwargs) -> sympy.Symbol:
+        return self.parent_handler.indirect_indexing(*args, **kwargs)
+
+    def _write(self, line):
+        # replace line with a new variable name
+        varname = f"tmp{next(self.var_counter)}"
+        self._output.writeline(f"{varname} = {line}")
+        return varname
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        return pytree.tree_map(
+            self._write, getattr(self.parent_handler, name)(*args, **kwargs)
+        )
+
+    def reduction(
+        self,
+        dtype: torch.dtype,
+        src_dtype: torch.dtype,
+        reduction_type: ReductionType,
+        value: Union[str, tuple[str, ...]],
+    ) -> Union[str, tuple[str, ...]]:
+        line = self.parent_handler.reduction(dtype, src_dtype, reduction_type, value)
+        num_values = reduction_num_outputs(reduction_type)
+        varnames = [f"tmp{next(self.var_counter)}" for _ in range(num_values)]
+        self._output.writeline(f"{','.join(varnames)} = {line}")
+        return tuple(varnames) if num_values > 1 else varnames[0]
+
+    def getvalue(self, result):
+        self._output.writeline(f"return {result}")
+        return self._output.getvalue()
+
+
+class WrapperHandler(DefaultHandler):
+    def __init__(self, inner: OpsHandler[Any]):
+        self._inner = inner
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        return getattr(self._inner, name)(*args, **kwargs)
+
+
+class AddParenHandler(WrapperHandler):
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        val = getattr(self._inner, name)(*args, **kwargs)
+        if not val or isinstance(val, (sympy.Expr, tuple, list)):
+            return val
+        return f"({val})"
+
+
+class OpCountResult(NamedTuple):
+    num_ops: int
+    used_ops: OrderedSet[str]
+    read_buffers: list[str]
+    nontrivial_read_count: int
+
+
+class OpCounterCSE(DefaultHandler):
+    """Shim to count how many ops are used"""
+
+    def __init__(self, inner: OpsHandler[Any]):
+        super().__init__()
+        self.parent_handler = inner
+        self.op_count = 0
+        self.var_names: dict[str, str] = {}
+        self._used_ops: OrderedSet[str] = OrderedSet()
+        self._read_names: list[str] = []
+        self._nontrivial_read_count = 0
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        self._used_ops.add(name)
+        return pytree.tree_map(
+            self._update_count, getattr(self.parent_handler, name)(*args, **kwargs)
+        )
+
+    def _update_count(self, val):
+        varname = self.var_names.get(val)
+        if not varname:
+            varname = f"tmp{self.op_count}"
+            self.op_count += 1
+            self.var_names[val] = varname
+        return varname
+
+    def indirect_indexing(self, *args, **kwargs):
+        self._used_ops.add("indirect_indexing")
+        return self.parent_handler.indirect_indexing(*args, **kwargs)
+
+    def load(self, name: str, index: sympy.Expr) -> str:
+        val = self.parent_handler.load(name, index)
+        if val not in self.var_names:
+            self._used_ops.add("load")
+            self._read_names.append(name)
+            if not isinstance(index, (sympy.Integer, int)):
+                self._nontrivial_read_count += 1
+        return self._update_count(val)
+
+    def load_seed(self, name: str, offset: T):
+        val = self.parent_handler.load_seed(name, offset)
+        if val not in self.var_names:
+            self._used_ops.add("load_seed")
+            self._read_names.append(name)
+        return self._update_count(val)
+
+    def bucketize(
+        self,
+        values: T,
+        boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr],
+        boundary_indices: T,
+        indexing_dtype: torch.dtype,
+        right: bool,
+        sorter: Optional[tuple[str, sympy.Expr]] = None,
+        sorter_indices: Optional[T] = None,
+    ) -> T:
+        """
+        See [Note: Inductor bucketize op]
+        """
+        val = self.parent_handler.bucketize(
+            values,
+            boundaries,
+            boundary_indices,
+            indexing_dtype,
+            right,
+            sorter,
+            sorter_indices,
+        )
+        if val not in self.var_names:
+            self._used_ops.add("bucketize")
+            self._read_names.append(boundaries[0])
+            if sorter is not None:
+                self._read_names.append(sorter[0])
+        return self._update_count(val)
+
+    def getvalue(self):
+        return OpCountResult(
+            self.op_count, self._used_ops, self._read_names, self._nontrivial_read_count
+        )
+
+
+class ExtractConstantsHandler(NoopHandler):
+    def __init__(self, device: Optional[torch.device]):
+        self.device = device
+
+    def constant(self, value: Any, dtype: torch.dtype) -> torch._inductor.ir.Constant:
+        from torch._inductor import ir
+
+        return ir.Constant(
+            value=value, dtype=dtype, device=self.device or torch.get_default_device()
+        )
+
+
+class SimpleCSEHandler(WrapperHandler):
+    """Wraps the underlying handler with a CSE pass
+
+    NOTE: Compared to codegen level CSE this is simplified as it
+    doesn't support stores which require load cache invalidation.
+    """
+
+    def __init__(self, inner: Any):
+        super().__init__(inner)
+        self.cse_cache: dict[str, Union[Any, tuple[Any, ...]]] = {}
+        self.mock = MockHandler()
+
+    def indirect_indexing(self, *args, **kwargs) -> sympy.Expr:
+        return super().indirect_indexing(*args, **kwargs)  # type: ignore[misc]
+
+    def store(self, *args, **kwargs) -> None:
+        raise NotImplementedError("store not implemented")
+
+    def store_reduction(self, *args, **kwargs) -> None:
+        raise NotImplementedError("store not implemented")
+
+    def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
+        key = getattr(self.mock, name)(*args, **kwargs)
+        val = self.cse_cache.get(key)
+        if val is not None:
+            return val
+
+        val = getattr(self._inner, name)(*args, **kwargs)
+        self.cse_cache[key] = val
+        return val
diff --git a/shared/package-files/b6/b6d4a21144ed38a935c7e9457344bd620db2c9464c26a3f5aee7c20d68254afc/sub_ops.h b/shared/package-files/b6/b6d4a21144ed38a935c7e9457344bd620db2c9464c26a3f5aee7c20d68254afc/sub_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..1007e9b07b315e26964c5413987020c51e6cb1cc
--- /dev/null
+++ b/shared/package-files/b6/b6d4a21144ed38a935c7e9457344bd620db2c9464c26a3f5aee7c20d68254afc/sub_ops.h
@@ -0,0 +1,84 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API sub_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out);
+};
+
+struct TORCH_API sub_Tensor {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub";
+  static constexpr const char* overload_name = "Tensor";
+  static constexpr const char* schema_str = "sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha);
+};
+
+struct TORCH_API sub__Tensor {
+  using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub_";
+  static constexpr const char* overload_name = "Tensor";
+  static constexpr const char* schema_str = "sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha);
+};
+
+struct TORCH_API sub_Scalar {
+  using schema = at::Tensor (const at::Tensor &, const at::Scalar &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha);
+};
+
+struct TORCH_API sub__Scalar {
+  using schema = at::Tensor & (at::Tensor &, const at::Scalar &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub_";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha);
+};
+
+struct TORCH_API sub_Scalar_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sub";
+  static constexpr const char* overload_name = "Scalar_out";
+  static constexpr const char* schema_str = "sub.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b6/b6e1238b997a1aa6cd8efef84fa6b77bc2c3cc8db329468bcef7e5b8d5ce144d/test_numpy.py b/shared/package-files/b6/b6e1238b997a1aa6cd8efef84fa6b77bc2c3cc8db329468bcef7e5b8d5ce144d/test_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd456d0d6cc49138c29d7ab28ee02694448d578f
--- /dev/null
+++ b/shared/package-files/b6/b6e1238b997a1aa6cd8efef84fa6b77bc2c3cc8db329468bcef7e5b8d5ce144d/test_numpy.py
@@ -0,0 +1,335 @@
+# This testfile tests SymPy <-> NumPy compatibility
+
+# Don't test any SymPy features here. Just pure interaction with NumPy.
+# Always write regular SymPy tests for anything, that can be tested in pure
+# Python (without numpy). Here we test everything, that a user may need when
+# using SymPy with NumPy
+from sympy.external.importtools import version_tuple
+from sympy.external import import_module
+
+numpy = import_module('numpy')
+if numpy:
+    array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
+else:
+    #bin/test will not execute any tests now
+    disabled = True
+
+
+from sympy.core.numbers import (Float, Integer, Rational)
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.trigonometric import sin
+from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
+from sympy.utilities.lambdify import lambdify
+import sympy
+
+import mpmath
+from sympy.abc import x, y, z
+from sympy.utilities.decorator import conserve_mpmath_dps
+from sympy.utilities.exceptions import ignore_warnings
+from sympy.testing.pytest import raises
+
+
+# first, systematically check, that all operations are implemented and don't
+# raise an exception
+
+
+def test_systematic_basic():
+    def s(sympy_object, numpy_array):
+        _ = [sympy_object + numpy_array,
+        numpy_array + sympy_object,
+        sympy_object - numpy_array,
+        numpy_array - sympy_object,
+        sympy_object * numpy_array,
+        numpy_array * sympy_object,
+        sympy_object / numpy_array,
+        numpy_array / sympy_object,
+        sympy_object ** numpy_array,
+        numpy_array ** sympy_object]
+    x = Symbol("x")
+    y = Symbol("y")
+    sympy_objs = [
+        Rational(2, 3),
+        Float("1.3"),
+        x,
+        y,
+        pow(x, y)*y,
+        Integer(5),
+        Float(5.5),
+    ]
+    numpy_objs = [
+        array([1]),
+        array([3, 8, -1]),
+        array([x, x**2, Rational(5)]),
+        array([x/y*sin(y), 5, Rational(5)]),
+    ]
+    for x in sympy_objs:
+        for y in numpy_objs:
+            s(x, y)
+
+
+# now some random tests, that test particular problems and that also
+# check that the results of the operations are correct
+
+def test_basics():
+    one = Rational(1)
+    zero = Rational(0)
+    assert array(1) == array(one)
+    assert array([one]) == array([one])
+    assert array([x]) == array([x])
+    assert array(x) == array(Symbol("x"))
+    assert array(one + x) == array(1 + x)
+
+    X = array([one, zero, zero])
+    assert (X == array([one, zero, zero])).all()
+    assert (X == array([one, 0, 0])).all()
+
+
+def test_arrays():
+    one = Rational(1)
+    zero = Rational(0)
+    X = array([one, zero, zero])
+    Y = one*X
+    X = array([Symbol("a") + Rational(1, 2)])
+    Y = X + X
+    assert Y == array([1 + 2*Symbol("a")])
+    Y = Y + 1
+    assert Y == array([2 + 2*Symbol("a")])
+    Y = X - X
+    assert Y == array([0])
+
+
+def test_conversion1():
+    a = list2numpy([x**2, x])
+    #looks like an array?
+    assert isinstance(a, ndarray)
+    assert a[0] == x**2
+    assert a[1] == x
+    assert len(a) == 2
+    #yes, it's the array
+
+
+def test_conversion2():
+    a = 2*list2numpy([x**2, x])
+    b = list2numpy([2*x**2, 2*x])
+    assert (a == b).all()
+
+    one = Rational(1)
+    zero = Rational(0)
+    X = list2numpy([one, zero, zero])
+    Y = one*X
+    X = list2numpy([Symbol("a") + Rational(1, 2)])
+    Y = X + X
+    assert Y == array([1 + 2*Symbol("a")])
+    Y = Y + 1
+    assert Y == array([2 + 2*Symbol("a")])
+    Y = X - X
+    assert Y == array([0])
+
+
+def test_list2numpy():
+    assert (array([x**2, x]) == list2numpy([x**2, x])).all()
+
+
+def test_Matrix1():
+    m = Matrix([[x, x**2], [5, 2/x]])
+    assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
+    m = Matrix([[sin(x), x**2], [5, 2/x]])
+    assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
+
+
+def test_Matrix2():
+    m = Matrix([[x, x**2], [5, 2/x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
+    m = Matrix([[sin(x), x**2], [5, 2/x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
+
+
+def test_Matrix3():
+    a = array([[2, 4], [5, 1]])
+    assert Matrix(a) == Matrix([[2, 4], [5, 1]])
+    assert Matrix(a) != Matrix([[2, 4], [5, 2]])
+    a = array([[sin(2), 4], [5, 1]])
+    assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
+
+
+def test_Matrix4():
+    with ignore_warnings(PendingDeprecationWarning):
+        a = matrix([[2, 4], [5, 1]])
+    assert Matrix(a) == Matrix([[2, 4], [5, 1]])
+    assert Matrix(a) != Matrix([[2, 4], [5, 2]])
+    with ignore_warnings(PendingDeprecationWarning):
+        a = matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
+
+
+def test_Matrix_sum():
+    M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
+    assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
+    assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
+    assert M + m == M.add(m)
+
+
+def test_Matrix_mul():
+    M = Matrix([[1, 2, 3], [x, y, x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        m = matrix([[2, 4], [x, 6], [x, z**2]])
+    assert M*m == Matrix([
+        [         2 + 5*x,        16 + 3*z**2],
+        [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
+    ])
+
+    assert m*M == Matrix([
+        [   2 + 4*x,      4 + 4*y,      6 + 4*x],
+        [       7*x,    2*x + 6*y,          9*x],
+        [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
+    ])
+    a = array([2])
+    assert a[0] * M == 2 * M
+    assert M * a[0] == 2 * M
+
+
+def test_Matrix_array():
+    class matarray:
+        def __array__(self, dtype=object, copy=None):
+            if copy is not None and not copy:
+                raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
+            from numpy import array
+            return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    matarr = matarray()
+    assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+
+
+def test_matrix2numpy():
+    a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
+    assert isinstance(a, ndarray)
+    assert a.shape == (2, 2)
+    assert a[0, 0] == 1
+    assert a[0, 1] == x**2
+    assert a[1, 0] == 3*sin(x)
+    assert a[1, 1] == 0
+
+
+def test_matrix2numpy_conversion():
+    a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
+    b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
+    assert (matrix2numpy(a) == b).all()
+    assert matrix2numpy(a).dtype == numpy.dtype('object')
+
+    c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
+    d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
+    assert c.dtype == numpy.dtype('int8')
+    assert d.dtype == numpy.dtype('float64')
+
+
+def test_issue_3728():
+    assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
+    assert (Rational(1, 2) + array(
+        [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
+    assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
+    assert (Float("0.5") + array(
+        [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
+
+
+@conserve_mpmath_dps
+def test_lambdify():
+    mpmath.mp.dps = 16
+    sin02 = mpmath.mpf("0.198669330795061215459412627")
+    f = lambdify(x, sin(x), "numpy")
+    prec = 1e-15
+    assert -prec < f(0.2) - sin02 < prec
+
+    # if this succeeds, it can't be a numpy function
+
+    if version_tuple(numpy.__version__) >= version_tuple('1.17'):
+        with raises(TypeError):
+            f(x)
+    else:
+        with raises(AttributeError):
+            f(x)
+
+
+def test_lambdify_matrix():
+    f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
+    assert (f(1) == array([[1, 2], [1, 2]])).all()
+
+
+def test_lambdify_matrix_multi_input():
+    M = sympy.Matrix([[x**2, x*y, x*z],
+                      [y*x, y**2, y*z],
+                      [z*x, z*y, z**2]])
+    f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
+
+    xh, yh, zh = 1.0, 2.0, 3.0
+    expected = array([[xh**2, xh*yh, xh*zh],
+                      [yh*xh, yh**2, yh*zh],
+                      [zh*xh, zh*yh, zh**2]])
+    actual = f(xh, yh, zh)
+    assert numpy.allclose(actual, expected)
+
+
+def test_lambdify_matrix_vec_input():
+    X = sympy.DeferredVector('X')
+    M = Matrix([
+        [X[0]**2, X[0]*X[1], X[0]*X[2]],
+        [X[1]*X[0], X[1]**2, X[1]*X[2]],
+        [X[2]*X[0], X[2]*X[1], X[2]**2]])
+    f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
+
+    Xh = array([1.0, 2.0, 3.0])
+    expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
+                      [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
+                      [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
+    actual = f(Xh)
+    assert numpy.allclose(actual, expected)
+
+
+def test_lambdify_transl():
+    from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
+    for sym, mat in NUMPY_TRANSLATIONS.items():
+        assert sym in sympy.__dict__
+        assert mat in numpy.__dict__
+
+
+def test_symarray():
+    """Test creation of numpy arrays of SymPy symbols."""
+
+    import numpy as np
+    import numpy.testing as npt
+
+    syms = symbols('_0,_1,_2')
+    s1 = symarray("", 3)
+    s2 = symarray("", 3)
+    npt.assert_array_equal(s1, np.array(syms, dtype=object))
+    assert s1[0] == s2[0]
+
+    a = symarray('a', 3)
+    b = symarray('b', 3)
+    assert not(a[0] == b[0])
+
+    asyms = symbols('a_0,a_1,a_2')
+    npt.assert_array_equal(a, np.array(asyms, dtype=object))
+
+    # Multidimensional checks
+    a2d = symarray('a', (2, 3))
+    assert a2d.shape == (2, 3)
+    a00, a12 = symbols('a_0_0,a_1_2')
+    assert a2d[0, 0] == a00
+    assert a2d[1, 2] == a12
+
+    a3d = symarray('a', (2, 3, 2))
+    assert a3d.shape == (2, 3, 2)
+    a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
+    assert a3d[0, 0, 0] == a000
+    assert a3d[1, 2, 0] == a120
+    assert a3d[1, 2, 1] == a121
+
+
+def test_vectorize():
+    assert (numpy.vectorize(
+        sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
diff --git a/shared/package-files/b6/b6e88a9a3036625fbc2db57d67d63584f48119d70413ea37ed1846350cbeec9e/Flags.h b/shared/package-files/b6/b6e88a9a3036625fbc2db57d67d63584f48119d70413ea37ed1846350cbeec9e/Flags.h
new file mode 100644
index 0000000000000000000000000000000000000000..0d460db224a51a279ae676c62acfcd377a921ad8
--- /dev/null
+++ b/shared/package-files/b6/b6e88a9a3036625fbc2db57d67d63584f48119d70413ea37ed1846350cbeec9e/Flags.h
@@ -0,0 +1,242 @@
+#ifndef C10_UTIL_FLAGS_H_
+#define C10_UTIL_FLAGS_H_
+
+/* Commandline flags support for C10.
+ *
+ * This is a portable commandline flags tool for c10, so we can optionally
+ * choose to use gflags or a lightweight custom implementation if gflags is
+ * not possible on a certain platform. If you have gflags installed, set the
+ * macro C10_USE_GFLAGS will seamlessly route everything to gflags.
+ *
+ * To define a flag foo of type bool default to true, do the following in the
+ * *global* namespace:
+ *     C10_DEFINE_bool(foo, true, "An example.");
+ *
+ * To use it in another .cc file, you can use C10_DECLARE_* as follows:
+ *     C10_DECLARE_bool(foo);
+ *
+ * In both cases, you can then access the flag via FLAGS_foo.
+ *
+ * It is recommended that you build with gflags. To learn more about the flags
+ * usage, refer to the gflags page here:
+ *
+ * https://gflags.github.io/gflags/
+ *
+ * Note about Python users / devs: gflags is initiated from a C++ function
+ * ParseCommandLineFlags, and is usually done in native binaries in the main
+ * function. As Python does not have a modifiable main function, it is usually
+ * difficult to change the flags after Python starts. Hence, it is recommended
+ * that one sets the default value of the flags to one that's acceptable in
+ * general - that will allow Python to run without wrong flags.
+ */
+
+#include 
+#include 
+
+#include 
+
+namespace c10 {
+/**
+ * Sets the usage message when a commandline tool is called with "--help".
+ */
+C10_API void SetUsageMessage(const std::string& str);
+
+/**
+ * Returns the usage message for the commandline tool set by SetUsageMessage.
+ */
+C10_API const char* UsageMessage();
+
+/**
+ * Parses the commandline flags.
+ *
+ * This command parses all the commandline arguments passed in via pargc
+ * and argv. Once it is finished, partc and argv will contain the remaining
+ * commandline args that c10 does not deal with. Note that following
+ * convention, argv[0] contains the binary name and is not parsed.
+ */
+C10_API bool ParseCommandLineFlags(int* pargc, char*** pargv);
+
+/**
+ * Checks if the commandline flags has already been passed.
+ */
+C10_API bool CommandLineFlagsHasBeenParsed();
+
+} // namespace c10
+
+////////////////////////////////////////////////////////////////////////////////
+// Below are gflags and non-gflags specific implementations.
+// In general, they define the following macros for one to declare (use
+// C10_DECLARE) or define (use C10_DEFINE) flags:
+// C10_{DECLARE,DEFINE}_{int,int64,double,bool,string}
+////////////////////////////////////////////////////////////////////////////////
+
+#ifdef C10_USE_GFLAGS
+
+////////////////////////////////////////////////////////////////////////////////
+// Begin gflags section: most functions are basically rerouted to gflags.
+////////////////////////////////////////////////////////////////////////////////
+#include 
+
+// C10 uses hidden visibility by default. However, in gflags, it only uses
+// export on Windows platform (with dllexport) but not on linux/mac (with
+// default visibility). As a result, to ensure that we are always exporting
+// global variables, we will redefine the GFLAGS_DLL_DEFINE_FLAG macro if we
+// are building C10 as a shared library.
+// This has to be done after the inclusion of gflags, because some early
+// versions of gflags.h (e.g. 2.0 on ubuntu 14.04) directly defines the
+// macros, so we need to do definition after gflags is done.
+#ifdef GFLAGS_DLL_DEFINE_FLAG
+#undef GFLAGS_DLL_DEFINE_FLAG
+#endif // GFLAGS_DLL_DEFINE_FLAG
+#ifdef GFLAGS_DLL_DECLARE_FLAG
+#undef GFLAGS_DLL_DECLARE_FLAG
+#endif // GFLAGS_DLL_DECLARE_FLAG
+#define GFLAGS_DLL_DEFINE_FLAG C10_EXPORT
+#define GFLAGS_DLL_DECLARE_FLAG C10_IMPORT
+
+// gflags before 2.0 uses namespace google and after 2.1 uses namespace gflags.
+// Using GFLAGS_GFLAGS_H_ to capture this change.
+#ifndef GFLAGS_GFLAGS_H_
+namespace gflags = google;
+#endif // GFLAGS_GFLAGS_H_
+
+// Motivation about the gflags wrapper:
+// (1) We would need to make sure that the gflags version and the non-gflags
+// version of C10 are going to expose the same flags abstraction. One should
+// explicitly use FLAGS_flag_name to access the flags.
+// (2) For flag names, it is recommended to start with c10_ to distinguish it
+// from regular gflags flags. For example, do
+//    C10_DEFINE_BOOL(c10_my_flag, true, "An example");
+// to allow one to use FLAGS_c10_my_flag.
+// (3) Gflags has a design issue that does not properly expose the global flags,
+// if one builds the library with -fvisibility=hidden. The current gflags (as of
+// Aug 2018) only deals with the Windows case using dllexport, and not the Linux
+// counterparts. As a result, we will explicitly use C10_EXPORT to export the
+// flags defined in C10. This is done via a global reference, so the flag
+// itself is not duplicated - under the hood it is the same global gflags flag.
+#define C10_GFLAGS_DEF_WRAPPER(type, real_type, name, default_value, help_str) \
+  DEFINE_##type(name, default_value, help_str);
+
+#define C10_DEFINE_int(name, default_value, help_str) \
+  C10_GFLAGS_DEF_WRAPPER(int32, gflags::int32, name, default_value, help_str)
+#define C10_DEFINE_int32(name, default_value, help_str) \
+  C10_DEFINE_int(name, default_value, help_str)
+#define C10_DEFINE_int64(name, default_value, help_str) \
+  C10_GFLAGS_DEF_WRAPPER(int64, gflags::int64, name, default_value, help_str)
+#define C10_DEFINE_double(name, default_value, help_str) \
+  C10_GFLAGS_DEF_WRAPPER(double, double, name, default_value, help_str)
+#define C10_DEFINE_bool(name, default_value, help_str) \
+  C10_GFLAGS_DEF_WRAPPER(bool, bool, name, default_value, help_str)
+#define C10_DEFINE_string(name, default_value, help_str) \
+  C10_GFLAGS_DEF_WRAPPER(string, ::fLS::clstring, name, default_value, help_str)
+
+// DECLARE_typed_var should be used in header files and in the global namespace.
+#define C10_GFLAGS_DECLARE_WRAPPER(type, real_type, name) DECLARE_##type(name);
+
+#define C10_DECLARE_int(name) \
+  C10_GFLAGS_DECLARE_WRAPPER(int32, gflags::int32, name)
+#define C10_DECLARE_int32(name) C10_DECLARE_int(name)
+#define C10_DECLARE_int64(name) \
+  C10_GFLAGS_DECLARE_WRAPPER(int64, gflags::int64, name)
+#define C10_DECLARE_double(name) \
+  C10_GFLAGS_DECLARE_WRAPPER(double, double, name)
+#define C10_DECLARE_bool(name) C10_GFLAGS_DECLARE_WRAPPER(bool, bool, name)
+#define C10_DECLARE_string(name) \
+  C10_GFLAGS_DECLARE_WRAPPER(string, ::fLS::clstring, name)
+
+#define TORCH_DECLARE_int(name) C10_DECLARE_int(name)
+#define TORCH_DECLARE_int32(name) C10_DECLARE_int32(name)
+#define TORCH_DECLARE_int64(name) C10_DECLARE_int64(name)
+#define TORCH_DECLARE_double(name) C10_DECLARE_double(name)
+#define TORCH_DECLARE_bool(name) C10_DECLARE_bool(name)
+#define TORCH_DECLARE_string(name) C10_DECLARE_string(name)
+
+////////////////////////////////////////////////////////////////////////////////
+// End gflags section.
+////////////////////////////////////////////////////////////////////////////////
+
+#else // C10_USE_GFLAGS
+
+////////////////////////////////////////////////////////////////////////////////
+// Begin non-gflags section: providing equivalent functionality.
+////////////////////////////////////////////////////////////////////////////////
+
+namespace c10 {
+
+class C10_API C10FlagParser {
+ public:
+  bool success() {
+    return success_;
+  }
+
+ protected:
+  template 
+  bool Parse(const std::string& content, T* value);
+  bool success_{false};
+};
+
+C10_DECLARE_REGISTRY(C10FlagsRegistry, C10FlagParser, const std::string&);
+
+} // namespace c10
+
+// The macros are defined outside the c10 namespace. In your code, you should
+// write the C10_DEFINE_* and C10_DECLARE_* macros outside any namespace
+// as well.
+
+#define C10_DEFINE_typed_var(type, name, default_value, help_str)       \
+  C10_EXPORT type FLAGS_##name = default_value;                         \
+  namespace c10 {                                                       \
+  namespace {                                                           \
+  class C10FlagParser_##name : public C10FlagParser {                   \
+   public:                                                              \
+    explicit C10FlagParser_##name(const std::string& content) {         \
+      success_ = C10FlagParser::Parse(content, &FLAGS_##name);    \
+    }                                                                   \
+  };                                                                    \
+  RegistererC10FlagsRegistry g_C10FlagsRegistry_##name(                 \
+      #name,                                                            \
+      C10FlagsRegistry(),                                               \
+      RegistererC10FlagsRegistry::DefaultCreator, \
+      "(" #type ", default " #default_value ") " help_str);             \
+  }                                                                     \
+  }
+
+#define C10_DEFINE_int(name, default_value, help_str) \
+  C10_DEFINE_typed_var(int, name, default_value, help_str)
+#define C10_DEFINE_int32(name, default_value, help_str) \
+  C10_DEFINE_int(name, default_value, help_str)
+#define C10_DEFINE_int64(name, default_value, help_str) \
+  C10_DEFINE_typed_var(int64_t, name, default_value, help_str)
+#define C10_DEFINE_double(name, default_value, help_str) \
+  C10_DEFINE_typed_var(double, name, default_value, help_str)
+#define C10_DEFINE_bool(name, default_value, help_str) \
+  C10_DEFINE_typed_var(bool, name, default_value, help_str)
+#define C10_DEFINE_string(name, default_value, help_str) \
+  C10_DEFINE_typed_var(std::string, name, default_value, help_str)
+
+// DECLARE_typed_var should be used in header files and in the global namespace.
+#define C10_DECLARE_typed_var(type, name) C10_API extern type FLAGS_##name
+
+#define C10_DECLARE_int(name) C10_DECLARE_typed_var(int, name)
+#define C10_DECLARE_int32(name) C10_DECLARE_int(name)
+#define C10_DECLARE_int64(name) C10_DECLARE_typed_var(int64_t, name)
+#define C10_DECLARE_double(name) C10_DECLARE_typed_var(double, name)
+#define C10_DECLARE_bool(name) C10_DECLARE_typed_var(bool, name)
+#define C10_DECLARE_string(name) C10_DECLARE_typed_var(std::string, name)
+
+#define TORCH_DECLARE_typed_var(type, name) TORCH_API extern type FLAGS_##name
+
+#define TORCH_DECLARE_int(name) TORCH_DECLARE_typed_var(int, name)
+#define TORCH_DECLARE_int32(name) TORCH_DECLARE_int(name)
+#define TORCH_DECLARE_int64(name) TORCH_DECLARE_typed_var(int64_t, name)
+#define TORCH_DECLARE_double(name) TORCH_DECLARE_typed_var(double, name)
+#define TORCH_DECLARE_bool(name) TORCH_DECLARE_typed_var(bool, name)
+#define TORCH_DECLARE_string(name) TORCH_DECLARE_typed_var(std::string, name)
+
+////////////////////////////////////////////////////////////////////////////////
+// End non-gflags section.
+////////////////////////////////////////////////////////////////////////////////
+
+#endif // C10_USE_GFLAGS
+
+#endif // C10_UTIL_FLAGS_H_
diff --git a/shared/package-files/b6/b6eabbbe4cbccfa2b97830f4bc8fa06ee68bd5780e4d7873bd27783b72121543/test_arrayexpr_derivatives.cpython-311.pyc b/shared/package-files/b6/b6eabbbe4cbccfa2b97830f4bc8fa06ee68bd5780e4d7873bd27783b72121543/test_arrayexpr_derivatives.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7210b2b71b5638359dfd47973f500e6b0304fc40
Binary files /dev/null and b/shared/package-files/b6/b6eabbbe4cbccfa2b97830f4bc8fa06ee68bd5780e4d7873bd27783b72121543/test_arrayexpr_derivatives.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b6ef91b97d3012a0aae7e40a76eb067105cbd3ddb3567127dab50637d6bcd9f3/_segment_reduce_backward_compositeexplicitautograd_dispatch.h b/shared/package-files/b6/b6ef91b97d3012a0aae7e40a76eb067105cbd3ddb3567127dab50637d6bcd9f3/_segment_reduce_backward_compositeexplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..0d6b150cadbdc8b8ad85aafd76f9de0b98d4883f
--- /dev/null
+++ b/shared/package-files/b6/b6ef91b97d3012a0aae7e40a76eb067105cbd3ddb3567127dab50637d6bcd9f3/_segment_reduce_backward_compositeexplicitautograd_dispatch.h
@@ -0,0 +1,24 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautograd {
+
+TORCH_API at::Tensor & _segment_reduce_backward_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & output, const at::Tensor & data, c10::string_view reduce, const ::std::optional & lengths={}, const ::std::optional & offsets={}, int64_t axis=0, const ::std::optional & initial=::std::nullopt);
+TORCH_API at::Tensor & _segment_reduce_backward_outf(const at::Tensor & grad, const at::Tensor & output, const at::Tensor & data, c10::string_view reduce, const ::std::optional & lengths, const ::std::optional & offsets, int64_t axis, const ::std::optional & initial, at::Tensor & out);
+
+} // namespace compositeexplicitautograd
+} // namespace at
diff --git a/shared/package-files/b6/b6f866c84e0982a698946edf0ae9fae13a8771d69f038f550bbd1aacd582e525/bitwise_right_shift_native.h b/shared/package-files/b6/b6f866c84e0982a698946edf0ae9fae13a8771d69f038f550bbd1aacd582e525/bitwise_right_shift_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..d580df33865f7a34ac9a1048466bd04b19fd0083
--- /dev/null
+++ b/shared/package-files/b6/b6f866c84e0982a698946edf0ae9fae13a8771d69f038f550bbd1aacd582e525/bitwise_right_shift_native.h
@@ -0,0 +1,28 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_bitwise_right_shift_out : public at::meta::structured_bitwise_right_shift_Tensor {
+void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out);
+};
+TORCH_API at::Tensor bitwise_right_shift(const at::Tensor & self, const at::Scalar & other);
+TORCH_API at::Tensor & bitwise_right_shift_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
+TORCH_API at::Tensor & bitwise_right_shift_(at::Tensor & self, const at::Scalar & other);
+TORCH_API at::Tensor bitwise_right_shift(const at::Scalar & self, const at::Tensor & other);
+TORCH_API at::Tensor & bitwise_right_shift_Scalar_Tensor_out(const at::Scalar & self, const at::Tensor & other, at::Tensor & out);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b6/b6f96b002a083faa1b0719805689de079b0a26cd1e0df5b78a1a634f5893f14c/_upsample_bicubic2d_aa_backward_meta_dispatch.h b/shared/package-files/b6/b6f96b002a083faa1b0719805689de079b0a26cd1e0df5b78a1a634f5893f14c/_upsample_bicubic2d_aa_backward_meta_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8cd55769ff1614954dfaa626faee834f196ae9d
--- /dev/null
+++ b/shared/package-files/b6/b6f96b002a083faa1b0719805689de079b0a26cd1e0df5b78a1a634f5893f14c/_upsample_bicubic2d_aa_backward_meta_dispatch.h
@@ -0,0 +1,28 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace meta {
+
+TORCH_API at::Tensor _upsample_bicubic2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor _upsample_bicubic2d_aa_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bicubic2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bicubic2d_aa_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input);
+TORCH_API at::Tensor & _upsample_bicubic2d_aa_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bicubic2d_aa_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input);
+
+} // namespace meta
+} // namespace at
diff --git a/shared/package-files/b6/b6fa0e6a402a91fedc58224d339d589c3ce1d8d2d465be31f7728602a1e7888b/matrices.cpython-311.pyc b/shared/package-files/b6/b6fa0e6a402a91fedc58224d339d589c3ce1d8d2d465be31f7728602a1e7888b/matrices.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbc8abf3b63f9d9edccfe1652d3dad6c57c60cc1
Binary files /dev/null and b/shared/package-files/b6/b6fa0e6a402a91fedc58224d339d589c3ce1d8d2d465be31f7728602a1e7888b/matrices.cpython-311.pyc differ
diff --git a/shared/package-files/b6/b6ffa96904ec07f5d88199ad74d4dd021b2480a7c57830320c81a273477a5952/matrix.py b/shared/package-files/b6/b6ffa96904ec07f5d88199ad74d4dd021b2480a7c57830320c81a273477a5952/matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9143da9a0024a244326628108ad448e98023edf
--- /dev/null
+++ b/shared/package-files/b6/b6ffa96904ec07f5d88199ad74d4dd021b2480a7c57830320c81a273477a5952/matrix.py
@@ -0,0 +1,168 @@
+"""
+====================
+Biadjacency matrices
+====================
+"""
+
+import itertools
+
+import networkx as nx
+from networkx.convert_matrix import _generate_weighted_edges
+
+__all__ = ["biadjacency_matrix", "from_biadjacency_matrix"]
+
+
+@nx._dispatchable(edge_attrs="weight")
+def biadjacency_matrix(
+    G, row_order, column_order=None, dtype=None, weight="weight", format="csr"
+):
+    r"""Returns the biadjacency matrix of the bipartite graph G.
+
+    Let `G = (U, V, E)` be a bipartite graph with node sets
+    `U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency
+    matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1`
+    if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is
+    not `None` and matches the name of an edge attribute, its value is
+    used instead of 1.
+
+    Parameters
+    ----------
+    G : graph
+       A NetworkX graph
+
+    row_order : list of nodes
+       The rows of the matrix are ordered according to the list of nodes.
+
+    column_order : list, optional
+       The columns of the matrix are ordered according to the list of nodes.
+       If column_order is None, then the ordering of columns is arbitrary.
+
+    dtype : NumPy data-type, optional
+        A valid NumPy dtype used to initialize the array. If None, then the
+        NumPy default is used.
+
+    weight : string or None, optional (default='weight')
+       The edge data key used to provide each value in the matrix.
+       If None, then each edge has weight 1.
+
+    format : str in {'dense', 'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
+        The type of the matrix to be returned (default 'csr'). For
+        some algorithms different implementations of sparse matrices
+        can perform better.  See [2]_ for details.
+
+    Returns
+    -------
+    M : SciPy sparse array
+        Biadjacency matrix representation of the bipartite graph G.
+
+    Notes
+    -----
+    No attempt is made to check that the input graph is bipartite.
+
+    For directed bipartite graphs only successors are considered as neighbors.
+    To obtain an adjacency matrix with ones (or weight values) for both
+    predecessors and successors you have to generate two biadjacency matrices
+    where the rows of one of them are the columns of the other, and then add
+    one to the transpose of the other.
+
+    See Also
+    --------
+    adjacency_matrix
+    from_biadjacency_matrix
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
+    .. [2] Scipy Dev. References, "Sparse Matrices",
+       https://docs.scipy.org/doc/scipy/reference/sparse.html
+    """
+    import scipy as sp
+
+    nlen = len(row_order)
+    if nlen == 0:
+        raise nx.NetworkXError("row_order is empty list")
+    if len(row_order) != len(set(row_order)):
+        msg = "Ambiguous ordering: `row_order` contained duplicates."
+        raise nx.NetworkXError(msg)
+    if column_order is None:
+        column_order = list(set(G) - set(row_order))
+    mlen = len(column_order)
+    if len(column_order) != len(set(column_order)):
+        msg = "Ambiguous ordering: `column_order` contained duplicates."
+        raise nx.NetworkXError(msg)
+
+    row_index = dict(zip(row_order, itertools.count()))
+    col_index = dict(zip(column_order, itertools.count()))
+
+    if G.number_of_edges() == 0:
+        row, col, data = [], [], []
+    else:
+        row, col, data = zip(
+            *(
+                (row_index[u], col_index[v], d.get(weight, 1))
+                for u, v, d in G.edges(row_order, data=True)
+                if u in row_index and v in col_index
+            )
+        )
+    A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, mlen), dtype=dtype)
+    try:
+        return A.asformat(format)
+    except ValueError as err:
+        raise nx.NetworkXError(f"Unknown sparse array format: {format}") from err
+
+
+@nx._dispatchable(graphs=None, returns_graph=True)
+def from_biadjacency_matrix(A, create_using=None, edge_attribute="weight"):
+    r"""Creates a new bipartite graph from a biadjacency matrix given as a
+    SciPy sparse array.
+
+    Parameters
+    ----------
+    A: scipy sparse array
+      A biadjacency matrix representation of a graph
+
+    create_using: NetworkX graph
+       Use specified graph for result.  The default is Graph()
+
+    edge_attribute: string
+       Name of edge attribute to store matrix numeric value. The data will
+       have the same type as the matrix entry (int, float, (real,imag)).
+
+    Notes
+    -----
+    The nodes are labeled with the attribute `bipartite` set to an integer
+    0 or 1 representing membership in part 0 or part 1 of the bipartite graph.
+
+    If `create_using` is an instance of :class:`networkx.MultiGraph` or
+    :class:`networkx.MultiDiGraph` and the entries of `A` are of
+    type :class:`int`, then this function returns a multigraph (of the same
+    type as `create_using`) with parallel edges. In this case, `edge_attribute`
+    will be ignored.
+
+    See Also
+    --------
+    biadjacency_matrix
+    from_numpy_array
+
+    References
+    ----------
+    [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
+    """
+    G = nx.empty_graph(0, create_using)
+    n, m = A.shape
+    # Make sure we get even the isolated nodes of the graph.
+    G.add_nodes_from(range(n), bipartite=0)
+    G.add_nodes_from(range(n, n + m), bipartite=1)
+    # Create an iterable over (u, v, w) triples and for each triple, add an
+    # edge from u to v with weight w.
+    triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A))
+    # If the entries in the adjacency matrix are integers and the graph is a
+    # multigraph, then create parallel edges, each with weight 1, for each
+    # entry in the adjacency matrix. Otherwise, create one edge for each
+    # positive entry in the adjacency matrix and set the weight of that edge to
+    # be the entry in the matrix.
+    if A.dtype.kind in ("i", "u") and G.is_multigraph():
+        chain = itertools.chain.from_iterable
+        triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
+    G.add_weighted_edges_from(triples, weight=edge_attribute)
+    return G
diff --git a/shared/package-files/b9/b901e3213a610ccee4e299ee1280c4ba9314c41a1bcef849a52cb4ba7a5e821e/surface_types.h b/shared/package-files/b9/b901e3213a610ccee4e299ee1280c4ba9314c41a1bcef849a52cb4ba7a5e821e/surface_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..62fb681111c041a0f470a20b8bc4c1cd6d90ec27
--- /dev/null
+++ b/shared/package-files/b9/b901e3213a610ccee4e299ee1280c4ba9314c41a1bcef849a52cb4ba7a5e821e/surface_types.h
@@ -0,0 +1,63 @@
+/*
+Copyright (c) 2022 - 2023 Advanced Micro Devices, Inc. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/**
+ *  @file  surface_types.h
+ *  @brief Defines surface types for HIP runtime.
+ */
+
+#ifndef HIP_INCLUDE_HIP_SURFACE_TYPES_H
+#define HIP_INCLUDE_HIP_SURFACE_TYPES_H
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wreserved-identifier"
+#endif
+
+#if !defined(__HIPCC_RTC__)
+#include 
+#endif
+
+/**
+ * An opaque value that represents a hip surface object
+ */
+struct __hip_surface;
+typedef struct __hip_surface* hipSurfaceObject_t;
+
+/**
+ * hip surface reference
+ */
+struct surfaceReference {
+    hipSurfaceObject_t surfaceObject;
+};
+
+/**
+ * hip surface boundary modes
+ */
+enum hipSurfaceBoundaryMode {
+    hipBoundaryModeZero = 0,
+    hipBoundaryModeTrap = 1,
+    hipBoundaryModeClamp = 2
+};
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+#endif /* !HIP_INCLUDE_HIP_SURFACE_TYPES_H */
diff --git a/shared/package-files/b9/b9046734211a10dae64968a67e980ef3c2c0312d29d5b2b2e10e2fd0bace05f6/test_feather.py b/shared/package-files/b9/b9046734211a10dae64968a67e980ef3c2c0312d29d5b2b2e10e2fd0bace05f6/test_feather.py
new file mode 100644
index 0000000000000000000000000000000000000000..22a7d3b83a459a5dc48ee5d56c2f70130d644be4
--- /dev/null
+++ b/shared/package-files/b9/b9046734211a10dae64968a67e980ef3c2c0312d29d5b2b2e10e2fd0bace05f6/test_feather.py
@@ -0,0 +1,252 @@
+""" test feather-format compat """
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import (
+    ArrowStringArray,
+    StringArray,
+)
+
+from pandas.io.feather_format import read_feather, to_feather  # isort:skip
+
+pytestmark = pytest.mark.filterwarnings(
+    "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
+)
+
+pa = pytest.importorskip("pyarrow")
+
+
+@pytest.mark.single_cpu
+class TestFeather:
+    def check_error_on_write(self, df, exc, err_msg):
+        # check that we are raising the exception
+        # on writing
+
+        with pytest.raises(exc, match=err_msg):
+            with tm.ensure_clean() as path:
+                to_feather(df, path)
+
+    def check_external_error_on_write(self, df):
+        # check that we are raising the exception
+        # on writing
+
+        with tm.external_error_raised(Exception):
+            with tm.ensure_clean() as path:
+                to_feather(df, path)
+
+    def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs):
+        if expected is None:
+            expected = df.copy()
+
+        with tm.ensure_clean() as path:
+            to_feather(df, path, **write_kwargs)
+
+            result = read_feather(path, **read_kwargs)
+
+            tm.assert_frame_equal(result, expected)
+
+    def test_error(self):
+        msg = "feather only support IO with DataFrames"
+        for obj in [
+            pd.Series([1, 2, 3]),
+            1,
+            "foo",
+            pd.Timestamp("20130101"),
+            np.array([1, 2, 3]),
+        ]:
+            self.check_error_on_write(obj, ValueError, msg)
+
+    def test_basic(self):
+        df = pd.DataFrame(
+            {
+                "string": list("abc"),
+                "int": list(range(1, 4)),
+                "uint": np.arange(3, 6).astype("u1"),
+                "float": np.arange(4.0, 7.0, dtype="float64"),
+                "float_with_null": [1.0, np.nan, 3],
+                "bool": [True, False, True],
+                "bool_with_null": [True, np.nan, False],
+                "cat": pd.Categorical(list("abc")),
+                "dt": pd.DatetimeIndex(
+                    list(pd.date_range("20130101", periods=3)), freq=None
+                ),
+                "dttz": pd.DatetimeIndex(
+                    list(pd.date_range("20130101", periods=3, tz="US/Eastern")),
+                    freq=None,
+                ),
+                "dt_with_null": [
+                    pd.Timestamp("20130101"),
+                    pd.NaT,
+                    pd.Timestamp("20130103"),
+                ],
+                "dtns": pd.DatetimeIndex(
+                    list(pd.date_range("20130101", periods=3, freq="ns")), freq=None
+                ),
+            }
+        )
+        df["periods"] = pd.period_range("2013", freq="M", periods=3)
+        df["timedeltas"] = pd.timedelta_range("1 day", periods=3)
+        df["intervals"] = pd.interval_range(0, 3, 3)
+
+        assert df.dttz.dtype.tz.zone == "US/Eastern"
+
+        expected = df.copy()
+        expected.loc[1, "bool_with_null"] = None
+        self.check_round_trip(df, expected=expected)
+
+    def test_duplicate_columns(self):
+        # https://github.com/wesm/feather/issues/53
+        # not currently able to handle duplicate columns
+        df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()
+        self.check_external_error_on_write(df)
+
+    def test_read_columns(self):
+        # GH 24025
+        df = pd.DataFrame(
+            {
+                "col1": list("abc"),
+                "col2": list(range(1, 4)),
+                "col3": list("xyz"),
+                "col4": list(range(4, 7)),
+            }
+        )
+        columns = ["col1", "col3"]
+        self.check_round_trip(df, expected=df[columns], columns=columns)
+
+    def test_read_columns_different_order(self):
+        # GH 33878
+        df = pd.DataFrame({"A": [1, 2], "B": ["x", "y"], "C": [True, False]})
+        expected = df[["B", "A"]]
+        self.check_round_trip(df, expected, columns=["B", "A"])
+
+    def test_unsupported_other(self):
+        # mixed python objects
+        df = pd.DataFrame({"a": ["a", 1, 2.0]})
+        self.check_external_error_on_write(df)
+
+    def test_rw_use_threads(self):
+        df = pd.DataFrame({"A": np.arange(100000)})
+        self.check_round_trip(df, use_threads=True)
+        self.check_round_trip(df, use_threads=False)
+
+    def test_path_pathlib(self):
+        df = pd.DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=pd.Index(list("ABCD"), dtype=object),
+            index=pd.Index([f"i-{i}" for i in range(30)], dtype=object),
+        ).reset_index()
+        result = tm.round_trip_pathlib(df.to_feather, read_feather)
+        tm.assert_frame_equal(df, result)
+
+    def test_path_localpath(self):
+        df = pd.DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=pd.Index(list("ABCD"), dtype=object),
+            index=pd.Index([f"i-{i}" for i in range(30)], dtype=object),
+        ).reset_index()
+        result = tm.round_trip_localpath(df.to_feather, read_feather)
+        tm.assert_frame_equal(df, result)
+
+    def test_passthrough_keywords(self):
+        df = pd.DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=pd.Index(list("ABCD"), dtype=object),
+            index=pd.Index([f"i-{i}" for i in range(30)], dtype=object),
+        ).reset_index()
+        self.check_round_trip(df, write_kwargs={"version": 1})
+
+    @pytest.mark.network
+    @pytest.mark.single_cpu
+    def test_http_path(self, feather_file, httpserver):
+        # GH 29055
+        expected = read_feather(feather_file)
+        with open(feather_file, "rb") as f:
+            httpserver.serve_content(content=f.read())
+            res = read_feather(httpserver.url)
+        tm.assert_frame_equal(expected, res)
+
+    def test_read_feather_dtype_backend(self, string_storage, dtype_backend):
+        # GH#50765
+        df = pd.DataFrame(
+            {
+                "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+                "b": pd.Series([1, 2, 3], dtype="Int64"),
+                "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+                "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+                "e": [True, False, None],
+                "f": [True, False, True],
+                "g": ["a", "b", "c"],
+                "h": ["a", "b", None],
+            }
+        )
+
+        if string_storage == "python":
+            string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+            string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_))
+
+        elif dtype_backend == "pyarrow":
+            from pandas.arrays import ArrowExtensionArray
+
+            string_array = ArrowExtensionArray(pa.array(["a", "b", "c"]))
+            string_array_na = ArrowExtensionArray(pa.array(["a", "b", None]))
+
+        else:
+            string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+            string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+        with tm.ensure_clean() as path:
+            to_feather(df, path)
+            with pd.option_context("mode.string_storage", string_storage):
+                result = read_feather(path, dtype_backend=dtype_backend)
+
+        expected = pd.DataFrame(
+            {
+                "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+                "b": pd.Series([1, 2, 3], dtype="Int64"),
+                "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+                "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+                "e": pd.Series([True, False, pd.NA], dtype="boolean"),
+                "f": pd.Series([True, False, True], dtype="boolean"),
+                "g": string_array,
+                "h": string_array_na,
+            }
+        )
+
+        if dtype_backend == "pyarrow":
+            from pandas.arrays import ArrowExtensionArray
+
+            expected = pd.DataFrame(
+                {
+                    col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+                    for col in expected.columns
+                }
+            )
+
+        tm.assert_frame_equal(result, expected)
+
+    def test_int_columns_and_index(self):
+        df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([3, 4, 5], name="test"))
+        self.check_round_trip(df)
+
+    def test_invalid_dtype_backend(self):
+        msg = (
+            "dtype_backend numpy is invalid, only 'numpy_nullable' and "
+            "'pyarrow' are allowed."
+        )
+        df = pd.DataFrame({"int": list(range(1, 4))})
+        with tm.ensure_clean("tmp.feather") as path:
+            df.to_feather(path)
+            with pytest.raises(ValueError, match=msg):
+                read_feather(path, dtype_backend="numpy")
+
+    def test_string_inference(self, tmp_path):
+        # GH#54431
+        path = tmp_path / "test_string_inference.p"
+        df = pd.DataFrame(data={"a": ["x", "y"]})
+        df.to_feather(path)
+        with pd.option_context("future.infer_string", True):
+            result = read_feather(path)
+        expected = pd.DataFrame(data={"a": ["x", "y"]}, dtype="string[pyarrow_numpy]")
+        tm.assert_frame_equal(result, expected)
diff --git a/shared/package-files/b9/b90894c252baa70f4687262aef9517e0d2b1f59964320d89db0318dd00bbfe7a/graph.py b/shared/package-files/b9/b90894c252baa70f4687262aef9517e0d2b1f59964320d89db0318dd00bbfe7a/graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6adcf0d0a33cc2487ca15141ba8da2a7a1729c1
--- /dev/null
+++ b/shared/package-files/b9/b90894c252baa70f4687262aef9517e0d2b1f59964320d89db0318dd00bbfe7a/graph.py
@@ -0,0 +1,2071 @@
+"""Base class for undirected graphs.
+
+The Graph class allows any hashable object as a node
+and can associate key/value attribute pairs with each undirected edge.
+
+Self-loops are allowed but multiple edges are not (see MultiGraph).
+
+For directed graphs see DiGraph and MultiDiGraph.
+"""
+
+from copy import deepcopy
+from functools import cached_property
+
+import networkx as nx
+from networkx import convert
+from networkx.classes.coreviews import AdjacencyView
+from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
+from networkx.exception import NetworkXError
+
+__all__ = ["Graph"]
+
+
+class _CachedPropertyResetterAdj:
+    """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
+
+    This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
+    ``G._adj`` is set to a new value.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached property "adj" whenever the underlying
+    instance attribute "_adj" is set to a new object. It only affects
+    the set process of the obj._adj attribute. All get/del operations
+    act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_adj"] = value
+        # reset cached properties
+        props = ["adj", "edges", "degree"]
+        for prop in props:
+            if prop in od:
+                del od[prop]
+
+
+class _CachedPropertyResetterNode:
+    """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
+
+    This assumes that the ``cached_property`` ``G.node`` should be reset whenever
+    ``G._node`` is set to a new value.
+
+    This object sits on a class and ensures that any instance of that
+    class clears its cached property "nodes" whenever the underlying
+    instance attribute "_node" is set to a new object. It only affects
+    the set process of the obj._adj attribute. All get/del operations
+    act as they normally would.
+
+    For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+    """
+
+    def __set__(self, obj, value):
+        od = obj.__dict__
+        od["_node"] = value
+        # reset cached properties
+        if "nodes" in od:
+            del od["nodes"]
+
+
+class Graph:
+    """
+    Base class for undirected graphs.
+
+    A Graph stores nodes and edges with optional data, or attributes.
+
+    Graphs hold undirected edges.  Self loops are allowed but multiple
+    (parallel) edges are not.
+
+    Nodes can be arbitrary (hashable) Python objects with optional
+    key/value attributes, except that `None` is not allowed as a node.
+
+    Edges are represented as links between nodes with optional
+    key/value attributes.
+
+    Parameters
+    ----------
+    incoming_graph_data : input graph (optional, default: None)
+        Data to initialize graph. If None (default) an empty
+        graph is created.  The data can be any format that is supported
+        by the to_networkx_graph() function, currently including edge list,
+        dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
+        sparse matrix, or PyGraphviz graph.
+
+    attr : keyword arguments, optional (default= no attributes)
+        Attributes to add to graph as key=value pairs.
+
+    See Also
+    --------
+    DiGraph
+    MultiGraph
+    MultiDiGraph
+
+    Examples
+    --------
+    Create an empty graph structure (a "null graph") with no nodes and
+    no edges.
+
+    >>> G = nx.Graph()
+
+    G can be grown in several ways.
+
+    **Nodes:**
+
+    Add one node at a time:
+
+    >>> G.add_node(1)
+
+    Add the nodes from any container (a list, dict, set or
+    even the lines from a file or the nodes from another graph).
+
+    >>> G.add_nodes_from([2, 3])
+    >>> G.add_nodes_from(range(100, 110))
+    >>> H = nx.path_graph(10)
+    >>> G.add_nodes_from(H)
+
+    In addition to strings and integers any hashable Python object
+    (except None) can represent a node, e.g. a customized node object,
+    or even another Graph.
+
+    >>> G.add_node(H)
+
+    **Edges:**
+
+    G can also be grown by adding edges.
+
+    Add one edge,
+
+    >>> G.add_edge(1, 2)
+
+    a list of edges,
+
+    >>> G.add_edges_from([(1, 2), (1, 3)])
+
+    or a collection of edges,
+
+    >>> G.add_edges_from(H.edges)
+
+    If some edges connect nodes not yet in the graph, the nodes
+    are added automatically.  There are no errors when adding
+    nodes or edges that already exist.
+
+    **Attributes:**
+
+    Each graph, node, and edge can hold key/value attribute pairs
+    in an associated attribute dictionary (the keys must be hashable).
+    By default these are empty, but can be added or changed using
+    add_edge, add_node or direct manipulation of the attribute
+    dictionaries named graph, node and edge respectively.
+
+    >>> G = nx.Graph(day="Friday")
+    >>> G.graph
+    {'day': 'Friday'}
+
+    Add node attributes using add_node(), add_nodes_from() or G.nodes
+
+    >>> G.add_node(1, time="5pm")
+    >>> G.add_nodes_from([3], time="2pm")
+    >>> G.nodes[1]
+    {'time': '5pm'}
+    >>> G.nodes[1]["room"] = 714  # node must exist already to use G.nodes
+    >>> del G.nodes[1]["room"]  # remove attribute
+    >>> list(G.nodes(data=True))
+    [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
+
+    Add edge attributes using add_edge(), add_edges_from(), subscript
+    notation, or G.edges.
+
+    >>> G.add_edge(1, 2, weight=4.7)
+    >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
+    >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
+    >>> G[1][2]["weight"] = 4.7
+    >>> G.edges[1, 2]["weight"] = 4
+
+    Warning: we protect the graph data structure by making `G.edges` a
+    read-only dict-like structure. However, you can assign to attributes
+    in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
+    data attributes: `G.edges[1, 2]['weight'] = 4`
+    (For multigraphs: `MG.edges[u, v, key][name] = value`).
+
+    **Shortcuts:**
+
+    Many common graph features allow python syntax to speed reporting.
+
+    >>> 1 in G  # check if node in graph
+    True
+    >>> [n for n in G if n < 3]  # iterate through nodes
+    [1, 2]
+    >>> len(G)  # number of nodes in graph
+    5
+
+    Often the best way to traverse all edges of a graph is via the neighbors.
+    The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
+
+    >>> for n, nbrsdict in G.adjacency():
+    ...     for nbr, eattr in nbrsdict.items():
+    ...         if "weight" in eattr:
+    ...             # Do something useful with the edges
+    ...             pass
+
+    But the edges() method is often more convenient:
+
+    >>> for u, v, weight in G.edges.data("weight"):
+    ...     if weight is not None:
+    ...         # Do something useful with the edges
+    ...         pass
+
+    **Reporting:**
+
+    Simple graph information is obtained using object-attributes and methods.
+    Reporting typically provides views instead of containers to reduce memory
+    usage. The views update as the graph is updated similarly to dict-views.
+    The objects `nodes`, `edges` and `adj` provide access to data attributes
+    via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
+    (e.g. `nodes.items()`, `nodes.data('color')`,
+    `nodes.data('color', default='blue')` and similarly for `edges`)
+    Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
+
+    For details on these and other miscellaneous methods, see below.
+
+    **Subclasses (Advanced):**
+
+    The Graph class uses a dict-of-dict-of-dict data structure.
+    The outer dict (node_dict) holds adjacency information keyed by node.
+    The next dict (adjlist_dict) represents the adjacency information and holds
+    edge data keyed by neighbor.  The inner dict (edge_attr_dict) represents
+    the edge data and holds edge attribute values keyed by attribute names.
+
+    Each of these three dicts can be replaced in a subclass by a user defined
+    dict-like object. In general, the dict-like features should be
+    maintained but extra features can be added. To replace one of the
+    dicts create a new graph class by changing the class(!) variable
+    holding the factory for that dict-like structure.
+
+    node_dict_factory : function, (default: dict)
+        Factory function to be used to create the dict containing node
+        attributes, keyed by node id.
+        It should require no arguments and return a dict-like object
+
+    node_attr_dict_factory: function, (default: dict)
+        Factory function to be used to create the node attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object
+
+    adjlist_outer_dict_factory : function, (default: dict)
+        Factory function to be used to create the outer-most dict
+        in the data structure that holds adjacency info keyed by node.
+        It should require no arguments and return a dict-like object.
+
+    adjlist_inner_dict_factory : function, (default: dict)
+        Factory function to be used to create the adjacency list
+        dict which holds edge data keyed by neighbor.
+        It should require no arguments and return a dict-like object
+
+    edge_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the edge attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    graph_attr_dict_factory : function, (default: dict)
+        Factory function to be used to create the graph attribute
+        dict which holds attribute values keyed by attribute name.
+        It should require no arguments and return a dict-like object.
+
+    Typically, if your extension doesn't impact the data structure all
+    methods will inherit without issue except: `to_directed/to_undirected`.
+    By default these methods create a DiGraph/Graph class and you probably
+    want them to create your extension of a DiGraph/Graph. To facilitate
+    this we define two class variables that you can set in your subclass.
+
+    to_directed_class : callable, (default: DiGraph or MultiDiGraph)
+        Class to create a new graph structure in the `to_directed` method.
+        If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
+
+    to_undirected_class : callable, (default: Graph or MultiGraph)
+        Class to create a new graph structure in the `to_undirected` method.
+        If `None`, a NetworkX class (Graph or MultiGraph) is used.
+
+    **Subclassing Example**
+
+    Create a low memory graph class that effectively disallows edge
+    attributes by using a single attribute dict for all edges.
+    This reduces the memory used, but you lose edge attributes.
+
+    >>> class ThinGraph(nx.Graph):
+    ...     all_edge_dict = {"weight": 1}
+    ...
+    ...     def single_edge_dict(self):
+    ...         return self.all_edge_dict
+    ...
+    ...     edge_attr_dict_factory = single_edge_dict
+    >>> G = ThinGraph()
+    >>> G.add_edge(2, 1)
+    >>> G[2][1]
+    {'weight': 1}
+    >>> G.add_edge(2, 2)
+    >>> G[2][1] is G[2][2]
+    True
+    """
+
+    __networkx_backend__ = "networkx"
+
+    _adj = _CachedPropertyResetterAdj()
+    _node = _CachedPropertyResetterNode()
+
+    node_dict_factory = dict
+    node_attr_dict_factory = dict
+    adjlist_outer_dict_factory = dict
+    adjlist_inner_dict_factory = dict
+    edge_attr_dict_factory = dict
+    graph_attr_dict_factory = dict
+
+    def to_directed_class(self):
+        """Returns the class to use for empty directed copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return nx.DiGraph
+
+    def to_undirected_class(self):
+        """Returns the class to use for empty undirected copies.
+
+        If you subclass the base classes, use this to designate
+        what directed class to use for `to_directed()` copies.
+        """
+        return Graph
+
+    def __init__(self, incoming_graph_data=None, **attr):
+        """Initialize a graph with edges, name, or graph attributes.
+
+        Parameters
+        ----------
+        incoming_graph_data : input graph (optional, default: None)
+            Data to initialize graph. If None (default) an empty
+            graph is created.  The data can be an edge list, or any
+            NetworkX graph object.  If the corresponding optional Python
+            packages are installed the data can also be a 2D NumPy array, a
+            SciPy sparse array, or a PyGraphviz graph.
+
+        attr : keyword arguments, optional (default= no attributes)
+            Attributes to add to graph as key=value pairs.
+
+        See Also
+        --------
+        convert
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G = nx.Graph(name="my graph")
+        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
+        >>> G = nx.Graph(e)
+
+        Arbitrary graph attribute pairs (key=value) may be assigned
+
+        >>> G = nx.Graph(e, day="Friday")
+        >>> G.graph
+        {'day': 'Friday'}
+
+        """
+        self.graph = self.graph_attr_dict_factory()  # dictionary for graph attributes
+        self._node = self.node_dict_factory()  # empty node attribute dict
+        self._adj = self.adjlist_outer_dict_factory()  # empty adjacency dict
+        self.__networkx_cache__ = {}
+        # attempt to load graph with data
+        if incoming_graph_data is not None:
+            convert.to_networkx_graph(incoming_graph_data, create_using=self)
+        # load graph attributes (must be after convert)
+        self.graph.update(attr)
+
+    @cached_property
+    def adj(self):
+        """Graph adjacency object holding the neighbors of each node.
+
+        This object is a read-only dict-like structure with node keys
+        and neighbor-dict values.  The neighbor-dict is keyed by neighbor
+        to the edge-data-dict.  So `G.adj[3][2]['color'] = 'blue'` sets
+        the color of the edge `(3, 2)` to `"blue"`.
+
+        Iterating over G.adj behaves like a dict. Useful idioms include
+        `for nbr, datadict in G.adj[n].items():`.
+
+        The neighbor information is also provided by subscripting the graph.
+        So `for nbr, foovalue in G[node].data('foo', default=1):` works.
+
+        For directed graphs, `G.adj` holds outgoing (successor) info.
+        """
+        return AdjacencyView(self._adj)
+
+    @property
+    def name(self):
+        """String identifier of the graph.
+
+        This graph attribute appears in the attribute dict G.graph
+        keyed by the string `"name"`. as well as an attribute (technically
+        a property) `G.name`. This is entirely user controlled.
+        """
+        return self.graph.get("name", "")
+
+    @name.setter
+    def name(self, s):
+        self.graph["name"] = s
+        nx._clear_cache(self)
+
+    def __str__(self):
+        """Returns a short summary of the graph.
+
+        Returns
+        -------
+        info : string
+            Graph information including the graph name (if any), graph type, and the
+            number of nodes and edges.
+
+        Examples
+        --------
+        >>> G = nx.Graph(name="foo")
+        >>> str(G)
+        "Graph named 'foo' with 0 nodes and 0 edges"
+
+        >>> G = nx.path_graph(3)
+        >>> str(G)
+        'Graph with 3 nodes and 2 edges'
+
+        """
+        return "".join(
+            [
+                type(self).__name__,
+                f" named {self.name!r}" if self.name else "",
+                f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
+            ]
+        )
+
+    def __iter__(self):
+        """Iterate over the nodes. Use: 'for n in G'.
+
+        Returns
+        -------
+        niter : iterator
+            An iterator over all nodes in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [n for n in G]
+        [0, 1, 2, 3]
+        >>> list(G)
+        [0, 1, 2, 3]
+        """
+        return iter(self._node)
+
+    def __contains__(self, n):
+        """Returns True if n is a node, False otherwise. Use: 'n in G'.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> 1 in G
+        True
+        """
+        try:
+            return n in self._node
+        except TypeError:
+            return False
+
+    def __len__(self):
+        """Returns the number of nodes in the graph. Use: 'len(G)'.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        number_of_nodes: identical method
+        order: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> len(G)
+        4
+
+        """
+        return len(self._node)
+
+    def __getitem__(self, n):
+        """Returns a dict of neighbors of node n.  Use: 'G[n]'.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph.
+
+        Returns
+        -------
+        adj_dict : dictionary
+           The adjacency dictionary for nodes connected to n.
+
+        Notes
+        -----
+        G[n] is the same as G.adj[n] and similar to G.neighbors(n)
+        (which is an iterator over G.adj[n])
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G[0]
+        AtlasView({1: {}})
+        """
+        return self.adj[n]
+
+    def add_node(self, node_for_adding, **attr):
+        """Add a single node `node_for_adding` and update node attributes.
+
+        Parameters
+        ----------
+        node_for_adding : node
+            A node can be any hashable Python object except None.
+        attr : keyword arguments, optional
+            Set or change node attributes using key=value.
+
+        See Also
+        --------
+        add_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_node(1)
+        >>> G.add_node("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_node(K3)
+        >>> G.number_of_nodes()
+        3
+
+        Use keywords set/change node attributes:
+
+        >>> G.add_node(1, size=10)
+        >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
+
+        Notes
+        -----
+        A hashable object is one that can be used as a key in a Python
+        dictionary. This includes strings, numbers, tuples of strings
+        and numbers, etc.
+
+        On many platforms hashable items also include mutables such as
+        NetworkX Graphs, though one should be careful that the hash
+        doesn't change on mutables.
+        """
+        if node_for_adding not in self._node:
+            if node_for_adding is None:
+                raise ValueError("None cannot be a node")
+            self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
+            attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
+            attr_dict.update(attr)
+        else:  # update attr even if node already exists
+            self._node[node_for_adding].update(attr)
+        nx._clear_cache(self)
+
+    def add_nodes_from(self, nodes_for_adding, **attr):
+        """Add multiple nodes.
+
+        Parameters
+        ----------
+        nodes_for_adding : iterable container
+            A container of nodes (list, dict, set, etc.).
+            OR
+            A container of (node, attribute dict) tuples.
+            Node attributes are updated using the attribute dict.
+        attr : keyword arguments, optional (default= no attributes)
+            Update attributes for all nodes in nodes.
+            Node attributes specified in nodes as a tuple take
+            precedence over attributes specified via keyword arguments.
+
+        See Also
+        --------
+        add_node
+
+        Notes
+        -----
+        When adding nodes from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.add_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_nodes_from("Hello")
+        >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
+        >>> G.add_nodes_from(K3)
+        >>> sorted(G.nodes(), key=str)
+        [0, 1, 2, 'H', 'e', 'l', 'o']
+
+        Use keywords to update specific node attributes for every node.
+
+        >>> G.add_nodes_from([1, 2], size=10)
+        >>> G.add_nodes_from([3, 4], weight=0.4)
+
+        Use (node, attrdict) tuples to update attributes for specific nodes.
+
+        >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
+        >>> G.nodes[1]["size"]
+        11
+        >>> H = nx.Graph()
+        >>> H.add_nodes_from(G.nodes(data=True))
+        >>> H.nodes[1]["size"]
+        11
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_nodes_from(n + 1 for n in G.nodes)
+        >>> # correct way
+        >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
+        """
+        for n in nodes_for_adding:
+            try:
+                newnode = n not in self._node
+                newdict = attr
+            except TypeError:
+                n, ndict = n
+                newnode = n not in self._node
+                newdict = attr.copy()
+                newdict.update(ndict)
+            if newnode:
+                if n is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[n] = self.adjlist_inner_dict_factory()
+                self._node[n] = self.node_attr_dict_factory()
+            self._node[n].update(newdict)
+        nx._clear_cache(self)
+
+    def remove_node(self, n):
+        """Remove node n.
+
+        Removes the node n and all adjacent edges.
+        Attempting to remove a nonexistent node will raise an exception.
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Raises
+        ------
+        NetworkXError
+           If n is not in the graph.
+
+        See Also
+        --------
+        remove_nodes_from
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> list(G.edges)
+        [(0, 1), (1, 2)]
+        >>> G.remove_node(1)
+        >>> list(G.edges)
+        []
+
+        """
+        adj = self._adj
+        try:
+            nbrs = list(adj[n])  # list handles self-loops (allows mutation)
+            del self._node[n]
+        except KeyError as err:  # NetworkXError if n not in self
+            raise NetworkXError(f"The node {n} is not in the graph.") from err
+        for u in nbrs:
+            del adj[u][n]  # remove all edges n-u in graph
+        del adj[n]  # now remove node
+        nx._clear_cache(self)
+
+    def remove_nodes_from(self, nodes):
+        """Remove multiple nodes.
+
+        Parameters
+        ----------
+        nodes : iterable container
+            A container of nodes (list, dict, set, etc.).  If a node
+            in the container is not in the graph it is silently
+            ignored.
+
+        See Also
+        --------
+        remove_node
+
+        Notes
+        -----
+        When removing nodes from an iterator over the graph you are changing,
+        a `RuntimeError` will be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_nodes)`, and pass this
+        object to `G.remove_nodes_from`.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = list(G.nodes)
+        >>> e
+        [0, 1, 2]
+        >>> G.remove_nodes_from(e)
+        >>> list(G.nodes)
+        []
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
+        >>> # this command will fail, as the graph's dict is modified during iteration
+        >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
+        >>> # this command will work, since the dictionary underlying graph is not modified
+        >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
+        """
+        adj = self._adj
+        for n in nodes:
+            try:
+                del self._node[n]
+                for u in list(adj[n]):  # list handles self-loops
+                    del adj[u][n]  # (allows mutation of dict in loop)
+                del adj[n]
+            except KeyError:
+                pass
+        nx._clear_cache(self)
+
+    @cached_property
+    def nodes(self):
+        """A NodeView of the Graph as G.nodes or G.nodes().
+
+        Can be used as `G.nodes` for data lookup and for set-like operations.
+        Can also be used as `G.nodes(data='color', default=None)` to return a
+        NodeDataView which reports specific node data but no set operations.
+        It presents a dict-like interface as well with `G.nodes.items()`
+        iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
+        providing the value of the `foo` attribute for node `3`. In addition,
+        a view `G.nodes.data('foo')` provides a dict-like interface to the
+        `foo` attribute of each node. `G.nodes.data('foo', default=1)`
+        provides a default for nodes that do not have attribute `foo`.
+
+        Parameters
+        ----------
+        data : string or bool, optional (default=False)
+            The node attribute returned in 2-tuple (n, ddict[data]).
+            If True, return entire node attribute dict as (n, ddict).
+            If False, return just the nodes n.
+
+        default : value, optional (default=None)
+            Value used for nodes that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        NodeView
+            Allows set-like operations over the nodes as well as node
+            attribute dict lookup and calling to get a NodeDataView.
+            A NodeDataView iterates over `(n, data)` and has no set operations.
+            A NodeView iterates over `n` and includes set operations.
+
+            When called, if data is False, an iterator over nodes.
+            Otherwise an iterator of 2-tuples (node, attribute value)
+            where the attribute is specified in `data`.
+            If data is True then the attribute becomes the
+            entire data dictionary.
+
+        Notes
+        -----
+        If your node data is not needed, it is simpler and equivalent
+        to use the expression ``for n in G``, or ``list(G)``.
+
+        Examples
+        --------
+        There are two simple ways of getting a list of all nodes in the graph:
+
+        >>> G = nx.path_graph(3)
+        >>> list(G.nodes)
+        [0, 1, 2]
+        >>> list(G)
+        [0, 1, 2]
+
+        To get the node data along with the nodes:
+
+        >>> G.add_node(1, time="5pm")
+        >>> G.nodes[0]["foo"] = "bar"
+        >>> list(G.nodes(data=True))
+        [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
+        >>> list(G.nodes.data())
+        [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
+
+        >>> list(G.nodes(data="foo"))
+        [(0, 'bar'), (1, None), (2, None)]
+        >>> list(G.nodes.data("foo"))
+        [(0, 'bar'), (1, None), (2, None)]
+
+        >>> list(G.nodes(data="time"))
+        [(0, None), (1, '5pm'), (2, None)]
+        >>> list(G.nodes.data("time"))
+        [(0, None), (1, '5pm'), (2, None)]
+
+        >>> list(G.nodes(data="time", default="Not Available"))
+        [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
+        >>> list(G.nodes.data("time", default="Not Available"))
+        [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
+
+        If some of your nodes have an attribute and the rest are assumed
+        to have a default attribute value you can create a dictionary
+        from node/attribute pairs using the `default` keyword argument
+        to guarantee the value is never None::
+
+            >>> G = nx.Graph()
+            >>> G.add_node(0)
+            >>> G.add_node(1, weight=2)
+            >>> G.add_node(2, weight=3)
+            >>> dict(G.nodes(data="weight", default=1))
+            {0: 1, 1: 2, 2: 3}
+
+        """
+        return NodeView(self)
+
+    def number_of_nodes(self):
+        """Returns the number of nodes in the graph.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        order: identical method
+        __len__: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.number_of_nodes()
+        3
+        """
+        return len(self._node)
+
+    def order(self):
+        """Returns the number of nodes in the graph.
+
+        Returns
+        -------
+        nnodes : int
+            The number of nodes in the graph.
+
+        See Also
+        --------
+        number_of_nodes: identical method
+        __len__: identical method
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.order()
+        3
+        """
+        return len(self._node)
+
+    def has_node(self, n):
+        """Returns True if the graph contains the node n.
+
+        Identical to `n in G`
+
+        Parameters
+        ----------
+        n : node
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.has_node(0)
+        True
+
+        It is more readable and simpler to use
+
+        >>> 0 in G
+        True
+
+        """
+        try:
+            return n in self._node
+        except TypeError:
+            return False
+
+    def add_edge(self, u_of_edge, v_of_edge, **attr):
+        """Add an edge between u and v.
+
+        The nodes u and v will be automatically added if they are
+        not already in the graph.
+
+        Edge attributes can be specified with keywords or by directly
+        accessing the edge's attribute dictionary. See examples below.
+
+        Parameters
+        ----------
+        u_of_edge, v_of_edge : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edges_from : add a collection of edges
+
+        Notes
+        -----
+        Adding an edge that already exists updates the edge data.
+
+        Many NetworkX algorithms designed for weighted graphs use
+        an edge attribute (by default `weight`) to hold a numerical value.
+
+        Examples
+        --------
+        The following all add the edge e=(1, 2) to graph G:
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> e = (1, 2)
+        >>> G.add_edge(1, 2)  # explicit two-node form
+        >>> G.add_edge(*e)  # single edge as tuple of two nodes
+        >>> G.add_edges_from([(1, 2)])  # add edges from iterable container
+
+        Associate data to edges using keywords:
+
+        >>> G.add_edge(1, 2, weight=3)
+        >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
+
+        For non-string attribute keys, use subscript notation.
+
+        >>> G.add_edge(1, 2)
+        >>> G[1][2].update({0: 5})
+        >>> G.edges[1, 2].update({0: 5})
+        """
+        u, v = u_of_edge, v_of_edge
+        # add nodes
+        if u not in self._node:
+            if u is None:
+                raise ValueError("None cannot be a node")
+            self._adj[u] = self.adjlist_inner_dict_factory()
+            self._node[u] = self.node_attr_dict_factory()
+        if v not in self._node:
+            if v is None:
+                raise ValueError("None cannot be a node")
+            self._adj[v] = self.adjlist_inner_dict_factory()
+            self._node[v] = self.node_attr_dict_factory()
+        # add the edge
+        datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+        datadict.update(attr)
+        self._adj[u][v] = datadict
+        self._adj[v][u] = datadict
+        nx._clear_cache(self)
+
+    def add_edges_from(self, ebunch_to_add, **attr):
+        """Add all the edges in ebunch_to_add.
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the container will be added to the
+            graph. The edges must be given as 2-tuples (u, v) or
+            3-tuples (u, v, d) where d is a dictionary containing edge data.
+        attr : keyword arguments, optional
+            Edge data (or labels or objects) can be assigned using
+            keyword arguments.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_weighted_edges_from : convenient way to add weighted edges
+
+        Notes
+        -----
+        Adding the same edge twice has no effect but any edge data
+        will be updated when each duplicate edge is added.
+
+        Edge attributes specified in an ebunch take precedence over
+        attributes specified via keyword arguments.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
+        >>> e = zip(range(0, 3), range(1, 4))
+        >>> G.add_edges_from(e)  # Add the path graph 0-1-2-3
+
+        Associate data to edges
+
+        >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
+        >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
+
+        Evaluate an iterator over a graph if using it to modify the same graph
+
+        >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_edges_from(((5, n) for n in G.nodes))
+        >>> # correct way - note that there will be no self-edge for node 5
+        >>> G.add_edges_from(list((5, n) for n in G.nodes))
+        """
+        for e in ebunch_to_add:
+            ne = len(e)
+            if ne == 3:
+                u, v, dd = e
+            elif ne == 2:
+                u, v = e
+                dd = {}  # doesn't need edge_attr_dict_factory
+            else:
+                raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
+            if u not in self._node:
+                if u is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[u] = self.adjlist_inner_dict_factory()
+                self._node[u] = self.node_attr_dict_factory()
+            if v not in self._node:
+                if v is None:
+                    raise ValueError("None cannot be a node")
+                self._adj[v] = self.adjlist_inner_dict_factory()
+                self._node[v] = self.node_attr_dict_factory()
+            datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
+            datadict.update(attr)
+            datadict.update(dd)
+            self._adj[u][v] = datadict
+            self._adj[v][u] = datadict
+        nx._clear_cache(self)
+
+    def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
+        """Add weighted edges in `ebunch_to_add` with specified weight attr
+
+        Parameters
+        ----------
+        ebunch_to_add : container of edges
+            Each edge given in the list or container will be added
+            to the graph. The edges must be given as 3-tuples (u, v, w)
+            where w is a number.
+        weight : string, optional (default= 'weight')
+            The attribute name for the edge weights to be added.
+        attr : keyword arguments, optional (default= no attributes)
+            Edge attributes to add/update for all edges.
+
+        See Also
+        --------
+        add_edge : add a single edge
+        add_edges_from : add multiple edges
+
+        Notes
+        -----
+        Adding the same edge twice for Graph/DiGraph simply updates
+        the edge data. For MultiGraph/MultiDiGraph, duplicate edges
+        are stored.
+
+        When adding edges from an iterator over the graph you are changing,
+        a `RuntimeError` can be raised with message:
+        `RuntimeError: dictionary changed size during iteration`. This
+        happens when the graph's underlying dictionary is modified during
+        iteration. To avoid this error, evaluate the iterator into a separate
+        object, e.g. by using `list(iterator_of_edges)`, and pass this
+        object to `G.add_weighted_edges_from`.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
+
+        Evaluate an iterator over edges before passing it
+
+        >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
+        >>> weight = 0.1
+        >>> # Grow graph by one new node, adding edges to all existing nodes.
+        >>> # wrong way - will raise RuntimeError
+        >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
+        >>> # correct way - note that there will be no self-edge for node 5
+        >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
+        """
+        self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
+        nx._clear_cache(self)
+
+    def remove_edge(self, u, v):
+        """Remove the edge between u and v.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Remove the edge between nodes u and v.
+
+        Raises
+        ------
+        NetworkXError
+            If there is not an edge between u and v.
+
+        See Also
+        --------
+        remove_edges_from : remove a collection of edges
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, etc
+        >>> G.remove_edge(0, 1)
+        >>> e = (1, 2)
+        >>> G.remove_edge(*e)  # unpacks e from an edge tuple
+        >>> e = (2, 3, {"weight": 7})  # an edge with attribute data
+        >>> G.remove_edge(*e[:2])  # select first part of edge tuple
+        """
+        try:
+            del self._adj[u][v]
+            if u != v:  # self-loop needs only one entry removed
+                del self._adj[v][u]
+        except KeyError as err:
+            raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
+        nx._clear_cache(self)
+
+    def remove_edges_from(self, ebunch):
+        """Remove all edges specified in ebunch.
+
+        Parameters
+        ----------
+        ebunch: list or container of edge tuples
+            Each edge given in the list or container will be removed
+            from the graph. The edges can be:
+
+                - 2-tuples (u, v) edge between u and v.
+                - 3-tuples (u, v, k) where k is ignored.
+
+        See Also
+        --------
+        remove_edge : remove a single edge
+
+        Notes
+        -----
+        Will fail silently if an edge in ebunch is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> ebunch = [(1, 2), (2, 3)]
+        >>> G.remove_edges_from(ebunch)
+        """
+        adj = self._adj
+        for e in ebunch:
+            u, v = e[:2]  # ignore edge data if present
+            if u in adj and v in adj[u]:
+                del adj[u][v]
+                if u != v:  # self loop needs only one entry removed
+                    del adj[v][u]
+        nx._clear_cache(self)
+
+    def update(self, edges=None, nodes=None):
+        """Update the graph using nodes/edges/graphs as input.
+
+        Like dict.update, this method takes a graph as input, adding the
+        graph's nodes and edges to this graph. It can also take two inputs:
+        edges and nodes. Finally it can take either edges or nodes.
+        To specify only nodes the keyword `nodes` must be used.
+
+        The collections of edges and nodes are treated similarly to
+        the add_edges_from/add_nodes_from methods. When iterated, they
+        should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
+
+        Parameters
+        ----------
+        edges : Graph object, collection of edges, or None
+            The first parameter can be a graph or some edges. If it has
+            attributes `nodes` and `edges`, then it is taken to be a
+            Graph-like object and those attributes are used as collections
+            of nodes and edges to be added to the graph.
+            If the first parameter does not have those attributes, it is
+            treated as a collection of edges and added to the graph.
+            If the first argument is None, no edges are added.
+        nodes : collection of nodes, or None
+            The second parameter is treated as a collection of nodes
+            to be added to the graph unless it is None.
+            If `edges is None` and `nodes is None` an exception is raised.
+            If the first parameter is a Graph, then `nodes` is ignored.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(5)
+        >>> G.update(nx.complete_graph(range(4, 10)))
+        >>> from itertools import combinations
+        >>> edges = (
+        ...     (u, v, {"power": u * v})
+        ...     for u, v in combinations(range(10, 20), 2)
+        ...     if u * v < 225
+        ... )
+        >>> nodes = [1000]  # for singleton, use a container
+        >>> G.update(edges, nodes)
+
+        Notes
+        -----
+        It you want to update the graph using an adjacency structure
+        it is straightforward to obtain the edges/nodes from adjacency.
+        The following examples provide common cases, your adjacency may
+        be slightly different and require tweaks of these examples::
+
+        >>> # dict-of-set/list/tuple
+        >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
+        >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
+        >>> G.update(edges=e, nodes=adj)
+
+        >>> DG = nx.DiGraph()
+        >>> # dict-of-dict-of-attribute
+        >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
+        >>> e = [
+        ...     (u, v, {"weight": d})
+        ...     for u, nbrs in adj.items()
+        ...     for v, d in nbrs.items()
+        ... ]
+        >>> DG.update(edges=e, nodes=adj)
+
+        >>> # dict-of-dict-of-dict
+        >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
+        >>> e = [
+        ...     (u, v, {"weight": d})
+        ...     for u, nbrs in adj.items()
+        ...     for v, d in nbrs.items()
+        ... ]
+        >>> DG.update(edges=e, nodes=adj)
+
+        >>> # predecessor adjacency (dict-of-set)
+        >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
+        >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
+
+        >>> # MultiGraph dict-of-dict-of-dict-of-attribute
+        >>> MDG = nx.MultiDiGraph()
+        >>> adj = {
+        ...     1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
+        ...     3: {2: {0: {"weight": 0.7}}},
+        ... }
+        >>> e = [
+        ...     (u, v, ekey, d)
+        ...     for u, nbrs in adj.items()
+        ...     for v, keydict in nbrs.items()
+        ...     for ekey, d in keydict.items()
+        ... ]
+        >>> MDG.update(edges=e)
+
+        See Also
+        --------
+        add_edges_from: add multiple edges to a graph
+        add_nodes_from: add multiple nodes to a graph
+        """
+        if edges is not None:
+            if nodes is not None:
+                self.add_nodes_from(nodes)
+                self.add_edges_from(edges)
+            else:
+                # check if edges is a Graph object
+                try:
+                    graph_nodes = edges.nodes
+                    graph_edges = edges.edges
+                except AttributeError:
+                    # edge not Graph-like
+                    self.add_edges_from(edges)
+                else:  # edges is Graph-like
+                    self.add_nodes_from(graph_nodes.data())
+                    self.add_edges_from(graph_edges.data())
+                    self.graph.update(edges.graph)
+        elif nodes is not None:
+            self.add_nodes_from(nodes)
+        else:
+            raise NetworkXError("update needs nodes or edges input")
+
+    def has_edge(self, u, v):
+        """Returns True if the edge (u, v) is in the graph.
+
+        This is the same as `v in G[u]` without KeyError exceptions.
+
+        Parameters
+        ----------
+        u, v : nodes
+            Nodes can be, for example, strings or numbers.
+            Nodes must be hashable (and not None) Python objects.
+
+        Returns
+        -------
+        edge_ind : bool
+            True if edge is in the graph, False otherwise.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.has_edge(0, 1)  # using two nodes
+        True
+        >>> e = (0, 1)
+        >>> G.has_edge(*e)  #  e is a 2-tuple (u, v)
+        True
+        >>> e = (0, 1, {"weight": 7})
+        >>> G.has_edge(*e[:2])  # e is a 3-tuple (u, v, data_dictionary)
+        True
+
+        The following syntax are equivalent:
+
+        >>> G.has_edge(0, 1)
+        True
+        >>> 1 in G[0]  # though this gives KeyError if 0 not in G
+        True
+
+        """
+        try:
+            return v in self._adj[u]
+        except KeyError:
+            return False
+
+    def neighbors(self, n):
+        """Returns an iterator over all neighbors of node n.
+
+        This is identical to `iter(G[n])`
+
+        Parameters
+        ----------
+        n : node
+           A node in the graph
+
+        Returns
+        -------
+        neighbors : iterator
+            An iterator over all neighbors of node n
+
+        Raises
+        ------
+        NetworkXError
+            If the node n is not in the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [n for n in G.neighbors(0)]
+        [1]
+
+        Notes
+        -----
+        Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edge("a", "b", weight=7)
+        >>> G["a"]
+        AtlasView({'b': {'weight': 7}})
+        >>> G = nx.path_graph(4)
+        >>> [n for n in G[0]]
+        [1]
+        """
+        try:
+            return iter(self._adj[n])
+        except KeyError as err:
+            raise NetworkXError(f"The node {n} is not in the graph.") from err
+
+    @cached_property
+    def edges(self):
+        """An EdgeView of the Graph as G.edges or G.edges().
+
+        edges(self, nbunch=None, data=False, default=None)
+
+        The EdgeView provides set-like operations on the edge-tuples
+        as well as edge attribute lookup. When called, it also provides
+        an EdgeDataView object which allows control of access to edge
+        attributes (but does not provide set-like operations).
+        Hence, `G.edges[u, v]['color']` provides the value of the color
+        attribute for edge `(u, v)` while
+        `for (u, v, c) in G.edges.data('color', default='red'):`
+        iterates through all the edges yielding the color attribute
+        with default `'red'` if no color attribute exists.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges from these nodes.
+        data : string or bool, optional (default=False)
+            The edge attribute returned in 3-tuple (u, v, ddict[data]).
+            If True, return edge attribute dict in 3-tuple (u, v, ddict).
+            If False, return 2-tuple (u, v).
+        default : value, optional (default=None)
+            Value used for edges that don't have the requested attribute.
+            Only relevant if data is not True or False.
+
+        Returns
+        -------
+        edges : EdgeView
+            A view of edge attributes, usually it iterates over (u, v)
+            or (u, v, d) tuples of edges, but can also be used for
+            attribute lookup as `edges[u, v]['foo']`.
+
+        Notes
+        -----
+        Nodes in nbunch that are not in the graph will be (quietly) ignored.
+        For directed graphs this returns the out-edges.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(3)  # or MultiGraph, etc
+        >>> G.add_edge(2, 3, weight=5)
+        >>> [e for e in G.edges]
+        [(0, 1), (1, 2), (2, 3)]
+        >>> G.edges.data()  # default data is {} (empty dict)
+        EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
+        >>> G.edges.data("weight", default=1)
+        EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
+        >>> G.edges([0, 3])  # only edges from these nodes
+        EdgeDataView([(0, 1), (3, 2)])
+        >>> G.edges(0)  # only edges from node 0
+        EdgeDataView([(0, 1)])
+        """
+        return EdgeView(self)
+
+    def get_edge_data(self, u, v, default=None):
+        """Returns the attribute dictionary associated with edge (u, v).
+
+        This is identical to `G[u][v]` except the default is returned
+        instead of an exception if the edge doesn't exist.
+
+        Parameters
+        ----------
+        u, v : nodes
+        default:  any Python object (default=None)
+            Value to return if the edge (u, v) is not found.
+
+        Returns
+        -------
+        edge_dict : dictionary
+            The edge attribute dictionary.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G[0][1]
+        {}
+
+        Warning: Assigning to `G[u][v]` is not permitted.
+        But it is safe to assign attributes `G[u][v]['foo']`
+
+        >>> G[0][1]["weight"] = 7
+        >>> G[0][1]["weight"]
+        7
+        >>> G[1][0]["weight"]
+        7
+
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.get_edge_data(0, 1)  # default edge data is {}
+        {}
+        >>> e = (0, 1)
+        >>> G.get_edge_data(*e)  # tuple form
+        {}
+        >>> G.get_edge_data("a", "b", default=0)  # edge not in graph, return 0
+        0
+        """
+        try:
+            return self._adj[u][v]
+        except KeyError:
+            return default
+
+    def adjacency(self):
+        """Returns an iterator over (node, adjacency dict) tuples for all nodes.
+
+        For directed graphs, only outgoing neighbors/adjacencies are included.
+
+        Returns
+        -------
+        adj_iter : iterator
+           An iterator over (node, adjacency dictionary) for all nodes in
+           the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
+        [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
+
+        """
+        return iter(self._adj.items())
+
+    @cached_property
+    def degree(self):
+        """A DegreeView for the Graph as G.degree or G.degree().
+
+        The node degree is the number of edges adjacent to the node.
+        The weighted node degree is the sum of the edge weights for
+        edges incident to that node.
+
+        This object provides an iterator for (node, degree) as well as
+        lookup for the degree for a single node.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        weight : string or None, optional (default=None)
+           The name of an edge attribute that holds the numerical value used
+           as a weight.  If None, then each edge has weight 1.
+           The degree is the sum of the edge weights adjacent to the node.
+
+        Returns
+        -------
+        DegreeView or int
+            If multiple nodes are requested (the default), returns a `DegreeView`
+            mapping nodes to their degree.
+            If a single node is requested, returns the degree of the node as an integer.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.degree[0]  # node 0 has degree 1
+        1
+        >>> list(G.degree([0, 1, 2]))
+        [(0, 1), (1, 2), (2, 2)]
+        """
+        return DegreeView(self)
+
+    def clear(self):
+        """Remove all nodes and edges from the graph.
+
+        This also removes the name, and all graph, node, and edge attributes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear()
+        >>> list(G.nodes)
+        []
+        >>> list(G.edges)
+        []
+
+        """
+        self._adj.clear()
+        self._node.clear()
+        self.graph.clear()
+        nx._clear_cache(self)
+
+    def clear_edges(self):
+        """Remove all edges from the graph without altering nodes.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.clear_edges()
+        >>> list(G.nodes)
+        [0, 1, 2, 3]
+        >>> list(G.edges)
+        []
+        """
+        for nbr_dict in self._adj.values():
+            nbr_dict.clear()
+        nx._clear_cache(self)
+
+    def is_multigraph(self):
+        """Returns True if graph is a multigraph, False otherwise."""
+        return False
+
+    def is_directed(self):
+        """Returns True if graph is directed, False otherwise."""
+        return False
+
+    def copy(self, as_view=False):
+        """Returns a copy of the graph.
+
+        The copy method by default returns an independent shallow copy
+        of the graph and attributes. That is, if an attribute is a
+        container, that container is shared by the original an the copy.
+        Use Python's `copy.deepcopy` for new containers.
+
+        If `as_view` is True then a view is returned instead of a copy.
+
+        Notes
+        -----
+        All copies reproduce the graph structure, but data attributes
+        may be handled in different ways. There are four types of copies
+        of a graph that people might want.
+
+        Deepcopy -- A "deepcopy" copies the graph structure as well as
+        all data attributes and any objects they might contain.
+        The entire graph object is new so that changes in the copy
+        do not affect the original object. (see Python's copy.deepcopy)
+
+        Data Reference (Shallow) -- For a shallow copy the graph structure
+        is copied but the edge, node and graph attribute dicts are
+        references to those in the original graph. This saves
+        time and memory but could cause confusion if you change an attribute
+        in one graph and it changes the attribute in the other.
+        NetworkX does not provide this level of shallow copy.
+
+        Independent Shallow -- This copy creates new independent attribute
+        dicts and then does a shallow copy of the attributes. That is, any
+        attributes that are containers are shared between the new graph
+        and the original. This is exactly what `dict.copy()` provides.
+        You can obtain this style copy using:
+
+            >>> G = nx.path_graph(5)
+            >>> H = G.copy()
+            >>> H = G.copy(as_view=False)
+            >>> H = nx.Graph(G)
+            >>> H = G.__class__(G)
+
+        Fresh Data -- For fresh data, the graph structure is copied while
+        new empty data attribute dicts are created. The resulting graph
+        is independent of the original and it has no edge, node or graph
+        attributes. Fresh copies are not enabled. Instead use:
+
+            >>> H = G.__class__()
+            >>> H.add_nodes_from(G)
+            >>> H.add_edges_from(G.edges)
+
+        View -- Inspired by dict-views, graph-views act like read-only
+        versions of the original graph, providing a copy of the original
+        structure without requiring any memory for copying the information.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Parameters
+        ----------
+        as_view : bool, optional (default=False)
+            If True, the returned graph-view provides a read-only view
+            of the original graph without actually copying any data.
+
+        Returns
+        -------
+        G : Graph
+            A copy of the graph.
+
+        See Also
+        --------
+        to_directed: return a directed copy of the graph.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> H = G.copy()
+
+        """
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self)
+        G = self.__class__()
+        G.graph.update(self.graph)
+        G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, datadict.copy())
+            for u, nbrs in self._adj.items()
+            for v, datadict in nbrs.items()
+        )
+        return G
+
+    def to_directed(self, as_view=False):
+        """Returns a directed representation of the graph.
+
+        Returns
+        -------
+        G : DiGraph
+            A directed graph with the same name, same nodes, and with
+            each edge (u, v, data) replaced by two directed edges
+            (u, v, data) and (v, u, data).
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar D=DiGraph(G) which returns a
+        shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed Graph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        DiGraph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.Graph()  # or MultiGraph, etc
+        >>> G.add_edge(0, 1)
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+
+        If already directed, return a (deep) copy
+
+        >>> G = nx.DiGraph()  # or MultiDiGraph, etc
+        >>> G.add_edge(0, 1)
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_directed_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, deepcopy(data))
+            for u, nbrs in self._adj.items()
+            for v, data in nbrs.items()
+        )
+        return G
+
+    def to_undirected(self, as_view=False):
+        """Returns an undirected copy of the graph.
+
+        Parameters
+        ----------
+        as_view : bool (optional, default=False)
+          If True return a view of the original undirected graph.
+
+        Returns
+        -------
+        G : Graph/MultiGraph
+            A deepcopy of the graph.
+
+        See Also
+        --------
+        Graph, copy, add_edge, add_edges_from
+
+        Notes
+        -----
+        This returns a "deepcopy" of the edge, node, and
+        graph attributes which attempts to completely copy
+        all of the data and references.
+
+        This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
+        shallow copy of the data.
+
+        See the Python copy module for more information on shallow
+        and deep copies, https://docs.python.org/3/library/copy.html.
+
+        Warning: If you have subclassed DiGraph to use dict-like objects
+        in the data structure, those changes do not transfer to the
+        Graph created by this method.
+
+        Examples
+        --------
+        >>> G = nx.path_graph(2)  # or MultiGraph, etc
+        >>> H = G.to_directed()
+        >>> list(H.edges)
+        [(0, 1), (1, 0)]
+        >>> G2 = H.to_undirected()
+        >>> list(G2.edges)
+        [(0, 1)]
+        """
+        graph_class = self.to_undirected_class()
+        if as_view is True:
+            return nx.graphviews.generic_graph_view(self, graph_class)
+        # deepcopy when not a view
+        G = graph_class()
+        G.graph.update(deepcopy(self.graph))
+        G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
+        G.add_edges_from(
+            (u, v, deepcopy(d))
+            for u, nbrs in self._adj.items()
+            for v, d in nbrs.items()
+        )
+        return G
+
+    def subgraph(self, nodes):
+        """Returns a SubGraph view of the subgraph induced on `nodes`.
+
+        The induced subgraph of the graph contains the nodes in `nodes`
+        and the edges between those nodes.
+
+        Parameters
+        ----------
+        nodes : list, iterable
+            A container of nodes which will be iterated through once.
+
+        Returns
+        -------
+        G : SubGraph View
+            A subgraph view of the graph. The graph structure cannot be
+            changed but node/edge attributes can and are shared with the
+            original graph.
+
+        Notes
+        -----
+        The graph, edge and node attributes are shared with the original graph.
+        Changes to the graph structure is ruled out by the view, but changes
+        to attributes are reflected in the original graph.
+
+        To create a subgraph with its own copy of the edge/node attributes use:
+        G.subgraph(nodes).copy()
+
+        For an inplace reduction of a graph to a subgraph you can remove nodes:
+        G.remove_nodes_from([n for n in G if n not in set(nodes)])
+
+        Subgraph views are sometimes NOT what you want. In most cases where
+        you want to do more than simply look at the induced edges, it makes
+        more sense to just create the subgraph as its own graph with code like:
+
+        ::
+
+            # Create a subgraph SG based on a (possibly multigraph) G
+            SG = G.__class__()
+            SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
+            if SG.is_multigraph():
+                SG.add_edges_from(
+                    (n, nbr, key, d)
+                    for n, nbrs in G.adj.items()
+                    if n in largest_wcc
+                    for nbr, keydict in nbrs.items()
+                    if nbr in largest_wcc
+                    for key, d in keydict.items()
+                )
+            else:
+                SG.add_edges_from(
+                    (n, nbr, d)
+                    for n, nbrs in G.adj.items()
+                    if n in largest_wcc
+                    for nbr, d in nbrs.items()
+                    if nbr in largest_wcc
+                )
+            SG.graph.update(G.graph)
+
+        Subgraphs are not guaranteed to preserve the order of nodes or edges
+        as they appear in the original graph. For example:
+
+        >>> G = nx.Graph()
+        >>> G.add_nodes_from(reversed(range(10)))
+        >>> list(G)
+        [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
+        >>> list(G.subgraph([1, 3, 2]))
+        [1, 2, 3]
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> H = G.subgraph([0, 1, 2])
+        >>> list(H.edges)
+        [(0, 1), (1, 2)]
+        """
+        induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
+        # if already a subgraph, don't make a chain
+        subgraph = nx.subgraph_view
+        if hasattr(self, "_NODE_OK"):
+            return subgraph(
+                self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
+            )
+        return subgraph(self, filter_node=induced_nodes)
+
+    def edge_subgraph(self, edges):
+        """Returns the subgraph induced by the specified edges.
+
+        The induced subgraph contains each edge in `edges` and each
+        node incident to any one of those edges.
+
+        Parameters
+        ----------
+        edges : iterable
+            An iterable of edges in this graph.
+
+        Returns
+        -------
+        G : Graph
+            An edge-induced subgraph of this graph with the same edge
+            attributes.
+
+        Notes
+        -----
+        The graph, edge, and node attributes in the returned subgraph
+        view are references to the corresponding attributes in the original
+        graph. The view is read-only.
+
+        To create a full graph version of the subgraph with its own copy
+        of the edge or node attributes, use::
+
+            G.edge_subgraph(edges).copy()
+
+        Examples
+        --------
+        >>> G = nx.path_graph(5)
+        >>> H = G.edge_subgraph([(0, 1), (3, 4)])
+        >>> list(H.nodes)
+        [0, 1, 3, 4]
+        >>> list(H.edges)
+        [(0, 1), (3, 4)]
+
+        """
+        return nx.edge_subgraph(self, edges)
+
+    def size(self, weight=None):
+        """Returns the number of edges or total of all edge weights.
+
+        Parameters
+        ----------
+        weight : string or None, optional (default=None)
+            The edge attribute that holds the numerical value used
+            as a weight. If None, then each edge has weight 1.
+
+        Returns
+        -------
+        size : numeric
+            The number of edges or
+            (if weight keyword is provided) the total weight sum.
+
+            If weight is None, returns an int. Otherwise a float
+            (or more general numeric if the weights are more general).
+
+        See Also
+        --------
+        number_of_edges
+
+        Examples
+        --------
+        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.size()
+        3
+
+        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
+        >>> G.add_edge("a", "b", weight=2)
+        >>> G.add_edge("b", "c", weight=4)
+        >>> G.size()
+        2
+        >>> G.size(weight="weight")
+        6.0
+        """
+        s = sum(d for v, d in self.degree(weight=weight))
+        # If `weight` is None, the sum of the degrees is guaranteed to be
+        # even, so we can perform integer division and hence return an
+        # integer. Otherwise, the sum of the weighted degrees is not
+        # guaranteed to be an integer, so we perform "real" division.
+        return s // 2 if weight is None else s / 2
+
+    def number_of_edges(self, u=None, v=None):
+        """Returns the number of edges between two nodes.
+
+        Parameters
+        ----------
+        u, v : nodes, optional (default=all edges)
+            If u and v are specified, return the number of edges between
+            u and v. Otherwise return the total number of all edges.
+
+        Returns
+        -------
+        nedges : int
+            The number of edges in the graph.  If nodes `u` and `v` are
+            specified return the number of edges between those nodes. If
+            the graph is directed, this only returns the number of edges
+            from `u` to `v`.
+
+        See Also
+        --------
+        size
+
+        Examples
+        --------
+        For undirected graphs, this method counts the total number of
+        edges in the graph:
+
+        >>> G = nx.path_graph(4)
+        >>> G.number_of_edges()
+        3
+
+        If you specify two nodes, this counts the total number of edges
+        joining the two nodes:
+
+        >>> G.number_of_edges(0, 1)
+        1
+
+        For directed graphs, this method can count the total number of
+        directed edges from `u` to `v`:
+
+        >>> G = nx.DiGraph()
+        >>> G.add_edge(0, 1)
+        >>> G.add_edge(1, 0)
+        >>> G.number_of_edges(0, 1)
+        1
+
+        """
+        if u is None:
+            return int(self.size())
+        if v in self._adj[u]:
+            return 1
+        return 0
+
+    def nbunch_iter(self, nbunch=None):
+        """Returns an iterator over nodes contained in nbunch that are
+        also in the graph.
+
+        The nodes in an iterable nbunch are checked for membership in the graph
+        and if not are silently ignored.
+
+        Parameters
+        ----------
+        nbunch : single node, container, or all nodes (default= all nodes)
+            The view will only report edges incident to these nodes.
+
+        Returns
+        -------
+        niter : iterator
+            An iterator over nodes in nbunch that are also in the graph.
+            If nbunch is None, iterate over all nodes in the graph.
+
+        Raises
+        ------
+        NetworkXError
+            If nbunch is not a node or sequence of nodes.
+            If a node in nbunch is not hashable.
+
+        See Also
+        --------
+        Graph.__iter__
+
+        Notes
+        -----
+        When nbunch is an iterator, the returned iterator yields values
+        directly from nbunch, becoming exhausted when nbunch is exhausted.
+
+        To test whether nbunch is a single node, one can use
+        "if nbunch in self:", even after processing with this routine.
+
+        If nbunch is not a node or a (possibly empty) sequence/iterator
+        or None, a :exc:`NetworkXError` is raised.  Also, if any object in
+        nbunch is not hashable, a :exc:`NetworkXError` is raised.
+        """
+        if nbunch is None:  # include all nodes via iterator
+            bunch = iter(self._adj)
+        elif nbunch in self:  # if nbunch is a single node
+            bunch = iter([nbunch])
+        else:  # if nbunch is a sequence of nodes
+
+            def bunch_iter(nlist, adj):
+                try:
+                    for n in nlist:
+                        if n in adj:
+                            yield n
+                except TypeError as err:
+                    exc, message = err, err.args[0]
+                    # capture error for non-sequence/iterator nbunch.
+                    if "iter" in message:
+                        exc = NetworkXError(
+                            "nbunch is not a node or a sequence of nodes."
+                        )
+                    # capture single nodes that are not in the graph.
+                    if "object is not iterable" in message:
+                        exc = NetworkXError(f"Node {nbunch} is not in the graph.")
+                    # capture error for unhashable node.
+                    if "hashable" in message:
+                        exc = NetworkXError(
+                            f"Node {n} in sequence nbunch is not a valid node."
+                        )
+                    raise exc
+
+            bunch = bunch_iter(nbunch, self._adj)
+        return bunch
diff --git a/shared/package-files/b9/b90e152de654cf2e25672b4b8c526d272393b6cb3d65396bf8370b3b3d5d38e6/threshold.h b/shared/package-files/b9/b90e152de654cf2e25672b4b8c526d272393b6cb3d65396bf8370b3b3d5d38e6/threshold.h
new file mode 100644
index 0000000000000000000000000000000000000000..c0013de30844846ef3e7b799b4753d1e8a5f4609
--- /dev/null
+++ b/shared/package-files/b9/b90e152de654cf2e25672b4b8c526d272393b6cb3d65396bf8370b3b3d5d38e6/threshold.h
@@ -0,0 +1,45 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor
+inline at::Tensor threshold(const at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value) {
+    return at::_ops::threshold::call(self, threshold, value);
+}
+
+// aten::threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!)
+inline at::Tensor & threshold_(at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value) {
+    return at::_ops::threshold_::call(self, threshold, value);
+}
+
+// aten::threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & threshold_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value) {
+    return at::_ops::threshold_out::call(self, threshold, value, out);
+}
+// aten::threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & threshold_outf(const at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value, at::Tensor & out) {
+    return at::_ops::threshold_out::call(self, threshold, value, out);
+}
+
+}
diff --git a/shared/package-files/b9/b90e21c34a0bf1f8a9a6b388f3cb86bbe0994d87756f3db24697a74e5af80b8c/fmod.h b/shared/package-files/b9/b90e21c34a0bf1f8a9a6b388f3cb86bbe0994d87756f3db24697a74e5af80b8c/fmod.h
new file mode 100644
index 0000000000000000000000000000000000000000..0ed12956d2a5dd0c386a8128631953764453fda3
--- /dev/null
+++ b/shared/package-files/b9/b90e21c34a0bf1f8a9a6b388f3cb86bbe0994d87756f3db24697a74e5af80b8c/fmod.h
@@ -0,0 +1,54 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fmod_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) {
+    return at::_ops::fmod_Scalar_out::call(self, other, out);
+}
+// aten::fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fmod_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) {
+    return at::_ops::fmod_Scalar_out::call(self, other, out);
+}
+
+// aten::fmod.Scalar(Tensor self, Scalar other) -> Tensor
+inline at::Tensor fmod(const at::Tensor & self, const at::Scalar & other) {
+    return at::_ops::fmod_Scalar::call(self, other);
+}
+
+// aten::fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fmod_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::fmod_Tensor_out::call(self, other, out);
+}
+// aten::fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fmod_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) {
+    return at::_ops::fmod_Tensor_out::call(self, other, out);
+}
+
+// aten::fmod.Tensor(Tensor self, Tensor other) -> Tensor
+inline at::Tensor fmod(const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::fmod_Tensor::call(self, other);
+}
+
+}
diff --git a/shared/package-files/b9/b910ba29445b36344ab28036abd3281b60ccfb6f7cb3de82a1342c36758552ff/to_mkldnn_backward.h b/shared/package-files/b9/b910ba29445b36344ab28036abd3281b60ccfb6f7cb3de82a1342c36758552ff/to_mkldnn_backward.h
new file mode 100644
index 0000000000000000000000000000000000000000..fd10e5ec4fbd1ea2e396da78d4bd28941eeaa056
--- /dev/null
+++ b/shared/package-files/b9/b910ba29445b36344ab28036abd3281b60ccfb6f7cb3de82a1342c36758552ff/to_mkldnn_backward.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::to_mkldnn_backward(Tensor grad, Tensor input) -> Tensor
+inline at::Tensor to_mkldnn_backward(const at::Tensor & grad, const at::Tensor & input) {
+    return at::_ops::to_mkldnn_backward::call(grad, input);
+}
+
+}
diff --git a/shared/package-files/b9/b910f604b42b8f452d00574ca3007b5884095538119c28618c37f9ba33aeeb25/sample.c.pysam.c b/shared/package-files/b9/b910f604b42b8f452d00574ca3007b5884095538119c28618c37f9ba33aeeb25/sample.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..8b39a90f35846af5454d55010aa59c40e4317b3f
--- /dev/null
+++ b/shared/package-files/b9/b910f604b42b8f452d00574ca3007b5884095538119c28618c37f9ba33aeeb25/sample.c.pysam.c
@@ -0,0 +1,136 @@
+#include "samtools.pysam.h"
+
+/*  sample.c -- group data by sample.
+
+    Copyright (C) 2010, 2011 Broad Institute.
+    Copyright (C) 2013 Genome Research Ltd.
+
+    Author: Heng Li 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#include 
+
+#include 
+#include 
+#include "sample.h"
+#include "htslib/khash.h"
+KHASH_MAP_INIT_STR(sm, int)
+
+bam_sample_t *bam_smpl_init(void)
+{
+    bam_sample_t *s;
+    s = calloc(1, sizeof(bam_sample_t));
+    s->rg2smid = kh_init(sm);
+    s->sm2id = kh_init(sm);
+    return s;
+}
+
+void bam_smpl_destroy(bam_sample_t *sm)
+{
+    int i;
+    khint_t k;
+    khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid;
+    if (sm == 0) return;
+    for (i = 0; i < sm->n; ++i) free(sm->smpl[i]);
+    free(sm->smpl);
+    for (k = kh_begin(rg2smid); k != kh_end(rg2smid); ++k)
+        if (kh_exist(rg2smid, k)) free((char*)kh_key(rg2smid, k));
+    kh_destroy(sm, sm->rg2smid);
+    kh_destroy(sm, sm->sm2id);
+    free(sm);
+}
+
+static void add_pair(bam_sample_t *sm, khash_t(sm) *sm2id, const char *key, const char *val)
+{
+    khint_t k_rg, k_sm;
+    int ret;
+    khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid;
+    k_rg = kh_get(sm, rg2smid, key);
+    if (k_rg != kh_end(rg2smid)) return; // duplicated @RG-ID
+    k_rg = kh_put(sm, rg2smid, strdup(key), &ret);
+    k_sm = kh_get(sm, sm2id, val);
+    if (k_sm == kh_end(sm2id)) { // absent
+        if (sm->n == sm->m) {
+            sm->m = sm->m? sm->m<<1 : 1;
+            sm->smpl = realloc(sm->smpl, sizeof(char*) * sm->m);
+        }
+        sm->smpl[sm->n] = strdup(val);
+        k_sm = kh_put(sm, sm2id, sm->smpl[sm->n], &ret);
+        kh_val(sm2id, k_sm) = sm->n++;
+    }
+    kh_val(rg2smid, k_rg) = kh_val(sm2id, k_sm);
+}
+
+int bam_smpl_add(bam_sample_t *sm, const char *fn, const char *txt)
+{
+    const char *p = txt, *q, *r;
+    kstring_t buf, first_sm;
+    int n = 0;
+    khash_t(sm) *sm2id = (khash_t(sm)*)sm->sm2id;
+    if (txt == 0) {
+        add_pair(sm, sm2id, fn, fn);
+        return 0;
+    }
+    memset(&buf, 0, sizeof(kstring_t));
+    memset(&first_sm, 0, sizeof(kstring_t));
+    while ((q = strstr(p, "@RG")) != 0) {
+        p = q + 3;
+        r = q = 0;
+        if ((q = strstr(p, "\tID:")) != 0) q += 4;
+        if ((r = strstr(p, "\tSM:")) != 0) r += 4;
+        if (r && q) {
+            char *u, *v;
+            int oq, or;
+            for (u = (char*)q; *u && *u != '\t' && *u != '\n'; ++u);
+            for (v = (char*)r; *v && *v != '\t' && *v != '\n'; ++v);
+            oq = *u; or = *v; *u = *v = '\0';
+            buf.l = 0; kputs(fn, &buf); kputc('/', &buf); kputs(q, &buf);
+            add_pair(sm, sm2id, buf.s, r);
+            if ( !first_sm.s )
+                kputs(r,&first_sm);
+            *u = oq; *v = or;
+        } else break;
+        p = q > r? q : r;
+        ++n;
+    }
+    if (n == 0) add_pair(sm, sm2id, fn, fn);
+    // If there is only one RG tag present in the header and reads are not annotated, don't refuse to work but
+    //  use the tag instead.
+    else if ( n==1 && first_sm.s )
+        add_pair(sm,sm2id,fn,first_sm.s);
+    if ( first_sm.s )
+        free(first_sm.s);
+
+//  add_pair(sm, sm2id, fn, fn);
+    free(buf.s);
+    return 0;
+}
+
+int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str)
+{
+    khint_t k;
+    khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid;
+    if (rg) {
+        str->l = 0;
+        kputs(fn, str); kputc('/', str); kputs(rg, str);
+        k = kh_get(sm, rg2smid, str->s);
+    } else k = kh_get(sm, rg2smid, fn);
+    return k == kh_end(rg2smid)? -1 : kh_val(rg2smid, k);
+}
diff --git a/shared/package-files/b9/b913ea0b86f9ae85077246351b1f36cf20bd8eafc7084877d8088276a0268ef9/test_expanders.py b/shared/package-files/b9/b913ea0b86f9ae85077246351b1f36cf20bd8eafc7084877d8088276a0268ef9/test_expanders.py
new file mode 100644
index 0000000000000000000000000000000000000000..7584c286540ec4f2e73243e92a8508657caa872a
--- /dev/null
+++ b/shared/package-files/b9/b913ea0b86f9ae85077246351b1f36cf20bd8eafc7084877d8088276a0268ef9/test_expanders.py
@@ -0,0 +1,171 @@
+"""Unit tests for the :mod:`networkx.generators.expanders` module."""
+
+import pytest
+
+import networkx as nx
+
+
+@pytest.mark.parametrize("n", (2, 3, 5, 6, 10))
+def test_margulis_gabber_galil_graph_properties(n):
+    g = nx.margulis_gabber_galil_graph(n)
+    assert g.number_of_nodes() == n * n
+    for node in g:
+        assert g.degree(node) == 8
+        assert len(node) == 2
+        for i in node:
+            assert int(i) == i
+            assert 0 <= i < n
+
+
+@pytest.mark.parametrize("n", (2, 3, 5, 6, 10))
+def test_margulis_gabber_galil_graph_eigvals(n):
+    np = pytest.importorskip("numpy")
+    sp = pytest.importorskip("scipy")
+
+    g = nx.margulis_gabber_galil_graph(n)
+    # Eigenvalues are already sorted using the scipy eigvalsh,
+    # but the implementation in numpy does not guarantee order.
+    w = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(g).toarray()))
+    assert w[-2] < 5 * np.sqrt(2)
+
+
+@pytest.mark.parametrize("p", (3, 5, 7, 11))  # Primes
+def test_chordal_cycle_graph(p):
+    """Test for the :func:`networkx.chordal_cycle_graph` function."""
+    G = nx.chordal_cycle_graph(p)
+    assert len(G) == p
+    # TODO The second largest eigenvalue should be smaller than a constant,
+    # independent of the number of nodes in the graph:
+    #
+    #     eigs = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(G).toarray()))
+    #     assert_less(eigs[-2], ...)
+    #
+
+
+@pytest.mark.parametrize("p", (3, 5, 7, 11, 13))  # Primes
+def test_paley_graph(p):
+    """Test for the :func:`networkx.paley_graph` function."""
+    G = nx.paley_graph(p)
+    # G has p nodes
+    assert len(G) == p
+    # G is (p-1)/2-regular
+    in_degrees = {G.in_degree(node) for node in G.nodes}
+    out_degrees = {G.out_degree(node) for node in G.nodes}
+    assert len(in_degrees) == 1 and in_degrees.pop() == (p - 1) // 2
+    assert len(out_degrees) == 1 and out_degrees.pop() == (p - 1) // 2
+
+    # If p = 1 mod 4, -1 is a square mod 4 and therefore the
+    # edge in the Paley graph are symmetric.
+    if p % 4 == 1:
+        for u, v in G.edges:
+            assert (v, u) in G.edges
+
+
+@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16)])
+def test_maybe_regular_expander(d, n):
+    pytest.importorskip("numpy")
+    G = nx.maybe_regular_expander(n, d, seed=1729)
+
+    assert len(G) == n, "Should have n nodes"
+    assert len(G.edges) == n * d / 2, "Should have n*d/2 edges"
+    assert nx.is_k_regular(G, d), "Should be d-regular"
+
+
+def test_maybe_regular_expander_max_tries():
+    pytest.importorskip("numpy")
+    d, n = 4, 10
+    msg = "Too many iterations in maybe_regular_expander"
+    with pytest.raises(nx.NetworkXError, match=msg):
+        nx.maybe_regular_expander(n, d, max_tries=100, seed=6818)  # See gh-8048
+
+    nx.maybe_regular_expander(n, d, max_tries=130, seed=6818)
+
+
+@pytest.mark.parametrize("n", (3, 5, 6, 10))
+def test_is_regular_expander(n):
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.complete_graph(n)
+
+    assert nx.is_regular_expander(G), "Should be a regular expander"
+
+
+@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16), (4, 2000)])
+def test_random_regular_expander(d, n):
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.random_regular_expander_graph(n, d, seed=1729)
+
+    assert len(G) == n, "Should have n nodes"
+    assert len(G.edges) == n * d / 2, "Should have n*d/2 edges"
+    assert nx.is_k_regular(G, d), "Should be d-regular"
+    assert nx.is_regular_expander(G), "Should be a regular expander"
+
+
+def test_random_regular_expander_explicit_construction():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+    G = nx.random_regular_expander_graph(d=4, n=5, seed=1729)
+
+    assert len(G) == 5 and len(G.edges) == 10, "Should be a complete graph"
+
+
+@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph))
+def test_margulis_gabber_galil_graph_badinput(graph_type):
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` must be an undirected multigraph"
+    ):
+        nx.margulis_gabber_galil_graph(3, create_using=graph_type)
+
+
+@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph))
+def test_chordal_cycle_graph_badinput(graph_type):
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` must be an undirected multigraph"
+    ):
+        nx.chordal_cycle_graph(3, create_using=graph_type)
+
+
+def test_paley_graph_badinput():
+    with pytest.raises(
+        nx.NetworkXError, match="`create_using` cannot be a multigraph."
+    ):
+        nx.paley_graph(3, create_using=nx.MultiGraph)
+
+
+def test_maybe_regular_expander_badinput():
+    pytest.importorskip("numpy")
+
+    with pytest.raises(nx.NetworkXError, match="n must be a positive integer"):
+        nx.maybe_regular_expander(n=-1, d=2)
+
+    with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"):
+        nx.maybe_regular_expander(n=10, d=0)
+
+    with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"):
+        nx.maybe_regular_expander(n=5, d=6)
+
+
+def test_is_regular_expander_badinput():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+
+    with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"):
+        nx.is_regular_expander(nx.Graph(), epsilon=-1)
+
+
+def test_random_regular_expander_badinput():
+    pytest.importorskip("numpy")
+    pytest.importorskip("scipy")
+
+    with pytest.raises(nx.NetworkXError, match="n must be a positive integer"):
+        nx.random_regular_expander_graph(n=-1, d=2)
+
+    with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"):
+        nx.random_regular_expander_graph(n=10, d=0)
+
+    with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"):
+        nx.random_regular_expander_graph(n=5, d=6)
+
+    with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"):
+        nx.random_regular_expander_graph(n=4, d=2, epsilon=-1)
diff --git a/shared/package-files/b9/b915dc6608a36c5eb808256fc53c45d51ae71063d5d4d771b49378409fdb7514/_foreach_minimum_ops.h b/shared/package-files/b9/b915dc6608a36c5eb808256fc53c45d51ae71063d5d4d771b49378409fdb7514/_foreach_minimum_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..d587c22cfd262911695cf69c4b14c58c5bc78d0d
--- /dev/null
+++ b/shared/package-files/b9/b915dc6608a36c5eb808256fc53c45d51ae71063d5d4d771b49378409fdb7514/_foreach_minimum_ops.h
@@ -0,0 +1,117 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _foreach_minimum_Scalar {
+  using schema = ::std::vector (at::TensorList, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "_foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]";
+  static ::std::vector call(at::TensorList self, const at::Scalar & scalar);
+  static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
+};
+
+struct TORCH_API _foreach_minimum__Scalar {
+  using schema = void (at::TensorList, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum_";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "_foreach_minimum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()";
+  static void call(at::TensorList self, const at::Scalar & scalar);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
+};
+
+struct TORCH_API _foreach_minimum_List {
+  using schema = ::std::vector (at::TensorList, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "List";
+  static constexpr const char* schema_str = "_foreach_minimum.List(Tensor[] self, Tensor[] other) -> Tensor[]";
+  static ::std::vector call(at::TensorList self, at::TensorList other);
+  static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
+};
+
+struct TORCH_API _foreach_minimum__List {
+  using schema = void (at::TensorList, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum_";
+  static constexpr const char* overload_name = "List";
+  static constexpr const char* schema_str = "_foreach_minimum_.List(Tensor(a!)[] self, Tensor[] other) -> ()";
+  static void call(at::TensorList self, at::TensorList other);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
+};
+
+struct TORCH_API _foreach_minimum_ScalarList {
+  using schema = ::std::vector (at::TensorList, at::ArrayRef);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "ScalarList";
+  static constexpr const char* schema_str = "_foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]";
+  static ::std::vector call(at::TensorList self, at::ArrayRef scalars);
+  static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars);
+};
+
+struct TORCH_API _foreach_minimum__ScalarList {
+  using schema = void (at::TensorList, at::ArrayRef);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum_";
+  static constexpr const char* overload_name = "ScalarList";
+  static constexpr const char* schema_str = "_foreach_minimum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()";
+  static void call(at::TensorList self, at::ArrayRef scalars);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars);
+};
+
+struct TORCH_API _foreach_minimum_Scalar_out {
+  using schema = void (at::TensorList, const at::Scalar &, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "Scalar_out";
+  static constexpr const char* schema_str = "_foreach_minimum.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()";
+  static void call(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar, at::TensorList out);
+};
+
+struct TORCH_API _foreach_minimum_List_out {
+  using schema = void (at::TensorList, at::TensorList, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "List_out";
+  static constexpr const char* schema_str = "_foreach_minimum.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()";
+  static void call(at::TensorList self, at::TensorList other, at::TensorList out);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, at::TensorList out);
+};
+
+struct TORCH_API _foreach_minimum_ScalarList_out {
+  using schema = void (at::TensorList, at::ArrayRef, at::TensorList);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_foreach_minimum";
+  static constexpr const char* overload_name = "ScalarList_out";
+  static constexpr const char* schema_str = "_foreach_minimum.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()";
+  static void call(at::TensorList self, at::ArrayRef scalars, at::TensorList out);
+  static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars, at::TensorList out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b9163769212daaeb8bfe4f61a44025951554e44d1a02699958186a4a2f0c6b56/special_bessel_y0.h b/shared/package-files/b9/b9163769212daaeb8bfe4f61a44025951554e44d1a02699958186a4a2f0c6b56/special_bessel_y0.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0c3615a99381932d0438f82e0d5e3ca347e17dc
--- /dev/null
+++ b/shared/package-files/b9/b9163769212daaeb8bfe4f61a44025951554e44d1a02699958186a4a2f0c6b56/special_bessel_y0.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::special_bessel_y0(Tensor self) -> Tensor
+inline at::Tensor special_bessel_y0(const at::Tensor & self) {
+    return at::_ops::special_bessel_y0::call(self);
+}
+
+// aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & special_bessel_y0_out(at::Tensor & out, const at::Tensor & self) {
+    return at::_ops::special_bessel_y0_out::call(self, out);
+}
+// aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & special_bessel_y0_outf(const at::Tensor & self, at::Tensor & out) {
+    return at::_ops::special_bessel_y0_out::call(self, out);
+}
+
+}
diff --git a/shared/package-files/b9/b91eb48ffa33404ed69d48527b51b17b2d1ce2b004b649f3d1b9a13bc2194e2c/_redistribute.cpython-311.pyc b/shared/package-files/b9/b91eb48ffa33404ed69d48527b51b17b2d1ce2b004b649f3d1b9a13bc2194e2c/_redistribute.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3b73ddeb05ee0c03842494696f8fe98318c704a
Binary files /dev/null and b/shared/package-files/b9/b91eb48ffa33404ed69d48527b51b17b2d1ce2b004b649f3d1b9a13bc2194e2c/_redistribute.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b928cdbf27cf3346e360e59f1d3b11e22993f554502f9eebf0c1eea5aaa98905/test_select.cpython-311.pyc b/shared/package-files/b9/b928cdbf27cf3346e360e59f1d3b11e22993f554502f9eebf0c1eea5aaa98905/test_select.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30a12652d67ee1c5b84743e0ad168ce4f2562b1e
Binary files /dev/null and b/shared/package-files/b9/b928cdbf27cf3346e360e59f1d3b11e22993f554502f9eebf0c1eea5aaa98905/test_select.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b92a38c6c9fce105119e61aba109b0437a33a57d3dc916dc8cd356323923105a/collect_metadata_analysis.cpython-311.pyc b/shared/package-files/b9/b92a38c6c9fce105119e61aba109b0437a33a57d3dc916dc8cd356323923105a/collect_metadata_analysis.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be05197030972d184968260b7875aa8b16a334d0
Binary files /dev/null and b/shared/package-files/b9/b92a38c6c9fce105119e61aba109b0437a33a57d3dc916dc8cd356323923105a/collect_metadata_analysis.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b92a94a46aadfc577bca1901deebd46c8f94aa7aa6e4915cff61b2d367617e3b/faulty_rpc_agent_test_fixture.cpython-311.pyc b/shared/package-files/b9/b92a94a46aadfc577bca1901deebd46c8f94aa7aa6e4915cff61b2d367617e3b/faulty_rpc_agent_test_fixture.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..486934ea8c1b96935ba3fdd79dac9f14e028dfbf
Binary files /dev/null and b/shared/package-files/b9/b92a94a46aadfc577bca1901deebd46c8f94aa7aa6e4915cff61b2d367617e3b/faulty_rpc_agent_test_fixture.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b92fd06a24e3ffcadc0cfe3134301132815d9c6ba063b91c1f24300b921fb627/test_pring.cpython-311.pyc b/shared/package-files/b9/b92fd06a24e3ffcadc0cfe3134301132815d9c6ba063b91c1f24300b921fb627/test_pring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a0962053a8be862850dbbb6ec7696e88b406c80
Binary files /dev/null and b/shared/package-files/b9/b92fd06a24e3ffcadc0cfe3134301132815d9c6ba063b91c1f24300b921fb627/test_pring.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b931a2d452db89ab9e1f79d59b66ce194dbd6748049cfe44699726da52b9c956/random.py b/shared/package-files/b9/b931a2d452db89ab9e1f79d59b66ce194dbd6748049cfe44699726da52b9c956/random.py
new file mode 100644
index 0000000000000000000000000000000000000000..d07fffba60945418dfb55702b9d3f0d02af16360
--- /dev/null
+++ b/shared/package-files/b9/b931a2d452db89ab9e1f79d59b66ce194dbd6748049cfe44699726da52b9c956/random.py
@@ -0,0 +1,904 @@
+"""Random variable generators.
+
+    bytes
+    -----
+           uniform bytes (values between 0 and 255)
+
+    integers
+    --------
+           uniform within range
+
+    sequences
+    ---------
+           pick random element
+           pick random sample
+           pick weighted random sample
+           generate random permutation
+
+    distributions on the real line:
+    ------------------------------
+           uniform
+           triangular
+           normal (Gaussian)
+           lognormal
+           negative exponential
+           gamma
+           beta
+           pareto
+           Weibull
+
+    distributions on the circle (angles 0 to 2pi)
+    ---------------------------------------------
+           circular uniform
+           von Mises
+
+General notes on the underlying Mersenne Twister core generator:
+
+* The period is 2**19937-1.
+* It is one of the most extensively tested generators in existence.
+* The random() method is implemented in C, executes in a single Python step,
+  and is, therefore, threadsafe.
+
+"""
+
+# Translated by Guido van Rossum from C source provided by
+# Adrian Baddeley.  Adapted by Raymond Hettinger for use with
+# the Mersenne Twister  and os.urandom() core generators.
+
+from warnings import warn as _warn
+from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
+from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
+from math import tau as TWOPI, floor as _floor, isfinite as _isfinite
+from os import urandom as _urandom
+from _collections_abc import Set as _Set, Sequence as _Sequence
+from operator import index as _index
+from itertools import accumulate as _accumulate, repeat as _repeat
+from bisect import bisect as _bisect
+import os as _os
+import _random
+
+try:
+    # hashlib is pretty heavy to load, try lean internal module first
+    from _sha512 import sha512 as _sha512
+except ImportError:
+    # fallback to official implementation
+    from hashlib import sha512 as _sha512
+
+__all__ = [
+    "Random",
+    "SystemRandom",
+    "betavariate",
+    "choice",
+    "choices",
+    "expovariate",
+    "gammavariate",
+    "gauss",
+    "getrandbits",
+    "getstate",
+    "lognormvariate",
+    "normalvariate",
+    "paretovariate",
+    "randbytes",
+    "randint",
+    "random",
+    "randrange",
+    "sample",
+    "seed",
+    "setstate",
+    "shuffle",
+    "triangular",
+    "uniform",
+    "vonmisesvariate",
+    "weibullvariate",
+]
+
+NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
+LOG4 = _log(4.0)
+SG_MAGICCONST = 1.0 + _log(4.5)
+BPF = 53        # Number of bits in a float
+RECIP_BPF = 2 ** -BPF
+_ONE = 1
+
+
+class Random(_random.Random):
+    """Random number generator base class used by bound module functions.
+
+    Used to instantiate instances of Random to get generators that don't
+    share state.
+
+    Class Random can also be subclassed if you want to use a different basic
+    generator of your own devising: in that case, override the following
+    methods:  random(), seed(), getstate(), and setstate().
+    Optionally, implement a getrandbits() method so that randrange()
+    can cover arbitrarily large ranges.
+
+    """
+
+    VERSION = 3     # used by getstate/setstate
+
+    def __init__(self, x=None):
+        """Initialize an instance.
+
+        Optional argument x controls seeding, as for Random.seed().
+        """
+
+        self.seed(x)
+        self.gauss_next = None
+
+    def seed(self, a=None, version=2):
+        """Initialize internal state from a seed.
+
+        The only supported seed types are None, int, float,
+        str, bytes, and bytearray.
+
+        None or no argument seeds from current time or from an operating
+        system specific randomness source if available.
+
+        If *a* is an int, all bits are used.
+
+        For version 2 (the default), all of the bits are used if *a* is a str,
+        bytes, or bytearray.  For version 1 (provided for reproducing random
+        sequences from older versions of Python), the algorithm for str and
+        bytes generates a narrower range of seeds.
+
+        """
+
+        if version == 1 and isinstance(a, (str, bytes)):
+            a = a.decode('latin-1') if isinstance(a, bytes) else a
+            x = ord(a[0]) << 7 if a else 0
+            for c in map(ord, a):
+                x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
+            x ^= len(a)
+            a = -2 if x == -1 else x
+
+        elif version == 2 and isinstance(a, (str, bytes, bytearray)):
+            if isinstance(a, str):
+                a = a.encode()
+            a = int.from_bytes(a + _sha512(a).digest())
+
+        elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
+            raise TypeError('The only supported seed types are: None,\n'
+                            'int, float, str, bytes, and bytearray.')
+
+        super().seed(a)
+        self.gauss_next = None
+
+    def getstate(self):
+        """Return internal state; can be passed to setstate() later."""
+        return self.VERSION, super().getstate(), self.gauss_next
+
+    def setstate(self, state):
+        """Restore internal state from object returned by getstate()."""
+        version = state[0]
+        if version == 3:
+            version, internalstate, self.gauss_next = state
+            super().setstate(internalstate)
+        elif version == 2:
+            version, internalstate, self.gauss_next = state
+            # In version 2, the state was saved as signed ints, which causes
+            #   inconsistencies between 32/64-bit systems. The state is
+            #   really unsigned 32-bit ints, so we convert negative ints from
+            #   version 2 to positive longs for version 3.
+            try:
+                internalstate = tuple(x % (2 ** 32) for x in internalstate)
+            except ValueError as e:
+                raise TypeError from e
+            super().setstate(internalstate)
+        else:
+            raise ValueError("state with version %s passed to "
+                             "Random.setstate() of version %s" %
+                             (version, self.VERSION))
+
+
+    ## -------------------------------------------------------
+    ## ---- Methods below this point do not need to be overridden or extended
+    ## ---- when subclassing for the purpose of using a different core generator.
+
+
+    ## -------------------- pickle support  -------------------
+
+    # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
+    # longer called; we leave it here because it has been here since random was
+    # rewritten back in 2001 and why risk breaking something.
+    def __getstate__(self):  # for pickle
+        return self.getstate()
+
+    def __setstate__(self, state):  # for pickle
+        self.setstate(state)
+
+    def __reduce__(self):
+        return self.__class__, (), self.getstate()
+
+
+    ## ---- internal support method for evenly distributed integers ----
+
+    def __init_subclass__(cls, /, **kwargs):
+        """Control how subclasses generate random integers.
+
+        The algorithm a subclass can use depends on the random() and/or
+        getrandbits() implementation available to it and determines
+        whether it can generate random integers from arbitrarily large
+        ranges.
+        """
+
+        for c in cls.__mro__:
+            if '_randbelow' in c.__dict__:
+                # just inherit it
+                break
+            if 'getrandbits' in c.__dict__:
+                cls._randbelow = cls._randbelow_with_getrandbits
+                break
+            if 'random' in c.__dict__:
+                cls._randbelow = cls._randbelow_without_getrandbits
+                break
+
+    def _randbelow_with_getrandbits(self, n):
+        "Return a random int in the range [0,n).  Defined for n > 0."
+
+        getrandbits = self.getrandbits
+        k = n.bit_length()  # don't use (n-1) here because n can be 1
+        r = getrandbits(k)  # 0 <= r < 2**k
+        while r >= n:
+            r = getrandbits(k)
+        return r
+
+    def _randbelow_without_getrandbits(self, n, maxsize=1< 0.
+
+        The implementation does not use getrandbits, but only random.
+        """
+
+        random = self.random
+        if n >= maxsize:
+            _warn("Underlying random() generator does not supply \n"
+                "enough bits to choose from a population range this large.\n"
+                "To remove the range limitation, add a getrandbits() method.")
+            return _floor(random() * n)
+        rem = maxsize % n
+        limit = (maxsize - rem) / maxsize   # int(limit * maxsize) % n == 0
+        r = random()
+        while r >= limit:
+            r = random()
+        return _floor(r * maxsize) % n
+
+    _randbelow = _randbelow_with_getrandbits
+
+
+    ## --------------------------------------------------------
+    ## ---- Methods below this point generate custom distributions
+    ## ---- based on the methods defined above.  They do not
+    ## ---- directly touch the underlying generator and only
+    ## ---- access randomness through the methods:  random(),
+    ## ---- getrandbits(), or _randbelow().
+
+
+    ## -------------------- bytes methods ---------------------
+
+    def randbytes(self, n):
+        """Generate n random bytes."""
+        return self.getrandbits(n * 8).to_bytes(n, 'little')
+
+
+    ## -------------------- integer methods  -------------------
+
+    def randrange(self, start, stop=None, step=_ONE):
+        """Choose a random item from range(stop) or range(start, stop[, step]).
+
+        Roughly equivalent to ``choice(range(start, stop, step))`` but
+        supports arbitrarily large ranges and is optimized for common cases.
+
+        """
+
+        # This code is a bit messy to make it fast for the
+        # common case while still doing adequate error checking.
+        try:
+            istart = _index(start)
+        except TypeError:
+            istart = int(start)
+            if istart != start:
+                _warn('randrange() will raise TypeError in the future',
+                      DeprecationWarning, 2)
+                raise ValueError("non-integer arg 1 for randrange()")
+            _warn('non-integer arguments to randrange() have been deprecated '
+                  'since Python 3.10 and will be removed in a subsequent '
+                  'version',
+                  DeprecationWarning, 2)
+        if stop is None:
+            # We don't check for "step != 1" because it hasn't been
+            # type checked and converted to an integer yet.
+            if step is not _ONE:
+                raise TypeError('Missing a non-None stop argument')
+            if istart > 0:
+                return self._randbelow(istart)
+            raise ValueError("empty range for randrange()")
+
+        # stop argument supplied.
+        try:
+            istop = _index(stop)
+        except TypeError:
+            istop = int(stop)
+            if istop != stop:
+                _warn('randrange() will raise TypeError in the future',
+                      DeprecationWarning, 2)
+                raise ValueError("non-integer stop for randrange()")
+            _warn('non-integer arguments to randrange() have been deprecated '
+                  'since Python 3.10 and will be removed in a subsequent '
+                  'version',
+                  DeprecationWarning, 2)
+        width = istop - istart
+        try:
+            istep = _index(step)
+        except TypeError:
+            istep = int(step)
+            if istep != step:
+                _warn('randrange() will raise TypeError in the future',
+                      DeprecationWarning, 2)
+                raise ValueError("non-integer step for randrange()")
+            _warn('non-integer arguments to randrange() have been deprecated '
+                  'since Python 3.10 and will be removed in a subsequent '
+                  'version',
+                  DeprecationWarning, 2)
+        # Fast path.
+        if istep == 1:
+            if width > 0:
+                return istart + self._randbelow(width)
+            raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
+
+        # Non-unit step argument supplied.
+        if istep > 0:
+            n = (width + istep - 1) // istep
+        elif istep < 0:
+            n = (width + istep + 1) // istep
+        else:
+            raise ValueError("zero step for randrange()")
+        if n <= 0:
+            raise ValueError("empty range for randrange()")
+        return istart + istep * self._randbelow(n)
+
+    def randint(self, a, b):
+        """Return random integer in range [a, b], including both end points.
+        """
+
+        return self.randrange(a, b+1)
+
+
+    ## -------------------- sequence methods  -------------------
+
+    def choice(self, seq):
+        """Choose a random element from a non-empty sequence."""
+
+        # As an accommodation for NumPy, we don't use "if not seq"
+        # because bool(numpy.array()) raises a ValueError.
+        if not len(seq):
+            raise IndexError('Cannot choose from an empty sequence')
+        return seq[self._randbelow(len(seq))]
+
+    def shuffle(self, x):
+        """Shuffle list x in place, and return None."""
+
+        randbelow = self._randbelow
+        for i in reversed(range(1, len(x))):
+            # pick an element in x[:i+1] with which to exchange x[i]
+            j = randbelow(i + 1)
+            x[i], x[j] = x[j], x[i]
+
+    def sample(self, population, k, *, counts=None):
+        """Chooses k unique random elements from a population sequence.
+
+        Returns a new list containing elements from the population while
+        leaving the original population unchanged.  The resulting list is
+        in selection order so that all sub-slices will also be valid random
+        samples.  This allows raffle winners (the sample) to be partitioned
+        into grand prize and second place winners (the subslices).
+
+        Members of the population need not be hashable or unique.  If the
+        population contains repeats, then each occurrence is a possible
+        selection in the sample.
+
+        Repeated elements can be specified one at a time or with the optional
+        counts parameter.  For example:
+
+            sample(['red', 'blue'], counts=[4, 2], k=5)
+
+        is equivalent to:
+
+            sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
+
+        To choose a sample from a range of integers, use range() for the
+        population argument.  This is especially fast and space efficient
+        for sampling from a large population:
+
+            sample(range(10000000), 60)
+
+        """
+
+        # Sampling without replacement entails tracking either potential
+        # selections (the pool) in a list or previous selections in a set.
+
+        # When the number of selections is small compared to the
+        # population, then tracking selections is efficient, requiring
+        # only a small set and an occasional reselection.  For
+        # a larger number of selections, the pool tracking method is
+        # preferred since the list takes less space than the
+        # set and it doesn't suffer from frequent reselections.
+
+        # The number of calls to _randbelow() is kept at or near k, the
+        # theoretical minimum.  This is important because running time
+        # is dominated by _randbelow() and because it extracts the
+        # least entropy from the underlying random number generators.
+
+        # Memory requirements are kept to the smaller of a k-length
+        # set or an n-length list.
+
+        # There are other sampling algorithms that do not require
+        # auxiliary memory, but they were rejected because they made
+        # too many calls to _randbelow(), making them slower and
+        # causing them to eat more entropy than necessary.
+
+        if not isinstance(population, _Sequence):
+            raise TypeError("Population must be a sequence.  "
+                            "For dicts or sets, use sorted(d).")
+        n = len(population)
+        if counts is not None:
+            cum_counts = list(_accumulate(counts))
+            if len(cum_counts) != n:
+                raise ValueError('The number of counts does not match the population')
+            total = cum_counts.pop()
+            if not isinstance(total, int):
+                raise TypeError('Counts must be integers')
+            if total <= 0:
+                raise ValueError('Total of counts must be greater than zero')
+            selections = self.sample(range(total), k=k)
+            bisect = _bisect
+            return [population[bisect(cum_counts, s)] for s in selections]
+        randbelow = self._randbelow
+        if not 0 <= k <= n:
+            raise ValueError("Sample larger than population or is negative")
+        result = [None] * k
+        setsize = 21        # size of a small set minus size of an empty list
+        if k > 5:
+            setsize += 4 ** _ceil(_log(k * 3, 4))  # table size for big sets
+        if n <= setsize:
+            # An n-length list is smaller than a k-length set.
+            # Invariant:  non-selected at pool[0 : n-i]
+            pool = list(population)
+            for i in range(k):
+                j = randbelow(n - i)
+                result[i] = pool[j]
+                pool[j] = pool[n - i - 1]  # move non-selected item into vacancy
+        else:
+            selected = set()
+            selected_add = selected.add
+            for i in range(k):
+                j = randbelow(n)
+                while j in selected:
+                    j = randbelow(n)
+                selected_add(j)
+                result[i] = population[j]
+        return result
+
+    def choices(self, population, weights=None, *, cum_weights=None, k=1):
+        """Return a k sized list of population elements chosen with replacement.
+
+        If the relative weights or cumulative weights are not specified,
+        the selections are made with equal probability.
+
+        """
+        random = self.random
+        n = len(population)
+        if cum_weights is None:
+            if weights is None:
+                floor = _floor
+                n += 0.0    # convert to float for a small speed improvement
+                return [population[floor(random() * n)] for i in _repeat(None, k)]
+            try:
+                cum_weights = list(_accumulate(weights))
+            except TypeError:
+                if not isinstance(weights, int):
+                    raise
+                k = weights
+                raise TypeError(
+                    f'The number of choices must be a keyword argument: {k=}'
+                ) from None
+        elif weights is not None:
+            raise TypeError('Cannot specify both weights and cumulative weights')
+        if len(cum_weights) != n:
+            raise ValueError('The number of weights does not match the population')
+        total = cum_weights[-1] + 0.0   # convert to float
+        if total <= 0.0:
+            raise ValueError('Total of weights must be greater than zero')
+        if not _isfinite(total):
+            raise ValueError('Total of weights must be finite')
+        bisect = _bisect
+        hi = n - 1
+        return [population[bisect(cum_weights, random() * total, 0, hi)]
+                for i in _repeat(None, k)]
+
+
+    ## -------------------- real-valued distributions  -------------------
+
+    def uniform(self, a, b):
+        "Get a random number in the range [a, b) or [a, b] depending on rounding."
+        return a + (b - a) * self.random()
+
+    def triangular(self, low=0.0, high=1.0, mode=None):
+        """Triangular distribution.
+
+        Continuous distribution bounded by given lower and upper limits,
+        and having a given mode value in-between.
+
+        http://en.wikipedia.org/wiki/Triangular_distribution
+
+        """
+        u = self.random()
+        try:
+            c = 0.5 if mode is None else (mode - low) / (high - low)
+        except ZeroDivisionError:
+            return low
+        if u > c:
+            u = 1.0 - u
+            c = 1.0 - c
+            low, high = high, low
+        return low + (high - low) * _sqrt(u * c)
+
+    def normalvariate(self, mu=0.0, sigma=1.0):
+        """Normal distribution.
+
+        mu is the mean, and sigma is the standard deviation.
+
+        """
+        # Uses Kinderman and Monahan method. Reference: Kinderman,
+        # A.J. and Monahan, J.F., "Computer generation of random
+        # variables using the ratio of uniform deviates", ACM Trans
+        # Math Software, 3, (1977), pp257-260.
+
+        random = self.random
+        while True:
+            u1 = random()
+            u2 = 1.0 - random()
+            z = NV_MAGICCONST * (u1 - 0.5) / u2
+            zz = z * z / 4.0
+            if zz <= -_log(u2):
+                break
+        return mu + z * sigma
+
+    def gauss(self, mu=0.0, sigma=1.0):
+        """Gaussian distribution.
+
+        mu is the mean, and sigma is the standard deviation.  This is
+        slightly faster than the normalvariate() function.
+
+        Not thread-safe without a lock around calls.
+
+        """
+        # When x and y are two variables from [0, 1), uniformly
+        # distributed, then
+        #
+        #    cos(2*pi*x)*sqrt(-2*log(1-y))
+        #    sin(2*pi*x)*sqrt(-2*log(1-y))
+        #
+        # are two *independent* variables with normal distribution
+        # (mu = 0, sigma = 1).
+        # (Lambert Meertens)
+        # (corrected version; bug discovered by Mike Miller, fixed by LM)
+
+        # Multithreading note: When two threads call this function
+        # simultaneously, it is possible that they will receive the
+        # same return value.  The window is very small though.  To
+        # avoid this, you have to use a lock around all calls.  (I
+        # didn't want to slow this down in the serial case by using a
+        # lock here.)
+
+        random = self.random
+        z = self.gauss_next
+        self.gauss_next = None
+        if z is None:
+            x2pi = random() * TWOPI
+            g2rad = _sqrt(-2.0 * _log(1.0 - random()))
+            z = _cos(x2pi) * g2rad
+            self.gauss_next = _sin(x2pi) * g2rad
+
+        return mu + z * sigma
+
+    def lognormvariate(self, mu, sigma):
+        """Log normal distribution.
+
+        If you take the natural logarithm of this distribution, you'll get a
+        normal distribution with mean mu and standard deviation sigma.
+        mu can have any value, and sigma must be greater than zero.
+
+        """
+        return _exp(self.normalvariate(mu, sigma))
+
+    def expovariate(self, lambd):
+        """Exponential distribution.
+
+        lambd is 1.0 divided by the desired mean.  It should be
+        nonzero.  (The parameter would be called "lambda", but that is
+        a reserved word in Python.)  Returned values range from 0 to
+        positive infinity if lambd is positive, and from negative
+        infinity to 0 if lambd is negative.
+
+        """
+        # lambd: rate lambd = 1/mean
+        # ('lambda' is a Python reserved word)
+
+        # we use 1-random() instead of random() to preclude the
+        # possibility of taking the log of zero.
+        return -_log(1.0 - self.random()) / lambd
+
+    def vonmisesvariate(self, mu, kappa):
+        """Circular data distribution.
+
+        mu is the mean angle, expressed in radians between 0 and 2*pi, and
+        kappa is the concentration parameter, which must be greater than or
+        equal to zero.  If kappa is equal to zero, this distribution reduces
+        to a uniform random angle over the range 0 to 2*pi.
+
+        """
+        # Based upon an algorithm published in: Fisher, N.I.,
+        # "Statistical Analysis of Circular Data", Cambridge
+        # University Press, 1993.
+
+        # Thanks to Magnus Kessler for a correction to the
+        # implementation of step 4.
+
+        random = self.random
+        if kappa <= 1e-6:
+            return TWOPI * random()
+
+        s = 0.5 / kappa
+        r = s + _sqrt(1.0 + s * s)
+
+        while True:
+            u1 = random()
+            z = _cos(_pi * u1)
+
+            d = z / (r + z)
+            u2 = random()
+            if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
+                break
+
+        q = 1.0 / r
+        f = (q + z) / (1.0 + q * z)
+        u3 = random()
+        if u3 > 0.5:
+            theta = (mu + _acos(f)) % TWOPI
+        else:
+            theta = (mu - _acos(f)) % TWOPI
+
+        return theta
+
+    def gammavariate(self, alpha, beta):
+        """Gamma distribution.  Not the gamma function!
+
+        Conditions on the parameters are alpha > 0 and beta > 0.
+
+        The probability distribution function is:
+
+                    x ** (alpha - 1) * math.exp(-x / beta)
+          pdf(x) =  --------------------------------------
+                      math.gamma(alpha) * beta ** alpha
+
+        """
+        # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
+
+        # Warning: a few older sources define the gamma distribution in terms
+        # of alpha > -1.0
+        if alpha <= 0.0 or beta <= 0.0:
+            raise ValueError('gammavariate: alpha and beta must be > 0.0')
+
+        random = self.random
+        if alpha > 1.0:
+
+            # Uses R.C.H. Cheng, "The generation of Gamma
+            # variables with non-integral shape parameters",
+            # Applied Statistics, (1977), 26, No. 1, p71-74
+
+            ainv = _sqrt(2.0 * alpha - 1.0)
+            bbb = alpha - LOG4
+            ccc = alpha + ainv
+
+            while True:
+                u1 = random()
+                if not 1e-7 < u1 < 0.9999999:
+                    continue
+                u2 = 1.0 - random()
+                v = _log(u1 / (1.0 - u1)) / ainv
+                x = alpha * _exp(v)
+                z = u1 * u1 * u2
+                r = bbb + ccc * v - x
+                if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
+                    return x * beta
+
+        elif alpha == 1.0:
+            # expovariate(1/beta)
+            return -_log(1.0 - random()) * beta
+
+        else:
+            # alpha is between 0 and 1 (exclusive)
+            # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
+            while True:
+                u = random()
+                b = (_e + alpha) / _e
+                p = b * u
+                if p <= 1.0:
+                    x = p ** (1.0 / alpha)
+                else:
+                    x = -_log((b - p) / alpha)
+                u1 = random()
+                if p > 1.0:
+                    if u1 <= x ** (alpha - 1.0):
+                        break
+                elif u1 <= _exp(-x):
+                    break
+            return x * beta
+
+    def betavariate(self, alpha, beta):
+        """Beta distribution.
+
+        Conditions on the parameters are alpha > 0 and beta > 0.
+        Returned values range between 0 and 1.
+
+        """
+        ## See
+        ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html
+        ## for Ivan Frohne's insightful analysis of why the original implementation:
+        ##
+        ##    def betavariate(self, alpha, beta):
+        ##        # Discrete Event Simulation in C, pp 87-88.
+        ##
+        ##        y = self.expovariate(alpha)
+        ##        z = self.expovariate(1.0/beta)
+        ##        return z/(y+z)
+        ##
+        ## was dead wrong, and how it probably got that way.
+
+        # This version due to Janne Sinkkonen, and matches all the std
+        # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
+        y = self.gammavariate(alpha, 1.0)
+        if y:
+            return y / (y + self.gammavariate(beta, 1.0))
+        return 0.0
+
+    def paretovariate(self, alpha):
+        """Pareto distribution.  alpha is the shape parameter."""
+        # Jain, pg. 495
+
+        u = 1.0 - self.random()
+        return u ** (-1.0 / alpha)
+
+    def weibullvariate(self, alpha, beta):
+        """Weibull distribution.
+
+        alpha is the scale parameter and beta is the shape parameter.
+
+        """
+        # Jain, pg. 499; bug fix courtesy Bill Arms
+
+        u = 1.0 - self.random()
+        return alpha * (-_log(u)) ** (1.0 / beta)
+
+
+## ------------------------------------------------------------------
+## --------------- Operating System Random Source  ------------------
+
+
+class SystemRandom(Random):
+    """Alternate random number generator using sources provided
+    by the operating system (such as /dev/urandom on Unix or
+    CryptGenRandom on Windows).
+
+     Not available on all systems (see os.urandom() for details).
+
+    """
+
+    def random(self):
+        """Get the next random number in the range 0.0 <= X < 1.0."""
+        return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF
+
+    def getrandbits(self, k):
+        """getrandbits(k) -> x.  Generates an int with k random bits."""
+        if k < 0:
+            raise ValueError('number of bits must be non-negative')
+        numbytes = (k + 7) // 8                       # bits / 8 and rounded up
+        x = int.from_bytes(_urandom(numbytes))
+        return x >> (numbytes * 8 - k)                # trim excess bits
+
+    def randbytes(self, n):
+        """Generate n random bytes."""
+        # os.urandom(n) fails with ValueError for n < 0
+        # and returns an empty bytes string for n == 0.
+        return _urandom(n)
+
+    def seed(self, *args, **kwds):
+        "Stub method.  Not used for a system random number generator."
+        return None
+
+    def _notimplemented(self, *args, **kwds):
+        "Method should not be called for a system random number generator."
+        raise NotImplementedError('System entropy source does not have state.')
+    getstate = setstate = _notimplemented
+
+
+# ----------------------------------------------------------------------
+# Create one instance, seeded from current time, and export its methods
+# as module-level functions.  The functions share state across all uses
+# (both in the user's code and in the Python libraries), but that's fine
+# for most programs and is easier for the casual user than making them
+# instantiate their own Random() instance.
+
+_inst = Random()
+seed = _inst.seed
+random = _inst.random
+uniform = _inst.uniform
+triangular = _inst.triangular
+randint = _inst.randint
+choice = _inst.choice
+randrange = _inst.randrange
+sample = _inst.sample
+shuffle = _inst.shuffle
+choices = _inst.choices
+normalvariate = _inst.normalvariate
+lognormvariate = _inst.lognormvariate
+expovariate = _inst.expovariate
+vonmisesvariate = _inst.vonmisesvariate
+gammavariate = _inst.gammavariate
+gauss = _inst.gauss
+betavariate = _inst.betavariate
+paretovariate = _inst.paretovariate
+weibullvariate = _inst.weibullvariate
+getstate = _inst.getstate
+setstate = _inst.setstate
+getrandbits = _inst.getrandbits
+randbytes = _inst.randbytes
+
+
+## ------------------------------------------------------
+## ----------------- test program -----------------------
+
+def _test_generator(n, func, args):
+    from statistics import stdev, fmean as mean
+    from time import perf_counter
+
+    t0 = perf_counter()
+    data = [func(*args) for i in _repeat(None, n)]
+    t1 = perf_counter()
+
+    xbar = mean(data)
+    sigma = stdev(data, xbar)
+    low = min(data)
+    high = max(data)
+
+    print(f'{t1 - t0:.3f} sec, {n} times {func.__name__}')
+    print('avg %g, stddev %g, min %g, max %g\n' % (xbar, sigma, low, high))
+
+
+def _test(N=2000):
+    _test_generator(N, random, ())
+    _test_generator(N, normalvariate, (0.0, 1.0))
+    _test_generator(N, lognormvariate, (0.0, 1.0))
+    _test_generator(N, vonmisesvariate, (0.0, 1.0))
+    _test_generator(N, gammavariate, (0.01, 1.0))
+    _test_generator(N, gammavariate, (0.1, 1.0))
+    _test_generator(N, gammavariate, (0.1, 2.0))
+    _test_generator(N, gammavariate, (0.5, 1.0))
+    _test_generator(N, gammavariate, (0.9, 1.0))
+    _test_generator(N, gammavariate, (1.0, 1.0))
+    _test_generator(N, gammavariate, (2.0, 1.0))
+    _test_generator(N, gammavariate, (20.0, 1.0))
+    _test_generator(N, gammavariate, (200.0, 1.0))
+    _test_generator(N, gauss, (0.0, 1.0))
+    _test_generator(N, betavariate, (3.0, 3.0))
+    _test_generator(N, triangular, (0.0, 1.0, 1.0 / 3.0))
+
+
+## ------------------------------------------------------
+## ------------------ fork support  ---------------------
+
+if hasattr(_os, "fork"):
+    _os.register_at_fork(after_in_child=_inst.seed)
+
+
+if __name__ == '__main__':
+    _test()
diff --git a/shared/package-files/b9/b93359ca5c416815502b5b5e6323c9ed1e39fadf1aa86ea3a1e193deaca2d004/apply_optimizer_in_backward.py b/shared/package-files/b9/b93359ca5c416815502b5b5e6323c9ed1e39fadf1aa86ea3a1e193deaca2d004/apply_optimizer_in_backward.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ff9854793df1aa96a27cb105a1afd1190df942a
--- /dev/null
+++ b/shared/package-files/b9/b93359ca5c416815502b5b5e6323c9ed1e39fadf1aa86ea3a1e193deaca2d004/apply_optimizer_in_backward.py
@@ -0,0 +1,121 @@
+from collections.abc import Iterable
+from typing import Any, no_type_check
+
+import torch
+
+
+__all__: list[str] = []
+
+# WeakTensorKeyDictionary to store relevant meta-data for the Tensor/Parameter
+# without changing it's life-time.
+# NOTE: Alternative is to add the meta-data as an attribute to the tensor,
+#       but that will serialize the meta-data if Tensor is serialized.
+param_to_optim_hook_handle_map = torch.utils.weak.WeakTensorKeyDictionary()
+param_to_acc_grad_map = torch.utils.weak.WeakTensorKeyDictionary()
+
+
+@no_type_check
+def _apply_optimizer_in_backward(
+    optimizer_class: type[torch.optim.Optimizer],
+    params: Iterable[torch.nn.Parameter],
+    optimizer_kwargs: dict[str, Any],
+    register_hook: bool = True,
+) -> None:
+    """
+    Upon ``backward()``, the optimizer specified for each parameter will fire after
+    the gradient has been accumulated into the parameter.
+
+    Note - gradients for these parameters will be set to None after ``backward()``.
+    This means that any other optimizer not specified via `_apply_optimizer_in_backward`
+    over this parameter will be a no-op.
+
+    Args:
+        optimizer_class: (Type[torch.optim.Optimizer]): Optimizer to apply to parameter
+        params: (Iterator[nn.Parameter]): parameters to apply optimizer state to
+        optimizer_kwargs: (Dict[str, Any]): kwargs to pass to optimizer constructor
+        register_hook: (bool): whether to register a hook that runs the optimizer
+            after gradient for this parameter is accumulated. This is the default
+            way that optimizer in backward is implemented, but specific use cases
+            (such as DDP) may wish to override this to implement custom behavior.
+            (Default = True)
+
+    Example::
+        params_generator = model.parameters()
+        param_1 = next(params_generator)
+        remainder_params = list(params_generator)
+
+        apply_optimizer_in_backward(torch.optim.SGD, [param_1], {"lr": 0.02})
+        apply_optimizer_in_backward(torch.optim.Adam, remainder_params, {"lr": 0.04})
+
+        model(...).sum().backward()  # after backward, parameters will already
+        # have their registered optimizer(s) applied.
+
+    """
+    torch._C._log_api_usage_once("torch.distributed.optim.apply_optimizer_in_backward")
+
+    @no_type_check
+    def _apply_optimizer_in_backward_to_param(param: torch.nn.Parameter) -> None:
+        # view_as creates a node in autograd graph that allows us access to the
+        # parameter's AccumulateGrad autograd function object. We register a
+        # hook on this object to fire the optimizer when the gradient for
+        # this parameter is ready (has been accumulated into .grad field)
+
+        # Don't create a new acc_grad if we already have one
+        # i.e. for shared parameters or attaching multiple optimizers to a param.
+        if param not in param_to_acc_grad_map:
+            param_to_acc_grad_map[param] = param.view_as(param).grad_fn.next_functions[
+                0
+            ][0]
+
+        optimizer = optimizer_class([param], **optimizer_kwargs)
+
+        if not hasattr(param, "_in_backward_optimizers"):
+            param._in_backward_optimizers = []  # type: ignore[attr-defined]
+            # TODO: Remove these attributes once we have a better way of accessing
+            # optimizer classes and kwargs for a parameter.
+            param._optimizer_classes = []  # type: ignore[attr-defined]
+            param._optimizer_kwargs = []  # type: ignore[attr-defined]
+
+        param._in_backward_optimizers.append(optimizer)  # type: ignore[attr-defined]
+        param._optimizer_classes.append(optimizer_class)  # type: ignore[attr-defined]
+        param._optimizer_kwargs.append(optimizer_kwargs)  # type: ignore[attr-defined]
+
+        if not register_hook:
+            return
+
+        def optimizer_hook(*_unused) -> None:
+            for opt in param._in_backward_optimizers:  # type: ignore[attr-defined]
+                opt.step()
+
+            param.grad = None
+
+        handle = param_to_acc_grad_map[param].register_hook(optimizer_hook)  # type: ignore[attr-defined]
+        if param not in param_to_optim_hook_handle_map:
+            param_to_optim_hook_handle_map[param] = []
+        param_to_optim_hook_handle_map[param].append(handle)
+
+    for param in params:
+        _apply_optimizer_in_backward_to_param(param)
+
+
+def _get_in_backward_optimizers(module: torch.nn.Module) -> list[torch.optim.Optimizer]:
+    """
+    Return a list of in-backward optimizers applied to ``module``'s parameters. Note that these
+    optimizers are not intended to directly have their ``step`` or ``zero_grad`` methods called
+    by the user and are intended to be used for things like checkpointing.
+
+    Args:
+        module: (torch.nn.Module): model to retrieve in-backward optimizers for
+
+    Returns:
+        List[torch.optim.Optimizer]: the in-backward optimizers.
+
+    Example::
+        _apply_optimizer_in_backward(torch.optim.SGD, model.parameters(), {"lr": 0.01})
+        optims = _get_optimizers_in_backward(model)
+    """
+    optims: list[torch.optim.Optimizer] = []
+    for param in module.parameters():
+        optims.extend(getattr(param, "_in_backward_optimizers", []))
+
+    return optims
diff --git a/shared/package-files/b9/b937c21bf7bcbaf3ca0eafd37aff727a2a145b5967488c592b61e5cbcfc214e5/_header_value_parser.py b/shared/package-files/b9/b937c21bf7bcbaf3ca0eafd37aff727a2a145b5967488c592b61e5cbcfc214e5/_header_value_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..0183a1508b1219be3eef49e2de7e3dfc3f838205
--- /dev/null
+++ b/shared/package-files/b9/b937c21bf7bcbaf3ca0eafd37aff727a2a145b5967488c592b61e5cbcfc214e5/_header_value_parser.py
@@ -0,0 +1,3044 @@
+"""Header value parser implementing various email-related RFC parsing rules.
+
+The parsing methods defined in this module implement various email related
+parsing rules.  Principal among them is RFC 5322, which is the followon
+to RFC 2822 and primarily a clarification of the former.  It also implements
+RFC 2047 encoded word decoding.
+
+RFC 5322 goes to considerable trouble to maintain backward compatibility with
+RFC 822 in the parse phase, while cleaning up the structure on the generation
+phase.  This parser supports correct RFC 5322 generation by tagging white space
+as folding white space only when folding is allowed in the non-obsolete rule
+sets.  Actually, the parser is even more generous when accepting input than RFC
+5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages.
+Where possible deviations from the standard are annotated on the 'defects'
+attribute of tokens that deviate.
+
+The general structure of the parser follows RFC 5322, and uses its terminology
+where there is a direct correspondence.  Where the implementation requires a
+somewhat different structure than that used by the formal grammar, new terms
+that mimic the closest existing terms are used.  Thus, it really helps to have
+a copy of RFC 5322 handy when studying this code.
+
+Input to the parser is a string that has already been unfolded according to
+RFC 5322 rules.  According to the RFC this unfolding is the very first step, and
+this parser leaves the unfolding step to a higher level message parser, which
+will have already detected the line breaks that need unfolding while
+determining the beginning and end of each header.
+
+The output of the parser is a TokenList object, which is a list subclass.  A
+TokenList is a recursive data structure.  The terminal nodes of the structure
+are Terminal objects, which are subclasses of str.  These do not correspond
+directly to terminal objects in the formal grammar, but are instead more
+practical higher level combinations of true terminals.
+
+All TokenList and Terminal objects have a 'value' attribute, which produces the
+semantically meaningful value of that part of the parse subtree.  The value of
+all whitespace tokens (no matter how many sub-tokens they may contain) is a
+single space, as per the RFC rules.  This includes 'CFWS', which is herein
+included in the general class of whitespace tokens.  There is one exception to
+the rule that whitespace tokens are collapsed into single spaces in values: in
+the value of a 'bare-quoted-string' (a quoted-string with no leading or
+trailing whitespace), any whitespace that appeared between the quotation marks
+is preserved in the returned value.  Note that in all Terminal strings quoted
+pairs are turned into their unquoted values.
+
+All TokenList and Terminal objects also have a string value, which attempts to
+be a "canonical" representation of the RFC-compliant form of the substring that
+produced the parsed subtree, including minimal use of quoted pair quoting.
+Whitespace runs are not collapsed.
+
+Comment tokens also have a 'content' attribute providing the string found
+between the parens (including any nested comments) with whitespace preserved.
+
+All TokenList and Terminal objects have a 'defects' attribute which is a
+possibly empty list all of the defects found while creating the token.  Defects
+may appear on any token in the tree, and a composite list of all defects in the
+subtree is available through the 'all_defects' attribute of any node.  (For
+Terminal notes x.defects == x.all_defects.)
+
+Each object in a parse tree is called a 'token', and each has a 'token_type'
+attribute that gives the name from the RFC 5322 grammar that it represents.
+Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that
+may be produced: 'ptext'.  A 'ptext' is a string of printable ascii characters.
+It is returned in place of lists of (ctext/quoted-pair) and
+(qtext/quoted-pair).
+
+XXX: provide complete list of token types.
+"""
+
+import re
+import sys
+import urllib   # For urllib.parse.unquote
+from string import hexdigits
+from operator import itemgetter
+from email import _encoded_words as _ew
+from email import errors
+from email import utils
+
+#
+# Useful constants and functions
+#
+
+WSP = set(' \t')
+CFWS_LEADER = WSP | set('(')
+SPECIALS = set(r'()<>@,:;.\"[]')
+ATOM_ENDS = SPECIALS | WSP
+DOT_ATOM_ENDS = ATOM_ENDS - set('.')
+# '.', '"', and '(' do not end phrases in order to support obs-phrase
+PHRASE_ENDS = SPECIALS - set('."(')
+TSPECIALS = (SPECIALS | set('/?=')) - set('.')
+TOKEN_ENDS = TSPECIALS | WSP
+ASPECIALS = TSPECIALS | set("*'%")
+ATTRIBUTE_ENDS = ASPECIALS | WSP
+EXTENDED_ATTRIBUTE_ENDS = ATTRIBUTE_ENDS - set('%')
+NLSET = {'\n', '\r'}
+SPECIALSNL = SPECIALS | NLSET
+
+
+def make_quoted_pairs(value):
+    """Escape dquote and backslash for use within a quoted-string."""
+    return str(value).replace('\\', '\\\\').replace('"', '\\"')
+
+
+def quote_string(value):
+    escaped = make_quoted_pairs(value)
+    return f'"{escaped}"'
+
+
+# Match a RFC 2047 word, looks like =?utf-8?q?someword?=
+rfc2047_matcher = re.compile(r'''
+   =\?            # literal =?
+   [^?]*          # charset
+   \?             # literal ?
+   [qQbB]         # literal 'q' or 'b', case insensitive
+   \?             # literal ?
+  .*?             # encoded word
+  \?=             # literal ?=
+''', re.VERBOSE | re.MULTILINE)
+
+
+#
+# TokenList and its subclasses
+#
+
+class TokenList(list):
+
+    token_type = None
+    syntactic_break = True
+    ew_combine_allowed = True
+
+    def __init__(self, *args, **kw):
+        super().__init__(*args, **kw)
+        self.defects = []
+
+    def __str__(self):
+        return ''.join(str(x) for x in self)
+
+    def __repr__(self):
+        return '{}({})'.format(self.__class__.__name__,
+                             super().__repr__())
+
+    @property
+    def value(self):
+        return ''.join(x.value for x in self if x.value)
+
+    @property
+    def all_defects(self):
+        return sum((x.all_defects for x in self), self.defects)
+
+    def startswith_fws(self):
+        return self[0].startswith_fws()
+
+    @property
+    def as_ew_allowed(self):
+        """True if all top level tokens of this part may be RFC2047 encoded."""
+        return all(part.as_ew_allowed for part in self)
+
+    @property
+    def comments(self):
+        comments = []
+        for token in self:
+            comments.extend(token.comments)
+        return comments
+
+    def fold(self, *, policy):
+        return _refold_parse_tree(self, policy=policy)
+
+    def pprint(self, indent=''):
+        print(self.ppstr(indent=indent))
+
+    def ppstr(self, indent=''):
+        return '\n'.join(self._pp(indent=indent))
+
+    def _pp(self, indent=''):
+        yield '{}{}/{}('.format(
+            indent,
+            self.__class__.__name__,
+            self.token_type)
+        for token in self:
+            if not hasattr(token, '_pp'):
+                yield (indent + '    !! invalid element in token '
+                                        'list: {!r}'.format(token))
+            else:
+                yield from token._pp(indent+'    ')
+        if self.defects:
+            extra = ' Defects: {}'.format(self.defects)
+        else:
+            extra = ''
+        yield '{}){}'.format(indent, extra)
+
+
+class WhiteSpaceTokenList(TokenList):
+
+    @property
+    def value(self):
+        return ' '
+
+    @property
+    def comments(self):
+        return [x.content for x in self if x.token_type=='comment']
+
+
+class UnstructuredTokenList(TokenList):
+    token_type = 'unstructured'
+
+
+class Phrase(TokenList):
+    token_type = 'phrase'
+
+class Word(TokenList):
+    token_type = 'word'
+
+
+class CFWSList(WhiteSpaceTokenList):
+    token_type = 'cfws'
+
+
+class Atom(TokenList):
+    token_type = 'atom'
+
+
+class Token(TokenList):
+    token_type = 'token'
+    encode_as_ew = False
+
+
+class EncodedWord(TokenList):
+    token_type = 'encoded-word'
+    cte = None
+    charset = None
+    lang = None
+
+
+class QuotedString(TokenList):
+
+    token_type = 'quoted-string'
+
+    @property
+    def content(self):
+        for x in self:
+            if x.token_type == 'bare-quoted-string':
+                return x.value
+
+    @property
+    def quoted_value(self):
+        res = []
+        for x in self:
+            if x.token_type == 'bare-quoted-string':
+                res.append(str(x))
+            else:
+                res.append(x.value)
+        return ''.join(res)
+
+    @property
+    def stripped_value(self):
+        for token in self:
+            if token.token_type == 'bare-quoted-string':
+                return token.value
+
+
+class BareQuotedString(QuotedString):
+
+    token_type = 'bare-quoted-string'
+
+    def __str__(self):
+        return quote_string(''.join(str(x) for x in self))
+
+    @property
+    def value(self):
+        return ''.join(str(x) for x in self)
+
+
+class Comment(WhiteSpaceTokenList):
+
+    token_type = 'comment'
+
+    def __str__(self):
+        return ''.join(sum([
+                            ["("],
+                            [self.quote(x) for x in self],
+                            [")"],
+                            ], []))
+
+    def quote(self, value):
+        if value.token_type == 'comment':
+            return str(value)
+        return str(value).replace('\\', '\\\\').replace(
+                                  '(', r'\(').replace(
+                                  ')', r'\)')
+
+    @property
+    def content(self):
+        return ''.join(str(x) for x in self)
+
+    @property
+    def comments(self):
+        return [self.content]
+
+class AddressList(TokenList):
+
+    token_type = 'address-list'
+
+    @property
+    def addresses(self):
+        return [x for x in self if x.token_type=='address']
+
+    @property
+    def mailboxes(self):
+        return sum((x.mailboxes
+                    for x in self if x.token_type=='address'), [])
+
+    @property
+    def all_mailboxes(self):
+        return sum((x.all_mailboxes
+                    for x in self if x.token_type=='address'), [])
+
+
+class Address(TokenList):
+
+    token_type = 'address'
+
+    @property
+    def display_name(self):
+        if self[0].token_type == 'group':
+            return self[0].display_name
+
+    @property
+    def mailboxes(self):
+        if self[0].token_type == 'mailbox':
+            return [self[0]]
+        elif self[0].token_type == 'invalid-mailbox':
+            return []
+        return self[0].mailboxes
+
+    @property
+    def all_mailboxes(self):
+        if self[0].token_type == 'mailbox':
+            return [self[0]]
+        elif self[0].token_type == 'invalid-mailbox':
+            return [self[0]]
+        return self[0].all_mailboxes
+
+class MailboxList(TokenList):
+
+    token_type = 'mailbox-list'
+
+    @property
+    def mailboxes(self):
+        return [x for x in self if x.token_type=='mailbox']
+
+    @property
+    def all_mailboxes(self):
+        return [x for x in self
+            if x.token_type in ('mailbox', 'invalid-mailbox')]
+
+
+class GroupList(TokenList):
+
+    token_type = 'group-list'
+
+    @property
+    def mailboxes(self):
+        if not self or self[0].token_type != 'mailbox-list':
+            return []
+        return self[0].mailboxes
+
+    @property
+    def all_mailboxes(self):
+        if not self or self[0].token_type != 'mailbox-list':
+            return []
+        return self[0].all_mailboxes
+
+
+class Group(TokenList):
+
+    token_type = "group"
+
+    @property
+    def mailboxes(self):
+        if self[2].token_type != 'group-list':
+            return []
+        return self[2].mailboxes
+
+    @property
+    def all_mailboxes(self):
+        if self[2].token_type != 'group-list':
+            return []
+        return self[2].all_mailboxes
+
+    @property
+    def display_name(self):
+        return self[0].display_name
+
+
+class NameAddr(TokenList):
+
+    token_type = 'name-addr'
+
+    @property
+    def display_name(self):
+        if len(self) == 1:
+            return None
+        return self[0].display_name
+
+    @property
+    def local_part(self):
+        return self[-1].local_part
+
+    @property
+    def domain(self):
+        return self[-1].domain
+
+    @property
+    def route(self):
+        return self[-1].route
+
+    @property
+    def addr_spec(self):
+        return self[-1].addr_spec
+
+
+class AngleAddr(TokenList):
+
+    token_type = 'angle-addr'
+
+    @property
+    def local_part(self):
+        for x in self:
+            if x.token_type == 'addr-spec':
+                return x.local_part
+
+    @property
+    def domain(self):
+        for x in self:
+            if x.token_type == 'addr-spec':
+                return x.domain
+
+    @property
+    def route(self):
+        for x in self:
+            if x.token_type == 'obs-route':
+                return x.domains
+
+    @property
+    def addr_spec(self):
+        for x in self:
+            if x.token_type == 'addr-spec':
+                if x.local_part:
+                    return x.addr_spec
+                else:
+                    return quote_string(x.local_part) + x.addr_spec
+        else:
+            return '<>'
+
+
+class ObsRoute(TokenList):
+
+    token_type = 'obs-route'
+
+    @property
+    def domains(self):
+        return [x.domain for x in self if x.token_type == 'domain']
+
+
+class Mailbox(TokenList):
+
+    token_type = 'mailbox'
+
+    @property
+    def display_name(self):
+        if self[0].token_type == 'name-addr':
+            return self[0].display_name
+
+    @property
+    def local_part(self):
+        return self[0].local_part
+
+    @property
+    def domain(self):
+        return self[0].domain
+
+    @property
+    def route(self):
+        if self[0].token_type == 'name-addr':
+            return self[0].route
+
+    @property
+    def addr_spec(self):
+        return self[0].addr_spec
+
+
+class InvalidMailbox(TokenList):
+
+    token_type = 'invalid-mailbox'
+
+    @property
+    def display_name(self):
+        return None
+
+    local_part = domain = route = addr_spec = display_name
+
+
+class Domain(TokenList):
+
+    token_type = 'domain'
+    as_ew_allowed = False
+
+    @property
+    def domain(self):
+        return ''.join(super().value.split())
+
+
+class DotAtom(TokenList):
+    token_type = 'dot-atom'
+
+
+class DotAtomText(TokenList):
+    token_type = 'dot-atom-text'
+    as_ew_allowed = True
+
+
+class NoFoldLiteral(TokenList):
+    token_type = 'no-fold-literal'
+    as_ew_allowed = False
+
+
+class AddrSpec(TokenList):
+
+    token_type = 'addr-spec'
+    as_ew_allowed = False
+
+    @property
+    def local_part(self):
+        return self[0].local_part
+
+    @property
+    def domain(self):
+        if len(self) < 3:
+            return None
+        return self[-1].domain
+
+    @property
+    def value(self):
+        if len(self) < 3:
+            return self[0].value
+        return self[0].value.rstrip()+self[1].value+self[2].value.lstrip()
+
+    @property
+    def addr_spec(self):
+        nameset = set(self.local_part)
+        if len(nameset) > len(nameset-DOT_ATOM_ENDS):
+            lp = quote_string(self.local_part)
+        else:
+            lp = self.local_part
+        if self.domain is not None:
+            return lp + '@' + self.domain
+        return lp
+
+
+class ObsLocalPart(TokenList):
+
+    token_type = 'obs-local-part'
+    as_ew_allowed = False
+
+
+class DisplayName(Phrase):
+
+    token_type = 'display-name'
+    ew_combine_allowed = False
+
+    @property
+    def display_name(self):
+        res = TokenList(self)
+        if len(res) == 0:
+            return res.value
+        if res[0].token_type == 'cfws':
+            res.pop(0)
+        else:
+            if res[0][0].token_type == 'cfws':
+                res[0] = TokenList(res[0][1:])
+        if res[-1].token_type == 'cfws':
+            res.pop()
+        else:
+            if res[-1][-1].token_type == 'cfws':
+                res[-1] = TokenList(res[-1][:-1])
+        return res.value
+
+    @property
+    def value(self):
+        quote = False
+        if self.defects:
+            quote = True
+        else:
+            for x in self:
+                if x.token_type == 'quoted-string':
+                    quote = True
+        if len(self) != 0 and quote:
+            pre = post = ''
+            if self[0].token_type=='cfws' or self[0][0].token_type=='cfws':
+                pre = ' '
+            if self[-1].token_type=='cfws' or self[-1][-1].token_type=='cfws':
+                post = ' '
+            return pre+quote_string(self.display_name)+post
+        else:
+            return super().value
+
+
+class LocalPart(TokenList):
+
+    token_type = 'local-part'
+    as_ew_allowed = False
+
+    @property
+    def value(self):
+        if self[0].token_type == "quoted-string":
+            return self[0].quoted_value
+        else:
+            return self[0].value
+
+    @property
+    def local_part(self):
+        # Strip whitespace from front, back, and around dots.
+        res = [DOT]
+        last = DOT
+        last_is_tl = False
+        for tok in self[0] + [DOT]:
+            if tok.token_type == 'cfws':
+                continue
+            if (last_is_tl and tok.token_type == 'dot' and
+                    last[-1].token_type == 'cfws'):
+                res[-1] = TokenList(last[:-1])
+            is_tl = isinstance(tok, TokenList)
+            if (is_tl and last.token_type == 'dot' and
+                    tok[0].token_type == 'cfws'):
+                res.append(TokenList(tok[1:]))
+            else:
+                res.append(tok)
+            last = res[-1]
+            last_is_tl = is_tl
+        res = TokenList(res[1:-1])
+        return res.value
+
+
+class DomainLiteral(TokenList):
+
+    token_type = 'domain-literal'
+    as_ew_allowed = False
+
+    @property
+    def domain(self):
+        return ''.join(super().value.split())
+
+    @property
+    def ip(self):
+        for x in self:
+            if x.token_type == 'ptext':
+                return x.value
+
+
+class MIMEVersion(TokenList):
+
+    token_type = 'mime-version'
+    major = None
+    minor = None
+
+
+class Parameter(TokenList):
+
+    token_type = 'parameter'
+    sectioned = False
+    extended = False
+    charset = 'us-ascii'
+
+    @property
+    def section_number(self):
+        # Because the first token, the attribute (name) eats CFWS, the second
+        # token is always the section if there is one.
+        return self[1].number if self.sectioned else 0
+
+    @property
+    def param_value(self):
+        # This is part of the "handle quoted extended parameters" hack.
+        for token in self:
+            if token.token_type == 'value':
+                return token.stripped_value
+            if token.token_type == 'quoted-string':
+                for token in token:
+                    if token.token_type == 'bare-quoted-string':
+                        for token in token:
+                            if token.token_type == 'value':
+                                return token.stripped_value
+        return ''
+
+
+class InvalidParameter(Parameter):
+
+    token_type = 'invalid-parameter'
+
+
+class Attribute(TokenList):
+
+    token_type = 'attribute'
+
+    @property
+    def stripped_value(self):
+        for token in self:
+            if token.token_type.endswith('attrtext'):
+                return token.value
+
+class Section(TokenList):
+
+    token_type = 'section'
+    number = None
+
+
+class Value(TokenList):
+
+    token_type = 'value'
+
+    @property
+    def stripped_value(self):
+        token = self[0]
+        if token.token_type == 'cfws':
+            token = self[1]
+        if token.token_type.endswith(
+                ('quoted-string', 'attribute', 'extended-attribute')):
+            return token.stripped_value
+        return self.value
+
+
+class MimeParameters(TokenList):
+
+    token_type = 'mime-parameters'
+    syntactic_break = False
+
+    @property
+    def params(self):
+        # The RFC specifically states that the ordering of parameters is not
+        # guaranteed and may be reordered by the transport layer.  So we have
+        # to assume the RFC 2231 pieces can come in any order.  However, we
+        # output them in the order that we first see a given name, which gives
+        # us a stable __str__.
+        params = {}  # Using order preserving dict from Python 3.7+
+        for token in self:
+            if not token.token_type.endswith('parameter'):
+                continue
+            if token[0].token_type != 'attribute':
+                continue
+            name = token[0].value.strip()
+            if name not in params:
+                params[name] = []
+            params[name].append((token.section_number, token))
+        for name, parts in params.items():
+            parts = sorted(parts, key=itemgetter(0))
+            first_param = parts[0][1]
+            charset = first_param.charset
+            # Our arbitrary error recovery is to ignore duplicate parameters,
+            # to use appearance order if there are duplicate rfc 2231 parts,
+            # and to ignore gaps.  This mimics the error recovery of get_param.
+            if not first_param.extended and len(parts) > 1:
+                if parts[1][0] == 0:
+                    parts[1][1].defects.append(errors.InvalidHeaderDefect(
+                        'duplicate parameter name; duplicate(s) ignored'))
+                    parts = parts[:1]
+                # Else assume the *0* was missing...note that this is different
+                # from get_param, but we registered a defect for this earlier.
+            value_parts = []
+            i = 0
+            for section_number, param in parts:
+                if section_number != i:
+                    # We could get fancier here and look for a complete
+                    # duplicate extended parameter and ignore the second one
+                    # seen.  But we're not doing that.  The old code didn't.
+                    if not param.extended:
+                        param.defects.append(errors.InvalidHeaderDefect(
+                            'duplicate parameter name; duplicate ignored'))
+                        continue
+                    else:
+                        param.defects.append(errors.InvalidHeaderDefect(
+                            "inconsistent RFC2231 parameter numbering"))
+                i += 1
+                value = param.param_value
+                if param.extended:
+                    try:
+                        value = urllib.parse.unquote_to_bytes(value)
+                    except UnicodeEncodeError:
+                        # source had surrogate escaped bytes.  What we do now
+                        # is a bit of an open question.  I'm not sure this is
+                        # the best choice, but it is what the old algorithm did
+                        value = urllib.parse.unquote(value, encoding='latin-1')
+                    else:
+                        try:
+                            value = value.decode(charset, 'surrogateescape')
+                        except (LookupError, UnicodeEncodeError):
+                            # XXX: there should really be a custom defect for
+                            # unknown character set to make it easy to find,
+                            # because otherwise unknown charset is a silent
+                            # failure.
+                            value = value.decode('us-ascii', 'surrogateescape')
+                        if utils._has_surrogates(value):
+                            param.defects.append(errors.UndecodableBytesDefect())
+                value_parts.append(value)
+            value = ''.join(value_parts)
+            yield name, value
+
+    def __str__(self):
+        params = []
+        for name, value in self.params:
+            if value:
+                params.append('{}={}'.format(name, quote_string(value)))
+            else:
+                params.append(name)
+        params = '; '.join(params)
+        return ' ' + params if params else ''
+
+
+class ParameterizedHeaderValue(TokenList):
+
+    # Set this false so that the value doesn't wind up on a new line even
+    # if it and the parameters would fit there but not on the first line.
+    syntactic_break = False
+
+    @property
+    def params(self):
+        for token in reversed(self):
+            if token.token_type == 'mime-parameters':
+                return token.params
+        return {}
+
+
+class ContentType(ParameterizedHeaderValue):
+    token_type = 'content-type'
+    as_ew_allowed = False
+    maintype = 'text'
+    subtype = 'plain'
+
+
+class ContentDisposition(ParameterizedHeaderValue):
+    token_type = 'content-disposition'
+    as_ew_allowed = False
+    content_disposition = None
+
+
+class ContentTransferEncoding(TokenList):
+    token_type = 'content-transfer-encoding'
+    as_ew_allowed = False
+    cte = '7bit'
+
+
+class HeaderLabel(TokenList):
+    token_type = 'header-label'
+    as_ew_allowed = False
+
+
+class MsgID(TokenList):
+    token_type = 'msg-id'
+    as_ew_allowed = False
+
+    def fold(self, policy):
+        # message-id tokens may not be folded.
+        return str(self) + policy.linesep
+
+
+class MessageID(MsgID):
+    token_type = 'message-id'
+
+
+class InvalidMessageID(MessageID):
+    token_type = 'invalid-message-id'
+
+
+class Header(TokenList):
+    token_type = 'header'
+
+
+#
+# Terminal classes and instances
+#
+
+class Terminal(str):
+
+    as_ew_allowed = True
+    ew_combine_allowed = True
+    syntactic_break = True
+
+    def __new__(cls, value, token_type):
+        self = super().__new__(cls, value)
+        self.token_type = token_type
+        self.defects = []
+        return self
+
+    def __repr__(self):
+        return "{}({})".format(self.__class__.__name__, super().__repr__())
+
+    def pprint(self):
+        print(self.__class__.__name__ + '/' + self.token_type)
+
+    @property
+    def all_defects(self):
+        return list(self.defects)
+
+    def _pp(self, indent=''):
+        return ["{}{}/{}({}){}".format(
+            indent,
+            self.__class__.__name__,
+            self.token_type,
+            super().__repr__(),
+            '' if not self.defects else ' {}'.format(self.defects),
+            )]
+
+    def pop_trailing_ws(self):
+        # This terminates the recursion.
+        return None
+
+    @property
+    def comments(self):
+        return []
+
+    def __getnewargs__(self):
+        return(str(self), self.token_type)
+
+
+class WhiteSpaceTerminal(Terminal):
+
+    @property
+    def value(self):
+        return ' '
+
+    def startswith_fws(self):
+        return True
+
+
+class ValueTerminal(Terminal):
+
+    @property
+    def value(self):
+        return self
+
+    def startswith_fws(self):
+        return False
+
+
+class EWWhiteSpaceTerminal(WhiteSpaceTerminal):
+
+    @property
+    def value(self):
+        return ''
+
+    def __str__(self):
+        return ''
+
+
+class _InvalidEwError(errors.HeaderParseError):
+    """Invalid encoded word found while parsing headers."""
+
+
+# XXX these need to become classes and used as instances so
+# that a program can't change them in a parse tree and screw
+# up other parse trees.  Maybe should have  tests for that, too.
+DOT = ValueTerminal('.', 'dot')
+ListSeparator = ValueTerminal(',', 'list-separator')
+ListSeparator.as_ew_allowed = False
+ListSeparator.syntactic_break = False
+RouteComponentMarker = ValueTerminal('@', 'route-component-marker')
+
+#
+# Parser
+#
+
+# Parse strings according to RFC822/2047/2822/5322 rules.
+#
+# This is a stateless parser.  Each get_XXX function accepts a string and
+# returns either a Terminal or a TokenList representing the RFC object named
+# by the method and a string containing the remaining unparsed characters
+# from the input.  Thus a parser method consumes the next syntactic construct
+# of a given type and returns a token representing the construct plus the
+# unparsed remainder of the input string.
+#
+# For example, if the first element of a structured header is a 'phrase',
+# then:
+#
+#     phrase, value = get_phrase(value)
+#
+# returns the complete phrase from the start of the string value, plus any
+# characters left in the string after the phrase is removed.
+
+_wsp_splitter = re.compile(r'([{}]+)'.format(''.join(WSP))).split
+_non_atom_end_matcher = re.compile(r"[^{}]+".format(
+    re.escape(''.join(ATOM_ENDS)))).match
+_non_printable_finder = re.compile(r"[\x00-\x20\x7F]").findall
+_non_token_end_matcher = re.compile(r"[^{}]+".format(
+    re.escape(''.join(TOKEN_ENDS)))).match
+_non_attribute_end_matcher = re.compile(r"[^{}]+".format(
+    re.escape(''.join(ATTRIBUTE_ENDS)))).match
+_non_extended_attribute_end_matcher = re.compile(r"[^{}]+".format(
+    re.escape(''.join(EXTENDED_ATTRIBUTE_ENDS)))).match
+
+def _validate_xtext(xtext):
+    """If input token contains ASCII non-printables, register a defect."""
+
+    non_printables = _non_printable_finder(xtext)
+    if non_printables:
+        xtext.defects.append(errors.NonPrintableDefect(non_printables))
+    if utils._has_surrogates(xtext):
+        xtext.defects.append(errors.UndecodableBytesDefect(
+            "Non-ASCII characters found in header token"))
+
+def _get_ptext_to_endchars(value, endchars):
+    """Scan printables/quoted-pairs until endchars and return unquoted ptext.
+
+    This function turns a run of qcontent, ccontent-without-comments, or
+    dtext-with-quoted-printables into a single string by unquoting any
+    quoted printables.  It returns the string, the remaining value, and
+    a flag that is True iff there were any quoted printables decoded.
+
+    """
+    fragment, *remainder = _wsp_splitter(value, 1)
+    vchars = []
+    escape = False
+    had_qp = False
+    for pos in range(len(fragment)):
+        if fragment[pos] == '\\':
+            if escape:
+                escape = False
+                had_qp = True
+            else:
+                escape = True
+                continue
+        if escape:
+            escape = False
+        elif fragment[pos] in endchars:
+            break
+        vchars.append(fragment[pos])
+    else:
+        pos = pos + 1
+    return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp
+
+def get_fws(value):
+    """FWS = 1*WSP
+
+    This isn't the RFC definition.  We're using fws to represent tokens where
+    folding can be done, but when we are parsing the *un*folding has already
+    been done so we don't need to watch out for CRLF.
+
+    """
+    newvalue = value.lstrip()
+    fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws')
+    return fws, newvalue
+
+def get_encoded_word(value, terminal_type='vtext'):
+    """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
+
+    """
+    ew = EncodedWord()
+    if not value.startswith('=?'):
+        raise errors.HeaderParseError(
+            "expected encoded word but found {}".format(value))
+    tok, *remainder = value[2:].split('?=', 1)
+    if tok == value[2:]:
+        raise errors.HeaderParseError(
+            "expected encoded word but found {}".format(value))
+    remstr = ''.join(remainder)
+    if (len(remstr) > 1 and
+        remstr[0] in hexdigits and
+        remstr[1] in hexdigits and
+        tok.count('?') < 2):
+        # The ? after the CTE was followed by an encoded word escape (=XX).
+        rest, *remainder = remstr.split('?=', 1)
+        tok = tok + '?=' + rest
+    if len(tok.split()) > 1:
+        ew.defects.append(errors.InvalidHeaderDefect(
+            "whitespace inside encoded word"))
+    ew.cte = value
+    value = ''.join(remainder)
+    try:
+        text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
+    except (ValueError, KeyError):
+        raise _InvalidEwError(
+            "encoded word format invalid: '{}'".format(ew.cte))
+    ew.charset = charset
+    ew.lang = lang
+    ew.defects.extend(defects)
+    while text:
+        if text[0] in WSP:
+            token, text = get_fws(text)
+            ew.append(token)
+            continue
+        chars, *remainder = _wsp_splitter(text, 1)
+        vtext = ValueTerminal(chars, terminal_type)
+        _validate_xtext(vtext)
+        ew.append(vtext)
+        text = ''.join(remainder)
+    # Encoded words should be followed by a WS
+    if value and value[0] not in WSP:
+        ew.defects.append(errors.InvalidHeaderDefect(
+            "missing trailing whitespace after encoded-word"))
+    return ew, value
+
+def get_unstructured(value):
+    """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct
+       obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS)
+       obs-utext = %d0 / obs-NO-WS-CTL / LF / CR
+
+       obs-NO-WS-CTL is control characters except WSP/CR/LF.
+
+    So, basically, we have printable runs, plus control characters or nulls in
+    the obsolete syntax, separated by whitespace.  Since RFC 2047 uses the
+    obsolete syntax in its specification, but requires whitespace on either
+    side of the encoded words, I can see no reason to need to separate the
+    non-printable-non-whitespace from the printable runs if they occur, so we
+    parse this into xtext tokens separated by WSP tokens.
+
+    Because an 'unstructured' value must by definition constitute the entire
+    value, this 'get' routine does not return a remaining value, only the
+    parsed TokenList.
+
+    """
+    # XXX: but what about bare CR and LF?  They might signal the start or
+    # end of an encoded word.  YAGNI for now, since our current parsers
+    # will never send us strings with bare CR or LF.
+
+    unstructured = UnstructuredTokenList()
+    while value:
+        if value[0] in WSP:
+            token, value = get_fws(value)
+            unstructured.append(token)
+            continue
+        valid_ew = True
+        if value.startswith('=?'):
+            try:
+                token, value = get_encoded_word(value, 'utext')
+            except _InvalidEwError:
+                valid_ew = False
+            except errors.HeaderParseError:
+                # XXX: Need to figure out how to register defects when
+                # appropriate here.
+                pass
+            else:
+                have_ws = True
+                if len(unstructured) > 0:
+                    if unstructured[-1].token_type != 'fws':
+                        unstructured.defects.append(errors.InvalidHeaderDefect(
+                            "missing whitespace before encoded word"))
+                        have_ws = False
+                if have_ws and len(unstructured) > 1:
+                    if unstructured[-2].token_type == 'encoded-word':
+                        unstructured[-1] = EWWhiteSpaceTerminal(
+                            unstructured[-1], 'fws')
+                unstructured.append(token)
+                continue
+        tok, *remainder = _wsp_splitter(value, 1)
+        # Split in the middle of an atom if there is a rfc2047 encoded word
+        # which does not have WSP on both sides. The defect will be registered
+        # the next time through the loop.
+        # This needs to only be performed when the encoded word is valid;
+        # otherwise, performing it on an invalid encoded word can cause
+        # the parser to go in an infinite loop.
+        if valid_ew and rfc2047_matcher.search(tok):
+            tok, *remainder = value.partition('=?')
+        vtext = ValueTerminal(tok, 'utext')
+        _validate_xtext(vtext)
+        unstructured.append(vtext)
+        value = ''.join(remainder)
+    return unstructured
+
+def get_qp_ctext(value):
+    r"""ctext = 
+
+    This is not the RFC ctext, since we are handling nested comments in comment
+    and unquoting quoted-pairs here.  We allow anything except the '()'
+    characters, but if we find any ASCII other than the RFC defined printable
+    ASCII, a NonPrintableDefect is added to the token's defects list.  Since
+    quoted pairs are converted to their unquoted values, what is returned is
+    a 'ptext' token.  In this case it is a WhiteSpaceTerminal, so it's value
+    is ' '.
+
+    """
+    ptext, value, _ = _get_ptext_to_endchars(value, '()')
+    ptext = WhiteSpaceTerminal(ptext, 'ptext')
+    _validate_xtext(ptext)
+    return ptext, value
+
+def get_qcontent(value):
+    """qcontent = qtext / quoted-pair
+
+    We allow anything except the DQUOTE character, but if we find any ASCII
+    other than the RFC defined printable ASCII, a NonPrintableDefect is
+    added to the token's defects list.  Any quoted pairs are converted to their
+    unquoted values, so what is returned is a 'ptext' token.  In this case it
+    is a ValueTerminal.
+
+    """
+    ptext, value, _ = _get_ptext_to_endchars(value, '"')
+    ptext = ValueTerminal(ptext, 'ptext')
+    _validate_xtext(ptext)
+    return ptext, value
+
+def get_atext(value):
+    """atext = 
+
+    We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
+    the token's defects list if we find non-atext characters.
+    """
+    m = _non_atom_end_matcher(value)
+    if not m:
+        raise errors.HeaderParseError(
+            "expected atext but found '{}'".format(value))
+    atext = m.group()
+    value = value[len(atext):]
+    atext = ValueTerminal(atext, 'atext')
+    _validate_xtext(atext)
+    return atext, value
+
+def get_bare_quoted_string(value):
+    """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE
+
+    A quoted-string without the leading or trailing white space.  Its
+    value is the text between the quote marks, with whitespace
+    preserved and quoted pairs decoded.
+    """
+    if value[0] != '"':
+        raise errors.HeaderParseError(
+            "expected '\"' but found '{}'".format(value))
+    bare_quoted_string = BareQuotedString()
+    value = value[1:]
+    if value and value[0] == '"':
+        token, value = get_qcontent(value)
+        bare_quoted_string.append(token)
+    while value and value[0] != '"':
+        if value[0] in WSP:
+            token, value = get_fws(value)
+        elif value[:2] == '=?':
+            valid_ew = False
+            try:
+                token, value = get_encoded_word(value)
+                bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
+                    "encoded word inside quoted string"))
+                valid_ew = True
+            except errors.HeaderParseError:
+                token, value = get_qcontent(value)
+            # Collapse the whitespace between two encoded words that occur in a
+            # bare-quoted-string.
+            if valid_ew and len(bare_quoted_string) > 1:
+                if (bare_quoted_string[-1].token_type == 'fws' and
+                        bare_quoted_string[-2].token_type == 'encoded-word'):
+                    bare_quoted_string[-1] = EWWhiteSpaceTerminal(
+                        bare_quoted_string[-1], 'fws')
+        else:
+            token, value = get_qcontent(value)
+        bare_quoted_string.append(token)
+    if not value:
+        bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
+            "end of header inside quoted string"))
+        return bare_quoted_string, value
+    return bare_quoted_string, value[1:]
+
+def get_comment(value):
+    """comment = "(" *([FWS] ccontent) [FWS] ")"
+       ccontent = ctext / quoted-pair / comment
+
+    We handle nested comments here, and quoted-pair in our qp-ctext routine.
+    """
+    if value and value[0] != '(':
+        raise errors.HeaderParseError(
+            "expected '(' but found '{}'".format(value))
+    comment = Comment()
+    value = value[1:]
+    while value and value[0] != ")":
+        if value[0] in WSP:
+            token, value = get_fws(value)
+        elif value[0] == '(':
+            token, value = get_comment(value)
+        else:
+            token, value = get_qp_ctext(value)
+        comment.append(token)
+    if not value:
+        comment.defects.append(errors.InvalidHeaderDefect(
+            "end of header inside comment"))
+        return comment, value
+    return comment, value[1:]
+
+def get_cfws(value):
+    """CFWS = (1*([FWS] comment) [FWS]) / FWS
+
+    """
+    cfws = CFWSList()
+    while value and value[0] in CFWS_LEADER:
+        if value[0] in WSP:
+            token, value = get_fws(value)
+        else:
+            token, value = get_comment(value)
+        cfws.append(token)
+    return cfws, value
+
+def get_quoted_string(value):
+    """quoted-string = [CFWS]  [CFWS]
+
+    'bare-quoted-string' is an intermediate class defined by this
+    parser and not by the RFC grammar.  It is the quoted string
+    without any attached CFWS.
+    """
+    quoted_string = QuotedString()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        quoted_string.append(token)
+    token, value = get_bare_quoted_string(value)
+    quoted_string.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        quoted_string.append(token)
+    return quoted_string, value
+
+def get_atom(value):
+    """atom = [CFWS] 1*atext [CFWS]
+
+    An atom could be an rfc2047 encoded word.
+    """
+    atom = Atom()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        atom.append(token)
+    if value and value[0] in ATOM_ENDS:
+        raise errors.HeaderParseError(
+            "expected atom but found '{}'".format(value))
+    if value.startswith('=?'):
+        try:
+            token, value = get_encoded_word(value)
+        except errors.HeaderParseError:
+            # XXX: need to figure out how to register defects when
+            # appropriate here.
+            token, value = get_atext(value)
+    else:
+        token, value = get_atext(value)
+    atom.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        atom.append(token)
+    return atom, value
+
+def get_dot_atom_text(value):
+    """ dot-text = 1*atext *("." 1*atext)
+
+    """
+    dot_atom_text = DotAtomText()
+    if not value or value[0] in ATOM_ENDS:
+        raise errors.HeaderParseError("expected atom at a start of "
+            "dot-atom-text but found '{}'".format(value))
+    while value and value[0] not in ATOM_ENDS:
+        token, value = get_atext(value)
+        dot_atom_text.append(token)
+        if value and value[0] == '.':
+            dot_atom_text.append(DOT)
+            value = value[1:]
+    if dot_atom_text[-1] is DOT:
+        raise errors.HeaderParseError("expected atom at end of dot-atom-text "
+            "but found '{}'".format('.'+value))
+    return dot_atom_text, value
+
+def get_dot_atom(value):
+    """ dot-atom = [CFWS] dot-atom-text [CFWS]
+
+    Any place we can have a dot atom, we could instead have an rfc2047 encoded
+    word.
+    """
+    dot_atom = DotAtom()
+    if value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        dot_atom.append(token)
+    if value.startswith('=?'):
+        try:
+            token, value = get_encoded_word(value)
+        except errors.HeaderParseError:
+            # XXX: need to figure out how to register defects when
+            # appropriate here.
+            token, value = get_dot_atom_text(value)
+    else:
+        token, value = get_dot_atom_text(value)
+    dot_atom.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        dot_atom.append(token)
+    return dot_atom, value
+
+def get_word(value):
+    """word = atom / quoted-string
+
+    Either atom or quoted-string may start with CFWS.  We have to peel off this
+    CFWS first to determine which type of word to parse.  Afterward we splice
+    the leading CFWS, if any, into the parsed sub-token.
+
+    If neither an atom or a quoted-string is found before the next special, a
+    HeaderParseError is raised.
+
+    The token returned is either an Atom or a QuotedString, as appropriate.
+    This means the 'word' level of the formal grammar is not represented in the
+    parse tree; this is because having that extra layer when manipulating the
+    parse tree is more confusing than it is helpful.
+
+    """
+    if value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+    else:
+        leader = None
+    if not value:
+        raise errors.HeaderParseError(
+            "Expected 'atom' or 'quoted-string' but found nothing.")
+    if value[0]=='"':
+        token, value = get_quoted_string(value)
+    elif value[0] in SPECIALS:
+        raise errors.HeaderParseError("Expected 'atom' or 'quoted-string' "
+                                      "but found '{}'".format(value))
+    else:
+        token, value = get_atom(value)
+    if leader is not None:
+        token[:0] = [leader]
+    return token, value
+
+def get_phrase(value):
+    """ phrase = 1*word / obs-phrase
+        obs-phrase = word *(word / "." / CFWS)
+
+    This means a phrase can be a sequence of words, periods, and CFWS in any
+    order as long as it starts with at least one word.  If anything other than
+    words is detected, an ObsoleteHeaderDefect is added to the token's defect
+    list.  We also accept a phrase that starts with CFWS followed by a dot;
+    this is registered as an InvalidHeaderDefect, since it is not supported by
+    even the obsolete grammar.
+
+    """
+    phrase = Phrase()
+    try:
+        token, value = get_word(value)
+        phrase.append(token)
+    except errors.HeaderParseError:
+        phrase.defects.append(errors.InvalidHeaderDefect(
+            "phrase does not start with word"))
+    while value and value[0] not in PHRASE_ENDS:
+        if value[0]=='.':
+            phrase.append(DOT)
+            phrase.defects.append(errors.ObsoleteHeaderDefect(
+                "period in 'phrase'"))
+            value = value[1:]
+        else:
+            try:
+                token, value = get_word(value)
+            except errors.HeaderParseError:
+                if value[0] in CFWS_LEADER:
+                    token, value = get_cfws(value)
+                    phrase.defects.append(errors.ObsoleteHeaderDefect(
+                        "comment found without atom"))
+                else:
+                    raise
+            phrase.append(token)
+    return phrase, value
+
+def get_local_part(value):
+    """ local-part = dot-atom / quoted-string / obs-local-part
+
+    """
+    local_part = LocalPart()
+    leader = None
+    if value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+    if not value:
+        raise errors.HeaderParseError(
+            "expected local-part but found '{}'".format(value))
+    try:
+        token, value = get_dot_atom(value)
+    except errors.HeaderParseError:
+        try:
+            token, value = get_word(value)
+        except errors.HeaderParseError:
+            if value[0] != '\\' and value[0] in PHRASE_ENDS:
+                raise
+            token = TokenList()
+    if leader is not None:
+        token[:0] = [leader]
+    local_part.append(token)
+    if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
+        obs_local_part, value = get_obs_local_part(str(local_part) + value)
+        if obs_local_part.token_type == 'invalid-obs-local-part':
+            local_part.defects.append(errors.InvalidHeaderDefect(
+                "local-part is not dot-atom, quoted-string, or obs-local-part"))
+        else:
+            local_part.defects.append(errors.ObsoleteHeaderDefect(
+                "local-part is not a dot-atom (contains CFWS)"))
+        local_part[0] = obs_local_part
+    try:
+        local_part.value.encode('ascii')
+    except UnicodeEncodeError:
+        local_part.defects.append(errors.NonASCIILocalPartDefect(
+                "local-part contains non-ASCII characters)"))
+    return local_part, value
+
+def get_obs_local_part(value):
+    """ obs-local-part = word *("." word)
+    """
+    obs_local_part = ObsLocalPart()
+    last_non_ws_was_dot = False
+    while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
+        if value[0] == '.':
+            if last_non_ws_was_dot:
+                obs_local_part.defects.append(errors.InvalidHeaderDefect(
+                    "invalid repeated '.'"))
+            obs_local_part.append(DOT)
+            last_non_ws_was_dot = True
+            value = value[1:]
+            continue
+        elif value[0]=='\\':
+            obs_local_part.append(ValueTerminal(value[0],
+                                                'misplaced-special'))
+            value = value[1:]
+            obs_local_part.defects.append(errors.InvalidHeaderDefect(
+                "'\\' character outside of quoted-string/ccontent"))
+            last_non_ws_was_dot = False
+            continue
+        if obs_local_part and obs_local_part[-1].token_type != 'dot':
+            obs_local_part.defects.append(errors.InvalidHeaderDefect(
+                "missing '.' between words"))
+        try:
+            token, value = get_word(value)
+            last_non_ws_was_dot = False
+        except errors.HeaderParseError:
+            if value[0] not in CFWS_LEADER:
+                raise
+            token, value = get_cfws(value)
+        obs_local_part.append(token)
+    if (obs_local_part[0].token_type == 'dot' or
+            obs_local_part[0].token_type=='cfws' and
+            obs_local_part[1].token_type=='dot'):
+        obs_local_part.defects.append(errors.InvalidHeaderDefect(
+            "Invalid leading '.' in local part"))
+    if (obs_local_part[-1].token_type == 'dot' or
+            obs_local_part[-1].token_type=='cfws' and
+            obs_local_part[-2].token_type=='dot'):
+        obs_local_part.defects.append(errors.InvalidHeaderDefect(
+            "Invalid trailing '.' in local part"))
+    if obs_local_part.defects:
+        obs_local_part.token_type = 'invalid-obs-local-part'
+    return obs_local_part, value
+
+def get_dtext(value):
+    r""" dtext =  / obs-dtext
+        obs-dtext = obs-NO-WS-CTL / quoted-pair
+
+    We allow anything except the excluded characters, but if we find any
+    ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is
+    added to the token's defects list.  Quoted pairs are converted to their
+    unquoted values, so what is returned is a ptext token, in this case a
+    ValueTerminal.  If there were quoted-printables, an ObsoleteHeaderDefect is
+    added to the returned token's defect list.
+
+    """
+    ptext, value, had_qp = _get_ptext_to_endchars(value, '[]')
+    ptext = ValueTerminal(ptext, 'ptext')
+    if had_qp:
+        ptext.defects.append(errors.ObsoleteHeaderDefect(
+            "quoted printable found in domain-literal"))
+    _validate_xtext(ptext)
+    return ptext, value
+
+def _check_for_early_dl_end(value, domain_literal):
+    if value:
+        return False
+    domain_literal.append(errors.InvalidHeaderDefect(
+        "end of input inside domain-literal"))
+    domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
+    return True
+
+def get_domain_literal(value):
+    """ domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
+
+    """
+    domain_literal = DomainLiteral()
+    if value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        domain_literal.append(token)
+    if not value:
+        raise errors.HeaderParseError("expected domain-literal")
+    if value[0] != '[':
+        raise errors.HeaderParseError("expected '[' at start of domain-literal "
+                "but found '{}'".format(value))
+    value = value[1:]
+    if _check_for_early_dl_end(value, domain_literal):
+        return domain_literal, value
+    domain_literal.append(ValueTerminal('[', 'domain-literal-start'))
+    if value[0] in WSP:
+        token, value = get_fws(value)
+        domain_literal.append(token)
+    token, value = get_dtext(value)
+    domain_literal.append(token)
+    if _check_for_early_dl_end(value, domain_literal):
+        return domain_literal, value
+    if value[0] in WSP:
+        token, value = get_fws(value)
+        domain_literal.append(token)
+    if _check_for_early_dl_end(value, domain_literal):
+        return domain_literal, value
+    if value[0] != ']':
+        raise errors.HeaderParseError("expected ']' at end of domain-literal "
+                "but found '{}'".format(value))
+    domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
+    value = value[1:]
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        domain_literal.append(token)
+    return domain_literal, value
+
+def get_domain(value):
+    """ domain = dot-atom / domain-literal / obs-domain
+        obs-domain = atom *("." atom))
+
+    """
+    domain = Domain()
+    leader = None
+    if value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+    if not value:
+        raise errors.HeaderParseError(
+            "expected domain but found '{}'".format(value))
+    if value[0] == '[':
+        token, value = get_domain_literal(value)
+        if leader is not None:
+            token[:0] = [leader]
+        domain.append(token)
+        return domain, value
+    try:
+        token, value = get_dot_atom(value)
+    except errors.HeaderParseError:
+        token, value = get_atom(value)
+    if value and value[0] == '@':
+        raise errors.HeaderParseError('Invalid Domain')
+    if leader is not None:
+        token[:0] = [leader]
+    domain.append(token)
+    if value and value[0] == '.':
+        domain.defects.append(errors.ObsoleteHeaderDefect(
+            "domain is not a dot-atom (contains CFWS)"))
+        if domain[0].token_type == 'dot-atom':
+            domain[:] = domain[0]
+        while value and value[0] == '.':
+            domain.append(DOT)
+            token, value = get_atom(value[1:])
+            domain.append(token)
+    return domain, value
+
+def get_addr_spec(value):
+    """ addr-spec = local-part "@" domain
+
+    """
+    addr_spec = AddrSpec()
+    token, value = get_local_part(value)
+    addr_spec.append(token)
+    if not value or value[0] != '@':
+        addr_spec.defects.append(errors.InvalidHeaderDefect(
+            "addr-spec local part with no domain"))
+        return addr_spec, value
+    addr_spec.append(ValueTerminal('@', 'address-at-symbol'))
+    token, value = get_domain(value[1:])
+    addr_spec.append(token)
+    return addr_spec, value
+
+def get_obs_route(value):
+    """ obs-route = obs-domain-list ":"
+        obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain])
+
+        Returns an obs-route token with the appropriate sub-tokens (that is,
+        there is no obs-domain-list in the parse tree).
+    """
+    obs_route = ObsRoute()
+    while value and (value[0]==',' or value[0] in CFWS_LEADER):
+        if value[0] in CFWS_LEADER:
+            token, value = get_cfws(value)
+            obs_route.append(token)
+        elif value[0] == ',':
+            obs_route.append(ListSeparator)
+            value = value[1:]
+    if not value or value[0] != '@':
+        raise errors.HeaderParseError(
+            "expected obs-route domain but found '{}'".format(value))
+    obs_route.append(RouteComponentMarker)
+    token, value = get_domain(value[1:])
+    obs_route.append(token)
+    while value and value[0]==',':
+        obs_route.append(ListSeparator)
+        value = value[1:]
+        if not value:
+            break
+        if value[0] in CFWS_LEADER:
+            token, value = get_cfws(value)
+            obs_route.append(token)
+        if value[0] == '@':
+            obs_route.append(RouteComponentMarker)
+            token, value = get_domain(value[1:])
+            obs_route.append(token)
+    if not value:
+        raise errors.HeaderParseError("end of header while parsing obs-route")
+    if value[0] != ':':
+        raise errors.HeaderParseError( "expected ':' marking end of "
+            "obs-route but found '{}'".format(value))
+    obs_route.append(ValueTerminal(':', 'end-of-obs-route-marker'))
+    return obs_route, value[1:]
+
+def get_angle_addr(value):
+    """ angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
+        obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
+
+    """
+    angle_addr = AngleAddr()
+    if value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        angle_addr.append(token)
+    if not value or value[0] != '<':
+        raise errors.HeaderParseError(
+            "expected angle-addr but found '{}'".format(value))
+    angle_addr.append(ValueTerminal('<', 'angle-addr-start'))
+    value = value[1:]
+    # Although it is not legal per RFC5322, SMTP uses '<>' in certain
+    # circumstances.
+    if value[0] == '>':
+        angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
+        angle_addr.defects.append(errors.InvalidHeaderDefect(
+            "null addr-spec in angle-addr"))
+        value = value[1:]
+        return angle_addr, value
+    try:
+        token, value = get_addr_spec(value)
+    except errors.HeaderParseError:
+        try:
+            token, value = get_obs_route(value)
+            angle_addr.defects.append(errors.ObsoleteHeaderDefect(
+                "obsolete route specification in angle-addr"))
+        except errors.HeaderParseError:
+            raise errors.HeaderParseError(
+                "expected addr-spec or obs-route but found '{}'".format(value))
+        angle_addr.append(token)
+        token, value = get_addr_spec(value)
+    angle_addr.append(token)
+    if value and value[0] == '>':
+        value = value[1:]
+    else:
+        angle_addr.defects.append(errors.InvalidHeaderDefect(
+            "missing trailing '>' on angle-addr"))
+    angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        angle_addr.append(token)
+    return angle_addr, value
+
+def get_display_name(value):
+    """ display-name = phrase
+
+    Because this is simply a name-rule, we don't return a display-name
+    token containing a phrase, but rather a display-name token with
+    the content of the phrase.
+
+    """
+    display_name = DisplayName()
+    token, value = get_phrase(value)
+    display_name.extend(token[:])
+    display_name.defects = token.defects[:]
+    return display_name, value
+
+
+def get_name_addr(value):
+    """ name-addr = [display-name] angle-addr
+
+    """
+    name_addr = NameAddr()
+    # Both the optional display name and the angle-addr can start with cfws.
+    leader = None
+    if value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+        if not value:
+            raise errors.HeaderParseError(
+                "expected name-addr but found '{}'".format(leader))
+    if value[0] != '<':
+        if value[0] in PHRASE_ENDS:
+            raise errors.HeaderParseError(
+                "expected name-addr but found '{}'".format(value))
+        token, value = get_display_name(value)
+        if not value:
+            raise errors.HeaderParseError(
+                "expected name-addr but found '{}'".format(token))
+        if leader is not None:
+            token[0][:0] = [leader]
+            leader = None
+        name_addr.append(token)
+    token, value = get_angle_addr(value)
+    if leader is not None:
+        token[:0] = [leader]
+    name_addr.append(token)
+    return name_addr, value
+
+def get_mailbox(value):
+    """ mailbox = name-addr / addr-spec
+
+    """
+    # The only way to figure out if we are dealing with a name-addr or an
+    # addr-spec is to try parsing each one.
+    mailbox = Mailbox()
+    try:
+        token, value = get_name_addr(value)
+    except errors.HeaderParseError:
+        try:
+            token, value = get_addr_spec(value)
+        except errors.HeaderParseError:
+            raise errors.HeaderParseError(
+                "expected mailbox but found '{}'".format(value))
+    if any(isinstance(x, errors.InvalidHeaderDefect)
+                       for x in token.all_defects):
+        mailbox.token_type = 'invalid-mailbox'
+    mailbox.append(token)
+    return mailbox, value
+
+def get_invalid_mailbox(value, endchars):
+    """ Read everything up to one of the chars in endchars.
+
+    This is outside the formal grammar.  The InvalidMailbox TokenList that is
+    returned acts like a Mailbox, but the data attributes are None.
+
+    """
+    invalid_mailbox = InvalidMailbox()
+    while value and value[0] not in endchars:
+        if value[0] in PHRASE_ENDS:
+            invalid_mailbox.append(ValueTerminal(value[0],
+                                                 'misplaced-special'))
+            value = value[1:]
+        else:
+            token, value = get_phrase(value)
+            invalid_mailbox.append(token)
+    return invalid_mailbox, value
+
+def get_mailbox_list(value):
+    """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
+        obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
+
+    For this routine we go outside the formal grammar in order to improve error
+    handling.  We recognize the end of the mailbox list only at the end of the
+    value or at a ';' (the group terminator).  This is so that we can turn
+    invalid mailboxes into InvalidMailbox tokens and continue parsing any
+    remaining valid mailboxes.  We also allow all mailbox entries to be null,
+    and this condition is handled appropriately at a higher level.
+
+    """
+    mailbox_list = MailboxList()
+    while value and value[0] != ';':
+        try:
+            token, value = get_mailbox(value)
+            mailbox_list.append(token)
+        except errors.HeaderParseError:
+            leader = None
+            if value[0] in CFWS_LEADER:
+                leader, value = get_cfws(value)
+                if not value or value[0] in ',;':
+                    mailbox_list.append(leader)
+                    mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
+                        "empty element in mailbox-list"))
+                else:
+                    token, value = get_invalid_mailbox(value, ',;')
+                    if leader is not None:
+                        token[:0] = [leader]
+                    mailbox_list.append(token)
+                    mailbox_list.defects.append(errors.InvalidHeaderDefect(
+                        "invalid mailbox in mailbox-list"))
+            elif value[0] == ',':
+                mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
+                    "empty element in mailbox-list"))
+            else:
+                token, value = get_invalid_mailbox(value, ',;')
+                if leader is not None:
+                    token[:0] = [leader]
+                mailbox_list.append(token)
+                mailbox_list.defects.append(errors.InvalidHeaderDefect(
+                    "invalid mailbox in mailbox-list"))
+        if value and value[0] not in ',;':
+            # Crap after mailbox; treat it as an invalid mailbox.
+            # The mailbox info will still be available.
+            mailbox = mailbox_list[-1]
+            mailbox.token_type = 'invalid-mailbox'
+            token, value = get_invalid_mailbox(value, ',;')
+            mailbox.extend(token)
+            mailbox_list.defects.append(errors.InvalidHeaderDefect(
+                "invalid mailbox in mailbox-list"))
+        if value and value[0] == ',':
+            mailbox_list.append(ListSeparator)
+            value = value[1:]
+    return mailbox_list, value
+
+
+def get_group_list(value):
+    """ group-list = mailbox-list / CFWS / obs-group-list
+        obs-group-list = 1*([CFWS] ",") [CFWS]
+
+    """
+    group_list = GroupList()
+    if not value:
+        group_list.defects.append(errors.InvalidHeaderDefect(
+            "end of header before group-list"))
+        return group_list, value
+    leader = None
+    if value and value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+        if not value:
+            # This should never happen in email parsing, since CFWS-only is a
+            # legal alternative to group-list in a group, which is the only
+            # place group-list appears.
+            group_list.defects.append(errors.InvalidHeaderDefect(
+                "end of header in group-list"))
+            group_list.append(leader)
+            return group_list, value
+        if value[0] == ';':
+            group_list.append(leader)
+            return group_list, value
+    token, value = get_mailbox_list(value)
+    if len(token.all_mailboxes)==0:
+        if leader is not None:
+            group_list.append(leader)
+        group_list.extend(token)
+        group_list.defects.append(errors.ObsoleteHeaderDefect(
+            "group-list with empty entries"))
+        return group_list, value
+    if leader is not None:
+        token[:0] = [leader]
+    group_list.append(token)
+    return group_list, value
+
+def get_group(value):
+    """ group = display-name ":" [group-list] ";" [CFWS]
+
+    """
+    group = Group()
+    token, value = get_display_name(value)
+    if not value or value[0] != ':':
+        raise errors.HeaderParseError("expected ':' at end of group "
+            "display name but found '{}'".format(value))
+    group.append(token)
+    group.append(ValueTerminal(':', 'group-display-name-terminator'))
+    value = value[1:]
+    if value and value[0] == ';':
+        group.append(ValueTerminal(';', 'group-terminator'))
+        return group, value[1:]
+    token, value = get_group_list(value)
+    group.append(token)
+    if not value:
+        group.defects.append(errors.InvalidHeaderDefect(
+            "end of header in group"))
+    elif value[0] != ';':
+        raise errors.HeaderParseError(
+            "expected ';' at end of group but found {}".format(value))
+    group.append(ValueTerminal(';', 'group-terminator'))
+    value = value[1:]
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        group.append(token)
+    return group, value
+
+def get_address(value):
+    """ address = mailbox / group
+
+    Note that counter-intuitively, an address can be either a single address or
+    a list of addresses (a group).  This is why the returned Address object has
+    a 'mailboxes' attribute which treats a single address as a list of length
+    one.  When you need to differentiate between to two cases, extract the single
+    element, which is either a mailbox or a group token.
+
+    """
+    # The formal grammar isn't very helpful when parsing an address.  mailbox
+    # and group, especially when allowing for obsolete forms, start off very
+    # similarly.  It is only when you reach one of @, <, or : that you know
+    # what you've got.  So, we try each one in turn, starting with the more
+    # likely of the two.  We could perhaps make this more efficient by looking
+    # for a phrase and then branching based on the next character, but that
+    # would be a premature optimization.
+    address = Address()
+    try:
+        token, value = get_group(value)
+    except errors.HeaderParseError:
+        try:
+            token, value = get_mailbox(value)
+        except errors.HeaderParseError:
+            raise errors.HeaderParseError(
+                "expected address but found '{}'".format(value))
+    address.append(token)
+    return address, value
+
+def get_address_list(value):
+    """ address_list = (address *("," address)) / obs-addr-list
+        obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
+
+    We depart from the formal grammar here by continuing to parse until the end
+    of the input, assuming the input to be entirely composed of an
+    address-list.  This is always true in email parsing, and allows us
+    to skip invalid addresses to parse additional valid ones.
+
+    """
+    address_list = AddressList()
+    while value:
+        try:
+            token, value = get_address(value)
+            address_list.append(token)
+        except errors.HeaderParseError as err:
+            leader = None
+            if value[0] in CFWS_LEADER:
+                leader, value = get_cfws(value)
+                if not value or value[0] == ',':
+                    address_list.append(leader)
+                    address_list.defects.append(errors.ObsoleteHeaderDefect(
+                        "address-list entry with no content"))
+                else:
+                    token, value = get_invalid_mailbox(value, ',')
+                    if leader is not None:
+                        token[:0] = [leader]
+                    address_list.append(Address([token]))
+                    address_list.defects.append(errors.InvalidHeaderDefect(
+                        "invalid address in address-list"))
+            elif value[0] == ',':
+                address_list.defects.append(errors.ObsoleteHeaderDefect(
+                    "empty element in address-list"))
+            else:
+                token, value = get_invalid_mailbox(value, ',')
+                if leader is not None:
+                    token[:0] = [leader]
+                address_list.append(Address([token]))
+                address_list.defects.append(errors.InvalidHeaderDefect(
+                    "invalid address in address-list"))
+        if value and value[0] != ',':
+            # Crap after address; treat it as an invalid mailbox.
+            # The mailbox info will still be available.
+            mailbox = address_list[-1][0]
+            mailbox.token_type = 'invalid-mailbox'
+            token, value = get_invalid_mailbox(value, ',')
+            mailbox.extend(token)
+            address_list.defects.append(errors.InvalidHeaderDefect(
+                "invalid address in address-list"))
+        if value:  # Must be a , at this point.
+            address_list.append(ListSeparator)
+            value = value[1:]
+    return address_list, value
+
+
+def get_no_fold_literal(value):
+    """ no-fold-literal = "[" *dtext "]"
+    """
+    no_fold_literal = NoFoldLiteral()
+    if not value:
+        raise errors.HeaderParseError(
+            "expected no-fold-literal but found '{}'".format(value))
+    if value[0] != '[':
+        raise errors.HeaderParseError(
+            "expected '[' at the start of no-fold-literal "
+            "but found '{}'".format(value))
+    no_fold_literal.append(ValueTerminal('[', 'no-fold-literal-start'))
+    value = value[1:]
+    token, value = get_dtext(value)
+    no_fold_literal.append(token)
+    if not value or value[0] != ']':
+        raise errors.HeaderParseError(
+            "expected ']' at the end of no-fold-literal "
+            "but found '{}'".format(value))
+    no_fold_literal.append(ValueTerminal(']', 'no-fold-literal-end'))
+    return no_fold_literal, value[1:]
+
+def get_msg_id(value):
+    """msg-id = [CFWS] "<" id-left '@' id-right  ">" [CFWS]
+       id-left = dot-atom-text / obs-id-left
+       id-right = dot-atom-text / no-fold-literal / obs-id-right
+       no-fold-literal = "[" *dtext "]"
+    """
+    msg_id = MsgID()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        msg_id.append(token)
+    if not value or value[0] != '<':
+        raise errors.HeaderParseError(
+            "expected msg-id but found '{}'".format(value))
+    msg_id.append(ValueTerminal('<', 'msg-id-start'))
+    value = value[1:]
+    # Parse id-left.
+    try:
+        token, value = get_dot_atom_text(value)
+    except errors.HeaderParseError:
+        try:
+            # obs-id-left is same as local-part of add-spec.
+            token, value = get_obs_local_part(value)
+            msg_id.defects.append(errors.ObsoleteHeaderDefect(
+                "obsolete id-left in msg-id"))
+        except errors.HeaderParseError:
+            raise errors.HeaderParseError(
+                "expected dot-atom-text or obs-id-left"
+                " but found '{}'".format(value))
+    msg_id.append(token)
+    if not value or value[0] != '@':
+        msg_id.defects.append(errors.InvalidHeaderDefect(
+            "msg-id with no id-right"))
+        # Even though there is no id-right, if the local part
+        # ends with `>` let's just parse it too and return
+        # along with the defect.
+        if value and value[0] == '>':
+            msg_id.append(ValueTerminal('>', 'msg-id-end'))
+            value = value[1:]
+        return msg_id, value
+    msg_id.append(ValueTerminal('@', 'address-at-symbol'))
+    value = value[1:]
+    # Parse id-right.
+    try:
+        token, value = get_dot_atom_text(value)
+    except errors.HeaderParseError:
+        try:
+            token, value = get_no_fold_literal(value)
+        except errors.HeaderParseError as e:
+            try:
+                token, value = get_domain(value)
+                msg_id.defects.append(errors.ObsoleteHeaderDefect(
+                    "obsolete id-right in msg-id"))
+            except errors.HeaderParseError:
+                raise errors.HeaderParseError(
+                    "expected dot-atom-text, no-fold-literal or obs-id-right"
+                    " but found '{}'".format(value))
+    msg_id.append(token)
+    if value and value[0] == '>':
+        value = value[1:]
+    else:
+        msg_id.defects.append(errors.InvalidHeaderDefect(
+            "missing trailing '>' on msg-id"))
+    msg_id.append(ValueTerminal('>', 'msg-id-end'))
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        msg_id.append(token)
+    return msg_id, value
+
+
+def parse_message_id(value):
+    """message-id      =   "Message-ID:" msg-id CRLF
+    """
+    message_id = MessageID()
+    try:
+        token, value = get_msg_id(value)
+        message_id.append(token)
+    except errors.HeaderParseError as ex:
+        token = get_unstructured(value)
+        message_id = InvalidMessageID(token)
+        message_id.defects.append(
+            errors.InvalidHeaderDefect("Invalid msg-id: {!r}".format(ex)))
+    else:
+        # Value after parsing a valid msg_id should be None.
+        if value:
+            message_id.defects.append(errors.InvalidHeaderDefect(
+                "Unexpected {!r}".format(value)))
+
+    return message_id
+
+#
+# XXX: As I begin to add additional header parsers, I'm realizing we probably
+# have two level of parser routines: the get_XXX methods that get a token in
+# the grammar, and parse_XXX methods that parse an entire field value.  So
+# get_address_list above should really be a parse_ method, as probably should
+# be get_unstructured.
+#
+
+def parse_mime_version(value):
+    """ mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]
+
+    """
+    # The [CFWS] is implicit in the RFC 2045 BNF.
+    # XXX: This routine is a bit verbose, should factor out a get_int method.
+    mime_version = MIMEVersion()
+    if not value:
+        mime_version.defects.append(errors.HeaderMissingRequiredValue(
+            "Missing MIME version number (eg: 1.0)"))
+        return mime_version
+    if value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mime_version.append(token)
+        if not value:
+            mime_version.defects.append(errors.HeaderMissingRequiredValue(
+                "Expected MIME version number but found only CFWS"))
+    digits = ''
+    while value and value[0] != '.' and value[0] not in CFWS_LEADER:
+        digits += value[0]
+        value = value[1:]
+    if not digits.isdigit():
+        mime_version.defects.append(errors.InvalidHeaderDefect(
+            "Expected MIME major version number but found {!r}".format(digits)))
+        mime_version.append(ValueTerminal(digits, 'xtext'))
+    else:
+        mime_version.major = int(digits)
+        mime_version.append(ValueTerminal(digits, 'digits'))
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mime_version.append(token)
+    if not value or value[0] != '.':
+        if mime_version.major is not None:
+            mime_version.defects.append(errors.InvalidHeaderDefect(
+                "Incomplete MIME version; found only major number"))
+        if value:
+            mime_version.append(ValueTerminal(value, 'xtext'))
+        return mime_version
+    mime_version.append(ValueTerminal('.', 'version-separator'))
+    value = value[1:]
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mime_version.append(token)
+    if not value:
+        if mime_version.major is not None:
+            mime_version.defects.append(errors.InvalidHeaderDefect(
+                "Incomplete MIME version; found only major number"))
+        return mime_version
+    digits = ''
+    while value and value[0] not in CFWS_LEADER:
+        digits += value[0]
+        value = value[1:]
+    if not digits.isdigit():
+        mime_version.defects.append(errors.InvalidHeaderDefect(
+            "Expected MIME minor version number but found {!r}".format(digits)))
+        mime_version.append(ValueTerminal(digits, 'xtext'))
+    else:
+        mime_version.minor = int(digits)
+        mime_version.append(ValueTerminal(digits, 'digits'))
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mime_version.append(token)
+    if value:
+        mime_version.defects.append(errors.InvalidHeaderDefect(
+            "Excess non-CFWS text after MIME version"))
+        mime_version.append(ValueTerminal(value, 'xtext'))
+    return mime_version
+
+def get_invalid_parameter(value):
+    """ Read everything up to the next ';'.
+
+    This is outside the formal grammar.  The InvalidParameter TokenList that is
+    returned acts like a Parameter, but the data attributes are None.
+
+    """
+    invalid_parameter = InvalidParameter()
+    while value and value[0] != ';':
+        if value[0] in PHRASE_ENDS:
+            invalid_parameter.append(ValueTerminal(value[0],
+                                                   'misplaced-special'))
+            value = value[1:]
+        else:
+            token, value = get_phrase(value)
+            invalid_parameter.append(token)
+    return invalid_parameter, value
+
+def get_ttext(value):
+    """ttext = 
+
+    We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
+    defects list if we find non-ttext characters.  We also register defects for
+    *any* non-printables even though the RFC doesn't exclude all of them,
+    because we follow the spirit of RFC 5322.
+
+    """
+    m = _non_token_end_matcher(value)
+    if not m:
+        raise errors.HeaderParseError(
+            "expected ttext but found '{}'".format(value))
+    ttext = m.group()
+    value = value[len(ttext):]
+    ttext = ValueTerminal(ttext, 'ttext')
+    _validate_xtext(ttext)
+    return ttext, value
+
+def get_token(value):
+    """token = [CFWS] 1*ttext [CFWS]
+
+    The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
+    tspecials.  We also exclude tabs even though the RFC doesn't.
+
+    The RFC implies the CFWS but is not explicit about it in the BNF.
+
+    """
+    mtoken = Token()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mtoken.append(token)
+    if value and value[0] in TOKEN_ENDS:
+        raise errors.HeaderParseError(
+            "expected token but found '{}'".format(value))
+    token, value = get_ttext(value)
+    mtoken.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        mtoken.append(token)
+    return mtoken, value
+
+def get_attrtext(value):
+    """attrtext = 1*(any non-ATTRIBUTE_ENDS character)
+
+    We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
+    token's defects list if we find non-attrtext characters.  We also register
+    defects for *any* non-printables even though the RFC doesn't exclude all of
+    them, because we follow the spirit of RFC 5322.
+
+    """
+    m = _non_attribute_end_matcher(value)
+    if not m:
+        raise errors.HeaderParseError(
+            "expected attrtext but found {!r}".format(value))
+    attrtext = m.group()
+    value = value[len(attrtext):]
+    attrtext = ValueTerminal(attrtext, 'attrtext')
+    _validate_xtext(attrtext)
+    return attrtext, value
+
+def get_attribute(value):
+    """ [CFWS] 1*attrtext [CFWS]
+
+    This version of the BNF makes the CFWS explicit, and as usual we use a
+    value terminal for the actual run of characters.  The RFC equivalent of
+    attrtext is the token characters, with the subtraction of '*', "'", and '%'.
+    We include tab in the excluded set just as we do for token.
+
+    """
+    attribute = Attribute()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        attribute.append(token)
+    if value and value[0] in ATTRIBUTE_ENDS:
+        raise errors.HeaderParseError(
+            "expected token but found '{}'".format(value))
+    token, value = get_attrtext(value)
+    attribute.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        attribute.append(token)
+    return attribute, value
+
+def get_extended_attrtext(value):
+    """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')
+
+    This is a special parsing routine so that we get a value that
+    includes % escapes as a single string (which we decode as a single
+    string later).
+
+    """
+    m = _non_extended_attribute_end_matcher(value)
+    if not m:
+        raise errors.HeaderParseError(
+            "expected extended attrtext but found {!r}".format(value))
+    attrtext = m.group()
+    value = value[len(attrtext):]
+    attrtext = ValueTerminal(attrtext, 'extended-attrtext')
+    _validate_xtext(attrtext)
+    return attrtext, value
+
+def get_extended_attribute(value):
+    """ [CFWS] 1*extended_attrtext [CFWS]
+
+    This is like the non-extended version except we allow % characters, so that
+    we can pick up an encoded value as a single string.
+
+    """
+    # XXX: should we have an ExtendedAttribute TokenList?
+    attribute = Attribute()
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        attribute.append(token)
+    if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
+        raise errors.HeaderParseError(
+            "expected token but found '{}'".format(value))
+    token, value = get_extended_attrtext(value)
+    attribute.append(token)
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        attribute.append(token)
+    return attribute, value
+
+def get_section(value):
+    """ '*' digits
+
+    The formal BNF is more complicated because leading 0s are not allowed.  We
+    check for that and add a defect.  We also assume no CFWS is allowed between
+    the '*' and the digits, though the RFC is not crystal clear on that.
+    The caller should already have dealt with leading CFWS.
+
+    """
+    section = Section()
+    if not value or value[0] != '*':
+        raise errors.HeaderParseError("Expected section but found {}".format(
+                                        value))
+    section.append(ValueTerminal('*', 'section-marker'))
+    value = value[1:]
+    if not value or not value[0].isdigit():
+        raise errors.HeaderParseError("Expected section number but "
+                                      "found {}".format(value))
+    digits = ''
+    while value and value[0].isdigit():
+        digits += value[0]
+        value = value[1:]
+    if digits[0] == '0' and digits != '0':
+        section.defects.append(errors.InvalidHeaderDefect(
+                "section number has an invalid leading 0"))
+    section.number = int(digits)
+    section.append(ValueTerminal(digits, 'digits'))
+    return section, value
+
+
+def get_value(value):
+    """ quoted-string / attribute
+
+    """
+    v = Value()
+    if not value:
+        raise errors.HeaderParseError("Expected value but found end of string")
+    leader = None
+    if value[0] in CFWS_LEADER:
+        leader, value = get_cfws(value)
+    if not value:
+        raise errors.HeaderParseError("Expected value but found "
+                                      "only {}".format(leader))
+    if value[0] == '"':
+        token, value = get_quoted_string(value)
+    else:
+        token, value = get_extended_attribute(value)
+    if leader is not None:
+        token[:0] = [leader]
+    v.append(token)
+    return v, value
+
+def get_parameter(value):
+    """ attribute [section] ["*"] [CFWS] "=" value
+
+    The CFWS is implied by the RFC but not made explicit in the BNF.  This
+    simplified form of the BNF from the RFC is made to conform with the RFC BNF
+    through some extra checks.  We do it this way because it makes both error
+    recovery and working with the resulting parse tree easier.
+    """
+    # It is possible CFWS would also be implicitly allowed between the section
+    # and the 'extended-attribute' marker (the '*') , but we've never seen that
+    # in the wild and we will therefore ignore the possibility.
+    param = Parameter()
+    token, value = get_attribute(value)
+    param.append(token)
+    if not value or value[0] == ';':
+        param.defects.append(errors.InvalidHeaderDefect("Parameter contains "
+            "name ({}) but no value".format(token)))
+        return param, value
+    if value[0] == '*':
+        try:
+            token, value = get_section(value)
+            param.sectioned = True
+            param.append(token)
+        except errors.HeaderParseError:
+            pass
+        if not value:
+            raise errors.HeaderParseError("Incomplete parameter")
+        if value[0] == '*':
+            param.append(ValueTerminal('*', 'extended-parameter-marker'))
+            value = value[1:]
+            param.extended = True
+    if value[0] != '=':
+        raise errors.HeaderParseError("Parameter not followed by '='")
+    param.append(ValueTerminal('=', 'parameter-separator'))
+    value = value[1:]
+    leader = None
+    if value and value[0] in CFWS_LEADER:
+        token, value = get_cfws(value)
+        param.append(token)
+    remainder = None
+    appendto = param
+    if param.extended and value and value[0] == '"':
+        # Now for some serious hackery to handle the common invalid case of
+        # double quotes around an extended value.  We also accept (with defect)
+        # a value marked as encoded that isn't really.
+        qstring, remainder = get_quoted_string(value)
+        inner_value = qstring.stripped_value
+        semi_valid = False
+        if param.section_number == 0:
+            if inner_value and inner_value[0] == "'":
+                semi_valid = True
+            else:
+                token, rest = get_attrtext(inner_value)
+                if rest and rest[0] == "'":
+                    semi_valid = True
+        else:
+            try:
+                token, rest = get_extended_attrtext(inner_value)
+            except:
+                pass
+            else:
+                if not rest:
+                    semi_valid = True
+        if semi_valid:
+            param.defects.append(errors.InvalidHeaderDefect(
+                "Quoted string value for extended parameter is invalid"))
+            param.append(qstring)
+            for t in qstring:
+                if t.token_type == 'bare-quoted-string':
+                    t[:] = []
+                    appendto = t
+                    break
+            value = inner_value
+        else:
+            remainder = None
+            param.defects.append(errors.InvalidHeaderDefect(
+                "Parameter marked as extended but appears to have a "
+                "quoted string value that is non-encoded"))
+    if value and value[0] == "'":
+        token = None
+    else:
+        token, value = get_value(value)
+    if not param.extended or param.section_number > 0:
+        if not value or value[0] != "'":
+            appendto.append(token)
+            if remainder is not None:
+                assert not value, value
+                value = remainder
+            return param, value
+        param.defects.append(errors.InvalidHeaderDefect(
+            "Apparent initial-extended-value but attribute "
+            "was not marked as extended or was not initial section"))
+    if not value:
+        # Assume the charset/lang is missing and the token is the value.
+        param.defects.append(errors.InvalidHeaderDefect(
+            "Missing required charset/lang delimiters"))
+        appendto.append(token)
+        if remainder is None:
+            return param, value
+    else:
+        if token is not None:
+            for t in token:
+                if t.token_type == 'extended-attrtext':
+                    break
+            t.token_type == 'attrtext'
+            appendto.append(t)
+            param.charset = t.value
+        if value[0] != "'":
+            raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
+                                          "delimiter, but found {!r}".format(value))
+        appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
+        value = value[1:]
+        if value and value[0] != "'":
+            token, value = get_attrtext(value)
+            appendto.append(token)
+            param.lang = token.value
+            if not value or value[0] != "'":
+                raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
+                                  "delimiter, but found {}".format(value))
+        appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
+        value = value[1:]
+    if remainder is not None:
+        # Treat the rest of value as bare quoted string content.
+        v = Value()
+        while value:
+            if value[0] in WSP:
+                token, value = get_fws(value)
+            elif value[0] == '"':
+                token = ValueTerminal('"', 'DQUOTE')
+                value = value[1:]
+            else:
+                token, value = get_qcontent(value)
+            v.append(token)
+        token = v
+    else:
+        token, value = get_value(value)
+    appendto.append(token)
+    if remainder is not None:
+        assert not value, value
+        value = remainder
+    return param, value
+
+def parse_mime_parameters(value):
+    """ parameter *( ";" parameter )
+
+    That BNF is meant to indicate this routine should only be called after
+    finding and handling the leading ';'.  There is no corresponding rule in
+    the formal RFC grammar, but it is more convenient for us for the set of
+    parameters to be treated as its own TokenList.
+
+    This is 'parse' routine because it consumes the remaining value, but it
+    would never be called to parse a full header.  Instead it is called to
+    parse everything after the non-parameter value of a specific MIME header.
+
+    """
+    mime_parameters = MimeParameters()
+    while value:
+        try:
+            token, value = get_parameter(value)
+            mime_parameters.append(token)
+        except errors.HeaderParseError as err:
+            leader = None
+            if value[0] in CFWS_LEADER:
+                leader, value = get_cfws(value)
+            if not value:
+                mime_parameters.append(leader)
+                return mime_parameters
+            if value[0] == ';':
+                if leader is not None:
+                    mime_parameters.append(leader)
+                mime_parameters.defects.append(errors.InvalidHeaderDefect(
+                    "parameter entry with no content"))
+            else:
+                token, value = get_invalid_parameter(value)
+                if leader:
+                    token[:0] = [leader]
+                mime_parameters.append(token)
+                mime_parameters.defects.append(errors.InvalidHeaderDefect(
+                    "invalid parameter {!r}".format(token)))
+        if value and value[0] != ';':
+            # Junk after the otherwise valid parameter.  Mark it as
+            # invalid, but it will have a value.
+            param = mime_parameters[-1]
+            param.token_type = 'invalid-parameter'
+            token, value = get_invalid_parameter(value)
+            param.extend(token)
+            mime_parameters.defects.append(errors.InvalidHeaderDefect(
+                "parameter with invalid trailing text {!r}".format(token)))
+        if value:
+            # Must be a ';' at this point.
+            mime_parameters.append(ValueTerminal(';', 'parameter-separator'))
+            value = value[1:]
+    return mime_parameters
+
+def _find_mime_parameters(tokenlist, value):
+    """Do our best to find the parameters in an invalid MIME header
+
+    """
+    while value and value[0] != ';':
+        if value[0] in PHRASE_ENDS:
+            tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
+            value = value[1:]
+        else:
+            token, value = get_phrase(value)
+            tokenlist.append(token)
+    if not value:
+        return
+    tokenlist.append(ValueTerminal(';', 'parameter-separator'))
+    tokenlist.append(parse_mime_parameters(value[1:]))
+
+def parse_content_type_header(value):
+    """ maintype "/" subtype *( ";" parameter )
+
+    The maintype and substype are tokens.  Theoretically they could
+    be checked against the official IANA list + x-token, but we
+    don't do that.
+    """
+    ctype = ContentType()
+    recover = False
+    if not value:
+        ctype.defects.append(errors.HeaderMissingRequiredValue(
+            "Missing content type specification"))
+        return ctype
+    try:
+        token, value = get_token(value)
+    except errors.HeaderParseError:
+        ctype.defects.append(errors.InvalidHeaderDefect(
+            "Expected content maintype but found {!r}".format(value)))
+        _find_mime_parameters(ctype, value)
+        return ctype
+    ctype.append(token)
+    # XXX: If we really want to follow the formal grammar we should make
+    # mantype and subtype specialized TokenLists here.  Probably not worth it.
+    if not value or value[0] != '/':
+        ctype.defects.append(errors.InvalidHeaderDefect(
+            "Invalid content type"))
+        if value:
+            _find_mime_parameters(ctype, value)
+        return ctype
+    ctype.maintype = token.value.strip().lower()
+    ctype.append(ValueTerminal('/', 'content-type-separator'))
+    value = value[1:]
+    try:
+        token, value = get_token(value)
+    except errors.HeaderParseError:
+        ctype.defects.append(errors.InvalidHeaderDefect(
+            "Expected content subtype but found {!r}".format(value)))
+        _find_mime_parameters(ctype, value)
+        return ctype
+    ctype.append(token)
+    ctype.subtype = token.value.strip().lower()
+    if not value:
+        return ctype
+    if value[0] != ';':
+        ctype.defects.append(errors.InvalidHeaderDefect(
+            "Only parameters are valid after content type, but "
+            "found {!r}".format(value)))
+        # The RFC requires that a syntactically invalid content-type be treated
+        # as text/plain.  Perhaps we should postel this, but we should probably
+        # only do that if we were checking the subtype value against IANA.
+        del ctype.maintype, ctype.subtype
+        _find_mime_parameters(ctype, value)
+        return ctype
+    ctype.append(ValueTerminal(';', 'parameter-separator'))
+    ctype.append(parse_mime_parameters(value[1:]))
+    return ctype
+
+def parse_content_disposition_header(value):
+    """ disposition-type *( ";" parameter )
+
+    """
+    disp_header = ContentDisposition()
+    if not value:
+        disp_header.defects.append(errors.HeaderMissingRequiredValue(
+            "Missing content disposition"))
+        return disp_header
+    try:
+        token, value = get_token(value)
+    except errors.HeaderParseError:
+        disp_header.defects.append(errors.InvalidHeaderDefect(
+            "Expected content disposition but found {!r}".format(value)))
+        _find_mime_parameters(disp_header, value)
+        return disp_header
+    disp_header.append(token)
+    disp_header.content_disposition = token.value.strip().lower()
+    if not value:
+        return disp_header
+    if value[0] != ';':
+        disp_header.defects.append(errors.InvalidHeaderDefect(
+            "Only parameters are valid after content disposition, but "
+            "found {!r}".format(value)))
+        _find_mime_parameters(disp_header, value)
+        return disp_header
+    disp_header.append(ValueTerminal(';', 'parameter-separator'))
+    disp_header.append(parse_mime_parameters(value[1:]))
+    return disp_header
+
+def parse_content_transfer_encoding_header(value):
+    """ mechanism
+
+    """
+    # We should probably validate the values, since the list is fixed.
+    cte_header = ContentTransferEncoding()
+    if not value:
+        cte_header.defects.append(errors.HeaderMissingRequiredValue(
+            "Missing content transfer encoding"))
+        return cte_header
+    try:
+        token, value = get_token(value)
+    except errors.HeaderParseError:
+        cte_header.defects.append(errors.InvalidHeaderDefect(
+            "Expected content transfer encoding but found {!r}".format(value)))
+    else:
+        cte_header.append(token)
+        cte_header.cte = token.value.strip().lower()
+    if not value:
+        return cte_header
+    while value:
+        cte_header.defects.append(errors.InvalidHeaderDefect(
+            "Extra text after content transfer encoding"))
+        if value[0] in PHRASE_ENDS:
+            cte_header.append(ValueTerminal(value[0], 'misplaced-special'))
+            value = value[1:]
+        else:
+            token, value = get_phrase(value)
+            cte_header.append(token)
+    return cte_header
+
+
+#
+# Header folding
+#
+# Header folding is complex, with lots of rules and corner cases.  The
+# following code does its best to obey the rules and handle the corner
+# cases, but you can be sure there are few bugs:)
+#
+# This folder generally canonicalizes as it goes, preferring the stringified
+# version of each token.  The tokens contain information that supports the
+# folder, including which tokens can be encoded in which ways.
+#
+# Folded text is accumulated in a simple list of strings ('lines'), each
+# one of which should be less than policy.max_line_length ('maxlen').
+#
+
+def _steal_trailing_WSP_if_exists(lines):
+    wsp = ''
+    if lines and lines[-1] and lines[-1][-1] in WSP:
+        wsp = lines[-1][-1]
+        lines[-1] = lines[-1][:-1]
+    return wsp
+
+def _refold_parse_tree(parse_tree, *, policy):
+    """Return string of contents of parse_tree folded according to RFC rules.
+
+    """
+    # max_line_length 0/None means no limit, ie: infinitely long.
+    maxlen = policy.max_line_length or sys.maxsize
+    encoding = 'utf-8' if policy.utf8 else 'us-ascii'
+    lines = ['']
+    last_ew = None
+    last_charset = None
+    wrap_as_ew_blocked = 0
+    want_encoding = False
+    end_ew_not_allowed = Terminal('', 'wrap_as_ew_blocked')
+    parts = list(parse_tree)
+    while parts:
+        part = parts.pop(0)
+        if part is end_ew_not_allowed:
+            wrap_as_ew_blocked -= 1
+            continue
+        tstr = str(part)
+        if not want_encoding:
+            if part.token_type in ('ptext', 'vtext'):
+                # Encode if tstr contains special characters.
+                want_encoding = not SPECIALSNL.isdisjoint(tstr)
+            else:
+                # Encode if tstr contains newlines.
+                want_encoding = not NLSET.isdisjoint(tstr)
+        try:
+            tstr.encode(encoding)
+            charset = encoding
+        except UnicodeEncodeError:
+            if any(isinstance(x, errors.UndecodableBytesDefect)
+                   for x in part.all_defects):
+                charset = 'unknown-8bit'
+            else:
+                # If policy.utf8 is false this should really be taken from a
+                # 'charset' property on the policy.
+                charset = 'utf-8'
+            want_encoding = True
+        if part.token_type == 'mime-parameters':
+            # Mime parameter folding (using RFC2231) is extra special.
+            _fold_mime_parameters(part, lines, maxlen, encoding)
+            continue
+        if want_encoding and not wrap_as_ew_blocked:
+            if not part.as_ew_allowed:
+                want_encoding = False
+                last_ew = None
+                if part.syntactic_break:
+                    encoded_part = part.fold(policy=policy)[:-len(policy.linesep)]
+                    if policy.linesep not in encoded_part:
+                        # It fits on a single line
+                        if len(encoded_part) > maxlen - len(lines[-1]):
+                            # But not on this one, so start a new one.
+                            newline = _steal_trailing_WSP_if_exists(lines)
+                            # XXX what if encoded_part has no leading FWS?
+                            lines.append(newline)
+                        lines[-1] += encoded_part
+                        continue
+                # Either this is not a major syntactic break, so we don't
+                # want it on a line by itself even if it fits, or it
+                # doesn't fit on a line by itself.  Either way, fall through
+                # to unpacking the subparts and wrapping them.
+            if not hasattr(part, 'encode'):
+                # It's not a Terminal, do each piece individually.
+                parts = list(part) + parts
+                want_encoding = False
+                continue
+            elif part.as_ew_allowed:
+                # It's a terminal, wrap it as an encoded word, possibly
+                # combining it with previously encoded words if allowed.
+                if (last_ew is not None and
+                    charset != last_charset and
+                    (last_charset == 'unknown-8bit' or
+                     last_charset == 'utf-8' and charset != 'us-ascii')):
+                    last_ew = None
+                last_ew = _fold_as_ew(tstr, lines, maxlen, last_ew,
+                                      part.ew_combine_allowed, charset)
+                last_charset = charset
+                want_encoding = False
+                continue
+            else:
+                # It's a terminal which should be kept non-encoded
+                # (e.g. a ListSeparator).
+                last_ew = None
+                want_encoding = False
+                # fall through
+
+        if len(tstr) <= maxlen - len(lines[-1]):
+            lines[-1] += tstr
+            continue
+        # This part is too long to fit.  The RFC wants us to break at
+        # "major syntactic breaks", so unless we don't consider this
+        # to be one, check if it will fit on the next line by itself.
+        if (part.syntactic_break and
+                len(tstr) + 1 <= maxlen):
+            newline = _steal_trailing_WSP_if_exists(lines)
+            if newline or part.startswith_fws():
+                lines.append(newline + tstr)
+                last_ew = None
+                continue
+        if not hasattr(part, 'encode'):
+            # It's not a terminal, try folding the subparts.
+            newparts = list(part)
+            if part.token_type == 'bare-quoted-string':
+                # To fold a quoted string we need to create a list of terminal
+                # tokens that will render the leading and trailing quotes
+                # and use quoted pairs in the value as appropriate.
+                newparts = (
+                    [ValueTerminal('"', 'ptext')] +
+                    [ValueTerminal(make_quoted_pairs(p), 'ptext')
+                     for p in newparts] +
+                    [ValueTerminal('"', 'ptext')])
+            if not part.as_ew_allowed:
+                wrap_as_ew_blocked += 1
+                newparts.append(end_ew_not_allowed)
+            parts = newparts + parts
+            continue
+        if part.as_ew_allowed and not wrap_as_ew_blocked:
+            # It doesn't need CTE encoding, but encode it anyway so we can
+            # wrap it.
+            parts.insert(0, part)
+            want_encoding = True
+            continue
+        # We can't figure out how to wrap, it, so give up.
+        newline = _steal_trailing_WSP_if_exists(lines)
+        if newline or part.startswith_fws():
+            lines.append(newline + tstr)
+        else:
+            # We can't fold it onto the next line either...
+            lines[-1] += tstr
+    return policy.linesep.join(lines) + policy.linesep
+
+def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset):
+    """Fold string to_encode into lines as encoded word, combining if allowed.
+    Return the new value for last_ew, or None if ew_combine_allowed is False.
+
+    If there is already an encoded word in the last line of lines (indicated by
+    a non-None value for last_ew) and ew_combine_allowed is true, decode the
+    existing ew, combine it with to_encode, and re-encode.  Otherwise, encode
+    to_encode.  In either case, split to_encode as necessary so that the
+    encoded segments fit within maxlen.
+
+    """
+    if last_ew is not None and ew_combine_allowed:
+        to_encode = str(
+            get_unstructured(lines[-1][last_ew:] + to_encode))
+        lines[-1] = lines[-1][:last_ew]
+    if to_encode[0] in WSP:
+        # We're joining this to non-encoded text, so don't encode
+        # the leading blank.
+        leading_wsp = to_encode[0]
+        to_encode = to_encode[1:]
+        if (len(lines[-1]) == maxlen):
+            lines.append(_steal_trailing_WSP_if_exists(lines))
+        lines[-1] += leading_wsp
+    trailing_wsp = ''
+    if to_encode[-1] in WSP:
+        # Likewise for the trailing space.
+        trailing_wsp = to_encode[-1]
+        to_encode = to_encode[:-1]
+    new_last_ew = len(lines[-1]) if last_ew is None else last_ew
+
+    encode_as = 'utf-8' if charset == 'us-ascii' else charset
+
+    # The RFC2047 chrome takes up 7 characters plus the length
+    # of the charset name.
+    chrome_len = len(encode_as) + 7
+
+    if (chrome_len + 1) >= maxlen:
+        raise errors.HeaderParseError(
+            "max_line_length is too small to fit an encoded word")
+
+    while to_encode:
+        remaining_space = maxlen - len(lines[-1])
+        text_space = remaining_space - chrome_len
+        if text_space <= 0:
+            lines.append(' ')
+            continue
+
+        to_encode_word = to_encode[:text_space]
+        encoded_word = _ew.encode(to_encode_word, charset=encode_as)
+        excess = len(encoded_word) - remaining_space
+        while excess > 0:
+            # Since the chunk to encode is guaranteed to fit into less than 100 characters,
+            # shrinking it by one at a time shouldn't take long.
+            to_encode_word = to_encode_word[:-1]
+            encoded_word = _ew.encode(to_encode_word, charset=encode_as)
+            excess = len(encoded_word) - remaining_space
+        lines[-1] += encoded_word
+        to_encode = to_encode[len(to_encode_word):]
+
+        if to_encode:
+            lines.append(' ')
+            new_last_ew = len(lines[-1])
+    lines[-1] += trailing_wsp
+    return new_last_ew if ew_combine_allowed else None
+
+def _fold_mime_parameters(part, lines, maxlen, encoding):
+    """Fold TokenList 'part' into the 'lines' list as mime parameters.
+
+    Using the decoded list of parameters and values, format them according to
+    the RFC rules, including using RFC2231 encoding if the value cannot be
+    expressed in 'encoding' and/or the parameter+value is too long to fit
+    within 'maxlen'.
+
+    """
+    # Special case for RFC2231 encoding: start from decoded values and use
+    # RFC2231 encoding iff needed.
+    #
+    # Note that the 1 and 2s being added to the length calculations are
+    # accounting for the possibly-needed spaces and semicolons we'll be adding.
+    #
+    for name, value in part.params:
+        # XXX What if this ';' puts us over maxlen the first time through the
+        # loop?  We should split the header value onto a newline in that case,
+        # but to do that we need to recognize the need earlier or reparse the
+        # header, so I'm going to ignore that bug for now.  It'll only put us
+        # one character over.
+        if not lines[-1].rstrip().endswith(';'):
+            lines[-1] += ';'
+        charset = encoding
+        error_handler = 'strict'
+        try:
+            value.encode(encoding)
+            encoding_required = False
+        except UnicodeEncodeError:
+            encoding_required = True
+            if utils._has_surrogates(value):
+                charset = 'unknown-8bit'
+                error_handler = 'surrogateescape'
+            else:
+                charset = 'utf-8'
+        if encoding_required:
+            encoded_value = urllib.parse.quote(
+                value, safe='', errors=error_handler)
+            tstr = "{}*={}''{}".format(name, charset, encoded_value)
+        else:
+            tstr = '{}={}'.format(name, quote_string(value))
+        if len(lines[-1]) + len(tstr) + 1 < maxlen:
+            lines[-1] = lines[-1] + ' ' + tstr
+            continue
+        elif len(tstr) + 2 <= maxlen:
+            lines.append(' ' + tstr)
+            continue
+        # We need multiple sections.  We are allowed to mix encoded and
+        # non-encoded sections, but we aren't going to.  We'll encode them all.
+        section = 0
+        extra_chrome = charset + "''"
+        while value:
+            chrome_len = len(name) + len(str(section)) + 3 + len(extra_chrome)
+            if maxlen <= chrome_len + 3:
+                # We need room for the leading blank, the trailing semicolon,
+                # and at least one character of the value.  If we don't
+                # have that, we'd be stuck, so in that case fall back to
+                # the RFC standard width.
+                maxlen = 78
+            splitpoint = maxchars = maxlen - chrome_len - 2
+            while True:
+                partial = value[:splitpoint]
+                encoded_value = urllib.parse.quote(
+                    partial, safe='', errors=error_handler)
+                if len(encoded_value) <= maxchars:
+                    break
+                splitpoint -= 1
+            lines.append(" {}*{}*={}{}".format(
+                name, section, extra_chrome, encoded_value))
+            extra_chrome = ''
+            section += 1
+            value = value[splitpoint:]
+            if value:
+                lines[-1] += ';'
diff --git a/shared/package-files/b9/b93b9f845ca4b4d8ad1ff4c24d019cba1d03defb1aa6c1a777a166b600edcfe9/_meta.cpython-311.pyc b/shared/package-files/b9/b93b9f845ca4b4d8ad1ff4c24d019cba1d03defb1aa6c1a777a166b600edcfe9/_meta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e6ea3bd14857f96644816a3c810610a8568e507
Binary files /dev/null and b/shared/package-files/b9/b93b9f845ca4b4d8ad1ff4c24d019cba1d03defb1aa6c1a777a166b600edcfe9/_meta.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b93e6425af4356487015531f30c9e295642789ef243725590f4a34efe1ef4b6e/functional_call.py b/shared/package-files/b9/b93e6425af4356487015531f30c9e295642789ef243725590f4a34efe1ef4b6e/functional_call.py
new file mode 100644
index 0000000000000000000000000000000000000000..62ca24ab3fdb961c030f9ed721e5dd16ce36772c
--- /dev/null
+++ b/shared/package-files/b9/b93e6425af4356487015531f30c9e295642789ef243725590f4a34efe1ef4b6e/functional_call.py
@@ -0,0 +1,253 @@
+# mypy: allow-untyped-defs
+from collections.abc import Sequence
+from typing import Any, Optional, Union
+
+import torch
+import torch.nn as nn
+from torch import Tensor
+from torch._functorch.utils import exposed_in
+
+
+@exposed_in("torch.func")
+def functional_call(
+    module: "torch.nn.Module",
+    parameter_and_buffer_dicts: Union[dict[str, Tensor], Sequence[dict[str, Tensor]]],
+    args: Optional[Union[Any, tuple]] = None,
+    kwargs: Optional[dict[str, Any]] = None,
+    *,
+    tie_weights: bool = True,
+    strict: bool = False,
+):
+    r"""Performs a functional call on the module by replacing the module parameters
+    and buffers with the provided ones.
+
+    .. note:: If the module has active parametrizations, passing a value in the
+        :attr:`parameter_and_buffer_dicts` argument with the name set to the regular parameter
+        name will completely disable the parametrization.
+        If you want to apply the parametrization function to the value passed
+        please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``.
+
+    .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected
+        in the ``parameter_and_buffer_dicts`` input.
+
+
+         Example::
+
+            >>> a = {'foo': torch.zeros(())}
+            >>> # xdoctest: +SKIP
+            >>> mod = Foo()  # does self.foo = self.foo + 1
+            >>> print(mod.foo)  # tensor(0.)
+            >>> functional_call(mod, a, torch.ones(()))
+            >>> print(mod.foo)  # tensor(0.)
+            >>> print(a['foo'])  # tensor(1.)
+
+    .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the
+        tie_weights flag.
+
+        Example::
+
+            >>> a = {'foo': torch.zeros(())}
+            >>> # xdoctest: +SKIP
+            >>> mod = Foo()  # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied
+            >>> print(mod.foo)  # tensor(1.)
+            >>> mod(torch.zeros(()))  # tensor(2.)
+            >>> functional_call(mod, a, torch.zeros(()))  # tensor(0.) since it will change self.foo_tied too
+            >>> functional_call(mod, a, torch.zeros(()), tie_weights=False)  # tensor(1.)--self.foo_tied is not updated
+            >>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())}
+            >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.)
+
+    An example of passing multiple dictionaries
+
+    .. code-block:: python
+
+            a = ({'weight': torch.ones(1, 1)}, {'buffer': torch.zeros(1)})  # two separate dictionaries
+            mod = nn.Bar(1, 1)  # return self.weight @ x + self.buffer
+            print(mod.weight)  # tensor(...)
+            print(mod.buffer)  # tensor(...)
+            x = torch.randn((1, 1))
+            print(x)
+            functional_call(mod, a, x)  # same as x
+            print(mod.weight)  # same as before functional_call
+
+
+    And here is an example of applying the grad transform over the parameters
+    of a model.
+
+    .. code-block:: python
+
+        import torch
+        import torch.nn as nn
+        from torch.func import functional_call, grad
+
+        x = torch.randn(4, 3)
+        t = torch.randn(4, 3)
+        model = nn.Linear(3, 3)
+
+        def compute_loss(params, x, t):
+            y = functional_call(model, params, x)
+            return nn.functional.mse_loss(y, t)
+
+        grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t)
+
+    .. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the
+        parameters for better performance and memory usage
+
+        Example::
+
+            >>> detached_params = {k: v.detach() for k, v in model.named_parameters()}
+            >>> grad_weights = grad(compute_loss)(detached_params, x, t)
+            >>> grad_weights.grad_fn  # None--it's not tracking gradients outside of grad
+
+        This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking
+        outside of the transforms, this will result in less memory usage and faster speeds.
+
+    Args:
+        module (torch.nn.Module): the module to call
+        parameters_and_buffer_dicts (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in
+            the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can
+            be used together
+        args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument.
+        kwargs (dict): keyword arguments to be passed to the module call
+        tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as
+            tied in the reparameterized version. Therefore, if True and different values are passed for the tied
+            parameters and buffers, it will error. If False, it will not respect the originally tied parameters and
+            buffers unless the values passed for both weights are the same. Default: True.
+        strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and
+            buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will
+            error. Default: False.
+
+    Returns:
+        Any: the result of calling ``module``.
+    """
+    if isinstance(parameter_and_buffer_dicts, dict):
+        parameters_and_buffers = parameter_and_buffer_dicts
+    elif isinstance(parameter_and_buffer_dicts, Sequence):
+        if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts):
+            raise ValueError(
+                "Expected all elements of parameter_and_buffer_dicts to be dictionaries"
+            )
+        all_keys = [k for d in parameter_and_buffer_dicts for k in d.keys()]
+        all_keys_counter: dict[str, int] = {}
+        for k in all_keys:
+            v = all_keys_counter.get(k, 0)
+            all_keys_counter[k] = v + 1
+        repeated_keys = [key for key, n in all_keys_counter.items() if n > 1]
+        if len(repeated_keys) > 0:
+            raise ValueError(
+                f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous"
+            )
+        parameters_and_buffers = {
+            k: v for d in parameter_and_buffer_dicts for k, v in d.items()
+        }
+    else:
+        raise ValueError(
+            f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, "
+            f"but got {type(parameter_and_buffer_dicts)}"
+        )
+
+    return nn.utils.stateless._functional_call(
+        module,
+        parameters_and_buffers,
+        args,
+        kwargs,
+        tie_weights=tie_weights,
+        strict=strict,
+    )
+
+
+@exposed_in("torch.func")
+def stack_module_state(
+    models: Union[Sequence[nn.Module], nn.ModuleList],
+) -> tuple[dict[str, Any], dict[str, Any]]:
+    """stack_module_state(models) -> params, buffers
+
+    Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
+
+    Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries
+    that stack all of their parameters and buffers together, indexed by name.
+    The stacked parameters are optimizable (i.e. they are new leaf nodes in the
+    autograd history that are unrelated to the original parameters and can be
+    passed directly to an optimizer).
+
+    Here's an example of how to ensemble over a very simple model:
+
+    .. code-block:: python
+
+        num_models = 5
+        batch_size = 64
+        in_features, out_features = 3, 3
+        models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
+        data = torch.randn(batch_size, 3)
+
+        def wrapper(params, buffers, data):
+            return torch.func.functional_call(models[0], (params, buffers), data)
+
+        params, buffers = stack_module_state(models)
+        output = vmap(wrapper, (0, 0, None))(params, buffers, data)
+
+        assert output.shape == (num_models, batch_size, out_features)
+
+    When there's submodules, this follows state dict naming conventions
+
+    .. code-block:: python
+
+        import torch.nn as nn
+        class Foo(nn.Module):
+            def __init__(self, in_features, out_features):
+                super().__init__()
+                hidden = 4
+                self.l1 = nn.Linear(in_features, hidden)
+                self.l2 = nn.Linear(hidden, out_features)
+
+            def forward(self, x):
+                return self.l2(self.l1(x))
+
+        num_models = 5
+        in_features, out_features = 3, 3
+        models = [Foo(in_features, out_features) for i in range(num_models)]
+        params, buffers = stack_module_state(models)
+        print(list(params.keys()))  # "l1.weight", "l1.bias", "l2.weight", "l2.bias"
+
+    .. warning::
+        All of the modules being stacked together must be the same (except for
+        the values of their parameters/buffers). For example, they should be in the
+        same mode (training vs eval).
+    """
+    if len(models) == 0:
+        raise RuntimeError("stack_module_state: Expected at least one model, got 0.")
+    if not (all(m.training for m in models) or all(not m.training for m in models)):
+        raise RuntimeError(
+            "stack_module_state: Expected all models to have the same training/eval mode."
+        )
+    model0_typ = type(models[0])
+    if not all(type(m) == model0_typ for m in models):
+        raise RuntimeError(
+            "stack_module_state: Expected all models to be of the same class."
+        )
+    all_params = [dict(model.named_parameters()) for model in models]
+    params = {
+        k: construct_stacked_leaf(tuple(params[k] for params in all_params), k)
+        for k in all_params[0]
+    }
+    all_buffers = [dict(model.named_buffers()) for model in models]
+    buffers = {
+        k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k)
+        for k in all_buffers[0]
+    }
+
+    return params, buffers
+
+
+def construct_stacked_leaf(
+    tensors: Union[tuple[Tensor, ...], list[Tensor]], name: str
+) -> Tensor:
+    all_requires_grad = all(t.requires_grad for t in tensors)
+    none_requires_grad = all(not t.requires_grad for t in tensors)
+    if not all_requires_grad and not none_requires_grad:
+        raise RuntimeError(
+            f"Expected {name} from each model to have the same .requires_grad"
+        )
+    result = torch.stack(tensors)
+    if all_requires_grad:
+        result = result.detach().requires_grad_()
+    return result
diff --git a/shared/package-files/b9/b940adc6d23593bcd32a4b95ce2b55ea4b5c08c803be05526380d70652e19d94/_util.py b/shared/package-files/b9/b940adc6d23593bcd32a4b95ce2b55ea4b5c08c803be05526380d70652e19d94/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3005dbd79da1128d41d9a5e7067efc337c44c7f0
--- /dev/null
+++ b/shared/package-files/b9/b940adc6d23593bcd32a4b95ce2b55ea4b5c08c803be05526380d70652e19d94/_util.py
@@ -0,0 +1,261 @@
+# mypy: ignore-errors
+
+"""Assorted utilities, which do not need anything other then torch and stdlib.
+"""
+
+import operator
+
+import torch
+
+from . import _dtypes_impl
+
+
+# https://github.com/numpy/numpy/blob/v1.23.0/numpy/distutils/misc_util.py#L497-L504
+def is_sequence(seq):
+    if isinstance(seq, str):
+        return False
+    try:
+        len(seq)
+    except Exception:
+        return False
+    return True
+
+
+class AxisError(ValueError, IndexError):
+    pass
+
+
+class UFuncTypeError(TypeError, RuntimeError):
+    pass
+
+
+def cast_if_needed(tensor, dtype):
+    # NB: no casting if dtype=None
+    if dtype is not None and tensor.dtype != dtype:
+        tensor = tensor.to(dtype)
+    return tensor
+
+
+def cast_int_to_float(x):
+    # cast integers and bools to the default float dtype
+    if _dtypes_impl._category(x.dtype) < 2:
+        x = x.to(_dtypes_impl.default_dtypes().float_dtype)
+    return x
+
+
+# a replica of the version in ./numpy/numpy/core/src/multiarray/common.h
+def normalize_axis_index(ax, ndim, argname=None):
+    if not (-ndim <= ax < ndim):
+        raise AxisError(f"axis {ax} is out of bounds for array of dimension {ndim}")
+    if ax < 0:
+        ax += ndim
+    return ax
+
+
+# from https://github.com/numpy/numpy/blob/main/numpy/core/numeric.py#L1378
+def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
+    """
+    Normalizes an axis argument into a tuple of non-negative integer axes.
+
+    This handles shorthands such as ``1`` and converts them to ``(1,)``,
+    as well as performing the handling of negative indices covered by
+    `normalize_axis_index`.
+
+    By default, this forbids axes from being specified multiple times.
+    Used internally by multi-axis-checking logic.
+
+    Parameters
+    ----------
+    axis : int, iterable of int
+        The un-normalized index or indices of the axis.
+    ndim : int
+        The number of dimensions of the array that `axis` should be normalized
+        against.
+    argname : str, optional
+        A prefix to put before the error message, typically the name of the
+        argument.
+    allow_duplicate : bool, optional
+        If False, the default, disallow an axis from being specified twice.
+
+    Returns
+    -------
+    normalized_axes : tuple of int
+        The normalized axis index, such that `0 <= normalized_axis < ndim`
+    """
+    # Optimization to speed-up the most common cases.
+    if type(axis) not in (tuple, list):
+        try:
+            axis = [operator.index(axis)]
+        except TypeError:
+            pass
+    # Going via an iterator directly is slower than via list comprehension.
+    axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
+    if not allow_duplicate and len(set(map(int, axis))) != len(axis):
+        if argname:
+            raise ValueError(f"repeated axis in `{argname}` argument")
+        else:
+            raise ValueError("repeated axis")
+    return axis
+
+
+def allow_only_single_axis(axis):
+    if axis is None:
+        return axis
+    if len(axis) != 1:
+        raise NotImplementedError("does not handle tuple axis")
+    return axis[0]
+
+
+def expand_shape(arr_shape, axis):
+    # taken from numpy 1.23.x, expand_dims function
+    if type(axis) not in (list, tuple):
+        axis = (axis,)
+    out_ndim = len(axis) + len(arr_shape)
+    axis = normalize_axis_tuple(axis, out_ndim)
+    shape_it = iter(arr_shape)
+    shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
+    return shape
+
+
+def apply_keepdims(tensor, axis, ndim):
+    if axis is None:
+        # tensor was a scalar
+        shape = (1,) * ndim
+        tensor = tensor.expand(shape).contiguous()
+    else:
+        shape = expand_shape(tensor.shape, axis)
+        tensor = tensor.reshape(shape)
+    return tensor
+
+
+def axis_none_flatten(*tensors, axis=None):
+    """Flatten the arrays if axis is None."""
+    if axis is None:
+        tensors = tuple(ar.flatten() for ar in tensors)
+        return tensors, 0
+    else:
+        return tensors, axis
+
+
+def typecast_tensor(t, target_dtype, casting):
+    """Dtype-cast tensor to target_dtype.
+
+    Parameters
+    ----------
+    t : torch.Tensor
+        The tensor to cast
+    target_dtype : torch dtype object
+        The array dtype to cast all tensors to
+    casting : str
+        The casting mode, see `np.can_cast`
+
+     Returns
+     -------
+    `torch.Tensor` of the `target_dtype` dtype
+
+     Raises
+     ------
+     ValueError
+        if the argument cannot be cast according to the `casting` rule
+
+    """
+    can_cast = _dtypes_impl.can_cast_impl
+
+    if not can_cast(t.dtype, target_dtype, casting=casting):
+        raise TypeError(
+            f"Cannot cast array data from {t.dtype} to"
+            f" {target_dtype} according to the rule '{casting}'"
+        )
+    return cast_if_needed(t, target_dtype)
+
+
+def typecast_tensors(tensors, target_dtype, casting):
+    return tuple(typecast_tensor(t, target_dtype, casting) for t in tensors)
+
+
+def _try_convert_to_tensor(obj):
+    try:
+        tensor = torch.as_tensor(obj)
+    except Exception as e:
+        mesg = f"failed to convert {obj} to ndarray. \nInternal error is: {str(e)}."
+        raise NotImplementedError(mesg)  # noqa: B904
+    return tensor
+
+
+def _coerce_to_tensor(obj, dtype=None, copy=False, ndmin=0):
+    """The core logic of the array(...) function.
+
+    Parameters
+    ----------
+    obj : tensor_like
+        The thing to coerce
+    dtype : torch.dtype object or None
+        Coerce to this torch dtype
+    copy : bool
+        Copy or not
+    ndmin : int
+        The results as least this many dimensions
+    is_weak : bool
+        Whether obj is a weakly typed python scalar.
+
+    Returns
+    -------
+    tensor : torch.Tensor
+        a tensor object with requested dtype, ndim and copy semantics.
+
+    Notes
+    -----
+    This is almost a "tensor_like" coersion function. Does not handle wrapper
+    ndarrays (those should be handled in the ndarray-aware layer prior to
+    invoking this function).
+    """
+    if isinstance(obj, torch.Tensor):
+        tensor = obj
+    else:
+        # tensor.dtype is the pytorch default, typically float32. If obj's elements
+        # are not exactly representable in float32, we've lost precision:
+        # >>> torch.as_tensor(1e12).item() - 1e12
+        # -4096.0
+        default_dtype = torch.get_default_dtype()
+        torch.set_default_dtype(_dtypes_impl.get_default_dtype_for(torch.float32))
+        try:
+            tensor = _try_convert_to_tensor(obj)
+        finally:
+            torch.set_default_dtype(default_dtype)
+
+    # type cast if requested
+    tensor = cast_if_needed(tensor, dtype)
+
+    # adjust ndim if needed
+    ndim_extra = ndmin - tensor.ndim
+    if ndim_extra > 0:
+        tensor = tensor.view((1,) * ndim_extra + tensor.shape)
+
+    # copy if requested
+    if copy:
+        tensor = tensor.clone()
+
+    return tensor
+
+
+def ndarrays_to_tensors(*inputs):
+    """Convert all ndarrays from `inputs` to tensors. (other things are intact)"""
+    from ._ndarray import ndarray
+
+    if len(inputs) == 0:
+        return ValueError()
+    elif len(inputs) == 1:
+        input_ = inputs[0]
+        if isinstance(input_, ndarray):
+            return input_.tensor
+        elif isinstance(input_, tuple):
+            result = []
+            for sub_input in input_:
+                sub_result = ndarrays_to_tensors(sub_input)
+                result.append(sub_result)
+            return tuple(result)
+        else:
+            return input_
+    else:
+        assert isinstance(inputs, tuple)  # sanity check
+        return ndarrays_to_tensors(inputs)
diff --git a/shared/package-files/b9/b94450ef0ac6e70c64b3be14a6b6b650f7df6ed3ffb9c593cea86dd5be8a413b/local_elastic_agent.cpython-311.pyc b/shared/package-files/b9/b94450ef0ac6e70c64b3be14a6b6b650f7df6ed3ffb9c593cea86dd5be8a413b/local_elastic_agent.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c65e2b01209aa061bfe36413edf3b2a1f24674b5
Binary files /dev/null and b/shared/package-files/b9/b94450ef0ac6e70c64b3be14a6b6b650f7df6ed3ffb9c593cea86dd5be8a413b/local_elastic_agent.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b94d3aebad645efa67b0a0be9d6edfd96eff3914ab192bd1b6b49d04e58fbb9e/multi_margin_loss_backward_cuda_dispatch.h b/shared/package-files/b9/b94d3aebad645efa67b0a0be9d6edfd96eff3914ab192bd1b6b49d04e58fbb9e/multi_margin_loss_backward_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..b491998c0c3d2c37712a3f505c22441a0d893b5e
--- /dev/null
+++ b/shared/package-files/b9/b94d3aebad645efa67b0a0be9d6edfd96eff3914ab192bd1b6b49d04e58fbb9e/multi_margin_loss_backward_cuda_dispatch.h
@@ -0,0 +1,25 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API at::Tensor multi_margin_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const at::Scalar & p, const at::Scalar & margin, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean);
+TORCH_API at::Tensor & multi_margin_loss_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const at::Scalar & p, const at::Scalar & margin, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean);
+TORCH_API at::Tensor & multi_margin_loss_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const at::Scalar & p, const at::Scalar & margin, const ::std::optional & weight, int64_t reduction, at::Tensor & grad_input);
+
+} // namespace cuda
+} // namespace at
diff --git a/shared/package-files/b9/b95273100cc9c282e5a5173315f478845783a8606544c73a6be1886c7b824907/__init__.cpython-311.pyc b/shared/package-files/b9/b95273100cc9c282e5a5173315f478845783a8606544c73a6be1886c7b824907/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18345dc65a71a066f8403deb8fe4e36dc8ec253a
Binary files /dev/null and b/shared/package-files/b9/b95273100cc9c282e5a5173315f478845783a8606544c73a6be1886c7b824907/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b957c99c1b88347be671776cffecf165b5408ca3be08ef8ebb02b9beab830df7/binary_cross_entropy_backward_cpu_dispatch.h b/shared/package-files/b9/b957c99c1b88347be671776cffecf165b5408ca3be08ef8ebb02b9beab830df7/binary_cross_entropy_backward_cpu_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..150836c2539b63cd7e5fb39013a503b971da3ed4
--- /dev/null
+++ b/shared/package-files/b9/b957c99c1b88347be671776cffecf165b5408ca3be08ef8ebb02b9beab830df7/binary_cross_entropy_backward_cpu_dispatch.h
@@ -0,0 +1,25 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cpu {
+
+TORCH_API at::Tensor binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean);
+TORCH_API at::Tensor & binary_cross_entropy_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean);
+TORCH_API at::Tensor & binary_cross_entropy_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, at::Tensor & grad_input);
+
+} // namespace cpu
+} // namespace at
diff --git a/shared/package-files/b9/b95f0e88cbd637fcefc222a17d81160f4312b6d0bb121086180506438b6a18fe/debug_util.h b/shared/package-files/b9/b95f0e88cbd637fcefc222a17d81160f4312b6d0bb121086180506438b6a18fe/debug_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..2847de6554234e2ade6ca0083e8a91b6d47fdcdc
--- /dev/null
+++ b/shared/package-files/b9/b95f0e88cbd637fcefc222a17d81160f4312b6d0bb121086180506438b6a18fe/debug_util.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch::lazy {
+
+TORCH_API std::function()>&
+GetPythonFramesFunction();
+
+TORCH_API std::string GetFirstUserFrameInPython();
+
+class TORCH_API DebugUtil {
+ public:
+  enum GraphFormat {
+    kText,
+    kDot,
+    kBackend,
+  };
+
+  static GraphFormat GetDefaultGraphFormat();
+
+  // Dumps the current Python frame and the IR Graph whose roots are the IR
+  // values held at the tensors. If indices is not nullptr, it selects the
+  // indices of the tensors whose graph will be emitted.
+  static std::string GetTensorsGraphInfo(
+      c10::ArrayRef tensors,
+      const std::vector* indices,
+      GraphFormat format = GetDefaultGraphFormat());
+
+  // If the environment variable LTC_SAVE_TENSORS_FILE is set to the proper
+  // output path, an instance of the report returned by GetTensorsGraphInfo() is
+  // saved.
+  static void SaveTensorsGraphInfo(
+      const char* name,
+      c10::ArrayRef tensors,
+      const std::vector* indices,
+      GraphFormat format = GetDefaultGraphFormat());
+
+  static bool ExperimentEnabled(const std::string& name);
+};
+
+} // namespace torch::lazy
diff --git a/shared/package-files/b9/b95fdf474695c87de3115cbc4fc1d3c54f62587122c93a8ee9561dc723444b06/_make_per_channel_quantized_tensor_native.h b/shared/package-files/b9/b95fdf474695c87de3115cbc4fc1d3c54f62587122c93a8ee9561dc723444b06/_make_per_channel_quantized_tensor_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..2a6f90dd87402c9c39151641e0e75aaaaa433f29
--- /dev/null
+++ b/shared/package-files/b9/b95fdf474695c87de3115cbc4fc1d3c54f62587122c93a8ee9561dc723444b06/_make_per_channel_quantized_tensor_native.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & _make_per_channel_quantized_tensor_out(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, at::Tensor & out);
+TORCH_API at::Tensor make_per_channel_quantized_tensor_cpu(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis);
+TORCH_API at::Tensor make_per_channel_quantized_tensor_cuda(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b9/b960dfd052a030ba0dbdd8602f247dd3175d7009e8de5af25434584fad52b6ec/__init__.py b/shared/package-files/b9/b960dfd052a030ba0dbdd8602f247dd3175d7009e8de5af25434584fad52b6ec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..080394810b7e0309de4d1709287f3205482e936c
--- /dev/null
+++ b/shared/package-files/b9/b960dfd052a030ba0dbdd8602f247dd3175d7009e8de5af25434584fad52b6ec/__init__.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from .drawing import BoxStyle
+from .traversal import DictTraversal
+from .util import KeyArgsConstructor
+
+
+class LeftAligned(KeyArgsConstructor):
+    """Creates a renderer for a left-aligned tree.
+
+    Any attributes of the resulting class instances can be set using
+    constructor arguments."""
+
+    draw = BoxStyle()
+    "The draw style used. See :class:`~asciitree.drawing.Style`."
+    traverse = DictTraversal()
+    "Traversal method. See :class:`~asciitree.traversal.Traversal`."
+
+    def render(self, node):
+        """Renders a node. This function is used internally, as it returns
+        a list of lines. Use :func:`~asciitree.LeftAligned.__call__` instead.
+        """
+        lines = []
+
+        children = self.traverse.get_children(node)
+        lines.append(self.draw.node_label(self.traverse.get_text(node)))
+
+        for n, child in enumerate(children):
+            child_tree = self.render(child)
+
+            if n == len(children) - 1:
+                # last child does not get the line drawn
+                lines.append(self.draw.last_child_head(child_tree.pop(0)))
+                lines.extend(self.draw.last_child_tail(l)
+                             for l in child_tree)
+            else:
+                lines.append(self.draw.child_head(child_tree.pop(0)))
+                lines.extend(self.draw.child_tail(l)
+                             for l in child_tree)
+
+        return lines
+
+    def __call__(self, tree):
+        """Render the tree into string suitable for console output.
+
+        :param tree: A tree."""
+        return '\n'.join(self.render(self.traverse.get_root(tree)))
+
+
+# legacy support below
+
+from .drawing import Style
+from .traversal import Traversal
+
+
+class LegacyStyle(Style):
+    def node_label(self, text):
+        return text
+
+    def child_head(self, label):
+        return '  +--' + label
+
+    def child_tail(self, line):
+        return '  |' + line
+
+    def last_child_head(self, label):
+        return '  +--' + label
+
+    def last_child_tail(self, line):
+        return '   ' + line
+
+
+def draw_tree(node,
+              child_iter=lambda n: n.children,
+              text_str=str):
+    """Support asciitree 0.2 API.
+
+    This function solely exist to not break old code (using asciitree 0.2).
+    Its use is deprecated."""
+    return LeftAligned(traverse=Traversal(get_text=text_str,
+                                          get_children=child_iter),
+                       draw=LegacyStyle())(node)
diff --git a/shared/package-files/b9/b962d2bf1c57ad89d6542e64a42fc2bd4a060198cd7177b8684155b6bf25ab39/index_select_backward_native.h b/shared/package-files/b9/b962d2bf1c57ad89d6542e64a42fc2bd4a060198cd7177b8684155b6bf25ab39/index_select_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..aaa014c73fe97f251f4d804791a36d262f0bae0e
--- /dev/null
+++ b/shared/package-files/b9/b962d2bf1c57ad89d6542e64a42fc2bd4a060198cd7177b8684155b6bf25ab39/index_select_backward_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor index_select_backward_symint(const at::Tensor & grad, c10::SymIntArrayRef self_sizes, int64_t dim, const at::Tensor & index);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b9/b96304c12946b126b2b7897b3682ff88c481fb309c7125a49b45f7eee7a66506/renorm_ops.h b/shared/package-files/b9/b96304c12946b126b2b7897b3682ff88c481fb309c7125a49b45f7eee7a66506/renorm_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..e402c0df7b985bee3d501f62fbe8d5459353eeb2
--- /dev/null
+++ b/shared/package-files/b9/b96304c12946b126b2b7897b3682ff88c481fb309c7125a49b45f7eee7a66506/renorm_ops.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API renorm_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::renorm";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm, at::Tensor & out);
+};
+
+struct TORCH_API renorm {
+  using schema = at::Tensor (const at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::renorm";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm);
+};
+
+struct TORCH_API renorm_ {
+  using schema = at::Tensor & (at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::renorm_";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b9663f0142ae692e3865b495e592c0533142b5503614e9aa04b630db97ea51e2/rpc_agent_test_fixture.cpython-311.pyc b/shared/package-files/b9/b9663f0142ae692e3865b495e592c0533142b5503614e9aa04b630db97ea51e2/rpc_agent_test_fixture.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bf9ebdbeafc8d03d978b04e15afff51f127e141
Binary files /dev/null and b/shared/package-files/b9/b9663f0142ae692e3865b495e592c0533142b5503614e9aa04b630db97ea51e2/rpc_agent_test_fixture.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9668cd791be7679d882725df38ddce27ff7ebbee5693b286ee5589321c2315b/fuse_handler.cpython-311.pyc b/shared/package-files/b9/b9668cd791be7679d882725df38ddce27ff7ebbee5693b286ee5589321c2315b/fuse_handler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f080a9f852beb5649de4bbbef788f172495216f
Binary files /dev/null and b/shared/package-files/b9/b9668cd791be7679d882725df38ddce27ff7ebbee5693b286ee5589321c2315b/fuse_handler.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9680a3f2dd7e96138240abf41c4321266651d170fbc2163afe453bd8ea23f36/method.cpython-311.pyc b/shared/package-files/b9/b9680a3f2dd7e96138240abf41c4321266651d170fbc2163afe453bd8ea23f36/method.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23e960c432c646caf324b78d26f933b983fc91c1
Binary files /dev/null and b/shared/package-files/b9/b9680a3f2dd7e96138240abf41c4321266651d170fbc2163afe453bd8ea23f36/method.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b96d77d9a36e6212f18ba4eea1afa9aa12d533bb5893d12b461af36bb7481290/log_softmax_ops.h b/shared/package-files/b9/b96d77d9a36e6212f18ba4eea1afa9aa12d533bb5893d12b461af36bb7481290/log_softmax_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..57364e65e6d584caf379a9383549cbf8d81acbb2
--- /dev/null
+++ b/shared/package-files/b9/b96d77d9a36e6212f18ba4eea1afa9aa12d533bb5893d12b461af36bb7481290/log_softmax_ops.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API log_softmax_int {
+  using schema = at::Tensor (const at::Tensor &, int64_t, ::std::optional);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::log_softmax";
+  static constexpr const char* overload_name = "int";
+  static constexpr const char* schema_str = "log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, int64_t dim, ::std::optional dtype);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, ::std::optional dtype);
+};
+
+struct TORCH_API log_softmax_int_out {
+  using schema = at::Tensor & (const at::Tensor &, int64_t, ::std::optional, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::log_softmax";
+  static constexpr const char* overload_name = "int_out";
+  static constexpr const char* schema_str = "log_softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, int64_t dim, ::std::optional dtype, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, ::std::optional dtype, at::Tensor & out);
+};
+
+struct TORCH_API log_softmax_Dimname {
+  using schema = at::Tensor (const at::Tensor &, at::Dimname, ::std::optional);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::log_softmax";
+  static constexpr const char* overload_name = "Dimname";
+  static constexpr const char* schema_str = "log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, at::Dimname dim, ::std::optional dtype);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, ::std::optional dtype);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b96f03a827578807b2a6434f29c0185fb696f3a09ac181fce10d1b5b87034d7a/test_hierarchy.py b/shared/package-files/b9/b96f03a827578807b2a6434f29c0185fb696f3a09ac181fce10d1b5b87034d7a/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaa6a67b8b7f048719aa189b8365ef8e4c65951c
--- /dev/null
+++ b/shared/package-files/b9/b96f03a827578807b2a6434f29c0185fb696f3a09ac181fce10d1b5b87034d7a/test_hierarchy.py
@@ -0,0 +1,46 @@
+import pytest
+
+import networkx as nx
+
+
+def test_hierarchy_undirected():
+    G = nx.cycle_graph(5)
+    pytest.raises(nx.NetworkXError, nx.flow_hierarchy, G)
+
+
+def test_hierarchy_cycle():
+    G = nx.cycle_graph(5, create_using=nx.DiGraph())
+    assert nx.flow_hierarchy(G) == 0.0
+
+
+def test_hierarchy_tree():
+    G = nx.full_rary_tree(2, 16, create_using=nx.DiGraph())
+    assert nx.flow_hierarchy(G) == 1.0
+
+
+def test_hierarchy_1():
+    G = nx.DiGraph()
+    G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 1), (3, 4), (0, 4)])
+    assert nx.flow_hierarchy(G) == 0.5
+
+
+def test_hierarchy_weight():
+    G = nx.DiGraph()
+    G.add_edges_from(
+        [
+            (0, 1, {"weight": 0.3}),
+            (1, 2, {"weight": 0.1}),
+            (2, 3, {"weight": 0.1}),
+            (3, 1, {"weight": 0.1}),
+            (3, 4, {"weight": 0.3}),
+            (0, 4, {"weight": 0.3}),
+        ]
+    )
+    assert nx.flow_hierarchy(G, weight="weight") == 0.75
+
+
+@pytest.mark.parametrize("n", (0, 1, 3))
+def test_hierarchy_empty_graph(n):
+    G = nx.empty_graph(n, create_using=nx.DiGraph)
+    with pytest.raises(nx.NetworkXError, match=".*not applicable to empty graphs"):
+        nx.flow_hierarchy(G)
diff --git a/shared/package-files/b9/b97466061ad9f2539122d18ce17fe1076e95e47c5b316a8b9b1458e8a2e5a5bd/rref_backward_resp.h b/shared/package-files/b9/b97466061ad9f2539122d18ce17fe1076e95e47c5b316a8b9b1458e8a2e5a5bd/rref_backward_resp.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a5fa65a6e841f2592beab4abe3f4a99dcf9b842
--- /dev/null
+++ b/shared/package-files/b9/b97466061ad9f2539122d18ce17fe1076e95e47c5b316a8b9b1458e8a2e5a5bd/rref_backward_resp.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+#include 
+
+namespace torch::distributed::autograd {
+
+// Response for the RRefBackwardReq.
+class TORCH_API RRefBackwardResp : public rpc::RpcCommandBase {
+ public:
+  RRefBackwardResp() = default;
+  c10::intrusive_ptr toMessageImpl() && override;
+  static std::unique_ptr fromMessage(
+      const rpc::Message& message);
+};
+
+} // namespace torch::distributed::autograd
diff --git a/shared/package-files/b9/b97594814592a8a5843d5f986b1cb3ffb1a1a03743f3ca64b7cf9478d41571a5/instancenorm.h b/shared/package-files/b9/b97594814592a8a5843d5f986b1cb3ffb1a1a03743f3ca64b7cf9478d41571a5/instancenorm.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c90a060340b7d6ae8d46c5a717f9dbe04c9dfc7
--- /dev/null
+++ b/shared/package-files/b9/b97594814592a8a5843d5f986b1cb3ffb1a1a03743f3ca64b7cf9478d41571a5/instancenorm.h
@@ -0,0 +1,87 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::nn {
+
+/// Options for the `InstanceNorm` module.
+struct TORCH_API InstanceNormOptions {
+  /* implicit */ InstanceNormOptions(int64_t num_features);
+
+  /// The number of features of the input tensor.
+  TORCH_ARG(int64_t, num_features);
+
+  /// The epsilon value added for numerical stability.
+  TORCH_ARG(double, eps) = 1e-5;
+
+  /// A momentum multiplier for the mean and variance.
+  TORCH_ARG(double, momentum) = 0.1;
+
+  /// Whether to learn a scale and bias that are applied in an affine
+  /// transformation on the input.
+  TORCH_ARG(bool, affine) = false;
+
+  /// Whether to store and update batch statistics (mean and variance) in the
+  /// module.
+  TORCH_ARG(bool, track_running_stats) = false;
+};
+
+/// Options for the `InstanceNorm1d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm1d
+/// model(InstanceNorm1dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm1dOptions = InstanceNormOptions;
+
+/// Options for the `InstanceNorm2d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm2d
+/// model(InstanceNorm2dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm2dOptions = InstanceNormOptions;
+
+/// Options for the `InstanceNorm3d` module.
+///
+/// Example:
+/// ```
+/// InstanceNorm3d
+/// model(InstanceNorm3dOptions(4).eps(0.5).momentum(0.1).affine(false).track_running_stats(true));
+/// ```
+using InstanceNorm3dOptions = InstanceNormOptions;
+
+namespace functional {
+
+/// Options for `torch::nn::functional::instance_norm`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::instance_norm(input,
+/// F::InstanceNormFuncOptions().running_mean(mean).running_var(variance).weight(weight).bias(bias).momentum(0.1).eps(1e-5));
+/// ```
+struct TORCH_API InstanceNormFuncOptions {
+  TORCH_ARG(Tensor, running_mean) = Tensor();
+
+  TORCH_ARG(Tensor, running_var) = Tensor();
+
+  TORCH_ARG(Tensor, weight) = Tensor();
+
+  TORCH_ARG(Tensor, bias) = Tensor();
+
+  TORCH_ARG(bool, use_input_stats) = true;
+
+  TORCH_ARG(double, momentum) = 0.1;
+
+  TORCH_ARG(double, eps) = 1e-5;
+};
+
+} // namespace functional
+
+} // namespace torch::nn
diff --git a/shared/package-files/b9/b9774b3cc39186ef78d0897c9b02101c0d73e49dd395881e6d2be8f3897eb965/binary_cross_entropy_with_logits.h b/shared/package-files/b9/b9774b3cc39186ef78d0897c9b02101c0d73e49dd395881e6d2be8f3897eb965/binary_cross_entropy_with_logits.h
new file mode 100644
index 0000000000000000000000000000000000000000..9e53607003daedcffaeb5c4d30bd6f54523f06bf
--- /dev/null
+++ b/shared/package-files/b9/b9774b3cc39186ef78d0897c9b02101c0d73e49dd395881e6d2be8f3897eb965/binary_cross_entropy_with_logits.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor
+inline at::Tensor binary_cross_entropy_with_logits(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean) {
+    return at::_ops::binary_cross_entropy_with_logits::call(self, target, weight, pos_weight, reduction);
+}
+
+// aten::binary_cross_entropy_with_logits.out(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & binary_cross_entropy_with_logits_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean) {
+    return at::_ops::binary_cross_entropy_with_logits_out::call(self, target, weight, pos_weight, reduction, out);
+}
+// aten::binary_cross_entropy_with_logits.out(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & binary_cross_entropy_with_logits_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, const ::std::optional & pos_weight, int64_t reduction, at::Tensor & out) {
+    return at::_ops::binary_cross_entropy_with_logits_out::call(self, target, weight, pos_weight, reduction, out);
+}
+
+}
diff --git a/shared/package-files/b9/b97abb8757c29af714c89861dc3ba3c99bc91f6486960a3e25174b6df7f76ca2/test_algebraic_connectivity.py b/shared/package-files/b9/b97abb8757c29af714c89861dc3ba3c99bc91f6486960a3e25174b6df7f76ca2/test_algebraic_connectivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..31f911f7a2b039cd523e930d5d552ad07c77dd4d
--- /dev/null
+++ b/shared/package-files/b9/b97abb8757c29af714c89861dc3ba3c99bc91f6486960a3e25174b6df7f76ca2/test_algebraic_connectivity.py
@@ -0,0 +1,400 @@
+from math import sqrt
+
+import pytest
+
+import networkx as nx
+
+np = pytest.importorskip("numpy")
+methods = ("tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg")
+
+
+def test_algebraic_connectivity_tracemin_chol():
+    """Test that "tracemin_chol" raises an exception."""
+    pytest.importorskip("scipy")
+    G = nx.barbell_graph(5, 4)
+    with pytest.raises(nx.NetworkXError):
+        nx.algebraic_connectivity(G, method="tracemin_chol")
+
+
+def test_fiedler_vector_tracemin_chol():
+    """Test that "tracemin_chol" raises an exception."""
+    pytest.importorskip("scipy")
+    G = nx.barbell_graph(5, 4)
+    with pytest.raises(nx.NetworkXError):
+        nx.fiedler_vector(G, method="tracemin_chol")
+
+
+def test_spectral_ordering_tracemin_chol():
+    """Test that "tracemin_chol" raises an exception."""
+    pytest.importorskip("scipy")
+    G = nx.barbell_graph(5, 4)
+    with pytest.raises(nx.NetworkXError):
+        nx.spectral_ordering(G, method="tracemin_chol")
+
+
+def test_fiedler_vector_tracemin_unknown():
+    """Test that "tracemin_unknown" raises an exception."""
+    pytest.importorskip("scipy")
+    G = nx.barbell_graph(5, 4)
+    L = nx.laplacian_matrix(G)
+    X = np.asarray(np.random.normal(size=(1, L.shape[0]))).T
+    with pytest.raises(nx.NetworkXError, match="Unknown linear system solver"):
+        nx.linalg.algebraicconnectivity._tracemin_fiedler(
+            L, X, normalized=False, tol=1e-8, method="tracemin_unknown"
+        )
+
+
+def test_spectral_bisection():
+    pytest.importorskip("scipy")
+    G = nx.barbell_graph(3, 0)
+    C = nx.spectral_bisection(G)
+    assert C == ({0, 1, 2}, {3, 4, 5})
+
+    mapping = dict(enumerate("badfec"))
+    G = nx.relabel_nodes(G, mapping)
+    C = nx.spectral_bisection(G)
+    assert C == (
+        {mapping[0], mapping[1], mapping[2]},
+        {mapping[3], mapping[4], mapping[5]},
+    )
+
+
+def check_eigenvector(A, l, x):
+    nx = np.linalg.norm(x)
+    # Check zeroness.
+    assert nx != pytest.approx(0, abs=1e-07)
+    y = A @ x
+    ny = np.linalg.norm(y)
+    # Check collinearity.
+    assert x @ y == pytest.approx(nx * ny, abs=1e-7)
+    # Check eigenvalue.
+    assert ny == pytest.approx(l * nx, abs=1e-7)
+
+
+class TestAlgebraicConnectivity:
+    @pytest.mark.parametrize("method", methods)
+    def test_directed(self, method):
+        G = nx.DiGraph()
+        pytest.raises(
+            nx.NetworkXNotImplemented, nx.algebraic_connectivity, G, method=method
+        )
+        pytest.raises(nx.NetworkXNotImplemented, nx.fiedler_vector, G, method=method)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_null_and_singleton(self, method):
+        G = nx.Graph()
+        pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method)
+        pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
+        G.add_edge(0, 0)
+        pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method=method)
+        pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_disconnected(self, method):
+        G = nx.Graph()
+        G.add_nodes_from(range(2))
+        assert nx.algebraic_connectivity(G) == 0
+        pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
+        G.add_edge(0, 1, weight=0)
+        assert nx.algebraic_connectivity(G) == 0
+        pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method=method)
+
+    def test_unrecognized_method(self):
+        pytest.importorskip("scipy")
+        G = nx.path_graph(4)
+        pytest.raises(nx.NetworkXError, nx.algebraic_connectivity, G, method="unknown")
+        pytest.raises(nx.NetworkXError, nx.fiedler_vector, G, method="unknown")
+
+    @pytest.mark.parametrize("method", methods)
+    def test_two_nodes(self, method):
+        pytest.importorskip("scipy")
+        G = nx.Graph()
+        G.add_edge(0, 1, weight=1)
+        A = nx.laplacian_matrix(G)
+        assert nx.algebraic_connectivity(G, tol=1e-12, method=method) == pytest.approx(
+            2, abs=1e-7
+        )
+        x = nx.fiedler_vector(G, tol=1e-12, method=method)
+        check_eigenvector(A, 2, x)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_two_nodes_multigraph(self, method):
+        pytest.importorskip("scipy")
+        G = nx.MultiGraph()
+        G.add_edge(0, 0, spam=1e8)
+        G.add_edge(0, 1, spam=1)
+        G.add_edge(0, 1, spam=-2)
+        A = -3 * nx.laplacian_matrix(G, weight="spam")
+        assert nx.algebraic_connectivity(
+            G, weight="spam", tol=1e-12, method=method
+        ) == pytest.approx(6, abs=1e-7)
+        x = nx.fiedler_vector(G, weight="spam", tol=1e-12, method=method)
+        check_eigenvector(A, 6, x)
+
+    def test_abbreviation_of_method(self):
+        pytest.importorskip("scipy")
+        G = nx.path_graph(8)
+        A = nx.laplacian_matrix(G)
+        sigma = 2 - sqrt(2 + sqrt(2))
+        ac = nx.algebraic_connectivity(G, tol=1e-12, method="tracemin")
+        assert ac == pytest.approx(sigma, abs=1e-7)
+        x = nx.fiedler_vector(G, tol=1e-12, method="tracemin")
+        check_eigenvector(A, sigma, x)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_path(self, method):
+        pytest.importorskip("scipy")
+        G = nx.path_graph(8)
+        A = nx.laplacian_matrix(G)
+        sigma = 2 - sqrt(2 + sqrt(2))
+        ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
+        assert ac == pytest.approx(sigma, abs=1e-7)
+        x = nx.fiedler_vector(G, tol=1e-12, method=method)
+        check_eigenvector(A, sigma, x)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_problematic_graph_issue_2381(self, method):
+        pytest.importorskip("scipy")
+        G = nx.path_graph(4)
+        G.add_edges_from([(4, 2), (5, 1)])
+        A = nx.laplacian_matrix(G)
+        sigma = 0.438447187191
+        ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
+        assert ac == pytest.approx(sigma, abs=1e-7)
+        x = nx.fiedler_vector(G, tol=1e-12, method=method)
+        check_eigenvector(A, sigma, x)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_cycle(self, method):
+        pytest.importorskip("scipy")
+        G = nx.cycle_graph(8)
+        A = nx.laplacian_matrix(G)
+        sigma = 2 - sqrt(2)
+        ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
+        assert ac == pytest.approx(sigma, abs=1e-7)
+        x = nx.fiedler_vector(G, tol=1e-12, method=method)
+        check_eigenvector(A, sigma, x)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_seed_argument(self, method):
+        pytest.importorskip("scipy")
+        G = nx.cycle_graph(8)
+        A = nx.laplacian_matrix(G)
+        sigma = 2 - sqrt(2)
+        ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1)
+        assert ac == pytest.approx(sigma, abs=1e-7)
+        x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1)
+        check_eigenvector(A, sigma, x)
+
+    @pytest.mark.parametrize(
+        ("normalized", "sigma", "laplacian_fn"),
+        (
+            (False, 0.2434017461399311, nx.laplacian_matrix),
+            (True, 0.08113391537997749, nx.normalized_laplacian_matrix),
+        ),
+    )
+    @pytest.mark.parametrize("method", methods)
+    def test_buckminsterfullerene(self, normalized, sigma, laplacian_fn, method):
+        pytest.importorskip("scipy")
+        G = nx.Graph(
+            [
+                (1, 10),
+                (1, 41),
+                (1, 59),
+                (2, 12),
+                (2, 42),
+                (2, 60),
+                (3, 6),
+                (3, 43),
+                (3, 57),
+                (4, 8),
+                (4, 44),
+                (4, 58),
+                (5, 13),
+                (5, 56),
+                (5, 57),
+                (6, 10),
+                (6, 31),
+                (7, 14),
+                (7, 56),
+                (7, 58),
+                (8, 12),
+                (8, 32),
+                (9, 23),
+                (9, 53),
+                (9, 59),
+                (10, 15),
+                (11, 24),
+                (11, 53),
+                (11, 60),
+                (12, 16),
+                (13, 14),
+                (13, 25),
+                (14, 26),
+                (15, 27),
+                (15, 49),
+                (16, 28),
+                (16, 50),
+                (17, 18),
+                (17, 19),
+                (17, 54),
+                (18, 20),
+                (18, 55),
+                (19, 23),
+                (19, 41),
+                (20, 24),
+                (20, 42),
+                (21, 31),
+                (21, 33),
+                (21, 57),
+                (22, 32),
+                (22, 34),
+                (22, 58),
+                (23, 24),
+                (25, 35),
+                (25, 43),
+                (26, 36),
+                (26, 44),
+                (27, 51),
+                (27, 59),
+                (28, 52),
+                (28, 60),
+                (29, 33),
+                (29, 34),
+                (29, 56),
+                (30, 51),
+                (30, 52),
+                (30, 53),
+                (31, 47),
+                (32, 48),
+                (33, 45),
+                (34, 46),
+                (35, 36),
+                (35, 37),
+                (36, 38),
+                (37, 39),
+                (37, 49),
+                (38, 40),
+                (38, 50),
+                (39, 40),
+                (39, 51),
+                (40, 52),
+                (41, 47),
+                (42, 48),
+                (43, 49),
+                (44, 50),
+                (45, 46),
+                (45, 54),
+                (46, 55),
+                (47, 54),
+                (48, 55),
+            ]
+        )
+        A = laplacian_fn(G)
+        try:
+            assert nx.algebraic_connectivity(
+                G, normalized=normalized, tol=1e-12, method=method
+            ) == pytest.approx(sigma, abs=1e-7)
+            x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12, method=method)
+            check_eigenvector(A, sigma, x)
+        except nx.NetworkXError as err:
+            if err.args not in (
+                ("Cholesky solver unavailable.",),
+                ("LU solver unavailable.",),
+            ):
+                raise
+
+
+class TestSpectralOrdering:
+    _graphs = (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
+
+    @pytest.mark.parametrize("graph", _graphs)
+    def test_nullgraph(self, graph):
+        G = graph()
+        pytest.raises(nx.NetworkXError, nx.spectral_ordering, G)
+
+    @pytest.mark.parametrize("graph", _graphs)
+    def test_singleton(self, graph):
+        G = graph()
+        G.add_node("x")
+        assert nx.spectral_ordering(G) == ["x"]
+        G.add_edge("x", "x", weight=33)
+        G.add_edge("x", "x", weight=33)
+        assert nx.spectral_ordering(G) == ["x"]
+
+    def test_unrecognized_method(self):
+        G = nx.path_graph(4)
+        pytest.raises(nx.NetworkXError, nx.spectral_ordering, G, method="unknown")
+
+    @pytest.mark.parametrize("method", methods)
+    def test_three_nodes(self, method):
+        pytest.importorskip("scipy")
+        G = nx.Graph()
+        G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)], weight="spam")
+        order = nx.spectral_ordering(G, weight="spam", method=method)
+        assert set(order) == set(G)
+        assert {1, 3} in (set(order[:-1]), set(order[1:]))
+
+    @pytest.mark.parametrize("method", methods)
+    def test_three_nodes_multigraph(self, method):
+        pytest.importorskip("scipy")
+        G = nx.MultiDiGraph()
+        G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)])
+        order = nx.spectral_ordering(G, method=method)
+        assert set(order) == set(G)
+        assert {2, 3} in (set(order[:-1]), set(order[1:]))
+
+    @pytest.mark.parametrize("method", methods)
+    def test_path(self, method):
+        pytest.importorskip("scipy")
+        path = list(range(10))
+        np.random.shuffle(path)
+        G = nx.Graph()
+        nx.add_path(G, path)
+        order = nx.spectral_ordering(G, method=method)
+        assert order in [path, list(reversed(path))]
+
+    @pytest.mark.parametrize("method", methods)
+    def test_seed_argument(self, method):
+        pytest.importorskip("scipy")
+        path = list(range(10))
+        np.random.shuffle(path)
+        G = nx.Graph()
+        nx.add_path(G, path)
+        order = nx.spectral_ordering(G, method=method, seed=1)
+        assert order in [path, list(reversed(path))]
+
+    @pytest.mark.parametrize("method", methods)
+    def test_disconnected(self, method):
+        pytest.importorskip("scipy")
+        G = nx.Graph()
+        nx.add_path(G, range(0, 10, 2))
+        nx.add_path(G, range(1, 10, 2))
+        order = nx.spectral_ordering(G, method=method)
+        assert set(order) == set(G)
+        seqs = [
+            list(range(0, 10, 2)),
+            list(range(8, -1, -2)),
+            list(range(1, 10, 2)),
+            list(range(9, -1, -2)),
+        ]
+        assert order[:5] in seqs
+        assert order[5:] in seqs
+
+    @pytest.mark.parametrize(
+        ("normalized", "expected_order"),
+        (
+            (False, [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8], [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]]),
+            (True, [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8], [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]),
+        ),
+    )
+    @pytest.mark.parametrize("method", methods)
+    def test_cycle(self, normalized, expected_order, method):
+        pytest.importorskip("scipy")
+        path = list(range(10))
+        G = nx.Graph()
+        nx.add_path(G, path, weight=5)
+        G.add_edge(path[-1], path[0], weight=1)
+        A = nx.laplacian_matrix(G).todense()
+        order = nx.spectral_ordering(G, normalized=normalized, method=method)
+        assert order in expected_order
diff --git a/shared/package-files/b9/b97d16a815a4bee456c2de01870da2eb7781d6db7a5eb51fa27ce4a62a230be3/_saturate_weight_to_fp16_native.h b/shared/package-files/b9/b97d16a815a4bee456c2de01870da2eb7781d6db7a5eb51fa27ce4a62a230be3/_saturate_weight_to_fp16_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..bb73d221b9bc1e1df83d5185070f68c3612e552c
--- /dev/null
+++ b/shared/package-files/b9/b97d16a815a4bee456c2de01870da2eb7781d6db7a5eb51fa27ce4a62a230be3/_saturate_weight_to_fp16_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor _saturate_weight_to_fp16(const at::Tensor & weight);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b9/b98059f7dfce445821eeab50929c4f11fc682010cfcdbf6a45c22c6a4a28dfb3/test_graphml.cpython-311.pyc b/shared/package-files/b9/b98059f7dfce445821eeab50929c4f11fc682010cfcdbf6a45c22c6a4a28dfb3/test_graphml.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..099c57d30d83312039b8c47123f2238efbd1f515
Binary files /dev/null and b/shared/package-files/b9/b98059f7dfce445821eeab50929c4f11fc682010cfcdbf6a45c22c6a4a28dfb3/test_graphml.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b98519b91d776693f4b80757a89b490cffd837c59b8c616b6f5ee1508969a719/_meta_registrations.py b/shared/package-files/b9/b98519b91d776693f4b80757a89b490cffd837c59b8c616b6f5ee1508969a719/_meta_registrations.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b96ad1374ef313d4fb9d85a5af0b66bea01db37
--- /dev/null
+++ b/shared/package-files/b9/b98519b91d776693f4b80757a89b490cffd837c59b8c616b6f5ee1508969a719/_meta_registrations.py
@@ -0,0 +1,7356 @@
+# mypy: allow-untyped-defs
+import math
+from collections.abc import Sequence
+from enum import Enum
+from functools import wraps
+from typing import Callable, Optional, TypeVar, Union
+from typing_extensions import ParamSpec
+
+import torch
+import torch._prims_common as utils
+from torch import SymBool, SymFloat, Tensor
+from torch._decomp import (
+    _add_op_to_registry,
+    _convert_out_params,
+    global_decomposition_table,
+    meta_table,
+)
+from torch._ops import OpOverload
+from torch._prims import _prim_elementwise_meta, ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND
+from torch._prims_common import (
+    BoolLike,
+    corresponding_complex_dtype,
+    corresponding_real_dtype,
+    elementwise_dtypes,
+    ELEMENTWISE_TYPE_PROMOTION_KIND,
+    FloatLike,
+    IntLike,
+    make_contiguous_strides_for,
+    Number,
+    TensorLike,
+)
+from torch._prims_common.wrappers import (
+    _maybe_convert_to_dtype,
+    _maybe_resize_out,
+    _resize_output_check,
+    _safe_copy_out,
+    out_wrapper,
+)
+from torch._refs import _broadcast_shapes, _maybe_broadcast
+from torch.fx.experimental import _config as exp_config
+from torch.utils import _pytree as pytree
+
+
+_T = TypeVar("_T")
+_P = ParamSpec("_P")
+
+aten = torch.ops.aten
+
+_meta_lib_dont_use_me_use_register_meta = torch.library.Library("aten", "IMPL", "Meta")
+MODE_SUM, MODE_MEAN, MODE_MAX = range(3)
+
+
+def register_meta(op) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
+    def wrapper(fn):
+        fn = _convert_out_params(fn)
+
+        def register(op):
+            _add_op_to_registry(meta_table, op, fn)
+
+        pytree.tree_map_(register, op)
+        return fn
+
+    return wrapper
+
+
+def elementwise_meta(
+    *args,
+    type_promotion: ELEMENTWISE_TYPE_PROMOTION_KIND,
+):
+    # Perform type promotion, as this is expected from prim_metafunction
+    _, result_dtype = utils.elementwise_dtypes(
+        *args,
+        type_promotion_kind=type_promotion,
+    )
+    args = [_maybe_convert_to_dtype(x, result_dtype) for x in args]
+
+    # Broadcast
+    args = _maybe_broadcast(*args)
+
+    # Perform prim checks
+    return _prim_elementwise_meta(
+        *args, type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+def toRealValueType(dtype):
+    from_complex = {
+        torch.complex32: torch.half,
+        torch.cfloat: torch.float,
+        torch.cdouble: torch.double,
+    }
+    return from_complex.get(dtype, dtype)
+
+
+def check_inplace_broadcast(self_shape, *args_shape):
+    broadcasted_shape = tuple(_broadcast_shapes(self_shape, *args_shape))
+    torch._check(
+        broadcasted_shape == self_shape,
+        lambda: f"output with shape {self_shape} doesn't match the broadcast shape {broadcasted_shape}",
+    )
+
+
+@register_meta([aten.linspace, aten.logspace])
+@out_wrapper()
+def meta_linspace_logspace(
+    start,
+    end,
+    steps,
+    base=None,
+    dtype=None,
+    device=None,
+    layout=torch.strided,
+    pin_memory=False,
+    requires_grad=False,
+):
+    if isinstance(start, torch.Tensor):
+        torch._check(
+            start.dim() == 0,
+            lambda: "linspace only supports 0-dimensional start and end tensors",
+        )
+    if isinstance(end, torch.Tensor):
+        torch._check(
+            end.dim() == 0,
+            lambda: "linspace only supports 0-dimensional start and end tensors",
+        )
+
+    if any(isinstance(arg, complex) for arg in (start, end, steps)):
+        default_complex_dtype = utils.corresponding_complex_dtype(
+            torch.get_default_dtype()
+        )
+        if dtype is None:
+            dtype = default_complex_dtype
+        else:
+            torch._check(
+                utils.is_complex_dtype(dtype),
+                lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}",
+            )
+    else:
+        dtype = dtype or torch.get_default_dtype()
+    assert isinstance(dtype, torch.dtype)
+
+    # steps does not participate in the computation of the dtype
+    torch._check_type(
+        isinstance(steps, IntLike),
+        lambda: f"received an invalid combination of arguments - got \
+({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})",
+    )
+    assert isinstance(steps, IntLike)  # for mypy
+    torch._check(steps >= 0, lambda: "number of steps must be non-negative")
+
+    return torch.empty(
+        (steps,),  # type: ignore[arg-type]
+        dtype=dtype,
+        layout=layout,
+        device="meta",
+        pin_memory=pin_memory,
+        requires_grad=requires_grad,
+    )
+
+
+@register_meta([aten.take.default, aten.take.out])
+@out_wrapper()
+def meta_take(self, index):
+    # Type and device checks
+    torch._check(
+        index.dtype == torch.long,
+        lambda: f"take(): Expected a long tensor for index, but got {index.dtype}",
+    )
+    # Index checks
+    torch._check_index(
+        not (self.numel() == 0 and index.numel() != 0),
+        lambda: "take(): tried to take from an empty tensor",
+    )
+    return self.new_empty(index.shape)
+
+
+@register_meta([aten.linalg_cross.default, aten.linalg_cross.out])
+@out_wrapper()
+def linalg_cross(self, other, *, dim=-1):
+    x_d = self.ndim
+    y_d = other.ndim
+    torch._check(
+        x_d == y_d,
+        lambda: "linalg.cross: inputs must have the same number of dimensions.",
+    )
+    torch._check(
+        self.size(dim) == 3 and other.size(dim) == 3,
+        lambda: (
+            f"linalg.cross: inputs dimension {dim} must have length 3. "
+            f"Got {self.size(dim)} and {other.size(dim)}"
+        ),
+    )
+    out_shape = _broadcast_shapes(self.shape, other.shape)
+    return self.new_empty(out_shape)
+
+
+@register_meta(aten.linalg_matrix_exp)
+@out_wrapper()
+def linalg_matrix_exp(self):
+    squareCheckInputs(self, "linalg.matrix_exp")
+    checkFloatingOrComplex(self, "linalg.matrix_exp")
+    return torch.empty_like(self, memory_format=torch.contiguous_format)
+
+
+@register_meta(
+    [aten.cummax.default, aten.cummax.out, aten.cummin.default, aten.cummin.out]
+)
+@out_wrapper("values", "indices")
+def cummaxmin(self, dim):
+    values = torch.empty(self.shape, device=self.device, dtype=self.dtype)
+    indices = torch.empty(self.shape, device=self.device, dtype=torch.int64)
+    if self.numel() != 0 and self.ndim != 0:
+        # Checks that dim is within bounds
+        maybe_wrap_dim(dim, self.ndim)
+    return values, indices
+
+
+@register_meta([aten.logcumsumexp.default, aten.logcumsumexp.out])
+@out_wrapper()
+def logcumsumexp(self, dim):
+    # Checks that dim is within bounds
+    maybe_wrap_dim(dim, self.ndim)
+    return torch.empty_like(self, memory_format=torch.contiguous_format)
+
+
+# Stride-related code from _exec_fft in aten/src/ATen/native/mkl/SpectralOps.cpp
+# and aten/src/ATen/cuda/SpectralOps.cpp
+#
+# Although the actual FFT launch is different, all the permuting code appears
+# to be the same
+def _exec_fft(out, self, out_sizes, dim, *, forward):
+    ndim = self.ndim
+    signal_ndim = len(dim)
+    batch_dims = ndim - signal_ndim
+
+    # Permute dimensions so batch dimensions come first, and in stride order
+    dim_permute = list(range(ndim))
+
+    is_transformed_dim = [False for _ in range(ndim)]
+    for d in dim:
+        is_transformed_dim[d] = True
+
+    # std::partition
+    left, right = [], []
+    for d in dim_permute:
+        if not is_transformed_dim[d]:
+            left.append(d)
+        else:
+            right.append(d)
+    dim_permute = left + right
+    batch_end = len(left)
+
+    self_strides = self.stride()
+    tmp = dim_permute[:batch_end]
+    tmp.sort(key=lambda x: self_strides[x], reverse=True)
+    dim_permute = tmp + dim_permute[batch_end:]
+    input = self.permute(dim_permute)
+
+    # Collapse batch dimensions into a single dimension
+    batched_sizes = [-1] + list(input.shape[batch_dims:])
+    input = input.reshape(batched_sizes)
+
+    batch_size = input.size(0)
+    batched_sizes[0] = batch_size
+    batched_out_sizes = list(batched_sizes)
+    for i in range(len(dim)):
+        batched_out_sizes[i + 1] = out_sizes[dim[i]]
+    out.resize_(batched_out_sizes, memory_format=torch.contiguous_format)
+
+    # Inplace reshaping to original batch shape and inverting the dimension permutation
+    out_strides = [0 for _ in range(ndim)]
+    batch_numel = 1
+    i = batch_dims - 1
+    while i >= 0:
+        out_strides[dim_permute[i]] = batch_numel * out.stride(0)
+        batch_numel *= out_sizes[dim_permute[i]]
+        i -= 1
+    for i in range(batch_dims, ndim):
+        out_strides[dim_permute[i]] = out.stride(1 + (i - batch_dims))
+    out.as_strided_(out_sizes, out_strides, out.storage_offset())
+
+    return out
+
+
+def _sort_dims(self: Tensor, dim: list[int], exclude_last: bool = False):
+    sorted_dims = list(dim)
+    self_strides = self.stride()
+    sorted_dims[: len(sorted_dims) - int(exclude_last)].sort(
+        key=lambda i: self_strides[i]
+    )
+    return sorted_dims
+
+
+# See _fft_c2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp
+# and _fft_c2c_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp
+@register_meta([aten._fft_c2c.default, aten._fft_c2c.out])
+@out_wrapper()
+def meta_fft_c2c(self, dim, normalization, forward):
+    torch._check(self.dtype.is_complex)
+    if not dim:
+        return self.clone()
+
+    sorted_dims = _sort_dims(self, dim)
+    out = self.new_empty(self.size())
+    return _exec_fft(out, self, self.size(), sorted_dims, forward=forward)
+
+
+cufft_max_ndim = 3
+
+
+def use_optimized_cufft_path(dim: list[int]):
+    if len(dim) > cufft_max_ndim or (len(dim) >= 2 and dim[0] == 0 and dim[1] == 1):
+        return False
+    else:
+        return True
+
+
+@register_meta([aten._fft_r2c.default, aten._fft_r2c.out])
+@out_wrapper()
+def meta_fft_r2c(self, dim, normalization, onesided):
+    torch._check(self.dtype.is_floating_point)
+    input_sizes = list(self.size())
+    out_sizes = list(input_sizes)
+    last_dim = dim[-1]
+    last_dim_halfsize = input_sizes[last_dim] // 2 + 1
+    onesided_sizes = list(input_sizes)
+    onesided_sizes[last_dim] = last_dim_halfsize
+
+    if onesided:
+        out_sizes[last_dim] = last_dim_halfsize
+
+    if device_hint(self) == "cuda":
+        # _fft_r2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp
+        output = self.new_empty(
+            out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
+        )
+
+        working_tensor = self
+        if use_optimized_cufft_path(dim):
+            _exec_fft(output, working_tensor, out_sizes, dim, forward=True)
+        else:
+            # First do the R2C transform on the last dimension
+            target_sizes = out_sizes if len(dim) == 1 else onesided_sizes
+            _exec_fft(output, working_tensor, target_sizes, [last_dim], forward=True)
+            if len(dim) > 1:
+                working_tensor = self.new_empty(
+                    out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
+                )
+
+            # Then any remaining C2C transforms
+            sorted_dims = dim[:-1]
+            while sorted_dims:
+                output, working_tensor = working_tensor, output
+                strides = working_tensor.stride()
+                sorted_dims.sort(
+                    key=lambda i: strides[i], reverse=True
+                )  # NB reverse!  Not sure if this is og bug
+                max_dims = min(cufft_max_ndim, len(sorted_dims))
+                last_dims = sorted_dims[len(sorted_dims) - max_dims :]
+                _exec_fft(
+                    output, working_tensor, onesided_sizes, last_dims, forward=True
+                )
+                sorted_dims = sorted_dims[: len(sorted_dims) - max_dims]
+
+        if not onesided:
+            if output.size(last_dim) != out_sizes[last_dim]:
+                working_tensor.resize_(out_sizes, memory_format=torch.contiguous_format)
+                output = working_tensor
+
+        return output
+
+    elif device_hint(self) == "xpu":
+        sorted_dims = _sort_dims(self, dim, exclude_last=True)
+        out = self.new_empty(
+            out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
+        )
+        return _exec_fft(out, self, out_sizes, sorted_dims, forward=True)
+    else:
+        return self.new_empty(
+            out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
+        )
+
+
+@register_meta(aten.randperm.generator_out)
+def meta_randperm(n, *, generator=None, out):
+    return _maybe_resize_out(out, torch.Size([n]))
+
+
+@register_meta(aten.randperm.default)
+def meta_randperm_default(
+    n,
+    *,
+    dtype=torch.long,
+    layout=None,
+    device=None,
+    pin_memory=None,
+):
+    return torch.empty(
+        n, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
+    )
+
+
+@register_meta([aten.randint.default, aten.randint.out])
+@out_wrapper()
+def meta_randint(
+    high,
+    size,
+    *,
+    dtype=torch.long,
+    layout=None,
+    device=None,
+    pin_memory=None,
+):
+    low = 0
+    torch._check(
+        high > low,
+        lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}",
+    )
+    return torch.empty(
+        size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
+    )
+
+
+@register_meta([aten.randint.low, aten.randint.low_out])
+@out_wrapper()
+def meta_randint_low(
+    low,
+    high,
+    size,
+    *,
+    dtype=torch.long,
+    layout=None,
+    device=None,
+    pin_memory=None,
+):
+    torch._check(
+        high > low,
+        lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}",
+    )
+    return torch.empty(
+        size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
+    )
+
+
+@register_meta([aten.rand.default, aten.rand.out])
+@out_wrapper()
+def meta_rand_default(size, *, dtype=None, layout=None, device=None, pin_memory=None):
+    return torch.empty(
+        size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
+    )
+
+
+@register_meta([aten._fft_c2r.default, aten._fft_c2r.out])
+@out_wrapper()
+def meta_fft_c2r(self: Tensor, dim: list[int], normalization: int, lastdim: int):
+    # _fft_c2r_mkl
+    torch._check(self.dtype.is_complex)
+
+    if device_hint(self) == "cuda":
+        out_sizes = list(self.size())
+        out_sizes[dim[-1]] = lastdim
+
+        output = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype))
+
+        if use_optimized_cufft_path(dim):
+            return _exec_fft(
+                output,
+                self.clone(memory_format=torch.contiguous_format),
+                out_sizes,
+                dim,
+                forward=False,
+            )
+        else:
+            # First complete any C2C transforms
+            if len(dim) > 1:
+                temp = meta_fft_c2c(self, dim[:-1], 0, lastdim)  # fft_norm_mode::none
+            else:
+                temp = self.clone(memory_format=torch.contiguous_format)
+            return _exec_fft(output, temp, out_sizes, [dim[-1]], forward=False)
+
+    else:
+        input = self
+        if len(dim) > 1:
+            c2c_dims = dim[:-1]
+            input = meta_fft_c2c(self, c2c_dims, normalization, forward=False)
+            dim = dim[-1:]
+
+        out_sizes = list(input.size())
+        out_sizes[dim[-1]] = lastdim
+        out = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype))
+        return _exec_fft(out, input, out_sizes, dim, forward=False)
+
+
+@register_meta(aten.copy_.default)
+def meta_copy_(self, src, non_blocking=False):
+    # This code simulates the original decomp from inductor,
+    # which runs most of the meta checks that we care about.
+    # In theory, we should make this more robust by carefully
+    # auditing our C++ copy_() kernel and copying the checks here.
+    from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
+
+    # TODO: Ideally, we'd insert a deferred runtime assert here, but if we are
+    # calling an actual copy_, you'll get that automatically
+    # https://github.com/pytorch/pytorch/issues/122477
+    if (
+        not free_unbacked_symbols(self) and torch._debug_has_internal_overlap(self) == 1
+    ):  # 1 == MemOverlap::Yes
+        raise RuntimeError(
+            "more than one element of the written-to tensor refers to a single memory location"
+        )
+
+    if isinstance(src, Tensor):
+        intermediate = src.to(self, non_blocking)
+        if self.size() != intermediate.size():
+            aten.expand_copy.default(intermediate, self.size())
+    return self
+
+
+def inferUnsqueezeGeometry(tensor, dim):
+    result_sizes = list(tensor.size())
+    result_strides = list(tensor.stride())
+    new_stride = 1 if dim >= tensor.dim() else result_sizes[dim] * result_strides[dim]
+    result_sizes.insert(dim, 1)
+    result_strides.insert(dim, new_stride)
+    return result_sizes, result_strides
+
+
+@register_meta(aten.unsqueeze_.default)
+def meta_unsqueeze_(self, dim):
+    dim = maybe_wrap_dim(dim, self.dim() + 1)
+    g_sizes, g_strides = inferUnsqueezeGeometry(self, dim)
+    self.as_strided_(g_sizes, g_strides)
+    return self
+
+
+@register_meta(aten._sparse_semi_structured_linear)
+def meta_sparse_structured_linear(
+    input: Tensor,
+    weight: Tensor,
+    _meta: Tensor,
+    bias: Optional[Tensor] = None,
+    _activation_opt: Optional[str] = None,
+    out_dtype: Optional[torch.dtype] = None,
+):
+    output_sizes = list(input.shape)
+    if bias is not None:
+        assert weight.size(0) == bias.size(0), "output size mismatch"
+    assert weight.size(1) == input.size(-1) / 2
+    output_sizes[-1] = weight.size(0)
+
+    # see: https://github.com/pytorch/pytorch/pull/114477#issuecomment-1830121375
+    # We assume that we have already squashed the inputs into a 2-D tensor
+    # Then, as the output is transposed, we need to propagate the transposed
+    # stride information to the output tensor
+    assert len(input.shape) == 2, "we can only handle the squashed input case"
+    transposed_strides = (1, input.size(0))
+
+    if out_dtype is not None:
+        assert input.dtype == torch.int8 and out_dtype == torch.int32, (
+            "out_dtype is only supported for i8i8->i32 linear operator"
+        )
+    output = input.new_empty(
+        output_sizes,
+        dtype=input.dtype if out_dtype is None else out_dtype,
+    ).as_strided(output_sizes, transposed_strides)
+
+    return output
+
+
+@register_meta(aten._sparse_semi_structured_mm)
+def meta_sparse_structured_mm(
+    mat1: Tensor,
+    mat1_meta: Tensor,
+    mat2: Tensor,
+    out_dtype: Optional[torch.dtype] = None,
+):
+    assert len(mat1.shape) == 2
+    assert len(mat1_meta.shape) == 2
+    assert len(mat2.shape) == 2
+    assert mat1.size(1) == mat2.size(0) / 2
+    output_sizes = [mat1.size(0), mat2.size(1)]
+
+    if out_dtype is not None:
+        assert mat2.dtype == torch.int8 and out_dtype == torch.int32, (
+            "out_dtype is only supported for i8i8->i32 linear operator"
+        )
+    output = mat2.new_empty(
+        output_sizes,
+        dtype=mat2.dtype if out_dtype is None else out_dtype,
+    )
+
+    return output
+
+
+@register_meta(aten._sparse_semi_structured_addmm)
+def meta_sparse_structured_addmm(
+    input: Tensor,
+    mat1: Tensor,
+    mat1_meta: Tensor,
+    mat2: Tensor,
+    *,
+    alpha=1,
+    beta=1,
+    out_dtype: Optional[torch.dtype] = None,
+):
+    assert len(input.shape) == 1, (
+        "only input broadcasted to columns of mat1 * mat2 product is supported"
+    )
+    assert len(mat1.shape) == 2
+    assert len(mat1_meta.shape) == 2
+    assert len(mat2.shape) == 2
+    assert input.size(0) == mat1.size(0), (
+        "only input broadcasted to columns of mat1 * mat2 product is supported"
+    )
+    assert mat1.size(1) == mat2.size(0) / 2
+    output_sizes = [mat1.size(0), mat2.size(1)]
+
+    if out_dtype is not None:
+        assert mat2.dtype == torch.int8 and out_dtype == torch.int32, (
+            "out_dtype is only supported for i8i8->i32 linear operator"
+        )
+    output = mat2.new_empty(
+        output_sizes,
+        dtype=mat2.dtype if out_dtype is None else out_dtype,
+    )
+
+    return output
+
+
+@register_meta(aten._cslt_sparse_mm)
+def meta__cslt_sparse_mm(
+    compressed_A: torch.Tensor,
+    dense_B: torch.Tensor,
+    bias: Optional[Tensor] = None,
+    alpha: Optional[Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    transpose_result: bool = False,
+    alg_id: int = 0,
+    split_k: int = 1,
+    split_k_one_kernel: bool = False,
+):
+    assert dense_B.dtype in {
+        torch.float32,
+        torch.float16,
+        torch.bfloat16,
+        torch.int8,
+        torch.float8_e4m3fn,
+    }, "_cslt_sparse_mm only supports fp16, bf16, int8, and fp8e4m3"
+    assert compressed_A.dtype == dense_B.dtype, "inputs must have the same dtype"
+    assert len(dense_B.shape) == 2, "_cslt_sparse_mm only supports 2d inputs"
+
+    is_8bit_input_type = compressed_A.dtype in [torch.int8, torch.float8_e4m3fn]
+    compression_factor = 10 if is_8bit_input_type else 9
+
+    if is_8bit_input_type:
+        assert not dense_B.is_contiguous(), (
+            "dense input must be transposed for 8bit dtypes"
+        )
+
+    k = dense_B.size(0)
+    n = dense_B.size(1)
+    m = (compressed_A.numel() * 16) // (compression_factor * k)
+    if bias is not None:
+        assert m == bias.size(0)
+
+    if out_dtype is not None:
+        assert is_8bit_input_type and out_dtype in {
+            torch.float16,
+            torch.bfloat16,
+            torch.int32,
+            torch.float8_e4m3fn,
+        }, (
+            "out_dtype is not supported for {compressed_A.dtype} x {dense_B.dtype} -> {out_dtype} matmul!"
+        )
+    output_shape = (n, m) if transpose_result else (m, n)
+    return dense_B.new_empty(output_shape, dtype=out_dtype)
+
+
+@register_meta(aten.index_reduce.default)
+def meta_index_reduce(
+    self: Tensor,
+    dim: int,
+    index: Tensor,
+    source: torch.Tensor,
+    reduce: str,
+    *,
+    include_self: bool = True,
+) -> Tensor:
+    return torch.empty_like(self, memory_format=torch.contiguous_format)
+
+
+@register_meta(aten.index_reduce_.default)
+def meta_index_reduce_(
+    self: Tensor,
+    dim: int,
+    index: Tensor,
+    source: torch.Tensor,
+    reduce: str,
+    *,
+    include_self: bool = True,
+) -> Tensor:
+    return self
+
+
+# Implementations below are taken from https://github.com/albanD/subclass_zoo/blob/main/python_meta_tensor.py
+@out_wrapper()
+@register_meta(aten.index_select.default)
+def meta_index_select(self, dim, index):
+    result_size = list(self.size())
+    if self.dim() > 0:
+        result_size[dim] = index.numel()
+    return self.new_empty(result_size)
+
+
+@register_meta(aten.segment_reduce.default)
+def meta_segment_reduce(
+    data: Tensor,
+    reduce: str,
+    *,
+    lengths: Optional[Tensor] = None,
+    indices: Optional[Tensor] = None,
+    offsets: Optional[Tensor] = None,
+    axis: int = 0,
+    unsafe: bool = False,
+    initial=None,
+) -> Tensor:
+    if indices is not None:
+        raise NotImplementedError(
+            "segment_reduce(): indices based reduction is not supported yet."
+        )
+
+    def segment_reduce_lengths_tensor(lengths_shape):
+        return torch.empty(
+            lengths_shape + data.shape[axis + 1 :],
+            dtype=data.dtype,
+            device="meta",
+            memory_format=torch.contiguous_format,
+        )
+
+    if lengths is not None:
+        return segment_reduce_lengths_tensor(lengths.shape)
+    # FIXME should probably check that lengths and offset aren't both set, but
+    # the ATen implementation neglects this too
+    if offsets is not None:
+        # lengths == torch.diff(offsets)
+        lengths_shape = offsets.shape[:-1] + (offsets.shape[-1] - 1,)
+        return segment_reduce_lengths_tensor(lengths_shape)
+    raise RuntimeError("segment_reduce(): Either lengths or offsets must be defined.")
+
+
+@register_meta([aten.max.default, aten.max.unary_out])
+@out_wrapper()
+def meta_max(self):
+    return self.new_empty(())
+
+
+@register_meta(aten.max.dim)
+def meta_max_dim(self, dim, keepdim=False):
+    dim = utils.reduction_dims(self.shape, (dim,))
+    output_shape = _compute_reduction_shape(self, dim, keepdim)
+    return (
+        self.new_empty(output_shape),
+        self.new_empty(output_shape, dtype=torch.long),
+    )
+
+
+@register_meta([aten.min.default, aten.min.unary_out])
+@out_wrapper()
+def meta_min(self):
+    return self.new_empty(())
+
+
+@register_meta(aten.min.dim)
+def meta_min_dim(self, dim, keepdim=False):
+    dim = utils.reduction_dims(self.shape, (dim,))
+    output_shape = _compute_reduction_shape(self, dim, keepdim)
+    return (
+        self.new_empty(output_shape),
+        self.new_empty(output_shape, dtype=torch.long),
+    )
+
+
+@register_meta(aten.angle.default)
+def meta_angle(self):
+    if self.is_complex():
+        result_dtype = corresponding_real_dtype(self.dtype)
+    else:
+        _, result_dtype = elementwise_dtypes(
+            self,
+            type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
+        )
+    return torch.empty_like(self, dtype=result_dtype)
+
+
+@register_meta(aten.angle.out)
+def meta_angle_out(self, out):
+    torch._resize_output_(out, self.size(), self.device)
+    return out.copy_(torch.angle(self))
+
+
+@register_meta(aten._assert_async.default)
+def assert_async(val):
+    return
+
+
+@register_meta(aten._assert_async.msg)
+def assert_async_meta(val, assert_msg):
+    return
+
+
+@register_meta(aten._print.default)
+def print_meta(s):
+    return
+
+
+@register_meta(aten._make_dep_token.default)
+def make_dep_token(
+    *,
+    dtype=None,
+    layout=None,
+    device=None,
+    pin_memory=None,
+    memory_format=None,
+):
+    return torch.empty(0, device="meta")
+
+
+@register_meta(aten.sym_constrain_range.default)
+def sym_constrain_range(size, min=None, max=None):
+    # Avoid importing sympy at a module level
+    from torch.fx.experimental.symbolic_shapes import constrain_range
+
+    if isinstance(size, (SymFloat, SymBool)):
+        raise ValueError("Constraining SymFloat or Symbool is nyi")
+    constrain_range(size, min=min, max=max)
+
+
+@register_meta(aten._functional_sym_constrain_range.default)
+def functional_sym_constrain_range(size, min=None, max=None, dep_token=None):
+    aten.sym_constrain_range(size, min=min, max=max)
+    return dep_token
+
+
+@register_meta(aten.sym_constrain_range_for_size.default)
+def sym_constrain_range_for_size(size, min=None, max=None):
+    # Avoid importing sympy at a module level
+    from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size
+
+    if min is None and max is None:
+        torch._check_is_size(size)
+        return
+
+    if isinstance(size, (SymFloat, SymBool)):
+        raise ValueError("Constraining SymFloat or Symbool is nyi")
+    if type(size) is int:
+        if min is not None:
+            torch._check(size >= min)
+        if max is not None:
+            torch._check(size <= max)
+        return
+    _constrain_range_for_size(size, min=min, max=max)
+
+
+@register_meta(aten._functional_sym_constrain_range_for_size.default)
+def functional_sym_constrain_range_for_size(size, min, max, dep_token):
+    aten.sym_constrain_range_for_size(size, min=min, max=max)
+    return dep_token
+
+
+@register_meta(aten._functional_assert_async.msg)
+def functional_assert_async_meta(val, assert_msg, dep_token):
+    return dep_token
+
+
+# From aten/src/ATen/native/LinearAlgebraUtils.h
+def squareCheckInputs(self: Tensor, f_name: str):
+    assert self.dim() >= 2, (
+        f"{f_name}: The input tensor must have at least 2 dimensions."
+    )
+    assert self.size(-1) == self.size(-2), (
+        f"{f_name}: A must be batches of square matrices, but they are {self.size(-2)} by {self.size(-1)} matrices"
+    )
+
+
+# Validates input shapes and devices
+# for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve)
+# From aten/src/ATen/native/LinearAlgebraUtils.h
+def linearSolveCheckInputs(self: Tensor, A: Tensor, name: str):
+    torch._check(
+        self.device == A.device,
+        lambda: (
+            f"Expected b and A to be on the same device, but found b on "
+            f"{self.device} and A on {A.device} instead."
+        ),
+    )
+
+    torch._check(
+        self.dtype == A.dtype,
+        lambda: (
+            f"Expected b and A to have the same dtype, but found b of type "
+            f"{self.dtype} and A of type {A.dtype} instead."
+        ),
+    )
+
+    torch._check(
+        A.size(-1) == A.size(-2),
+        lambda: (
+            f"A must be batches of square matrices, "
+            f"but they are {A.size(-2)} by {A.size(-1)} matrices"
+        ),
+    )
+
+    torch._check(
+        A.size(-1) == self.size(-2),
+        lambda: (
+            f"Incompatible matrix sizes for {name}: each A "
+            f"matrix is {A.size(-1)} by {A.size(-1)}"
+            f" but each b matrix is {self.size(-2)} by {self.size(-1)}"
+        ),
+    )
+
+
+# From aten/src/ATen/native/LinearAlgebraUtils.h
+def checkFloatingOrComplex(
+    t: Tensor,
+    f_name: str,
+    allow_low_precision_dtypes: bool = True,
+):
+    dtype = t.dtype
+    torch._check(
+        t.is_floating_point() or t.is_complex(),
+        lambda: f"{f_name}: Expected a floating point or complex tensor as input. Got {dtype}",
+    )
+    if not allow_low_precision_dtypes:
+        torch._check(
+            dtype in (torch.float, torch.double, torch.cfloat, torch.cdouble),
+            lambda: f"{f_name}: Low precision dtypes not supported. Got {dtype}",
+        )
+
+
+# From aten/src/ATen/native/LinearAlgebraUtils.h
+def checkIsMatrix(A: Tensor, f_name: str, arg_name: str = "A"):
+    torch._check(
+        A.dim() >= 2,
+        lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.",
+    )
+
+
+def checkInputsSolver(A: Tensor, B: Tensor, left: bool, f_name: str):
+    squareCheckInputs(A, f_name)
+    checkIsMatrix(B, f_name)
+    torch._check(
+        A.size(-2) == B.size(-2) if left else A.size(-1) == B.size(-1),
+        lambda: (
+            f"{f_name}: Incompatible shapes of A and B for the equation "
+            f"{'AX = B' if left else 'XA = B'}"
+            f" ({A.size(-2)}x{A.size(-1)} and {B.size(-2)}x{B.size(-1)})"
+        ),
+    )
+
+
+def checkSameDevice(
+    fn_name: str,
+    result: Tensor,
+    input: Tensor,
+    result_name: str = "result",
+):
+    torch._check(
+        result.device == input.device,
+        lambda: (
+            f"{fn_name}: Expected {result_name} and input tensors to be on the same device, but got "
+            f"{result_name} on {result.device} and input on {input.device}"
+        ),
+    )
+
+
+def checkUplo(UPLO: str):
+    UPLO_uppercase = UPLO.upper()
+    torch._check(
+        len(UPLO) == 1 and (UPLO_uppercase == "U" or UPLO_uppercase == "L"),
+        lambda: f"Expected UPLO argument to be 'L' or 'U', but got {UPLO}",
+    )
+
+
+@register_meta([aten._linalg_eigh.default, aten._linalg_eigh.eigenvalues])
+@out_wrapper("eigenvalues", "eigenvectors")
+def meta__linalg_eigh(A: Tensor, UPLO: str = "L", compute_v: bool = True):
+    squareCheckInputs(A, "linalg.eigh")
+    checkUplo(UPLO)
+
+    shape = list(A.shape)
+    if compute_v:
+        vecs = A.new_empty(shape)
+        vecs.as_strided_(shape, make_contiguous_strides_for(shape, row_major=False))
+    else:
+        vecs = A.new_empty([0])
+
+    shape.pop()
+    vals = A.new_empty(shape, dtype=toRealValueType(A.dtype))
+
+    return vals, vecs
+
+
+@register_meta([aten._linalg_eigvals.default, aten.linalg_eigvals.out])
+@out_wrapper()
+def meta__linalg_eigvals(input: Tensor) -> Tensor:
+    squareCheckInputs(input, "linalg.eigvals")
+    complex_dtype = (
+        input.dtype
+        if utils.is_complex_dtype(input.dtype)
+        else utils.corresponding_complex_dtype(input.dtype)
+    )
+    return input.new_empty(input.shape[:-1], dtype=complex_dtype)
+
+
+@register_meta([aten.linalg_eig])
+@out_wrapper("eigenvalues", "eigenvectors")
+def meta_linalg_eig(input: Tensor):
+    squareCheckInputs(input, "linalg.eig")
+    complex_dtype = (
+        input.dtype
+        if utils.is_complex_dtype(input.dtype)
+        else utils.corresponding_complex_dtype(input.dtype)
+    )
+    values = input.new_empty(input.shape[:-1], dtype=complex_dtype)
+    vectors = input.new_empty(input.shape, dtype=complex_dtype)
+    return values, vectors
+
+
+def cloneBatchedColumnMajor(src: Tensor) -> Tensor:
+    return src.mT.clone(memory_format=torch.contiguous_format).transpose(-2, -1)
+
+
+@register_meta(aten._cholesky_solve_helper)
+@out_wrapper()
+def _cholesky_solve_helper(self: Tensor, A: Tensor, upper: bool) -> Tensor:
+    return cloneBatchedColumnMajor(self)
+
+
+@register_meta(aten.cholesky_solve)
+@out_wrapper()
+def cholesky_solve(self: Tensor, A: Tensor, upper: bool = False) -> Tensor:
+    torch._check(
+        self.ndim >= 2,
+        lambda: f"b should have at least 2 dimensions, but has {self.ndim} dimensions instead",
+    )
+    torch._check(
+        A.ndim >= 2,
+        lambda: f"u should have at least 2 dimensions, but has {A.ndim} dimensions instead",
+    )
+    self_broadcasted, A_broadcasted = _linalg_broadcast_batch_dims_name(
+        self, A, "cholesky_solve"
+    )
+    return _cholesky_solve_helper(self_broadcasted, A_broadcasted, upper)
+
+
+@register_meta(aten.cholesky)
+@out_wrapper()
+def cholesky(self: Tensor, upper: bool = False) -> Tensor:
+    if self.numel() == 0:
+        return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
+    squareCheckInputs(self, "cholesky")
+    return cloneBatchedColumnMajor(self)
+
+
+@register_meta(aten.cholesky_inverse)
+@out_wrapper()
+def cholesky_inverse(self: Tensor, upper: bool = False) -> Tensor:
+    squareCheckInputs(self, "cholesky_inverse")
+    return cloneBatchedColumnMajor(self)
+
+
+# From aten/src/ATen/native/BatchLinearAlgebra.cpp
+@register_meta(aten.linalg_cholesky_ex.default)
+def linalg_cholesky_ex(A: Tensor, upper: bool = False, check_errors: bool = False):
+    squareCheckInputs(A, "linalg.cholesky")
+    checkFloatingOrComplex(A, "linalg.cholesky")
+
+    A_shape = A.shape
+    ndim = len(A_shape)
+
+    # L
+    L_strides = make_contiguous_strides_for(A_shape, False)
+    L = A.new_empty(A_shape)
+    L.as_strided_(A_shape, L_strides)
+
+    # infos
+    infos = A.new_empty(A_shape[0 : ndim - 2], dtype=torch.int32)
+    return L, infos
+
+
+@register_meta(
+    [aten.linalg_householder_product.default, aten.linalg_householder_product.out]
+)
+@out_wrapper()
+def linalg_householder_product(input: Tensor, tau: Tensor) -> Tensor:
+    torch._check(
+        input.ndim >= 2,
+        lambda: "torch.linalg.householder_product: input must have at least 2 dimensions.",
+    )
+    torch._check(
+        input.size(-2) >= input.size(-1),
+        lambda: "torch.linalg.householder_product: input.shape[-2] must be greater than or equal to input.shape[-1]",
+    )
+    torch._check(
+        input.size(-1) >= tau.size(-1),
+        lambda: "torch.linalg.householder_product: input.shape[-1] must be greater than or equal to tau.shape[-1]",
+    )
+
+    torch._check(
+        input.ndim - tau.ndim == 1,
+        lambda: (
+            f"torch.linalg.householder_product: Expected tau to have one dimension less than input, "
+            f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}"
+        ),
+    )
+    if input.ndim > 2:
+        expected_batch_tau_shape = input.shape[:-2]
+        actual_batch_tau_shape = tau.shape[:-1]
+        torch._check(
+            actual_batch_tau_shape == expected_batch_tau_shape,
+            lambda: (
+                f"torch.linalg.householder_product: Expected batch dimensions of tau to be "
+                f"equal to input.shape[:-2], but got {actual_batch_tau_shape}"
+            ),
+        )
+
+    torch._check(
+        tau.dtype == input.dtype,
+        lambda: (
+            f"torch.linalg.householder_product: tau dtype {tau.dtype}"
+            f" does not match input dtype {input.dtype}"
+        ),
+    )
+    checkSameDevice("torch.linalg.householder_product", tau, input, "tau")
+
+    return torch.empty_strided(
+        size=input.shape,
+        stride=make_contiguous_strides_for(input.shape, row_major=False),
+        dtype=input.dtype,
+        device=input.device,
+    )
+
+
+# From aten/src/ATen/native/BatchLinearAlgebra.cpp
+@register_meta(aten.linalg_inv_ex.default)
+def linalg_inv_ex_meta(A: Tensor, check_errors: bool = False):
+    squareCheckInputs(A, "linalg.inv_ex")
+    checkFloatingOrComplex(A, "linalg.inv_ex", allow_low_precision_dtypes=False)
+
+    L = A.new_empty(A.shape)
+    L.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False))
+
+    infos = A.new_empty(A.shape[:-2], dtype=torch.int32)
+    return L, infos
+
+
+@register_meta([aten.linalg_ldl_factor_ex.default, aten.linalg_ldl_factor_ex.out])
+@out_wrapper("LD", "pivots", "info")
+def linalg_ldl_factor_ex_meta(
+    self: Tensor,
+    *,
+    hermitian: bool = False,
+    check_errors: bool = False,
+) -> tuple[Tensor, Tensor, Tensor]:
+    squareCheckInputs(self, "torch.linalg.ldl_factor_ex")
+    checkFloatingOrComplex(self, "torch.linalg.ldl_factor_ex")
+    LD = torch.empty_strided(
+        size=self.shape,
+        stride=make_contiguous_strides_for(self.shape, row_major=False),
+        dtype=self.dtype,
+        device=self.device,
+    )
+    pivots = self.new_empty(self.shape[:-1], dtype=torch.int)
+    info = self.new_empty(self.shape[:-2], dtype=torch.int)
+    return LD, pivots, info
+
+
+@register_meta([aten.linalg_ldl_solve.default, aten.linalg_ldl_solve.out])
+@out_wrapper()
+def linalg_ldl_solve_meta(
+    LD: Tensor,
+    pivots: Tensor,
+    B: Tensor,
+    *,
+    hermitian: bool = False,
+) -> Tensor:
+    squareCheckInputs(LD, "torch.linalg.ldl_solve")
+    checkFloatingOrComplex(LD, "torch.linalg.ldl_solve")
+    linearSolveCheckInputs(B, LD, "torch.linalg.ldl_solve")
+    torch._check(
+        B.ndim >= 2,
+        lambda: (
+            f"torch.linalg.ldl_solve: Expected B to have at least 2 dimensions, "
+            f"but it has {B.ndim} dimensions instead"
+        ),
+    )
+    expected_pivots_shape = LD.shape[:-1]
+    torch._check(
+        expected_pivots_shape == pivots.shape,
+        lambda: (
+            f"torch.linalg.ldl_solve: Expected LD.shape[:-1] and pivots.shape to be the same, "
+            f"but got pivots with shape {pivots.shape} instead"
+        ),
+    )
+    torch._check(
+        utils.is_integer_dtype(pivots.dtype),
+        lambda: f"torch.linalg.ldl_solve: Expected pivots to be integers. Got {pivots.dtype}",
+    )
+    torch._check(
+        LD.dtype == B.dtype,
+        lambda: f"torch.linalg.ldl_solve: LD dtype {LD.dtype} does not match b dtype {B.dtype}",
+    )
+    B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LD)
+    return torch.empty_strided(
+        size=B_broadcast_size,
+        stride=make_contiguous_strides_for(B_broadcast_size, row_major=False),
+        dtype=B.dtype,
+        device=B.device,
+    )
+
+
+@register_meta([aten.linalg_lu.default, aten.linalg_lu.out])
+@out_wrapper("P", "L", "U")
+def linalg_lu_meta(A: Tensor, *, pivot: bool = True) -> tuple[Tensor, Tensor, Tensor]:
+    torch._check(
+        A.ndim >= 2,
+        lambda: f"linalg.lu: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead",
+    )
+
+    sizes = list(A.shape)
+    m = sizes[-2]
+    n = sizes[-1]
+    k = min(m, n)
+
+    sizes[-1] = m
+    if pivot:
+        P = A.new_empty(sizes)
+    else:
+        P = A.new_empty([0])
+
+    sizes[-1] = k
+    L = A.new_empty(sizes)
+
+    sizes[-2] = k
+    sizes[-1] = n
+    U = A.new_empty(sizes)
+    return P, L, U
+
+
+@register_meta([aten.linalg_lu_factor_ex.default, aten.linalg_lu_factor_ex.out])
+@out_wrapper("LU", "pivots", "info")
+def linalg_lu_factor_ex_meta(
+    A: Tensor,
+    *,
+    pivot: bool = True,
+    check_errors: bool = False,
+) -> tuple[Tensor, Tensor, Tensor]:
+    torch._check(
+        A.ndim >= 2,
+        lambda: f"torch.lu_factor: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead",
+    )
+
+    sizes = list(A.shape)
+    m = sizes[-2]
+    n = sizes[-1]
+
+    LU = torch.empty_strided(
+        size=sizes,
+        stride=make_contiguous_strides_for(sizes, row_major=False),
+        dtype=A.dtype,
+        device=A.device,
+    )
+
+    # Sets sizes to the size of pivots
+    sizes.pop()
+    sizes[-1] = min(m, n)
+    pivots = A.new_empty(sizes, dtype=torch.int)
+
+    # Sets sizes to the size of info
+    sizes.pop()
+    info = A.new_empty(sizes, dtype=torch.int)
+
+    return LU, pivots, info
+
+
+@register_meta([aten.linalg_lu_solve.default, aten.linalg_lu_solve.out])
+@out_wrapper()
+def linalg_lu_solve_meta(
+    LU: Tensor,
+    pivots: Tensor,
+    B: Tensor,
+    *,
+    left: bool = True,
+    adjoint: bool = False,
+) -> Tensor:
+    # dtype
+    checkFloatingOrComplex(LU, "torch.linalg.lu_solve")
+    torch._check(
+        LU.dtype == B.dtype,
+        lambda: (
+            f"linalg.lu_solve: Expected LU and B to have the same dtype, "
+            f"but found LU of type {LU.dtype} and B of type {B.dtype} instead"
+        ),
+    )
+    torch._check(
+        pivots.dtype == torch.int,
+        lambda: "linalg.lu_solve: pivots should be a Tensor of scalar type torch.int32",
+    )
+
+    # matrix shapes
+    squareCheckInputs(LU, "torch.linalg.lu_solve")
+    checkInputsSolver(LU, B, left, "linalg.lu_solve")
+    torch._check(
+        LU.size(-1) == pivots.size(-1),
+        lambda: "linalg.lu_solve: Number of pivots per batch should be same as the dimension of the matrix",
+    )
+
+    # batches
+    torch._check(
+        LU.shape[:-1] == pivots.shape,
+        lambda: (
+            f"linalg.lu_solve: Expected LU.shape[:-1] and pivots.shape to be the same, "
+            f"but got pivots with shape {pivots.shape} instead"
+        ),
+    )
+
+    B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LU)
+
+    result = torch.empty_strided(
+        size=B_broadcast_size,
+        stride=make_contiguous_strides_for(B_broadcast_size, row_major=not left),
+        dtype=B.dtype,
+        device=B.device,
+    )
+
+    if result.numel() != 0 and not left:
+        if result.is_complex():
+            result = result.conj()
+
+    return result
+
+
+@register_meta(aten.lu_unpack)
+@out_wrapper("P", "L", "U")
+def lu_unpack_meta(
+    LU: Tensor,
+    pivots: Tensor,
+    unpack_data: bool = True,
+    unpack_pivots: bool = True,
+) -> tuple[Tensor, Tensor, Tensor]:
+    torch._check(
+        LU.ndim >= 2,
+        lambda: f"torch.lu_unpack: Expected tensor with 2 or more dimensions. Got size: {LU.shape} instead",
+    )
+    if unpack_pivots:
+        torch._check(
+            pivots.dtype == torch.int32,
+            lambda: (
+                "torch.lu_unpack: LU_pivots is expected to be a contiguous tensor of torch.int32 dtype.\n"
+                "Note: this function is intended to be used with the output produced by torch.linalg.lu_factor"
+            ),
+        )
+    sizes = list(LU.shape)
+    m = sizes[-2]
+    n = sizes[-1]
+    k = min(m, n)
+    sizes[-1] = m
+    if unpack_pivots:
+        P = LU.new_empty(sizes)
+    else:
+        P = LU.new_empty([0])
+    if unpack_data:
+        sizes[-1] = k
+        L = LU.new_empty(sizes)
+        sizes[-2] = k
+        sizes[-1] = n
+        U = LU.new_empty(sizes)
+    else:
+        L = LU.new_empty([0])
+        U = LU.new_empty([0])
+    return P, L, U
+
+
+# parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced)
+def _parse_qr_mode(mode: str) -> tuple[bool, bool]:
+    if mode == "reduced":
+        compute_q = True
+        reduced = True
+    elif mode == "complete":
+        compute_q = True
+        reduced = False
+    elif mode == "r":
+        compute_q = False
+        reduced = True  # this is actually irrelevant in this mode
+    else:
+        torch._check(
+            False,
+            lambda: (
+                f"qr received unrecognized mode '{mode}' "
+                f"but expected one of 'reduced' (default), 'r', or 'complete'"
+            ),
+        )
+    return compute_q, reduced  # type: ignore[possibly-undefined]
+
+
+@register_meta([aten.linalg_qr.default, aten.linalg_qr.out])
+@out_wrapper("Q", "R")
+def linalg_qr_meta(A: Tensor, mode: str = "reduced") -> tuple[Tensor, Tensor]:
+    checkIsMatrix(A, "linalg.qr")
+    checkFloatingOrComplex(A, "linalg.qr")
+
+    compute_q, reduced_mode = _parse_qr_mode(mode)
+
+    m = A.shape[-2]
+    n = A.shape[-1]
+    k = min(m, n)
+
+    if compute_q:
+        Q_shape = list(A.shape)
+        Q_shape[-1] = k if reduced_mode else m
+        Q = A.new_empty(Q_shape)
+        Q.as_strided_(Q_shape, make_contiguous_strides_for(Q_shape, row_major=False))
+    else:
+        Q = A.new_empty([0])
+
+    # For readability
+    R_shape = list(A.shape)
+    R_shape[-2] = k if reduced_mode or not compute_q else m
+    R = A.new_empty(R_shape)
+    R.as_strided_(R_shape, make_contiguous_strides_for(R_shape, row_major=False))
+    return Q, R
+
+
+@register_meta([aten._linalg_slogdet.default, aten._linalg_slogdet.sign])
+@out_wrapper("sign", "logabsdet", "LU", "pivots")
+def _linalg_slogdet(A: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+    squareCheckInputs(A, "linalg.slogdet")
+    checkFloatingOrComplex(A, "linalg.slogdet", False)
+    shape = A.shape
+    sign = A.new_empty(shape[:-2])
+    logabsdet = A.new_empty(shape[:-2], dtype=toRealValueType(A.dtype))
+    LU = torch.empty_strided(
+        size=shape,
+        stride=make_contiguous_strides_for(shape, False),
+        dtype=A.dtype,
+        device=A.device,
+    )
+    pivots = A.new_empty(shape[:-1], dtype=torch.int32)
+    return sign, logabsdet, LU, pivots
+
+
+# From aten/src/ATen/native/BatchLinearAlgebra.cpp
+# NOTE: matching defaults in aten/src/ATen/native/native_functions.yaml
+@register_meta(aten._linalg_svd.default)
+def _linalg_svd_meta(
+    A: Tensor,
+    full_matrices: bool = False,
+    compute_uv: bool = True,
+    driver: Optional[str] = None,
+):
+    checkIsMatrix(A, "linalg.svd")
+    checkFloatingOrComplex(A, "linalg.svd")
+
+    batch_dims = list(A.shape[:-2])
+    m = A.shape[-2]
+    n = A.shape[-1]
+    k = min(m, n)
+
+    if compute_uv:
+        U_shape = batch_dims + [m, m if full_matrices else k]
+        U = A.new_empty(U_shape)
+        U.as_strided_(U_shape, make_contiguous_strides_for(U_shape, row_major=False))
+
+        V_shape = batch_dims + [n if full_matrices else k, n]
+        V = A.new_empty(V_shape)
+        # NB: This checks for CUDA since there is no way to check for cuSolver.
+        # Also, this might not work correctly on CPU when fake_device is not
+        # available as device_hint just defaults to CUDA in that case. See
+        # _linalg_svd meta in core.
+        is_cuda = device_hint(A) == "cuda"
+        V.as_strided_(V_shape, make_contiguous_strides_for(V_shape, row_major=is_cuda))
+    else:
+        # doesn't matter
+        U = A.new_empty([0])
+        V = A.new_empty([0])
+
+    # S is always real, even when A is complex.
+    S = A.new_empty(batch_dims + [k], dtype=toRealValueType(A.dtype))
+    return U, S, V
+
+
+def _linalg_broadcast_batch_dims(
+    arg1: Tensor,
+    arg2: Tensor,
+) -> tuple[list[int], list[int]]:
+    # broadcast the batch dimensions of arg1 and arg2.
+    arg1_batch_sizes = arg1.shape[:-2]
+    arg2_batch_sizes = arg2.shape[:-2]
+    expand_batch_portion = _broadcast_shapes(arg1_batch_sizes, arg2_batch_sizes)
+
+    arg1_expand_size = list(expand_batch_portion)
+    arg1_expand_size += [arg1.size(-2), arg1.size(-1)]
+
+    arg2_expand_size = list(expand_batch_portion)
+    arg2_expand_size += [arg2.size(-2), arg2.size(-1)]
+    return arg1_expand_size, arg2_expand_size
+
+
+def _linalg_broadcast_batch_dims_name(
+    arg1: Tensor,
+    arg2: Tensor,
+    name: Optional[str],
+) -> tuple[Tensor, Tensor]:
+    # If there's no name we assume we don't want to check the errors
+    if name:
+        linearSolveCheckInputs(arg1, arg2, name)
+
+    arg1_expand_size, arg2_expand_size = _linalg_broadcast_batch_dims(arg1, arg2)
+
+    arg1_broadcasted = (
+        arg1 if arg1_expand_size == arg1.shape else arg1.expand(arg1_expand_size)
+    )
+    arg2_broadcasted = (
+        arg2 if arg2_expand_size == arg2.shape else arg2.expand(arg2_expand_size)
+    )
+    return arg1_broadcasted, arg2_broadcasted
+
+
+def linalg_solve_is_vector_rhs(input: Tensor, other: Tensor) -> bool:
+    expected_batched_rhs_shape = input.shape[:-1]
+    vector_case = other.ndim == 1 or (
+        input.ndim - 1 == other.ndim and other.shape == expected_batched_rhs_shape
+    )
+    return vector_case
+
+
+@register_meta(aten._linalg_solve_ex)
+def _linalg_solve_ex(
+    A: Tensor,
+    B: Tensor,
+    *,
+    left: bool = True,
+    check_errors: bool = False,
+    result: Optional[Tensor] = None,
+    LU: Optional[Tensor] = None,
+    pivots: Optional[Tensor] = None,
+    info: Optional[Tensor] = None,
+) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+    checkFloatingOrComplex(A, "linalg.solve")
+    torch._check(
+        A.dtype == B.dtype,
+        lambda: (
+            f"linalg.solve: Expected A and B to have the same dtype, but found A of type "
+            f"{A.dtype} and B of type {B.dtype} instead"
+        ),
+    )
+    vector_case = linalg_solve_is_vector_rhs(A, B)
+    B_ = B.unsqueeze(-1) if vector_case else B
+    checkInputsSolver(A, B_, left, "linalg.solve")
+    B_broad_shape, _ = _linalg_broadcast_batch_dims(B_, A)
+    torch._check(
+        left or not vector_case,
+        lambda: (
+            "linalg.solve: Vector broadcasting of the left hand side is not supported for left=False. "
+            "In this case linalg.solve is equivalent to B / A.squeeze(-1)"
+        ),
+    )
+    result_shape = B_broad_shape[:-1] if vector_case else B_broad_shape
+    result_ = torch.empty_strided(
+        size=result_shape,
+        stride=make_contiguous_strides_for(result_shape, not left),
+        dtype=B.dtype,
+        device=B.device,
+    )
+    shape = A.shape
+    LU_ = torch.empty_strided(
+        size=shape,
+        stride=make_contiguous_strides_for(shape, False),
+        dtype=A.dtype,
+        device=A.device,
+    )
+    pivots_ = A.new_empty(shape[:-1], dtype=torch.int32)
+    info_ = A.new_empty(shape[:-2], dtype=torch.int32)
+    out = (result, LU, pivots, info)
+    res = (result_, LU_, pivots_, info_)
+    if all(x is not None for x in out):
+        for r, o in zip(res, out):
+            # resize and copy operations are done in-place
+            _maybe_resize_out(o, r.shape)  # type: ignore[arg-type]
+            # strides are not copied in out_wrapper
+            o.as_strided_(r.shape, r.stride())  # type: ignore[union-attr]
+            _safe_copy_out(copy_from=r, copy_to=o, exact_dtype=False)  # type: ignore[arg-type]
+    return res
+
+
+@register_meta([aten.linalg_solve_triangular.default, aten.linalg_solve_triangular.out])
+def linalg_solve_triangular_meta(
+    A: Tensor,
+    B: Tensor,
+    *,
+    upper: bool,
+    left: bool = True,
+    unitriangular: bool = False,
+    out: Optional[Tensor] = None,
+) -> Tensor:
+    if out is None:
+        out = A.new_empty([0])
+    assert isinstance(out, TensorLike)
+    checkInputsSolver(A, B, left, "linalg.solve_triangular")
+    B_, A_ = _linalg_broadcast_batch_dims_name(B, A, None)
+    avoid_copy_A = A_.transpose(-2, -1).is_contiguous() and A_.is_conj()
+    if avoid_copy_A:
+        out = _maybe_resize_out(out, B_.shape)
+    else:
+        # reimplementation of resize_output with result F-contig
+        if _resize_output_check(out, B_.shape):
+            out.resize_(B_.transpose(-2, -1).shape)
+            out.transpose_(-2, -1)
+    return out  # type: ignore[return-value]
+
+
+@register_meta(aten.triangular_solve)
+@out_wrapper("X", "M", exact_dtype=True)
+def triangular_solve_meta(
+    self: Tensor,
+    A: Tensor,
+    upper: bool = True,
+    transpose: bool = False,
+    unitriangular: bool = False,
+) -> tuple[Tensor, Tensor]:
+    torch._check(
+        self.ndim >= 2,
+        lambda: (
+            f"torch.triangular_solve: Expected b to have at least 2 dimensions, "
+            f"but it has {self.ndim} dimensions instead"
+        ),
+    )
+    torch._check(
+        A.ndim >= 2,
+        lambda: (
+            f"torch.triangular_solve: Expected A to have at least 2 dimensions, "
+            f"but it has {A.ndim} dimensions instead"
+        ),
+    )
+
+    linearSolveCheckInputs(self, A, "triangular_solve")
+
+    if A.layout == torch.strided:
+        self_broadcast_size, A_broadcast_size = _linalg_broadcast_batch_dims(self, A)
+        solution = torch.empty_strided(
+            size=self_broadcast_size,
+            stride=make_contiguous_strides_for(self_broadcast_size, row_major=False),
+            dtype=self.dtype,
+            device=self.device,
+        )
+        cloned_coefficient = torch.empty_strided(
+            size=A_broadcast_size,
+            stride=make_contiguous_strides_for(A_broadcast_size, row_major=False),
+            dtype=A.dtype,
+            device=A.device,
+        )
+    elif A.layout == torch.sparse_csr or A.layout == torch.sparse_bsr:
+        solution = torch.empty_like(self)
+        cloned_coefficient = self.new_empty([0])
+    else:
+        torch._check(False, lambda: "triangular_solve: Got an unexpected layout.")
+    return solution, cloned_coefficient  # type: ignore[possibly-undefined]
+
+
+# From aten/src/ATen/native/LinearAlgebra.cpp
+@register_meta(aten._linalg_det.default)
+def _linalg_det_meta(A):
+    squareCheckInputs(A, "linalg.det")
+    checkFloatingOrComplex(A, "linalg.det")
+
+    det = A.new_empty(A.shape[:-2])
+
+    LU = A.new_empty(A.shape)
+    LU.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False))
+
+    pivots = A.new_empty(A.shape[:-1], dtype=torch.int32)
+    return det, LU, pivots
+
+
+@register_meta(aten.ormqr)
+@out_wrapper()
+def ormqr(
+    input: Tensor,
+    tau: Tensor,
+    other: Tensor,
+    left: bool = True,
+    transpose: bool = False,
+) -> Tensor:
+    torch._check(
+        input.ndim >= 2, lambda: "torch.ormqr: input must have at least 2 dimensions."
+    )
+    torch._check(
+        other.ndim >= 2, lambda: "torch.ormqr: other must have at least 2 dimensions."
+    )
+
+    left_size_condition = -2 if left else -1
+    torch._check(
+        other.shape[left_size_condition] >= tau.shape[-1],
+        lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be greater than or equal to tau.shape[-1]",
+    )
+    torch._check(
+        other.shape[left_size_condition] == input.shape[-2],
+        lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be equal to input.shape[-2]",
+    )
+
+    torch._check(
+        tau.shape[-1] <= input.shape[-1],
+        lambda: "torch.ormqr: tau.shape[-1] must be less than or equal to input.shape[-1]",
+    )
+
+    torch._check(
+        input.ndim - tau.ndim == 1,
+        lambda: (
+            f"torch.ormqr: Expected tau to have one dimension less than input, "
+            f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}"
+        ),
+    )
+    torch._check(
+        input.ndim == other.ndim,
+        lambda: (
+            f"torch.ormqr: Expected other to have the same number of dimensions as input, "
+            f"but got other.ndim equal to {other.ndim} and input.ndim is equal to {input.ndim}"
+        ),
+    )
+
+    if input.ndim > 2:
+        expected_batch_shape = input.shape[:-2]
+        actual_batch_tau_shape = tau.shape[:-1]
+        torch._check(
+            actual_batch_tau_shape == expected_batch_shape,
+            lambda: (
+                f"torch.ormqr: Expected batch dimensions of tau to be "
+                f"equal to input.shape[:-2], but got {actual_batch_tau_shape}"
+            ),
+        )
+
+        actual_batch_other_shape = other.shape[:-2]
+        torch._check(
+            actual_batch_other_shape == expected_batch_shape,
+            lambda: (
+                f"torch.ormqr: Expected batch dimensions of other to be "
+                f"equal to input.shape[:-2], but got {actual_batch_other_shape}"
+            ),
+        )
+
+    torch._check(
+        tau.dtype == input.dtype,
+        lambda: (
+            f"torch.ormqr: Expected input and tau to have the same dtype, "
+            f"but input has dtype {input.dtype} and tau has dtype {tau.dtype}"
+        ),
+    )
+    torch._check(
+        other.dtype == input.dtype,
+        lambda: (
+            f"torch.ormqr: Expected input and other to have the same dtype, "
+            f"but input has dtype {input.dtype} and other has dtype {other.dtype}"
+        ),
+    )
+
+    checkSameDevice("torch.ormqr", tau, input, "tau")
+    checkSameDevice("torch.ormqr", other, input, "other")
+
+    return torch.empty_strided(
+        size=other.shape,
+        stride=make_contiguous_strides_for(other.shape, row_major=False),
+        dtype=other.dtype,
+        device=other.device,
+    )
+
+
+def _padding_check_valid_input(input, padding, *, dim):
+    torch._check(
+        len(padding) == 2 * dim,
+        lambda: f"padding size is expected to be {2 * dim}, but got: {len(padding)}",
+    )
+
+    input_dim = input.ndim
+
+    is_batch_mode = input_dim == (dim + 2)
+
+    valid_batch_mode = is_batch_mode
+    valid_non_batch_mode = not is_batch_mode
+
+    if is_batch_mode:
+        # allow batch size of 0-dim.
+        for d in range(1, input_dim):
+            valid_batch_mode = valid_batch_mode and input.size(d) != 0
+    else:
+        for d in range(0, input_dim):
+            valid_non_batch_mode = valid_non_batch_mode and input.size(d) != 0
+
+    # allow empty batch size but not other dimensions.
+    torch._check(
+        valid_batch_mode or valid_non_batch_mode,
+        lambda: (
+            f"Expected {dim + 1}D or {dim + 2}D (batch mode) tensor with possibly 0 batch size "
+            f"and other non-zero dimensions for input, but got: {input.shape}"
+        ),
+    )
+
+
+def _pad1d_common(input, padding, *, is_reflection):
+    dim_plane = 0
+    dim_w = 1
+    nbatch = 1
+
+    if input.ndim == 3:
+        nbatch = input.size(0)
+        dim_w += 1
+        dim_plane += 1
+
+    _padding_check_valid_input(input, padding, dim=1)
+
+    pad_l, pad_r = padding
+
+    nplane = input.size(dim_plane)
+    input_w = input.size(dim_w)
+    output_w = input_w + pad_l + pad_r
+
+    if is_reflection:
+        torch._check(
+            pad_l < input_w and pad_r < input_w,
+            lambda: (
+                f"Argument #4: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
+            ),
+        )
+
+    torch._check(
+        output_w >= 1,
+        lambda: f"input (W: {input_w}) is too small. Calculated output W: {output_w}",
+    )
+
+    if input.ndim == 2:
+        return input.new_empty((nplane, output_w))
+    else:
+        return input.new_empty((nbatch, nplane, output_w))
+
+
+@register_meta(aten.reflection_pad1d)
+@out_wrapper()
+def meta_reflection_pad1d(input, padding):
+    return _pad1d_common(input, padding, is_reflection=True)
+
+
+@register_meta(aten.replication_pad1d)
+@out_wrapper()
+def meta_replication_pad1d(input, padding):
+    return _pad1d_common(input, padding, is_reflection=False)
+
+
+def _pad1d_backward_common(grad_output, input, padding, *, is_reflection):
+    dim_w = 1
+    if not is_reflection:
+        torch._check(len(padding) == 2, lambda: "padding size is expected to be 2")
+
+    if input.ndim == 3:
+        dim_w += 1
+
+    pad_l, pad_r = padding
+
+    input_w = input.size(dim_w)
+    output_w = input_w + pad_l + pad_r
+
+    if is_reflection:
+        torch._check(
+            pad_l < input_w and pad_r < input_w,
+            lambda: (
+                f"Argument #4: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
+            ),
+        )
+
+    torch._check(
+        output_w == grad_output.size(dim_w),
+        lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
+    )
+
+    return input.new_empty(input.shape)
+
+
+@register_meta(aten.reflection_pad1d_backward)
+@out_wrapper("grad_input")
+def meta_reflection_pad1d_backward(grad_output, input, padding):
+    return _pad1d_backward_common(grad_output, input, padding, is_reflection=True)
+
+
+@register_meta(aten.replication_pad1d_backward)
+@out_wrapper("grad_input")
+def meta_replication_pad1d_backward(grad_output, input, padding):
+    return _pad1d_backward_common(grad_output, input, padding, is_reflection=False)
+
+
+def _pad2d_common(input, padding, *, is_reflection):
+    dim_w = 2
+    dim_h = 1
+    dim_slices = 0
+    nbatch = 1
+
+    _padding_check_valid_input(input, padding, dim=2)
+
+    ndim = input.ndim
+    if ndim == 4:
+        nbatch = input.size(0)
+        dim_w += 1
+        dim_h += 1
+        dim_slices += 1
+
+    pad_l, pad_r, pad_t, pad_b = padding
+
+    nplane = input.size(dim_slices)
+    input_h = input.size(dim_h)
+    input_w = input.size(dim_w)
+    output_h = input_h + pad_t + pad_b
+    output_w = input_w + pad_l + pad_r
+
+    if is_reflection:
+        torch._check(
+            pad_l < input_w and pad_r < input_w,
+            lambda: (
+                f"Argument #4: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
+            ),
+        )
+        torch._check(
+            pad_t < input_h and pad_b < input_h,
+            lambda: (
+                f"Argument #6: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}"
+            ),
+        )
+
+    torch._check(
+        output_w >= 1 or output_h >= 1,
+        lambda: (
+            f"input (H: {input_h} W: {input_w}) is too small. "
+            f"Calculated output H: {output_h} W: {output_w}"
+        ),
+    )
+
+    if input.ndim == 3:
+        return input.new_empty((nplane, output_h, output_w))
+    else:
+        return input.new_empty((nbatch, nplane, output_h, output_w))
+
+
+@register_meta(aten.reflection_pad2d)
+@out_wrapper()
+def meta_reflection_pad2d(input, padding):
+    return _pad2d_common(input, padding, is_reflection=True)
+
+
+@register_meta(aten.replication_pad2d)
+@out_wrapper()
+def meta_replication_pad2d(input, padding):
+    return _pad2d_common(input, padding, is_reflection=False)
+
+
+@register_meta(
+    [
+        aten.reflection_pad2d_backward.default,
+        aten.reflection_pad2d_backward.grad_input,
+        aten.replication_pad2d_backward.default,
+        aten.replication_pad2d_backward.grad_input,
+    ]
+)
+@out_wrapper("grad_input")
+def meta_pad2d_backward(grad_output, self, padding):
+    dim_w = 2
+    dim_h = 1
+    dim_plane = 0
+
+    self_shape = self.shape
+    if self.dim() == 4:
+        dim_w += 1
+        dim_h += 1
+        dim_plane += 1
+
+    pad_l, pad_r, pad_t, pad_b = padding
+
+    input_h = self_shape[dim_h]
+    input_w = self_shape[dim_w]
+    output_h = input_h + pad_t + pad_b
+    output_w = input_w + pad_l + pad_r
+
+    torch._check(
+        output_w == grad_output.size(dim_w),
+        lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
+    )
+    torch._check(
+        output_h == grad_output.size(dim_h),
+        lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}",
+    )
+    return self.new_empty(self.shape)
+
+
+def _pad3d_common(input, padding, *, is_reflection):
+    dim_w = 3
+    dim_h = 2
+    dim_d = 1
+    dim_plane = 0
+
+    _padding_check_valid_input(input, padding, dim=3)
+
+    batch_mode = input.ndim == 5
+    if batch_mode:
+        nbatch = input.size(0)
+        dim_w += 1
+        dim_h += 1
+        dim_d += 1
+        dim_plane += 1
+
+    pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding
+
+    nplane = input.size(dim_plane)
+    input_d = input.size(dim_d)
+    input_h = input.size(dim_h)
+    input_w = input.size(dim_w)
+    output_d = input_d + pad_f + pad_bk
+    output_h = input_h + pad_t + pad_b
+    output_w = input_w + pad_l + pad_r
+
+    if is_reflection:
+        torch._check(
+            pad_l < input_w and pad_r < input_w,
+            lambda: (
+                f"Argument #4: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
+            ),
+        )
+        torch._check(
+            pad_t < input_h and pad_b < input_h,
+            lambda: (
+                f"Argument #6: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}"
+            ),
+        )
+        torch._check(
+            pad_f < input_d and pad_bk < input_d,
+            lambda: (
+                f"Argument #8: Padding size should be less than the corresponding input dimension, "
+                f"but got: padding ({pad_f}, {pad_bk}) at dimension {dim_d} of input {input.shape}"
+            ),
+        )
+
+    torch._check(
+        output_w >= 1 or output_h >= 1 or output_d >= 1,
+        lambda: (
+            f"input (D: {input_d} H: {input_h} W: {input_w}) is too small. "
+            f"Calculated output D: {output_d} H: {output_h} W: {output_w}"
+        ),
+    )
+
+    if batch_mode:
+        return input.new_empty((nbatch, nplane, output_d, output_h, output_w))  # type: ignore[possibly-undefined]
+    else:
+        return input.new_empty((nplane, output_d, output_h, output_w))
+
+
+@register_meta(aten.reflection_pad3d)
+@out_wrapper()
+def meta_reflection_pad3d(input, padding):
+    return _pad3d_common(input, padding, is_reflection=True)
+
+
+@register_meta(aten.replication_pad3d)
+@out_wrapper()
+def meta_replication_pad3d(input, padding):
+    return _pad3d_common(input, padding, is_reflection=False)
+
+
+@register_meta(
+    [
+        aten.reflection_pad3d_backward.default,
+        aten.reflection_pad3d_backward.grad_input,
+        aten.replication_pad3d_backward.default,
+        aten.replication_pad3d_backward.grad_input,
+    ]
+)
+@out_wrapper("grad_input")
+def meta_pad3d_backward(grad_output, input, padding):
+    torch._check(len(padding) == 6, lambda: "padding size is expected to be 6")
+    assert input.ndim > 3
+    assert grad_output.ndim == input.ndim
+
+    dim_w = 3
+    dim_h = 2
+    dim_d = 1
+
+    if input.ndim == 5:
+        dim_w += 1
+        dim_h += 1
+        dim_d += 1
+
+    pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding
+
+    input_d = input.size(dim_d)
+    input_h = input.size(dim_h)
+    input_w = input.size(dim_w)
+    output_d = input_d + pad_f + pad_bk
+    output_h = input_h + pad_t + pad_b
+    output_w = input_w + pad_l + pad_r
+
+    torch._check(
+        output_w == grad_output.size(dim_w),
+        lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
+    )
+    torch._check(
+        output_h == grad_output.size(dim_h),
+        lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}",
+    )
+    torch._check(
+        output_d == grad_output.size(dim_d),
+        lambda: f"grad_output depth unexpected. Expected: {output_d}, Got: {grad_output.size(dim_d)}",
+    )
+
+    return input.new_empty(input.shape)
+
+
+@register_meta(aten._pdist_forward)
+@out_wrapper()
+def meta__pdist_forward(self: Tensor, p: float = 2) -> Tensor:
+    torch._check(
+        self.is_contiguous(), lambda: "_pdist_forward requires contiguous input"
+    )
+    n = self.size(0)
+    if n <= 1:
+        return self.new_empty([0]).to(memory_format=torch.legacy_contiguous_format)  # type: ignore[call-overload]
+    else:
+        return self.new_empty((n * (n - 1) // 2,)).to(
+            memory_format=torch.legacy_contiguous_format
+        )  # type: ignore[call-overload]
+
+
+@register_meta(aten._pdist_backward)
+@out_wrapper()
+def meta__pdist_backward(grad: Tensor, self: Tensor, p: float, pdist: Tensor) -> Tensor:
+    torch._check(
+        self.is_contiguous(), lambda: "_pdist_backward requires self to be contiguous"
+    )
+    torch._check(
+        pdist.is_contiguous(), lambda: "_pdist_backward requires pdist to be contiguous"
+    )
+    return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
+
+
+@register_meta([aten.baddbmm.default, aten.baddbmm.out])
+@out_wrapper()
+def meta_baddbmm(self, batch1, batch2, *, beta=1, alpha=1):
+    dim1 = batch1.size(0)
+    dim2 = batch1.size(1)
+    dim3 = batch2.size(2)
+    self = self.expand((dim1, dim2, dim3))
+    torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
+    torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
+    torch._check(
+        self.dtype == batch1.dtype == batch2.dtype,
+        lambda: f"Input dtypes must be the same, got: input: {self.dtype}, batch1: {batch1.dtype}, batch2: {batch2.dtype}",
+    )
+    batch1_sizes = batch1.shape
+    batch2_sizes = batch2.shape
+    bs = batch1_sizes[0]
+    contraction_size = batch1_sizes[2]
+    torch._check(
+        batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size,
+        lambda: (
+            f"Expected size for first two dimensions of batch2 tensor to be: "
+            f"[{bs}, {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}]."
+        ),
+    )
+    return self.new_empty(self.size())
+
+
+@register_meta([aten.bernoulli.default, aten.bernoulli.out])
+@out_wrapper()
+def meta_bernoulli(self, *, generator=None):
+    # https://github.com/pytorch/pytorch/issues/88612
+    return torch.empty_like(self, memory_format=torch.contiguous_format)
+
+
+@register_meta(aten.bernoulli_.float)
+def meta_bernoulli_(self, p=0.5, generator=None):
+    return self
+
+
+@register_meta(aten.bernoulli.p)
+def meta_bernoulli_p(self, p=0.5, generator=None):
+    # https://github.com/pytorch/pytorch/issues/88612
+    return torch.empty_like(self, memory_format=torch.contiguous_format)
+
+
+@register_meta([aten.poisson.default, aten.poisson.out])
+@out_wrapper()
+def meta_poisson(self, generator=None):
+    return torch.empty_like(self)
+
+
+@register_meta(aten._fused_moving_avg_obs_fq_helper.default)
+def meta__fused_moving_avg_obs_fq_helper(
+    self,
+    observer_on,
+    fake_quant_on,
+    running_min,
+    running_max,
+    scale,
+    zero_point,
+    averaging_const,
+    quant_min,
+    quant_max,
+    ch_axis,
+    per_row_fake_quant=False,
+    symmetric_quant=False,
+):
+    torch._check(
+        ch_axis < self.dim(),
+        lambda: "Error in fused_moving_avg_obs_fake_quant_cpu: ch_axis must be < self.dim()",
+    )
+    mask = torch.empty_like(self, dtype=torch.bool)
+    return (torch.empty_like(self), mask)
+
+
+@register_meta(aten.mm)
+@out_wrapper()
+def meta_mm(a, b):
+    torch._check(a.dim() == 2, lambda: "a must be 2D")
+    torch._check(b.dim() == 2, lambda: "b must be 2D")
+    N, M1 = a.shape
+    M2, P = b.shape
+    torch._check(
+        M1 == M2,
+        lambda: f"a and b must have same reduction dim, but got [{N}, {M1}] X [{M2}, {P}].",
+    )
+    return a.new_empty(N, P)
+
+
+def _compute_reduction_shape(self, dims, keepdim):
+    if keepdim:
+        return tuple(self.shape[i] if i not in dims else 1 for i in range(self.ndim))
+
+    return utils.compute_reduction_output_shape(self.shape, dims)
+
+
+# FakeTensors (meta tensors with a device) will report device as meta
+# when running meta kernels. Here, access the "fake device" of FakeTensor if it
+# exists so meta kernels which have diverge per device will be more
+# accurate when run with FakeTensors
+def device_hint(tensor) -> "str":
+    if isinstance(tensor, torch._subclasses.FakeTensor):
+        return tensor.fake_device.type
+    elif (
+        hasattr(tensor, "device")
+        and hasattr(tensor.device, "type")
+        and tensor.device.type != "meta"
+    ):
+        return tensor.device.type
+    else:
+        return "cuda"  # default to cuda
+
+
+def calc_conv_nd_return_shape(
+    input_tensor: torch.Tensor,
+    weight: torch.Tensor,
+    stride: Union[list[int], int],
+    padding: Union[list[int], int],
+    dilation: Union[list[int], int],
+    is_transposed: bool,
+    groups: int,
+    output_padding: Optional[Union[list[int], int]] = None,
+):
+    def _formula(ln: int, p: int, d: int, k: int, s: int) -> int:
+        """
+        Formula to apply to calculate the length of some dimension of the output
+
+        See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
+
+        Args:
+            ln: length of the dimension
+            p: padding in that dim
+            d: dilation in that dim
+            k: kernel size in that dim
+            s: stride in that dim
+        Returns:
+            The output length
+        """
+        return (ln + 2 * p - d * (k - 1) - 1) // s + 1
+
+    def _formula_transposed(ln: int, p: int, d: int, k: int, s: int, op: int) -> int:
+        """
+        Formula to apply to calculate the length of some dimension of the output
+        if transposed convolution is used.
+        See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html
+
+        Args:
+            ln: length of the dimension
+            p: padding in that dim
+            d: dilation in that dim
+            k: kernel size in that dim
+            s: stride in that dim
+            op: output padding in that dim
+
+        Returns:
+            The output length
+        """
+        return (ln - 1) * s - 2 * p + d * (k - 1) + op + 1
+
+    kernel_size = weight.shape[2:]
+    dims = input_tensor.shape[2:]
+    if is_transposed:
+        out_channels = groups * weight.shape[1]
+    else:
+        out_channels = weight.shape[0]
+        if weight.shape[1] * groups != input_tensor.shape[1]:
+            raise RuntimeError("Invalid channel dimensions")
+
+    ret_shape = [input_tensor.shape[0], out_channels]
+    if isinstance(stride, IntLike):
+        stride = [stride] * len(dims)
+    elif len(stride) == 1:
+        stride = [stride[0]] * len(dims)
+
+    if isinstance(padding, IntLike):
+        padding = [padding] * len(dims)
+    elif len(padding) == 1:
+        padding = [padding[0]] * len(dims)
+
+    if isinstance(dilation, IntLike):
+        dilation = [dilation] * len(dims)
+    elif len(dilation) == 1:
+        dilation = [dilation[0]] * len(dims)
+
+    output_padding_list: Optional[list[int]] = None
+    if output_padding:
+        if isinstance(output_padding, IntLike):
+            output_padding_list = [output_padding] * len(dims)
+        elif len(output_padding) == 1:
+            output_padding_list = [output_padding[0]] * len(dims)
+        else:
+            output_padding_list = output_padding
+
+    for i in range(len(dims)):
+        # If output_padding is present, we are dealing with a transposed convolution
+        if output_padding_list:
+            ret_shape.append(
+                _formula_transposed(
+                    dims[i],
+                    padding[i],
+                    dilation[i],
+                    kernel_size[i],
+                    stride[i],
+                    output_padding_list[i],
+                )
+            )
+        else:
+            ret_shape.append(
+                _formula(dims[i], padding[i], dilation[i], kernel_size[i], stride[i])
+            )
+    torch._check(
+        any(x > 0 for x in ret_shape[2:]),
+        lambda: f"Given input size per channel: {list(dims)}. "
+        f"Calculated output size per channel: {ret_shape[2:]}. "
+        f"Output size is too small",
+    )
+
+    return ret_shape
+
+
+def is_channels_last(ten):
+    return torch._prims_common.suggest_memory_format(ten) == torch.channels_last
+
+
+@register_meta(aten.miopen_batch_norm.default)
+def meta_miopen_batch_norm(
+    input_tensor: torch.Tensor,
+    weight: torch.Tensor,
+    bias: Optional[torch.Tensor],
+    running_mean: Optional[torch.Tensor],
+    running_var: Optional[torch.Tensor],
+    training: bool,
+    exponential_average_factor: float,
+    epsilon: float,
+):
+    # In batch norm the output is of the same shape as the input
+    out_shape = input_tensor.shape
+
+    # If tensor is provided for running_mean and running_var then use this. If these are not
+    # provded then we return the shape of weight tensor. Similar to how this is handled in the decomposition
+    save_mean_shape = running_mean.shape if running_mean is not None else weight.shape
+    save_var_shape = running_var.shape if running_var is not None else weight.shape
+
+    def pick_memory_format():
+        if is_channels_last(input_tensor):
+            return torch.channels_last
+        if input_tensor.is_contiguous(memory_format=torch.contiguous_format):
+            return torch.contiguous_format
+        return torch.contiguous_format
+
+    out = input_tensor.new_empty(out_shape).to(memory_format=pick_memory_format())
+
+    if training:
+        save_mean = input_tensor.new_empty(save_mean_shape)
+        save_var = input_tensor.new_empty(save_var_shape)
+    else:
+        save_mean = input_tensor.new_empty((0,))
+        save_var = input_tensor.new_empty((0,))
+
+    return out, save_mean, save_var
+
+
+@register_meta(aten.convolution.default)
+def meta_conv(
+    input_tensor: torch.Tensor,
+    weight: torch.Tensor,
+    bias: torch.Tensor,
+    stride: list[int],
+    padding: list[int],
+    dilation: list[int],
+    is_transposed: bool,
+    output_padding: list[int],
+    groups: int,
+):
+    def pick_memory_format():
+        if device_hint(input_tensor) == "cuda":
+            if is_channels_last(input_tensor) or is_channels_last(weight):
+                return torch.channels_last
+        else:
+            if is_channels_last(input_tensor):
+                return torch.channels_last
+        if input_tensor.is_contiguous(memory_format=torch.contiguous_format):
+            return torch.contiguous_format
+        elif input_tensor.is_contiguous(memory_format=torch.preserve_format):
+            return torch.preserve_format
+
+    shape_out = calc_conv_nd_return_shape(
+        input_tensor,
+        weight,
+        stride,
+        padding,
+        dilation,
+        is_transposed,
+        groups,
+        output_padding if is_transposed else None,
+    )
+
+    input_channels_dim = 1
+    output_channels_dim = 1
+    if input_tensor.size(input_channels_dim) == 0:
+        shape_out[output_channels_dim] = 0
+
+    out = input_tensor.new_empty(shape_out)
+    out = out.to(memory_format=pick_memory_format())  # type: ignore[call-overload]
+    return out
+
+
+if torch._C._has_mkldnn:
+    _meta_lib_dont_use_me_use_register_meta_for_mkldnn = torch.library.Library(
+        "mkldnn", "IMPL", "Meta"
+    )
+
+    @register_meta(torch.ops.mkldnn._convolution_pointwise.default)
+    def meta_mkldnn_convolution_default(
+        input_tensor,
+        weight,
+        bias,
+        padding,
+        stride,
+        dilation,
+        groups,
+        attr,
+        scalars,
+        algorithm,
+    ):
+        shape_out = calc_conv_nd_return_shape(
+            input_tensor, weight, stride, padding, dilation, False, groups, []
+        )
+        out = input_tensor.new_empty(shape_out)
+        out_memory_format = torch.channels_last
+        if input_tensor.dim() == 5:
+            out_memory_format = torch.channels_last_3d
+        out = out.to(memory_format=out_memory_format)  # type: ignore[call-overload]
+        return out
+
+    @register_meta(torch.ops.mkldnn._linear_pointwise.default)
+    def meta_linear_pointwise_default(
+        input_tensor, weight, bias, attr, scalars, algorithm
+    ):
+        return input_tensor.new_empty((*input_tensor.shape[:-1], weight.shape[0]))
+
+    if torch._C.has_mkl:
+        _meta_lib_dont_use_me_use_register_meta_for_mkl = torch.library.Library(
+            "mkl", "IMPL", "Meta"
+        )
+
+        @register_meta(torch.ops.mkl._mkl_linear)
+        def meta_mkl_linear(input_tensor, packed_weight, orig_weight, bias, batch_size):
+            return input_tensor.new_empty(
+                (*input_tensor.shape[:-1], orig_weight.shape[0])
+            )
+
+    _meta_lib_dont_use_me_use_register_meta_for_onednn = torch.library.Library(
+        "onednn", "IMPL", "Meta"
+    )
+
+    @register_meta(torch.ops.onednn.qconv2d_pointwise.default)
+    def meta_qconv2d_pointwise(
+        x,
+        x_scale,
+        x_zp,
+        w,  # prepacked_weight
+        w_scale,
+        w_zp,
+        bias,
+        stride,
+        padding,
+        dilation,
+        groups,
+        output_scale,
+        output_zero_point,
+        output_dtype,
+        attr,
+        scalars,
+        algorithm,
+    ):
+        shape_out = calc_conv_nd_return_shape(
+            x,
+            w,
+            stride,
+            padding,
+            dilation,
+            False,
+            groups,
+            None,
+        )
+        assert output_dtype in [torch.float32, torch.bfloat16, torch.uint8, torch.int8]
+        out = x.new_empty(shape_out, dtype=output_dtype)
+        out = out.to(memory_format=torch.channels_last)
+        return out
+
+    @register_meta(torch.ops.onednn.qconv2d_pointwise.binary)
+    def meta_qconv2d_pointwise_binary(
+        x,
+        x_scale,
+        x_zp,
+        w,
+        w_scale,
+        w_zp,
+        accum,
+        bias,
+        stride,
+        padding,
+        dilation,
+        groups,
+        output_scale,
+        output_zero_point,
+        output_dtype,
+        accum_scale,
+        accum_zero_point,
+        binary_op_name,
+        alpha,
+        unary_op_name,
+        unary_op_args,
+        unary_op_algorithm,
+    ):
+        assert binary_op_name == "sum"
+        return accum
+
+    @register_meta(torch.ops.onednn.qlinear_pointwise.default)
+    @register_meta(torch.ops.onednn.qlinear_pointwise.tensor)
+    def meta_qlinear_pointwise(
+        x,
+        x_scale,
+        x_zp,
+        w,
+        w_scale,
+        w_zp,
+        bias,
+        output_scale,
+        output_zero_point,
+        output_dtype,
+        post_op_name,
+        post_op_args,
+        post_op_algorithm,
+    ):
+        output_shape = list(x.shape)
+        # The weight has been transposed during the qlinear weight prepack process.
+        output_shape[-1] = w.shape[1]
+        assert output_dtype in [torch.float32, torch.bfloat16, torch.int8, torch.uint8]
+        out = x.new_empty(output_shape, dtype=output_dtype)
+        return out
+
+    @register_meta(torch.ops.onednn.qlinear_pointwise.binary)
+    @register_meta(torch.ops.onednn.qlinear_pointwise.binary_tensor)
+    def meta_qlinear_pointwise_binary(
+        x,
+        x_scale,
+        x_zp,
+        w,
+        w_scale,
+        w_zp,
+        x_2,
+        bias,
+        output_scale,
+        output_zero_point,
+        output_dtype,
+        x2_scale,
+        x2_zp,
+        binary_op_name,
+        alpha,
+        unary_op_name,
+        unary_op_args,
+        unary_op_algorithm,
+    ):
+        if binary_op_name == "sum":
+            return x_2
+        output_shape = list(x.shape)
+        # The weight has been transposed during the qlinear weight prepack process.
+        output_shape[-1] = w.shape[1]
+        assert output_dtype in [torch.float32, torch.bfloat16, torch.uint8, torch.int8]
+        out = x.new_empty(output_shape, dtype=output_dtype)
+        return out
+
+    @register_meta(torch.ops.onednn.linear_dynamic_fp16.default)
+    @register_meta(torch.ops.onednn.linear_relu_dynamic_fp16.default)
+    def meta_linear_dynamic_fp16(
+        x,
+        w,
+        bias,
+    ):
+        output_shape = list(x.shape)
+        # The weight has been transposed during the qlinear weight prepack process.
+        output_shape[-1] = w.shape[1]
+        out = x.new_empty(output_shape)
+        return out
+
+    _meta_lib_dont_use_me_use_register_meta_for_quantized = torch.library.Library(
+        "quantized", "IMPL", "Meta"
+    )
+
+    @register_meta(torch.ops.quantized.max_pool2d)
+    def meta_quantized_max_pool2d(
+        input,
+        kernel_size,
+        stride=(),
+        padding=(0,),
+        dilation=(1,),
+        ceil_mode=False,
+    ):
+        (
+            nInputPlane,
+            outputHeight,
+            outputWidth,
+        ) = max_pool2d_checks_and_compute_shape(
+            input, kernel_size, stride, padding, dilation, ceil_mode
+        )
+        nbatch = input.size(-4) if input.dim() == 4 else 1
+        memory_format = torch.channels_last
+        if input.dim() == 3:
+            size = [nInputPlane, outputHeight, outputWidth]
+        else:
+            size = [nbatch, nInputPlane, outputHeight, outputWidth]
+        return torch.empty(
+            size,
+            dtype=input.dtype,
+            device=input.device,
+            memory_format=memory_format,
+        )
+
+    @register_meta(torch.ops.quantized.int4mm_packed_weight_cpu)
+    def meta_int4mm_packed_weight_cpu(x, w, q_group_size, q_scale_and_zeros):
+        torch._check(x.dim() == 2, f"x must be a 2D tensor, got {x.dim()}D")
+        torch._check(w.dim() == 2, f"w must be a 2D tensor, got {w.dim()}D")
+        torch._check(
+            x.dtype in [torch.float32, torch.float16, torch.bfloat16],
+            f"expected x to be f32/f16/bf16, got {x.dtype}",
+        )
+        torch._check(w.dtype == torch.uint8, f"expected w to be uint8, got {w.dtype}")
+        torch._check(
+            q_group_size.dtype == torch.int64,
+            f"q_group_size must be int64, got {q_group_size.dtype}",
+        )
+        torch._check(
+            q_scale_and_zeros.dtype == x.dtype,
+            f"q_scale_and_zeros must have the same dtype as x, got {q_scale_and_zeros.dtype}",
+        )
+        return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
+
+
+# from check_dim_size() in aten/src/ATen/TensorUtils.cpp.
+def check_dim_size(tensor, dim, dim_size, size):
+    torch._check(
+        tensor.dim() == dim and tensor.shape[dim_size] == size,
+        lambda: f"Expected a tensor of dimension {dim} and tensor.size[{dim_size}] == {size}, "
+        + f"but got : dimension {tensor.dim()} and tensor.size[{dim_size}] = {tensor.shape[dim_size]}",
+    )
+
+
+@register_meta(aten.avg_pool2d.default)
+def meta_avg_pool2d(
+    input,
+    kernel_size,
+    stride=(),
+    padding=(0,),
+    ceil_mode=False,
+    count_include_pad=True,
+    divisor_override=None,
+):
+    def unpack(name, val):
+        torch._check(
+            len(val) in [1, 2],
+            lambda: f"avg_pool2d: {name} must either be a single int, or a tuple of two ints",
+        )
+        H = val[0]
+        W = H if len(val) == 1 else val[1]
+        return H, W
+
+    kH, kW = unpack("kernel_size", kernel_size)
+    torch._check(
+        len(stride) in [0, 1, 2],
+        lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
+    )
+    torch._check(
+        input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64],
+        lambda: f""""avg_pool2d" not implemented for '{input.dtype.__str__()}'""",
+    )
+    if len(stride) == 0:
+        dH, dW = kH, kW
+    elif len(stride) == 1:
+        dH, dW = stride[0], stride[0]
+    else:
+        dH, dW = unpack("stride", stride)
+
+    padH, padW = unpack("padding", padding)
+
+    torch._check(
+        divisor_override is None or divisor_override != 0,
+        lambda: "divisor must be not zero",
+    )
+
+    nbatch = input.size(-4) if input.dim() == 4 else 1
+    nInputPlane = input.size(-3)
+    inputHeight = input.size(-2)
+    inputWidth = input.size(-1)
+
+    outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode)
+    outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode)
+
+    memory_format = utils.suggest_memory_format(input)
+    pool2d_shape_check(
+        input,
+        kH,
+        kW,
+        dH,
+        dW,
+        padH,
+        padW,
+        1,
+        1,
+        nInputPlane,
+        inputHeight,
+        inputWidth,
+        outputHeight,
+        outputWidth,
+        memory_format,
+    )
+
+    if input.dim() == 3:
+        size = [nInputPlane, outputHeight, outputWidth]
+    else:
+        size = [nbatch, nInputPlane, outputHeight, outputWidth]
+    return torch.empty(
+        size,
+        dtype=input.dtype,
+        device=input.device,
+        memory_format=memory_format,
+    )
+
+
+# from avg_pool2d_backward_shape_check() in aten/src/ATen/native/Pool.h.
+def avg_pool2d_backward_shape_check(
+    input,
+    gradOutput,
+    nbatch,
+    kH,
+    kW,
+    dH,
+    dW,
+    padH,
+    padW,
+    nInputPlane,
+    inputHeight,
+    inputWidth,
+    outputHeight,
+    outputWidth,
+    mem_format,
+):
+    pool2d_shape_check(
+        input,
+        kH,
+        kW,
+        dH,
+        dW,
+        padH,
+        padW,
+        1,
+        1,
+        nInputPlane,
+        inputHeight,
+        inputWidth,
+        outputHeight,
+        outputWidth,
+        mem_format,
+    )
+
+    ndim = input.dim()
+    nOutputPlane = nInputPlane
+
+    check_dim_size(gradOutput, ndim, ndim - 3, nOutputPlane)
+    check_dim_size(gradOutput, ndim, ndim - 2, outputHeight)
+    check_dim_size(gradOutput, ndim, ndim - 1, outputWidth)
+
+
+# Don't override the C++ registration.
+@register_meta(aten.avg_pool2d_backward.default)
+def meta_avg_pool2d_backward(
+    gradOutput_,
+    input,
+    kernel_size,
+    stride,
+    padding,
+    ceil_mode,
+    count_include_pad,
+    divisor_override,
+):
+    # From aten/src/ATen/native/AveragePool2d.cpp structured kernel meta func.
+    torch._check(
+        len(kernel_size) == 1 or len(kernel_size) == 2,
+        lambda: "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints",
+    )
+    kH = kernel_size[0]
+    kW = kH if len(kernel_size) == 1 else kernel_size[1]
+    torch._check(
+        len(stride) == 0 or len(stride) == 1 or len(stride) == 2,
+        lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
+    )
+    dH = kH if len(stride) == 0 else stride[0]
+    dW = kW if len(stride) == 0 else dH if len(stride) == 1 else stride[1]
+    torch._check(
+        len(padding) == 1 or len(padding) == 2,
+        lambda: "avg_pool2d: padding must either be a single int, or a tuple of two ints",
+    )
+    padH = padding[0]
+    padW = padH if len(padding) == 1 else padding[1]
+
+    torch._check(
+        divisor_override is None or divisor_override != 0,
+        lambda: "divisor must be not zero",
+    )
+
+    input_size = input.shape
+    nbatch = input_size[-4] if input.dim() == 4 else 1
+    nInputPlane = input_size[-3]
+    inputHeight = input_size[-2]
+    inputWidth = input_size[-1]
+
+    outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode)
+    outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode)
+
+    mem_format = utils.suggest_memory_format(input)
+
+    avg_pool2d_backward_shape_check(
+        input,
+        gradOutput_,
+        nbatch,
+        kH,
+        kW,
+        dH,
+        dW,
+        padH,
+        padW,
+        nInputPlane,
+        inputHeight,
+        inputWidth,
+        outputHeight,
+        outputWidth,
+        mem_format,
+    )
+
+    return torch.empty(
+        input_size,
+        dtype=input.dtype,
+        device=input.device,
+        memory_format=mem_format,
+    )
+
+
+@register_meta(aten.avg_pool3d)
+@out_wrapper()
+def meta_avg_pool3d(
+    input,
+    kernel_size,
+    stride=(),
+    padding=(0,),
+    ceil_mode=False,
+    count_include_pad=True,
+    divisor_override=None,
+):
+    torch._check(
+        len(kernel_size) in (1, 3),
+        lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints",
+    )
+    kT = kernel_size[0]
+    kH = kT if len(kernel_size) == 1 else kernel_size[1]
+    kW = kT if len(kernel_size) == 1 else kernel_size[2]
+
+    torch._check(
+        not stride or len(stride) in (1, 3),
+        lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints",
+    )
+    torch._check(
+        input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64],
+        lambda: f""""avg_pool3d" not implemented for '{input.dtype.__str__()}'""",
+    )
+    dT = kT if not stride else stride[0]
+    dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
+    dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
+
+    torch._check(
+        len(padding) in (1, 3),
+        lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints",
+    )
+    padT = padding[0]
+    padH = padT if len(padding) == 1 else padding[1]
+    padW = padT if len(padding) == 1 else padding[2]
+
+    torch._check(
+        input.ndim in (4, 5),
+        lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
+    )
+
+    torch._check(
+        not divisor_override or divisor_override != 0,
+        lambda: "divisor must be not zero",
+    )
+
+    nbatch = input.size(0)
+    nslices = input.size(-4)
+    itime = input.size(-3)
+    iheight = input.size(-2)
+    iwidth = input.size(-1)
+
+    otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode)
+    oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode)
+    owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode)
+
+    pool3d_shape_check(
+        input,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        padT,
+        padH,
+        padW,
+        1,
+        1,
+        1,
+        itime,
+        iheight,
+        iwidth,
+        otime,
+        oheight,
+        owidth,
+        "avg_pool3d()",
+        check_input_size=True,
+    )
+
+    if input.ndim == 4:
+        return input.new_empty((nslices, otime, oheight, owidth))
+    else:
+        return input.new_empty((nbatch, nslices, otime, oheight, owidth))
+
+
+@register_meta(aten.avg_pool3d_backward)
+@out_wrapper("grad_input")
+def meta_avg_pool3d_backward(
+    grad_output,
+    input,
+    kernel_size,
+    stride,
+    padding,
+    ceil_mode,
+    count_include_pad,
+    divisor_override,
+):
+    torch._check(
+        len(kernel_size) in (1, 3),
+        lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints",
+    )
+    kT = kernel_size[0]
+    kH = kT if len(kernel_size) == 1 else kernel_size[1]
+    kW = kT if len(kernel_size) == 1 else kernel_size[2]
+
+    torch._check(
+        not stride or len(stride) in (1, 3),
+        lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints",
+    )
+    dT = kT if not stride else stride[0]
+    dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
+    dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
+
+    torch._check(
+        len(padding) in (1, 3),
+        lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints",
+    )
+    padT = padding[0]
+    padH = padT if len(padding) == 1 else padding[1]
+    padW = padT if len(padding) == 1 else padding[2]
+
+    torch._check(
+        input.ndim in (4, 5),
+        lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
+    )
+
+    torch._check(
+        not divisor_override or divisor_override != 0,
+        lambda: "divisor must be not zero",
+    )
+
+    nslices = input.size(-4)
+    itime = input.size(-3)
+    iheight = input.size(-2)
+    iwidth = input.size(-1)
+
+    otime_for_shape_check = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode)
+    oheight_for_shape_check = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode)
+    owidth_for_shape_check = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode)
+
+    avg_pool3d_backward_shape_check(
+        input,
+        grad_output,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        padT,
+        padH,
+        padW,
+        itime,
+        iheight,
+        iwidth,
+        otime_for_shape_check,
+        oheight_for_shape_check,
+        owidth_for_shape_check,
+        "avg_pool3d_backward()",
+    )
+
+    return input.new_empty(input.shape)
+
+
+@register_meta(aten._adaptive_avg_pool2d.default)
+def meta_adaptive_avg_pool2d(self, output_size):
+    torch._check(
+        self.ndim == 3 or self.ndim == 4,
+        lambda: f"Expected 3D or 4D tensor, but got {self.shape}",
+    )
+    output_shape = self.shape[:-2] + tuple(output_size)
+    memory_format = utils.suggest_memory_format(self)
+    # need to set memory_format to preserve the memory format of the input
+    # channel last input should have channel last output
+    return torch.empty(
+        output_shape,
+        dtype=self.dtype,
+        device=self.device,
+        memory_format=memory_format,
+    )
+
+
+@register_meta(aten._adaptive_avg_pool3d.default)
+def meta_adaptive_avg_pool3d(self, output_size):
+    torch._check(
+        self.ndim == 4 or self.ndim == 5,
+        lambda: f"Expected 4D or 5D tensor, but got {self.shape}",
+    )
+    return self.new_empty(self.shape[:-3] + tuple(output_size))
+
+
+@register_meta(aten._adaptive_avg_pool2d_backward.default)
+def meta__adaptive_avg_pool2d_backward(grad_out, self):
+    ndim = grad_out.ndim
+    for i in range(1, ndim):
+        torch._check(
+            grad_out.size(i) > 0,
+            lambda: f"adaptive_avg_pool2d_backward(): Expected grad_output to have non-zero \
+                      size for non-batch dimensions, {grad_out.shape} with dimension {i} being empty",
+        )
+    torch._check(
+        ndim == 3 or ndim == 4,
+        lambda: f"adaptive_avg_pool2d_backward(): Expected 3D or 4D tensor, but got {self.shape}",
+    )
+    torch._check(
+        self.dtype == grad_out.dtype,
+        lambda: f"expected dtype {self.dtype} for `grad_output` but got dtype {grad_out.dtype}",
+    )
+    memory_format = torch.contiguous_format
+    if is_channels_last(self):
+        memory_format = torch.channels_last
+    return self.new_empty(self.shape).to(memory_format=memory_format)
+
+
+@register_meta(aten._adaptive_avg_pool3d_backward)
+@out_wrapper("grad_input")
+def meta__adaptive_avg_pool3d_backward(grad_output, self):
+    _adaptive_pool_empty_output_check(grad_output, "adaptive_avg_pool3d_backward")
+    return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
+
+
+def _adaptive_pool_empty_output_check(grad_output: Tensor, arg_name: str):
+    ndim = grad_output.ndim
+    for i in range(1, ndim):
+        torch._check(
+            grad_output.size(i) > 0,
+            lambda: (
+                f"{arg_name}(): Expected grad_output to have non-zero size for non-batch dimensions, "
+                f"but grad_output has sizes {grad_output.shape} with dimension {i} being empty"
+            ),
+        )
+
+
+@register_meta(aten.adaptive_max_pool2d)
+@out_wrapper("out", "indices")
+def meta_adaptive_max_pool2d(input, output_size):
+    ndim = input.ndim
+    torch._check(
+        ndim in (3, 4),
+        lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: {input.shape}",
+    )
+    for i in range(1, ndim):
+        torch._check(
+            input.size(i) > 0,
+            lambda: (
+                f"adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, "
+                f"but input has sizes {input.shape} with dimension {i} being empty"
+            ),
+        )
+
+    torch._check(
+        len(output_size) == 2,
+        lambda: "adaptive_max_pool2d(): internal error: output_size.size() must be 2",
+    )
+
+    dimH = 1
+    sizeB = 1
+    sizeD = 0
+
+    if input.ndim == 4:
+        sizeB = input.size(0)
+        dimH += 1
+
+    sizeD = input.size(dimH - 1)
+    osizeH, osizeW = output_size
+
+    if input.ndim == 3:
+        out_shape = (sizeD, osizeH, osizeW)
+        out = input.new_empty(out_shape)
+        indices = input.new_empty(out_shape, dtype=torch.int64)
+        return out, indices
+    else:
+        out_shape = (sizeB, sizeD, osizeH, osizeW)  # type: ignore[assignment]
+        memory_format = utils.suggest_memory_format(input)
+        out = input.new_empty(out_shape).to(memory_format=memory_format)
+        indices = input.new_empty(out_shape, dtype=torch.int64).to(
+            memory_format=memory_format
+        )
+        return out, indices
+
+
+@register_meta(aten.adaptive_max_pool2d_backward)
+@out_wrapper("grad_input")
+def meta_adaptive_max_pool2d_backward(grad_output, input, indices):
+    ndim = grad_output.ndim
+    torch._check(
+        ndim in (3, 4),
+        lambda: f"adaptive_max_pooling2d_backward(): Expected 3D or 4D grad_output, but got: {grad_output.shape}",
+    )
+
+    _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool2d_backward")
+
+    torch._check(
+        input.dtype == grad_output.dtype,
+        lambda: f"expected dtype {input.dtype} for `grad_output` but got dtype {grad_output.dtype}",
+    )
+
+    memory_format = utils.suggest_memory_format(input)
+    return input.new_empty(input.shape).to(memory_format=memory_format)
+
+
+@register_meta(aten.adaptive_max_pool3d)
+@out_wrapper("out", "indices")
+def meta_adaptive_max_pool3d(input, output_size):
+    ndim = input.ndim
+    torch._check(
+        ndim in (4, 5),
+        lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got: {input.shape}",
+    )
+    for i in range(1, ndim):
+        torch._check(
+            input.size(i) > 0,
+            lambda: (
+                f"adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, "
+                f"but input has sizes {input.shape} with dimension {i} being empty"
+            ),
+        )
+
+    torch._check(
+        len(output_size) == 3,
+        lambda: "adaptive_max_pool3d(): internal error: output_size.size() must be 3",
+    )
+
+    dimD = 0
+    sizeB = 1
+    sizeD = 0
+
+    if ndim == 5:
+        sizeB = input.size(0)
+        dimD += 1
+
+    sizeD = input.size(dimD)
+    osizeT, osizeH, osizeW = output_size
+
+    if ndim == 4:
+        out_shape = (sizeD, osizeT, osizeH, osizeW)
+    else:
+        out_shape = (sizeB, sizeD, osizeT, osizeH, osizeW)  # type: ignore[assignment]
+
+    out = input.new_empty(out_shape)
+    indices = input.new_empty(out_shape, dtype=torch.int64)
+
+    return out, indices
+
+
+@register_meta(aten.adaptive_max_pool3d_backward)
+@out_wrapper("grad_input")
+def meta_adaptive_max_pool3d_backward(grad_output, input, indices):
+    _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool3d_backward")
+    return input.new_empty(input.shape)
+
+
+@register_meta(aten.repeat_interleave.Tensor)
+def meta_repeat_interleave_Tensor(repeats, output_size=None):
+    if output_size is None:
+        raise RuntimeError("cannot repeat_interleave a meta tensor without output_size")
+    return repeats.new_empty(output_size)
+
+
+@register_meta([aten.complex.default, aten.complex.out])
+@out_wrapper()
+def meta_complex(real, imag):
+    assert real.dtype.is_floating_point
+    assert imag.dtype.is_floating_point
+    out_shape = _broadcast_shapes(real.shape, imag.shape)
+    return real.new_empty(out_shape, dtype=corresponding_complex_dtype(real.dtype))
+
+
+@register_meta([aten.nonzero_static.default, aten.nonzero_static.out])
+@out_wrapper()
+def nonzero_static(self, *, size, fill_value: int = -1):
+    return self.new_empty((size, self.dim()), dtype=torch.long)
+
+
+@register_meta([torch.ops.aten.nonzero.default, torch.ops.aten.nonzero.out])
+@out_wrapper()
+def nonzero(self):
+    torch._check_not_implemented(
+        exp_config.meta_nonzero_assume_all_nonzero,
+        lambda: "The register_meta function for torch.nonzero() raises unimplemented by default, "
+        "as a correct data-independent implementation does not exist. This implementation "
+        "returns a fake value, assuming all elements of the tensor are non-zero. "
+        "To enable this registration, please set "
+        "'torch.fx.experimental._config.meta_nonzero_assume_all_nonzero' to True.",
+    )
+    return torch.empty_strided(
+        (self.numel(), self.dim()),
+        (1, self.numel()),
+        dtype=torch.long,
+        device=self.device,
+    )
+
+
+@register_meta([aten.index.Tensor, aten._unsafe_index.Tensor])
+def meta_index_Tensor(self, indices):
+    torch._check(bool(indices), lambda: "at least one index must be provided")
+    # aten::index is the internal advanced indexing implementation
+    # checkIndexTensorTypes and expandTensors
+    result: list[Optional[Tensor]] = []
+    for i, index in enumerate(indices):
+        if index is not None:
+            torch._check(
+                index.dtype in [torch.long, torch.int, torch.int8, torch.bool],
+                lambda: "tensors used as indices must be long, int, byte or bool tensors",
+            )
+            if index.dtype in [torch.int8, torch.bool]:
+                nonzero = index.nonzero()
+                k = len(result)
+                torch._check_index(
+                    k + index.ndim <= self.ndim,
+                    lambda: f"too many indices for tensor of dimension {self.ndim}",
+                )
+                for j in range(index.ndim):
+                    torch._check_index(
+                        index.shape[j] == self.shape[k + j],
+                        lambda: f"The shape of the mask {index.shape} at index {i} "
+                        f"does not match the shape of the indexed tensor {self.shape} at index {k + j}",
+                    )
+                    result.append(nonzero.select(1, j))
+            else:
+                result.append(index)
+        else:
+            result.append(index)
+    indices = result
+    torch._check(
+        len(indices) <= self.ndim,
+        lambda: f"too many indices for tensor of dimension {self.ndim} (got {len(indices)})",
+    )
+    # expand_outplace
+    import torch._refs as refs  # avoid import cycle in mypy
+
+    indices = list(refs._maybe_broadcast(*indices))
+    # add missing null tensors
+    while len(indices) < self.ndim:
+        indices.append(None)
+
+    # hasContiguousSubspace
+    #   true if all non-null tensors are adjacent
+    # See:
+    # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing
+    # https://stackoverflow.com/questions/53841497/why-does-numpy-mixed-basic-advanced-indexing-depend-on-slice-adjacency
+    state = 0
+    has_contiguous_subspace = False
+    for index in indices:
+        if state == 0:
+            if index is not None:
+                state = 1
+        elif state == 1:
+            if index is None:
+                state = 2
+        else:
+            if index is not None:
+                break
+    else:
+        has_contiguous_subspace = True
+
+    # transposeToFront
+    # This is the logic that causes the newly inserted dimensions to show up
+    # at the beginning of the tensor, if they're not contiguous
+    if not has_contiguous_subspace:
+        dims = []
+        transposed_indices = []
+        for i, index in enumerate(indices):
+            if index is not None:
+                dims.append(i)
+                transposed_indices.append(index)
+        for i, index in enumerate(indices):
+            if index is None:
+                dims.append(i)
+                transposed_indices.append(index)
+        self = self.permute(dims)
+        indices = transposed_indices
+
+    # AdvancedIndex::AdvancedIndex
+    # Now we can assume the indices have contiguous subspace
+    # This is simplified from AdvancedIndex which goes to more effort
+    # to put the input and indices in a form so that TensorIterator can
+    # take them.  If we write a ref for this, probably that logic should
+    # get implemented
+    before_shape: list[int] = []
+    after_shape: list[int] = []
+    replacement_shape: list[int] = []
+    for dim, index in enumerate(indices):
+        if index is None:
+            if replacement_shape:
+                after_shape.append(self.shape[dim])
+            else:
+                before_shape.append(self.shape[dim])
+        else:
+            replacement_shape = list(index.shape)
+
+    def _restride_src(self):
+        """
+        This follows restride_src in TensorAdvancedIndexing.cpp
+        """
+        shape = before_shape + replacement_shape + after_shape
+        strides = list(self.stride())
+        strides[len(before_shape) : len(self.shape) - len(after_shape)] = [0] * len(
+            replacement_shape
+        )
+        return self.as_strided(shape, strides)
+
+    out = self.new_empty(before_shape + replacement_shape + after_shape)
+    from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
+
+    if guard_size_oblivious(self.numel() == 0):
+        # No need to worry about the output strides if self is empty.
+        return out
+
+    # Try to follow eager to decide the output stride based on self.
+    # Note that perm here is the reverse of the 'perm_' decided by
+    # TensorIteratorBase::reorder_dimensions
+    restrided_self = _restride_src(self)
+    perm = utils.compute_elementwise_output_logical_to_physical_perm(restrided_self)
+
+    # Follow TensorIteratorBase::allocate_or_resize_outputs
+    if list(perm) != list(range(len(perm))):
+        perm_shape = utils.apply_perm(out.shape, perm)
+        new_stride = utils.make_contiguous_strides_for(perm_shape)
+        new_stride = utils.apply_perm(new_stride, utils.invert_perm(perm))
+        out = out.as_strided(out.size(), new_stride)
+    return out
+
+
+@register_meta([aten.convolution_backward.default])
+def meta_convolution_backward(
+    grad_output_,
+    input_,
+    weight_,
+    bias_sizes_opt,
+    stride,
+    padding,
+    dilation,
+    transposed,
+    output_padding,
+    groups,
+    output_mask,
+):
+    # High level logic taken from slow_conv3d_backward_cpu which should
+    # be representative of all convolution_backward impls
+    backend_grad_input = None
+    backend_grad_weight = None
+    backend_grad_bias = None
+
+    if output_mask[0]:
+        backend_grad_input = grad_output_.new_empty(input_.size())
+    if output_mask[1]:
+        backend_grad_weight = grad_output_.new_empty(weight_.size())
+    if output_mask[2]:
+        backend_grad_bias = grad_output_.new_empty(bias_sizes_opt)
+
+    return (backend_grad_input, backend_grad_weight, backend_grad_bias)
+
+
+@register_meta([aten.addbmm.default, aten.addbmm.out])
+@out_wrapper()
+def meta_addbmm(self, batch1, batch2, *, beta=1, alpha=1):
+    dim1 = batch1.size(1)
+    dim2 = batch2.size(2)
+    self = self.expand((dim1, dim2))
+    torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
+    torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
+    torch._check(
+        batch1.size(0) == batch2.size(0),
+        lambda: f"batch1 and batch2 must have same number of batches, got {batch1.size(0)} and {batch2.size(0)}",
+    )
+    torch._check(
+        batch1.size(2) == batch2.size(1),
+        lambda: (
+            f"Incompatible matrix sizes for bmm ({batch1.size(1)}x{batch1.size(2)} "
+            f"and {batch2.size(1)}x{batch2.size(2)})"
+        ),
+    )
+    torch._check(
+        self.size(0) == dim1 and self.size(1) == dim2,
+        lambda: "self tensor does not match matmul output shape",
+    )
+    return self.new_empty(self.size())
+
+
+@register_meta([aten._fused_adam_.default, aten._fused_adamw_.default])
+def meta__fused_adam_(
+    self,
+    grads,
+    exp_avgs,
+    exp_avg_sqs,
+    max_exp_avg_sqs,
+    state_steps,
+    *,
+    lr,
+    beta1,
+    beta2,
+    weight_decay,
+    eps,
+    amsgrad,
+    maximize,
+    grad_scale=None,
+    found_inf=None,
+):
+    for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]:
+        torch._check(
+            isinstance(l, list),
+            lambda: f"exponent must be a tensor list but got {type(l)}",
+        )
+
+
+@register_meta([aten._fused_adam.default])
+def meta__fused_adam(
+    self,
+    grads,
+    exp_avgs,
+    exp_avg_sqs,
+    max_exp_avg_sqs,
+    state_steps,
+    *,
+    lr,
+    beta1,
+    beta2,
+    weight_decay,
+    eps,
+    amsgrad,
+    maximize,
+    grad_scale=None,
+    found_inf=None,
+):
+    for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]:
+        torch._check(
+            isinstance(l, list),
+            lambda: f"exponent must be a tensor list but got {type(l)}",
+        )
+
+    def empty_like_list(tensor_list):
+        return [torch.empty_like(t) for t in tensor_list]
+
+    return (
+        empty_like_list(self),
+        empty_like_list(grads),
+        empty_like_list(exp_avgs),
+        empty_like_list(exp_avg_sqs),
+        empty_like_list(max_exp_avg_sqs),
+    )
+
+
+@register_meta([aten._int_mm])
+@out_wrapper()
+def meta__int_mm(a, b):
+    torch._check(a.dim() == 2, lambda: "a must be a 2D tensor")
+    torch._check(b.dim() == 2, lambda: "b must be a 2D tensor")
+    torch._check(
+        a.dtype is torch.int8,
+        lambda: f"expected self to be int8, got {a.dtype}",
+    )
+    torch._check(
+        b.dtype is torch.int8,
+        lambda: f"expected mat2 to be int8, got {b.dtype}",
+    )
+    torch._check(
+        a.size(1) == b.size(0),
+        lambda: (
+            f"Incompatible matrix sizes for _int_mm ({a.size(0)}x{a.size(1)} "
+            f"and {b.size(0)}x{b.size(1)})"
+        ),
+    )
+    return a.new_empty((a.size(0), b.size(1)), dtype=torch.int32)
+
+
+@register_meta([aten._convert_weight_to_int4pack])
+def meta__convert_weight_to_int4pack(w, inner_k_tiles):
+    torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
+    torch._check(
+        w.dtype is torch.uint8,
+        lambda: f"expected w to be uint8, got {w.dtype}",
+    )
+    n = w.size(0)
+    k = w.size(1) * 2  # w is [n][k / 2] uint8
+    return w.new_empty(
+        (
+            n // 8,
+            k // (inner_k_tiles * 16),
+            32,
+            inner_k_tiles // 2,
+        ),
+        dtype=torch.int32,
+    )
+
+
+@register_meta([aten._convert_weight_to_int4pack_for_cpu])
+def meta__convert_weight_to_int4pack_for_cpu(w, inner_k_tiles):
+    torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
+    torch._check(
+        w.dtype is torch.int32,
+        lambda: f"expected w to be int32, got {w.dtype}",
+    )
+    n = w.size(0)
+    k = w.size(1)  # w is [n][k] int32
+    return w.new_empty(
+        (n, k // 2),
+        dtype=torch.uint8,
+    )
+
+
+@register_meta([aten._weight_int4pack_mm])
+def meta__weight_int4pack_mm(x, w, q_group_size, q_scale_and_zeros):
+    torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
+    torch._check(w.dim() == 4, lambda: "w must be a 4D tensor")
+    torch._check(
+        x.dtype in [torch.float32, torch.float16, torch.bfloat16],
+        lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
+    )
+    torch._check(
+        w.dtype is torch.int32,
+        lambda: f"expected w to be int32, got {w.dtype}",
+    )
+    return x.new_empty(x.size(0), w.size(0) * 8, dtype=x.dtype)
+
+
+@register_meta([aten._weight_int4pack_mm_for_cpu])
+def meta__weight_int4pack_mm_for_cpu(x, w, q_group_size, q_scale_and_zeros):
+    torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
+    torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
+    torch._check(
+        x.dtype in [torch.float32, torch.float16, torch.bfloat16],
+        lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
+    )
+    torch._check(
+        w.dtype is torch.uint8,
+        lambda: f"expected w to be uint8, got {w.dtype}",
+    )
+    return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
+
+
+def kai_roundup(a: int, b: int) -> int:
+    return ((a + b - 1) // b) * b
+
+
+def get_kai_packed_weight_size(n_bits, N, K, groupsize):
+    if n_bits == 4:
+        if groupsize == K:  # channelwise
+            # dotprod params only [1x8x32_neon_dotprod]
+            kai_nr = 8
+            kai_kr = 16
+            kai_sr = 2
+            kai_num_bytes_sum_rhs = 4  # sizeof(int32_t)
+            kai_num_bytes_multiplier_rhs = 4  # sizeof(float)
+            kai_num_bytes_bias = 4  # sizeof(float)
+
+            def kai_k_roundedup(k, kr, sr):
+                # Since we pack a float and int32 value at the end of the row,
+                # we must make sure that k is a multiple of 4 for alignment
+                kr_sr_roundedup4 = kai_roundup(kr * sr, 4)
+                return kai_roundup(k, kr_sr_roundedup4)
+
+            def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
+                k, nr, kr, sr
+            ):
+                k_internal = kai_k_roundedup(k, kr, sr)
+
+                assert (k_internal % 2) == 0, "k_internal must be even"
+
+                return nr * (
+                    (k_internal // 2)
+                    + kai_num_bytes_multiplier_rhs
+                    + kai_num_bytes_sum_rhs
+                    + kai_num_bytes_bias
+                )
+
+            def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
+                n, k, nr, kr, sr
+            ):
+                num_rows = kai_roundup(n, nr) // nr
+
+                return (
+                    num_rows
+                    * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
+                        k, nr, kr, sr
+                    )
+                )
+
+            return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
+                N, K, kai_nr, kai_kr, kai_sr
+            )
+        elif groupsize % 32 == 0 and K % groupsize == 0:  # groupwise
+            kai_nr = 8
+            kai_kr = 16
+            kai_sr = 2
+            kai_num_bytes_sum_rhs = 4
+            kai_num_bytes_bias = 4
+            kai_nr_multiple_of = 4
+            kai_bl_multiple_of = 32
+
+            def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
+                n, k, nr, kr, sr, bl
+            ):
+                assert (bl % kr) == 0
+                assert (nr % kai_nr_multiple_of) == 0
+                assert (bl % kai_bl_multiple_of) == 0
+
+                num_rows = kai_roundup(n, nr) // nr
+
+                return (
+                    num_rows
+                    * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
+                        k, nr, kr, sr, bl
+                    )
+                )
+
+            def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
+                k, nr, kr, sr, bl
+            ):
+                assert (bl % kr) == 0
+                assert (nr % kai_nr_multiple_of) == 0
+                assert (bl % kai_bl_multiple_of) == 0
+
+                # kr and sr are unused in the calculation
+                num_bytes_multiplier_rhs = kai_get_bf16_datatype_size_in_bytes()
+                num_blocks_per_row = kai_num_blocks_per_row(k, bl)
+                num_bytes_per_block = kai_num_bytes_per_block(
+                    bl, num_bytes_multiplier_rhs
+                )
+
+                return nr * (
+                    (num_bytes_per_block * num_blocks_per_row)
+                    + kai_num_bytes_sum_rhs
+                    + kai_num_bytes_bias
+                )
+
+            # This funtion retuns size of these datatypes stored as enum. We modify it to just return bf16 datatype
+            # https://gitlab.arm.com/kleidi/kleidiai/-/blob/main/kai/kai_common.h?ref_type=heads#L55
+            def kai_get_bf16_datatype_size_in_bytes():
+                return 2  # 2 bytes
+
+            def kai_num_blocks_per_row(k, bl):
+                assert (bl % kai_bl_multiple_of) == 0
+                return kai_roundup(k, bl) // bl
+
+            def kai_num_bytes_per_block(bl, num_bytes_multiplier_rhs):
+                assert (bl % kai_bl_multiple_of) == 0
+                return (bl // 2) + num_bytes_multiplier_rhs
+
+            return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
+                N, K, kai_nr, kai_kr, kai_sr, groupsize
+            )
+
+
+@register_meta([aten._dyn_quant_pack_4bit_weight])
+def meta__dyn_quant_pack_4bit_weight(
+    weights, scales_zeros, bias: Optional[Tensor], block_size, in_features, out_features
+):
+    torch._check(
+        weights.dtype is torch.uint8,
+        lambda: f"expected w to be uint8, got {weights.dtype}",
+    )
+    if torch.backends.kleidiai.is_available() and (
+        (block_size == in_features and scales_zeros.dtype == torch.float)
+        or (
+            block_size < in_features
+            and block_size % 32 == 0
+            and in_features % block_size == 0
+            and scales_zeros.dtype == torch.bfloat16
+        )
+    ):
+        packed_weight_size = get_kai_packed_weight_size(
+            4, out_features, in_features, block_size
+        )
+        return weights.new_empty(int(packed_weight_size), dtype=torch.uint8)
+    packed_weight_size = weights.numel() + scales_zeros.numel()
+    return weights.new_empty(packed_weight_size, dtype=torch.float)
+
+
+@register_meta([aten._dyn_quant_matmul_4bit])
+def meta__dyn_quant_matmul_4bit(
+    inp,
+    packed_weights,
+    block_size,
+    in_features,
+    out_features,
+):
+    torch._check(inp.dim() == 2, lambda: "input must be a 2D tensor")
+    torch._check(
+        inp.dtype in [torch.float32],
+        lambda: f"expected input to be f32, got {inp.dtype}",
+    )
+    M = inp.size(0)
+    return inp.new_empty(M, out_features, dtype=inp.dtype)
+
+
+@register_meta([aten._weight_int8pack_mm])
+def meta__weight_int8pack_mm(x, w, q_scales):
+    torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
+    torch._check(
+        x.dtype in [torch.float32, torch.float16, torch.bfloat16],
+        lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
+    )
+    torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
+    torch._check(
+        w.dtype is torch.int8,
+        lambda: f"expected w to be int8, got {w.dtype}",
+    )
+    return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
+
+
+@register_meta(aten._cdist_forward.default)
+def meta_cdist_forward(x1, x2, p, compute_mode):
+    torch._check(
+        x1.dim() >= 2,
+        lambda: f"cdist only supports at least 2D tensors, X1 got: {x1.dim()}D",
+    )
+    torch._check(
+        x2.dim() >= 2,
+        lambda: f"cdist only supports at least 2D tensors, X2 got: {x2.dim()}D",
+    )
+    torch._check(
+        x1.size(-1) == x2.size(-1),
+        lambda: f"X1 and X2 must have the same number of columns. X1: {x1.size(-1)} X2: {x2.size(-1)}",
+    )
+    torch._check(
+        utils.is_float_dtype(x1.dtype),
+        lambda: "cdist only supports floating-point dtypes, X1 got: {x1.dtype}",
+    )
+    torch._check(
+        utils.is_float_dtype(x2.dtype),
+        lambda: "cdist only supports floating-point dtypes, X2 got: {x2.dtype}",
+    )
+    torch._check(p >= 0, lambda: "cdist only supports non-negative p values")
+    torch._check(
+        compute_mode in (None, 1, 2),
+        lambda: f"possible modes: None, 1, 2, but was: {compute_mode}",
+    )
+    r1 = x1.size(-2)
+    r2 = x2.size(-2)
+    batch_tensor1 = x1.shape[:-2]
+    batch_tensor2 = x2.shape[:-2]
+    output_shape = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2))
+    output_shape.extend([r1, r2])
+    return x1.new_empty(output_shape)
+
+
+@register_meta(aten._cdist_backward)
+@out_wrapper()
+def meta_cdist_backward(grad, x1, x2, p, cdist):
+    c1 = x1.shape[-1]
+    r1 = x1.shape[-2]
+    r2 = x2.shape[-2]
+    batch_tensor1 = x1.shape[:-2]
+    batch_tensor2 = x2.shape[:-2]
+    expand_batch_portion = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2))
+    tensor1_expand_size = expand_batch_portion.copy()
+    tensor1_expand_size.extend([r1, c1])
+    batch_product = math.prod(expand_batch_portion)
+    if r1 == 0 or r2 == 0 or c1 == 0 or batch_product == 0:
+        return torch.zeros_like(x1)
+    if tensor1_expand_size != list(x1.shape):
+        x1 = x1.expand(tensor1_expand_size)
+    return torch.empty_like(x1, memory_format=torch.contiguous_format)
+
+
+# NB: This meta function accepts non-meta arguments!  When this behavior
+# was originally introduced this was accidental, but it is now load bearing
+# as people are using this so that they can conveniently test code involving
+# embeddings (feeding CPU tensor inputs with meta device EmbeddingBag module)
+@register_meta(aten._embedding_bag.default)
+def meta_embedding_bag(
+    weight,
+    indices,
+    offsets,
+    scale_grad_by_freq=False,
+    mode=0,
+    sparse=False,
+    per_sample_weights=None,
+    include_last_offset=False,
+    padding_idx=-1,
+):
+    torch._check(
+        indices.dtype in (torch.long, torch.int),
+        lambda: f"expected indices to be long or int, got {indices.dtype}",
+    )
+    torch._check(
+        offsets.dtype in (torch.long, torch.int),
+        lambda: f"expected offsets to be long or int, got {offsets.dtype}",
+    )
+    torch._check(
+        utils.is_float_dtype(weight.dtype),
+        lambda: f"expected weight to be floating point type, got {weight.dtype}",
+    )
+
+    num_bags = offsets.size(0)
+    if include_last_offset:
+        torch._check(
+            num_bags >= 1,
+            lambda: "include_last_offset: numBags should be at least 1",
+        )
+        num_bags -= 1
+
+    output = weight.new_empty(num_bags, weight.size(1))
+
+    if per_sample_weights is not None:
+        torch._check(
+            mode == MODE_SUM,
+            lambda: "embedding_bag: per_sample_weights only supported with mode='sum'",
+        )
+        torch._check(
+            per_sample_weights.ndim == 1,
+            lambda: f"expected per_sample_weights to be 1D tensor, got {per_sample_weights.ndim}D",
+        )
+        torch._check(
+            per_sample_weights.numel() == indices.numel(),
+            lambda: (
+                f"expected per_sample_weights.numel() ({per_sample_weights.numel()} "
+                f"to be the same as indices.numel() ({indices.numel()})"
+            ),
+        )
+
+    def is_fast_path_index_select_scale(src, scale, output, padding_idx):
+        return (
+            is_fast_path_index_select(src, output, padding_idx) and scale.stride(0) == 1
+        )
+
+    def is_fast_path_index_select(src, output, padding_idx):
+        return (
+            (src.dtype == torch.float or src.dtype == torch.half)
+            and src.stride(1) == 1
+            and output.stride(1) == 1
+            and padding_idx < 0
+        )
+
+    def is_fast_path(src, scale, output, padding_idx):
+        if scale is not None:
+            return is_fast_path_index_select_scale(src, scale, output, padding_idx)
+        else:
+            return is_fast_path_index_select(src, output, padding_idx)
+
+    if device_hint(offsets) != "cpu":
+        offset2bag = indices.new_empty(indices.size(0))
+        bag_size = indices.new_empty(offsets.size())
+        if mode == MODE_MAX:
+            max_indices = indices.new_empty(num_bags, weight.size(1))
+        else:
+            max_indices = indices.new_empty(0)
+    else:
+        fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx)
+        if mode in (MODE_MEAN, MODE_MAX) or not fast_path_sum:
+            offset2bag = offsets.new_empty(indices.size(0))
+        else:
+            offset2bag = offsets.new_empty(0)
+        bag_size = offsets.new_empty(num_bags)
+        # This part of the logic comes from make_max_indices_out in EmbeddingBag.cpp
+        numBags = offsets.shape[0]
+        if mode == MODE_MAX:
+            if include_last_offset:
+                torch._check(
+                    numBags >= 1,
+                    lambda: "include_last_offset: numBags should be at least 1",
+                )
+                numBags -= 1
+            max_indices = offsets.new_empty(numBags, weight.shape[1])
+        else:
+            max_indices = offsets.new_empty(bag_size.size())
+    return output, offset2bag, bag_size, max_indices
+
+
+@register_meta(aten._embedding_bag_forward_only.default)
+def meta_embedding_bag_forward_only(weight, indices, offsets, *args):
+    output, offset2bag, bag_size, max_indices = meta_embedding_bag(
+        weight, indices, offsets, *args
+    )
+    if device_hint(offsets) == "cpu":
+        bag_size = offsets.new_empty(offsets.size())
+    return output, offset2bag, bag_size, max_indices
+
+
+def _get_reduction_dtype(input, dtype, promote_int_to_long=True):
+    # if specified, dtype takes precedence
+    if dtype:
+        return dtype
+
+    if input.dtype.is_floating_point or input.dtype.is_complex:
+        return input.dtype
+    elif promote_int_to_long:
+        return torch.long
+
+    return input.dtype
+
+
+@register_meta([aten.nansum.default, aten.nansum.out])
+@out_wrapper()
+def meta_nansum(input, dims=None, keepdim=False, *, dtype=None):
+    output_dtype = _get_reduction_dtype(input, dtype, promote_int_to_long=True)
+    dims = utils.reduction_dims(input.shape, dims)
+    output_shape = _compute_reduction_shape(input, dims, keepdim)
+    return input.new_empty(output_shape, dtype=output_dtype)
+
+
+@register_meta([aten.median.default, aten.nanmedian.default])
+def meta_median(input):
+    output_shape = utils.compute_reduction_output_shape(
+        input.shape, tuple(range(input.dim()))
+    )
+    return input.new_empty(output_shape)
+
+
+@register_meta(
+    [
+        aten.median.dim,
+        aten.median.dim_values,
+        aten.nanmedian.dim,
+        aten.nanmedian.dim_values,
+        aten.mode.default,
+        aten.mode.values,
+    ]
+)
+@out_wrapper("values", "indices")
+def meta_median_mode_dim(input, dim=-1, keepdim=False):
+    if device_hint(input) == "cuda":
+        utils.alert_not_deterministic("median CUDA with indices output")
+    dim = utils.reduction_dims(input.shape, (dim,))
+    output_shape = _compute_reduction_shape(input, dim, keepdim)
+    return (
+        input.new_empty(output_shape),
+        input.new_empty(output_shape, dtype=torch.long),
+    )
+
+
+@register_meta(aten.logical_not_.default)
+def meta_logical_not_(self):
+    return self
+
+
+@register_meta(aten.repeat.default)
+def meta_repeat(self, repeats):
+    torch._check(
+        len(repeats) >= self.dim(),
+        lambda: "Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor",
+    )
+    # Add new leading dimensions to the tensor if the
+    # number of target dimensions is larger than the
+    # number of source dimensions.
+    num_new_dimensions = len(repeats) - self.dim()
+    padded_size = (1,) * num_new_dimensions + tuple(self.shape)
+    target_size = [padded_size[i] * repeats[i] for i in range(len(repeats))]
+    return self.new_empty(target_size)
+
+
+@register_meta(aten.zero_.default)
+def meta_zero_(self):
+    return self
+
+
+@register_meta(
+    [
+        aten.mul_.Scalar,
+        aten.div_.Scalar,
+        aten.mul_.Tensor,
+        aten.div_.Tensor,
+        aten.logical_and_.default,
+        aten.logical_or_.default,
+        aten.logical_xor_.default,
+    ],
+)
+def meta_binop_inplace(self, other):
+    if isinstance(other, torch.Tensor):
+        check_inplace_broadcast(self.shape, other.shape)
+    return self
+
+
+@register_meta(
+    [
+        aten.add_.Scalar,
+        aten.sub_.Scalar,
+        aten.add_.Tensor,
+        aten.sub_.Tensor,
+    ],
+)
+def meta_binop_inplace_alpha(self, other, alpha=1):
+    """
+    Some checks for inplace ops.
+    Checks for promotion rules for some dtypes.
+    int.add/sub_(float) and bool.add/sub_(others) are rejected.
+    Promoting in these in-place operations would require reallocating
+    and copying over elements, hence not allowed.
+    Checks for alpha param.
+    """
+
+    def is_integeric(arg):
+        if isinstance(arg, TensorLike):
+            return utils.is_integer_dtype(arg.dtype)
+        else:
+            return isinstance(arg, IntLike)
+
+    def is_floatic(arg):
+        if isinstance(arg, TensorLike):
+            return utils.is_float_dtype(arg.dtype)
+        else:
+            return isinstance(arg, FloatLike)
+
+    def is_booleanic(arg):
+        if isinstance(arg, TensorLike):
+            return utils.is_boolean_dtype(arg.dtype)
+        else:
+            return isinstance(arg, BoolLike)
+
+    # Do not allow int+float->int in-place
+    if is_integeric(self) and is_floatic(other):
+        raise RuntimeError(
+            "Promotion of int.add/sub_(float) in in-place ops are not possible due to element size change."
+        )
+
+    # Do not allow bool+other->bool in-place
+    if is_booleanic(self) and not is_booleanic(other):
+        raise RuntimeError(
+            "Promotion of book.add/sub_(others) in in-place ops are not possible due to element size change."
+        )
+
+    if isinstance(other, torch.Tensor):
+        check_inplace_broadcast(self.shape, other.shape)
+    return self
+
+
+@register_meta([aten.round.default, aten.round.decimals])
+def meta_round(self, **kwargs):
+    return elementwise_meta(
+        self, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+def shift_dtype_check(fn_name, self, val):
+    torch._check(
+        utils.is_integer_dtype(self.dtype),
+        lambda: f"{fn_name}: Expected input tensor to have an integral dtype. Got {self.dtype}",
+    )
+    if isinstance(val, torch.Tensor):
+        torch._check(
+            utils.is_integer_dtype(val.dtype),
+            lambda: f"{fn_name}: Expected shift value to have an integral dtype. Got {val.dtype}",
+        )
+    else:
+        torch._check(
+            isinstance(val, IntLike),
+            lambda: f"{fn_name}: Expected shift value to be an int. Got {val}",
+        )
+
+
+@register_meta([aten.__rshift__.Tensor, aten.__rshift__.Scalar])
+def meta_rshifts(self, other):
+    shift_dtype_check("rshift", self, other)
+    return elementwise_meta(
+        self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+@register_meta([aten.__lshift__.Tensor, aten.__lshift__.Scalar])
+def meta_lshifts(self, other):
+    shift_dtype_check("lshift", self, other)
+    return elementwise_meta(
+        self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+@register_meta(aten.zero.default)
+def meta_zero(self):
+    return self.new_empty(self.shape)
+
+
+@register_meta([aten.fill_.Tensor, aten.fill_.Scalar])
+def meta_fill_(self, val):
+    return self
+
+
+@register_meta([aten.fill.Tensor, aten.fill.Scalar])
+def meta_fill(self, val):
+    return torch.empty_like(self)
+
+
+@register_meta(aten.relu_.default)
+def meta_relu_(self):
+    return self
+
+
+@register_meta(aten._add_relu.Tensor)
+@out_wrapper()
+def meta__add_relu(self, other, alpha=1) -> Tensor:
+    return elementwise_meta(
+        self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+@register_meta([aten.rrelu_with_noise])
+@out_wrapper()
+def meta_rrelu_with_noise(
+    self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None
+):
+    return torch.empty_like(self)
+
+
+@register_meta([aten.rrelu_with_noise_functional])
+def meta_rrelu_with_noise_functional(
+    self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None
+):
+    return torch.empty_like(self), torch.empty_like(noise)
+
+
+@register_meta([aten.rrelu_with_noise_])
+def meta_rrelu_with_noise_(
+    self, lower=0.125, upper=0.3333333333333333, training=False, generator=None
+):
+    return self
+
+
+@register_meta([aten.index_put.default, aten._unsafe_index_put.default])
+def meta_index_put(self, indices, values, accumulate=False):
+    return torch.empty_like(self)
+
+
+@register_meta(aten.masked_fill_.Scalar)
+def meta_masked_fill_(self, mask, value):
+    check_inplace_broadcast(self.shape, mask.shape)
+    return self
+
+
+@register_meta(aten._masked_scale.default)
+def meta__masked_scale(self, mask, scale):
+    masked_scale = self.new_empty(self.size()).to(
+        memory_format=utils.suggest_memory_format(self)
+    )
+    return masked_scale
+
+
+@register_meta(aten.masked_scatter_)
+def meta_masked_scatter_(self, mask, source):
+    torch._check(
+        mask.dtype in (torch.bool, torch.uint8), lambda: "Mask must be bool or uint8"
+    )
+    torch._check(
+        self.dtype == source.dtype,
+        lambda: "masked_scatter: expected self and source to have same "
+        f"dtypes but got {self.dtype} and {source.dtype}",
+    )
+    return self
+
+
+@register_meta(aten.masked_scatter)
+@out_wrapper()
+def meta_masked_scatter(self, mask, source):
+    self, mask = _maybe_broadcast(self, mask)
+    output = torch.empty_like(self, memory_format=torch.contiguous_format)
+    return meta_masked_scatter_(output, mask, source)
+
+
+@register_meta(aten.masked_scatter_backward)
+def meta_masked_scatter_backward(self, mask, sizes):
+    return self.new_empty(sizes)
+
+
+@register_meta(aten.index_put_.default)
+def meta_index_put_(self, indices, values, accumulate=False):
+    return self
+
+
+@register_meta(aten.alias.default)
+def meta_alias(self):
+    return self.view(self.shape)
+
+
+def common_meta_baddbmm_bmm(batch1, batch2, is_bmm, self_baddbmm=None):
+    torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
+    torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
+
+    batch1_sizes = batch1.size()
+    batch2_sizes = batch2.size()
+
+    bs = batch1_sizes[0]
+    contraction_size = batch1_sizes[2]
+    res_rows = batch1_sizes[1]
+    res_cols = batch2_sizes[2]
+    output_size = (bs, res_rows, res_cols)
+
+    torch._check(
+        batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size,
+        lambda: f"Expected size for first two dimensions of batch2 tensor to be: [{bs}"
+        f", {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}].",
+    )
+
+    # TODO: handle out
+
+    output = batch2.new_empty(output_size)
+
+    if not is_bmm and self_baddbmm is not None:
+        torch._check(self_baddbmm.dim() == 3, lambda: "self must be a 3D tensor")
+        torch._check(
+            self_baddbmm.size() == output_size,
+            lambda: f"Expected an input tensor shape with shape {output_size} but got shape: {self_baddbmm.size()}",
+        )
+
+    return output
+
+
+@register_meta(aten.bmm.default)
+def meta_bmm(self, mat2):
+    return common_meta_baddbmm_bmm(self, mat2, True)
+
+
+def div_rtn(x, y):
+    q = x // y
+    r = x % y
+    # WARNING: explicit bool conversion here is necessary;
+    # would be fixed by SymBool
+    if r != 0 and (bool(r < 0) != bool(y < 0)):
+        q -= 1
+    return q
+
+
+def pooling_output_shape_pad_lr(
+    inputSize,
+    kernelSize,
+    pad_l,
+    pad_r,
+    stride,
+    dilation,
+    ceil_mode,
+):
+    outputSize = (
+        div_rtn(
+            inputSize
+            + pad_l
+            + pad_r
+            - dilation * (kernelSize - 1)
+            - 1
+            + (stride - 1 if ceil_mode else 0),
+            stride,
+        )
+        + 1
+    )
+    if ceil_mode:
+        if (outputSize - 1) * stride >= inputSize + pad_l:
+            outputSize -= 1
+    return outputSize
+
+
+def pooling_output_shape(inputSize, kernelSize, pad, stride, dilation, ceil_mode):
+    torch._check(stride != 0, lambda: "stride should not be zero")
+    torch._check(pad >= 0, lambda: f"pad must be non-negative, but got pad: {pad}")
+    torch._check(
+        pad <= ((kernelSize - 1) * dilation + 1) // 2,
+        lambda: (
+            f"pad should be at most half of effective kernel size, but got pad={pad}, "
+            f"kernel_size={kernelSize} and dilation={dilation}"
+        ),
+    )
+    return pooling_output_shape_pad_lr(
+        inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode
+    )
+
+
+def pool2d_shape_check(
+    input,
+    kH,
+    kW,
+    dH,
+    dW,
+    padH,
+    padW,
+    dilationH,
+    dilationW,
+    nInputPlane,
+    inputHeight,
+    inputWidth,
+    outputHeight,
+    outputWidth,
+    memory_format,
+):
+    ndim = input.dim()
+    nOutputPlane = nInputPlane
+
+    torch._check(
+        kW > 0 and kH > 0,
+        lambda: "kernel size should be greater than zero, but got kH: {kH}, kW: {kW}",
+    )
+    torch._check(
+        dW > 0 and dH > 0,
+        lambda: "stride should be greater than zero, but got dH: {dH}, dW: {dW}",
+    )
+    torch._check(
+        dilationH > 0 and dilationW > 0,
+        lambda: "dilation should be greater than zero, but got dilationH: {dilationH}, dilationW: {dilationW}",
+    )
+
+    valid_dims = input.size(1) != 0 and input.size(2) != 0
+
+    if memory_format == torch.channels_last:
+        torch._check(
+            ndim == 4 and valid_dims and input.size(3) != 0,
+            lambda: "Expected 4D (batch mode) tensor expected for input with channels_last layout"
+            " with optional 0 dim batch size for input, but got: {input.size()}",
+        )
+    else:
+        torch._check(
+            (ndim == 3 and input.size(0) != 0 and valid_dims)
+            or (ndim == 4 and valid_dims and input.size(3) != 0),
+            lambda: f"Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got: {input.size()}",
+        )
+
+    torch._check(
+        kW // 2 >= padW and kH // 2 >= padH,
+        lambda: "pad should be smaller than or equal to half of kernel size, but got "
+        f"padW = {padW}, padH = {padH}, kW = {kW}, kH = {kH}",
+    )
+
+    torch._check(
+        outputWidth >= 1 and outputHeight >= 1,
+        lambda: f"Given input size: ({nInputPlane}x{inputHeight}x{inputWidth}). "
+        f"Calculated output size: ({nOutputPlane}x{outputHeight}x{outputWidth}). "
+        "Output size is too small",
+    )
+
+
+def pool3d_shape_check(
+    input: Tensor,
+    nslices: int,
+    kT: int,
+    kH: int,
+    kW: int,
+    dT: int,
+    dH: int,
+    dW: int,
+    pT: int,
+    pH: int,
+    pW: int,
+    dilationT: int,
+    dilationH: int,
+    dilationW: int,
+    itime: int,
+    iheight: int,
+    iwidth: int,
+    otime: int,
+    oheight: int,
+    owidth: int,
+    fn_name: str,
+    check_input_size: bool = False,
+):
+    ndim = input.ndim
+
+    torch._check(
+        kT > 0 and kW > 0 and kH > 0,
+        lambda: (
+            f"kernel size should be greater than zero, but got "
+            f"kT: {kT}, kH: {kH}, kW: {kW}"
+        ),
+    )
+    torch._check(
+        dT > 0 and dW > 0 and dH > 0,
+        lambda: (
+            f"stride should be greater than zero, but got dT: {dT}, dH: {dH}, dW: {dW}"
+        ),
+    )
+    torch._check(
+        dilationT > 0 and dilationW > 0 and dilationH > 0,
+        lambda: (
+            f"dilation should be greater than zero, but got "
+            f"dilationT: {dilationT}, dilationH: {dilationH}, dilationW: {dilationW}"
+        ),
+    )
+
+    torch._check(
+        ndim in (4, 5),
+        lambda: f"{fn_name}: Expected 4D or 5D tensor for input, but got: {input.shape}",
+    )
+
+    for i in range(ndim):
+        if ndim == 5 and i == 0:
+            # size of batch-dim can be 0.
+            continue
+        torch._check(
+            input.size(i) > 0,
+            lambda: (
+                f"{fn_name}: Expected input's non-batch dimensions to have positive length,"
+                f" but input has a shape of {input.shape}"
+                f" and non-batch dimension {input.size(i)} has length zero!"
+            ),
+        )
+
+    if check_input_size:  # AveragePool3d
+        torch._check(
+            itime >= kT and iheight >= kH and iwidth >= kW,
+            lambda: (
+                f"input image (T: {itime} H: {iheight} W: {iwidth}) smaller than "
+                f"kernel size (kT: {kT} kH: {kH} kW: {kW})"
+            ),
+        )
+
+    torch._check(
+        kT / 2 >= pT and kW / 2 >= pW and kH / 2 >= pH,
+        lambda: (
+            f"pad should be smaller than or equal to half of kernel size, but got "
+            f"kT: {kT} kW: {kW} kH: {kH} padT: {pT} padW: {pW} padH: {pH}"
+        ),
+    )
+
+    torch._check(
+        otime >= 1 and owidth >= 1 and oheight >= 1,
+        lambda: (
+            f"Given input size: ({nslices}x{itime}x{iheight}x{iwidth}). "
+            f"Calculated output size: ({nslices}x{otime}x{oheight}x{owidth}). "
+            f"Output size is too small"
+        ),
+    )
+
+
+def max_pool3d_backward_shape_check(
+    input,
+    grad_output,
+    indices,
+    nslices,
+    kT,
+    kH,
+    kW,
+    dT,
+    dH,
+    dW,
+    pT,
+    pH,
+    pW,
+    dilationT,
+    dilationH,
+    dilationW,
+    itime,
+    iheight,
+    iwidth,
+    otime,
+    oheight,
+    owidth,
+    fn_name,
+):
+    ndim = input.ndim
+
+    pool3d_shape_check(
+        input,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        pT,
+        pH,
+        pW,
+        dilationT,
+        dilationH,
+        dilationW,
+        itime,
+        iheight,
+        iwidth,
+        otime,
+        oheight,
+        owidth,
+        fn_name,
+    )
+
+    check_dim_size(grad_output, ndim, ndim - 4, nslices)
+    check_dim_size(grad_output, ndim, ndim - 3, otime)
+    check_dim_size(grad_output, ndim, ndim - 2, oheight)
+    check_dim_size(grad_output, ndim, ndim - 1, owidth)
+
+    check_dim_size(indices, ndim, ndim - 4, nslices)
+    check_dim_size(indices, ndim, ndim - 3, otime)
+    check_dim_size(indices, ndim, ndim - 2, oheight)
+    check_dim_size(indices, ndim, ndim - 1, owidth)
+
+
+def avg_pool3d_backward_shape_check(
+    input: Tensor,
+    grad_output: Tensor,
+    nslices: int,
+    kT: int,
+    kH: int,
+    kW: int,
+    dT: int,
+    dH: int,
+    dW: int,
+    pT: int,
+    pH: int,
+    pW: int,
+    itime: int,
+    iheight: int,
+    iwidth: int,
+    otime: int,
+    oheight: int,
+    owidth: int,
+    fn_name: str,
+):
+    ndim = input.ndim
+
+    pool3d_shape_check(
+        input,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        pT,
+        pH,
+        pW,
+        1,
+        1,
+        1,
+        itime,
+        iheight,
+        iwidth,
+        otime,
+        oheight,
+        owidth,
+        fn_name,
+        True,
+    )
+
+    check_dim_size(grad_output, ndim, ndim - 4, nslices)
+    check_dim_size(grad_output, ndim, ndim - 3, otime)
+    check_dim_size(grad_output, ndim, ndim - 2, oheight)
+    check_dim_size(grad_output, ndim, ndim - 1, owidth)
+
+
+def max_pool2d_checks_and_compute_shape(
+    input,
+    kernel_size,
+    stride,
+    padding,
+    dilation,
+    ceil_mode,
+):
+    # Reference: aten/src/ATen/native/DilatedMaxPool2d.cpp
+    def unpack(name, val):
+        torch._check(
+            len(val) in [1, 2],
+            lambda: f"max_pool2d: {name} must either be a single int, or a tuple of two ints",
+        )
+        H = val[0]
+        W = H if len(val) == 1 else val[1]
+        return H, W
+
+    kH, kW = unpack("kernel_size", kernel_size)
+
+    torch._check(
+        len(stride) in [0, 1, 2],
+        lambda: "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
+    )
+    if len(stride) == 0:
+        dH, dW = kH, kW
+    else:
+        dH, dW = unpack("stride", stride)
+
+    padH, padW = unpack("padding", padding)
+    dilationH, dilationW = unpack("dilation", dilation)
+    nInputPlane = input.size(-3)
+    inputHeight = input.size(-2)
+    inputWidth = input.size(-1)
+
+    memory_format = utils.suggest_memory_format(input)
+    if memory_format == torch.channels_last:
+        torch._check(
+            input.dim() == 4,
+            lambda: "non-empty 4D (batch mode) tensor expected for input with channels_last layout",
+        )
+    elif memory_format == torch.contiguous_format:
+        torch._check(
+            input.dim() in [3, 4],
+            lambda: "non-empty 3D or 4D (batch mode) tensor expected for input",
+        )
+    else:
+        torch._check(
+            False,
+            lambda: "Unsupport memory format. Supports only ChannelsLast, Contiguous",
+        )
+
+    outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode)
+    outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode)
+
+    pool2d_shape_check(
+        input,
+        kH,
+        kW,
+        dH,
+        dW,
+        padH,
+        padW,
+        dilationH,
+        dilationW,
+        nInputPlane,
+        inputHeight,
+        inputWidth,
+        outputHeight,
+        outputWidth,
+        memory_format,
+    )
+
+    return nInputPlane, outputHeight, outputWidth
+
+
+@register_meta(aten.max_pool2d_with_indices_backward.default)
+def meta_max_pool2d_with_indices_backward(
+    grad_output,
+    self,
+    kernel_size,
+    stride,
+    padding,
+    dilation,
+    ceil_mode,
+    indices,
+):
+    (
+        nInputPlane,
+        outputHeight,
+        outputWidth,
+    ) = max_pool2d_checks_and_compute_shape(
+        self, kernel_size, stride, padding, dilation, ceil_mode
+    )
+
+    torch._check(
+        self.dtype == grad_output.dtype,
+        lambda: f"Expected dtype {self.dtype} for `gradOutput` but got dtype {grad_output.dtype}",
+    )
+
+    nOutputPlane = nInputPlane
+    ndim = self.ndim
+
+    def _check_dim_size(t):
+        check_dim_size(t, ndim, ndim - 3, nOutputPlane)
+        check_dim_size(t, ndim, ndim - 2, outputHeight)
+        check_dim_size(t, ndim, ndim - 1, outputWidth)
+
+    _check_dim_size(grad_output)
+    _check_dim_size(indices)
+
+    memory_format = utils.suggest_memory_format(self)
+    return torch.empty(
+        self.shape,
+        dtype=self.dtype,
+        device=self.device,
+        memory_format=memory_format,
+    )
+
+
+@register_meta(aten.max_pool2d_with_indices.default)
+def meta_max_pool2d_with_indices(
+    input,
+    kernel_size,
+    stride=(),
+    padding=(0,),
+    dilation=(1,),
+    ceil_mode=False,
+):
+    (
+        nInputPlane,
+        outputHeight,
+        outputWidth,
+    ) = max_pool2d_checks_and_compute_shape(
+        input, kernel_size, stride, padding, dilation, ceil_mode
+    )
+
+    nbatch = input.size(-4) if input.dim() == 4 else 1
+    memory_format = utils.suggest_memory_format(input)
+    if input.dim() == 3:
+        size = [nInputPlane, outputHeight, outputWidth]
+    else:
+        size = [nbatch, nInputPlane, outputHeight, outputWidth]
+    return (
+        torch.empty(
+            size,
+            dtype=input.dtype,
+            device=input.device,
+            memory_format=memory_format,
+        ),
+        torch.empty(
+            size,
+            dtype=torch.int64,
+            device=input.device,
+            memory_format=memory_format,
+        ),
+    )
+
+
+@register_meta(aten.fractional_max_pool2d.default)
+def meta_fractional_max_pool2d(self, kernel_size, output_size, random_samples):
+    torch._check(
+        self.ndim in (3, 4),
+        lambda: f"fractional_max_pool2d: Expected 3D or 4D tensor, but got: {self.ndim}",
+    )
+    ndim = self.ndim
+
+    for d in range(ndim - 3, ndim):
+        torch._check(
+            self.size(d) > 0,
+            f"fractional_max_pool2d: Expected input to have non-zero "
+            f" size for non-batch dimenions, but got {self.size()} with dimension {d} empty",
+        )
+
+    # the check and message are out of sync, but this matches the structured meta
+    torch._check(
+        len(kernel_size) == 2,
+        lambda: "fractional_max_pool2d: kernel_size must"
+        "either be a single int or tuple of Ints",
+    )
+    torch._check(
+        len(output_size) == 2,
+        lambda: "fractional_max_pool2d: output_size must "
+        "either be a single int or tuple of Ints",
+    )
+
+    input_channels = self.size(-3)
+    input_height = self.size(-2)
+    input_width = self.size(-1)
+    if ndim == 4:
+        input_batch = self.size(0)
+    else:
+        input_batch = 1
+
+    torch._check(
+        self.dtype == random_samples.dtype,
+        lambda: "Expect _random_samples to have the same dtype as input",
+    )
+    torch._check(
+        random_samples.ndim == 3,
+        lambda: f"Expect _random samples to have 3 dimensions got, {random_samples.ndim}",
+    )
+
+    n = random_samples.size(0)
+    c = random_samples.size(1)
+    d = random_samples.size(2)
+    torch._check(
+        n >= input_batch,
+        "Expect _random_samples.size(0) no less then input batch size.",
+    )
+    torch._check(
+        c == input_channels,
+        lambda: "Expect _random_samples.size(1) equals to input channel size.",
+    )
+    torch._check(d == 2, lambda: f"Expect _random_samples.size(2) equals to 2 got {d}.")
+
+    torch._check(
+        output_size[0] + kernel_size[0] - 1 <= input_height,
+        lambda: f"fractional_max_pool2d: kernel height {kernel_size[0]} is too large relative to input height {input_height}",
+    )
+    torch._check(
+        output_size[1] + kernel_size[1] - 1 <= input_width,
+        lambda: f"fractional_max_pool2d: kernel width {kernel_size[1]} is too large relative to input width {input_width}",
+    )
+
+    if self.dim() == 4:
+        size = [input_batch, input_channels, output_size[0], output_size[1]]
+    else:
+        size = [input_channels, output_size[0], output_size[1]]
+
+    return (
+        torch.empty(
+            size,
+            dtype=self.dtype,
+            device=self.device,
+        ),
+        torch.empty(
+            size,
+            dtype=torch.int64,
+            device=self.device,
+        ),
+    )
+
+
+@register_meta(aten.max_pool3d_with_indices)
+@out_wrapper("out", "indices")
+def meta_max_pool3d_with_indices(
+    input,
+    kernel_size,
+    stride=(),
+    padding=(0,),
+    dilation=(1,),
+    ceil_mode=False,
+):
+    torch._check(
+        len(kernel_size) in (1, 3),
+        lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints",
+    )
+    kT = kernel_size[0]
+    kH = kT if len(kernel_size) == 1 else kernel_size[1]
+    kW = kT if len(kernel_size) == 1 else kernel_size[2]
+
+    torch._check(
+        not stride or len(stride) in (1, 3),
+        lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints",
+    )
+    dT = kT if not stride else stride[0]
+    dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
+    dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
+
+    torch._check(
+        len(padding) in (1, 3),
+        lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints",
+    )
+    pT = padding[0]
+    pH = pT if len(padding) == 1 else padding[1]
+    pW = pT if len(padding) == 1 else padding[2]
+
+    torch._check(
+        len(dilation) in (1, 3),
+        lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints",
+    )
+    dilationT = dilation[0]
+    dilationH = dilationT if len(dilation) == 1 else dilation[1]
+    dilationW = dilationT if len(dilation) == 1 else dilation[2]
+
+    torch._check(
+        input.ndim in (4, 5),
+        lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
+    )
+
+    nbatch = input.size(-5) if input.ndim == 5 else 1
+    nslices = input.size(-4)
+    itime = input.size(-3)
+    iheight = input.size(-2)
+    iwidth = input.size(-1)
+
+    otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode)
+    oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode)
+    owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode)
+
+    pool3d_shape_check(
+        input,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        pT,
+        pH,
+        pW,
+        dilationT,
+        dilationH,
+        dilationW,
+        itime,
+        iheight,
+        iwidth,
+        otime,
+        oheight,
+        owidth,
+        "max_pool3d_with_indices()",
+    )
+
+    channels_last = (
+        input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d
+    )
+    if input.ndim == 4:
+        input_channels_last_check = input.unsqueeze(0)
+        channels_last = (
+            not input_channels_last_check.is_contiguous()
+        ) and input_channels_last_check.is_contiguous(
+            memory_format=torch.channels_last_3d
+        )
+        out_shape = (nslices, otime, oheight, owidth)
+    else:
+        out_shape = (nbatch, nslices, otime, oheight, owidth)  # type: ignore[assignment]
+
+    out = input.new_empty(out_shape)
+    indices = input.new_empty(out_shape, dtype=torch.int64)
+
+    if channels_last:
+        out = out.to(memory_format=torch.channels_last_3d)
+        indices = indices.to(memory_format=torch.channels_last_3d)
+
+    return out, indices
+
+
+@register_meta(aten.max_pool3d_with_indices_backward)
+@out_wrapper("grad_input")
+def meta_max_pool3d_with_indices_backward(
+    grad_output,
+    input,
+    kernel_size,
+    stride,
+    padding,
+    dilation,
+    ceil_mode,
+    indices,
+):
+    torch._check(
+        len(kernel_size) in (1, 3),
+        lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints",
+    )
+    kT = kernel_size[0]
+    kH = kT if len(kernel_size) == 1 else kernel_size[1]
+    kW = kT if len(kernel_size) == 1 else kernel_size[2]
+
+    torch._check(
+        not stride or len(stride) in (1, 3),
+        lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints",
+    )
+    dT = kT if not stride else stride[0]
+    dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
+    dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
+
+    torch._check(
+        len(padding) in (1, 3),
+        lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints",
+    )
+    pT = padding[0]
+    pH = pT if len(padding) == 1 else padding[1]
+    pW = pT if len(padding) == 1 else padding[2]
+
+    torch._check(
+        len(dilation) in (1, 3),
+        lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints",
+    )
+    dilationT = dilation[0]
+    dilationH = dilationT if len(dilation) == 1 else dilation[1]
+    dilationW = dilationT if len(dilation) == 1 else dilation[2]
+
+    torch._check(
+        input.ndim in (4, 5),
+        lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
+    )
+
+    nslices = input.size(-4)
+    itime = input.size(-3)
+    iheight = input.size(-2)
+    iwidth = input.size(-1)
+
+    otime = grad_output.size(-3)
+    oheight = grad_output.size(-2)
+    owidth = grad_output.size(-1)
+
+    max_pool3d_backward_shape_check(
+        input,
+        grad_output,
+        indices,
+        nslices,
+        kT,
+        kH,
+        kW,
+        dT,
+        dH,
+        dW,
+        pT,
+        pH,
+        pW,
+        dilationT,
+        dilationH,
+        dilationW,
+        itime,
+        iheight,
+        iwidth,
+        otime,
+        oheight,
+        owidth,
+        "max_pool3d_with_indices_backward()",
+    )
+
+    channels_last = (
+        input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d
+    )
+    if input.ndim == 4:
+        input_channels_last_check = input.unsqueeze(0)
+        channels_last = (
+            not input_channels_last_check.is_contiguous()
+        ) and input_channels_last_check.is_contiguous(
+            memory_format=torch.channels_last_3d
+        )
+
+    grad_input = input.new_empty(input.shape)
+
+    if channels_last:
+        grad_input = grad_input.to(memory_format=torch.channels_last_3d)
+
+    return grad_input
+
+
+def check_grid_sampler_common(input: Tensor, grid: Tensor):
+    torch._check(
+        input.device == grid.device,
+        lambda: (
+            f"grid_sampler(): expected input and grid to be on same device, but input "
+            f"is on {input.device} and grid is on {grid.device}"
+        ),
+    )
+    torch._check(
+        input.layout == torch.strided and grid.layout == torch.strided,
+        lambda: (
+            f"grid_sampler(): expected input and grid to have torch.strided layout, but "
+            f"input has {input.layout} and grid has {grid.layout}"
+        ),
+    )
+    torch._check(
+        input.shape[0] == grid.shape[0],
+        lambda: (
+            f"grid_sampler(): expected grid and input to have same batch size, but got "
+            f"input with sizes {input.shape} and grid with sizes {grid.shape}"
+        ),
+    )
+    torch._check(
+        grid.shape[-1] == input.ndim - 2,
+        lambda: (
+            f"grid_sampler(): expected grid to have size {input.ndim - 2} in last "
+            f"dimension, but got grid with sizes {grid.shape}"
+        ),
+    )
+
+    for i in range(2, input.ndim):
+        torch._check(
+            input.shape[i] > 0,
+            lambda: (
+                f"grid_sampler(): expected input to have non-empty spatial dimensions, "
+                f"but input has sizes {input.shape} with dimension {i} being empty"
+            ),
+        )
+
+
+class GridSamplerInterpolation(Enum):
+    BILINEAR = 0
+    NEAREST = 1
+    BICUBIC = 2
+
+
+def check_grid_sampler_3d(input: Tensor, grid: Tensor, interpolation_mode: int):
+    torch._check(
+        input.ndim == 5 and input.ndim == grid.ndim,
+        lambda: (
+            f"grid_sampler(): expected 5D input and grid with same number of "
+            f"dimensions, but got input with sizes {input.shape}"
+            f" and grid with sizes {grid.shape}"
+        ),
+    )
+    torch._check(
+        not (
+            input.ndim == 5
+            and interpolation_mode == GridSamplerInterpolation.BICUBIC.value
+        ),
+        lambda: "grid_sampler(): bicubic interpolation only supports 4D input",
+    )
+
+
+@register_meta(aten.grid_sampler_2d_backward.default)
+def grid_sampler_2d_backward_meta(
+    grad_output,
+    input,
+    grid,
+    interpolation_mode,
+    padding_mode,
+    align_corners,
+    output_mask,
+):
+    input_requires_grad = output_mask[0]
+    if input_requires_grad:
+        grad_input = torch.zeros_like(input, memory_format=torch.contiguous_format)
+    else:
+        grad_input = None
+    grad_grid = torch.empty_like(grid, memory_format=torch.contiguous_format)
+    return (grad_input, grad_grid)
+
+
+@register_meta(aten.grid_sampler_3d)
+@out_wrapper()
+def grid_sampler_3d(
+    input,
+    grid,
+    interpolation_mode,
+    padding_mode,
+    align_corners,
+):
+    check_grid_sampler_common(input, grid)
+    check_grid_sampler_3d(input, grid, interpolation_mode)
+    N = input.shape[0]
+    C = input.shape[1]
+    out_D = grid.shape[1]
+    out_H = grid.shape[2]
+    out_W = grid.shape[3]
+    return input.new_empty((N, C, out_D, out_H, out_W))
+
+
+@register_meta(aten.grid_sampler_3d_backward)
+@out_wrapper("grad_input", "grad_grid")
+def grid_sampler_3d_backward(
+    grad_output,
+    input,
+    grid,
+    interpolation_mode,
+    padding_mode,
+    align_corners,
+    output_mask,
+):
+    check_grid_sampler_common(input, grid)
+    check_grid_sampler_3d(input, grid, interpolation_mode)
+    input_requires_grad = output_mask[0]
+    if input_requires_grad:
+        grad_input = torch.zeros_like(
+            input, memory_format=torch.legacy_contiguous_format
+        )
+    else:
+        grad_input = None
+    grad_grid = torch.empty_like(grid, memory_format=torch.legacy_contiguous_format)
+    return grad_input, grad_grid
+
+
+@register_meta([aten.full.default])
+def full(size, fill_value, *args, **kwargs):
+    dtype = kwargs.get("dtype", None)
+    if not dtype:
+        dtype = utils.get_dtype(fill_value)
+    kwargs["dtype"] = dtype
+    return torch.empty(size, *args, **kwargs)
+
+
+# zeros_like is special cased to work for sparse
+@register_meta(aten.zeros_like.default)
+def zeros_like(
+    self,
+    dtype=None,
+    layout=None,
+    device=None,
+    pin_memory=None,
+    memory_format=None,
+):
+    if layout == torch.sparse_coo:
+        torch._check(
+            memory_format is None,
+            lambda: "memory format option is only supported by strided tensors",
+        )
+
+        res = torch.empty(
+            0,
+            dtype=self.dtype if dtype is None else dtype,
+            layout=layout,
+            device=self.device if device is None else device,
+            pin_memory=pin_memory,
+        )
+
+        if self.is_sparse:
+            res.sparse_resize_and_clear_(
+                self.size(), self.sparse_dim(), self.dense_dim()
+            )
+        else:
+            res.sparse_resize_and_clear_(self.size(), self.dim(), 0)
+
+        res._coalesced_(True)
+        return res
+    res = aten.empty_like.default(
+        self,
+        dtype=dtype,
+        layout=layout,
+        device=device,
+        pin_memory=pin_memory,
+        memory_format=memory_format,
+    )
+    # device can be not "meta"
+    res.fill_(0)
+    return res
+
+
+@register_meta(aten.select.int)
+def meta_select(self, dim, index):
+    from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
+
+    ndim = self.dim()
+    torch._check_index(
+        ndim != 0,
+        lambda: "select() cannot be applied to a 0-dim tensor.",
+    )
+
+    dim = dim if dim >= 0 else dim + ndim
+    size = self.size(dim)
+
+    torch._check_index(
+        not (
+            guard_size_oblivious(-index > size) or guard_size_oblivious(index >= size)
+        ),
+        lambda: f"select(): index {index} out of range for tensor of size "
+        f"{self.size()} at dimension {dim}",
+    )
+
+    index = index if index >= 0 else index + size
+
+    new_size = list(self.size())
+    new_stride = list(self.stride())
+
+    new_storage_offset = self.storage_offset() + index * new_stride[dim]
+    del new_size[dim]
+    del new_stride[dim]
+
+    return self.as_strided(new_size, new_stride, new_storage_offset)
+
+
+@register_meta(aten.select_scatter.default)
+def meta_select_scatter(self, src, dim, index):
+    return utils.clone_preserve_strides(self)
+
+
+@register_meta(aten.slice_scatter.default)
+def meta_slice_scatter(self, src, dim=0, start=None, end=None, step=1):
+    return utils.clone_preserve_strides(self)
+
+
+# TODO: Deduplicate this with canonicalize_dim
+def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True):
+    if dim_post_expr <= 0:
+        assert wrap_scalar
+        dim_post_expr = 1
+    min = -dim_post_expr
+    max = dim_post_expr - 1
+    assert not (dim < min or dim > max), f"dim {dim} out of bounds ({min}, {max})"
+    if dim < 0:
+        dim += dim_post_expr
+    return dim
+
+
+def ensure_nonempty_size(t, dim):
+    return 1 if t.dim() == 0 else t.shape[dim]
+
+
+# From aten/src/ATen/native/ScatterGatherChecks.h
+def gather_shape_check(self, dim, index):
+    self_dims = max(self.dim(), 1)
+    index_dims = max(index.dim(), 1)
+    torch._check(
+        self_dims == index_dims,
+        lambda: "Index tensor must have the same number of dimensions as input tensor",
+    )
+    for i in range(self_dims):
+        if i != dim:
+            torch._check(
+                ensure_nonempty_size(index, i) <= ensure_nonempty_size(self, i),
+                lambda: f"Size does not match at dimension {i} expected index {index.shape}"
+                + f" to be no larger than self {self.shape} apart from dimension {dim}",
+            )
+
+
+@register_meta(aten.gather.default)
+def meta_gather(self, dim, index, sparse_grad=False):
+    from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
+
+    wrapped_dim = maybe_wrap_dim(dim, self.dim())
+    is_index_empty = guard_size_oblivious(index.numel() == 0)
+    if not is_index_empty:
+        torch._check(
+            index.dtype == torch.long,
+            lambda: f"gather(): Expected dtype int64 for index, but got {index.dtype}",
+        )
+        gather_shape_check(self, wrapped_dim, index)
+    return self.new_empty(index.shape)
+
+
+# From aten/src/ATen/native/TensorAdvancedIndexing.cpp
+def get_operator_enum(reduce_, use_new_options=False):
+    if use_new_options:
+        if reduce_ == "sum":
+            return "REDUCE_ADD"
+        elif reduce_ == "prod":
+            return "REDUCE_MULTIPLY"
+        elif reduce_ == "mean":
+            return "REDUCE_MEAN"
+        elif reduce_ == "amax":
+            return "REDUCE_MAXIMUM"
+        elif reduce_ == "amin":
+            return "REDUCE_MINIMUM"
+        torch._check(
+            False,
+            lambda: "reduce argument must be either sum, prod, mean, amax or amin.",
+        )
+        return
+    else:
+        if reduce_ == "add":
+            return "REDUCE_ADD"
+        elif reduce_ == "multiply":
+            return "REDUCE_MULTIPLY"
+        torch._check(False, lambda: "reduce argument must be either add or multiply.")
+        return
+
+
+# From aten/src/ATen/native/ScatterGatherChecks.h
+def scatter_gather_dtype_check(method_name, self, index, src_opt=None):
+    from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
+
+    if guard_size_oblivious(index.numel() != 0):
+        torch._check(
+            index.dtype == torch.long,
+            lambda: f"{method_name}(): Expected dtype int64 for index",
+        )
+
+    if src_opt is not None:
+        torch._check(
+            self.dtype == src_opt.dtype,
+            lambda: f"{method_name}(): Expected self.dtype to be equal to src.dtype",
+        )
+
+
+def ensure_nonempty_dim(dim):
+    return max(dim, 1)
+
+
+# From aten/src/ATen/native/ScatterGatherChecks.h
+def scatter_shape_check(self, dim, index, src_opt=None):
+    from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
+
+    if guard_size_oblivious(index.numel() == 0):
+        return
+    torch._check(
+        ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()),
+        lambda: "Index tensor must have the same number of dimensions as self tensor",
+    )
+
+    is_wrong_shape = False
+    self_dims = ensure_nonempty_dim(self.dim())
+
+    # Check: index.size(d) <= self.size(d) for all d != dim
+    for d in range(self_dims):
+        index_d_size = ensure_nonempty_size(index, d)
+        if d == dim:
+            continue
+        if index_d_size > ensure_nonempty_size(self, d):
+            is_wrong_shape = True
+            break
+
+    # Check: index.size(d) <= src.size(d) for all d if src is Tensor
+    if not is_wrong_shape and src_opt is not None:
+        for d in range(self_dims):
+            index_d_size = ensure_nonempty_size(index, d)
+            if index_d_size > ensure_nonempty_size(src_opt, d):
+                is_wrong_shape = True
+                break
+
+    if src_opt is not None:
+        torch._check(
+            ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()),
+            lambda: "Index tensor must have the same number of dimensions as self tensor",
+        )
+        torch._check(
+            not is_wrong_shape,
+            lambda: f"Expected index {index.shape} to be no larger than self {self.shape}"
+            + f" apart from dimension {dim} and to be no larger than src {src_opt.shape}",
+        )
+    else:
+        torch._check(
+            not is_wrong_shape,
+            lambda: f"Expected index {index.shape} to be no larger than self {self.shape}"
+            + f" apart from dimension {dim}",
+        )
+
+
+# From aten/src/ATen/native/TensorAdvancedIndexing.cpp
+def scatter_meta_impl(self, dim, index, src=None, reduce_=None, use_new_options=False):
+    wrapped_dim = maybe_wrap_dim(dim, self.dim())
+    scatter_gather_dtype_check("scatter", self, index, src)
+    scatter_shape_check(self, wrapped_dim, index, src)
+    if reduce_ is not None:
+        # Check if we have a valid reduce operator.
+        get_operator_enum(reduce_, use_new_options)
+
+
+@register_meta(aten.scatter_add.default)
+def meta_scatter_add(self, dim, index, src):
+    scatter_meta_impl(self, dim, index, src, "add")
+    return self.new_empty(self.shape)
+
+
+@register_meta(aten.scatter_add_)
+def meta_scatter_add_(self, dim, index, src):
+    scatter_meta_impl(self, dim, index, src, "add")
+    return self
+
+
+@register_meta(
+    [
+        aten.scatter.src,
+        aten.scatter.value,
+        aten.scatter.reduce,
+        aten.scatter.value_reduce,
+    ]
+)
+@out_wrapper()
+def meta_scatter(self, dim, index, src_or_value, reduce=None):
+    src = src_or_value if isinstance(src_or_value, torch.Tensor) else None
+    scatter_meta_impl(self, dim, index, src, reduce)
+    return self.new_empty(self.shape)
+
+
+@register_meta(
+    [
+        aten.scatter_.src,
+        aten.scatter_.value,
+        aten.scatter_.reduce,
+        aten.scatter_.value_reduce,
+    ]
+)
+def meta_scatter_(self, dim, index, src_or_value, reduce=None):
+    src = src_or_value if isinstance(src_or_value, torch.Tensor) else None
+    scatter_meta_impl(self, dim, index, src, reduce)
+    return self
+
+
+@register_meta([aten._scaled_dot_product_flash_attention])
+def meta__scaled_dot_product_flash_attention(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    return_debug_mask: bool = False,
+    scale: Optional[float] = None,
+):
+    batch_size = query.size(0)
+    num_heads = query.size(1)
+    max_seqlen_batch_q = query.size(2)
+    head_dim = query.size(3)
+    max_seqlen_batch_k = key.size(2)
+
+    query_t = query.transpose(1, 2)
+    attention = torch.empty_like(query_t).transpose(1, 2)
+    logsumexp = torch.empty(
+        (batch_size, num_heads, max_seqlen_batch_q),
+        dtype=torch.float,
+        device=query.device,
+    )
+
+    if return_debug_mask:
+        blocksize_c = 128 if head_dim > 64 else 256
+        max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c)
+        if max_seqlen_batch_k <= 128:
+            max_seqlen_k = 128
+        elif max_seqlen_batch_k <= 256:
+            max_seqlen_k = 256
+        debug_mask = torch.empty(
+            (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k),
+            dtype=query.dtype,
+            device=query.device,
+        )
+    else:
+        debug_mask = torch.empty(0, dtype=query.dtype, device=query.device)
+
+    # Note [Seed and Offset]: device for seed and offset below depends on whether we are
+    # capturing or not, but at the time of tracing we don't know if we
+    # are going to use cudagraphs or not, so we return meta tensors here
+    # it's possible we'll need to have some special handling in inductor for sdpa
+    # See [Note] BC breaking change to flash seed/offset
+    if torch.version.hip and torch.cuda.is_available():
+        # Maintian old path on AMD
+        seed = torch.empty((), dtype=torch.long, device="meta")
+        offset = torch.empty((), dtype=torch.long, device="meta")
+    else:
+        seed = torch.empty((2), dtype=torch.uint64, device="meta")
+        offset = torch.empty((), dtype=torch.uint64, device="meta")
+
+    return (
+        attention,
+        logsumexp,
+        None,
+        None,
+        max_seqlen_batch_q,
+        max_seqlen_batch_k,
+        seed,
+        offset,
+        debug_mask,
+    )
+
+
+@register_meta([aten._scaled_dot_product_cudnn_attention])
+def meta__scaled_dot_product_cudnn_attention(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    attn_bias: Optional[Tensor],
+    compute_log_sumexp: bool,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    return_debug_mask: bool = False,
+    scale: Optional[float] = None,
+):
+    B = query.size(0)
+    H = query.size(1)
+    S_Q = query.size(2)
+    S_KV = key.size(2)
+    D_V = value.size(-1)
+
+    res = torch.empty((B, H, S_Q, D_V), dtype=query.dtype, device=query.device)
+    logsum_exp = torch.empty(
+        (B, H, S_Q),
+        dtype=torch.float,
+        device=query.device,
+    )
+
+    # See Note [Seed and Offset]
+    seed = torch.empty((), dtype=torch.long, device="meta")
+    offset = torch.empty((), dtype=torch.long, device="meta")
+
+    return (
+        res,
+        logsum_exp,
+        None,
+        None,
+        S_Q,
+        S_KV,
+        seed,
+        offset,
+        None,
+    )
+
+
+@register_meta([aten._scaled_dot_product_fused_attention_overrideable])
+def meta__scaled_dot_product_fused_attention_overrideable(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    attn_bias: Optional[Tensor] = None,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    return_debug_mask: bool = False,
+    scale: Optional[float] = None,
+):
+    B = query.size(0)
+    H = query.size(1)
+    S_Q = query.size(2)
+    S_KV = key.size(2)
+    D_V = value.size(-1)
+
+    res = torch.empty((B, H, S_Q, D_V), dtype=query.dtype, device=query.device)
+    logsum_exp = torch.empty(
+        (B, H, S_Q),
+        dtype=torch.float,
+        device=query.device,
+    )
+
+    # See Note [Seed and Offset]
+    seed = torch.empty((), dtype=torch.long, device="meta")
+    offset = torch.empty((), dtype=torch.long, device="meta")
+
+    return (
+        res,
+        logsum_exp,
+        None,
+        None,
+        S_Q,
+        S_KV,
+        seed,
+        offset,
+        None,
+    )
+
+
+@register_meta(
+    [
+        aten._scaled_dot_product_flash_attention_backward,
+    ]
+)
+def meta__scaled_dot_product_flash_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    out: Tensor,
+    logsumexp: Tensor,
+    cum_seq_q: Tensor,
+    cum_seq_k: Tensor,
+    max_q: int,
+    max_k: int,
+    dropout_p: float,
+    is_causal: bool,
+    philox_seed: Tensor,
+    philox_offset: Tensor,
+    scale: Optional[float] = None,
+):
+    grad_q = torch.empty_like(query.transpose(1, 2)).transpose(1, 2)
+    grad_k = torch.empty_like(key.transpose(1, 2)).transpose(1, 2)
+    grad_v = torch.empty_like(value.transpose(1, 2)).transpose(1, 2)
+    return grad_q, grad_k, grad_v
+
+
+@register_meta(
+    [
+        aten._scaled_dot_product_flash_attention_for_cpu,
+    ]
+)
+def meta__scaled_dot_product_flash_attention_for_cpu(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    dropout_p: float = 0.0,
+    is_causal: bool = False,
+    attn_mask: Optional[Tensor] = None,
+    scale: Optional[float] = None,
+):
+    batch_size = query.size(0)
+    num_heads = query.size(1)
+    max_seqlen_batch_q = query.size(2)
+
+    attention = torch.empty_like(query)
+    logsumexp = torch.empty(
+        (
+            batch_size,
+            max_seqlen_batch_q,
+            num_heads,
+        ),
+        dtype=torch.float,
+        device=query.device,
+    ).transpose(1, 2)
+    return (
+        attention,
+        logsumexp,
+    )
+
+
+@register_meta(
+    [
+        aten._scaled_dot_product_flash_attention_for_cpu_backward,
+    ]
+)
+def meta__scaled_dot_product_flash_attention_for_cpu_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    out: Tensor,
+    logsumexp: Tensor,
+    dropout_p: float,
+    is_causal: bool,
+    attn_mask: Optional[Tensor] = None,
+    scale: Optional[float] = None,
+):
+    # cpus's grad layout is different from cuda's,
+    # i.e. (batch_size, seq_len,num_heads, head_dim)
+    batch_size = query.size(0)
+    num_heads = query.size(1)
+    head_dim = query.size(3)
+    len_q = query.size(2)
+    len_k = key.size(2)
+
+    grad_q = torch.empty_permuted(
+        (batch_size, num_heads, len_q, head_dim),
+        (0, 2, 1, 3),
+        dtype=query.dtype,
+        device=query.device,
+    )
+    grad_k = torch.empty_permuted(
+        (batch_size, num_heads, len_k, head_dim),
+        (0, 2, 1, 3),
+        dtype=key.dtype,
+        device=key.device,
+    )
+    grad_v = torch.empty_permuted(
+        (batch_size, num_heads, len_k, head_dim),
+        (0, 2, 1, 3),
+        dtype=value.dtype,
+        device=value.device,
+    )
+
+    return grad_q, grad_k, grad_v
+
+
+@register_meta([aten._scaled_dot_product_efficient_attention])
+def meta__scaled_dot_product_efficient_attention(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    attn_bias: Optional[Tensor],
+    compute_log_sumexp: bool,
+    dropout_p=0.0,
+    is_causal: bool = False,
+    scale: Optional[float] = None,
+):
+    query = query.transpose(1, 2)
+    key = key.transpose(1, 2)
+    value = value.transpose(1, 2)
+
+    B = query.size(0)
+    M = query.size(1)
+    num_heads = query.size(-2)
+    Kv = value.size(-1)
+
+    res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device)
+
+    if torch.version.hip and torch.cuda.is_available():
+        """Please see: https://github.com/pytorch/pytorch/issues/146848
+        longsumexp last dim should be seq length
+        """
+        logsumexp_dim = M if compute_log_sumexp else 0
+    else:
+        logsumexp_dim = math.ceil(M / 32) * 32 if compute_log_sumexp else 0
+
+    logsum_exp = torch.empty(
+        (B, num_heads, logsumexp_dim),
+        dtype=torch.float,
+        device=query.device,
+    )
+
+    res = res.transpose(1, 2)
+
+    # See Note [Seed and Offset]:
+    seed = torch.empty((), dtype=torch.long, device="meta")
+    offset = torch.empty((), dtype=torch.long, device="meta")
+
+    return res, logsum_exp, seed, offset
+
+
+@register_meta(
+    [
+        aten._scaled_dot_product_efficient_attention_backward,
+    ]
+)
+def meta__scaled_dot_product_efficient_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    attn_bias: Optional[Tensor],
+    out: Tensor,
+    logsumexp: Tensor,
+    philox_seed: Tensor,
+    philox_offset: Tensor,
+    dropout_p: float,
+    grad_input_mask: list[bool],
+    is_causal: bool = False,
+    scale: Optional[float] = None,
+):
+    batch_size = query.size(0)
+    num_heads = query.size(1)
+    max_q = query.size(2)
+    head_dim = query.size(3)
+    head_dim_v = value.size(3)
+
+    max_k = key.size(2)
+
+    grad_q = torch.empty_permuted(
+        (batch_size, num_heads, max_q, head_dim),
+        (0, 2, 1, 3),
+        dtype=query.dtype,
+        device=query.device,
+    )
+    grad_k = torch.empty_permuted(
+        (batch_size, num_heads, max_k, head_dim),
+        (0, 2, 1, 3),
+        dtype=key.dtype,
+        device=key.device,
+    )
+    grad_v = torch.empty_permuted(
+        (batch_size, num_heads, max_k, head_dim_v),
+        (0, 2, 1, 3),
+        dtype=value.dtype,
+        device=value.device,
+    )
+    grad_bias = None
+    if attn_bias is not None and grad_input_mask[3]:
+        lastDim = attn_bias.size(-1)
+        lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16
+        new_sizes = list(attn_bias.size())
+        new_sizes[-1] = lastDimAligned
+        grad_bias = torch.empty(
+            new_sizes, dtype=attn_bias.dtype, device=attn_bias.device
+        )
+        grad_bias = grad_bias[..., :lastDim]
+
+    return grad_q, grad_k, grad_v, grad_bias
+
+
+@register_meta(
+    [
+        aten._scaled_dot_product_cudnn_attention_backward,
+    ]
+)
+def meta__scaled_dot_product_cudnn_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    out: Tensor,
+    logsumexp: Tensor,
+    philox_seed: Tensor,
+    philox_offset: Tensor,
+    attn_bias: Tensor,
+    cum_seq_q: Tensor,
+    cum_seq_k: Tensor,
+    max_q: int,
+    max_k: int,
+    dropout_p: float,
+    is_causal: bool,
+    scale: Optional[float] = None,
+):
+    grad_q = torch.empty_like(query)
+    grad_k = torch.empty_like(key)
+    grad_v = torch.empty_like(value)
+    return grad_q, grad_k, grad_v
+
+
+@register_meta(
+    [
+        aten._flash_attention_forward,
+    ]
+)
+def meta__flash_attention_forward(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    cum_seq_q: Optional[Tensor],
+    cum_seq_k: Optional[Tensor],
+    max_q: int,
+    max_k: int,
+    dropout_p: float,
+    is_causal: bool,
+    return_debug_mask: bool,
+    scale: Optional[float] = None,
+    window_size_left: Optional[int] = None,
+    window_size_right: Optional[int] = None,
+    seqused_k: Optional[Tensor] = None,
+    alibi_slopes: Optional[Tensor] = None,
+):
+    # NB: there are two underlying paths:
+    # 1. normal dense path; expect 4D inputs of shape (batch_size, seqlen, num_heads, head_dim)
+    # 2. varseqlen path; expect 3D inputs of shape (total, num_heads, head_dim) where total
+    #    includes all batch item sequences. cum_seq_q / cum_seq_k contain offsets into total
+    batch_size = query.size(0) if cum_seq_q is None else cum_seq_q.numel() - 1
+    max_seqlen_batch_q = query.size(1) if cum_seq_q is None else max_q
+    max_seqlen_batch_k = key.size(1) if cum_seq_k is None else max_k
+    num_heads = query.size(-2)
+    head_dim = query.size(-1)
+
+    # Cuda Path
+    attention = torch.empty_like(query)
+    if cum_seq_q is None:
+        logsumexp = torch.empty(
+            (batch_size, num_heads, max_seqlen_batch_q),
+            dtype=torch.float,
+            device=query.device,
+        )
+    else:
+        total_q = query.size(0)
+        logsumexp = torch.empty(
+            (num_heads, total_q), dtype=torch.float, device=query.device
+        )
+
+    if return_debug_mask:
+        blocksize_c = 128 if head_dim > 64 else 256
+        max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c)
+        if max_seqlen_batch_k <= 128:
+            max_seqlen_k = 128
+        elif max_seqlen_batch_k <= 256:
+            max_seqlen_k = 256
+        debug_mask = torch.empty(
+            (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k),
+            dtype=query.dtype,
+            device=query.device,
+        )
+    else:
+        debug_mask = torch.empty(0, dtype=query.dtype, device=query.device)
+
+    # See Note [Seed and Offset]
+    # See [Note] BC breaking change to flash seed/offset
+    seed, offset = None, None
+    if torch.version.hip and torch.cuda.is_available():
+        # Maintian old path on AMD
+        seed = torch.empty((), dtype=torch.long, device="meta")
+        offset = torch.empty((), dtype=torch.long, device="meta")
+    else:
+        seed = torch.empty((2), dtype=torch.uint64, device="meta")
+        offset = torch.empty((), dtype=torch.uint64, device="meta")
+    return (
+        attention,
+        logsumexp,
+        seed,
+        offset,
+        debug_mask,
+    )
+
+
+@register_meta(
+    [
+        aten._flash_attention_backward,
+    ]
+)
+def meta__flash_attention_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    out: Tensor,
+    logsumexp: Tensor,
+    cum_seq_q: Tensor,
+    cum_seq_k: Tensor,
+    max_q: int,
+    max_k: int,
+    dropout_p: float,
+    is_causal: bool,
+    philox_seed: Tensor,
+    philox_offset: Tensor,
+    scale: Optional[float] = None,
+    window_size_left: Optional[int] = None,
+    window_size_right: Optional[int] = None,
+):
+    grad_query = torch.empty_like(query)
+    grad_key = torch.empty_like(key)
+    grad_value = torch.empty_like(value)
+
+    return grad_query, grad_key, grad_value
+
+
+@register_meta(
+    [
+        aten._efficient_attention_forward,
+    ]
+)
+def meta__efficient_attention_forward(
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    bias: Optional[Tensor],
+    cu_seqlens_q: Optional[Tensor],
+    cu_seqlens_k: Optional[Tensor],
+    max_seqlen_q: Optional[int],
+    max_seqlen_k: Optional[int],
+    dropout_p: float,
+    custom_mask_type: int,
+    compute_log_sumexp: bool = False,
+    scale: Optional[float] = None,
+    causal_diagonal: Optional[Tensor] = None,
+    seqlen_k: Optional[Tensor] = None,
+    window_size: Optional[int] = None,
+):
+    B = query.size(0)
+    M = query.size(1)
+    N = key.size(1)
+    num_heads = query.size(-2)
+    Kv = value.size(-1)
+
+    res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device)
+
+    logsumexp_batch_dim = cu_seqlens_q.size(0) - 1 if (cu_seqlens_q is not None) else B
+    actual_max_seqlen_q = M
+    if cu_seqlens_q is not None:
+        assert max_seqlen_q is not None
+        actual_max_seqlen_q = max_seqlen_q
+    actual_max_seqlen_k = max_seqlen_k if max_seqlen_k is not None else N
+    logsumexp_dim = (
+        math.ceil(actual_max_seqlen_q / 32) * 32 if compute_log_sumexp else 0
+    )
+    logsum_exp = torch.empty(
+        (logsumexp_batch_dim, num_heads, logsumexp_dim),
+        dtype=torch.float,
+        device=query.device,
+    )
+
+    # See Note [Seed and Offset]:
+    seed = torch.empty((), dtype=torch.long, device="meta")
+    offset = torch.empty((), dtype=torch.long, device="meta")
+
+    return res, logsum_exp, seed, offset, actual_max_seqlen_q, actual_max_seqlen_k
+
+
+@register_meta(
+    [
+        aten._efficient_attention_backward,
+    ]
+)
+def meta__efficient_attention_backward(
+    grad_out: Tensor,
+    query: Tensor,
+    key: Tensor,
+    value: Tensor,
+    bias: Optional[Tensor],
+    cu_seqlens_q: Optional[Tensor],
+    cu_seqlens_k: Optional[Tensor],
+    max_seqlen_q: torch.SymInt,
+    max_seqlen_k: torch.SymInt,
+    logsumexp: Tensor,
+    dropout_p: float,
+    philox_seed: Tensor,
+    philox_offset: Tensor,
+    custom_mask_type: int,
+    bias_requires_grad: bool,
+    scale: Optional[float] = None,
+    num_splits_key: Optional[int] = None,
+    shared_storage_dqdkdv: bool = False,
+):
+    if shared_storage_dqdkdv:
+        torch._check(
+            query.shape[1] == key.shape[1],
+            lambda: "seqlen must match for `shared_storage_dqdkdv",
+        )
+        torch._check(
+            query.shape[3] == key.shape[3],
+            lambda: "embedding dim must match for `shared_storage_dqdkdv",
+        )
+        chunk = torch.empty(
+            (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]),
+            dtype=query.dtype,
+            device=query.device,
+        )
+        grad_query = chunk.select(-3, 0)
+        grad_key = chunk.select(-3, 1)
+        grad_value = chunk.select(-3, 2)
+    else:
+        grad_query = torch.empty_like(query)
+        grad_key = torch.empty_like(key)
+        grad_value = torch.empty_like(value)
+
+    if bias is not None:
+        lastDim = bias.size(-1)
+        lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16
+        new_sizes = list(bias.size())
+        new_sizes[-1] = lastDimAligned
+        grad_bias = torch.empty(new_sizes, dtype=bias.dtype, device=bias.device)
+        grad_bias = grad_bias[..., :lastDim]
+    else:
+        grad_bias = torch.empty((), device=query.device)
+
+    return grad_query, grad_key, grad_value, grad_bias
+
+
+@register_meta([aten._scaled_mm.default])
+def meta_scaled_mm(
+    self: torch.Tensor,
+    mat2: torch.Tensor,
+    scale_a: torch.Tensor,
+    scale_b: torch.Tensor,
+    bias: Optional[torch.Tensor] = None,
+    scale_result: Optional[torch.Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    use_fast_accum: bool = False,
+):
+    def is_fp8_type(dtype):
+        return dtype in (
+            torch.float8_e4m3fn,
+            torch.float8_e5m2,
+            torch.float8_e4m3fnuz,
+            torch.float8_e5m2fnuz,
+        )
+
+    torch._check(
+        self.dim() == 2 and mat2.dim() == 2,
+        lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}",
+    )
+    torch._check(
+        is_fp8_type(self.dtype) and is_fp8_type(mat2.dtype),
+        lambda: f"Expected both inputs to be fp8 types but got self.dtype={self.dtype} and mat2.dtype={mat2.dtype}",
+    )
+
+    if device_hint(self) == "cuda":
+
+        def is_row_major(stride):
+            return stride[0] > stride[1] and stride[1] == 1
+
+        def is_col_major(stride):
+            return stride[0] == 1 and stride[1] > 1
+
+        def has_zero_dim(tensor_2d):
+            return tensor_2d.size(0) == 0 or tensor_2d.size(1) == 0
+
+        torch._check(
+            is_row_major(self.stride()) or has_zero_dim(self),
+            lambda: f"self must be row_major, got stride {self.stride()}",
+        )
+        torch._check(
+            is_col_major(mat2.stride()) or has_zero_dim(mat2),
+            lambda: f"mat2 must be col_major, got stride {mat2.stride()}",
+        )
+        torch._check(
+            self.size(1) % 16 == 0,
+            lambda: f"Expected self.size(1) to be divisible by 16, but got self.size(1)={self.size(1)}",
+        )
+        torch._check(
+            mat2.size(0) % 16 == 0 and mat2.size(1) % 16 == 0,
+            lambda: f"Expected both dimensions of mat2 to be divisble by 16 but got {mat2.shape}",
+        )
+
+        # determine scaling type and check input dimensions (refer to Blas.cpp op)
+        torch._check(
+            scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32,
+            lambda: "Both scale_a and scale_b must be float (fp32) tensors.",
+        )
+        m, _k = self.shape
+        n = mat2.size(1)
+        if scale_a.numel() == 1 and scale_b.numel() == 1:
+            # tensorwise scaling
+            pass
+        else:
+            # for non-tensorwise scaling, enforce 2D input tensors
+            torch._check(
+                scale_a.dim() == 2 and scale_b.dim() == 2,
+                lambda: f"For non-tensorwise scaling, scale tensors must be 2D, but got {scale_a.dim()=} and {scale_b.dim()=}",
+            )
+
+            if (
+                scale_a.size(0) == m
+                and scale_a.size(1) == 1
+                and scale_b.size(0) == 1
+                and scale_b.size(1) == n
+            ):
+                # rowwise scaling
+                torch._check(
+                    scale_a.is_contiguous() and scale_b.is_contiguous(),
+                    lambda: "Both scale_a and scale_b must be contiguous for rowwise scaling.",
+                )
+            else:
+                # does not match any valid scaling type
+                torch._check(
+                    False,
+                    lambda: (
+                        "Invalid scaling configuration. "
+                        "For tensorwise scaling, both scales should be scalar. "
+                        f"For rowwise scaling, scale_a should be ({m}, 1), scale_b should be (1, {n}). "
+                        f"Got scale_a.size()=({scale_a.size(0)}, {scale_a.size(1)}) "
+                        f"and scale_b.size()=({scale_b.size(0)}, {scale_b.size(1)})"
+                    ),
+                )
+
+    _out_dtype = out_dtype if out_dtype is not None else self.dtype
+    return torch.empty(self.size(0), mat2.size(1), dtype=_out_dtype, device=self.device)
+
+
+@register_meta([aten.scatter_reduce.two, aten.scatter_reduce.two_out])
+@out_wrapper()
+def meta_scatter_reduce_two(self, dim, index, src, reduce, include_self=True):
+    scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True)
+    return self.new_empty(self.shape)
+
+
+@register_meta(aten.scatter_reduce_.two)
+def meta_scatter_reduce__two(self, dim, index, src, reduce, include_self=True):
+    scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True)
+    return self
+
+
+@register_meta([aten.multinomial.default, aten.multinomial.out])
+@out_wrapper()
+def meta_multinomial(input, num_samples, replacement=False, *, generator=None):
+    torch._check(
+        0 < input.dim() <= 2,
+        lambda: f"The probabilty distributions dimensions must be 1 or 2, but got {input.dim()}",
+    )
+    if input.dim() == 1:
+        return torch.empty(num_samples, dtype=torch.long, device=input.device)
+    return torch.empty(
+        input.size(0), num_samples, dtype=torch.long, device=input.device
+    )
+
+
+def multiply_integers(vs):
+    r = 1
+    for v in vs:
+        r *= v
+    return r
+
+
+def upsample_common_check(input_size, output_size, num_spatial_dims):
+    torch._check(
+        len(output_size) == num_spatial_dims,
+        lambda: f"It is expected output_size equals to {num_spatial_dims}, but got size {len(output_size)}",
+    )
+    expected_input_dims = num_spatial_dims + 2  # N, C, ...
+    torch._check(
+        len(input_size) == expected_input_dims,
+        lambda: f"It is expected input_size equals to {expected_input_dims}, but got size {len(input_size)}",
+    )
+
+    torch._check(
+        all(s > 0 for s in input_size[2:]) and all(s > 0 for s in output_size),
+        lambda: f"Input and output sizes should be greater than 0, but got "
+        f"input size {input_size} and output size {output_size}",
+    )
+
+    nbatch, channels = input_size[:2]
+    return (nbatch, channels, *output_size)
+
+
+@register_meta(
+    [aten.upsample_nearest1d.default, aten._upsample_nearest_exact1d.default]
+)
+def upsample_nearest1d(input, output_size, scales=None):
+    torch._check(
+        input.numel() != 0 or multiply_integers(input.size()[1:]),
+        lambda: f"Non-empty 3D data tensor expected but got a tensor with sizes {input.size()}",
+    )
+    full_output_size = upsample_common_check(
+        input.size(), output_size, num_spatial_dims=1
+    )
+    return input.new_empty(full_output_size).to(
+        memory_format=utils.suggest_memory_format(input)
+    )
+
+
+@register_meta(
+    [aten.upsample_nearest2d.default, aten._upsample_nearest_exact2d.default]
+)
+def upsample_nearest2d(input, output_size, scales_h=None, scales_w=None):
+    torch._check(
+        input.numel() != 0 or multiply_integers(input.size()[1:]),
+        lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}",
+    )
+    full_output_size = upsample_common_check(
+        input.size(), output_size, num_spatial_dims=2
+    )
+    output = input.new_empty(full_output_size)
+
+    # convert output to correct memory format, if necessary
+    memory_format = utils.suggest_memory_format(input)
+
+    # following "heuristic: only use channels_last path when it's faster than the contiguous path"
+    _, n_channels, _, _ = input.shape
+    if input.device.type == "cuda" and n_channels < 4:
+        memory_format = torch.contiguous_format
+
+    output = output.contiguous(memory_format=memory_format)
+
+    return output
+
+
+@register_meta(
+    [
+        aten.upsample_nearest2d_backward.default,
+        aten._upsample_nearest_exact2d_backward.default,
+    ]
+)
+def upsample_nearest2d_backward(
+    grad_output: Tensor,
+    output_size: Sequence[Union[int, torch.SymInt]],
+    input_size: Sequence[Union[int, torch.SymInt]],
+    scales_h: Optional[float] = None,
+    scales_w: Optional[float] = None,
+):
+    full_output_size = upsample_common_check(
+        input_size, output_size, num_spatial_dims=2
+    )
+    torch._check(
+        grad_output.ndim == 4,
+        lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}",
+    )
+    for i in range(4):
+        torch._check(
+            grad_output.size(i) == full_output_size[i],
+            lambda: (
+                f"Expected grad_output to have the same shape as output;"
+                f" output.size({i}) = {full_output_size[i]}"
+                f" but got grad_output.size({i}) = {grad_output.size(i)}"
+            ),
+        )
+
+    return grad_output.new_empty(input_size).to(
+        memory_format=utils.suggest_memory_format(grad_output)
+    )  # type: ignore[call-overload]
+
+
+@register_meta(
+    [aten.upsample_nearest3d.default, aten._upsample_nearest_exact3d.default]
+)
+def upsample_nearest3d(input, output_size, scales_d=None, scales_h=None, scales_w=None):
+    torch._check(
+        input.numel() != 0 or multiply_integers(input.size()[1:]),
+        lambda: f"Non-empty 5D data tensor expected but got a tensor with sizes {input.size()}",
+    )
+    full_output_size = upsample_common_check(
+        input.size(), output_size, num_spatial_dims=3
+    )
+    return input.new_empty(full_output_size).to(
+        memory_format=utils.suggest_memory_format(input)
+    )
+
+
+@register_meta(
+    [
+        aten.sort.default,
+        aten.sort.stable,
+        aten.sort.values,
+        aten.sort.values_stable,
+    ]
+)
+def meta_sort(self, stable=None, dim=-1, descending=False, values=None, indices=None):
+    v, i = torch.empty_like(self), torch.empty_like(self, dtype=torch.int64)
+    if values is not None and indices is not None:
+        assert isinstance(values, TensorLike)
+        assert isinstance(indices, TensorLike)
+        # Makes sure values and indices have the same strides. For cases where
+        # these have different shapes, like (5, 10, 5) and (0) in msort.
+        out_shape = v.shape
+        out_stride = v.stride()
+        values = _maybe_resize_out(values, out_shape)
+        indices = _maybe_resize_out(indices, out_shape)
+        values.as_strided_(out_shape, out_stride)
+        indices.as_strided_(out_shape, out_stride)
+        _safe_copy_out(copy_from=v, copy_to=values)  # type: ignore[arg-type]
+        _safe_copy_out(copy_from=i, copy_to=indices)  # type: ignore[arg-type]
+        return values, indices
+    return v, i
+
+
+def rnn_cell_checkSizes(
+    input_gates,
+    hidden_gates,
+    input_bias,
+    hidden_bias,
+    factor,
+    prev_hidden,
+):
+    torch._check(input_gates.ndim == 2, lambda: f"{input_gates.ndim} != 2")
+    torch._check(
+        input_gates.shape == hidden_gates.shape,
+        lambda: f"{input_gates.shape} != {hidden_gates.shape}",
+    )
+    gates_size = input_gates.size(1)
+    if input_bias is not None:
+        torch._check(input_bias.ndim == 1, lambda: f"{input_bias.ndim} != 1")
+        torch._check(
+            input_bias.numel() == gates_size,
+            lambda: f"{input_bias.numel()} != {gates_size}",
+        )
+        torch._check(
+            input_bias.shape == hidden_bias.shape,
+            lambda: f"{input_bias.shape} != {hidden_bias.shape}",
+        )
+    torch._check(prev_hidden.ndim == 2, lambda: f"{prev_hidden.ndim} != 2")
+    expected_prev_hidden_numel = input_gates.size(0) * gates_size // factor
+    torch._check(
+        prev_hidden.numel() == expected_prev_hidden_numel,
+        lambda: f"{prev_hidden.numel()} != {input_gates.size(0)} * {gates_size} // {factor} (aka {expected_prev_hidden_numel})",
+    )
+    torch._check(
+        all(
+            x.device == input_gates.device
+            for x in [hidden_gates, input_bias, hidden_bias, prev_hidden]
+        ),
+        lambda: "expected all inputs to be same device",
+    )
+
+
+@register_meta(aten._thnn_fused_lstm_cell.default)
+def _thnn_fused_lstm_cell_meta(
+    input_gates,
+    hidden_gates,
+    cx,
+    input_bias=None,
+    hidden_bias=None,
+):
+    rnn_cell_checkSizes(input_gates, hidden_gates, input_bias, hidden_bias, 4, cx)
+    workspace = torch.empty_like(input_gates, memory_format=torch.contiguous_format)
+    hy = torch.empty_like(cx, memory_format=torch.contiguous_format)
+    cy = torch.empty_like(cx, memory_format=torch.contiguous_format)
+    return (hy, cy, workspace)
+
+
+@register_meta(aten._cudnn_rnn.default)
+def _cudnn_rnn(
+    input,
+    weight,
+    weight_stride0,
+    weight_buf,
+    hx,
+    cx,
+    mode,
+    hidden_size,
+    proj_size,
+    num_layers,
+    batch_first,
+    dropout,
+    train,
+    bidirectional,
+    batch_sizes,
+    dropout_state,
+):
+    is_input_packed = len(batch_sizes) != 0
+    if is_input_packed:
+        seq_length = len(batch_sizes)
+        mini_batch = batch_sizes[0]
+        batch_sizes_sum = input.shape[0]
+    else:
+        seq_length = input.shape[1] if batch_first else input.shape[0]
+        mini_batch = input.shape[0] if batch_first else input.shape[1]
+        batch_sizes_sum = -1
+
+    num_directions = 2 if bidirectional else 1
+    out_size = proj_size if proj_size != 0 else hidden_size
+    if is_input_packed:
+        out_shape = [batch_sizes_sum, out_size * num_directions]
+    else:
+        out_shape = (
+            [mini_batch, seq_length, out_size * num_directions]
+            if batch_first
+            else [seq_length, mini_batch, out_size * num_directions]
+        )
+    output = input.new_empty(out_shape)
+
+    cell_shape = [num_layers * num_directions, mini_batch, hidden_size]
+    if cx is None:
+        cy = torch.empty(0, device=input.device)
+    else:
+        cy = cx.new_empty(cell_shape)
+
+    hy = hx.new_empty([num_layers * num_directions, mini_batch, out_size])
+
+    # TODO: Query cudnnGetRNNTrainingReserveSize (expose to python)
+    reserve_shape = 0 if train else 0
+    reserve = input.new_empty(reserve_shape, dtype=torch.uint8)
+
+    return output, hy, cy, reserve, weight_buf
+
+
+@register_meta(aten.mkldnn_rnn_layer.default)
+def mkldnn_rnn_layer(
+    input,
+    w0,
+    w1,
+    w2,
+    w3,
+    hx_,
+    cx_,
+    reverse,
+    batch_sizes,
+    mode,
+    hidden_size,
+    num_layers,
+    has_biases,
+    bidirectional,
+    batch_first,
+    train,
+):
+    seq_length = input.shape[1] if batch_first else input.shape[0]
+    mini_batch = input.shape[0] if batch_first else input.shape[1]
+    output_chanels = hidden_size
+    out_shape = (
+        [mini_batch, seq_length, output_chanels]
+        if batch_first
+        else [seq_length, mini_batch, output_chanels]
+    )
+    output = input.new_empty(out_shape)
+    if hx_ is None:
+        hy = torch.empty(0, device=input.device)
+    else:
+        hy = hx_.new_empty(hx_.shape)
+    if cx_ is None:
+        cy = torch.empty(0, device=input.device)
+    else:
+        cy = cx_.new_empty(cx_.shape)
+    workspace = torch.empty(0, device=input.device, dtype=torch.uint8)
+    return output, hy, cy, workspace
+
+
+def zero_numel_check_dims(self, dim, fn_name):
+    if self.ndim == 0:
+        torch._check_index(
+            dim == 0 or dim == -1,
+            lambda: f"{fn_name}: Expected reduction dim -1 or 0 for scalar but got {dim}",
+        )
+    else:
+        torch._check_index(
+            self.size(dim) != 0,
+            lambda: f"{fn_name}: Expected reduction dim {dim} to have non-zero size.",
+        )
+
+
+# From aten/src/ATen/native/ReduceOps.cpp
+def check_argmax_argmin(name, self, dim):
+    if dim is not None:
+        dim = maybe_wrap_dim(dim, self.dim())
+        zero_numel_check_dims(self, dim, name)
+    else:
+        torch._check(
+            self.numel() != 0,
+            lambda: f"{name}: Expected reduction dim to be specified for input.numel() == 0.",
+        )
+
+
+@register_meta([aten.argmax.default, aten.argmin.default])
+def argmax_argmin_meta(self, dim=None, keepdim=False):
+    check_argmax_argmin("argmax", self, dim)
+    dims = utils.reduction_dims(self.shape, (dim,) if dim is not None else None)
+    shape = _compute_reduction_shape(self, dims, keepdim)
+    return self.new_empty(shape, dtype=torch.int64)
+
+
+@register_meta(aten.scalar_tensor.default)
+def scalar_tensor(s, dtype=None, layout=None, device=None, pin_memory=None):
+    # NB: It's always wrong to try to create a scalar tensor with the jagged layout.
+    # Rather than fix this everywhere, just use the strided layout and let NJT handle
+    # scalar tensor broadcasting.
+    if layout == torch.jagged:
+        layout = torch.strided
+    return torch.empty(
+        (), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
+    )
+
+
+@register_meta(aten.topk.default)
+def topk_meta(self, k, dim=-1, largest=True, sorted=True):
+    # From aten/src/ATen/native/Sorting.cpp
+    dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True)
+    sliceSize = 1 if self.dim() == 0 else self.size(dim)
+    torch._check_is_size(k)
+    torch._check(k <= sliceSize, lambda: "k not in range for dimension")
+
+    topKSize = list(self.shape)
+    if len(topKSize) > 0:
+        topKSize[dim] = k
+    return self.new_empty(topKSize), self.new_empty(topKSize, dtype=torch.int64)
+
+
+@register_meta(aten._segment_reduce_backward)
+@out_wrapper()
+def meta__segment_reduce_backward(
+    grad, output, data, reduce, lengths=None, offsets=None, axis=0, initial=None
+):
+    assert lengths is not None or offsets is not None, (
+        "segment_reduce(): Either lengths or offsets must be defined"
+    )
+    data_contig = data.contiguous()
+    grad_contig = grad.contiguous()
+    return torch.empty_like(
+        data_contig,
+        dtype=grad_contig.dtype,
+        device=grad_contig.device,
+        layout=grad_contig.layout,
+    )
+
+
+@register_meta([aten.kthvalue.default, aten.kthvalue.values])
+@out_wrapper("values", "indices")
+def kthvalue_meta(self, k, dim=-1, keepdim=False):
+    dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True)
+    dimSize = self.size(dim) if self.dim() > 0 else 1
+    torch._check(
+        k >= 1 and k <= dimSize,
+        lambda: f"kthvalue(): selected number k out of range for dimension {dim}",
+    )
+
+    shape = list(self.shape[:dim] + self.shape[dim + 1 :])
+    if keepdim and self.dim() > 0:
+        shape.insert(dim, 1)
+    return self.new_empty(shape), self.new_empty(shape, dtype=torch.int64)
+
+
+legacy_contiguous_memory_format = torch.contiguous_format
+
+
+# From aten/src/ATen/native/cuda/RNN.cu
+def checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace):
+    defined_grad = grad_hy if grad_hy is not None else grad_cy
+    torch._check(defined_grad.dim() == 2, lambda: "")
+    exp_size = defined_grad.size()
+    if grad_hy is not None:
+        torch._check(grad_hy.size() == exp_size, lambda: "")
+    if grad_cy is not None:
+        torch._check(grad_cy.size() == exp_size, lambda: "")
+    torch._check(cx.size() == exp_size, lambda: "")
+    torch._check(cy.size() == exp_size, lambda: "")
+    torch._check(workspace.dim() == 2, lambda: "")
+    torch._check(workspace.numel() == exp_size[0] * exp_size[1] * 4, lambda: "")
+
+
+# From aten/src/ATen/native/cuda/RNN.cu
+@register_meta(aten._thnn_fused_lstm_cell_backward_impl.default)
+def _thnn_fused_lstm_cell_backward_impl(grad_hy, grad_cy, cx, cy, workspace, has_bias):
+    if grad_hy is None and grad_cy is None:
+        return None, None, None
+    checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace)
+    grad_gates = torch.empty_like(
+        workspace, memory_format=legacy_contiguous_memory_format
+    )
+    grad_cx = torch.empty_like(cx, memory_format=legacy_contiguous_memory_format)
+    grad_bias = grad_gates.sum(0, keepdim=False) if has_bias else None
+    return grad_gates, grad_cx, grad_bias
+
+
+# From aten/src/ATen/native/mps/operations/Linear.mm
+@register_meta(aten.linear_backward.default)
+def linear_backward(input_, grad_output_, weight_, output_mask):
+    grad_input = None
+    grad_weight = None
+    grad_bias = None
+    if output_mask[0]:
+        grad_input = grad_output_.new_empty(input_.size())
+    if output_mask[1] or output_mask[2]:
+        grad_weight = grad_output_.new_empty((grad_output_.size(-1), input_.size(-1)))
+        grad_bias = grad_output_.new_empty(grad_output_.size(-1))
+    return (grad_input, grad_weight, grad_bias)
+
+
+@register_meta(aten.pixel_shuffle.default)
+def meta_pixel_shuffle(self, upscale_factor):
+    assert (
+        len(self.shape) > 2 and self.shape[-3] % (upscale_factor * upscale_factor) == 0
+    ), (
+        f"Invalid input shape for pixel_shuffle: {self.shape} with upscale_factor = {upscale_factor}"
+    )
+
+    def is_channels_last(ten):
+        return torch._prims_common.suggest_memory_format(ten) == torch.channels_last
+
+    def pick_memory_format():
+        if is_channels_last(self):
+            if device_hint(self) == "cuda":
+                return torch.contiguous_format
+            else:
+                return torch.channels_last
+        elif self.is_contiguous(memory_format=torch.contiguous_format):
+            return torch.contiguous_format
+        elif self.is_contiguous(memory_format=torch.preserve_format):
+            return torch.preserve_format
+
+    C = self.shape[-3] // (upscale_factor * upscale_factor)
+    Hr = self.shape[-2] * upscale_factor
+    Wr = self.shape[-1] * upscale_factor
+    out_shape = (*self.shape[:-3], C, Hr, Wr)
+
+    out = self.new_empty(out_shape)
+    out = out.to(memory_format=pick_memory_format())  # type: ignore[call-overload]
+    return out
+
+
+@register_meta(aten.mkldnn_rnn_layer_backward.default)
+def mkldnn_rnn_layer_backward(
+    input,
+    weight0,
+    weight1,
+    weight2,
+    weight3,
+    hx_,
+    cx_tmp,
+    output,
+    hy_,
+    cy_,
+    grad_output_r_opt,
+    grad_hy_r_opt,
+    grad_cy_r_opt,
+    reverse,
+    mode,
+    hidden_size,
+    num_layers,
+    has_biases,
+    train,
+    bidirectional,
+    batch_sizes,
+    batch_first,
+    workspace,
+):
+    diff_x = input.new_empty(input.shape)
+    diff_hx = hx_.new_empty(hx_.shape)
+    diff_cx = cx_tmp.new_empty(cx_tmp.shape)
+    diff_w1 = weight0.new_empty(weight0.shape)
+    diff_w2 = weight1.new_empty(weight1.shape)
+    diff_b = weight2.new_empty(weight2.shape)
+    return diff_x, diff_w1, diff_w2, diff_b, diff_b, diff_hx, diff_cx
+
+
+@register_meta([aten.bucketize.Tensor, aten.bucketize.Tensor_out])
+@out_wrapper()
+def meta_bucketize(self, boundaries, *, out_int32=False, right=False):
+    return torch.empty_like(
+        self,
+        dtype=torch.int32 if out_int32 else torch.int64,
+        memory_format=torch.contiguous_format,
+    )
+
+
+@register_meta([aten.histc])
+@out_wrapper()
+def meta_histc(input, bins=100, min=0, max=0):
+    fn_name = "histc()"
+    if device_hint(input) == "cpu":
+        torch._check(
+            input.is_floating_point(),
+            lambda: f"\"histogram_cpu\" not implemented for '{input.dtype}'",
+        )
+    torch._check(
+        isinstance(bins, IntLike),
+        lambda: f"{fn_name}: argument 'bins' must be int, not {type(bins)}",
+    )
+    torch._check(bins > 0, lambda: f"{fn_name}: bins must be > 0, but got {bins}")
+    torch._check(
+        isinstance(min, Number),
+        lambda: f"{fn_name}: argument 'min' must be Number, not {type(min)}",
+    )
+    torch._check(
+        isinstance(max, Number),
+        lambda: f"{fn_name}: argument 'max' must be Number, not {type(max)}",
+    )
+    torch._check(max >= min, lambda: "{fn_name}: max must be larger than min")
+    return torch.empty(bins, device=input.device, dtype=input.dtype)
+
+
+@register_meta(
+    [aten._upsample_bilinear2d_aa.default, aten._upsample_bicubic2d_aa.default]
+)
+def meta_upsample_bimode2d_aa(
+    input,
+    output_size,
+    align_corners,
+    scales_h=None,
+    scales_w=None,
+):
+    full_output_size = upsample_common_check(
+        input.size(), output_size, num_spatial_dims=2
+    )
+    torch._check(
+        input.numel() != 0 or all(size > 0 for size in input.size()[1:]),
+        lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}",
+    )
+    return input.new_empty(full_output_size).to(
+        memory_format=utils.suggest_memory_format(input)
+    )
+
+
+@register_meta([aten._upsample_bilinear2d_aa_backward.default])
+def meta_upsample_bimode2d_aa_backward(
+    grad_output,
+    output_size,
+    input_size,
+    align_corners,
+    scales_h=None,
+    scales_w=None,
+):
+    full_output_size = upsample_common_check(
+        input_size, output_size, num_spatial_dims=2
+    )
+    torch._check(
+        grad_output.ndim == 4,
+        lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}",
+    )
+    for i in range(4):
+        torch._check(
+            grad_output.shape[i] == full_output_size[i],
+            lambda: f"""
+Expected grad_output to have the same shape as output; output.size({i}) = {full_output_size[i]}
+but got grad_output_size({i}) = {grad_output.size(i)}""",
+        )
+    return grad_output.new_empty(input_size).to(
+        memory_format=utils.suggest_memory_format(grad_output)
+    )
+
+
+# From aten/src/ATen/native/cuda/AmpKernels.cu
+@register_meta(aten._amp_foreach_non_finite_check_and_unscale_.default)
+def _amp_foreach_non_finite_check_and_unscale_(self, found_inf, inv_scale):
+    torch._check(
+        found_inf.numel() == 1, lambda: "found_inf must be a 1-element tensor."
+    )
+    torch._check(
+        inv_scale.numel() == 1, lambda: "inv_scale must be a 1-element tensor."
+    )
+    torch._check(
+        found_inf.dtype.is_floating_point,
+        lambda: "found_inf must be a float tensor.",
+    )
+    torch._check(
+        inv_scale.dtype.is_floating_point,
+        lambda: "inv_scale must be a float tensor.",
+    )
+
+
+# From aten/src/ATen/native/UnaryOps.cpp
+@register_meta([aten.nan_to_num.default, aten.nan_to_num.out])
+@out_wrapper()
+def nan_to_num(self, nan=None, posinf=None, neginf=None):
+    result_size = list(self.size())
+    return self.new_empty(result_size)
+
+
+@register_meta(torch.ops.aten.transpose_)
+def transpose_(self, dim0, dim1):
+    assert self.layout not in {
+        torch.sparse_csr,
+        torch.sparse_csc,
+        torch.sparse_bsr,
+        torch.sparse_bsc,
+    }, (
+        f"torch.transpose_: in-place transposition is not supported for {self.layout} layout"
+    )
+
+    ndims = self.ndim
+
+    dim0 = maybe_wrap_dim(dim0, ndims)
+    dim1 = maybe_wrap_dim(dim1, ndims)
+
+    if dim0 == dim1:
+        return self
+
+    size = list(self.size())
+    stride = list(self.stride())
+
+    stride[dim0], stride[dim1] = stride[dim1], stride[dim0]
+    size[dim0], size[dim1] = size[dim1], size[dim0]
+
+    self.as_strided_(size, stride)
+    return self
+
+
+@register_meta(torch.ops.aten.t_)
+def t_(self):
+    ndims = self.ndim
+
+    if self.is_sparse:
+        sparse_dim = self.sparse_dim()
+        dense_dim = self.dense_dim()
+        assert sparse_dim <= 2 and dense_dim == 0, (
+            f"t_ expects a tensor with <= 2 sparse and 0 dense dimensions, "
+            f"but got {sparse_dim} sparse and {dense_dim} dense dimensions"
+        )
+    else:
+        assert self.dim() <= 2, (
+            f"t_ expects a tensor with <= 2 dimensions, but self is {ndims}D"
+        )
+
+    return transpose_(self, 0, 0 if ndims < 2 else 1)
+
+
+@register_meta(aten.searchsorted)
+@out_wrapper()
+def meta_searchsorted(
+    sorted_sequence,
+    self,
+    *,
+    out_int32=False,
+    right=False,
+    side=None,
+    sorter=None,
+):
+    # If the sorted_sequence is not one-dimensional, its shape must match that of values
+    # in all but the last dimension.
+    torch._check(
+        len(sorted_sequence.shape) <= 1
+        or sorted_sequence.shape[:-1] == self.shape[:-1],
+        lambda: (
+            "torch.searchsorted(): boundaries tensor should be 1 dimension or the "
+            "first N-1 dimensions of boundaries tensor and input value tensor must "
+            f"match, but we got boundaries tensor {list(sorted_sequence.shape)} and "
+            f"input value tensor {list(self.shape)}"
+        ),
+    )
+
+    # If a sorter array is provided, its dimensions must exactly match sorted_sequence.
+    torch._check(
+        sorter is None or sorted_sequence.shape == sorter.shape,
+        lambda: (
+            "torch.searchsorted(): boundary and sorter must have the same size, but "
+            f"got boundary tensor {list(sorted_sequence.shape)} and got sorter tensor "
+            f"{list(sorter.shape) if sorter is not None else []}"
+        ),
+    )
+
+    # Per the docs, if side == "left" and right is True, we error.
+    torch._check(
+        side != "left" or not right,
+        "torch.searchsorted(): side and right can't be set to opposites, got side of "
+        "left while right was True",
+    )
+
+    dtype = torch.int32 if out_int32 else torch.int64
+    if isinstance(self, torch.Tensor):
+        return torch.empty_like(
+            self, dtype=dtype, memory_format=torch.contiguous_format
+        )
+    else:  # Scalar
+        return torch.empty((), dtype=dtype, device=sorted_sequence.device)
+
+
+def _check_for_unsupported_isin_dtype(dtype):
+    torch._check(
+        dtype not in (torch.bool, torch.complex128, torch.complex64),
+        lambda: f"Unsupported input type encountered for isin(): {dtype}",
+    )
+
+
+@register_meta(aten._embedding_bag_backward)
+def meta_embedding_bag_backward(
+    grad,
+    indices,
+    offsets,
+    offset2bag,
+    bag_size,
+    maximum_indices,
+    num_weights,
+    scale_grad_by_freq,
+    mode,
+    sparse,
+    per_sample_weights,
+    padding_idx=-1,
+):
+    if sparse:
+        return aten._embedding_bag_sparse_backward(
+            grad,
+            indices,
+            offsets,
+            offset2bag,
+            bag_size,
+            num_weights,
+            scale_grad_by_freq,
+            mode,
+            per_sample_weights,
+            padding_idx,
+        )
+    else:
+        return meta_embedding_bag_dense_backward(
+            grad,
+            indices,
+            offset2bag,
+            bag_size,
+            maximum_indices,
+            num_weights,
+            scale_grad_by_freq,
+            mode,
+            per_sample_weights,
+            padding_idx,
+        )
+
+
+@register_meta(aten._embedding_bag_dense_backward)
+def meta_embedding_bag_dense_backward(
+    grad,
+    indices,
+    offset2bag,
+    bag_size,
+    maximum_indices,
+    num_weights,
+    scale_grad_by_freq,
+    mode,
+    per_sample_weights,
+    padding_idx=-1,
+):
+    torch._check(
+        grad.dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64],
+        lambda: f"Unsupported input type encountered: {grad.dtype}",
+    )
+    if mode == MODE_MAX:
+        torch._check(maximum_indices is not None)
+    index_grad_weight = grad.new_empty((num_weights, grad.size(1)))
+    return index_grad_weight
+
+
+@register_meta(aten._embedding_bag_per_sample_weights_backward)
+def meta_embedding_bag_per_sample_weights_backward(
+    grad,
+    weight,
+    indices,
+    offsets,
+    offset2bag,
+    mode,
+    padding_idx=-1,
+):
+    embedding_features = grad.size(1)
+    torch._check(
+        mode == MODE_SUM,
+        "embedding_bag_backward: per_sample_weights only supported for mode='sum'",
+    )
+    torch._check(grad.dim() == 2)
+    torch._check(indices.dim() == 1)
+    num_samples = indices.size(0)
+    torch._check(weight.dim() == 2)
+    torch._check(weight.size(1) == embedding_features)
+    output = grad.new_empty((num_samples,))
+    return output
+
+
+@register_meta(aten.isin)
+@out_wrapper()
+def meta_isin(elements, test_elements, *, assume_unique=False, invert=False):
+    torch._check(
+        isinstance(elements, Tensor) or isinstance(test_elements, Tensor),
+        lambda: "At least one of elements and test_elements must be a Tensor.",
+    )
+    if not isinstance(elements, Tensor):
+        elements = torch.tensor(elements, device=test_elements.device)
+
+    if not isinstance(test_elements, Tensor):
+        test_elements = torch.tensor(test_elements, device=elements.device)
+
+    _check_for_unsupported_isin_dtype(elements.dtype)
+    _check_for_unsupported_isin_dtype(test_elements.dtype)
+    return torch.empty_like(elements, dtype=torch.bool)
+
+
+@register_meta(aten.polygamma)
+@out_wrapper()
+def meta_polygamma(n: int, self: Tensor) -> Tensor:
+    torch._check(n >= 0, lambda: "polygamma(n, x) does not support negative n.")
+    _, result_dtype = elementwise_dtypes(
+        self,
+        type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
+    )
+    return torch.empty_like(self, dtype=result_dtype)
+
+
+@register_meta(aten._local_scalar_dense)
+def meta_local_scalar_dense(self: Tensor):
+    raise RuntimeError("Tensor.item() cannot be called on meta tensors")
+
+
+@register_meta(aten.silu)
+@out_wrapper(exact_dtype=True)
+def silu(self: Tensor) -> Tensor:
+    return torch.empty_like(self)
+
+
+@register_meta(aten.sigmoid)
+@out_wrapper()
+def sigmoid(self: Tensor) -> Tensor:
+    _, result_dtype = elementwise_dtypes(
+        self,
+        type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
+    )
+    return torch.empty_like(self, dtype=result_dtype)
+
+
+@register_meta(aten._softmax)
+@out_wrapper()
+def softmax(x: Tensor, dim: int, half_to_float: bool) -> Tensor:
+    if half_to_float:
+        assert x.dtype == torch.half
+    computation_dtype, result_dtype = utils.elementwise_dtypes(
+        x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+    result_dtype = result_dtype if not half_to_float else computation_dtype
+    res = torch.empty_like(x, dtype=result_dtype, memory_format=torch.contiguous_format)
+    return res
+
+
+@register_meta(aten.embedding)
+@out_wrapper()
+def embedding(
+    weight: Tensor,
+    indices: Tensor,
+    padding_idx: int = -1,
+    scale_grad_by_freq: bool = False,
+    sparse: bool = False,
+) -> Tensor:
+    assert weight.dim() == 2, "'weight' must be 2-D"
+    weight_shape = weight.shape
+    indices_shape = indices.shape
+
+    if indices.ndim == 0:
+        out_shape: tuple[int, ...] = (weight_shape[1],)
+    elif indices.ndim == 1:
+        out_shape = (indices_shape[0], weight_shape[1])
+    else:
+        out_shape = (*indices_shape, weight_shape[1])
+
+    out_dtype = weight.dtype
+    return weight.new_empty(out_shape, dtype=out_dtype)
+
+
+@register_meta(aten._jagged_to_padded_dense_forward.default)
+def meta__jagged_to_padded_dense_forward(
+    values: Tensor,
+    offsets: list[Tensor],
+    max_lengths: list[int],
+    padding_value: float = 0.0,
+):
+    # only one jagged dim is supported for now
+    assert len(offsets) == 1
+    assert len(max_lengths) == 1
+
+    B = offsets[0].shape[0] - 1
+    S = max_lengths[0]
+    output_shape = (B, S, *values.shape[1:])
+    return values.new_empty(output_shape)
+
+
+def _create_unary_float_meta_func(func):
+    @register_meta(func)
+    @out_wrapper()
+    def _f(x):
+        return elementwise_meta(
+            x, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
+        )
+
+    return _f
+
+
+def _create_binary_float_meta_func(func):
+    @register_meta(func)
+    @out_wrapper()
+    def _f(x, y):
+        return elementwise_meta(
+            x, y, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
+        )
+
+    return _f
+
+
+_create_unary_float_meta_func(aten.special_airy_ai)
+_create_unary_float_meta_func(aten.special_bessel_y0)
+_create_unary_float_meta_func(aten.special_bessel_y1)
+_create_unary_float_meta_func(aten.special_modified_bessel_i0)
+_create_unary_float_meta_func(aten.special_modified_bessel_i1)
+_create_unary_float_meta_func(aten.special_modified_bessel_k0)
+_create_unary_float_meta_func(aten.special_modified_bessel_k1)
+_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k0)
+_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k1)
+
+
+_create_binary_float_meta_func(aten.special_chebyshev_polynomial_t)
+_create_binary_float_meta_func(aten.special_chebyshev_polynomial_u)
+_create_binary_float_meta_func(aten.special_chebyshev_polynomial_v)
+_create_binary_float_meta_func(aten.special_chebyshev_polynomial_w)
+_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_t)
+_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_u)
+_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_v)
+_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_w)
+_create_binary_float_meta_func(aten.special_hermite_polynomial_h)
+_create_binary_float_meta_func(aten.special_hermite_polynomial_he)
+_create_binary_float_meta_func(aten.special_laguerre_polynomial_l)
+_create_binary_float_meta_func(aten.special_legendre_polynomial_p)
+
+
+def _register_inplace_meta(fn):
+    @wraps(fn)
+    def _fn(self, *args, **kwargs):
+        out = fn(self, *args, **kwargs)
+        check_inplace_broadcast(self.shape, out.shape)
+        return self
+
+    inplace_name = f"{fn.__name__}_"
+    _fn.__name__ = inplace_name
+    _fn = register_meta(getattr(aten, inplace_name))(_fn)  # type: ignore[assignment]
+
+    return _fn
+
+
+@register_meta(aten.lerp)
+@out_wrapper()
+def lerp(start, end, weight):
+    torch._check(
+        start.dtype == end.dtype,
+        lambda: f"expected dtype {start.dtype} for `end`, but got dtype {end.dtype}",
+    )
+    args = [start, end]
+    if isinstance(weight, TensorLike):
+        if weight.ndim != 0:
+            torch._check(
+                start.dtype == weight.dtype,
+                lambda: f"expected dtype {start.dtype} for `weight`, but got dtype {weight.dtype}",
+            )
+        args.append(weight)
+    return elementwise_meta(
+        *args, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+@register_meta(aten.addcmul)
+@out_wrapper()
+def addcmul(input, tensor1, tensor2, *, value=1):
+    return elementwise_meta(
+        input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+@register_meta(aten.addcdiv)
+@out_wrapper()
+def addcdiv(input, tensor1, tensor2, *, value=1):
+    torch._check(
+        not (
+            utils.is_integer_dtype(tensor1.dtype)
+            and utils.is_integer_dtype(tensor2.dtype)
+        ),
+        lambda: (
+            "Integer division with addcdiv is no longer supported, and in a future ",
+            "release addcdiv will perform a true division of tensor1 and tensor2. ",
+            "The historic addcdiv behavior can be implemented as ",
+            "(input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) ",
+            "for integer inputs and as ",
+            "(input + value * tensor1 / tensor2) for float inputs. ",
+            "The future addcdiv behavior is just the latter implementation: ",
+            "(input + value * tensor1 / tensor2), for all dtypes.",
+        ),
+    )
+    return elementwise_meta(
+        input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
+    )
+
+
+lerp_ = _register_inplace_meta(aten.lerp)
+addcmul_ = _register_inplace_meta(aten.addcmul)
+addcdiv_ = _register_inplace_meta(aten.addcdiv)
+
+
+# We must also trigger meta registrations from PrimTorch ref
+# decompositions
+import torch._refs
+import torch._refs.nn.functional
+import torch._refs.special
+
+
+def activate_meta():
+    activate_meta_table = {}
+
+    # For a given op, we pick the most specific decomp function from
+    # global_decomp_table in the precedence order of meta > post_autograd > pre_autograd
+    for type in ["meta", "post_autograd", "pre_autograd"]:
+        registry = global_decomposition_table[type]
+
+        for opo in registry:
+            if opo not in activate_meta_table:
+                activate_meta_table[opo] = registry[opo]
+
+    for op_overload, fn in activate_meta_table.items():
+        # Don't register meta for HigherOrderOp's decomp.
+        # We can reconsider this in the future, but in general,
+        # the way you do a meta for a HigherOrderOp is different from
+        # OpOverload.
+        if isinstance(op_overload, torch._ops.HigherOrderOperator):
+            continue
+        assert isinstance(op_overload, OpOverload)
+
+        op_overload.py_impl(torch._C.DispatchKey.Meta)(fn)
+
+        if torch._C._dispatch_has_kernel_for_dispatch_key(
+            op_overload.name(), "CompositeImplicitAutograd"
+        ):
+            # Internally, we shouldn't be registering meta kernels for any operators that
+            # have CompositeImplicitAutograd kernels.
+            # Instead, we should be letting those decompositions run, and writing meta kernels
+            # only for the base operators.
+            if op_overload in global_decomposition_table["meta"]:
+                raise RuntimeError(
+                    f"{op_overload} is a CompositeImplicitAutograd op, we shouldn't "
+                    "register meta function for it. Instead, we should let the decomposition run and write "
+                    "meta kernels for the base operators."
+                )
+        elif op_overload.is_view:
+            # Attempting to register a python meta kernel for a view operator.
+            # We shouldn't do this, because the output will report as not having aliased storages.
+            # All view ops have meta kernels in C++ today, so we should use those instead.
+            pass
+        elif (
+            op_overload.name()
+            in {
+                "aten::empty_strided",  # causing infinite recursion, test_meta.py
+                "aten::clone",  # causing infinite recursion
+                "aten::_to_copy",  # causing infinite recursion, test_serialization.py -k test_tensor_subclass_getstate_overwrite  # noqa: B950
+                "aten::copy_",  # Exception not raised, test_torch.py -k test_storage_meta_errors_cpu_int64  # noqa: B950
+                "aten::constant_pad_nd",  # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_amp_istft_cuda_float32  # noqa: B950
+                "aten::rot90",  # requires_grad mismatch! test_ops.py -k test_fake_crossref_backward_amp_rot90_cuda_float32  # noqa: B950
+                "aten::as_strided_scatter",  # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_no_amp_as_strided_scatter_cuda_float32  # noqa: B950
+            }
+        ):
+            pass
+        else:
+            if "mkldnn::" in op_overload.name():
+                _meta_lib_dont_use_me_use_register_meta_for_mkldnn.impl(op_overload, fn)
+            elif "mkl::" in op_overload.name():
+                _meta_lib_dont_use_me_use_register_meta_for_mkl.impl(op_overload, fn)
+            elif "onednn::" in op_overload.name():
+                _meta_lib_dont_use_me_use_register_meta_for_onednn.impl(op_overload, fn)
+            elif "quantized::" in op_overload.name():
+                _meta_lib_dont_use_me_use_register_meta_for_quantized.impl(
+                    op_overload, fn
+                )
+            else:
+                _meta_lib_dont_use_me_use_register_meta.impl(op_overload, fn)
+
+
+activate_meta()
diff --git a/shared/package-files/b9/b9866551386d7596453396f5159b21b1e632bbcec8dcdcc129acf5ae9e851b1d/_embedding_bag_backward_ops.h b/shared/package-files/b9/b9866551386d7596453396f5159b21b1e632bbcec8dcdcc129acf5ae9e851b1d/_embedding_bag_backward_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..78f991c4c20562db95b4aa56d14a1aa0997478c4
--- /dev/null
+++ b/shared/package-files/b9/b9866551386d7596453396f5159b21b1e632bbcec8dcdcc129acf5ae9e851b1d/_embedding_bag_backward_ops.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _embedding_bag_backward {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymInt, bool, int64_t, bool, const ::std::optional &, int64_t);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_embedding_bag_backward";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor";
+  static at::Tensor call(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, int64_t padding_idx);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, int64_t padding_idx);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b98a1182da495bb47d56026de3f4f1992c592f87e4d91a43094105c6a84fd963/prod_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/b9/b98a1182da495bb47d56026de3f4f1992c592f87e4d91a43094105c6a84fd963/prod_compositeexplicitautogradnonfunctional_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..104a51d6d31322e32c4036d31e861f73220f5797
--- /dev/null
+++ b/shared/package-files/b9/b98a1182da495bb47d56026de3f4f1992c592f87e4d91a43094105c6a84fd963/prod_compositeexplicitautogradnonfunctional_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautogradnonfunctional {
+
+TORCH_API at::Tensor prod(const at::Tensor & self, int64_t dim, bool keepdim=false, ::std::optional dtype=::std::nullopt);
+
+} // namespace compositeexplicitautogradnonfunctional
+} // namespace at
diff --git a/shared/package-files/b9/b9931eb55c31e4a4ba182b8546323e4e7be4c449f345097fbbbf97ff627a732c/_fused_dropout_cuda_dispatch.h b/shared/package-files/b9/b9931eb55c31e4a4ba182b8546323e4e7be4c449f345097fbbbf97ff627a732c/_fused_dropout_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..2993f6a6283355a4dce8620963f08bcfd249093d
--- /dev/null
+++ b/shared/package-files/b9/b9931eb55c31e4a4ba182b8546323e4e7be4c449f345097fbbbf97ff627a732c/_fused_dropout_cuda_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API ::std::tuple _fused_dropout(const at::Tensor & self, double p, ::std::optional generator=::std::nullopt);
+
+} // namespace cuda
+} // namespace at
diff --git a/shared/package-files/b9/b993faabaca56c0b4593254348046cde95a61be81b93e93a7c2c06f5f0c0a4c0/python_nn_functions.h b/shared/package-files/b9/b993faabaca56c0b4593254348046cde95a61be81b93e93a7c2c06f5f0c0a4c0/python_nn_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..2fc4f4727e39e7dbaa8ee277dc944562c6110984
--- /dev/null
+++ b/shared/package-files/b9/b993faabaca56c0b4593254348046cde95a61be81b93e93a7c2c06f5f0c0a4c0/python_nn_functions.h
@@ -0,0 +1,7 @@
+#pragma once
+#include 
+namespace torch::autograd {
+
+void initNNFunctions(PyObject* module);
+
+}
diff --git a/shared/package-files/b9/b9944e71af25aa218e7f91082e80148df6a55a8514e42b6c7a2138ea5ff79644/asyn_wrapper.py b/shared/package-files/b9/b9944e71af25aa218e7f91082e80148df6a55a8514e42b6c7a2138ea5ff79644/asyn_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7e885b2409d890644b57dc4e7faf820642585a5
--- /dev/null
+++ b/shared/package-files/b9/b9944e71af25aa218e7f91082e80148df6a55a8514e42b6c7a2138ea5ff79644/asyn_wrapper.py
@@ -0,0 +1,114 @@
+import asyncio
+import functools
+import inspect
+
+import fsspec
+from fsspec.asyn import AsyncFileSystem, running_async
+
+
+def async_wrapper(func, obj=None):
+    """
+    Wraps a synchronous function to make it awaitable.
+
+    Parameters
+    ----------
+    func : callable
+        The synchronous function to wrap.
+    obj : object, optional
+        The instance to bind the function to, if applicable.
+
+    Returns
+    -------
+    coroutine
+        An awaitable version of the function.
+    """
+
+    @functools.wraps(func)
+    async def wrapper(*args, **kwargs):
+        return await asyncio.to_thread(func, *args, **kwargs)
+
+    return wrapper
+
+
+class AsyncFileSystemWrapper(AsyncFileSystem):
+    """
+    A wrapper class to convert a synchronous filesystem into an asynchronous one.
+
+    This class takes an existing synchronous filesystem implementation and wraps all
+    its methods to provide an asynchronous interface.
+
+    Parameters
+    ----------
+    sync_fs : AbstractFileSystem
+        The synchronous filesystem instance to wrap.
+    """
+
+    protocol = "asyncwrapper", "async_wrapper"
+    cachable = False
+
+    def __init__(
+        self,
+        fs=None,
+        asynchronous=None,
+        target_protocol=None,
+        target_options=None,
+        **kwargs,
+    ):
+        if asynchronous is None:
+            asynchronous = running_async()
+        super().__init__(asynchronous=asynchronous, **kwargs)
+        if fs is not None:
+            self.sync_fs = fs
+        else:
+            self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
+        self.protocol = self.sync_fs.protocol
+        self._wrap_all_sync_methods()
+
+    @property
+    def fsid(self):
+        return f"async_{self.sync_fs.fsid}"
+
+    def _wrap_all_sync_methods(self):
+        """
+        Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
+        """
+        excluded_methods = {"open"}
+        for method_name in dir(self.sync_fs):
+            if method_name.startswith("_") or method_name in excluded_methods:
+                continue
+
+            attr = inspect.getattr_static(self.sync_fs, method_name)
+            if isinstance(attr, property):
+                continue
+
+            method = getattr(self.sync_fs, method_name)
+            if callable(method) and not asyncio.iscoroutinefunction(method):
+                async_method = async_wrapper(method, obj=self)
+                setattr(self, f"_{method_name}", async_method)
+
+    @classmethod
+    def wrap_class(cls, sync_fs_class):
+        """
+        Create a new class that can be used to instantiate an AsyncFileSystemWrapper
+        with lazy instantiation of the underlying synchronous filesystem.
+
+        Parameters
+        ----------
+        sync_fs_class : type
+            The class of the synchronous filesystem to wrap.
+
+        Returns
+        -------
+        type
+            A new class that wraps the provided synchronous filesystem class.
+        """
+
+        class GeneratedAsyncFileSystemWrapper(cls):
+            def __init__(self, *args, **kwargs):
+                sync_fs = sync_fs_class(*args, **kwargs)
+                super().__init__(sync_fs)
+
+        GeneratedAsyncFileSystemWrapper.__name__ = (
+            f"Async{sync_fs_class.__name__}Wrapper"
+        )
+        return GeneratedAsyncFileSystemWrapper
diff --git a/shared/package-files/b9/b995b4dded78d69fbe035e8eb78600ba0052de1eb20211253da4324d22409f32/test_pip_install_sdist.py b/shared/package-files/b9/b995b4dded78d69fbe035e8eb78600ba0052de1eb20211253da4324d22409f32/test_pip_install_sdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2f1c080038bfd9c6db545ddfe5e9dd634d4147c
--- /dev/null
+++ b/shared/package-files/b9/b995b4dded78d69fbe035e8eb78600ba0052de1eb20211253da4324d22409f32/test_pip_install_sdist.py
@@ -0,0 +1,223 @@
+# https://github.com/python/mypy/issues/16936
+# mypy: disable-error-code="has-type"
+"""Integration tests for setuptools that focus on building packages via pip.
+
+The idea behind these tests is not to exhaustively check all the possible
+combinations of packages, operating systems, supporting libraries, etc, but
+rather check a limited number of popular packages and how they interact with
+the exposed public API. This way if any change in API is introduced, we hope to
+identify backward compatibility problems before publishing a release.
+
+The number of tested packages is purposefully kept small, to minimise duration
+and the associated maintenance cost (changes in the way these packages define
+their build process may require changes in the tests).
+"""
+
+import json
+import os
+import shutil
+import sys
+from enum import Enum
+from glob import glob
+from hashlib import md5
+from urllib.request import urlopen
+
+import pytest
+from packaging.requirements import Requirement
+
+from .helpers import Archive, run
+
+pytestmark = pytest.mark.integration
+
+
+(LATEST,) = Enum("v", "LATEST")  # type: ignore[misc] # https://github.com/python/mypy/issues/16936
+"""Default version to be checked"""
+# There are positive and negative aspects of checking the latest version of the
+# packages.
+# The main positive aspect is that the latest version might have already
+# removed the use of APIs deprecated in previous releases of setuptools.
+
+
+# Packages to be tested:
+# (Please notice the test environment cannot support EVERY library required for
+# compiling binary extensions. In Ubuntu/Debian nomenclature, we only assume
+# that `build-essential`, `gfortran` and `libopenblas-dev` are installed,
+# due to their relevance to the numerical/scientific programming ecosystem)
+EXAMPLES = [
+    ("pip", LATEST),  # just in case...
+    ("pytest", LATEST),  # uses setuptools_scm
+    ("mypy", LATEST),  # custom build_py + ext_modules
+    # --- Popular packages: https://hugovk.github.io/top-pypi-packages/ ---
+    ("botocore", LATEST),
+    ("kiwisolver", LATEST),  # build_ext
+    ("brotli", LATEST),  # not in the list but used by urllib3
+    ("pyyaml", LATEST),  # cython + custom build_ext + custom distclass
+    ("charset-normalizer", LATEST),  # uses mypyc, used by aiohttp
+    ("protobuf", LATEST),
+    ("requests", LATEST),
+    ("celery", LATEST),
+    # When adding packages to this list, make sure they expose a `__version__`
+    # attribute, or modify the tests below
+]
+
+
+# Some packages have "optional" dependencies that modify their build behaviour
+# and are not listed in pyproject.toml, others still use `setup_requires`
+EXTRA_BUILD_DEPS = {
+    "pyyaml": ("Cython<3.0",),  # constraint to avoid errors
+    "charset-normalizer": ("mypy>=1.4.1",),  # no pyproject.toml available
+}
+
+EXTRA_ENV_VARS = {
+    "pyyaml": {"PYYAML_FORCE_CYTHON": "1"},
+    "charset-normalizer": {"CHARSET_NORMALIZER_USE_MYPYC": "1"},
+}
+
+IMPORT_NAME = {
+    "pyyaml": "yaml",
+    "protobuf": "google.protobuf",
+}
+
+
+VIRTUALENV = (sys.executable, "-m", "virtualenv")
+
+
+# By default, pip will try to build packages in isolation (PEP 517), which
+# means it will download the previous stable version of setuptools.
+# `pip` flags can avoid that (the version of setuptools under test
+# should be the one to be used)
+INSTALL_OPTIONS = (
+    "--ignore-installed",
+    "--no-build-isolation",
+    # Omit "--no-binary :all:" the sdist is supplied directly.
+    # Allows dependencies as wheels.
+)
+# The downside of `--no-build-isolation` is that pip will not download build
+# dependencies. The test script will have to also handle that.
+
+
+@pytest.fixture
+def venv_python(tmp_path):
+    run([*VIRTUALENV, str(tmp_path / ".venv")])
+    possible_path = (str(p.parent) for p in tmp_path.glob(".venv/*/python*"))
+    return shutil.which("python", path=os.pathsep.join(possible_path))
+
+
+@pytest.fixture(autouse=True)
+def _prepare(tmp_path, venv_python, monkeypatch):
+    download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path))
+    os.makedirs(download_path, exist_ok=True)
+
+    # Environment vars used for building some of the packages
+    monkeypatch.setenv("USE_MYPYC", "1")
+
+    yield
+
+    # Let's provide the maximum amount of information possible in the case
+    # it is necessary to debug the tests directly from the CI logs.
+    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
+    print("Temporary directory:")
+    map(print, tmp_path.glob("*"))
+    print("Virtual environment:")
+    run([venv_python, "-m", "pip", "freeze"])
+
+
+@pytest.mark.parametrize(("package", "version"), EXAMPLES)
+@pytest.mark.uses_network
+def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel):
+    venv_pip = (venv_python, "-m", "pip")
+    sdist = retrieve_sdist(package, version, tmp_path)
+    deps = build_deps(package, sdist)
+    if deps:
+        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
+        print("Dependencies:", deps)
+        run([*venv_pip, "install", *deps])
+
+    # Use a virtualenv to simulate PEP 517 isolation
+    # but install fresh setuptools wheel to ensure the version under development
+    env = EXTRA_ENV_VARS.get(package, {})
+    run([*venv_pip, "install", "--force-reinstall", setuptools_wheel])
+    run([*venv_pip, "install", *INSTALL_OPTIONS, sdist], env)
+
+    # Execute a simple script to make sure the package was installed correctly
+    pkg = IMPORT_NAME.get(package, package).replace("-", "_")
+    script = f"import {pkg}; print(getattr({pkg}, '__version__', 0))"
+    run([venv_python, "-c", script])
+
+
+# ---- Helper Functions ----
+
+
+def retrieve_sdist(package, version, tmp_path):
+    """Either use cached sdist file or download it from PyPI"""
+    # `pip download` cannot be used due to
+    # https://github.com/pypa/pip/issues/1884
+    # https://discuss.python.org/t/pep-625-file-name-of-a-source-distribution/4686
+    # We have to find the correct distribution file and download it
+    download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path))
+    dist = retrieve_pypi_sdist_metadata(package, version)
+
+    # Remove old files to prevent cache to grow indefinitely
+    for file in glob(os.path.join(download_path, f"{package}*")):
+        if dist["filename"] != file:
+            os.unlink(file)
+
+    dist_file = os.path.join(download_path, dist["filename"])
+    if not os.path.exists(dist_file):
+        download(dist["url"], dist_file, dist["md5_digest"])
+    return dist_file
+
+
+def retrieve_pypi_sdist_metadata(package, version):
+    # https://warehouse.pypa.io/api-reference/json.html
+    id_ = package if version is LATEST else f"{package}/{version}"
+    with urlopen(f"https://pypi.org/pypi/{id_}/json") as f:
+        metadata = json.load(f)
+
+    if metadata["info"]["yanked"]:
+        raise ValueError(f"Release for {package} {version} was yanked")
+
+    version = metadata["info"]["version"]
+    release = metadata["releases"][version] if version is LATEST else metadata["urls"]
+    (sdist,) = filter(lambda d: d["packagetype"] == "sdist", release)
+    return sdist
+
+
+def download(url, dest, md5_digest):
+    with urlopen(url) as f:
+        data = f.read()
+
+    assert md5(data).hexdigest() == md5_digest
+
+    with open(dest, "wb") as f:
+        f.write(data)
+
+    assert os.path.exists(dest)
+
+
+def build_deps(package, sdist_file):
+    """Find out what are the build dependencies for a package.
+
+    "Manually" install them, since pip will not install build
+    deps with `--no-build-isolation`.
+    """
+    # delay importing, since pytest discovery phase may hit this file from a
+    # testenv without tomli
+    from setuptools.compat.py310 import tomllib
+
+    archive = Archive(sdist_file)
+    info = tomllib.loads(_read_pyproject(archive))
+    deps = info.get("build-system", {}).get("requires", [])
+    deps += EXTRA_BUILD_DEPS.get(package, [])
+    # Remove setuptools from requirements (and deduplicate)
+    requirements = {Requirement(d).name: d for d in deps}
+    return [v for k, v in requirements.items() if k != "setuptools"]
+
+
+def _read_pyproject(archive):
+    contents = (
+        archive.get_content(member)
+        for member in archive
+        if os.path.basename(archive.get_name(member)) == "pyproject.toml"
+    )
+    return next(contents, "")
diff --git a/shared/package-files/b9/b9a8cfcd93867a4bdc14f0e4b2418f7a05ed5a351391bd1e719737f9c798567b/special_gammainc.h b/shared/package-files/b9/b9a8cfcd93867a4bdc14f0e4b2418f7a05ed5a351391bd1e719737f9c798567b/special_gammainc.h
new file mode 100644
index 0000000000000000000000000000000000000000..7f34d6d59db543cff9a77f6c6b6c5c9f4fe9a379
--- /dev/null
+++ b/shared/package-files/b9/b9a8cfcd93867a4bdc14f0e4b2418f7a05ed5a351391bd1e719737f9c798567b/special_gammainc.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & special_gammainc_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::special_gammainc_out::call(self, other, out);
+}
+// aten::special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & special_gammainc_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) {
+    return at::_ops::special_gammainc_out::call(self, other, out);
+}
+
+// aten::special_gammainc(Tensor self, Tensor other) -> Tensor
+inline at::Tensor special_gammainc(const at::Tensor & self, const at::Tensor & other) {
+    return at::_ops::special_gammainc::call(self, other);
+}
+
+}
diff --git a/shared/package-files/b9/b9ab38a682eb56410b692be655a8420f6c99d01b11e28360bf663f75de87afbe/offsets.cpython-311.pyc b/shared/package-files/b9/b9ab38a682eb56410b692be655a8420f6c99d01b11e28360bf663f75de87afbe/offsets.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92eb8946a53a923191420496422904d06f25a2ea
Binary files /dev/null and b/shared/package-files/b9/b9ab38a682eb56410b692be655a8420f6c99d01b11e28360bf663f75de87afbe/offsets.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9ab51b07ee28e926a1e59653d1de754421c5888e0d643266ea08d90236b55a4/__init__.cpython-311.pyc b/shared/package-files/b9/b9ab51b07ee28e926a1e59653d1de754421c5888e0d643266ea08d90236b55a4/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1567790c630da58a9ec7ecb5737a40efb331e5c
Binary files /dev/null and b/shared/package-files/b9/b9ab51b07ee28e926a1e59653d1de754421c5888e0d643266ea08d90236b55a4/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9ae2a050026fa08bddb79514713a001e6d3b130a847dde9cfc6473d705d72eb/qft.py b/shared/package-files/b9/b9ae2a050026fa08bddb79514713a001e6d3b130a847dde9cfc6473d705d72eb/qft.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6a3fa4539267f7bb6cf015521007e292b3d4cfd
--- /dev/null
+++ b/shared/package-files/b9/b9ae2a050026fa08bddb79514713a001e6d3b130a847dde9cfc6473d705d72eb/qft.py
@@ -0,0 +1,215 @@
+"""An implementation of qubits and gates acting on them.
+
+Todo:
+
+* Update docstrings.
+* Update tests.
+* Implement apply using decompose.
+* Implement represent using decompose or something smarter. For this to
+  work we first have to implement represent for SWAP.
+* Decide if we want upper index to be inclusive in the constructor.
+* Fix the printing of Rk gates in plotting.
+"""
+
+from sympy.core.expr import Expr
+from sympy.core.numbers import (I, Integer, pi)
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import exp
+from sympy.matrices.dense import Matrix
+from sympy.functions import sqrt
+
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qexpr import QuantumError, QExpr
+from sympy.matrices import eye
+from sympy.physics.quantum.tensorproduct import matrix_tensor_product
+
+from sympy.physics.quantum.gate import (
+    Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate
+)
+
+from sympy.functions.elementary.complexes import sign
+
+__all__ = [
+    'QFT',
+    'IQFT',
+    'RkGate',
+    'Rk'
+]
+
+#-----------------------------------------------------------------------------
+# Fourier stuff
+#-----------------------------------------------------------------------------
+
+
+class RkGate(OneQubitGate):
+    """This is the R_k gate of the QTF."""
+    gate_name = 'Rk'
+    gate_name_latex = 'R'
+
+    def __new__(cls, *args):
+        if len(args) != 2:
+            raise QuantumError(
+                'Rk gates only take two arguments, got: %r' % args
+            )
+        # For small k, Rk gates simplify to other gates, using these
+        # substitutions give us familiar results for the QFT for small numbers
+        # of qubits.
+        target = args[0]
+        k = args[1]
+        if k == 1:
+            return ZGate(target)
+        elif k == 2:
+            return PhaseGate(target)
+        elif k == 3:
+            return TGate(target)
+        args = cls._eval_args(args)
+        inst = Expr.__new__(cls, *args)
+        inst.hilbert_space = cls._eval_hilbert_space(args)
+        return inst
+
+    @classmethod
+    def _eval_args(cls, args):
+        # Fall back to this, because Gate._eval_args assumes that args is
+        # all targets and can't contain duplicates.
+        return QExpr._eval_args(args)
+
+    @property
+    def k(self):
+        return self.label[1]
+
+    @property
+    def targets(self):
+        return self.label[:1]
+
+    @property
+    def gate_name_plot(self):
+        return r'$%s_%s$' % (self.gate_name_latex, str(self.k))
+
+    def get_target_matrix(self, format='sympy'):
+        if format == 'sympy':
+            return Matrix([[1, 0], [0, exp(sign(self.k)*Integer(2)*pi*I/(Integer(2)**abs(self.k)))]])
+        raise NotImplementedError(
+            'Invalid format for the R_k gate: %r' % format)
+
+
+Rk = RkGate
+
+
+class Fourier(Gate):
+    """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
+
+    @classmethod
+    def _eval_args(self, args):
+        if len(args) != 2:
+            raise QuantumError(
+                'QFT/IQFT only takes two arguments, got: %r' % args
+            )
+        if args[0] >= args[1]:
+            raise QuantumError("Start must be smaller than finish")
+        return Gate._eval_args(args)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_ZGate(None, **options)
+
+    def _represent_ZGate(self, basis, **options):
+        """
+            Represents the (I)QFT In the Z Basis
+        """
+        nqubits = options.get('nqubits', 0)
+        if nqubits == 0:
+            raise QuantumError(
+                'The number of qubits must be given as nqubits.')
+        if nqubits < self.min_qubits:
+            raise QuantumError(
+                'The number of qubits %r is too small for the gate.' % nqubits
+            )
+        size = self.size
+        omega = self.omega
+
+        #Make a matrix that has the basic Fourier Transform Matrix
+        arrayFT = [[omega**(
+            i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
+        matrixFT = Matrix(arrayFT)
+
+        #Embed the FT Matrix in a higher space, if necessary
+        if self.label[0] != 0:
+            matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
+        if self.min_qubits < nqubits:
+            matrixFT = matrix_tensor_product(
+                matrixFT, eye(2**(nqubits - self.min_qubits)))
+
+        return matrixFT
+
+    @property
+    def targets(self):
+        return range(self.label[0], self.label[1])
+
+    @property
+    def min_qubits(self):
+        return self.label[1]
+
+    @property
+    def size(self):
+        """Size is the size of the QFT matrix"""
+        return 2**(self.label[1] - self.label[0])
+
+    @property
+    def omega(self):
+        return Symbol('omega')
+
+
+class QFT(Fourier):
+    """The forward quantum Fourier transform."""
+
+    gate_name = 'QFT'
+    gate_name_latex = 'QFT'
+
+    def decompose(self):
+        """Decomposes QFT into elementary gates."""
+        start = self.label[0]
+        finish = self.label[1]
+        circuit = 1
+        for level in reversed(range(start, finish)):
+            circuit = HadamardGate(level)*circuit
+            for i in range(level - start):
+                circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit
+        for i in range((finish - start)//2):
+            circuit = SwapGate(i + start, finish - i - 1)*circuit
+        return circuit
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        return qapply(self.decompose()*qubits)
+
+    def _eval_inverse(self):
+        return IQFT(*self.args)
+
+    @property
+    def omega(self):
+        return exp(2*pi*I/self.size)
+
+
+class IQFT(Fourier):
+    """The inverse quantum Fourier transform."""
+
+    gate_name = 'IQFT'
+    gate_name_latex = '{QFT^{-1}}'
+
+    def decompose(self):
+        """Decomposes IQFT into elementary gates."""
+        start = self.args[0]
+        finish = self.args[1]
+        circuit = 1
+        for i in range((finish - start)//2):
+            circuit = SwapGate(i + start, finish - i - 1)*circuit
+        for level in range(start, finish):
+            for i in reversed(range(level - start)):
+                circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit
+            circuit = HadamardGate(level)*circuit
+        return circuit
+
+    def _eval_inverse(self):
+        return QFT(*self.args)
+
+    @property
+    def omega(self):
+        return exp(-2*pi*I/self.size)
diff --git a/shared/package-files/b9/b9aea0f493875e184a5f533bc56adf6ad4127ffd2540539cf8b7bee40163ed5d/graph_info_provider.cpython-311.pyc b/shared/package-files/b9/b9aea0f493875e184a5f533bc56adf6ad4127ffd2540539cf8b7bee40163ed5d/graph_info_provider.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fc1f2e551e34e087f58eaec9c6f3fb26a782a29
Binary files /dev/null and b/shared/package-files/b9/b9aea0f493875e184a5f533bc56adf6ad4127ffd2540539cf8b7bee40163ed5d/graph_info_provider.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9aed835f2a19f4e2adec1c91c737f418e2436ce0a7169125dc088111c97f40a/__init__.cpython-311.pyc b/shared/package-files/b9/b9aed835f2a19f4e2adec1c91c737f418e2436ce0a7169125dc088111c97f40a/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1a897510d4ef8879dc63a538e11d50148567fc9
Binary files /dev/null and b/shared/package-files/b9/b9aed835f2a19f4e2adec1c91c737f418e2436ce0a7169125dc088111c97f40a/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9b41222f2df4649fea8aefb07b4c4b3ca3d81b2faf5c09e3641c6fd29c2eddb/gt_ops.h b/shared/package-files/b9/b9b41222f2df4649fea8aefb07b4c4b3ca3d81b2faf5c09e3641c6fd29c2eddb/gt_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..8f6957cbb2a1132d8a27920f9e2422d6429b6b11
--- /dev/null
+++ b/shared/package-files/b9/b9b41222f2df4649fea8aefb07b4c4b3ca3d81b2faf5c09e3641c6fd29c2eddb/gt_ops.h
@@ -0,0 +1,84 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API gt_Scalar_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt";
+  static constexpr const char* overload_name = "Scalar_out";
+  static constexpr const char* schema_str = "gt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
+};
+
+struct TORCH_API gt_Scalar {
+  using schema = at::Tensor (const at::Tensor &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "gt.Scalar(Tensor self, Scalar other) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Scalar & other);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other);
+};
+
+struct TORCH_API gt_Tensor_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt";
+  static constexpr const char* overload_name = "Tensor_out";
+  static constexpr const char* schema_str = "gt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+};
+
+struct TORCH_API gt_Tensor {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt";
+  static constexpr const char* overload_name = "Tensor";
+  static constexpr const char* schema_str = "gt.Tensor(Tensor self, Tensor other) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
+};
+
+struct TORCH_API gt__Scalar {
+  using schema = at::Tensor & (at::Tensor &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt_";
+  static constexpr const char* overload_name = "Scalar";
+  static constexpr const char* schema_str = "gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Scalar & other);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other);
+};
+
+struct TORCH_API gt__Tensor {
+  using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::gt_";
+  static constexpr const char* overload_name = "Tensor";
+  static constexpr const char* schema_str = "gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b9b43a36628cd972e54bf9f65f2097fe1e1c20618b292f4f5384aa91eb840da0/leaky_relu_backward_native.h b/shared/package-files/b9/b9b43a36628cd972e54bf9f65f2097fe1e1c20618b292f4f5384aa91eb840da0/leaky_relu_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..38e9a5d467f26f9550ac4790c8c76d042f0c4df5
--- /dev/null
+++ b/shared/package-files/b9/b9b43a36628cd972e54bf9f65f2097fe1e1c20618b292f4f5384aa91eb840da0/leaky_relu_backward_native.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_leaky_relu_backward_out : public at::meta::structured_leaky_relu_backward {
+void impl(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result, const at::Tensor & grad_input);
+};
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b9/b9c04f442248f855112f3767324c49291636c7f8c26a1e09ad86a4b09d5c90f9/scalars.cpython-311.pyc b/shared/package-files/b9/b9c04f442248f855112f3767324c49291636c7f8c26a1e09ad86a4b09d5c90f9/scalars.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c92e12d93288f284c4f977200ff7ee311622082b
Binary files /dev/null and b/shared/package-files/b9/b9c04f442248f855112f3767324c49291636c7f8c26a1e09ad86a4b09d5c90f9/scalars.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9d49f01a84d9d903f01ba7f6cd0d893457a922e19edad264c42c96ce40158e5/__init__.cpython-311.pyc b/shared/package-files/b9/b9d49f01a84d9d903f01ba7f6cd0d893457a922e19edad264c42c96ce40158e5/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb7318d4696d950139d6c974ccb3628ec8abb94a
Binary files /dev/null and b/shared/package-files/b9/b9d49f01a84d9d903f01ba7f6cd0d893457a922e19edad264c42c96ce40158e5/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9d708c97eedea6ee046a235aaef1769de616ecd6b3c888afebc6d66b2f597ec/test_melt.cpython-311.pyc b/shared/package-files/b9/b9d708c97eedea6ee046a235aaef1769de616ecd6b3c888afebc6d66b2f597ec/test_melt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1de752ab8154f9320f819c2e77cda77d5b668fe0
Binary files /dev/null and b/shared/package-files/b9/b9d708c97eedea6ee046a235aaef1769de616ecd6b3c888afebc6d66b2f597ec/test_melt.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9d7093a97854a9930e3cc81c643d6e7e7e483b4231ced097e2cdf55bcee61db/_scaled_dot_product_flash_attention_for_cpu_native.h b/shared/package-files/b9/b9d7093a97854a9930e3cc81c643d6e7e7e483b4231ced097e2cdf55bcee61db/_scaled_dot_product_flash_attention_for_cpu_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..e8a1ddf81f26ba16ca85242bb1384ef1b8ccda2e
--- /dev/null
+++ b/shared/package-files/b9/b9d7093a97854a9930e3cc81c643d6e7e7e483b4231ced097e2cdf55bcee61db/_scaled_dot_product_flash_attention_for_cpu_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API ::std::tuple _scaled_dot_product_flash_attention_cpu(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p=0.0, bool is_causal=false, const ::std::optional & attn_mask={}, ::std::optional scale=::std::nullopt);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/b9/b9d8cf821e3cd229ff48323f49881f16ae0b9ca7ea84a0a7dab34a5991d27594/utils.cpython-311.pyc b/shared/package-files/b9/b9d8cf821e3cd229ff48323f49881f16ae0b9ca7ea84a0a7dab34a5991d27594/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fbc799fc3209e9d9ec9b0f2b4a1ef3605f66e52
Binary files /dev/null and b/shared/package-files/b9/b9d8cf821e3cd229ff48323f49881f16ae0b9ca7ea84a0a7dab34a5991d27594/utils.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9da23f12c00d766320fa7f729756960d1e3ffdedc3a4440e5ce908a607967da/special_ndtri_ops.h b/shared/package-files/b9/b9da23f12c00d766320fa7f729756960d1e3ffdedc3a4440e5ce908a607967da/special_ndtri_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..08814b2f7128209b70082e28f7dd52169488553e
--- /dev/null
+++ b/shared/package-files/b9/b9da23f12c00d766320fa7f729756960d1e3ffdedc3a4440e5ce908a607967da/special_ndtri_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API special_ndtri {
+  using schema = at::Tensor (const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_ndtri";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "special_ndtri(Tensor self) -> Tensor";
+  static at::Tensor call(const at::Tensor & self);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
+};
+
+struct TORCH_API special_ndtri_out {
+  using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_ndtri";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "special_ndtri.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b9dcc54ab8bed3b417815d2ffb11c9dc2c7cc0abc925aa02072c80c30220ea03/test_writers.py b/shared/package-files/b9/b9dcc54ab8bed3b417815d2ffb11c9dc2c7cc0abc925aa02072c80c30220ea03/test_writers.py
new file mode 100644
index 0000000000000000000000000000000000000000..292eab2d881526e6816d85f1fcd38aaa35255243
--- /dev/null
+++ b/shared/package-files/b9/b9dcc54ab8bed3b417815d2ffb11c9dc2c7cc0abc925aa02072c80c30220ea03/test_writers.py
@@ -0,0 +1,1511 @@
+from datetime import (
+    date,
+    datetime,
+    timedelta,
+)
+from functools import partial
+from io import BytesIO
+import os
+import re
+
+import numpy as np
+import pytest
+
+from pandas.compat import is_platform_windows
+from pandas.compat._constants import PY310
+from pandas.compat._optional import import_optional_dependency
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import (
+    DataFrame,
+    Index,
+    MultiIndex,
+    date_range,
+    option_context,
+)
+import pandas._testing as tm
+
+from pandas.io.excel import (
+    ExcelFile,
+    ExcelWriter,
+    _OpenpyxlWriter,
+    _XlsxWriter,
+    register_writer,
+)
+from pandas.io.excel._util import _writers
+
+if is_platform_windows():
+    pytestmark = pytest.mark.single_cpu
+
+
+def get_exp_unit(path: str) -> str:
+    return "ns"
+
+
+@pytest.fixture
+def frame(float_frame):
+    """
+    Returns the first ten items in fixture "float_frame".
+    """
+    return float_frame[:10]
+
+
+@pytest.fixture(params=[True, False])
+def merge_cells(request):
+    return request.param
+
+
+@pytest.fixture
+def path(ext):
+    """
+    Fixture to open file for use in each test case.
+    """
+    with tm.ensure_clean(ext) as file_path:
+        yield file_path
+
+
+@pytest.fixture
+def set_engine(engine, ext):
+    """
+    Fixture to set engine for use in each test case.
+
+    Rather than requiring `engine=...` to be provided explicitly as an
+    argument in each test, this fixture sets a global option to dictate
+    which engine should be used to write Excel files. After executing
+    the test it rolls back said change to the global option.
+    """
+    option_name = f"io.excel.{ext.strip('.')}.writer"
+    with option_context(option_name, engine):
+        yield
+
+
+@pytest.mark.parametrize(
+    "ext",
+    [
+        pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),
+        pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),
+        pytest.param(
+            ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")]
+        ),
+        pytest.param(".ods", marks=td.skip_if_no("odf")),
+    ],
+)
+class TestRoundTrip:
+    @pytest.mark.parametrize(
+        "header,expected",
+        [(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))],
+    )
+    def test_read_one_empty_col_no_header(self, ext, header, expected):
+        # xref gh-12292
+        filename = "no_header"
+        df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])
+
+        with tm.ensure_clean(ext) as path:
+            df.to_excel(path, sheet_name=filename, index=False, header=False)
+            result = pd.read_excel(
+                path, sheet_name=filename, usecols=[0], header=header
+            )
+
+        tm.assert_frame_equal(result, expected)
+
+    @pytest.mark.parametrize(
+        "header,expected",
+        [(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))],
+    )
+    def test_read_one_empty_col_with_header(self, ext, header, expected):
+        filename = "with_header"
+        df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])
+
+        with tm.ensure_clean(ext) as path:
+            df.to_excel(path, sheet_name="with_header", index=False, header=True)
+            result = pd.read_excel(
+                path, sheet_name=filename, usecols=[0], header=header
+            )
+
+        tm.assert_frame_equal(result, expected)
+
+    def test_set_column_names_in_parameter(self, ext):
+        # GH 12870 : pass down column names associated with
+        # keyword argument names
+        refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"])
+
+        with tm.ensure_clean(ext) as pth:
+            with ExcelWriter(pth) as writer:
+                refdf.to_excel(
+                    writer, sheet_name="Data_no_head", header=False, index=False
+                )
+                refdf.to_excel(writer, sheet_name="Data_with_head", index=False)
+
+            refdf.columns = ["A", "B"]
+
+            with ExcelFile(pth) as reader:
+                xlsdf_no_head = pd.read_excel(
+                    reader, sheet_name="Data_no_head", header=None, names=["A", "B"]
+                )
+                xlsdf_with_head = pd.read_excel(
+                    reader,
+                    sheet_name="Data_with_head",
+                    index_col=None,
+                    names=["A", "B"],
+                )
+
+            tm.assert_frame_equal(xlsdf_no_head, refdf)
+            tm.assert_frame_equal(xlsdf_with_head, refdf)
+
+    def test_creating_and_reading_multiple_sheets(self, ext):
+        # see gh-9450
+        #
+        # Test reading multiple sheets, from a runtime
+        # created Excel file with multiple sheets.
+        def tdf(col_sheet_name):
+            d, i = [11, 22, 33], [1, 2, 3]
+            return DataFrame(d, i, columns=[col_sheet_name])
+
+        sheets = ["AAA", "BBB", "CCC"]
+
+        dfs = [tdf(s) for s in sheets]
+        dfs = dict(zip(sheets, dfs))
+
+        with tm.ensure_clean(ext) as pth:
+            with ExcelWriter(pth) as ew:
+                for sheetname, df in dfs.items():
+                    df.to_excel(ew, sheet_name=sheetname)
+
+            dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)
+
+            for s in sheets:
+                tm.assert_frame_equal(dfs[s], dfs_returned[s])
+
+    def test_read_excel_multiindex_empty_level(self, ext):
+        # see gh-12453
+        with tm.ensure_clean(ext) as path:
+            df = DataFrame(
+                {
+                    ("One", "x"): {0: 1},
+                    ("Two", "X"): {0: 3},
+                    ("Two", "Y"): {0: 7},
+                    ("Zero", ""): {0: 0},
+                }
+            )
+
+            expected = DataFrame(
+                {
+                    ("One", "x"): {0: 1},
+                    ("Two", "X"): {0: 3},
+                    ("Two", "Y"): {0: 7},
+                    ("Zero", "Unnamed: 4_level_1"): {0: 0},
+                }
+            )
+
+            df.to_excel(path)
+            actual = pd.read_excel(path, header=[0, 1], index_col=0)
+            tm.assert_frame_equal(actual, expected)
+
+            df = DataFrame(
+                {
+                    ("Beg", ""): {0: 0},
+                    ("Middle", "x"): {0: 1},
+                    ("Tail", "X"): {0: 3},
+                    ("Tail", "Y"): {0: 7},
+                }
+            )
+
+            expected = DataFrame(
+                {
+                    ("Beg", "Unnamed: 1_level_1"): {0: 0},
+                    ("Middle", "x"): {0: 1},
+                    ("Tail", "X"): {0: 3},
+                    ("Tail", "Y"): {0: 7},
+                }
+            )
+
+            df.to_excel(path)
+            actual = pd.read_excel(path, header=[0, 1], index_col=0)
+            tm.assert_frame_equal(actual, expected)
+
+    @pytest.mark.parametrize("c_idx_names", ["a", None])
+    @pytest.mark.parametrize("r_idx_names", ["b", None])
+    @pytest.mark.parametrize("c_idx_levels", [1, 3])
+    @pytest.mark.parametrize("r_idx_levels", [1, 3])
+    def test_excel_multindex_roundtrip(
+        self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request
+    ):
+        # see gh-4679
+        with tm.ensure_clean(ext) as pth:
+            # Empty name case current read in as
+            # unnamed levels, not Nones.
+            check_names = bool(r_idx_names) or r_idx_levels <= 1
+
+            if c_idx_levels == 1:
+                columns = Index(list("abcde"))
+            else:
+                columns = MultiIndex.from_arrays(
+                    [range(5) for _ in range(c_idx_levels)],
+                    names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)],
+                )
+            if r_idx_levels == 1:
+                index = Index(list("ghijk"))
+            else:
+                index = MultiIndex.from_arrays(
+                    [range(5) for _ in range(r_idx_levels)],
+                    names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)],
+                )
+            df = DataFrame(
+                1.1 * np.ones((5, 5)),
+                columns=columns,
+                index=index,
+            )
+            df.to_excel(pth)
+
+            act = pd.read_excel(
+                pth,
+                index_col=list(range(r_idx_levels)),
+                header=list(range(c_idx_levels)),
+            )
+            tm.assert_frame_equal(df, act, check_names=check_names)
+
+            df.iloc[0, :] = np.nan
+            df.to_excel(pth)
+
+            act = pd.read_excel(
+                pth,
+                index_col=list(range(r_idx_levels)),
+                header=list(range(c_idx_levels)),
+            )
+            tm.assert_frame_equal(df, act, check_names=check_names)
+
+            df.iloc[-1, :] = np.nan
+            df.to_excel(pth)
+            act = pd.read_excel(
+                pth,
+                index_col=list(range(r_idx_levels)),
+                header=list(range(c_idx_levels)),
+            )
+            tm.assert_frame_equal(df, act, check_names=check_names)
+
+    def test_read_excel_parse_dates(self, ext):
+        # see gh-11544, gh-12051
+        df = DataFrame(
+            {"col": [1, 2, 3], "date_strings": date_range("2012-01-01", periods=3)}
+        )
+        df2 = df.copy()
+        df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y")
+
+        with tm.ensure_clean(ext) as pth:
+            df2.to_excel(pth)
+
+            res = pd.read_excel(pth, index_col=0)
+            tm.assert_frame_equal(df2, res)
+
+            res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
+            tm.assert_frame_equal(df, res)
+
+            date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y")
+            with tm.assert_produces_warning(
+                FutureWarning,
+                match="use 'date_format' instead",
+                raise_on_extra_warnings=False,
+            ):
+                res = pd.read_excel(
+                    pth,
+                    parse_dates=["date_strings"],
+                    date_parser=date_parser,
+                    index_col=0,
+                )
+            tm.assert_frame_equal(df, res)
+            res = pd.read_excel(
+                pth, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0
+            )
+            tm.assert_frame_equal(df, res)
+
+    def test_multiindex_interval_datetimes(self, ext):
+        # GH 30986
+        midx = MultiIndex.from_arrays(
+            [
+                range(4),
+                pd.interval_range(
+                    start=pd.Timestamp("2020-01-01"), periods=4, freq="6ME"
+                ),
+            ]
+        )
+        df = DataFrame(range(4), index=midx)
+        with tm.ensure_clean(ext) as pth:
+            df.to_excel(pth)
+            result = pd.read_excel(pth, index_col=[0, 1])
+        expected = DataFrame(
+            range(4),
+            MultiIndex.from_arrays(
+                [
+                    range(4),
+                    [
+                        "(2020-01-31 00:00:00, 2020-07-31 00:00:00]",
+                        "(2020-07-31 00:00:00, 2021-01-31 00:00:00]",
+                        "(2021-01-31 00:00:00, 2021-07-31 00:00:00]",
+                        "(2021-07-31 00:00:00, 2022-01-31 00:00:00]",
+                    ],
+                ]
+            ),
+        )
+        tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+    "engine,ext",
+    [
+        pytest.param(
+            "openpyxl",
+            ".xlsx",
+            marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],
+        ),
+        pytest.param(
+            "openpyxl",
+            ".xlsm",
+            marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],
+        ),
+        pytest.param(
+            "xlsxwriter",
+            ".xlsx",
+            marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")],
+        ),
+        pytest.param("odf", ".ods", marks=td.skip_if_no("odf")),
+    ],
+)
+@pytest.mark.usefixtures("set_engine")
+class TestExcelWriter:
+    def test_excel_sheet_size(self, path):
+        # GH 26080
+        breaking_row_count = 2**20 + 1
+        breaking_col_count = 2**14 + 1
+        # purposely using two arrays to prevent memory issues while testing
+        row_arr = np.zeros(shape=(breaking_row_count, 1))
+        col_arr = np.zeros(shape=(1, breaking_col_count))
+        row_df = DataFrame(row_arr)
+        col_df = DataFrame(col_arr)
+
+        msg = "sheet is too large"
+        with pytest.raises(ValueError, match=msg):
+            row_df.to_excel(path)
+
+        with pytest.raises(ValueError, match=msg):
+            col_df.to_excel(path)
+
+    def test_excel_sheet_by_name_raise(self, path):
+        gt = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+        gt.to_excel(path)
+
+        with ExcelFile(path) as xl:
+            df = pd.read_excel(xl, sheet_name=0, index_col=0)
+
+        tm.assert_frame_equal(gt, df)
+
+        msg = "Worksheet named '0' not found"
+        with pytest.raises(ValueError, match=msg):
+            pd.read_excel(xl, "0")
+
+    def test_excel_writer_context_manager(self, frame, path):
+        with ExcelWriter(path) as writer:
+            frame.to_excel(writer, sheet_name="Data1")
+            frame2 = frame.copy()
+            frame2.columns = frame.columns[::-1]
+            frame2.to_excel(writer, sheet_name="Data2")
+
+        with ExcelFile(path) as reader:
+            found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0)
+            found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0)
+
+            tm.assert_frame_equal(found_df, frame)
+            tm.assert_frame_equal(found_df2, frame2)
+
+    def test_roundtrip(self, frame, path):
+        frame = frame.copy()
+        frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
+
+        frame.to_excel(path, sheet_name="test1")
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", index=False)
+
+        # test roundtrip
+        frame.to_excel(path, sheet_name="test1")
+        recons = pd.read_excel(path, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(frame, recons)
+
+        frame.to_excel(path, sheet_name="test1", index=False)
+        recons = pd.read_excel(path, sheet_name="test1", index_col=None)
+        recons.index = frame.index
+        tm.assert_frame_equal(frame, recons)
+
+        frame.to_excel(path, sheet_name="test1", na_rep="NA")
+        recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"])
+        tm.assert_frame_equal(frame, recons)
+
+        # GH 3611
+        frame.to_excel(path, sheet_name="test1", na_rep="88")
+        recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"])
+        tm.assert_frame_equal(frame, recons)
+
+        frame.to_excel(path, sheet_name="test1", na_rep="88")
+        recons = pd.read_excel(
+            path, sheet_name="test1", index_col=0, na_values=[88, 88.0]
+        )
+        tm.assert_frame_equal(frame, recons)
+
+        # GH 6573
+        frame.to_excel(path, sheet_name="Sheet1")
+        recons = pd.read_excel(path, index_col=0)
+        tm.assert_frame_equal(frame, recons)
+
+        frame.to_excel(path, sheet_name="0")
+        recons = pd.read_excel(path, index_col=0)
+        tm.assert_frame_equal(frame, recons)
+
+        # GH 8825 Pandas Series should provide to_excel method
+        s = frame["A"]
+        s.to_excel(path)
+        recons = pd.read_excel(path, index_col=0)
+        tm.assert_frame_equal(s.to_frame(), recons)
+
+    def test_mixed(self, frame, path):
+        mixed_frame = frame.copy()
+        mixed_frame["foo"] = "bar"
+
+        mixed_frame.to_excel(path, sheet_name="test1")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(mixed_frame, recons)
+
+    def test_ts_frame(self, path):
+        unit = get_exp_unit(path)
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((5, 4)),
+            columns=Index(list("ABCD")),
+            index=date_range("2000-01-01", periods=5, freq="B"),
+        )
+
+        # freq doesn't round-trip
+        index = pd.DatetimeIndex(np.asarray(df.index), freq=None)
+        df.index = index
+
+        expected = df[:]
+        expected.index = expected.index.as_unit(unit)
+
+        df.to_excel(path, sheet_name="test1")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(expected, recons)
+
+    def test_basics_with_nan(self, frame, path):
+        frame = frame.copy()
+        frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
+        frame.to_excel(path, sheet_name="test1")
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", index=False)
+
+    @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64])
+    def test_int_types(self, np_type, path):
+        # Test np.int values read come back as int
+        # (rather than float which is Excel's format).
+        df = DataFrame(
+            np.random.default_rng(2).integers(-10, 10, size=(10, 2)), dtype=np_type
+        )
+        df.to_excel(path, sheet_name="test1")
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+
+        int_frame = df.astype(np.int64)
+        tm.assert_frame_equal(int_frame, recons)
+
+        recons2 = pd.read_excel(path, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(int_frame, recons2)
+
+    @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64])
+    def test_float_types(self, np_type, path):
+        # Test np.float values read come back as float.
+        df = DataFrame(np.random.default_rng(2).random(10), dtype=np_type)
+        df.to_excel(path, sheet_name="test1")
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+                np_type
+            )
+
+        tm.assert_frame_equal(df, recons)
+
+    def test_bool_types(self, path):
+        # Test np.bool_ values read come back as float.
+        df = DataFrame([1, 0, True, False], dtype=np.bool_)
+        df.to_excel(path, sheet_name="test1")
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+                np.bool_
+            )
+
+        tm.assert_frame_equal(df, recons)
+
+    def test_inf_roundtrip(self, path):
+        df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
+        df.to_excel(path, sheet_name="test1")
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+
+        tm.assert_frame_equal(df, recons)
+
+    def test_sheets(self, frame, path):
+        # freq doesn't round-trip
+        unit = get_exp_unit(path)
+        tsframe = DataFrame(
+            np.random.default_rng(2).standard_normal((5, 4)),
+            columns=Index(list("ABCD")),
+            index=date_range("2000-01-01", periods=5, freq="B"),
+        )
+        index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
+        tsframe.index = index
+
+        expected = tsframe[:]
+        expected.index = expected.index.as_unit(unit)
+
+        frame = frame.copy()
+        frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
+
+        frame.to_excel(path, sheet_name="test1")
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", index=False)
+
+        # Test writing to separate sheets
+        with ExcelWriter(path) as writer:
+            frame.to_excel(writer, sheet_name="test1")
+            tsframe.to_excel(writer, sheet_name="test2")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+            tm.assert_frame_equal(frame, recons)
+            recons = pd.read_excel(reader, sheet_name="test2", index_col=0)
+        tm.assert_frame_equal(expected, recons)
+        assert 2 == len(reader.sheet_names)
+        assert "test1" == reader.sheet_names[0]
+        assert "test2" == reader.sheet_names[1]
+
+    def test_colaliases(self, frame, path):
+        frame = frame.copy()
+        frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
+
+        frame.to_excel(path, sheet_name="test1")
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", index=False)
+
+        # column aliases
+        col_aliases = Index(["AA", "X", "Y", "Z"])
+        frame.to_excel(path, sheet_name="test1", header=col_aliases)
+        with ExcelFile(path) as reader:
+            rs = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        xp = frame.copy()
+        xp.columns = col_aliases
+        tm.assert_frame_equal(xp, rs)
+
+    def test_roundtrip_indexlabels(self, merge_cells, frame, path):
+        frame = frame.copy()
+        frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
+
+        frame.to_excel(path, sheet_name="test1")
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", index=False)
+
+        # test index_label
+        df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0
+        df.to_excel(
+            path, sheet_name="test1", index_label=["test"], merge_cells=merge_cells
+        )
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+                np.int64
+            )
+        df.index.names = ["test"]
+        assert df.index.names == recons.index.names
+
+        df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0
+        df.to_excel(
+            path,
+            sheet_name="test1",
+            index_label=["test", "dummy", "dummy2"],
+            merge_cells=merge_cells,
+        )
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+                np.int64
+            )
+        df.index.names = ["test"]
+        assert df.index.names == recons.index.names
+
+        df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0
+        df.to_excel(
+            path, sheet_name="test1", index_label="test", merge_cells=merge_cells
+        )
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+                np.int64
+            )
+        df.index.names = ["test"]
+        tm.assert_frame_equal(df, recons.astype(bool))
+
+        frame.to_excel(
+            path,
+            sheet_name="test1",
+            columns=["A", "B", "C", "D"],
+            index=False,
+            merge_cells=merge_cells,
+        )
+        # take 'A' and 'B' as indexes (same row as cols 'C', 'D')
+        df = frame.copy()
+        df = df.set_index(["A", "B"])
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+        tm.assert_frame_equal(df, recons)
+
+    def test_excel_roundtrip_indexname(self, merge_cells, path):
+        df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
+        df.index.name = "foo"
+
+        df.to_excel(path, merge_cells=merge_cells)
+
+        with ExcelFile(path) as xf:
+            result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0)
+
+        tm.assert_frame_equal(result, df)
+        assert result.index.name == "foo"
+
+    def test_excel_roundtrip_datetime(self, merge_cells, path):
+        # datetime.date, not sure what to test here exactly
+        unit = get_exp_unit(path)
+
+        # freq does not round-trip
+        tsframe = DataFrame(
+            np.random.default_rng(2).standard_normal((5, 4)),
+            columns=Index(list("ABCD")),
+            index=date_range("2000-01-01", periods=5, freq="B"),
+        )
+        index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
+        tsframe.index = index
+
+        tsf = tsframe.copy()
+
+        tsf.index = [x.date() for x in tsframe.index]
+        tsf.to_excel(path, sheet_name="test1", merge_cells=merge_cells)
+
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+
+        expected = tsframe[:]
+        expected.index = expected.index.as_unit(unit)
+        tm.assert_frame_equal(expected, recons)
+
+    def test_excel_date_datetime_format(self, ext, path):
+        # see gh-4133
+        #
+        # Excel output format strings
+        unit = get_exp_unit(path)
+
+        df = DataFrame(
+            [
+                [date(2014, 1, 31), date(1999, 9, 24)],
+                [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
+            ],
+            index=["DATE", "DATETIME"],
+            columns=["X", "Y"],
+        )
+        df_expected = DataFrame(
+            [
+                [datetime(2014, 1, 31), datetime(1999, 9, 24)],
+                [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
+            ],
+            index=["DATE", "DATETIME"],
+            columns=["X", "Y"],
+        )
+        df_expected = df_expected.astype(f"M8[{unit}]")
+
+        with tm.ensure_clean(ext) as filename2:
+            with ExcelWriter(path) as writer1:
+                df.to_excel(writer1, sheet_name="test1")
+
+            with ExcelWriter(
+                filename2,
+                date_format="DD.MM.YYYY",
+                datetime_format="DD.MM.YYYY HH-MM-SS",
+            ) as writer2:
+                df.to_excel(writer2, sheet_name="test1")
+
+            with ExcelFile(path) as reader1:
+                rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0)
+
+            with ExcelFile(filename2) as reader2:
+                rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0)
+
+        tm.assert_frame_equal(rs1, rs2)
+
+        # Since the reader returns a datetime object for dates,
+        # we need to use df_expected to check the result.
+        tm.assert_frame_equal(rs2, df_expected)
+
+    def test_to_excel_interval_no_labels(self, path, using_infer_string):
+        # see gh-19242
+        #
+        # Test writing Interval without labels.
+        df = DataFrame(
+            np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64
+        )
+        expected = df.copy()
+
+        df["new"] = pd.cut(df[0], 10)
+        expected["new"] = pd.cut(expected[0], 10).astype(
+            str if not using_infer_string else "string[pyarrow_numpy]"
+        )
+
+        df.to_excel(path, sheet_name="test1")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(expected, recons)
+
+    def test_to_excel_interval_labels(self, path):
+        # see gh-19242
+        #
+        # Test writing Interval with labels.
+        df = DataFrame(
+            np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64
+        )
+        expected = df.copy()
+        intervals = pd.cut(
+            df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
+        )
+        df["new"] = intervals
+        expected["new"] = pd.Series(list(intervals))
+
+        df.to_excel(path, sheet_name="test1")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(expected, recons)
+
+    def test_to_excel_timedelta(self, path):
+        # see gh-19242, gh-9155
+        #
+        # Test writing timedelta to xls.
+        df = DataFrame(
+            np.random.default_rng(2).integers(-10, 10, size=(20, 1)),
+            columns=["A"],
+            dtype=np.int64,
+        )
+        expected = df.copy()
+
+        df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))
+        expected["new"] = expected["A"].apply(
+            lambda x: timedelta(seconds=x).total_seconds() / 86400
+        )
+
+        df.to_excel(path, sheet_name="test1")
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(expected, recons)
+
+    def test_to_excel_periodindex(self, path):
+        # xp has a PeriodIndex
+        df = DataFrame(
+            np.random.default_rng(2).standard_normal((5, 4)),
+            columns=Index(list("ABCD")),
+            index=date_range("2000-01-01", periods=5, freq="B"),
+        )
+        xp = df.resample("ME").mean().to_period("M")
+
+        xp.to_excel(path, sheet_name="sht1")
+
+        with ExcelFile(path) as reader:
+            rs = pd.read_excel(reader, sheet_name="sht1", index_col=0)
+        tm.assert_frame_equal(xp, rs.to_period("M"))
+
+    def test_to_excel_multiindex(self, merge_cells, frame, path):
+        arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1)
+        new_index = MultiIndex.from_arrays(arrays, names=["first", "second"])
+        frame.index = new_index
+
+        frame.to_excel(path, sheet_name="test1", header=False)
+        frame.to_excel(path, sheet_name="test1", columns=["A", "B"])
+
+        # round trip
+        frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells)
+        with ExcelFile(path) as reader:
+            df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+        tm.assert_frame_equal(frame, df)
+
+    # GH13511
+    def test_to_excel_multiindex_nan_label(self, merge_cells, path):
+        df = DataFrame(
+            {
+                "A": [None, 2, 3],
+                "B": [10, 20, 30],
+                "C": np.random.default_rng(2).random(3),
+            }
+        )
+        df = df.set_index(["A", "B"])
+
+        df.to_excel(path, merge_cells=merge_cells)
+        df1 = pd.read_excel(path, index_col=[0, 1])
+        tm.assert_frame_equal(df, df1)
+
+    # Test for Issue 11328. If column indices are integers, make
+    # sure they are handled correctly for either setting of
+    # merge_cells
+    def test_to_excel_multiindex_cols(self, merge_cells, frame, path):
+        arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1)
+        new_index = MultiIndex.from_arrays(arrays, names=["first", "second"])
+        frame.index = new_index
+
+        new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1), (50, 2)])
+        frame.columns = new_cols_index
+        header = [0, 1]
+        if not merge_cells:
+            header = 0
+
+        # round trip
+        frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells)
+        with ExcelFile(path) as reader:
+            df = pd.read_excel(
+                reader, sheet_name="test1", header=header, index_col=[0, 1]
+            )
+        if not merge_cells:
+            fm = frame.columns._format_multi(sparsify=False, include_names=False)
+            frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
+        tm.assert_frame_equal(frame, df)
+
+    def test_to_excel_multiindex_dates(self, merge_cells, path):
+        # try multiindex with dates
+        unit = get_exp_unit(path)
+        tsframe = DataFrame(
+            np.random.default_rng(2).standard_normal((5, 4)),
+            columns=Index(list("ABCD")),
+            index=date_range("2000-01-01", periods=5, freq="B"),
+        )
+        tsframe.index = MultiIndex.from_arrays(
+            [
+                tsframe.index.as_unit(unit),
+                np.arange(len(tsframe.index), dtype=np.int64),
+            ],
+            names=["time", "foo"],
+        )
+
+        tsframe.to_excel(path, sheet_name="test1", merge_cells=merge_cells)
+        with ExcelFile(path) as reader:
+            recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+
+        tm.assert_frame_equal(tsframe, recons)
+        assert recons.index.names == ("time", "foo")
+
+    def test_to_excel_multiindex_no_write_index(self, path):
+        # Test writing and re-reading a MI without the index. GH 5616.
+
+        # Initial non-MI frame.
+        frame1 = DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]})
+
+        # Add a MI.
+        frame2 = frame1.copy()
+        multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)])
+        frame2.index = multi_index
+
+        # Write out to Excel without the index.
+        frame2.to_excel(path, sheet_name="test1", index=False)
+
+        # Read it back in.
+        with ExcelFile(path) as reader:
+            frame3 = pd.read_excel(reader, sheet_name="test1")
+
+        # Test that it is the same as the initial frame.
+        tm.assert_frame_equal(frame1, frame3)
+
+    def test_to_excel_empty_multiindex(self, path):
+        # GH 19543.
+        expected = DataFrame([], columns=[0, 1, 2])
+
+        df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2])
+        df.to_excel(path, sheet_name="test1")
+
+        with ExcelFile(path) as reader:
+            result = pd.read_excel(reader, sheet_name="test1")
+        tm.assert_frame_equal(
+            result, expected, check_index_type=False, check_dtype=False
+        )
+
+    def test_to_excel_float_format(self, path):
+        df = DataFrame(
+            [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+            index=["A", "B"],
+            columns=["X", "Y", "Z"],
+        )
+        df.to_excel(path, sheet_name="test1", float_format="%.2f")
+
+        with ExcelFile(path) as reader:
+            result = pd.read_excel(reader, sheet_name="test1", index_col=0)
+
+        expected = DataFrame(
+            [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],
+            index=["A", "B"],
+            columns=["X", "Y", "Z"],
+        )
+        tm.assert_frame_equal(result, expected)
+
+    def test_to_excel_output_encoding(self, ext):
+        # Avoid mixed inferred_type.
+        df = DataFrame(
+            [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]],
+            index=["A\u0192", "B"],
+            columns=["X\u0193", "Y", "Z"],
+        )
+
+        with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
+            df.to_excel(filename, sheet_name="TestSheet")
+            result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0)
+            tm.assert_frame_equal(result, df)
+
+    def test_to_excel_unicode_filename(self, ext):
+        with tm.ensure_clean("\u0192u." + ext) as filename:
+            try:
+                with open(filename, "wb"):
+                    pass
+            except UnicodeEncodeError:
+                pytest.skip("No unicode file names on this system")
+
+            df = DataFrame(
+                [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+                index=["A", "B"],
+                columns=["X", "Y", "Z"],
+            )
+            df.to_excel(filename, sheet_name="test1", float_format="%.2f")
+
+            with ExcelFile(filename) as reader:
+                result = pd.read_excel(reader, sheet_name="test1", index_col=0)
+
+        expected = DataFrame(
+            [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],
+            index=["A", "B"],
+            columns=["X", "Y", "Z"],
+        )
+        tm.assert_frame_equal(result, expected)
+
+    @pytest.mark.parametrize("use_headers", [True, False])
+    @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3])
+    @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3])
+    def test_excel_010_hemstring(
+        self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path
+    ):
+        def roundtrip(data, header=True, parser_hdr=0, index=True):
+            data.to_excel(path, header=header, merge_cells=merge_cells, index=index)
+
+            with ExcelFile(path) as xf:
+                return pd.read_excel(
+                    xf, sheet_name=xf.sheet_names[0], header=parser_hdr
+                )
+
+        # Basic test.
+        parser_header = 0 if use_headers else None
+        res = roundtrip(DataFrame([0]), use_headers, parser_header)
+
+        assert res.shape == (1, 2)
+        assert res.iloc[0, 0] is not np.nan
+
+        # More complex tests with multi-index.
+        nrows = 5
+        ncols = 3
+
+        # ensure limited functionality in 0.10
+        # override of gh-2370 until sorted out in 0.11
+
+        if c_idx_nlevels == 1:
+            columns = Index([f"a-{i}" for i in range(ncols)], dtype=object)
+        else:
+            columns = MultiIndex.from_arrays(
+                [range(ncols) for _ in range(c_idx_nlevels)],
+                names=[f"i-{i}" for i in range(c_idx_nlevels)],
+            )
+        if r_idx_nlevels == 1:
+            index = Index([f"b-{i}" for i in range(nrows)], dtype=object)
+        else:
+            index = MultiIndex.from_arrays(
+                [range(nrows) for _ in range(r_idx_nlevels)],
+                names=[f"j-{i}" for i in range(r_idx_nlevels)],
+            )
+
+        df = DataFrame(
+            np.ones((nrows, ncols)),
+            columns=columns,
+            index=index,
+        )
+
+        # This if will be removed once multi-column Excel writing
+        # is implemented. For now fixing gh-9794.
+        if c_idx_nlevels > 1:
+            msg = (
+                "Writing to Excel with MultiIndex columns and no index "
+                "\\('index'=False\\) is not yet implemented."
+            )
+            with pytest.raises(NotImplementedError, match=msg):
+                roundtrip(df, use_headers, index=False)
+        else:
+            res = roundtrip(df, use_headers)
+
+            if use_headers:
+                assert res.shape == (nrows, ncols + r_idx_nlevels)
+            else:
+                # First row taken as columns.
+                assert res.shape == (nrows - 1, ncols + r_idx_nlevels)
+
+            # No NaNs.
+            for r in range(len(res.index)):
+                for c in range(len(res.columns)):
+                    assert res.iloc[r, c] is not np.nan
+
+    def test_duplicated_columns(self, path):
+        # see gh-5235
+        df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"])
+        df.to_excel(path, sheet_name="test1")
+        expected = DataFrame(
+            [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"]
+        )
+
+        # By default, we mangle.
+        result = pd.read_excel(path, sheet_name="test1", index_col=0)
+        tm.assert_frame_equal(result, expected)
+
+        # see gh-11007, gh-10970
+        df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"])
+        df.to_excel(path, sheet_name="test1")
+
+        result = pd.read_excel(path, sheet_name="test1", index_col=0)
+        expected = DataFrame(
+            [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"]
+        )
+        tm.assert_frame_equal(result, expected)
+
+        # see gh-10982
+        df.to_excel(path, sheet_name="test1", index=False, header=False)
+        result = pd.read_excel(path, sheet_name="test1", header=None)
+
+        expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
+        tm.assert_frame_equal(result, expected)
+
+    def test_swapped_columns(self, path):
+        # Test for issue #5427.
+        write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})
+        write_frame.to_excel(path, sheet_name="test1", columns=["B", "A"])
+
+        read_frame = pd.read_excel(path, sheet_name="test1", header=0)
+
+        tm.assert_series_equal(write_frame["A"], read_frame["A"])
+        tm.assert_series_equal(write_frame["B"], read_frame["B"])
+
+    def test_invalid_columns(self, path):
+        # see gh-10982
+        write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})
+
+        with pytest.raises(KeyError, match="Not all names specified"):
+            write_frame.to_excel(path, sheet_name="test1", columns=["B", "C"])
+
+        with pytest.raises(
+            KeyError, match="'passes columns are not ALL present dataframe'"
+        ):
+            write_frame.to_excel(path, sheet_name="test1", columns=["C", "D"])
+
+    @pytest.mark.parametrize(
+        "to_excel_index,read_excel_index_col",
+        [
+            (True, 0),  # Include index in write to file
+            (False, None),  # Dont include index in write to file
+        ],
+    )
+    def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):
+        # GH 31677
+        write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]})
+        write_frame.to_excel(
+            path, sheet_name="col_subset_bug", columns=["A", "B"], index=to_excel_index
+        )
+
+        expected = write_frame[["A", "B"]]
+        read_frame = pd.read_excel(
+            path, sheet_name="col_subset_bug", index_col=read_excel_index_col
+        )
+
+        tm.assert_frame_equal(expected, read_frame)
+
+    def test_comment_arg(self, path):
+        # see gh-18735
+        #
+        # Test the comment argument functionality to pd.read_excel.
+
+        # Create file to read in.
+        df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
+        df.to_excel(path, sheet_name="test_c")
+
+        # Read file without comment arg.
+        result1 = pd.read_excel(path, sheet_name="test_c", index_col=0)
+
+        result1.iloc[1, 0] = None
+        result1.iloc[1, 1] = None
+        result1.iloc[2, 1] = None
+
+        result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
+        tm.assert_frame_equal(result1, result2)
+
+    def test_comment_default(self, path):
+        # Re issue #18735
+        # Test the comment argument default to pd.read_excel
+
+        # Create file to read in
+        df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
+        df.to_excel(path, sheet_name="test_c")
+
+        # Read file with default and explicit comment=None
+        result1 = pd.read_excel(path, sheet_name="test_c")
+        result2 = pd.read_excel(path, sheet_name="test_c", comment=None)
+        tm.assert_frame_equal(result1, result2)
+
+    def test_comment_used(self, path):
+        # see gh-18735
+        #
+        # Test the comment argument is working as expected when used.
+
+        # Create file to read in.
+        df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
+        df.to_excel(path, sheet_name="test_c")
+
+        # Test read_frame_comment against manually produced expected output.
+        expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]})
+        result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
+        tm.assert_frame_equal(result, expected)
+
+    def test_comment_empty_line(self, path):
+        # Re issue #18735
+        # Test that pd.read_excel ignores commented lines at the end of file
+
+        df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]})
+        df.to_excel(path, index=False)
+
+        # Test that all-comment lines at EoF are ignored
+        expected = DataFrame({"a": [1], "b": [2]})
+        result = pd.read_excel(path, comment="#")
+        tm.assert_frame_equal(result, expected)
+
+    def test_datetimes(self, path):
+        # Test writing and reading datetimes. For issue #9139. (xref #9185)
+        unit = get_exp_unit(path)
+        datetimes = [
+            datetime(2013, 1, 13, 1, 2, 3),
+            datetime(2013, 1, 13, 2, 45, 56),
+            datetime(2013, 1, 13, 4, 29, 49),
+            datetime(2013, 1, 13, 6, 13, 42),
+            datetime(2013, 1, 13, 7, 57, 35),
+            datetime(2013, 1, 13, 9, 41, 28),
+            datetime(2013, 1, 13, 11, 25, 21),
+            datetime(2013, 1, 13, 13, 9, 14),
+            datetime(2013, 1, 13, 14, 53, 7),
+            datetime(2013, 1, 13, 16, 37, 0),
+            datetime(2013, 1, 13, 18, 20, 52),
+        ]
+
+        write_frame = DataFrame({"A": datetimes})
+        write_frame.to_excel(path, sheet_name="Sheet1")
+        read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)
+
+        expected = write_frame.astype(f"M8[{unit}]")
+        tm.assert_series_equal(expected["A"], read_frame["A"])
+
+    def test_bytes_io(self, engine):
+        # see gh-7074
+        with BytesIO() as bio:
+            df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
+
+            # Pass engine explicitly, as there is no file path to infer from.
+            with ExcelWriter(bio, engine=engine) as writer:
+                df.to_excel(writer)
+
+            bio.seek(0)
+            reread_df = pd.read_excel(bio, index_col=0)
+            tm.assert_frame_equal(df, reread_df)
+
+    def test_engine_kwargs(self, engine, path):
+        # GH#52368
+        df = DataFrame([{"A": 1, "B": 2}, {"A": 3, "B": 4}])
+
+        msgs = {
+            "odf": r"OpenDocumentSpreadsheet() got an unexpected keyword "
+            r"argument 'foo'",
+            "openpyxl": r"__init__() got an unexpected keyword argument 'foo'",
+            "xlsxwriter": r"__init__() got an unexpected keyword argument 'foo'",
+        }
+
+        if PY310:
+            msgs[
+                "openpyxl"
+            ] = "Workbook.__init__() got an unexpected keyword argument 'foo'"
+            msgs[
+                "xlsxwriter"
+            ] = "Workbook.__init__() got an unexpected keyword argument 'foo'"
+
+        # Handle change in error message for openpyxl (write and append mode)
+        if engine == "openpyxl" and not os.path.exists(path):
+            msgs[
+                "openpyxl"
+            ] = r"load_workbook() got an unexpected keyword argument 'foo'"
+
+        with pytest.raises(TypeError, match=re.escape(msgs[engine])):
+            df.to_excel(
+                path,
+                engine=engine,
+                engine_kwargs={"foo": "bar"},
+            )
+
+    def test_write_lists_dict(self, path):
+        # see gh-8188.
+        df = DataFrame(
+            {
+                "mixed": ["a", ["b", "c"], {"d": "e", "f": 2}],
+                "numeric": [1, 2, 3.0],
+                "str": ["apple", "banana", "cherry"],
+            }
+        )
+        df.to_excel(path, sheet_name="Sheet1")
+        read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0)
+
+        expected = df.copy()
+        expected.mixed = expected.mixed.apply(str)
+        expected.numeric = expected.numeric.astype("int64")
+
+        tm.assert_frame_equal(read, expected)
+
+    def test_render_as_column_name(self, path):
+        # see gh-34331
+        df = DataFrame({"render": [1, 2], "data": [3, 4]})
+        df.to_excel(path, sheet_name="Sheet1")
+        read = pd.read_excel(path, "Sheet1", index_col=0)
+        expected = df
+        tm.assert_frame_equal(read, expected)
+
+    def test_true_and_false_value_options(self, path):
+        # see gh-13347
+        df = DataFrame([["foo", "bar"]], columns=["col1", "col2"], dtype=object)
+        with option_context("future.no_silent_downcasting", True):
+            expected = df.replace({"foo": True, "bar": False}).astype("bool")
+
+        df.to_excel(path)
+        read_frame = pd.read_excel(
+            path, true_values=["foo"], false_values=["bar"], index_col=0
+        )
+        tm.assert_frame_equal(read_frame, expected)
+
+    def test_freeze_panes(self, path):
+        # see gh-15160
+        expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
+        expected.to_excel(path, sheet_name="Sheet1", freeze_panes=(1, 1))
+
+        result = pd.read_excel(path, index_col=0)
+        tm.assert_frame_equal(result, expected)
+
+    def test_path_path_lib(self, engine, ext):
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD")),
+            index=Index([f"i-{i}" for i in range(30)], dtype=object),
+        )
+        writer = partial(df.to_excel, engine=engine)
+
+        reader = partial(pd.read_excel, index_col=0)
+        result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}")
+        tm.assert_frame_equal(result, df)
+
+    def test_path_local_path(self, engine, ext):
+        df = DataFrame(
+            1.1 * np.arange(120).reshape((30, 4)),
+            columns=Index(list("ABCD")),
+            index=Index([f"i-{i}" for i in range(30)]),
+        )
+        writer = partial(df.to_excel, engine=engine)
+
+        reader = partial(pd.read_excel, index_col=0)
+        result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}")
+        tm.assert_frame_equal(result, df)
+
+    def test_merged_cell_custom_objects(self, path):
+        # see GH-27006
+        mi = MultiIndex.from_tuples(
+            [
+                (pd.Period("2018"), pd.Period("2018Q1")),
+                (pd.Period("2018"), pd.Period("2018Q2")),
+            ]
+        )
+        expected = DataFrame(np.ones((2, 2), dtype="int64"), columns=mi)
+        expected.to_excel(path)
+        result = pd.read_excel(path, header=[0, 1], index_col=0)
+        # need to convert PeriodIndexes to standard Indexes for assert equal
+        expected.columns = expected.columns.set_levels(
+            [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]],
+            level=[0, 1],
+        )
+        tm.assert_frame_equal(result, expected)
+
+    @pytest.mark.parametrize("dtype", [None, object])
+    def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path):
+        # GH 27008, GH 7056
+        tz = tz_aware_fixture
+        data = pd.Timestamp("2019", tz=tz)
+        df = DataFrame([data], dtype=dtype)
+        with pytest.raises(ValueError, match="Excel does not support"):
+            df.to_excel(path)
+
+        data = data.to_pydatetime()
+        df = DataFrame([data], dtype=dtype)
+        with pytest.raises(ValueError, match="Excel does not support"):
+            df.to_excel(path)
+
+    def test_excel_duplicate_columns_with_names(self, path):
+        # GH#39695
+        df = DataFrame({"A": [0, 1], "B": [10, 11]})
+        df.to_excel(path, columns=["A", "B", "A"], index=False)
+
+        result = pd.read_excel(path)
+        expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])
+        tm.assert_frame_equal(result, expected)
+
+    def test_if_sheet_exists_raises(self, ext):
+        # GH 40230
+        msg = "if_sheet_exists is only valid in append mode (mode='a')"
+
+        with tm.ensure_clean(ext) as f:
+            with pytest.raises(ValueError, match=re.escape(msg)):
+                ExcelWriter(f, if_sheet_exists="replace")
+
+    def test_excel_writer_empty_frame(self, engine, ext):
+        # GH#45793
+        with tm.ensure_clean(ext) as path:
+            with ExcelWriter(path, engine=engine) as writer:
+                DataFrame().to_excel(writer)
+            result = pd.read_excel(path)
+            expected = DataFrame()
+            tm.assert_frame_equal(result, expected)
+
+    def test_to_excel_empty_frame(self, engine, ext):
+        # GH#45793
+        with tm.ensure_clean(ext) as path:
+            DataFrame().to_excel(path, engine=engine)
+            result = pd.read_excel(path)
+            expected = DataFrame()
+            tm.assert_frame_equal(result, expected)
+
+
+class TestExcelWriterEngineTests:
+    @pytest.mark.parametrize(
+        "klass,ext",
+        [
+            pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")),
+            pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")),
+        ],
+    )
+    def test_ExcelWriter_dispatch(self, klass, ext):
+        with tm.ensure_clean(ext) as path:
+            with ExcelWriter(path) as writer:
+                if ext == ".xlsx" and bool(
+                    import_optional_dependency("xlsxwriter", errors="ignore")
+                ):
+                    # xlsxwriter has preference over openpyxl if both installed
+                    assert isinstance(writer, _XlsxWriter)
+                else:
+                    assert isinstance(writer, klass)
+
+    def test_ExcelWriter_dispatch_raises(self):
+        with pytest.raises(ValueError, match="No engine"):
+            ExcelWriter("nothing")
+
+    def test_register_writer(self):
+        class DummyClass(ExcelWriter):
+            called_save = False
+            called_write_cells = False
+            called_sheets = False
+            _supported_extensions = ("xlsx", "xls")
+            _engine = "dummy"
+
+            def book(self):
+                pass
+
+            def _save(self):
+                type(self).called_save = True
+
+            def _write_cells(self, *args, **kwargs):
+                type(self).called_write_cells = True
+
+            @property
+            def sheets(self):
+                type(self).called_sheets = True
+
+            @classmethod
+            def assert_called_and_reset(cls):
+                assert cls.called_save
+                assert cls.called_write_cells
+                assert not cls.called_sheets
+                cls.called_save = False
+                cls.called_write_cells = False
+
+        register_writer(DummyClass)
+
+        with option_context("io.excel.xlsx.writer", "dummy"):
+            path = "something.xlsx"
+            with tm.ensure_clean(path) as filepath:
+                with ExcelWriter(filepath) as writer:
+                    assert isinstance(writer, DummyClass)
+                df = DataFrame(
+                    ["a"],
+                    columns=Index(["b"], name="foo"),
+                    index=Index(["c"], name="bar"),
+                )
+                df.to_excel(filepath)
+            DummyClass.assert_called_and_reset()
+
+        with tm.ensure_clean("something.xls") as filepath:
+            df.to_excel(filepath, engine="dummy")
+        DummyClass.assert_called_and_reset()
+
+
+@td.skip_if_no("xlrd")
+@td.skip_if_no("openpyxl")
+class TestFSPath:
+    def test_excelfile_fspath(self):
+        with tm.ensure_clean("foo.xlsx") as path:
+            df = DataFrame({"A": [1, 2]})
+            df.to_excel(path)
+            with ExcelFile(path) as xl:
+                result = os.fspath(xl)
+            assert result == path
+
+    def test_excelwriter_fspath(self):
+        with tm.ensure_clean("foo.xlsx") as path:
+            with ExcelWriter(path) as writer:
+                assert os.fspath(writer) == str(path)
+
+    def test_to_excel_pos_args_deprecation(self):
+        # GH-54229
+        df = DataFrame({"a": [1, 2, 3]})
+        msg = (
+            r"Starting with pandas version 3.0 all arguments of to_excel except "
+            r"for the argument 'excel_writer' will be keyword-only."
+        )
+        with tm.assert_produces_warning(FutureWarning, match=msg):
+            buf = BytesIO()
+            writer = ExcelWriter(buf)
+            df.to_excel(writer, "Sheet_name_1")
+
+
+@pytest.mark.parametrize("klass", _writers.values())
+def test_subclass_attr(klass):
+    # testing that subclasses of ExcelWriter don't have public attributes (issue 49602)
+    attrs_base = {name for name in dir(ExcelWriter) if not name.startswith("_")}
+    attrs_klass = {name for name in dir(klass) if not name.startswith("_")}
+    assert not attrs_base.symmetric_difference(attrs_klass)
diff --git a/shared/package-files/b9/b9df5a102face3e365c7a508c56936e28a944286ccd15807bcae82747c4f49af/Copy.h b/shared/package-files/b9/b9df5a102face3e365c7a508c56936e28a944286ccd15807bcae82747c4f49af/Copy.h
new file mode 100644
index 0000000000000000000000000000000000000000..f4b90b7b513235d3c25d966ac049d9a63a8fa1da
--- /dev/null
+++ b/shared/package-files/b9/b9df5a102face3e365c7a508c56936e28a944286ccd15807bcae82747c4f49af/Copy.h
@@ -0,0 +1,11 @@
+#pragma once
+
+namespace at {
+struct TensorIteratorBase;
+
+namespace native {
+
+void direct_copy_kernel_cuda(TensorIteratorBase& iter);
+
+}
+} // namespace at
diff --git a/shared/package-files/b9/b9e077c5c0ca58603566ad1146d982d4e861fdc4a43af537e19c0046a243b67e/special_modified_bessel_k0_ops.h b/shared/package-files/b9/b9e077c5c0ca58603566ad1146d982d4e861fdc4a43af537e19c0046a243b67e/special_modified_bessel_k0_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..a6630abdfef6f81d19f8f318033391bdbc2b6f8f
--- /dev/null
+++ b/shared/package-files/b9/b9e077c5c0ca58603566ad1146d982d4e861fdc4a43af537e19c0046a243b67e/special_modified_bessel_k0_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API special_modified_bessel_k0 {
+  using schema = at::Tensor (const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_modified_bessel_k0";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "special_modified_bessel_k0(Tensor self) -> Tensor";
+  static at::Tensor call(const at::Tensor & self);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
+};
+
+struct TORCH_API special_modified_bessel_k0_out {
+  using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_modified_bessel_k0";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/b9/b9ee5b500fb7c42c00b501b20dee4ed5de6b02645b55b72b5ca7c84dde313352/cupti_range_profiler.h b/shared/package-files/b9/b9ee5b500fb7c42c00b501b20dee4ed5de6b02645b55b72b5ca7c84dde313352/cupti_range_profiler.h
new file mode 100644
index 0000000000000000000000000000000000000000..ebcb25c0921bf473df943d63f476b877fdec2d66
--- /dev/null
+++ b/shared/package-files/b9/b9ee5b500fb7c42c00b501b20dee4ed5de6b02645b55b72b5ca7c84dde313352/cupti_range_profiler.h
@@ -0,0 +1,465 @@
+/*
+ * Copyright 2024 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#if !defined(_CUPTI_RANGE_PROFILER_H_)
+#define _CUPTI_RANGE_PROFILER_H_
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility push(default)
+#endif
+
+/**
+ * \defgroup CUPTI_RANGE_PROFILER_API CUPTI Range Profiling API
+ * Functions, types, and enums that implement the CUPTI Range Profiling API.
+ * @{
+ */
+#ifndef CUPTI_PROFILER_STRUCT_SIZE
+#define CUPTI_PROFILER_STRUCT_SIZE(type_, lastfield_)                     (offsetof(type_, lastfield_) + sizeof(((type_*)0)->lastfield_))
+#endif
+
+
+typedef struct CUpti_RangeProfiler_Object CUpti_RangeProfiler_Object;
+
+/**
+ * \brief Params for cuptiRangeProfilerSetConfig
+ */
+typedef struct CUpti_RangeProfiler_SetConfig_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [in] Size of the config image.
+    size_t configSize;
+    /// [in] Config image.
+    const uint8_t* pConfig;
+    /// [in] Size of the counter data image.
+    size_t counterDataImageSize;
+    /// [in] Counter data image.
+    uint8_t* pCounterDataImage;
+    /// [in] Profiling Range mode.
+    CUpti_ProfilerRange range;
+    /// [in] Replay mode.
+    CUpti_ProfilerReplayMode replayMode;
+    /// [in] Maximum number of ranges that can be profiled in a pass.
+    size_t maxRangesPerPass;
+    /// [in] number of nesting level to be profiled. For Auto range mode, this should be set to 1.
+    uint16_t numNestingLevels;
+    /// [in] minimum nesting level to be profiled.
+    uint16_t minNestingLevel;
+    /// [in] Pass index for the replay session.
+    size_t passIndex;
+    /// [in] Target nesting level for the replay session.
+    uint16_t targetNestingLevel;
+} CUpti_RangeProfiler_SetConfig_Params;
+
+#define CUpti_RangeProfiler_SetConfig_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_SetConfig_Params, targetNestingLevel)
+
+/**
+ * \brief Set the configuration for range profiler like maximum number of ranges per pass, number of nesting levels,
+ * range and replay mode and the config image which has scheduling info for metric collection.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_SetConfig_Params
+ *
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ */
+CUptiResult CUPTIAPI cuptiRangeProfilerSetConfig(CUpti_RangeProfiler_SetConfig_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerEnable
+ */
+typedef struct CUpti_RangeProfiler_Enable_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Context to be used for profiling.
+    CUcontext ctx;
+    /// [out] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+} CUpti_RangeProfiler_Enable_Params;
+#define CUpti_RangeProfiler_Enable_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_Enable_Params, pRangeProfilerObject)
+
+/**
+ * \brief Create a range profiler object and enable range profiling on the CUDA context.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_Enable_Params
+ *
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_OUT_OF_MEMORY if memory allocation fails while creating the PM sampling object
+ * \retval CUPTI_ERROR_INSUFFICIENT_PRIVILEGES if the user does not have sufficient privileges to perform the operation
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+ */
+CUptiResult CUPTIAPI cuptiRangeProfilerEnable(CUpti_RangeProfiler_Enable_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerDisable
+ */
+typedef struct CUpti_RangeProfiler_Disable_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+} CUpti_RangeProfiler_Disable_Params;
+#define CUpti_RangeProfiler_Disable_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_Disable_Params, pRangeProfilerObject)
+
+/**
+ * \brief Disable the range profiler on the CUDA context and destroy the range profiler object.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_Disable_Params
+ *
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ */
+CUptiResult CUPTIAPI cuptiRangeProfilerDisable(CUpti_RangeProfiler_Disable_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerStart
+ */
+typedef struct CUpti_RangeProfiler_Start_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+} CUpti_RangeProfiler_Start_Params;
+#define CUpti_RangeProfiler_Start_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_Start_Params, pRangeProfilerObject)
+
+/**
+ * \brief Start the range profiler.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_Start_Params
+ *
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler Start is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+ */
+CUptiResult CUPTIAPI cuptiRangeProfilerStart(CUpti_RangeProfiler_Start_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerStop
+ */
+typedef struct CUpti_RangeProfiler_Stop_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [out] pass index for the replay session.
+    size_t passIndex;
+    /// [out] target nesting level for the replay session.
+    size_t targetNestingLevel;
+    /// [out] 1 if all passes are submitted to GPU for collection, 0 otherwise.
+    uint8_t isAllPassSubmitted;
+} CUpti_RangeProfiler_Stop_Params;
+#define CUpti_RangeProfiler_Stop_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_Stop_Params, isAllPassSubmitted)
+
+/**
+ * \brief Stop the range profiler.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_Stop_Params
+ *
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler Stop is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+ */
+CUptiResult CUPTIAPI cuptiRangeProfilerStop(CUpti_RangeProfiler_Stop_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerPushRange
+ */
+typedef struct CUpti_RangeProfiler_PushRange_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [in] Name of the range to be profiled (only valid for User range mode).
+    const char* pRangeName;
+} CUpti_RangeProfiler_PushRange_Params;
+#define CUpti_RangeProfiler_PushRange_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_PushRange_Params, pRangeName)
+
+/**
+ * \brief Add a new range to the Range Profiler with a given range name.
+ * For nested ranges, this API should be called again for the innermost range. For profiling the nested
+ * range, users need to set the values for minNestingLevel and numNestingLevels in the SetConfig API.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_PushRange_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler PushRange is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerPushRange(CUpti_RangeProfiler_PushRange_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerPopRange
+ */
+typedef struct CUpti_RangeProfiler_PopRange_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+} CUpti_RangeProfiler_PopRange_Params;
+#define CUpti_RangeProfiler_PopRange_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_PopRange_Params, pRangeProfilerObject)
+
+/**
+ * \brief pop the current range to the Range Profiler.
+ * The number of pop range API call should be same as number of push ranges in the same order.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_PopRange_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler PopRange is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerPopRange(CUpti_RangeProfiler_PopRange_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerDecodeData
+ */
+typedef struct CUpti_RangeProfiler_DecodeData_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Range Profiler Object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [out] Number of ranges dropped in the processed passes.
+    size_t numOfRangeDropped;
+} CUpti_RangeProfiler_DecodeData_Params;
+#define CUpti_RangeProfiler_DecodeData_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_DecodeData_Params, numOfRangeDropped)
+
+/**
+ * \brief Decode the profiling data stored in the hardware to the counter data image passed in the
+ * SetConfig API. This API should be called after cuptiRangeProfilerStop. The counter data image
+ * will be updated with the profiling data for the ranges profiled.
+ * 
+ * For the cases where the number of ranges counter data image can store is less than the number of ranges
+ * profiled (= maxRangesPerPass in SetConfig API), the counter data image will report dropped ranges.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_DecodeData_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler DecodeData is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerDecodeData(CUpti_RangeProfiler_DecodeData_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerGetCounterDataSize
+ */
+typedef struct CUpti_RangeProfiler_GetCounterDataSize_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Periodic sampler object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [in] Names of the metrics to be collected.
+    const char** pMetricNames;
+    /// [in] Number of metrics to be collected.
+    size_t numMetrics;
+    /// [in] Maximum number of ranges to be stored in the counter data image.
+    size_t maxNumOfRanges;
+    /// [in] Maximum number of RangeTree nodes; must be >= maxNumOfRanges
+    uint32_t maxNumRangeTreeNodes;
+    /// [out] Size of the counter data image.
+    size_t counterDataSize;
+} CUpti_RangeProfiler_GetCounterDataSize_Params;
+#define CUpti_RangeProfiler_GetCounterDataSize_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_GetCounterDataSize_Params, counterDataSize)
+
+/**
+ * \brief Get the size of the counter data image required to store the profiling data for the ranges profiled.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_GetCounterDataSize_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler GetCounterDataSize is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerGetCounterDataSize(CUpti_RangeProfiler_GetCounterDataSize_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerCounterDataImageInitialize
+ */
+typedef struct CUpti_RangeProfiler_CounterDataImage_Initialize_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Periodic sampler object.
+    CUpti_RangeProfiler_Object* pRangeProfilerObject;
+    /// [in] Size of the counter data image.
+    size_t counterDataSize;
+    /// [in] Counter data image.
+    uint8_t* pCounterData;
+} CUpti_RangeProfiler_CounterDataImage_Initialize_Params;
+#define CUpti_RangeProfiler_CounterDataImage_Initialize_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_CounterDataImage_Initialize_Params, pCounterData)
+
+/**
+ * \brief Initialize the counter data image with the profiling data for the ranges profiled.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_CounterDataImage_Initialize_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_INVALID_OPERATION if range profiler CounterDataImageInitialize is called without enabling range profiler
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerCounterDataImageInitialize(CUpti_RangeProfiler_CounterDataImage_Initialize_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerGetCounterDataInfo
+ */
+typedef struct CUpti_RangeProfiler_GetCounterDataInfo_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Counter data image.
+    const uint8_t* pCounterDataImage;
+    /// [in] Size of the counter data image.
+    size_t counterDataImageSize;
+    /// [out] Number of ranges in the counter data image.
+    size_t numTotalRanges;
+} CUpti_RangeProfiler_GetCounterDataInfo_Params;
+#define CUpti_RangeProfiler_GetCounterDataInfo_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_GetCounterDataInfo_Params, numTotalRanges)
+
+/**
+ * \brief Get the number of ranges stored in the counter data image.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_GetCounterDataInfo_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerGetCounterDataInfo(CUpti_RangeProfiler_GetCounterDataInfo_Params* pParams);
+
+/**
+ * \brief Params for cuptiRangeProfilerCounterDataGetRangeInfo
+ */
+typedef struct CUpti_RangeProfiler_CounterData_GetRangeInfo_Params
+{
+    /// [in] Size of the data structure.
+    size_t structSize;
+    /// [in] Set to NULL.
+    void* pPriv;
+    /// [in] Counter data image.
+    const uint8_t* pCounterDataImage;
+    /// [in] Size of the counter data image.
+    size_t counterDataImageSize;
+    /// [in] Index of the sample.
+    size_t rangeIndex;
+    /// [in] range delimiter.
+    const char* rangeDelimiter;
+    /// [out] RangeName;
+    const char* rangeName;
+} CUpti_RangeProfiler_CounterData_GetRangeInfo_Params;
+#define CUpti_RangeProfiler_CounterData_GetRangeInfo_Params_STRUCT_SIZE                  CUPTI_PROFILER_STRUCT_SIZE(CUpti_RangeProfiler_CounterData_GetRangeInfo_Params, rangeName)
+
+/**
+ * \brief Get the range name for the given range index.
+ * 
+ * \param pParams A pointer to \ref CUpti_RangeProfiler_CounterData_GetRangeInfo_Params
+ * 
+ * \retval CUPTI_SUCCESS
+ * \retval CUPTI_ERROR_INVALID_PARAMETER if any \p pParams is not valid
+ * \retval CUPTI_ERROR_UNKNOWN for any internal error
+*/
+CUptiResult CUPTIAPI cuptiRangeProfilerCounterDataGetRangeInfo(CUpti_RangeProfiler_CounterData_GetRangeInfo_Params* pParams);
+
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility pop
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /*_CUPTI_RANGE_PROFILER_H_*/
diff --git a/shared/package-files/b9/b9ef85b3358590ba80d6506dffbbfdb3d8817b3b0b18d26ec416a7a9a968ce1c/test_geometric.cpython-311.pyc b/shared/package-files/b9/b9ef85b3358590ba80d6506dffbbfdb3d8817b3b0b18d26ec416a7a9a968ce1c/test_geometric.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d034f6b3c1c10afe41856d6eb0578c557e2ef874
Binary files /dev/null and b/shared/package-files/b9/b9ef85b3358590ba80d6506dffbbfdb3d8817b3b0b18d26ec416a7a9a968ce1c/test_geometric.cpython-311.pyc differ
diff --git a/shared/package-files/b9/b9facd2bcb57ab95a56f6c347fe83033f9596a0c89a8551195484af91b401ddc/hardsigmoid.h b/shared/package-files/b9/b9facd2bcb57ab95a56f6c347fe83033f9596a0c89a8551195484af91b401ddc/hardsigmoid.h
new file mode 100644
index 0000000000000000000000000000000000000000..c4d1e7294a1b31ac68513c9ece6d99341c633b24
--- /dev/null
+++ b/shared/package-files/b9/b9facd2bcb57ab95a56f6c347fe83033f9596a0c89a8551195484af91b401ddc/hardsigmoid.h
@@ -0,0 +1,45 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & hardsigmoid_out(at::Tensor & out, const at::Tensor & self) {
+    return at::_ops::hardsigmoid_out::call(self, out);
+}
+// aten::hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & hardsigmoid_outf(const at::Tensor & self, at::Tensor & out) {
+    return at::_ops::hardsigmoid_out::call(self, out);
+}
+
+// aten::hardsigmoid(Tensor self) -> Tensor
+inline at::Tensor hardsigmoid(const at::Tensor & self) {
+    return at::_ops::hardsigmoid::call(self);
+}
+
+// aten::hardsigmoid_(Tensor(a!) self) -> Tensor(a!)
+inline at::Tensor & hardsigmoid_(at::Tensor & self) {
+    return at::_ops::hardsigmoid_::call(self);
+}
+
+}
diff --git a/shared/package-files/bc/bc3591c9a094737e6e7d50f4a774457c862bb82a9dd6d2399bc0c06241d5db17/_lower_to_native_backend.cpython-311.pyc b/shared/package-files/bc/bc3591c9a094737e6e7d50f4a774457c862bb82a9dd6d2399bc0c06241d5db17/_lower_to_native_backend.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41146b45b5bf108512f69b6bcf553c40dae3a158
Binary files /dev/null and b/shared/package-files/bc/bc3591c9a094737e6e7d50f4a774457c862bb82a9dd6d2399bc0c06241d5db17/_lower_to_native_backend.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e606b6a3b6b43046a31ff5379b0313c230066f22d29b1fe17e8db6bc77bad9b5/_reporting_descriptor.cpython-311.pyc b/shared/package-files/e6/e606b6a3b6b43046a31ff5379b0313c230066f22d29b1fe17e8db6bc77bad9b5/_reporting_descriptor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b189f4693ad2065b7d5abb92466d7d606a358c1
Binary files /dev/null and b/shared/package-files/e6/e606b6a3b6b43046a31ff5379b0313c230066f22d29b1fe17e8db6bc77bad9b5/_reporting_descriptor.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e608a8927813a6f66bf5e0900f5359442eb3e097e697190929dfd358c8cd500c/convolution_backward_overrideable.h b/shared/package-files/e6/e608a8927813a6f66bf5e0900f5359442eb3e097e697190929dfd358c8cd500c/convolution_backward_overrideable.h
new file mode 100644
index 0000000000000000000000000000000000000000..116ff8c4f090f0c3d1a8c2a25c5e293cbaeb76c4
--- /dev/null
+++ b/shared/package-files/e6/e608a8927813a6f66bf5e0900f5359442eb3e097e697190929dfd358c8cd500c/convolution_backward_overrideable.h
@@ -0,0 +1,92 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+inline ::std::tuple convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask);
+  }
+}
+
+// aten::convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+inline ::std::tuple convolution_backward_overrideable_symint(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask);
+  }
+}
+
+// aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+inline ::std::tuple convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
+  }
+}
+
+// aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+inline ::std::tuple convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
+  }
+}
+
+// aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+inline ::std::tuple convolution_backward_overrideable_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
+  }
+}
+
+// aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+inline ::std::tuple convolution_backward_overrideable_symint_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
+}
+namespace symint {
+  template >>
+  ::std::tuple convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
+    return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
+  }
+}
+
+}
diff --git a/shared/package-files/e6/e60e78c99f38352fbcac034da79cbd221bf5c76f7da096a65e58ee3dbfe1d9d1/CUDAPluggableAllocator.h b/shared/package-files/e6/e60e78c99f38352fbcac034da79cbd221bf5c76f7da096a65e58ee3dbfe1d9d1/CUDAPluggableAllocator.h
new file mode 100644
index 0000000000000000000000000000000000000000..d80b3782937ed85e7630c19053f14ba371cd5063
--- /dev/null
+++ b/shared/package-files/e6/e60e78c99f38352fbcac034da79cbd221bf5c76f7da096a65e58ee3dbfe1d9d1/CUDAPluggableAllocator.h
@@ -0,0 +1,192 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+
+namespace torch::cuda::CUDAPluggableAllocator {
+
+using MallocFuncType = void*(size_t, int, cudaStream_t);
+using FreeFuncType = void(void*, size_t, int, cudaStream_t);
+
+// A CUDAPluggableAllocatorDeleterContext object is used as the `ctx`
+// argument for DataPtr. We need context because a user can use
+// multiple allocators in the same PyTorch program, and
+// the allocators can have different free functions, such as:
+// free, cudaFree, cudaFreeAsync, ncclMemFree etc.
+struct TORCH_CUDA_CPP_API CUDAPluggableAllocatorDeleterContext {
+  explicit CUDAPluggableAllocatorDeleterContext(
+      std::function free_fn,
+      void* data,
+      size_t size,
+      int device,
+      cudaStream_t stream);
+
+  void free();
+
+ private:
+  std::function free_fn_;
+  void* data_;
+  size_t size_;
+  int device_;
+  cudaStream_t stream_{};
+};
+
+#if defined(USE_ROCM)
+using streamType = c10::hip::HIPStream;
+#else
+using streamType = c10::cuda::CUDAStream;
+#endif
+
+TORCH_CUDA_CPP_API std::shared_ptr<
+    c10::cuda::CUDACachingAllocator::CUDAAllocator>
+getCurrentAllocator();
+TORCH_CUDA_CPP_API std::shared_ptr<
+    c10::cuda::CUDACachingAllocator::CUDAAllocator>
+createCustomAllocator(
+    std::function alloc_fn,
+    std::function free_fn);
+TORCH_CUDA_CPP_API void changeCurrentAllocator(
+    const std::shared_ptr&
+        allocator);
+
+struct _AllocationMetadata {
+  _AllocationMetadata();
+  _AllocationMetadata(
+      size_t size,
+      c10::DeviceIndex device_idx,
+      cudaStream_t stream);
+  size_t size;
+  c10::DeviceIndex device_idx;
+  cudaStream_t stream{};
+};
+
+struct TORCH_CUDA_CPP_API CUDAPluggableAllocator
+    : public c10::cuda::CUDACachingAllocator::CUDAAllocator {
+  CUDAPluggableAllocator(
+      std::function alloc_fn,
+      std::function free_fn);
+
+  CUDAPluggableAllocator(CUDAPluggableAllocator& other);
+  CUDAPluggableAllocator(CUDAPluggableAllocator&& other) = delete;
+  CUDAPluggableAllocator& operator=(const CUDAPluggableAllocator& other) =
+      delete;
+  CUDAPluggableAllocator& operator=(CUDAPluggableAllocator&& other) = delete;
+  ~CUDAPluggableAllocator() override = default;
+
+  void set_init_fn(std::function init_fn);
+
+  void set_reset_fn(std::function reset_fn);
+
+  void set_memory_fraction_fn(
+      std::function memory_fraction_fn);
+
+  void set_base_alloc_fn(std::function base_alloc_fn);
+
+  void set_record_stream_fn(
+      std::function record_stream_fn);
+
+  void set_begin_allocate_to_pool(
+      std::function<
+          void(int, c10::cuda::MempoolId_t, std::function)>
+          capture_begin_fn);
+
+  void set_end_allocate_to_pool_fn(
+      std::function capture_about_to_end_fn);
+
+  void set_release_pool(
+      std::function capture_destroy_fn);
+
+  void* malloc(size_t size, c10::DeviceIndex device, cudaStream_t stream);
+
+  c10::DataPtr allocate(size_t size) override;
+  c10::DeleterFnPtr raw_deleter() const override;
+
+  void* raw_alloc(size_t nbytes) override;
+  void* raw_alloc_with_stream(size_t nbytes, cudaStream_t stream) override;
+  void raw_delete(void* ptr) override;
+  void init(int device_count) override;
+  bool initialized() override;
+  double getMemoryFraction(c10::DeviceIndex device) override;
+  void setMemoryFraction(double fraction, c10::DeviceIndex device) override;
+  void emptyCache() override;
+  void enable(bool) override {}
+  bool isEnabled() const override {
+    return true;
+  }
+  void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) override;
+  void* getBaseAllocation(void* ptr, size_t* size) override;
+
+  void recordStream(const c10::DataPtr&, streamType stream) override;
+
+  c10::CachingDeviceAllocator::DeviceStats getDeviceStats(
+      c10::DeviceIndex device) override;
+  void resetAccumulatedStats(c10::DeviceIndex device) override;
+  void resetPeakStats(c10::DeviceIndex device) override;
+  c10::cuda::CUDACachingAllocator::SnapshotInfo snapshot() override;
+  void beginAllocateToPool(
+      c10::DeviceIndex device,
+      c10::cuda::MempoolId_t mempool_id,
+      std::function) override;
+  void endAllocateToPool(
+      c10::DeviceIndex device,
+      c10::cuda::MempoolId_t mempool_id) override;
+  void releasePool(c10::DeviceIndex device, c10::cuda::MempoolId_t mempool_id)
+      override;
+  std::shared_ptr getIpcDevPtr(std::string handle) override;
+  c10::cuda::CUDACachingAllocator::ShareableHandle shareIpcHandle(
+      void*) override;
+  void recordHistory(
+      bool enabled,
+      c10::cuda::CUDACachingAllocator::CreateContextFn context_recorder,
+      size_t alloc_trace_max_entries,
+      c10::cuda::CUDACachingAllocator::RecordContext when) override;
+  void attachOutOfMemoryObserver(
+      c10::cuda::CUDACachingAllocator::OutOfMemoryObserver observer) override;
+  void attachAllocatorTraceTracker(
+      c10::cuda::CUDACachingAllocator::AllocatorTraceTracker tracker) override;
+  std::shared_ptr
+  getCheckpointState(c10::DeviceIndex device, at::cuda::MempoolId_t id)
+      override;
+  c10::cuda::CUDACachingAllocator::CheckpointDelta setCheckpointPoolState(
+      c10::DeviceIndex device,
+      std::shared_ptr pps)
+      override;
+  void enablePeerAccess(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access)
+      override;
+  cudaError_t memcpyAsync(
+      void* dst,
+      int dstDevice,
+      const void* src,
+      int srcDevice,
+      size_t count,
+      cudaStream_t stream,
+      bool p2p_enabled) override;
+  std::string name() override;
+  void copy_data(void* dest, const void* src, std::size_t count) const final;
+
+ protected:
+  std::function alloc_fn_;
+  std::function free_fn_;
+  std::function init_fn_;
+  std::function reset_fn_;
+  std::function memory_fraction_fn_;
+  std::function base_alloc_fn_;
+  std::function record_stream_fn_;
+  std::function<
+      void(int, c10::cuda::MempoolId_t, std::function)>
+      begin_allocate_to_pool_fn_;
+  std::function end_allocate_to_pool_fn_;
+  std::function relase_pool_fn_;
+  std::mutex allocator_mutex_;
+  // We do the bookeeping here in order to simplify custom allocators
+  std::unordered_map allocation_metadata_;
+
+  bool initialized_ = false;
+};
+} // namespace torch::cuda::CUDAPluggableAllocator
diff --git a/shared/package-files/e6/e60ed4784d70e17a42403331cfa90696a4c732637725a4fad79a15f55e9fc5a8/__init__.cpython-311.pyc b/shared/package-files/e6/e60ed4784d70e17a42403331cfa90696a4c732637725a4fad79a15f55e9fc5a8/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30e3cb8c1c8fa87fd46304c9acc4eae23ed6d5e2
Binary files /dev/null and b/shared/package-files/e6/e60ed4784d70e17a42403331cfa90696a4c732637725a4fad79a15f55e9fc5a8/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e61006e9a2fab7c4b489681c4f46c868983b850d1685f64787716ecdb00f99fc/DispatchKeyExtractor.h b/shared/package-files/e6/e61006e9a2fab7c4b489681c4f46c868983b850d1685f64787716ecdb00f99fc/DispatchKeyExtractor.h
new file mode 100644
index 0000000000000000000000000000000000000000..27438b926db558bcc2c460bea297745b98a2c14c
--- /dev/null
+++ b/shared/package-files/e6/e61006e9a2fab7c4b489681c4f46c868983b850d1685f64787716ecdb00f99fc/DispatchKeyExtractor.h
@@ -0,0 +1,258 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace c10 {
+
+namespace impl {
+
+// Take a DispatchKeySet for a Tensor and determine what the actual dispatch
+// DispatchKey should be, taking into account TLS, and skipping backends which
+// fall through.
+//
+// Unlike Tensor::key_set(), the value of this on a tensor can change depending
+// on TLS.
+//
+// NB: If there is no valid dispatch key, this will return Undefined
+inline DispatchKeySet computeDispatchKeySet(
+    DispatchKeySet ks,
+    // The key mask lets us eliminate (by zero entries) keys which should not
+    // be considered for dispatch.  There are two cases when we use this:
+    //
+    // - If an operator's dispatch table contains a fallthrough entry, we
+    //   should bypass it entirely when finding the key
+    // - If a user invokes with redispatch, the mask lets us
+    //   zero out the key the user asked us to stop.
+    //
+    // These excluded backends are NOT tracked in the TLS, but must be applied
+    // AFTER TLS (since the backend may have been introduced for consideration
+    // by the included TLS), which is why you have to pass them in to this
+    // function (as opposed to just applying it to the input 'ks').
+    DispatchKeySet key_mask) {
+  c10::impl::LocalDispatchKeySet local =
+      c10::impl::tls_local_dispatch_key_set();
+  // TODO: It's a bit irritating that we have to do logical ORs here, it would
+  // be nice to only do one.  Can always_included be folded into the TLS?  Well,
+  // it's a bit troublesome, because fastpath TLS access requires the type of
+  // the TLS in question to be zero-initialized, so you don't actually win
+  // anything in that case.
+  return (((ks | local.included_) - local.excluded_) & key_mask);
+}
+
+} // namespace impl
+
+namespace detail {
+// A small gadget to extract the DispatchKeySet from types which are known
+// to have it.  Used to extract dispatch keys from unboxed calls.
+struct MultiDispatchKeySet : at::IterArgs {
+  DispatchKeySet ts;
+  void operator()(const at::Tensor& x) {
+    ts = ts | x.key_set();
+  }
+  void operator()(const std::optional& x) {
+    if (x.has_value()) {
+      ts = ts | x->key_set();
+    }
+  }
+  void operator()(at::ArrayRef xs) {
+    for (const auto& x : xs) {
+      ts = ts | x.key_set();
+    }
+  }
+  // Tensor?[] translates to this case.
+  void operator()(const c10::List>& xs) {
+    for (std::optional x : xs) {
+      if (x.has_value()) {
+        ts = ts | x.value().key_set();
+      }
+    }
+  }
+  // Structured Tensor[] translates to this case
+  void operator()(const at::ITensorListRef& xs) {
+    for (const auto& x : xs) {
+      ts = ts | x.key_set();
+    }
+  }
+  [[noreturn]] void operator()(at::ArrayRef>) {
+    // Just checking that the handling of Tensor?[] didn't change.
+    TORCH_INTERNAL_ASSERT(false);
+  }
+  void operator()(const at::Generator& gen) {
+    if (gen.defined()) {
+      ts = ts | gen.key_set();
+    }
+  }
+  void operator()(const std::optional& gen) {
+    if (gen.has_value() && gen->defined()) {
+      ts = ts | gen->key_set();
+    }
+  }
+  template 
+  void operator()(const T&) {
+    // do nothing
+  }
+};
+
+// NB: take by const reference (Don't do universal forwarding here! You
+// don't want to move into this function!)
+template 
+DispatchKeySet multi_dispatch_key_set(const Args&... args) {
+  return MultiDispatchKeySet().apply(args...).ts;
+}
+} // namespace detail
+
+/**
+ * An instance of DispatchKeyExtractor knows how to get a dispatch key given
+ * a list of arguments for an operator call.
+ *
+ * The instance is specific for a certain operator as:
+ *  - In boxed dispatch, different operators have different ways to extract
+ *    the dispatch key (e.g. different numbers of arguments), and we precompute
+ *    the stack locations we should look at; and
+ *  - In all dispatch, some backends should be excluded from dispatch because
+ *    they have been registered as fallthrough.  The set of excluded backends
+ *    varies from operator, as some operators may have overridden the
+ *    fallthrough with custom behavior.
+ *
+ *   Note - this should maintain identical impl to the py dispatcher key
+ * extraction logic at pytorch/torch/dispatcher.py
+ */
+struct TORCH_API DispatchKeyExtractor final {
+ public:
+  static DispatchKeyExtractor make(const FunctionSchema& schema) {
+    return DispatchKeyExtractor(makeBitsetForDispatchArgs(schema));
+  }
+
+  static DispatchKeyExtractor makeUninitialized() {
+    return DispatchKeyExtractor(c10::utils::bitset());
+  }
+
+  void registerSchema(const FunctionSchema& schema) {
+    TORCH_INTERNAL_ASSERT(dispatch_arg_indices_reverse_.is_entirely_unset());
+    dispatch_arg_indices_reverse_ = makeBitsetForDispatchArgs(schema);
+  }
+  void deregisterSchema() {
+    dispatch_arg_indices_reverse_ = c10::utils::bitset();
+  }
+
+  DispatchKeySet getDispatchKeySetBoxed(const torch::jit::Stack* stack) const {
+    DispatchKeySet ks;
+    dispatch_arg_indices_reverse_.for_each_set_bit([&](size_t
+                                                           reverse_arg_index) {
+      const auto& ivalue = torch::jit::peek(*stack, 0, reverse_arg_index + 1);
+      if (C10_LIKELY(ivalue.isTensor())) {
+        // NB: Take care not to introduce a refcount bump (there's
+        // no safe toTensorRef method, alas)
+        ks = ks | ivalue.unsafeToTensorImpl()->key_set();
+      } else if (C10_UNLIKELY(ivalue.isTensorList())) {
+        for (const at::Tensor& tensor : ivalue.toTensorList()) {
+          ks = ks | tensor.key_set();
+        }
+      }
+      // Tensor?[] translates to a c10::List so we need to peek inside
+      else if (C10_UNLIKELY(ivalue.isList())) {
+        for (const auto& elt : ivalue.toListRef()) {
+          if (elt.isTensor()) {
+            ks = ks | elt.toTensor().key_set();
+          }
+        }
+      }
+    });
+    // Keys that are fallthrough should be skipped
+    if (requiresBitsetPerBackend_) {
+      c10::impl::LocalDispatchKeySet tls =
+          c10::impl::tls_local_dispatch_key_set();
+      auto backend_idx =
+          ((ks | tls.included_) - tls.excluded_).getBackendIndex();
+      return impl::computeDispatchKeySet(
+          ks, nonFallthroughKeysPerBackend_[backend_idx]);
+    } else {
+      return impl::computeDispatchKeySet(ks, nonFallthroughKeys_);
+    }
+  }
+
+  template 
+  DispatchKeySet getDispatchKeySetUnboxed(const Args&... args) const {
+    auto ks = detail::multi_dispatch_key_set(args...);
+    // Keys that are fallthrough should be skipped
+    if (requiresBitsetPerBackend_) {
+      c10::impl::LocalDispatchKeySet tls =
+          c10::impl::tls_local_dispatch_key_set();
+      auto backend_idx =
+          ((ks | tls.included_) - tls.excluded_).getBackendIndex();
+      return impl::computeDispatchKeySet(
+          ks, nonFallthroughKeysPerBackend_[backend_idx]);
+    } else {
+      return impl::computeDispatchKeySet(ks, nonFallthroughKeys_);
+    }
+  }
+
+  void setOperatorHasFallthroughForKey(DispatchKey k, bool has_fallthrough);
+
+  std::string dumpState() const;
+  void checkInvariants(const FunctionSchema& schema) const;
+
+ private:
+  static c10::utils::bitset makeBitsetForDispatchArgs(
+      const FunctionSchema& schema) {
+    TORCH_CHECK(
+        schema.arguments().size() <= c10::utils::bitset::NUM_BITS(),
+        "The function schema has ",
+        schema.arguments().size(),
+        " arguments but this PyTorch build only supports ",
+        c10::utils::bitset::NUM_BITS());
+    c10::utils::bitset dispatch_arg_indices_reverse;
+    for (const auto index : c10::irange(schema.arguments().size())) {
+      if (schema.arguments()[index].type()->isSubtypeOf(*TensorType::get()) ||
+          schema.arguments()[index].type()->isSubtypeOf(
+              *ListType::ofTensors()) ||
+          schema.arguments()[index].type()->isSubtypeOf(
+              *ListType::ofOptionalTensors()) ||
+          schema.arguments()[index].type()->isSubtypeOf(
+              *OptionalType::ofTensor())) {
+        dispatch_arg_indices_reverse.set(schema.arguments().size() - 1 - index);
+      }
+    }
+    return dispatch_arg_indices_reverse;
+  }
+
+  explicit DispatchKeyExtractor(c10::utils::bitset dispatch_arg_indices_reverse)
+      : dispatch_arg_indices_reverse_(dispatch_arg_indices_reverse),
+        nonFallthroughKeys_(DispatchKeySet::FULL),
+        requiresBitsetPerBackend_(false) {
+    for (const auto i : c10::irange(nonFallthroughKeysPerBackend_.size())) {
+      nonFallthroughKeysPerBackend_[i] = DispatchKeySet::FULL;
+    }
+  }
+
+  // this is a bitset that has ones for each argument index which has to be
+  // considered for dispatch. This avoids having to iterate over the stack
+  // to find all the tensors. The bits are stored in reverse order, i.e.
+  // dispatch_arg_indices_reverse_[i] == true, then the i-th argument from
+  // the top of the stack (i.e. the i-th last argument of the function)
+  // is relevant for dispatch.
+  // dispatch_arg_indices_reverse_ is allowed to have zero bits set; that just
+  // means you must do the fallthrough
+  c10::utils::bitset dispatch_arg_indices_reverse_;
+
+  // Set of functionality keys for which the operator does NOT have fallthrough
+  // kernel.
+  DispatchKeySet nonFallthroughKeys_;
+  // Set of functionality keys for which the operator does NOT have fallthrough
+  // kernel, defined PER BACKEND. This is only needed if we know that the
+  // operator has a different set of fallthroughs defined for some backends.
+  std::array nonFallthroughKeysPerBackend_;
+  // Flag to tell us if we can use the single set of nonFallthroughKeys_ (fast
+  // path), or if we need to fall back to the slower path and check
+  // nonFallthroughKeysPerBackend_
+  bool requiresBitsetPerBackend_;
+};
+
+} // namespace c10
diff --git a/shared/package-files/e6/e61347cdfca665a4fa47ba58a122112522e1bfe8bc3e6c87d81ebf30d8d11b01/iso8859_4.cpython-311.pyc b/shared/package-files/e6/e61347cdfca665a4fa47ba58a122112522e1bfe8bc3e6c87d81ebf30d8d11b01/iso8859_4.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51b573102c3b36b417e2629595086c12d479b3c2
Binary files /dev/null and b/shared/package-files/e6/e61347cdfca665a4fa47ba58a122112522e1bfe8bc3e6c87d81ebf30d8d11b01/iso8859_4.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e61367332cd8c1a9a5d6c263eb6937119799ff6b23bd2ae51c37593414dabd35/textplot.cpython-311.pyc b/shared/package-files/e6/e61367332cd8c1a9a5d6c263eb6937119799ff6b23bd2ae51c37593414dabd35/textplot.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d660a8b8265936689522d9b657b998149a89437a
Binary files /dev/null and b/shared/package-files/e6/e61367332cd8c1a9a5d6c263eb6937119799ff6b23bd2ae51c37593414dabd35/textplot.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e613fa41980db558d0eb6b73c6bfbd4a6989801db266746b445d4e8eef440065/quantization_utils.cpython-311.pyc b/shared/package-files/e6/e613fa41980db558d0eb6b73c6bfbd4a6989801db266746b445d4e8eef440065/quantization_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a986c11a24c43c9a3c3fec56c1bf71464043661
Binary files /dev/null and b/shared/package-files/e6/e613fa41980db558d0eb6b73c6bfbd4a6989801db266746b445d4e8eef440065/quantization_utils.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6168421e48262a5418fe991c3b8265635b82328521dde232111e4848bb6d8ae/aoti_schema.py b/shared/package-files/e6/e6168421e48262a5418fe991c3b8265635b82328521dde232111e4848bb6d8ae/aoti_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..d19add43705c959474722aef692e96ac8fa09628
--- /dev/null
+++ b/shared/package-files/e6/e6168421e48262a5418fe991c3b8265635b82328521dde232111e4848bb6d8ae/aoti_schema.py
@@ -0,0 +1,14 @@
+from dataclasses import dataclass
+
+from torch._export.serde.schema import Node
+
+
+@dataclass
+class ExternKernelNode:
+    name: str
+    node: Node
+
+
+@dataclass
+class ExternKernelNodes:
+    nodes: list[ExternKernelNode]
diff --git a/shared/package-files/e6/e61837e1a5de726747380f1e530b2984d850cded94ec9d2c12c2e9014b0675b7/test_ticks.cpython-311.pyc b/shared/package-files/e6/e61837e1a5de726747380f1e530b2984d850cded94ec9d2c12c2e9014b0675b7/test_ticks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0233a6eb00805e17b88fca9591e3a5112038e95b
Binary files /dev/null and b/shared/package-files/e6/e61837e1a5de726747380f1e530b2984d850cded94ec9d2c12c2e9014b0675b7/test_ticks.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6184ce10e266134fdcfa401e8f1a95005bcd4f18d16b62b757323e2833fe9a9/INSTALLER b/shared/package-files/e6/e6184ce10e266134fdcfa401e8f1a95005bcd4f18d16b62b757323e2833fe9a9/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/shared/package-files/e6/e6184ce10e266134fdcfa401e8f1a95005bcd4f18d16b62b757323e2833fe9a9/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/shared/package-files/e6/e61a718992809902ff6d4016a3570229c7d3c87a9b288941885ef1f5a0b6456f/aminmax_meta_dispatch.h b/shared/package-files/e6/e61a718992809902ff6d4016a3570229c7d3c87a9b288941885ef1f5a0b6456f/aminmax_meta_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..f0b0c764f8e5997eef32d1187fb355df8d50b086
--- /dev/null
+++ b/shared/package-files/e6/e61a718992809902ff6d4016a3570229c7d3c87a9b288941885ef1f5a0b6456f/aminmax_meta_dispatch.h
@@ -0,0 +1,25 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace meta {
+
+TORCH_API ::std::tuple aminmax(const at::Tensor & self, ::std::optional dim=::std::nullopt, bool keepdim=false);
+TORCH_API ::std::tuple aminmax_out(at::Tensor & min, at::Tensor & max, const at::Tensor & self, ::std::optional dim=::std::nullopt, bool keepdim=false);
+TORCH_API ::std::tuple aminmax_outf(const at::Tensor & self, ::std::optional dim, bool keepdim, at::Tensor & min, at::Tensor & max);
+
+} // namespace meta
+} // namespace at
diff --git a/shared/package-files/e6/e61af7fdcaadd2f600398922ca4ca0aa8c77caf591d38ea6f172ade86a32957d/_util.cpython-311.pyc b/shared/package-files/e6/e61af7fdcaadd2f600398922ca4ca0aa8c77caf591d38ea6f172ade86a32957d/_util.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcb9b833c46593c03260b5b6be29a63b4fd95585
Binary files /dev/null and b/shared/package-files/e6/e61af7fdcaadd2f600398922ca4ca0aa8c77caf591d38ea6f172ade86a32957d/_util.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e61bd9f076f2689ad004ec87014be155e1f49169b6edeb682a1892173888c619/libbz2-a1e77c99.so.1.0.6 b/shared/package-files/e6/e61bd9f076f2689ad004ec87014be155e1f49169b6edeb682a1892173888c619/libbz2-a1e77c99.so.1.0.6
new file mode 100644
index 0000000000000000000000000000000000000000..ee2a16861ab5d257fa34ef203ece73a30657cb8a
Binary files /dev/null and b/shared/package-files/e6/e61bd9f076f2689ad004ec87014be155e1f49169b6edeb682a1892173888c619/libbz2-a1e77c99.so.1.0.6 differ
diff --git a/shared/package-files/e6/e61c30086e9fef27fbd8f7d41b488b224d9b011b195391097918c3c5242b90a2/test_interchange_spec.py b/shared/package-files/e6/e61c30086e9fef27fbd8f7d41b488b224d9b011b195391097918c3c5242b90a2/test_interchange_spec.py
new file mode 100644
index 0000000000000000000000000000000000000000..d060f7842c2fe0963d5a110c576240ba6503b7d3
--- /dev/null
+++ b/shared/package-files/e6/e61c30086e9fef27fbd8f7d41b488b224d9b011b195391097918c3c5242b90a2/test_interchange_spec.py
@@ -0,0 +1,293 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import ctypes
+import hypothesis as h
+import hypothesis.strategies as st
+
+import pytest
+try:
+    import numpy as np
+except ImportError:
+    np = None
+import pyarrow as pa
+import pyarrow.tests.strategies as past
+
+
+all_types = st.deferred(
+    lambda: (
+        past.signed_integer_types |
+        past.unsigned_integer_types |
+        past.floating_types |
+        past.bool_type |
+        past.string_type |
+        past.large_string_type
+    )
+)
+
+
+# datetime is tested in test_extra.py
+# dictionary is tested in test_categorical()
+@pytest.mark.numpy
+@h.given(past.arrays(all_types, size=3))
+def test_dtypes(arr):
+    table = pa.table([arr], names=["a"])
+    df = table.__dataframe__()
+
+    null_count = df.get_column(0).null_count
+    assert null_count == arr.null_count
+    assert isinstance(null_count, int)
+    assert df.get_column(0).size() == 3
+    assert df.get_column(0).offset == 0
+
+
+@pytest.mark.numpy
+@pytest.mark.parametrize(
+    "uint, uint_bw",
+    [
+        (pa.uint8(), 8),
+        (pa.uint16(), 16),
+        (pa.uint32(), 32)
+    ]
+)
+@pytest.mark.parametrize(
+    "int, int_bw", [
+        (pa.int8(), 8),
+        (pa.int16(), 16),
+        (pa.int32(), 32),
+        (pa.int64(), 64)
+    ]
+)
+@pytest.mark.parametrize(
+    "float, float_bw, np_float_str", [
+        (pa.float16(), 16, "float16"),
+        (pa.float32(), 32, "float32"),
+        (pa.float64(), 64, "float64")
+    ]
+)
+@pytest.mark.parametrize("unit", ['s', 'ms', 'us', 'ns'])
+@pytest.mark.parametrize("tz", ['', 'America/New_York', '+07:30', '-04:30'])
+@pytest.mark.parametrize("use_batch", [False, True])
+def test_mixed_dtypes(uint, uint_bw, int, int_bw,
+                      float, float_bw, np_float_str, unit, tz,
+                      use_batch):
+    from datetime import datetime as dt
+    arr = [1, 2, 3]
+    dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), dt(2007, 7, 15)]
+    table = pa.table(
+        {
+            "a": pa.array(arr, type=uint),
+            "b": pa.array(arr, type=int),
+            "c": pa.array(np.array(arr, dtype=np.dtype(np_float_str)), type=float),
+            "d": [True, False, True],
+            "e": ["a", "", "c"],
+            "f": pa.array(dt_arr, type=pa.timestamp(unit, tz=tz))
+        }
+    )
+    if use_batch:
+        table = table.to_batches()[0]
+    df = table.__dataframe__()
+    # 0 = DtypeKind.INT, 1 = DtypeKind.UINT, 2 = DtypeKind.FLOAT,
+    # 20 = DtypeKind.BOOL, 21 = DtypeKind.STRING, 22 = DtypeKind.DATETIME
+    # see DtypeKind class in column.py
+    columns = {"a": 1, "b": 0, "c": 2, "d": 20, "e": 21, "f": 22}
+
+    for column, kind in columns.items():
+        col = df.get_column_by_name(column)
+
+        assert col.null_count == 0
+        assert col.size() == 3
+        assert col.offset == 0
+        assert col.dtype[0] == kind
+
+    assert df.get_column_by_name("a").dtype[1] == uint_bw
+    assert df.get_column_by_name("b").dtype[1] == int_bw
+    assert df.get_column_by_name("c").dtype[1] == float_bw
+
+
+def test_na_float():
+    table = pa.table({"a": [1.0, None, 2.0]})
+    df = table.__dataframe__()
+    col = df.get_column_by_name("a")
+    assert col.null_count == 1
+    assert isinstance(col.null_count, int)
+
+
+def test_noncategorical():
+    table = pa.table({"a": [1, 2, 3]})
+    df = table.__dataframe__()
+    col = df.get_column_by_name("a")
+    with pytest.raises(TypeError, match=".*categorical.*"):
+        col.describe_categorical
+
+
+@pytest.mark.parametrize("use_batch", [False, True])
+def test_categorical(use_batch):
+    import pyarrow as pa
+    arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", None]
+    table = pa.table(
+        {"weekday": pa.array(arr).dictionary_encode()}
+    )
+    if use_batch:
+        table = table.to_batches()[0]
+
+    col = table.__dataframe__().get_column_by_name("weekday")
+    categorical = col.describe_categorical
+    assert isinstance(categorical["is_ordered"], bool)
+    assert isinstance(categorical["is_dictionary"], bool)
+
+
+@pytest.mark.parametrize("use_batch", [False, True])
+def test_dataframe(use_batch):
+    n = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
+    a = pa.chunked_array([["Flamingo", "Parrot", "Cow"],
+                         ["Horse", "Brittle stars", "Centipede"]])
+    table = pa.table([n, a], names=['n_legs', 'animals'])
+    if use_batch:
+        table = table.combine_chunks().to_batches()[0]
+    df = table.__dataframe__()
+
+    assert df.num_columns() == 2
+    assert df.num_rows() == 6
+    if use_batch:
+        assert df.num_chunks() == 1
+    else:
+        assert df.num_chunks() == 2
+    assert list(df.column_names()) == ['n_legs', 'animals']
+    assert list(df.select_columns((1,)).column_names()) == list(
+        df.select_columns_by_name(("animals",)).column_names()
+    )
+
+
+@pytest.mark.parametrize("use_batch", [False, True])
+@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
+def test_df_get_chunks(use_batch, size, n_chunks):
+    table = pa.table({"x": list(range(size))})
+    if use_batch:
+        table = table.to_batches()[0]
+    df = table.__dataframe__()
+    chunks = list(df.get_chunks(n_chunks))
+    assert len(chunks) == n_chunks
+    assert sum(chunk.num_rows() for chunk in chunks) == size
+
+
+@pytest.mark.parametrize("use_batch", [False, True])
+@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
+def test_column_get_chunks(use_batch, size, n_chunks):
+    table = pa.table({"x": list(range(size))})
+    if use_batch:
+        table = table.to_batches()[0]
+    df = table.__dataframe__()
+    chunks = list(df.get_column(0).get_chunks(n_chunks))
+    assert len(chunks) == n_chunks
+    assert sum(chunk.size() for chunk in chunks) == size
+
+
+@pytest.mark.pandas
+@pytest.mark.parametrize(
+    "uint", [pa.uint8(), pa.uint16(), pa.uint32()]
+)
+@pytest.mark.parametrize(
+    "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()]
+)
+@pytest.mark.parametrize(
+    "float, np_float_str", [
+        (pa.float16(), "float16"),
+        (pa.float32(), "float32"),
+        (pa.float64(), "float64")
+    ]
+)
+@pytest.mark.parametrize("use_batch", [False, True])
+def test_get_columns(uint, int, float, np_float_str, use_batch):
+    arr = [[1, 2, 3], [4, 5]]
+    arr_float = np.array([1, 2, 3, 4, 5], dtype=np.dtype(np_float_str))
+    table = pa.table(
+        {
+            "a": pa.chunked_array(arr, type=uint),
+            "b": pa.chunked_array(arr, type=int),
+            "c": pa.array(arr_float, type=float)
+        }
+    )
+    if use_batch:
+        table = table.combine_chunks().to_batches()[0]
+    df = table.__dataframe__()
+    for col in df.get_columns():
+        assert col.size() == 5
+        assert col.num_chunks() == 1
+
+    # 0 = DtypeKind.INT, 1 = DtypeKind.UINT, 2 = DtypeKind.FLOAT,
+    # see DtypeKind class in column.py
+    assert df.get_column(0).dtype[0] == 1  # UINT
+    assert df.get_column(1).dtype[0] == 0  # INT
+    assert df.get_column(2).dtype[0] == 2  # FLOAT
+
+
+@pytest.mark.parametrize(
+    "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()]
+)
+@pytest.mark.parametrize("use_batch", [False, True])
+def test_buffer(int, use_batch):
+    arr = [0, 1, -1]
+    table = pa.table({"a": pa.array(arr, type=int)})
+    if use_batch:
+        table = table.to_batches()[0]
+    df = table.__dataframe__()
+    col = df.get_column(0)
+    buf = col.get_buffers()
+
+    dataBuf, dataDtype = buf["data"]
+
+    assert dataBuf.bufsize > 0
+    assert dataBuf.ptr != 0
+    device, _ = dataBuf.__dlpack_device__()
+
+    # 0 = DtypeKind.INT
+    # see DtypeKind class in column.py
+    assert dataDtype[0] == 0
+
+    if device == 1:  # CPU-only as we're going to directly read memory here
+        bitwidth = dataDtype[1]
+        ctype = {
+            8: ctypes.c_int8,
+            16: ctypes.c_int16,
+            32: ctypes.c_int32,
+            64: ctypes.c_int64,
+        }[bitwidth]
+
+        for idx, truth in enumerate(arr):
+            val = ctype.from_address(dataBuf.ptr + idx * (bitwidth // 8)).value
+            assert val == truth, f"Buffer at index {idx} mismatch"
+
+
+@pytest.mark.parametrize(
+    "indices_type, bitwidth, f_string", [
+        (pa.int8(), 8, "c"),
+        (pa.int16(), 16, "s"),
+        (pa.int32(), 32, "i"),
+        (pa.int64(), 64, "l")
+    ]
+)
+def test_categorical_dtype(indices_type, bitwidth, f_string):
+    type = pa.dictionary(indices_type, pa.string())
+    arr = pa.array(["a", "b", None, "d"], type)
+    table = pa.table({'a': arr})
+
+    df = table.__dataframe__()
+    col = df.get_column(0)
+    assert col.dtype[0] == 23  # 
+    assert col.dtype[1] == bitwidth
+    assert col.dtype[2] == f_string
diff --git a/shared/package-files/e6/e61ebb01e4a7e68629de1b851d551063325a55b4a87b993532f545beb7bd1328/edlib.c.pysam.c b/shared/package-files/e6/e61ebb01e4a7e68629de1b851d551063325a55b4a87b993532f545beb7bd1328/edlib.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..e5b69984dc3d2341bdd5585ed44feec7eee76b4b
--- /dev/null
+++ b/shared/package-files/e6/e61ebb01e4a7e68629de1b851d551063325a55b4a87b993532f545beb7bd1328/edlib.c.pysam.c
@@ -0,0 +1,664 @@
+#include "bcftools.pysam.h"
+
+/*
+ * A cut down C translated of the C++ edlib.cpp file.
+ * Taken from edlib v0.1.0-166-g931be2b
+ */
+
+#include 
+#include 
+#include 
+#include 
+
+#include "edlib.h"
+
+typedef uint64_t Word;
+static const int WORD_SIZE = 64; // Size of Word in bits
+static const Word WORD_1 = (Word)1;
+static const Word HIGH_BIT_MASK = 1LL << 63;  // 100..00
+//#define MAX_UCHAR 255
+#define MAX_UCHAR 7 // better cache usage for our data
+
+#ifndef MAX
+#define MAX(a,b) ((a)>(b)?(a):(b))
+#endif
+
+typedef struct Block {
+    Word P;  // Pvin
+    Word M;  // Mvin
+    int score; // score of last cell in block;
+} Block;
+
+
+/**
+ * Defines equality relation on alphabet characters.
+ * By default each character is always equal only to itself, but you can also provide additional equalities.
+ */
+typedef struct EqualityDefinition {
+    bool matrix[MAX_UCHAR + 1][MAX_UCHAR + 1];
+} EqualityDefinition;
+
+static EqualityDefinition *
+CreateEqualityDefinition(const char *alphabet, int alphabet_size,
+			 const EdlibEqualityPair* additionalEqualities,
+			 const int additionalEqualitiesLength) {
+    EqualityDefinition *ed = malloc(sizeof(*ed));
+
+    for (size_t i = 0; i < alphabet_size; i++) {
+	for (size_t j = 0; j < alphabet_size; j++) {
+	    ed->matrix[i][j] = (i == j);
+	}
+    }
+    if (additionalEqualities != NULL) {
+	for (int i = 0; i < additionalEqualitiesLength; i++) {
+	    const char *firstTransformed = strchr(alphabet, additionalEqualities[i].first);
+	    const char *secondTransformed = strchr(alphabet, additionalEqualities[i].second);
+	    if (firstTransformed && alphabet_size) {
+		ed->matrix[firstTransformed - alphabet][secondTransformed - alphabet] =
+		ed->matrix[secondTransformed - alphabet][firstTransformed - alphabet]
+		    = true;
+	    }
+	}
+    }
+
+    return ed;
+}
+
+/**
+ * @param a  Element from transformed sequence.
+ * @param b  Element from transformed sequence.
+ * @return True if a and b are defined as equal, false otherwise.
+ */
+static inline const /* attribute pure or const? */
+bool equalityDefinition_areEqual(const EqualityDefinition *ed, unsigned char a, unsigned char b) {
+    return ed->matrix[a][b];
+}
+
+static int myersCalcEditDistanceSemiGlobal(const Word* Peq, int W, int maxNumBlocks,
+                                           int queryLength,
+                                           const unsigned char* target, int targetLength,
+                                           int k, EdlibAlignMode mode,
+                                           int* bestScore_, int** positions_, int* numPositions_);
+
+static char *transformSequences(const char* queryOriginal, int queryLength,
+				const char* targetOriginal, int targetLength,
+				unsigned char** queryTransformed,
+				unsigned char** targetTransformed,
+                                int *alphabet_size);
+
+static inline int ceilDiv(int x, int y);
+
+static inline unsigned char* createReverseCopy(const unsigned char* seq, int length);
+
+static inline Word* buildPeq(const int alphabetLength,
+                             const unsigned char* query,
+                             const int queryLength,
+                             const EqualityDefinition* equalityDefinition);
+
+
+/**
+ * Main edlib method.
+ */
+EdlibAlignResult edlibAlign(const char* const queryOriginal, const int queryLength,
+			    const char* const targetOriginal, const int targetLength,
+			    const EdlibAlignConfig config) {
+    EdlibAlignResult result;
+    result.status = EDLIB_STATUS_OK;
+    result.editDistance = -1;
+    result.endLocations = result.startLocations = NULL;
+    result.numLocations = 0;
+    result.alignment = NULL;
+    result.alignmentLength = 0;
+    result.alphabetLength = 0;
+
+    /*------------ TRANSFORM SEQUENCES AND RECOGNIZE ALPHABET -----------*/
+    unsigned char* query, * target;
+    int alphabet_size;
+    char *alphabet = transformSequences(queryOriginal, queryLength, targetOriginal, targetLength,
+                                         &query, &target, &alphabet_size);
+    result.alphabetLength = alphabet_size;
+    /*-------------------------------------------------------*/
+
+    // Handle special situation when at least one of the sequences has length 0.
+    if (queryLength == 0 || targetLength == 0) {
+        if (config.mode == EDLIB_MODE_NW) {
+            result.editDistance = MAX(queryLength, targetLength);
+            result.endLocations = malloc(sizeof(int) * 1);
+            result.endLocations[0] = targetLength - 1;
+            result.numLocations = 1;
+        } else if (config.mode == EDLIB_MODE_SHW || config.mode == EDLIB_MODE_HW) {
+            result.editDistance = queryLength;
+            result.endLocations = malloc(sizeof(int) * 1);
+            result.endLocations[0] = -1;
+            result.numLocations = 1;
+        } else {
+            result.status = EDLIB_STATUS_ERROR;
+        }
+
+        free(query);
+        free(target);
+        free(alphabet);
+        return result;
+    }
+
+    /*--------------------- INITIALIZATION ------------------*/
+    int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
+    int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
+    EqualityDefinition *equalityDefinition =
+	CreateEqualityDefinition(alphabet, alphabet_size, config.additionalEqualities, config.additionalEqualitiesLength);
+    Word* Peq = buildPeq(alphabet_size, query, queryLength, equalityDefinition);
+    /*-------------------------------------------------------*/
+
+    /*------------------ MAIN CALCULATION -------------------*/
+    // TODO: Store alignment data only after k is determined? That could make things faster.
+//    int positionNW; // Used only when mode is NW.
+//    AlignmentData* alignData = NULL;
+    bool dynamicK = false;
+    int k = config.k;
+    if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
+        dynamicK = true;
+        k = WORD_SIZE; // Gives better results than smaller k.
+    }
+
+    do {
+        if (config.mode == EDLIB_MODE_HW || config.mode == EDLIB_MODE_SHW) {
+            myersCalcEditDistanceSemiGlobal(Peq, W, maxNumBlocks,
+                                            queryLength, target, targetLength,
+                                            k, config.mode, &(result.editDistance),
+                                            &(result.endLocations), &(result.numLocations));
+        } else {  // mode == EDLIB_MODE_NW
+//            myersCalcEditDistanceNW(Peq, W, maxNumBlocks,
+//                                    queryLength, target, targetLength,
+//                                    k, &(result.editDistance), &positionNW,
+//                                    false, &alignData, -1);
+        }
+        k *= 2;
+    } while(dynamicK && result.editDistance == -1);
+
+    if (result.editDistance >= 0) {  // If there is solution.
+        // If NW mode, set end location explicitly.
+        if (config.mode == EDLIB_MODE_NW) {
+            result.endLocations = malloc(sizeof(int) * 1);
+            result.endLocations[0] = targetLength - 1;
+            result.numLocations = 1;
+        }
+
+        // Find starting locations.
+        if (config.task == EDLIB_TASK_LOC || config.task == EDLIB_TASK_PATH) {
+            result.startLocations = malloc(result.numLocations * sizeof(int));
+            if (config.mode == EDLIB_MODE_HW) {  // If HW, I need to calculate start locations.
+                const unsigned char* rTarget = createReverseCopy(target, targetLength);
+                const unsigned char* rQuery  = createReverseCopy(query, queryLength);
+                // Peq for reversed query.
+                Word* rPeq = buildPeq(alphabet_size, rQuery, queryLength, equalityDefinition);
+                for (int i = 0; i < result.numLocations; i++) {
+                    int endLocation = result.endLocations[i];
+                    if (endLocation == -1) {
+                        // NOTE: Sometimes one of optimal solutions is that query starts before target, like this:
+                        //                       AAGG <- target
+                        //                   CCTT     <- query
+                        //   It will never be only optimal solution and it does not happen often, however it is
+                        //   possible and in that case end location will be -1. What should we do with that?
+                        //   Should we just skip reporting such end location, although it is a solution?
+                        //   If we do report it, what is the start location? -4? -1? Nothing?
+                        // TODO: Figure this out. This has to do in general with how we think about start
+                        //   and end locations.
+                        //   Also, we have alignment later relying on this locations to limit the space of it's
+                        //   search -> how can it do it right if these locations are negative or incorrect?
+                        result.startLocations[i] = 0;  // I put 0 for now, but it does not make much sense.
+                    } else {
+                        int bestScoreSHW, numPositionsSHW;
+                        int* positionsSHW;
+                        myersCalcEditDistanceSemiGlobal(
+                                rPeq, W, maxNumBlocks,
+                                queryLength, rTarget + targetLength - endLocation - 1, endLocation + 1,
+                                result.editDistance, EDLIB_MODE_SHW,
+                                &bestScoreSHW, &positionsSHW, &numPositionsSHW);
+                        // Taking last location as start ensures that alignment will not start with insertions
+                        // if it can start with mismatches instead.
+                        result.startLocations[i] = endLocation - positionsSHW[numPositionsSHW - 1];
+                        free(positionsSHW);
+                    }
+                }
+                free((void *)rTarget);
+                free((void *)rQuery);
+                free(rPeq);
+            } else {  // If mode is SHW or NW
+                for (int i = 0; i < result.numLocations; i++) {
+                    result.startLocations[i] = 0;
+                }
+            }
+        }
+    }
+    /*-------------------------------------------------------*/
+
+    //--- Free memory ---//
+    free(Peq);
+    free(query);
+    free(target);
+    free(alphabet);
+    free(equalityDefinition);
+//    DestroyAlignmentData(alignData);
+    //-------------------//
+
+    return result;
+}
+
+/**
+ * Build Peq table for given query and alphabet.
+ * Peq is table of dimensions alphabetLength+1 x maxNumBlocks.
+ * Bit i of Peq[s * maxNumBlocks + b] is 1 if i-th symbol from block b of query equals symbol s, otherwise it is 0.
+ * NOTICE: free returned array with free()!
+ */
+static inline Word* buildPeq(const int alphabetLength,
+                             const unsigned char* const query,
+                             const int queryLength,
+                             const EqualityDefinition* equalityDefinition) {
+    int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
+    // table of dimensions alphabetLength+1 x maxNumBlocks. Last symbol is wildcard.
+    Word* Peq = malloc((alphabetLength + 1) * maxNumBlocks * sizeof(*Peq));
+
+    // Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
+    // Optimised Peq building avoiding branching.
+    for (int symbol = 0; symbol < alphabetLength; symbol++) {
+        for (int b = 0; b < maxNumBlocks; b++) {
+            Word PeqW = 0;
+            for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
+                PeqW = (PeqW<<1)
+                     + (r >= queryLength
+                        || equalityDefinition_areEqual(equalityDefinition,
+                                                       query[r], symbol)); 
+            }
+            Peq[symbol * maxNumBlocks + b] = PeqW;
+        }
+    }
+    {
+        int symbol = alphabetLength;
+        for (int b = 0; b < maxNumBlocks; b++) {
+            // Last symbol is wildcard, so it is all 1s
+            Peq[symbol * maxNumBlocks + b] = (Word)-1;
+        }
+    }
+
+    return Peq;
+}
+
+
+/**
+ * Returns new sequence that is reverse of given sequence.
+ * Free returned array with free()
+ */
+static inline unsigned char* createReverseCopy(const unsigned char* const seq, const int length) {
+    unsigned char* rSeq = malloc(length);
+    for (int i = 0; i < length; i++) {
+        rSeq[i] = seq[length - i - 1];
+    }
+    return rSeq;
+}
+
+/**
+ * Corresponds to Advance_Block function from Myers.
+ * Calculates one word(block), which is part of a column.
+ * Highest bit of word (one most to the left) is most bottom cell of block from column.
+ * Pv[i] and Mv[i] define vin of cell[i]: vin = cell[i] - cell[i-1].
+ * @param [in] Pv  Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
+ * @param [in] Mv  Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
+ * @param [in] Eq  Bitset, Eq[i] == 1 if match, 0 if mismatch.
+ * @param [in] hin  Will be +1, 0 or -1.
+ * @param [out] PvOut  Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
+ * @param [out] MvOut  Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
+ * @param [out] hout  Will be +1, 0 or -1.
+ */
+static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin,
+                                 Word *PvOut, Word *MvOut) {
+    // hin can be 1, -1 or 0.
+    // 1  -> 00...01
+    // 0  -> 00...00
+    // -1 -> 11...11 (2-complement)
+
+    Word hinIsNeg = (Word)(hin >> 2) & WORD_1; // 00...001 if hin is -1, 00...000 if 0 or 1
+
+    Word Xv = Eq | Mv;
+    // This is instruction below written using 'if': if (hin < 0) Eq |= (Word)1;
+    Eq |= hinIsNeg;
+    Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
+
+    Word Ph = Mv | ~(Xh | Pv);
+    Word Mh = Pv & Xh;
+
+    int hout = 0;
+    // This is instruction below written using 'if': if (Ph & HIGH_BIT_MASK) hout = 1;
+    hout = (Ph & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
+    // This is instruction below written using 'if': if (Mh & HIGH_BIT_MASK) hout = -1;
+    hout -= (Mh & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
+
+    Ph <<= 1;
+    Mh <<= 1;
+
+    // This is instruction below written using 'if': if (hin < 0) Mh |= (Word)1;
+    Mh |= hinIsNeg;
+    // This is instruction below written using 'if': if (hin > 0) Ph |= (Word)1;
+    Ph |= (Word)((hin + 1) >> 1);
+
+    *PvOut = Mh | ~(Xv | Ph);
+    *MvOut = Ph & Xv;
+
+    return hout;
+}
+
+/**
+ * Does ceiling division x / y.
+ * Note: x and y must be non-negative and x + y must not overflow.
+ */
+static inline int ceilDiv(const int x, const int y) {
+    return x % y ? x / y + 1 : x / y;
+}
+
+static inline int min(const int x, const int y) {
+    return x < y ? x : y;
+}
+
+
+/**
+ * @param [in] block
+ * @return Values of cells in block, starting with bottom cell in block.
+ */
+static inline int *getBlockCellValues(const Block block) {
+    int *scores = malloc(WORD_SIZE * sizeof(*scores));
+    int score = block.score;
+    Word mask = HIGH_BIT_MASK;
+    for (int i = 0; i < WORD_SIZE - 1; i++) {
+        scores[i] = score;
+        if (block.P & mask) score--;
+        if (block.M & mask) score++;
+        mask >>= 1;
+    }
+    scores[WORD_SIZE - 1] = score;
+    return scores;
+}
+
+/**
+ * @param [in] block
+ * @param [in] k
+ * @return True if all cells in block have value larger than k, otherwise false.
+ */
+static inline bool allBlockCellsLarger(const Block block, const int k) {
+    int *scores = getBlockCellValues(block);
+    for (int i = 0; i < WORD_SIZE; i++) {
+        if (scores[i] <= k) {
+            free(scores);
+            return false;
+        }
+    }
+
+    free(scores);
+    return true;
+}
+
+
+/**
+ * Uses Myers' bit-vector algorithm to find edit distance for one of semi-global alignment methods.
+ * @param [in] Peq  Query profile.
+ * @param [in] W  Size of padding in last block.
+ *                TODO: Calculate this directly from query, instead of passing it.
+ * @param [in] maxNumBlocks  Number of blocks needed to cover the whole query.
+ *                           TODO: Calculate this directly from query, instead of passing it.
+ * @param [in] queryLength
+ * @param [in] target
+ * @param [in] targetLength
+ * @param [in] k
+ * @param [in] mode  EDLIB_MODE_HW or EDLIB_MODE_SHW
+ * @param [out] bestScore_  Edit distance.
+ * @param [out] positions_  Array of 0-indexed positions in target at which best score was found.
+                            Make sure to free this array with free().
+ * @param [out] numPositions_  Number of positions in the positions_ array.
+ * @return Status.
+ */
+static int myersCalcEditDistanceSemiGlobal(
+        const Word* const Peq, const int W, const int maxNumBlocks,
+        const int queryLength,
+        const unsigned char* const target, const int targetLength,
+        int k, const EdlibAlignMode mode,
+        int* const bestScore_, int** const positions_, int* const numPositions_) {
+    *positions_ = NULL;
+    *numPositions_ = 0;
+
+    // firstBlock is 0-based index of first block in Ukkonen band.
+    // lastBlock is 0-based index of last block in Ukkonen band.
+    int firstBlock = 0;
+    int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks) - 1; // y in Myers
+    Block *bl; // Current block
+
+    Block* blocks = malloc(maxNumBlocks * sizeof(*blocks));
+
+    // For HW, solution will never be larger then queryLength.
+    if (mode == EDLIB_MODE_HW) {
+        k = min(queryLength, k);
+    }
+
+    // Each STRONG_REDUCE_NUM column is reduced in more expensive way.
+    // This gives speed up of about 2 times for small k.
+    const int STRONG_REDUCE_NUM = 2048;
+
+    // Initialize P, M and score
+    bl = blocks;
+    for (int b = 0; b <= lastBlock; b++) {
+        bl->score = (b + 1) * WORD_SIZE;
+        bl->P = (Word)(-1); // All 1s
+        bl->M = (Word)(0);
+        bl++;
+    }
+
+    int bestScore = -1;
+#define MAX_POS 100  // maximum number of positions returned.
+    int positions[MAX_POS];
+    int npositions = 0;
+    const int startHout = mode == EDLIB_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized;
+    const unsigned char* targetChar = target;
+    for (int c = 0; c < targetLength; c++) { // for each column
+        const Word* Peq_c = Peq + (*targetChar) * maxNumBlocks;
+
+        //----------------------- Calculate column -------------------------//
+        int hout = startHout;
+        bl = blocks + firstBlock;
+        Peq_c += firstBlock;
+        for (int b = firstBlock; b <= lastBlock; b++) {
+            hout = calculateBlock(bl->P, bl->M, *Peq_c, hout, &bl->P, &bl->M);
+            bl->score += hout;
+            bl++; Peq_c++;
+        }
+        bl--; Peq_c--;
+        //------------------------------------------------------------------//
+
+        //---------- Adjust number of blocks according to Ukkonen ----------//
+        if ((lastBlock < maxNumBlocks - 1) && (bl->score - hout <= k) // bl is pointing to last block
+            && ((*(Peq_c + 1) & WORD_1) || hout < 0)) { // Peq_c is pointing to last block
+            // If score of left block is not too big, calculate one more block
+            lastBlock++; bl++; Peq_c++;
+            bl->P = (Word)(-1); // All 1s
+            bl->M = (Word)(0);
+            bl->score = (bl - 1)->score - hout + WORD_SIZE + calculateBlock(bl->P, bl->M, *Peq_c, hout, &bl->P, &bl->M);
+        } else {
+            while (lastBlock >= firstBlock && bl->score >= k + WORD_SIZE) {
+                lastBlock--; bl--; Peq_c--;
+            }
+        }
+
+        // Every some columns, do some expensive but also more efficient block reducing.
+        // This is important!
+        //
+        // Reduce the band by decreasing last block if possible.
+        if (c % STRONG_REDUCE_NUM == 0) {
+            while (lastBlock >= 0 && lastBlock >= firstBlock && allBlockCellsLarger(*bl, k)) {
+                lastBlock--; bl--; Peq_c--;
+            }
+        }
+        // For HW, even if all cells are > k, there still may be solution in next
+        // column because starting conditions at upper boundary are 0.
+        // That means that first block is always candidate for solution,
+        // and we can never end calculation before last column.
+        if (mode == EDLIB_MODE_HW && lastBlock == -1) {
+            lastBlock++; bl++; Peq_c++;
+        }
+
+        // Reduce band by increasing first block if possible. Not applicable to HW.
+        if (mode != EDLIB_MODE_HW) {
+            while (firstBlock <= lastBlock && blocks[firstBlock].score >= k + WORD_SIZE) {
+                firstBlock++;
+            }
+            if (c % STRONG_REDUCE_NUM == 0) { // Do strong reduction every some blocks
+                while (firstBlock <= lastBlock && allBlockCellsLarger(blocks[firstBlock], k)) {
+                    firstBlock++;
+                }
+            }
+        }
+
+        // If band stops to exist finish
+        if (lastBlock < firstBlock) {
+            *bestScore_ = bestScore;
+            if (bestScore != -1) {
+                *positions_ = malloc(npositions * sizeof(int));
+                *numPositions_ = npositions;
+                memcpy(*positions_, positions, npositions * sizeof(int));
+            }
+            free(blocks);
+            return EDLIB_STATUS_OK;
+        }
+        //------------------------------------------------------------------//
+
+        //------------------------- Update best score ----------------------//
+        if (lastBlock == maxNumBlocks - 1) {
+            int colScore = bl->score;
+            if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
+                // NOTE: Score that I find in column c is actually score from column c-W
+                if (bestScore == -1 || colScore <= bestScore) {
+                    if (colScore != bestScore) {
+			npositions = 0;
+                        bestScore = colScore;
+                        // Change k so we will look only for equal or better
+                        // scores then the best found so far.
+                        k = bestScore;
+                    }
+		    if (npositions < MAX_POS)
+			positions[npositions++] = c - W;
+                }
+            }
+        }
+        //------------------------------------------------------------------//
+
+        targetChar++;
+    }
+
+
+    // Obtain results for last W columns from last column.
+    if (lastBlock == maxNumBlocks - 1) {
+	int *blockScores = getBlockCellValues(*bl);
+        for (int i = 0; i < W; i++) {
+            int colScore = blockScores[i + 1];
+            if (colScore <= k && (bestScore == -1 || colScore <= bestScore)) {
+                if (colScore != bestScore) {
+                    npositions = 0;
+                    k = bestScore = colScore;
+                }
+		if (npositions < MAX_POS)
+		    positions[npositions++] = targetLength - W + i;
+            }
+        }
+        free(blockScores);
+    }
+
+    *bestScore_ = bestScore;
+    if (bestScore != -1) {
+        *positions_ = malloc(npositions * sizeof(int));
+        *numPositions_ = npositions;
+        memcpy(*positions_, positions, npositions * sizeof(int));
+    }
+
+    free(blocks);
+    return EDLIB_STATUS_OK;
+}
+
+
+/**
+ * Takes char query and char target, recognizes alphabet and transforms them into unsigned char sequences
+ * where elements in sequences are not any more letters of alphabet, but their index in alphabet.
+ * Most of internal edlib functions expect such transformed sequences.
+ * This function will allocate queryTransformed and targetTransformed, so make sure to free them when done.
+ * Example:
+ *   Original sequences: "ACT" and "CGT".
+ *   Alphabet would be recognized as "ACTG". Alphabet length = 4.
+ *   Transformed sequences: [0, 1, 2] and [1, 3, 2].
+ * @param [in] queryOriginal
+ * @param [in] queryLength
+ * @param [in] targetOriginal
+ * @param [in] targetLength
+ * @param [out] queryTransformed  It will contain values in range [0, alphabet length - 1].
+ * @param [out] targetTransformed  It will contain values in range [0, alphabet length - 1].
+ * @return  Alphabet as a string of unique characters, where index of each character is its value in transformed
+ *          sequences.
+ */
+static char *transformSequences(const char* const queryOriginal, const int queryLength,
+				const char* const targetOriginal, const int targetLength,
+				unsigned char** const queryTransformed,
+				unsigned char** const targetTransformed,
+                                int *alphabet_size) {
+    // Alphabet is constructed from letters that are present in sequences.
+    // Each letter is assigned an ordinal number, starting from 0 up to alphabetLength - 1,
+    // and new query and target are created in which letters are replaced with their ordinal numbers.
+    // This query and target are used in all the calculations later.
+    *queryTransformed  = malloc(sizeof(unsigned char) * queryLength);
+    *targetTransformed = malloc(sizeof(unsigned char) * targetLength);
+
+    char *alphabet = malloc(MAX_UCHAR+1), *alphabet_cp = alphabet;
+
+    // Alphabet information, it is constructed on fly while transforming sequences.
+    // letterIdx[c] is index of letter c in alphabet.
+    unsigned char letterIdx[MAX_UCHAR + 1];
+    bool inAlphabet[MAX_UCHAR + 1]; // inAlphabet[c] is true if c is in alphabet
+    for (int i = 0; i < MAX_UCHAR + 1; i++) inAlphabet[i] = false;
+
+    for (int i = 0; i < queryLength; i++) {
+        unsigned char c = queryOriginal[i];
+        if (!inAlphabet[c]) {
+            inAlphabet[c] = true;
+            letterIdx[c] = alphabet_cp - alphabet;
+            *alphabet_cp++ = queryOriginal[i];
+        }
+        (*queryTransformed)[i] = letterIdx[c];
+    }
+    for (int i = 0; i < targetLength; i++) {
+        unsigned char c = targetOriginal[i];
+        if (!inAlphabet[c]) {
+            inAlphabet[c] = true;
+            letterIdx[c] = alphabet_cp - alphabet;
+            *alphabet_cp++ = targetOriginal[i];
+        }
+        (*targetTransformed)[i] = letterIdx[c];
+    }
+
+    *alphabet_size = alphabet_cp - alphabet;
+    return alphabet;
+}
+
+
+EdlibAlignConfig edlibNewAlignConfig(int k, EdlibAlignMode mode, EdlibAlignTask task,
+				     const EdlibEqualityPair* additionalEqualities,
+				     int additionalEqualitiesLength) {
+    EdlibAlignConfig config;
+    config.k = k;
+    config.mode = mode;
+    config.task = task;
+    config.additionalEqualities = additionalEqualities;
+    config.additionalEqualitiesLength = additionalEqualitiesLength;
+    return config;
+}
+
+EdlibAlignConfig edlibDefaultAlignConfig(void) {
+    return edlibNewAlignConfig(-1, EDLIB_MODE_NW, EDLIB_TASK_DISTANCE, NULL, 0);
+}
+
+void edlibFreeAlignResult(EdlibAlignResult result) {
+    if (result.endLocations) free(result.endLocations);
+    if (result.startLocations) free(result.startLocations);
+    if (result.alignment) free(result.alignment);
+}
diff --git a/shared/package-files/e6/e61f84943e182645fcec71e5d1cea7d5c7b6ef954c2169e99587fdb9bc26f637/masked_shared.cpython-311.pyc b/shared/package-files/e6/e61f84943e182645fcec71e5d1cea7d5c7b6ef954c2169e99587fdb9bc26f637/masked_shared.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84ba602b87644d870c25955ccbedc7e30116ce48
Binary files /dev/null and b/shared/package-files/e6/e61f84943e182645fcec71e5d1cea7d5c7b6ef954c2169e99587fdb9bc26f637/masked_shared.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e623a7fc10e189ddb69ec44dbf18f4b4e7059cf3ac3760138b8d2e984439eb5f/pooling.h b/shared/package-files/e6/e623a7fc10e189ddb69ec44dbf18f4b4e7059cf3ac3760138b8d2e984439eb5f/pooling.h
new file mode 100644
index 0000000000000000000000000000000000000000..3934f326c8a5da08241b93e51534b7b06acb27fa
--- /dev/null
+++ b/shared/package-files/e6/e623a7fc10e189ddb69ec44dbf18f4b4e7059cf3ac3760138b8d2e984439eb5f/pooling.h
@@ -0,0 +1,594 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::nn {
+
+/// Options for a `D`-dimensional avgpool module.
+template 
+struct AvgPoolOptions {
+  AvgPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take an average over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size`
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+
+  /// when True, will include the zero-padding in the averaging calculation
+  TORCH_ARG(bool, count_include_pad) = true;
+
+  /// if specified, it will be used as divisor, otherwise size of the pooling
+  /// region will be used.
+
+  TORCH_ARG(std::optional, divisor_override) = std::nullopt;
+};
+
+/// `AvgPoolOptions` specialized for the `AvgPool1d` module.
+///
+/// Example:
+/// ```
+/// AvgPool1d model(AvgPool1dOptions(3).stride(2));
+/// ```
+using AvgPool1dOptions = AvgPoolOptions<1>;
+
+/// `AvgPoolOptions` specialized for the `AvgPool2d` module.
+///
+/// Example:
+/// ```
+/// AvgPool2d model(AvgPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+using AvgPool2dOptions = AvgPoolOptions<2>;
+
+/// `AvgPoolOptions` specialized for the `AvgPool3d` module.
+///
+/// Example:
+/// ```
+/// AvgPool3d model(AvgPool3dOptions(5).stride(2));
+/// ```
+using AvgPool3dOptions = AvgPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool1d`.
+///
+/// See the documentation for `torch::nn::AvgPool1dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool1d(x, F::AvgPool1dFuncOptions(3).stride(2));
+/// ```
+using AvgPool1dFuncOptions = AvgPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool2d`.
+///
+/// See the documentation for `torch::nn::AvgPool2dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool2d(x, F::AvgPool2dFuncOptions(3).stride(2));
+/// ```
+using AvgPool2dFuncOptions = AvgPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::avg_pool3d`.
+///
+/// See the documentation for `torch::nn::AvgPool3dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::avg_pool3d(x, F::AvgPool3dFuncOptions(3).stride(2));
+/// ```
+using AvgPool3dFuncOptions = AvgPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional maxpool module.
+template 
+struct MaxPoolOptions {
+  MaxPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// a parameter that controls the stride of elements in the window
+  TORCH_ARG(ExpandingArray, dilation) = 1;
+
+  /// when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+};
+
+/// `MaxPoolOptions` specialized for the `MaxPool1d` module.
+///
+/// Example:
+/// ```
+/// MaxPool1d model(MaxPool1dOptions(3).stride(2));
+/// ```
+using MaxPool1dOptions = MaxPoolOptions<1>;
+
+/// `MaxPoolOptions` specialized for the `MaxPool2d` module.
+///
+/// Example:
+/// ```
+/// MaxPool2d model(MaxPool2dOptions({3, 2}).stride({2, 2}));
+/// ```
+using MaxPool2dOptions = MaxPoolOptions<2>;
+
+/// `MaxPoolOptions` specialized for the `MaxPool3d` module.
+///
+/// Example:
+/// ```
+/// MaxPool3d model(MaxPool3dOptions(3).stride(2));
+/// ```
+using MaxPool3dOptions = MaxPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool1d` and
+/// `torch::nn::functional::max_pool1d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool1d(x, F::MaxPool1dFuncOptions(3).stride(2));
+/// ```
+using MaxPool1dFuncOptions = MaxPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool2d` and
+/// `torch::nn::functional::max_pool2d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool2d(x, F::MaxPool2dFuncOptions(3).stride(2));
+/// ```
+using MaxPool2dFuncOptions = MaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::max_pool3d` and
+/// `torch::nn::functional::max_pool3d_with_indices`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_pool3d(x, F::MaxPool3dFuncOptions(3).stride(2));
+/// ```
+using MaxPool3dFuncOptions = MaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional adaptive maxpool module.
+template 
+struct AdaptiveMaxPoolOptions {
+  AdaptiveMaxPoolOptions(output_size_t output_size)
+      : output_size_(output_size) {}
+
+  /// the target output size
+  TORCH_ARG(output_size_t, output_size);
+};
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool1d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool1d model(AdaptiveMaxPool1dOptions(3));
+/// ```
+using AdaptiveMaxPool1dOptions = AdaptiveMaxPoolOptions>;
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool2d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool2d model(AdaptiveMaxPool2dOptions({3, 2}));
+/// ```
+using AdaptiveMaxPool2dOptions =
+    AdaptiveMaxPoolOptions>;
+
+/// `AdaptiveMaxPoolOptions` specialized for the `AdaptiveMaxPool3d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveMaxPool3d model(AdaptiveMaxPool3dOptions(3));
+/// ```
+using AdaptiveMaxPool3dOptions =
+    AdaptiveMaxPoolOptions>;
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool1d` and
+/// `torch::nn::functional::adaptive_max_pool1d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool1d(x, F::AdaptiveMaxPool1dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool1dFuncOptions = AdaptiveMaxPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool2d` and
+/// `torch::nn::functional::adaptive_max_pool2d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool2d(x, F::AdaptiveMaxPool2dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool2dFuncOptions = AdaptiveMaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_max_pool3d` and
+/// `torch::nn::functional::adaptive_max_pool3d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_max_pool3d(x, F::AdaptiveMaxPool3dFuncOptions(3));
+/// ```
+using AdaptiveMaxPool3dFuncOptions = AdaptiveMaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional adaptive avgpool module.
+template 
+struct AdaptiveAvgPoolOptions {
+  AdaptiveAvgPoolOptions(output_size_t output_size)
+      : output_size_(output_size) {}
+
+  /// the target output size
+  TORCH_ARG(output_size_t, output_size);
+};
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool1d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool1d model(AdaptiveAvgPool1dOptions(5));
+/// ```
+using AdaptiveAvgPool1dOptions = AdaptiveAvgPoolOptions>;
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool2d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool2d model(AdaptiveAvgPool2dOptions({3, 2}));
+/// ```
+using AdaptiveAvgPool2dOptions =
+    AdaptiveAvgPoolOptions>;
+
+/// `AdaptiveAvgPoolOptions` specialized for the `AdaptiveAvgPool3d` module.
+///
+/// Example:
+/// ```
+/// AdaptiveAvgPool3d model(AdaptiveAvgPool3dOptions(3));
+/// ```
+using AdaptiveAvgPool3dOptions =
+    AdaptiveAvgPoolOptions>;
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool1d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool1dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool1d(x, F::AdaptiveAvgPool1dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool1dFuncOptions = AdaptiveAvgPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool2d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool2dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool2d(x, F::AdaptiveAvgPool2dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool2dFuncOptions = AdaptiveAvgPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::adaptive_avg_pool3d`.
+///
+/// See the documentation for `torch::nn::AdaptiveAvgPool3dOptions` class to
+/// learn what arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::adaptive_avg_pool3d(x, F::AdaptiveAvgPool3dFuncOptions(3));
+/// ```
+using AdaptiveAvgPool3dFuncOptions = AdaptiveAvgPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional maxunpool module.
+template 
+struct MaxUnpoolOptions {
+  MaxUnpoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+};
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool1d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool1d model(MaxUnpool1dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool1dOptions = MaxUnpoolOptions<1>;
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool2d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool2d model(MaxUnpool2dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool2dOptions = MaxUnpoolOptions<2>;
+
+/// `MaxUnpoolOptions` specialized for the `MaxUnpool3d` module.
+///
+/// Example:
+/// ```
+/// MaxUnpool3d model(MaxUnpool3dOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool3dOptions = MaxUnpoolOptions<3>;
+
+// ============================================================================
+
+namespace functional {
+
+/// Options for a `D`-dimensional maxunpool functional.
+template 
+struct MaxUnpoolFuncOptions {
+  MaxUnpoolFuncOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size), stride_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the stride of the window. Default value is `kernel_size
+  TORCH_ARG(ExpandingArray, stride);
+
+  /// implicit zero padding to be added on both sides
+  TORCH_ARG(ExpandingArray, padding) = 0;
+
+  /// the targeted output size
+  TORCH_ARG(std::optional>, output_size) = std::nullopt;
+};
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool1d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool1d(x, indices,
+/// F::MaxUnpool1dFuncOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool1dFuncOptions = MaxUnpoolFuncOptions<1>;
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool2d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool2d(x, indices,
+/// F::MaxUnpool2dFuncOptions(3).stride(2).padding(1));
+/// ```
+using MaxUnpool2dFuncOptions = MaxUnpoolFuncOptions<2>;
+
+/// `MaxUnpoolFuncOptions` specialized for
+/// `torch::nn::functional::max_unpool3d`.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::max_unpool3d(x, indices, F::MaxUnpool3dFuncOptions(3));
+/// ```
+using MaxUnpool3dFuncOptions = MaxUnpoolFuncOptions<3>;
+
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional fractional maxpool module.
+template 
+struct FractionalMaxPoolOptions {
+  FractionalMaxPoolOptions(ExpandingArray kernel_size)
+      : kernel_size_(kernel_size) {}
+
+  /// the size of the window to take a max over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  /// the target output size of the image
+  TORCH_ARG(std::optional>, output_size) = std::nullopt;
+
+  /// If one wants to have an output size as a ratio of the input size, this
+  /// option can be given. This has to be a number or tuple in the range (0, 1)
+  using ExpandingArrayDouble = torch::ExpandingArray;
+  TORCH_ARG(std::optional, output_ratio) = std::nullopt;
+
+  TORCH_ARG(torch::Tensor, _random_samples) = Tensor();
+};
+
+/// `FractionalMaxPoolOptions` specialized for the `FractionalMaxPool2d` module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool2d model(FractionalMaxPool2dOptions(5).output_size(1));
+/// ```
+using FractionalMaxPool2dOptions = FractionalMaxPoolOptions<2>;
+
+/// `FractionalMaxPoolOptions` specialized for the `FractionalMaxPool3d` module.
+///
+/// Example:
+/// ```
+/// FractionalMaxPool3d model(FractionalMaxPool3dOptions(5).output_size(1));
+/// ```
+using FractionalMaxPool3dOptions = FractionalMaxPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::fractional_max_pool2d` and
+/// `torch::nn::functional::fractional_max_pool2d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool2d(x,
+/// F::FractionalMaxPool2dFuncOptions(3).output_size(2));
+/// ```
+using FractionalMaxPool2dFuncOptions = FractionalMaxPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::fractional_max_pool3d` and
+/// `torch::nn::functional::fractional_max_pool3d_with_indices`
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::fractional_max_pool3d(x,
+/// F::FractionalMaxPool3dFuncOptions(3).output_size(2));
+/// ```
+using FractionalMaxPool3dFuncOptions = FractionalMaxPool3dOptions;
+} // namespace functional
+
+// ============================================================================
+
+/// Options for a `D`-dimensional lppool module.
+template 
+struct LPPoolOptions {
+  LPPoolOptions(double norm_type, ExpandingArray kernel_size)
+      : norm_type_(norm_type),
+        kernel_size_(kernel_size),
+        stride_(kernel_size) {}
+
+  TORCH_ARG(double, norm_type);
+
+  // the size of the window to take an average over
+  TORCH_ARG(ExpandingArray, kernel_size);
+
+  // the stride of the window. Default value is `kernel_size`
+  TORCH_ARG(ExpandingArray, stride);
+
+  // when True, will use `ceil` instead of `floor` to compute the output shape
+  TORCH_ARG(bool, ceil_mode) = false;
+};
+
+/// `LPPoolOptions` specialized for the `LPPool1d` module.
+///
+/// Example:
+/// ```
+/// LPPool1d model(LPPool1dOptions(1, 2).stride(5).ceil_mode(true));
+/// ```
+using LPPool1dOptions = LPPoolOptions<1>;
+
+/// `LPPoolOptions` specialized for the `LPPool2d` module.
+///
+/// Example:
+/// ```
+/// LPPool2d model(LPPool2dOptions(1, std::vector({3, 4})).stride({5,
+/// 6}).ceil_mode(true));
+/// ```
+using LPPool2dOptions = LPPoolOptions<2>;
+
+/// `LPPoolOptions` specialized for the `LPPool3d` module.
+///
+/// Example:
+/// ```
+/// LPPool3d model(LPPool3dOptions(1, std::vector({3, 4, 5})).stride(
+/// {5, 6, 7}).ceil_mode(true));
+/// ```
+using LPPool3dOptions = LPPoolOptions<3>;
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool1d`.
+///
+/// See the documentation for `torch::nn::LPPool1dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool1d(x, F::LPPool1dFuncOptions(2, 3).stride(2));
+/// ```
+using LPPool1dFuncOptions = LPPool1dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool2d`.
+///
+/// See the documentation for `torch::nn::LPPool2dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool2d(x, F::LPPool2dFuncOptions(2, {2, 3}).stride(2));
+/// ```
+using LPPool2dFuncOptions = LPPool2dOptions;
+} // namespace functional
+
+namespace functional {
+/// Options for `torch::nn::functional::lp_pool3d`.
+///
+/// See the documentation for `torch::nn::LPPool3dOptions` class to learn what
+/// arguments are supported.
+///
+/// Example:
+/// ```
+/// namespace F = torch::nn::functional;
+/// F::lp_pool3d(x, F::LPPool3dFuncOptions(2, {2, 3, 4}).stride(2));
+/// ```
+using LPPool3dFuncOptions = LPPool3dOptions;
+} // namespace functional
+
+} // namespace torch::nn
diff --git a/shared/package-files/e6/e624c53f232d3995399797911e2fa6cd01a44ab3f6549578e34454b8cb14d84b/test_repr.cpython-311.pyc b/shared/package-files/e6/e624c53f232d3995399797911e2fa6cd01a44ab3f6549578e34454b8cb14d84b/test_repr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41188528aec078f03e41b3792b01da837571cd86
Binary files /dev/null and b/shared/package-files/e6/e624c53f232d3995399797911e2fa6cd01a44ab3f6549578e34454b8cb14d84b/test_repr.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e624ee2b7d9d43d2eadd11068681ef64f32914ea99c59f3490f5104facd4dcc5/_foreach_asin.h b/shared/package-files/e6/e624ee2b7d9d43d2eadd11068681ef64f32914ea99c59f3490f5104facd4dcc5/_foreach_asin.h
new file mode 100644
index 0000000000000000000000000000000000000000..e9ef2f00a6d0aff38d0303f562aacd12da965ffd
--- /dev/null
+++ b/shared/package-files/e6/e624ee2b7d9d43d2eadd11068681ef64f32914ea99c59f3490f5104facd4dcc5/_foreach_asin.h
@@ -0,0 +1,45 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_foreach_asin(Tensor[] self) -> Tensor[]
+inline ::std::vector _foreach_asin(at::TensorList self) {
+    return at::_ops::_foreach_asin::call(self);
+}
+
+// aten::_foreach_asin_(Tensor(a!)[] self) -> ()
+inline void _foreach_asin_(at::TensorList self) {
+    return at::_ops::_foreach_asin_::call(self);
+}
+
+// aten::_foreach_asin.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
+inline void _foreach_asin_out(at::TensorList out, at::TensorList self) {
+    return at::_ops::_foreach_asin_out::call(self, out);
+}
+// aten::_foreach_asin.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
+inline void _foreach_asin_outf(at::TensorList self, at::TensorList out) {
+    return at::_ops::_foreach_asin_out::call(self, out);
+}
+
+}
diff --git a/shared/package-files/e6/e624fa1647e9c70f5bbe6beb2c1d751a502d320b4d4488e0c244e5f90e72681d/test_period.cpython-311.pyc b/shared/package-files/e6/e624fa1647e9c70f5bbe6beb2c1d751a502d320b4d4488e0c244e5f90e72681d/test_period.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1120bd50230f2f11ef4c02898d22a1d5d350cb57
Binary files /dev/null and b/shared/package-files/e6/e624fa1647e9c70f5bbe6beb2c1d751a502d320b4d4488e0c244e5f90e72681d/test_period.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e625b60c3fc334673712cb371ea7366f88ccc904d28303a7b1aa2e1e55c21591/_to_copy_ops.h b/shared/package-files/e6/e625b60c3fc334673712cb371ea7366f88ccc904d28303a7b1aa2e1e55c21591/_to_copy_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..859d5655e9b909935431e8e3c6213716ba338842
--- /dev/null
+++ b/shared/package-files/e6/e625b60c3fc334673712cb371ea7366f88ccc904d28303a7b1aa2e1e55c21591/_to_copy_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _to_copy {
+  using schema = at::Tensor (const at::Tensor &, ::std::optional, ::std::optional, ::std::optional, ::std::optional, bool, ::std::optional);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_to_copy";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, bool non_blocking, ::std::optional memory_format);
+};
+
+struct TORCH_API _to_copy_out {
+  using schema = at::Tensor & (const at::Tensor &, bool, ::std::optional, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_to_copy";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "_to_copy.out(Tensor self, *, bool non_blocking=False, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, bool non_blocking, ::std::optional memory_format, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking, ::std::optional memory_format, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e6283b0b2002dce1eed344720609a7f18e0a14f934346515549db99730e0f907/bam_split.c.pysam.c b/shared/package-files/e6/e6283b0b2002dce1eed344720609a7f18e0a14f934346515549db99730e0f907/bam_split.c.pysam.c
new file mode 100644
index 0000000000000000000000000000000000000000..f1fd5f4d85ab7dfd3d145818e874d076e23b72af
--- /dev/null
+++ b/shared/package-files/e6/e6283b0b2002dce1eed344720609a7f18e0a14f934346515549db99730e0f907/bam_split.c.pysam.c
@@ -0,0 +1,901 @@
+#include "samtools.pysam.h"
+
+/*  bam_split.c -- split subcommand.
+
+    Copyright (C) 2013-2016,2018-2019,2023,2024 Genome Research Ltd.
+
+    Author: Martin Pollard 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.  */
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include "htslib/thread_pool.h"
+#include "sam_opts.h"
+#include "samtools.h"
+
+
+KHASH_MAP_INIT_STR(c2i, int)
+
+struct parsed_opts {
+    const char *merged_input_name;
+    const char *unaccounted_header_name;
+    const char *unaccounted_name;
+    const char *output_format_string;
+    const char *tag;
+    long max_split;
+    bool verbose;
+    int no_pg;
+    int zero_pad;
+    sam_global_args ga;
+};
+
+#define DEFAULT_MAX_SPLIT 100
+
+typedef struct parsed_opts parsed_opts_t;
+
+struct state {
+    samFile* merged_input_file;
+    sam_hdr_t* merged_input_header;
+    samFile* unaccounted_file;
+    sam_hdr_t* unaccounted_header;
+    char *unaccounted_idx_fn;
+    size_t output_count;
+    char **tag_vals;
+    char **index_file_name;
+    char **output_file_name;
+    samFile **output_file;
+    sam_hdr_t **output_header;
+    kh_c2i_t* tag_val_hash;
+    htsThreadPool p;
+    int write_index;
+};
+
+typedef struct state state_t;
+
+static int cleanup_state(state_t* status, bool check_close);
+static void cleanup_opts(parsed_opts_t* opts);
+
+static void usage(FILE *write_to)
+{
+    fprintf(write_to,
+"Usage: samtools split [-u ] [-h ]\n"
+"                      [-f ] [-v] \n"
+"Options:\n"
+"  -f STRING           output filename format string [\"%%*_%%#.%%.\"]\n"
+"  -u FILE1            put left-over reads in FILE1\n"
+"  -h FILE2            ... and override the header with FILE2 (-u file only)\n"
+"  -d TAG              split by TAG value. TAG value must be a string.\n"
+"  -p NUMBER           zero-pad numbers in filenames to NUMBER digits\n"
+"  -M,--max-split NUM  limit number of output files from -d to NUM [%d]\n"
+"  -v                  verbose output\n"
+"  --no-PG             do not add a PG line\n",
+            DEFAULT_MAX_SPLIT);
+    sam_global_opt_help(write_to, "-....@..");
+    fprintf(write_to,
+"\n"
+"Format string expansions:\n"
+"  %%%%     %%\n"
+"  %%*     basename\n"
+"  %%#     index (of @RG in the header, or count of TAG values seen so far)\n"
+"  %%!     @RG ID or TAG value\n"
+"  %%.     filename extension for output format\n"
+      );
+}
+
+// Takes the command line options and turns them into something we can understand
+static parsed_opts_t* parse_args(int argc, char** argv)
+{
+    if (argc == 1) { usage(samtools_stdout); return NULL; }
+
+    const char *optstring = "vf:h:u:d:M:p:@:";
+    char *default_format_string = "%*_%#.%.";
+
+    static const struct option lopts[] = {
+        SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'),
+        {"no-PG", no_argument, NULL, 1},
+        {"max-split", required_argument, NULL, 'M'},
+        {"zero-pad", required_argument, NULL, 'p'},
+        { NULL, 0, NULL, 0 }
+    };
+
+    parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1);
+    if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; }
+
+    retval->max_split = DEFAULT_MAX_SPLIT;
+    sam_global_args_init(&retval->ga);
+
+    int opt;
+    while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) {
+        switch (opt) {
+        case 'f':
+            retval->output_format_string = optarg;
+            break;
+        case 'h':
+            retval->unaccounted_header_name = optarg;
+            break;
+        case 'v':
+            retval->verbose = true;
+            break;
+        case 'u':
+            retval->unaccounted_name = optarg;
+            break;
+        case 'd':
+            retval->tag = optarg;
+            default_format_string = "%*_%!.%.";
+            break;
+        case 'M': {
+            char *end = optarg;
+            retval->max_split = strtol(optarg, &end, 10);
+            if (*optarg == '\0' || *end != '\0' || retval->max_split == 0) {
+                print_error("split", "Invalid -M argument: \"%s\"", optarg);
+                free(retval);
+                return NULL;
+            }
+            if (retval->max_split < 0) // No limit requested
+                retval->max_split = LONG_MAX;
+            break;
+        }
+        case 'p': {
+            char *end = optarg;
+            unsigned long val = strtoul(optarg, &end, 10);
+            if (*optarg == '\0' || *end != '\0' || val > 20) {
+                print_error("split", "Invalid -p argument: \"%s\"", optarg);
+                free(retval);
+                return NULL;
+            }
+            retval->zero_pad = (int) val;
+            break;
+        }
+        case 1:
+            retval->no_pg = 1;
+            break;
+
+        default:
+            if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break;
+            /* else fall-through */
+        case '?':
+            usage(samtools_stdout);
+            free(retval);
+            return NULL;
+        }
+    }
+
+    if (retval->output_format_string == NULL) retval->output_format_string = default_format_string;
+
+    argc -= optind;
+    argv += optind;
+
+    if (argc != 1) {
+        print_error("split", "Invalid number of arguments: %d", argc);
+        usage(samtools_stderr);
+        free(retval);
+        return NULL;
+    }
+
+    retval->merged_input_name = argv[0];
+
+    return retval;
+}
+
+// Expands a output filename format string
+static char* expand_format_string(const char* format_string,
+                                  const char* basename, const char* tag_val,
+                                  const int file_idx, const int zero_pad,
+                                  const htsFormat *format)
+{
+    kstring_t str = { 0, 0, NULL };
+    const char* pointer = format_string;
+    const char* next;
+    while ((next = strchr(pointer, '%')) != NULL) {
+        if (kputsn(pointer, next-pointer, &str) < 0) goto memfail;
+        ++next;
+        switch (*next) {
+            case '%':
+                if (kputc('%', &str) < 0) goto memfail;
+                break;
+            case '*':
+                if (kputs(basename, &str) < 0) goto memfail;
+                break;
+            case '#':
+                if (zero_pad == 0) {
+                    if (kputl(file_idx, &str) < 0) goto memfail;
+                } else {
+                    if (ksprintf(&str, "%0*d", zero_pad, file_idx) < 0)
+                        goto memfail;
+                }
+                break;
+            case '!':
+                if (kputs(tag_val, &str) < 0) goto memfail;
+                break;
+            case '.':
+                // Only really need to cope with sam, bam, cram
+                if (format->format != unknown_format) {
+                    if (kputs(hts_format_file_extension(format), &str) < 0)
+                        goto memfail;
+                } else {
+                    if (kputs("bam", &str) < 0) goto memfail;
+                }
+                break;
+            case '\0':
+                print_error("split", "Trailing %% in filename format string");
+                goto fail;
+            default:
+                // Error is: fprintf(samtools_stderr, "bad format string, unknown format specifier\n");
+                print_error("split", "Unknown specifier %%%c in filename format string", *next);
+                goto fail;
+        }
+        pointer = next + 1;
+    }
+    if (kputs(pointer, &str) < 0) goto memfail;
+    return ks_release(&str);
+
+ memfail:
+    print_error_errno("split", "Couldn't build output filename");
+ fail:
+    free(str.s);
+    return NULL;
+}
+
+// Parse the header, count the number of RG tags and return a list of their names
+static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name)
+{
+    char **names = NULL;
+    kstring_t id_val = KS_INITIALIZE;
+    int i, n_rg = sam_hdr_count_lines(hdr, "RG");
+
+    if (n_rg < 0) {
+        print_error("split", "Failed to get @RG IDs");
+        *count = 0;
+        *output_name = NULL;
+        return false;
+    }
+
+    if (n_rg == 0) {
+        *count = 0;
+        *output_name = NULL;
+        return true;
+    }
+
+    names = calloc(n_rg, sizeof(names[0]));
+    if (!names) goto memfail;
+
+    for (i = 0; i < n_rg; i++) {
+        if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail;
+        names[i] = ks_release(&id_val);
+    }
+
+    *count = n_rg;
+    *output_name = names;
+    return true;
+
+ memfail:
+    print_error_errno("split", "Failed to get @RG IDs");
+    *count = 0;
+    *output_name = NULL;
+    ks_free(&id_val);
+    free(names);
+    return false;
+}
+
+static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2)
+{
+    size_t n;
+    if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) {
+        print_error("split",
+                    "Unaccounted header contains wrong number of references");
+        return -1;
+    }
+    for (n = 0; n < sam_hdr_nref(hdr1); n++) {
+        hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n);
+        hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n);
+        if (h1_len != h2_len) {
+            print_error("split",
+                        "Unaccounted header reference %zu \"%s\" is not the same length as in the input file",
+                        n + 1, sam_hdr_tid2name(hdr2, n));
+            return -1;
+        }
+    }
+    return 0;
+}
+
+static int grow_output_lists(state_t *state, size_t count) {
+    char **new_list = realloc(state->tag_vals, count * sizeof(char *));
+    if (!new_list)
+        return -1;
+    state->tag_vals = new_list;
+    new_list = realloc(state->index_file_name, count * sizeof(char *));
+    if (!new_list)
+        return -1;
+    state->index_file_name = new_list;
+    new_list = realloc(state->output_file_name, count * sizeof(char *));
+    if (!new_list)
+        return -1;
+    state->output_file_name = new_list;
+    samFile **new_file = realloc(state->output_file,
+                                 count * sizeof(samFile *));
+    if (!new_file)
+        return -1;
+    state->output_file = new_file;
+    sam_hdr_t **new_hdr = realloc(state->output_header,
+                                  count * sizeof(sam_hdr_t *));
+    if (!new_hdr)
+        return -1;
+    state->output_header = new_hdr;
+    return 0;
+}
+
+static khiter_t prep_sam_file(parsed_opts_t *opts, state_t *state,
+                              const char *tag, const char *arg_list,
+                              int is_rg) {
+    char *input_base_name = NULL, *new_file_name = NULL, *tag_val = NULL;
+    char *new_idx_fn = NULL;
+    sam_hdr_t *new_hdr = NULL;
+    samFile *new_sam_file = NULL;
+
+    khiter_t i = kh_get_c2i(state->tag_val_hash, tag);
+    if (i != kh_end(state->tag_val_hash)) {
+        return i;
+    }
+    // create new file
+    if (grow_output_lists(state, state->output_count + 1) != 0) {
+        print_error_errno("split", "Couldn't grow output lists");
+        return kh_end(state->tag_val_hash);
+    }
+    tag_val = strdup(tag);
+    if (!tag_val) {
+        print_error_errno("split", "Couldn't copy tag value");
+        return kh_end(state->tag_val_hash);
+    }
+    char *dirsep = strrchr(opts->merged_input_name, '/');
+    input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
+    if (!input_base_name) {
+        print_error_errno("split", "Filename parsing failed");
+        goto fail;
+    }
+
+    char* extension = strrchr(input_base_name, '.');
+    if (extension) *extension = '\0';
+
+    new_file_name = expand_format_string(opts->output_format_string,
+                                         input_base_name, tag,
+                                         kh_size(state->tag_val_hash),
+                                         opts->zero_pad, &opts->ga.out);
+    if (!new_file_name) {
+        print_error_errno("split", "Filename creation failed");
+        goto fail;
+    }
+
+    new_hdr = sam_hdr_dup(state->merged_input_header);
+    if (!new_hdr) {
+        print_error_errno("split", "Duplicating header for file \"%s\" failed", new_file_name);
+        goto fail;
+    }
+    if (!opts->no_pg && sam_hdr_add_pg(new_hdr, "samtools",
+                                       "VN", samtools_version(),
+                                       arg_list ? "CL": NULL,
+                                       arg_list ? arg_list : NULL,
+                                       NULL)) {
+        print_error_errno("split", "Adding PG line to file \"%s\" failed", new_file_name);
+        goto fail;
+    }
+
+    if (is_rg) {
+        // If here, we've found an RG:Z: tag without a corresponding @RG
+        // line in the header.
+        if (sam_hdr_remove_lines(new_hdr, "RG", "ID", NULL) != 0) {
+            print_error_errno("split",
+                              "Failed to remove @RG lines from file \"%s\"",
+                              new_file_name);
+            goto fail;
+        }
+        if (sam_hdr_add_line(new_hdr, "RG", "ID", tag_val, NULL) != 0) {
+            print_error_errno("split",
+                              "Failed to add @RG line to file \"%s\"",
+                              new_file_name);
+            goto fail;
+        }
+    }
+
+    char outmode[4] = "w";
+    sam_open_mode(outmode + 1, new_file_name, NULL);
+    new_sam_file = sam_open_format(new_file_name, outmode, &opts->ga.out);
+    if (!new_sam_file) {
+        print_error_errno("split", "Opening filename for writing \"%s\" failed", new_file_name);
+        goto fail;
+    }
+    if (state->p.pool)
+        hts_set_opt(new_sam_file, HTS_OPT_THREAD_POOL, &state->p);
+
+    if (sam_hdr_write(new_sam_file, new_hdr) != 0) {
+        print_error_errno("split", "Couldn't write header to \"%s\"",
+                          new_file_name);
+        goto fail;
+    }
+
+    if (state->write_index) {
+        new_idx_fn = auto_index(new_sam_file, new_file_name, new_hdr);
+        if (!new_idx_fn) {
+            print_error_errno("split", "Creating index file for file \"%s\" failed", new_file_name);
+            goto fail;
+        }
+    }
+
+    int ret = -1;
+    i = kh_put_c2i(state->tag_val_hash, tag_val, &ret);
+    if (ret < 0) {
+        print_error_errno("split", "Adding file \"%s\" failed", new_file_name);
+        goto fail;
+    }
+
+    kh_val(state->tag_val_hash, i) = state->output_count;
+    state->tag_vals[state->output_count] = tag_val;
+    state->index_file_name[state->output_count] = new_idx_fn;
+    state->output_file_name[state->output_count] = new_file_name;
+    state->output_file[state->output_count] = new_sam_file;
+    state->output_header[state->output_count] = new_hdr;
+    state->output_count++;
+    free(input_base_name);
+    return i;
+
+ fail:
+    free(input_base_name);
+    free(new_file_name);
+    free(tag_val);
+    free(new_idx_fn);
+    if (new_hdr)
+        sam_hdr_destroy(new_hdr);
+    if (new_sam_file)
+        sam_close(new_sam_file);
+    return kh_end(state->tag_val_hash);
+}
+
+// Set the initial state
+static state_t* init(parsed_opts_t* opts, const char *arg_list)
+{
+    state_t* retval = calloc(sizeof(state_t), 1);
+    if (!retval) {
+        print_error_errno("split", "Initialisation failed");
+        return NULL;
+    }
+
+    if (opts->ga.nthreads > 0) {
+        if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) {
+            fprintf(samtools_stderr, "Error creating thread pool\n");
+            cleanup_state(retval, false);
+            return NULL;
+        }
+    }
+
+    retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in);
+    if (!retval->merged_input_file) {
+        print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name);
+        cleanup_state(retval, false);
+        return NULL;
+    }
+    if (retval->p.pool)
+        hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p);
+    retval->merged_input_header = sam_hdr_read(retval->merged_input_file);
+    if (retval->merged_input_header == NULL) {
+        print_error("split", "Could not read header from \"%s\"", opts->merged_input_name);
+        cleanup_state(retval, false);
+        return NULL;
+    }
+    retval->write_index = opts->ga.write_index;
+
+    if (opts->unaccounted_name) {
+        if (opts->unaccounted_header_name) {
+            samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in);
+            if (!hdr_load) {
+                print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name);
+                cleanup_state(retval, false);
+                return NULL;
+            }
+            retval->unaccounted_header = sam_hdr_read(hdr_load);
+            if (retval->unaccounted_header == NULL) {
+                print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name);
+                cleanup_state(retval, false);
+                sam_close(hdr_load);
+                return NULL;
+            }
+            sam_close(hdr_load);
+            if (header_compatible(retval->merged_input_header,
+                                  retval->unaccounted_header) != 0) {
+                cleanup_state(retval, false);
+                return NULL;
+            }
+        } else {
+            retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header);
+            if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools",
+                                               "VN", samtools_version(),
+                                               arg_list ? "CL": NULL,
+                                               arg_list ? arg_list : NULL,
+                                               NULL)) {
+                print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name);
+                cleanup_state(retval, false);
+                return NULL;
+            }
+        }
+
+        char outmode[4] = "w";
+        sam_open_mode(outmode + 1, opts->unaccounted_name, NULL);
+        retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out);
+
+        if (retval->unaccounted_file == NULL) {
+            print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name);
+            cleanup_state(retval, false);
+            return NULL;
+        }
+        if (retval->p.pool)
+            hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p);
+    }
+
+    int is_rg = !opts->tag || strcmp(opts->tag, "RG") == 0;
+    if (is_rg) {
+        if (!count_RG(retval->merged_input_header,
+                      &retval->output_count, &retval->tag_vals)) {
+            cleanup_state(retval, false);
+            return NULL;
+        }
+        if (opts->verbose)
+            fprintf(samtools_stderr, "@RG's found %zu\n",retval->output_count);
+    } else {
+        retval->output_count = 0;
+    }
+
+    // Prevent calloc(0, size);
+    size_t num = retval->output_count ? retval->output_count : 1;
+    retval->index_file_name = (char **)calloc(num, sizeof(char *));
+    retval->output_file_name = (char **)calloc(num, sizeof(char *));
+    retval->output_file = (samFile**)calloc(num, sizeof(samFile*));
+    retval->output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*));
+    retval->tag_val_hash = kh_init_c2i();
+    if (!retval->output_file_name || !retval->output_file || !retval->output_header ||
+        !retval->tag_val_hash || !retval->index_file_name) {
+        print_error_errno("split", "Could not initialise output file array");
+        cleanup_state(retval, false);
+        return NULL;
+    }
+    if (!is_rg)
+        return retval;  // Done for this case - outputs will be opened later
+
+    // Adjust max_split if too small for the read-groups listed in the header
+    if (opts->max_split < retval->output_count)
+        opts->max_split = retval->output_count;
+
+    // Open output files for RGs
+    char* dirsep = strrchr(opts->merged_input_name, '/');
+    char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
+    if (!input_base_name) {
+        print_error_errno("split", "Filename manipulation failed");
+        cleanup_state(retval, false);
+        return NULL;
+    }
+    char* extension = strrchr(input_base_name, '.');
+    if (extension) *extension = '\0';
+
+    size_t i;
+    for (i = 0; i < retval->output_count; i++) {
+        char* output_filename = NULL;
+        char outmode[4] = "w";
+
+        output_filename = expand_format_string(opts->output_format_string,
+                                               input_base_name,
+                                               retval->tag_vals[i], i,
+                                               opts->zero_pad, &opts->ga.out);
+
+        if ( output_filename == NULL ) {
+            cleanup_state(retval, false);
+            free(input_base_name);
+            return NULL;
+        }
+
+        retval->output_file_name[i] = output_filename;
+        sam_open_mode(outmode + 1, output_filename, NULL);
+        retval->output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out);
+
+        if (retval->output_file[i] == NULL) {
+            print_error_errno("split", "Could not open \"%s\"", output_filename);
+            cleanup_state(retval, false);
+            free(input_base_name);
+            return NULL;
+        }
+        if (retval->p.pool)
+            hts_set_opt(retval->output_file[i], HTS_OPT_THREAD_POOL, &retval->p);
+
+        // Record index in hash
+        int ret;
+        khiter_t iter = kh_put_c2i(retval->tag_val_hash, retval->tag_vals[i], &ret);
+        if (ret < 0) {
+            print_error_errno("split", "Couldn't add @RG ID to look-up table");
+            cleanup_state(retval, false);
+            free(input_base_name);
+            return NULL;
+        }
+        kh_val(retval->tag_val_hash,iter) = i;
+
+        // Set and edit header
+        retval->output_header[i] = sam_hdr_dup(retval->merged_input_header);
+        if (sam_hdr_remove_except(retval->output_header[i], "RG", "ID", retval->tag_vals[i]) ||
+            (!opts->no_pg &&
+             sam_hdr_add_pg(retval->output_header[i], "samtools",
+                            "VN", samtools_version(),
+                            arg_list ? "CL": NULL,
+                            arg_list ? arg_list : NULL,
+                            NULL))) {
+            print_error("split", "Could not rewrite header for \"%s\"", output_filename);
+            cleanup_state(retval, false);
+            free(input_base_name);
+            return NULL;
+        }
+    }
+
+    free(input_base_name);
+
+    return retval;
+}
+
+static bool split(state_t* state, parsed_opts_t *opts, char *arg_list)
+{
+    int is_rg = !opts->tag || strcmp(opts->tag, "RG") == 0;
+    if (state->unaccounted_file) {
+        if (sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) {
+            print_error_errno("split", "Could not write output file header");
+            return false;
+        }
+        if (opts->ga.write_index) {
+            state->unaccounted_idx_fn = auto_index(state->unaccounted_file,
+                                                   opts->unaccounted_name,
+                                                   state->unaccounted_header);
+            if (!state->unaccounted_idx_fn) {
+                print_error_errno("split",
+                                  "Creating index file for file \"%s\" failed",
+                                  opts->unaccounted_name);
+                return false;
+            }
+        }
+    }
+    bam1_t* file_read = bam_init1();
+    // Read the first record
+    int r;
+    if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
+        // Nothing more to read?  Ignore this file
+        bam_destroy1(file_read);
+        file_read = NULL;
+        if (r < -1) {
+            print_error("split", "Could not read first input record");
+            return false;
+        }
+    }
+
+    if (is_rg) {
+        size_t i;
+        for (i = 0; i < state->output_count; i++) {
+            if (sam_hdr_write(state->output_file[i], state->output_header[i]) != 0) {
+                print_error_errno("split", "Could not write file header to \"%s\"", state->output_file_name[i]);
+                goto error;
+            }
+            if (state->write_index) {
+                state->index_file_name[i] = auto_index(state->output_file[i],
+                        state->output_file_name[i],
+                        state->output_header[i]);
+                if (!state->index_file_name[i]) {
+                    print_error_errno("split", "Could not create index for file \"%s\"", state->output_file_name[i]);
+                    goto error;
+                }
+            }
+        }
+    }
+    while (file_read != NULL) {
+        // Get RG tag from read and look it up in hash to find file to output it to
+        uint8_t* tag = bam_aux_get(file_read, is_rg ? "RG" : opts->tag);
+        char *val = NULL;
+        char number[28];
+        khiter_t iter;
+        if (tag) {
+            switch (*tag) {
+            case 'Z': case 'H':
+                val = bam_aux2Z(tag);
+                break;
+            case 'c': case 'C': case 's': case 'S': case 'i': case 'I':
+                if (opts->zero_pad == 0) {
+                    snprintf(number, sizeof(number), "%"PRId64, bam_aux2i(tag));
+                } else {
+                    int64_t v = bam_aux2i(tag);
+                    snprintf(number, sizeof(number), "%0*"PRId64,
+                             v < 0 ? opts->zero_pad + 1 : opts->zero_pad, v);
+                }
+                val = number;
+                break;
+            default:
+                break;
+            }
+        }
+        if ( val != NULL ) {
+            iter = kh_get_c2i(state->tag_val_hash, val);
+        } else {
+            iter = kh_end(state->tag_val_hash);
+        }
+
+        // Check for opts->tag here instead of !is_rg so we open new
+        // files if the user specified '-d RG' and we find a RG:Z: value
+        // that wasn't listed in the header.  If the '-d' option is
+        // not used, we don't open a file to preserve existing behaviour.
+        if (opts->tag && val && iter == kh_end(state->tag_val_hash)
+            && state->output_count < opts->max_split) {
+            // Need to open a new output file
+            iter = prep_sam_file(opts, state, val, arg_list, is_rg);
+            if (iter == kh_end(state->tag_val_hash)) { // Open failed
+                print_error("split",
+                            "Could not create output file for tag \"%s:%s\"",
+                            opts->tag, bam_aux2Z(tag));
+                goto error;
+
+            }
+        }
+
+        // Write the read out to correct file
+        if (iter != kh_end(state->tag_val_hash)) {
+            // if found write to the appropriate untangled bam
+            int i = kh_val(state->tag_val_hash,iter);
+            if (sam_write1(state->output_file[i], state->output_header[i], file_read) < 0) {
+                print_error_errno("split", "Could not write to \"%s\"", state->output_file_name[i]);
+                goto error;
+            }
+        } else {
+            // otherwise write to the unaccounted bam if there is one or fail
+            if (state->unaccounted_file == NULL) {
+                if (tag) {
+                    fprintf(samtools_stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag));
+                } else {
+                    fprintf(samtools_stderr, "Read \"%s\" has no %s tag.\n",
+                            bam_get_qname(file_read), is_rg ? "RG" : opts->tag);
+                }
+                goto error;
+            } else {
+                if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) {
+                    print_error_errno("split", "Could not write to unaccounted output file");
+                    goto error;
+                }
+            }
+        }
+
+        // Replace written read with the next one to process
+        if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
+            // Nothing more to read?  Ignore this file in future
+            bam_destroy1(file_read);
+            file_read = NULL;
+            if (r < -1) {
+                print_error("split", "Could not read input record");
+                return false;
+            }
+        }
+    }
+
+    if (state->write_index) {
+        size_t i;
+        for (i = 0; i < state->output_count; i++) {
+            if (sam_idx_save(state->output_file[i]) < 0) {
+                print_error_errno("split", "writing index \"%s\" failed",
+                                  state->index_file_name[i]);
+                return false;
+            }
+        }
+        if (state->unaccounted_file) {
+            if (sam_idx_save(state->unaccounted_file) < 0) {
+                print_error_errno("split", "writing index \"%s\" failed",
+                                  state->unaccounted_idx_fn);
+                return false;
+            }
+        }
+    }
+
+    return true;
+error:
+    bam_destroy1(file_read);
+    return false;
+}
+
+static int cleanup_state(state_t* status, bool check_close)
+{
+    int ret = 0;
+
+    if (!status) return 0;
+    if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header);
+    if (status->unaccounted_file) {
+        if (sam_close(status->unaccounted_file) < 0 && check_close) {
+            print_error("split", "Error on closing unaccounted file");
+            ret = -1;
+        }
+    }
+    sam_close(status->merged_input_file);
+    size_t i;
+    for (i = 0; i < status->output_count; i++) {
+        if (status->output_header && status->output_header[i])
+            sam_hdr_destroy(status->output_header[i]);
+        if (status->output_file && status->output_file[i]) {
+            if (sam_close(status->output_file[i]) < 0 && check_close) {
+                print_error("split", "Error on closing output file \"%s\"", status->output_file_name[i]);
+                ret = -1;
+            }
+        }
+        if (status->tag_vals) free(status->tag_vals[i]);
+        if (status->output_file_name) free(status->output_file_name[i]);
+        if (status->index_file_name[i]) free(status->index_file_name[i]);
+    }
+    if (status->merged_input_header)
+        sam_hdr_destroy(status->merged_input_header);
+    free(status->output_header);
+    free(status->output_file);
+    free(status->output_file_name);
+    free(status->index_file_name);
+    free(status->unaccounted_idx_fn);
+    kh_destroy_c2i(status->tag_val_hash);
+
+    free(status->tag_vals);
+    if (status->p.pool)
+        hts_tpool_destroy(status->p.pool);
+    free(status);
+
+    return ret;
+}
+
+static void cleanup_opts(parsed_opts_t* opts)
+{
+    if (!opts) return;
+    sam_global_args_free(&opts->ga);
+    free(opts);
+}
+
+int main_split(int argc, char** argv)
+{
+    int ret = 1;
+    char *arg_list = NULL;
+    parsed_opts_t* opts = parse_args(argc, argv);
+    if (!opts) goto cleanup_opts;
+    if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
+        goto cleanup_opts;
+    state_t* status = init(opts, arg_list);
+    if (!status) goto cleanup_opts;
+
+    if (!split(status, opts, arg_list)) {
+        cleanup_state(status, false);
+        goto cleanup_opts;
+    }
+
+    ret = cleanup_state(status, true);
+
+cleanup_opts:
+    cleanup_opts(opts);
+    free(arg_list);
+
+    return ret;
+}
diff --git a/shared/package-files/e6/e629003355aabf1bf907025dcabe8121b03e29b03d21b4b7be622af29753a663/__init__.cpython-311.pyc b/shared/package-files/e6/e629003355aabf1bf907025dcabe8121b03e29b03d21b4b7be622af29753a663/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ea1bd7d893b5766d210220d2308b69dfbe2a57f
Binary files /dev/null and b/shared/package-files/e6/e629003355aabf1bf907025dcabe8121b03e29b03d21b4b7be622af29753a663/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6343b738b13fb7f08fd5ce5ff60a66b7bb126fbdd29301f9c2662d39ad75167/serialize.h b/shared/package-files/e6/e6343b738b13fb7f08fd5ce5ff60a66b7bb126fbdd29301f9c2662d39ad75167/serialize.h
new file mode 100644
index 0000000000000000000000000000000000000000..50f66782f276300bf234378f4b542aaedd278860
--- /dev/null
+++ b/shared/package-files/e6/e6343b738b13fb7f08fd5ce5ff60a66b7bb126fbdd29301f9c2662d39ad75167/serialize.h
@@ -0,0 +1,315 @@
+#pragma once
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::optim {
+namespace detail {
+// Utility function to save state
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const ska::flat_hash_map>&
+        state) {
+  for (const auto& item : state) {
+    serialize::OutputArchive param_state_archive(archive.compilation_unit());
+    std::string tensorimpl_key =
+        std::to_string(reinterpret_cast(item.first));
+    const DerivedOptimizerParamState& curr_state =
+        static_cast(*(item.second));
+    curr_state.serialize(param_state_archive);
+    archive.write(tensorimpl_key, param_state_archive);
+  }
+}
+
+// Utility function to load state
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    ska::flat_hash_map>& state) {
+  std::vector tensorimpl_keys = archive.keys();
+  for (const std::string& tensorimpl_key : tensorimpl_keys) {
+    serialize::InputArchive param_state_archive;
+    archive.read(tensorimpl_key, param_state_archive);
+    DerivedOptimizerParamState param_state;
+    param_state.serialize(param_state_archive);
+    // NOLINTNEXTLINE(performance-no-int-to-ptr)
+    state[reinterpret_cast(std::stoull(tensorimpl_key))] =
+        std::make_unique(param_state);
+  }
+}
+
+// Utility function to save param_groups
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::vector& param_groups) {
+  archive.write(
+      "param_groups/size",
+      torch::tensor(static_cast(param_groups.size())));
+  for (const auto i : c10::irange(param_groups.size())) {
+    serialize::OutputArchive param_group_archive(archive.compilation_unit());
+    std::vector params = param_groups[i].params();
+    param_group_archive.write(
+        "params/size", torch::tensor(static_cast(params.size())));
+    for (const auto index : c10::irange(params.size())) {
+      param_group_archive.write(
+          "params/" + std::to_string(index),
+          IValue(std::to_string(
+              reinterpret_cast(params[index].unsafeGetTensorImpl()))));
+    }
+    const DerivedOptimizerParamOptions& param_group_options =
+        static_cast(
+            param_groups[i].options());
+    serialize::OutputArchive param_group_options_archive(
+        param_group_archive.compilation_unit());
+    param_group_options.serialize(param_group_options_archive);
+    param_group_archive.write("options", param_group_options_archive);
+    archive.write("param_groups/" + std::to_string(i), param_group_archive);
+  }
+}
+
+// Utility function to load param_groups
+// We take as input vector of pair of string and unique_ptr to optimizer options
+// so that we can retain the state for each param by using the old tensor impl
+// keys (saved during serialization) and map the new tensor impl keys to the
+// correct state for each param
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    std::vector<
+        std::pair, std::unique_ptr>>&
+        param_groups) {
+  torch::Tensor param_groups_size_tensor;
+  archive.read("param_groups/size", param_groups_size_tensor);
+  const int64_t param_groups_size = param_groups_size_tensor.item();
+  for (const auto i : c10::irange(param_groups_size)) {
+    serialize::InputArchive param_group_archive;
+    archive.read("param_groups/" + std::to_string(i), param_group_archive);
+    torch::Tensor size_tensor;
+    param_group_archive.read("params/size", size_tensor);
+    const int64_t size = size_tensor.item();
+    std::vector params;
+    for (const auto index : c10::irange(size)) {
+      IValue ivalue;
+      param_group_archive.read("params/" + std::to_string(index), ivalue);
+      std::string element = ivalue.toStringRef();
+      params.emplace_back(element);
+    }
+    serialize::InputArchive param_group_options_archive;
+    param_group_archive.read("options", param_group_options_archive);
+    DerivedOptimizerParamOptions param_group_options(0);
+    param_group_options.serialize(param_group_options_archive);
+    param_groups.emplace_back(std::make_pair(
+        params,
+        std::make_unique(param_group_options)));
+  }
+}
+} // namespace detail
+
+// Note: These functions are all called `serialize()` so they can be called
+// inside a template where the archive type is a template type and can thus be
+// passed such that the appropriate overload is selected.
+
+/// Utility function to save a value of `int64_t` type.
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const int64_t& value);
+
+/// Utility function to load a value of `int64_t` type.
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    int64_t& value);
+
+/// Utility function to save a vector of step buffers.
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const std::vector& steps);
+
+/// Utility function to load a vector of step buffers.
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    std::vector& steps);
+
+// Utility function to save state and param_groups
+template <
+    typename DerivedOptimizerParamState,
+    typename DerivedOptimizerParamOptions>
+void serialize(serialize::OutputArchive& archive, const Optimizer& optimizer) {
+  archive.write("pytorch_version", IValue("1.5.0"));
+  serialize::OutputArchive state_archive(archive.compilation_unit());
+  detail::serialize(
+      state_archive, optimizer.state());
+  archive.write("state", state_archive);
+
+  serialize::OutputArchive param_groups_archive(archive.compilation_unit());
+  detail::serialize(
+      param_groups_archive, optimizer.param_groups());
+  archive.write("param_groups", param_groups_archive);
+}
+
+// Utility function to load state and param_groups and update state
+template <
+    typename DerivedOptimizerParamState,
+    typename DerivedOptimizerParamOptions>
+void serialize(serialize::InputArchive& archive, Optimizer& optimizer) {
+  IValue pytorch_version;
+  archive.read("pytorch_version", pytorch_version);
+  TORCH_INTERNAL_ASSERT(pytorch_version.toStringRef() == "1.5.0");
+  serialize::InputArchive state_archive;
+  archive.read("state", state_archive);
+  ska::flat_hash_map> saved_state;
+  detail::serialize(state_archive, saved_state);
+
+  serialize::InputArchive param_groups_archive;
+  archive.read("param_groups", param_groups_archive);
+  std::vector<
+      std::pair, std::unique_ptr>>
+      saved_param_groups;
+  detail::serialize(
+      param_groups_archive, saved_param_groups);
+
+  // update state and optimizer options
+  TORCH_CHECK(
+      saved_param_groups.size() == optimizer.param_groups().size(),
+      "loaded state dict has a different number of parameter groups");
+  for (const auto i : c10::irange(saved_param_groups.size())) {
+    std::vector param_group_old_keys = saved_param_groups[i].first;
+    std::vector params = optimizer.param_groups()[i].params();
+    TORCH_CHECK(
+        param_group_old_keys.size() == params.size(),
+        "loaded state dict contains a parameter group that has a different size than the optimizer's parameter group");
+
+    for (const auto idx : c10::irange(params.size())) {
+      auto param_group_old_key =
+          // NOLINTNEXTLINE(performance-no-int-to-ptr)
+          reinterpret_cast(std::stoull(param_group_old_keys[idx]));
+      if (saved_state.find(param_group_old_key) != saved_state.end()) {
+        optimizer.state()[params[idx].unsafeGetTensorImpl()] =
+            std::move(saved_state[param_group_old_key]);
+      }
+    }
+
+    auto& saved_options = reinterpret_cast(
+        *saved_param_groups[i].second);
+    auto& current_options = reinterpret_cast(
+        optimizer.param_groups()[i].options());
+    current_options = saved_options;
+  }
+}
+
+/// Utility function to save a vector of buffers.
+template 
+void serialize(
+    serialize::OutputArchive& archive,
+    const std::string& key,
+    const BufferContainer& buffers) {
+  archive.write(
+      key + "/size", torch::tensor(static_cast(buffers.size())));
+  for (const auto index : c10::irange(buffers.size())) {
+    archive.write(
+        key + "/" + std::to_string(index), buffers[index], /*is_buffer=*/true);
+  }
+}
+
+/// Utility function to load a vector of buffers.
+template 
+void serialize(
+    serialize::InputArchive& archive,
+    const std::string& key,
+    BufferContainer& buffers) {
+  buffers.clear();
+  torch::Tensor size_tensor;
+  archive.read(key + "/size", size_tensor);
+  const size_t size = size_tensor.item();
+  for (const auto index : c10::irange(size)) {
+    buffers.emplace_back();
+    archive.read(
+        key + "/" + std::to_string(index), buffers.back(), /*is_buffer=*/true);
+  }
+}
+
+template 
+c10::List deque_to_list(const std::deque& dq) {
+  c10::List list;
+  list.reserve(dq.size());
+  for (const auto& e : dq) {
+    list.emplace_back(e);
+  }
+  return list;
+}
+
+template 
+std::deque list_to_deque(const c10::List& list) {
+  std::deque dq;
+  for (const auto& e : list) {
+    dq.emplace_back(e);
+  }
+  return dq;
+}
+
+#define _TORCH_OPTIM_SERIALIZE(name) \
+  torch::optim::serialize(archive, #name, self.name)
+
+#define _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(OptimizerName)               \
+  torch::optim::serialize( \
+      archive, self)
+
+#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG(name)           \
+  {                                                      \
+    auto ivalue = torch::IValue(name());                 \
+    /* do not serialize if name is an undefined tensor*/ \
+    if (!(ivalue.isTensor() &&                           \
+          ivalue.unsafeToTensorImpl() ==                 \
+              at::UndefinedTensorImpl::singleton())) {   \
+      archive.write(#name, ivalue);                      \
+    }                                                    \
+  }
+
+#define _TORCH_OPTIM_SERIALIZE_TORCH_ARG_DEQUE(name)           \
+  {                                                            \
+    c10::IValue ivalue = torch::IValue(deque_to_list(name())); \
+    archive.write(#name, ivalue);                              \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(T, name)                        \
+  {                                                                        \
+    c10::IValue ivalue;                                                    \
+    bool exists = archive.try_read(#name, ivalue);                         \
+    if (exists) {                                                          \
+      name(ivalue.to());                                                \
+    } else {                                                               \
+      constexpr bool is_tensor_type = std::is_base_of_v; \
+      TORCH_INTERNAL_ASSERT(is_tensor_type);                               \
+    }                                                                      \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_OPTIONAL(T, name) \
+  {                                                          \
+    c10::IValue ivalue;                                      \
+    bool exists = archive.try_read(#name, ivalue);           \
+    if (exists) {                                            \
+      name(ivalue.toOptional());                          \
+    }                                                        \
+  }
+
+#define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_DEQUE(T, name) \
+  {                                                       \
+    c10::IValue ivalue;                                   \
+    archive.read(#name, ivalue);                          \
+    auto list = ivalue.to>();    \
+    name(list_to_deque(list));                            \
+  }
+
+} // namespace torch::optim
diff --git a/shared/package-files/e6/e638ade7b515921ba9ece54832f8404e81a1ac069f2286ce46603752b95a8e4a/_sparse_sum_native.h b/shared/package-files/e6/e638ade7b515921ba9ece54832f8404e81a1ac069f2286ce46603752b95a8e4a/_sparse_sum_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..1fc416c9cce0b9f1f2f31f668e156fe260f63cd3
--- /dev/null
+++ b/shared/package-files/e6/e638ade7b515921ba9ece54832f8404e81a1ac069f2286ce46603752b95a8e4a/_sparse_sum_native.h
@@ -0,0 +1,25 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor _sparse_sum(const at::Tensor & self);
+TORCH_API at::Tensor _sparse_sum(const at::Tensor & self, at::ScalarType dtype);
+TORCH_API at::Tensor _sparse_sum(const at::Tensor & self, at::IntArrayRef dim);
+TORCH_API at::Tensor & _sparse_sum_dim_out(const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out);
+TORCH_API at::Tensor _sparse_sum(const at::Tensor & self, at::IntArrayRef dim, at::ScalarType dtype);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e63d3e659465b95edceee2efe703bcc9ddc88aca1863ee737aabaaaf0c95116b/test_immutable_ndim_array.cpython-311.pyc b/shared/package-files/e6/e63d3e659465b95edceee2efe703bcc9ddc88aca1863ee737aabaaaf0c95116b/test_immutable_ndim_array.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..581d3115f8a32121abd6d23ed4c810f9b3c4f361
Binary files /dev/null and b/shared/package-files/e6/e63d3e659465b95edceee2efe703bcc9ddc88aca1863ee737aabaaaf0c95116b/test_immutable_ndim_array.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e63edc0aa05635fb196a135dc8b1c8eaf9673b41fa7935a7562ed6902ede6dfb/NetworkFlow.h b/shared/package-files/e6/e63edc0aa05635fb196a135dc8b1c8eaf9673b41fa7935a7562ed6902ede6dfb/NetworkFlow.h
new file mode 100644
index 0000000000000000000000000000000000000000..684b88906578f0fec70c15a5778e818e99f4dfc5
--- /dev/null
+++ b/shared/package-files/e6/e63edc0aa05635fb196a135dc8b1c8eaf9673b41fa7935a7562ed6902ede6dfb/NetworkFlow.h
@@ -0,0 +1,54 @@
+#pragma once
+
+#include 
+
+#include 
+#include 
+
+/**
+ * This file provides a network flow implementation.
+ * https://en.wikipedia.org/wiki/Flow_network
+ *
+ * It aims to mirror some of the behavior of networkx, which is/was used by
+ * functorch partitioners for splitting the graph into a forward and backward
+ * graph.
+ */
+
+namespace c10 {
+
+enum class C10_API_ENUM MinCutStatus {
+  SUCCESS = 0,
+  UNBOUNDED = 1,
+  OVERFLOW_INF = 2,
+  INVALID = 3,
+};
+
+struct MinCutResult {
+  MinCutStatus status;
+  int64_t max_flow;
+  std::vector reachable;
+  std::vector unreachable;
+};
+
+// Modeled after networkx implementation
+class C10_API NetworkFlowGraph {
+ public:
+  // selected such that INF + INF is < INT64_MAX
+  constexpr static int64_t INF = (1LL << 62) - 1;
+
+  struct Edge {
+    std::string source, dest;
+    int64_t capacity;
+  };
+
+  MinCutStatus add_edge(
+      const std::string& source,
+      const std::string& dest,
+      int64_t capacity = 1);
+
+  MinCutResult minimum_cut(const std::string& s, const std::string& t) const;
+
+  std::vector edges;
+};
+
+} // namespace c10
diff --git a/shared/package-files/e6/e640518fdb6e06c56b781b18db61f67de30efc9419b12a0e64c53f3097d47af6/test_dist_info.py b/shared/package-files/e6/e640518fdb6e06c56b781b18db61f67de30efc9419b12a0e64c53f3097d47af6/test_dist_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..426694e0198fdbe6ee7466822bc7c15634e2b648
--- /dev/null
+++ b/shared/package-files/e6/e640518fdb6e06c56b781b18db61f67de30efc9419b12a0e64c53f3097d47af6/test_dist_info.py
@@ -0,0 +1,210 @@
+"""Test .dist-info style distributions."""
+
+import pathlib
+import re
+import shutil
+import subprocess
+import sys
+from functools import partial
+
+import pytest
+
+import pkg_resources
+from setuptools.archive_util import unpack_archive
+
+from .textwrap import DALS
+
+read = partial(pathlib.Path.read_text, encoding="utf-8")
+
+
+class TestDistInfo:
+    metadata_base = DALS(
+        """
+        Metadata-Version: 1.2
+        Requires-Dist: splort (==4)
+        Provides-Extra: baz
+        Requires-Dist: quux (>=1.1); extra == 'baz'
+        """
+    )
+
+    @classmethod
+    def build_metadata(cls, **kwargs):
+        lines = ('{key}: {value}\n'.format(**locals()) for key, value in kwargs.items())
+        return cls.metadata_base + ''.join(lines)
+
+    @pytest.fixture
+    def metadata(self, tmpdir):
+        dist_info_name = 'VersionedDistribution-2.718.dist-info'
+        versioned = tmpdir / dist_info_name
+        versioned.mkdir()
+        filename = versioned / 'METADATA'
+        content = self.build_metadata(
+            Name='VersionedDistribution',
+        )
+        filename.write_text(content, encoding='utf-8')
+
+        dist_info_name = 'UnversionedDistribution.dist-info'
+        unversioned = tmpdir / dist_info_name
+        unversioned.mkdir()
+        filename = unversioned / 'METADATA'
+        content = self.build_metadata(
+            Name='UnversionedDistribution',
+            Version='0.3',
+        )
+        filename.write_text(content, encoding='utf-8')
+
+        return str(tmpdir)
+
+    def test_distinfo(self, metadata):
+        dists = dict(
+            (d.project_name, d) for d in pkg_resources.find_distributions(metadata)
+        )
+
+        assert len(dists) == 2, dists
+
+        unversioned = dists['UnversionedDistribution']
+        versioned = dists['VersionedDistribution']
+
+        assert versioned.version == '2.718'  # from filename
+        assert unversioned.version == '0.3'  # from METADATA
+
+    def test_conditional_dependencies(self, metadata):
+        specs = 'splort==4', 'quux>=1.1'
+        requires = list(map(pkg_resources.Requirement.parse, specs))
+
+        for d in pkg_resources.find_distributions(metadata):
+            assert d.requires() == requires[:1]
+            assert d.requires(extras=('baz',)) == [
+                requires[0],
+                pkg_resources.Requirement.parse('quux>=1.1;extra=="baz"'),
+            ]
+            assert d.extras == ['baz']
+
+    def test_invalid_version(self, tmp_path):
+        """
+        Supplying an invalid version crashes dist_info.
+        """
+        config = "[metadata]\nname=proj\nversion=42\n[egg_info]\ntag_build=invalid!!!\n"
+        (tmp_path / "setup.cfg").write_text(config, encoding="utf-8")
+        msg = re.compile("invalid version", re.M | re.I)
+        proc = run_command_inner("dist_info", cwd=tmp_path, check=False)
+        assert proc.returncode
+        assert msg.search(proc.stdout)
+        assert not list(tmp_path.glob("*.dist-info"))
+
+    def test_tag_arguments(self, tmp_path):
+        config = """
+        [metadata]
+        name=proj
+        version=42
+        [egg_info]
+        tag_date=1
+        tag_build=.post
+        """
+        (tmp_path / "setup.cfg").write_text(config, encoding="utf-8")
+
+        print(run_command("dist_info", "--no-date", cwd=tmp_path))
+        dist_info = next(tmp_path.glob("*.dist-info"))
+        assert dist_info.name.startswith("proj-42")
+        shutil.rmtree(dist_info)
+
+        print(run_command("dist_info", "--tag-build", ".a", cwd=tmp_path))
+        dist_info = next(tmp_path.glob("*.dist-info"))
+        assert dist_info.name.startswith("proj-42a")
+
+    @pytest.mark.parametrize("keep_egg_info", (False, True))
+    def test_output_dir(self, tmp_path, keep_egg_info):
+        config = "[metadata]\nname=proj\nversion=42\n"
+        (tmp_path / "setup.cfg").write_text(config, encoding="utf-8")
+        out = tmp_path / "__out"
+        out.mkdir()
+        opts = ["--keep-egg-info"] if keep_egg_info else []
+        run_command("dist_info", "--output-dir", out, *opts, cwd=tmp_path)
+        assert len(list(out.glob("*.dist-info"))) == 1
+        assert len(list(tmp_path.glob("*.dist-info"))) == 0
+        expected_egg_info = int(keep_egg_info)
+        assert len(list(out.glob("*.egg-info"))) == expected_egg_info
+        assert len(list(tmp_path.glob("*.egg-info"))) == 0
+        assert len(list(out.glob("*.__bkp__"))) == 0
+        assert len(list(tmp_path.glob("*.__bkp__"))) == 0
+
+
+class TestWheelCompatibility:
+    """Make sure the .dist-info directory produced with the ``dist_info`` command
+    is the same as the one produced by ``bdist_wheel``.
+    """
+
+    SETUPCFG = DALS(
+        """
+    [metadata]
+    name = {name}
+    version = {version}
+
+    [options]
+    install_requires =
+        foo>=12; sys_platform != "linux"
+
+    [options.extras_require]
+    test = pytest
+
+    [options.entry_points]
+    console_scripts =
+        executable-name = my_package.module:function
+    discover =
+        myproj = my_package.other_module:function
+    """
+    )
+
+    EGG_INFO_OPTS = [
+        # Related: #3088 #2872
+        ("", ""),
+        (".post", "[egg_info]\ntag_build = post\n"),
+        (".post", "[egg_info]\ntag_build = .post\n"),
+        (".post", "[egg_info]\ntag_build = post\ntag_date = 1\n"),
+        (".dev", "[egg_info]\ntag_build = .dev\n"),
+        (".dev", "[egg_info]\ntag_build = .dev\ntag_date = 1\n"),
+        ("a1", "[egg_info]\ntag_build = .a1\n"),
+        ("+local", "[egg_info]\ntag_build = +local\n"),
+    ]
+
+    @pytest.mark.parametrize("name", "my-proj my_proj my.proj My.Proj".split())
+    @pytest.mark.parametrize("version", ["0.42.13"])
+    @pytest.mark.parametrize(("suffix", "cfg"), EGG_INFO_OPTS)
+    def test_dist_info_is_the_same_as_in_wheel(
+        self, name, version, tmp_path, suffix, cfg
+    ):
+        config = self.SETUPCFG.format(name=name, version=version) + cfg
+
+        for i in "dir_wheel", "dir_dist":
+            (tmp_path / i).mkdir()
+            (tmp_path / i / "setup.cfg").write_text(config, encoding="utf-8")
+
+        run_command("bdist_wheel", cwd=tmp_path / "dir_wheel")
+        wheel = next(tmp_path.glob("dir_wheel/dist/*.whl"))
+        unpack_archive(wheel, tmp_path / "unpack")
+        wheel_dist_info = next(tmp_path.glob("unpack/*.dist-info"))
+
+        run_command("dist_info", cwd=tmp_path / "dir_dist")
+        dist_info = next(tmp_path.glob("dir_dist/*.dist-info"))
+
+        assert dist_info.name == wheel_dist_info.name
+        assert dist_info.name.startswith(f"my_proj-{version}{suffix}")
+        for file in "METADATA", "entry_points.txt":
+            assert read(dist_info / file) == read(wheel_dist_info / file)
+
+
+def run_command_inner(*cmd, **kwargs):
+    opts = {
+        "stderr": subprocess.STDOUT,
+        "stdout": subprocess.PIPE,
+        "text": True,
+        "encoding": "utf-8",
+        "check": True,
+        **kwargs,
+    }
+    cmd = [sys.executable, "-c", "__import__('setuptools').setup()", *map(str, cmd)]
+    return subprocess.run(cmd, **opts)
+
+
+def run_command(*args, **kwargs):
+    return run_command_inner(*args, **kwargs).stdout
diff --git a/shared/package-files/e6/e6414bbc158ad2007fc17f892ec49cca67cbb6d4f90920f4267ddeb19f032a03/timeit.py b/shared/package-files/e6/e6414bbc158ad2007fc17f892ec49cca67cbb6d4f90920f4267ddeb19f032a03/timeit.py
new file mode 100644
index 0000000000000000000000000000000000000000..3250563f4222ddfd49b4ccc3b16c30ab3628f62c
--- /dev/null
+++ b/shared/package-files/e6/e6414bbc158ad2007fc17f892ec49cca67cbb6d4f90920f4267ddeb19f032a03/timeit.py
@@ -0,0 +1,382 @@
+#! /usr/bin/env python3
+
+"""Tool for measuring execution time of small code snippets.
+
+This module avoids a number of common traps for measuring execution
+times.  See also Tim Peters' introduction to the Algorithms chapter in
+the Python Cookbook, published by O'Reilly.
+
+Library usage: see the Timer class.
+
+Command line usage:
+    python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement]
+
+Options:
+  -n/--number N: how many times to execute 'statement' (default: see below)
+  -r/--repeat N: how many times to repeat the timer (default 5)
+  -s/--setup S: statement to be executed once initially (default 'pass').
+                Execution time of this setup statement is NOT timed.
+  -p/--process: use time.process_time() (default is time.perf_counter())
+  -v/--verbose: print raw timing results; repeat for more digits precision
+  -u/--unit: set the output time unit (nsec, usec, msec, or sec)
+  -h/--help: print this usage message and exit
+  --: separate options from statement, use when statement starts with -
+  statement: statement to be timed (default 'pass')
+
+A multi-line statement may be given by specifying each line as a
+separate argument; indented lines are possible by enclosing an
+argument in quotes and using leading spaces.  Multiple -s options are
+treated similarly.
+
+If -n is not given, a suitable number of loops is calculated by trying
+increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the
+total time is at least 0.2 seconds.
+
+Note: there is a certain baseline overhead associated with executing a
+pass statement.  It differs between versions.  The code here doesn't try
+to hide it, but you should be aware of it.  The baseline overhead can be
+measured by invoking the program without arguments.
+
+Classes:
+
+    Timer
+
+Functions:
+
+    timeit(string, string) -> float
+    repeat(string, string) -> list
+    default_timer() -> float
+
+"""
+
+import gc
+import itertools
+import sys
+import time
+
+__all__ = ["Timer", "timeit", "repeat", "default_timer"]
+
+dummy_src_name = ""
+default_number = 1000000
+default_repeat = 5
+default_timer = time.perf_counter
+
+_globals = globals
+
+# Don't change the indentation of the template; the reindent() calls
+# in Timer.__init__() depend on setup being indented 4 spaces and stmt
+# being indented 8 spaces.
+template = """
+def inner(_it, _timer{init}):
+    {setup}
+    _t0 = _timer()
+    for _i in _it:
+        {stmt}
+        pass
+    _t1 = _timer()
+    return _t1 - _t0
+"""
+
+
+def reindent(src, indent):
+    """Helper to reindent a multi-line statement."""
+    return src.replace("\n", "\n" + " " * indent)
+
+
+class Timer:
+    """Class for timing execution speed of small code snippets.
+
+    The constructor takes a statement to be timed, an additional
+    statement used for setup, and a timer function.  Both statements
+    default to 'pass'; the timer function is platform-dependent (see
+    module doc string).  If 'globals' is specified, the code will be
+    executed within that namespace (as opposed to inside timeit's
+    namespace).
+
+    To measure the execution time of the first statement, use the
+    timeit() method.  The repeat() method is a convenience to call
+    timeit() multiple times and return a list of results.
+
+    The statements may contain newlines, as long as they don't contain
+    multi-line string literals.
+    """
+
+    def __init__(self, stmt="pass", setup="pass", timer=default_timer,
+                 globals=None):
+        """Constructor.  See class doc string."""
+        self.timer = timer
+        local_ns = {}
+        global_ns = _globals() if globals is None else globals
+        init = ''
+        if isinstance(setup, str):
+            # Check that the code can be compiled outside a function
+            compile(setup, dummy_src_name, "exec")
+            stmtprefix = setup + '\n'
+            setup = reindent(setup, 4)
+        elif callable(setup):
+            local_ns['_setup'] = setup
+            init += ', _setup=_setup'
+            stmtprefix = ''
+            setup = '_setup()'
+        else:
+            raise ValueError("setup is neither a string nor callable")
+        if isinstance(stmt, str):
+            # Check that the code can be compiled outside a function
+            compile(stmtprefix + stmt, dummy_src_name, "exec")
+            stmt = reindent(stmt, 8)
+        elif callable(stmt):
+            local_ns['_stmt'] = stmt
+            init += ', _stmt=_stmt'
+            stmt = '_stmt()'
+        else:
+            raise ValueError("stmt is neither a string nor callable")
+        src = template.format(stmt=stmt, setup=setup, init=init)
+        self.src = src  # Save for traceback display
+        code = compile(src, dummy_src_name, "exec")
+        exec(code, global_ns, local_ns)
+        self.inner = local_ns["inner"]
+
+    def print_exc(self, file=None):
+        """Helper to print a traceback from the timed code.
+
+        Typical use:
+
+            t = Timer(...)       # outside the try/except
+            try:
+                t.timeit(...)    # or t.repeat(...)
+            except:
+                t.print_exc()
+
+        The advantage over the standard traceback is that source lines
+        in the compiled template will be displayed.
+
+        The optional file argument directs where the traceback is
+        sent; it defaults to sys.stderr.
+        """
+        import linecache, traceback
+        if self.src is not None:
+            linecache.cache[dummy_src_name] = (len(self.src),
+                                               None,
+                                               self.src.split("\n"),
+                                               dummy_src_name)
+        # else the source is already stored somewhere else
+
+        traceback.print_exc(file=file)
+
+    def timeit(self, number=default_number):
+        """Time 'number' executions of the main statement.
+
+        To be precise, this executes the setup statement once, and
+        then returns the time it takes to execute the main statement
+        a number of times, as float seconds if using the default timer.   The
+        argument is the number of times through the loop, defaulting
+        to one million.  The main statement, the setup statement and
+        the timer function to be used are passed to the constructor.
+        """
+        it = itertools.repeat(None, number)
+        gcold = gc.isenabled()
+        gc.disable()
+        try:
+            timing = self.inner(it, self.timer)
+        finally:
+            if gcold:
+                gc.enable()
+        return timing
+
+    def repeat(self, repeat=default_repeat, number=default_number):
+        """Call timeit() a few times.
+
+        This is a convenience function that calls the timeit()
+        repeatedly, returning a list of results.  The first argument
+        specifies how many times to call timeit(), defaulting to 5;
+        the second argument specifies the timer argument, defaulting
+        to one million.
+
+        Note: it's tempting to calculate mean and standard deviation
+        from the result vector and report these.  However, this is not
+        very useful.  In a typical case, the lowest value gives a
+        lower bound for how fast your machine can run the given code
+        snippet; higher values in the result vector are typically not
+        caused by variability in Python's speed, but by other
+        processes interfering with your timing accuracy.  So the min()
+        of the result is probably the only number you should be
+        interested in.  After that, you should look at the entire
+        vector and apply common sense rather than statistics.
+        """
+        r = []
+        for i in range(repeat):
+            t = self.timeit(number)
+            r.append(t)
+        return r
+
+    def autorange(self, callback=None):
+        """Return the number of loops and time taken so that total time >= 0.2.
+
+        Calls the timeit method with increasing numbers from the sequence
+        1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2
+        second.  Returns (number, time_taken).
+
+        If *callback* is given and is not None, it will be called after
+        each trial with two arguments: ``callback(number, time_taken)``.
+        """
+        i = 1
+        while True:
+            for j in 1, 2, 5:
+                number = i * j
+                time_taken = self.timeit(number)
+                if callback:
+                    callback(number, time_taken)
+                if time_taken >= 0.2:
+                    return (number, time_taken)
+            i *= 10
+
+
+def timeit(stmt="pass", setup="pass", timer=default_timer,
+           number=default_number, globals=None):
+    """Convenience function to create Timer object and call timeit method."""
+    return Timer(stmt, setup, timer, globals).timeit(number)
+
+
+def repeat(stmt="pass", setup="pass", timer=default_timer,
+           repeat=default_repeat, number=default_number, globals=None):
+    """Convenience function to create Timer object and call repeat method."""
+    return Timer(stmt, setup, timer, globals).repeat(repeat, number)
+
+
+def main(args=None, *, _wrap_timer=None):
+    """Main program, used when run as a script.
+
+    The optional 'args' argument specifies the command line to be parsed,
+    defaulting to sys.argv[1:].
+
+    The return value is an exit code to be passed to sys.exit(); it
+    may be None to indicate success.
+
+    When an exception happens during timing, a traceback is printed to
+    stderr and the return value is 1.  Exceptions at other times
+    (including the template compilation) are not caught.
+
+    '_wrap_timer' is an internal interface used for unit testing.  If it
+    is not None, it must be a callable that accepts a timer function
+    and returns another timer function (used for unit testing).
+    """
+    if args is None:
+        args = sys.argv[1:]
+    import getopt
+    try:
+        opts, args = getopt.getopt(args, "n:u:s:r:tcpvh",
+                                   ["number=", "setup=", "repeat=",
+                                    "time", "clock", "process",
+                                    "verbose", "unit=", "help"])
+    except getopt.error as err:
+        print(err)
+        print("use -h/--help for command line help")
+        return 2
+
+    timer = default_timer
+    stmt = "\n".join(args) or "pass"
+    number = 0  # auto-determine
+    setup = []
+    repeat = default_repeat
+    verbose = 0
+    time_unit = None
+    units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0}
+    precision = 3
+    for o, a in opts:
+        if o in ("-n", "--number"):
+            number = int(a)
+        if o in ("-s", "--setup"):
+            setup.append(a)
+        if o in ("-u", "--unit"):
+            if a in units:
+                time_unit = a
+            else:
+                print("Unrecognized unit. Please select nsec, usec, msec, or sec.",
+                      file=sys.stderr)
+                return 2
+        if o in ("-r", "--repeat"):
+            repeat = int(a)
+            if repeat <= 0:
+                repeat = 1
+        if o in ("-p", "--process"):
+            timer = time.process_time
+        if o in ("-v", "--verbose"):
+            if verbose:
+                precision += 1
+            verbose += 1
+        if o in ("-h", "--help"):
+            print(__doc__, end=' ')
+            return 0
+    setup = "\n".join(setup) or "pass"
+
+    # Include the current directory, so that local imports work (sys.path
+    # contains the directory of this script, rather than the current
+    # directory)
+    import os
+    sys.path.insert(0, os.curdir)
+    if _wrap_timer is not None:
+        timer = _wrap_timer(timer)
+
+    t = Timer(stmt, setup, timer)
+    if number == 0:
+        # determine number so that 0.2 <= total time < 2.0
+        callback = None
+        if verbose:
+            def callback(number, time_taken):
+                msg = "{num} loop{s} -> {secs:.{prec}g} secs"
+                plural = (number != 1)
+                print(msg.format(num=number, s='s' if plural else '',
+                                 secs=time_taken, prec=precision))
+        try:
+            number, _ = t.autorange(callback)
+        except:
+            t.print_exc()
+            return 1
+
+        if verbose:
+            print()
+
+    try:
+        raw_timings = t.repeat(repeat, number)
+    except:
+        t.print_exc()
+        return 1
+
+    def format_time(dt):
+        unit = time_unit
+
+        if unit is not None:
+            scale = units[unit]
+        else:
+            scales = [(scale, unit) for unit, scale in units.items()]
+            scales.sort(reverse=True)
+            for scale, unit in scales:
+                if dt >= scale:
+                    break
+
+        return "%.*g %s" % (precision, dt / scale, unit)
+
+    if verbose:
+        print("raw times: %s" % ", ".join(map(format_time, raw_timings)))
+        print()
+    timings = [dt / number for dt in raw_timings]
+
+    best = min(timings)
+    print("%d loop%s, best of %d: %s per loop"
+          % (number, 's' if number != 1 else '',
+             repeat, format_time(best)))
+
+    best = min(timings)
+    worst = max(timings)
+    if worst >= best * 4:
+        import warnings
+        warnings.warn_explicit("The test results are likely unreliable. "
+                               "The worst time (%s) was more than four times "
+                               "slower than the best time (%s)."
+                               % (format_time(worst), format_time(best)),
+                               UserWarning, '', 0)
+    return None
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/shared/package-files/e6/e6455b9418678f1aad597e4829ebcf4eb74e5a8237be7d6820870f89f161eba7/create_autodiff_subgraphs.h b/shared/package-files/e6/e6455b9418678f1aad597e4829ebcf4eb74e5a8237be7d6820870f89f161eba7/create_autodiff_subgraphs.h
new file mode 100644
index 0000000000000000000000000000000000000000..6cfc8fda6be7fb1d0ed256dd5d6ea242fe9a7369
--- /dev/null
+++ b/shared/package-files/e6/e6455b9418678f1aad597e4829ebcf4eb74e5a8237be7d6820870f89f161eba7/create_autodiff_subgraphs.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+#include 
+
+#include 
+
+namespace torch::jit {
+
+// insert GraphExecutor nodes that group together
+// subgraphs that are differentiable by the jit's autodiff passes
+// threshold - minimum number of nodes that will appear in a block
+// returns all differentiable blocks that have been found
+TORCH_API std::vector CreateAutodiffSubgraphs(
+    const std::shared_ptr& graph,
+    size_t threshold = 2);
+} // namespace torch::jit
diff --git a/shared/package-files/e6/e645c9e13cfb7ffbec7cfb16976716ebf0270924b9ccfaa853c9cfd037bbf5d8/layer_norm_expanded_weights.py b/shared/package-files/e6/e645c9e13cfb7ffbec7cfb16976716ebf0270924b9ccfaa853c9cfd037bbf5d8/layer_norm_expanded_weights.py
new file mode 100644
index 0000000000000000000000000000000000000000..f223f97460a129d6feebf83dfd847eaf81a57451
--- /dev/null
+++ b/shared/package-files/e6/e645c9e13cfb7ffbec7cfb16976716ebf0270924b9ccfaa853c9cfd037bbf5d8/layer_norm_expanded_weights.py
@@ -0,0 +1,87 @@
+# mypy: allow-untyped-defs
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+
+from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
+from .expanded_weights_utils import (
+    forward_helper,
+    set_grad_sample_if_exists,
+    standard_kwargs,
+    sum_over_all_but_batch_and_last_n,
+    unpack_expanded_weight_or_tensor,
+)
+
+
+@implements_per_sample_grads(F.layer_norm)
+class LayerNormPerSampleGrad(torch.autograd.Function):
+    @staticmethod
+    def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
+        expanded_args, expanded_kwargs = standard_kwargs(
+            kwarg_names, expanded_args_and_kwargs
+        )
+        input = expanded_args[0]
+        normalized_shape = expanded_args[1]
+        if len(input.shape) <= len(normalized_shape):
+            raise RuntimeError(
+                "Expanded Weights: Layer norm should not normalize over batch dimension for per sample gradient"
+                f"computations but got that normalized shape, {normalized_shape}, matched input shape."
+            )
+        output, mean, rstd = forward_helper(
+            torch.native_layer_norm, expanded_args, expanded_kwargs
+        )
+        ctx.args = expanded_args
+
+        if input.requires_grad or isinstance(expanded_kwargs["weight"], ExpandedWeight):
+            ctx.weight = expanded_kwargs["weight"]
+        if input.requires_grad or isinstance(expanded_kwargs["bias"], ExpandedWeight):
+            ctx.bias = expanded_kwargs["bias"]
+        ctx.eps = expanded_kwargs["eps"]
+        ctx.mean, ctx.rstd = mean, rstd
+        return output
+
+    @staticmethod
+    def backward(ctx, grad_output):
+        def weight_per_sample_grad(weight):
+            return sum_over_all_but_batch_and_last_n(
+                F.layer_norm(input, normalized_shape, eps=ctx.eps) * grad_output,
+                weight.dim(),
+            )
+
+        input, normalized_shape = ctx.args
+        mean, rstd = ctx.mean, ctx.rstd
+
+        results: list[Optional[torch.Tensor]] = []
+        results.append(None)  # for kwarg names
+        results.append(None)  # for op reference
+        if input.requires_grad:
+            weight_ = unpack_expanded_weight_or_tensor(ctx.weight)
+            bias_ = unpack_expanded_weight_or_tensor(ctx.bias)
+            results.append(
+                torch.ops.aten.native_layer_norm_backward(
+                    grad_output,
+                    input,
+                    normalized_shape,
+                    mean,
+                    rstd,
+                    weight_,
+                    bias_,
+                    (True, False, False),
+                )[0]
+            )
+        else:
+            results.append(None)
+
+        # weight and bias don't compute batched gradients; no other arguments are differentiable
+        results = results + [None] * 4
+
+        # set grad_sample field for weight and bias with per sample gradients
+        if hasattr(ctx, "weight"):
+            set_grad_sample_if_exists(ctx.weight, weight_per_sample_grad)
+        if hasattr(ctx, "bias"):
+            set_grad_sample_if_exists(
+                ctx.bias,
+                lambda bias: sum_over_all_but_batch_and_last_n(grad_output, bias.dim()),
+            )
+        return tuple(results)
diff --git a/shared/package-files/e6/e64b9f34a4062d67325eaa41ca42c9e792263d5b14a5c47b32df58f0dc137f08/test_guess.cpython-311.pyc b/shared/package-files/e6/e64b9f34a4062d67325eaa41ca42c9e792263d5b14a5c47b32df58f0dc137f08/test_guess.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4718ca6f39e544806d0acc580518c5fbdd48b805
Binary files /dev/null and b/shared/package-files/e6/e64b9f34a4062d67325eaa41ca42c9e792263d5b14a5c47b32df58f0dc137f08/test_guess.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e653bfda1c2d00f26d956912cd4ac6e892334899fd5300c18a8fb6e7f8bd6093/sample_pymc.cpython-311.pyc b/shared/package-files/e6/e653bfda1c2d00f26d956912cd4ac6e892334899fd5300c18a8fb6e7f8bd6093/sample_pymc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..521a7565298a0add9d1c99f1d8f28c6e1788cca9
Binary files /dev/null and b/shared/package-files/e6/e653bfda1c2d00f26d956912cd4ac6e892334899fd5300c18a8fb6e7f8bd6093/sample_pymc.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6545f4a41626bfc41037d82b0f160a55439117f76f7192e89d43103d3ba0e53/sdpa.py b/shared/package-files/e6/e6545f4a41626bfc41037d82b0f160a55439117f76f7192e89d43103d3ba0e53/sdpa.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ac4cc86a58cc3d7bd385a9290e1ec07ab6f8fc2
--- /dev/null
+++ b/shared/package-files/e6/e6545f4a41626bfc41037d82b0f160a55439117f76f7192e89d43103d3ba0e53/sdpa.py
@@ -0,0 +1,934 @@
+# mypy: allow-untyped-defs
+import logging
+from typing import Optional
+
+import torch
+import torch.nn
+import torch.nn.functional as F
+from torch.backends.cuda import (
+    can_use_cudnn_attention,
+    can_use_efficient_attention,
+    can_use_flash_attention,
+    cudnn_sdp_enabled,
+    flash_sdp_enabled,
+    math_sdp_enabled,
+    mem_efficient_sdp_enabled,
+    SDPAParams,
+)
+from torch.nn.attention import SDPBackend
+
+from .nested_tensor import NestedTensor
+
+
+log = logging.getLogger(__name__)
+
+
+def _validate_sdpa_input(
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    attn_mask: Optional[torch.Tensor] = None,
+    dropout_p=0.0,
+    is_causal=False,
+    scale=None,
+):
+    if (
+        not isinstance(query, NestedTensor)
+        or not isinstance(key, NestedTensor)
+        or not isinstance(value, NestedTensor)
+    ):
+        raise ValueError(
+            f"Expected query, key, and value to be nested tensors, "
+            f"but got query.is_nested: {query.is_nested}, key.is_nested: {key.is_nested}, "
+            f"and value.is_nested: {value.is_nested} instead."
+        )
+    if query.dtype != key.dtype or query.dtype != value.dtype:
+        raise ValueError(
+            f"Expected query, key, and value to have the same dtype, "
+            f"but got query.dtype: {query.dtype}, key.dtype: {key.dtype}, "
+            f"and value.dtype: {value.dtype} instead."
+        )
+    if query.device != key.device or query.device != value.device:
+        raise ValueError(
+            f"Expected query, key, and value to have the same device type, "
+            f"but got query.device: {query.device}, key.device: {key.device}, "
+            f"and value.device: {value.device} instead."
+        )
+    if query.dim() < 3 or key.dim() < 3 or value.dim() < 3:
+        raise ValueError(
+            f"Expected query, key, and value to all be  at least 3 dimensional, but got query.dim: "
+            f"{query.dim()}, key.dim: {key.dim()} and value.dim: {value.dim()} instead."
+        )
+    if query._ragged_idx != key._ragged_idx or query._ragged_idx != value._ragged_idx:
+        raise ValueError(
+            f"Expected query, key, and value to all be ragged on the same dimension, but got ragged "
+            f"dims {query._ragged_idx}, {key._ragged_idx}, and {value._ragged_idx}, respectively."
+        )
+    if attn_mask is not None:
+        # TODO: Figure out whether masks are actually supported for this layout or not
+        raise ValueError("Masks are not yet supported!")
+        if attn_mask.dtype != torch.bool and attn_mask.dtype != query.dtype:
+            raise ValueError(
+                f"Expected attn_mask dtype to be bool or to match query dtype, but got attn_mask.dtype: "
+                f"{attn_mask.dtype}, and query.dtype: {query.dtype} instead."
+            )
+
+
+def _check_batch_size_nested(params: SDPAParams, debug=False) -> bool:
+    # This is expected to be called after check_tensor_shapes ensuring that the
+    # size() calls won't error since the inputs are all 4 dimensional
+    q_batch_size = params.query.size(0)
+    k_batch_size = params.key.size(0)
+    v_batch_size = params.value.size(0)
+
+    # num_heads logic for nested input is checked in
+    # check_for_seq_len_0_nested_tensor as there is handling there to make sure
+    # num_heads is not ragged
+    return q_batch_size == k_batch_size and q_batch_size == v_batch_size
+
+
+def _check_head_dim_size_flash_nested(params: SDPAParams, debug=False) -> bool:
+    max_size = 256
+    query_size_last = params.query.size(-1)
+    key_size_last = params.key.size(-1)
+    value_size_last = params.value.size(-1)
+    same_head_dim_size = (
+        query_size_last == key_size_last and query_size_last == value_size_last
+    )
+    if not (
+        same_head_dim_size
+        and (query_size_last % 8 == 0)
+        and (query_size_last <= max_size)
+    ):
+        if debug:
+            log.warning(
+                "For NestedTensor inputs, Flash attention requires q,k,v to have the same "
+                "last dimension and to be a multiple of 8 and less than or equal to 256. "
+                "Got Query.size(-1): %d, Key.size(-1): %d, Value.size(-1): %d instead.",
+                query_size_last,
+                key_size_last,
+                value_size_last,
+            )
+        return False
+    return True
+
+
+def _check_head_dim_size_cudnn_nested(params: SDPAParams, debug=False) -> bool:
+    max_size = 128
+    query_size_last = params.query.size(-1)
+    key_size_last = params.key.size(-1)
+    value_size_last = params.value.size(-1)
+    same_head_dim_size = (
+        query_size_last == key_size_last and query_size_last == value_size_last
+    )
+    if not (
+        same_head_dim_size
+        and (query_size_last % 8 == 0)
+        and (query_size_last <= max_size)
+    ):
+        if debug:
+            log.warning(
+                "For NestedTensor inputs, cuDNN attention requires q,k,v to have the same "
+                "last dimension and to be a multiple of 8 and less than or equal to 128. "
+                "Got Query.size(-1): %d, Key.size(-1): %d, Value.size(-1): %d instead.",
+                query_size_last,
+                key_size_last,
+                value_size_last,
+            )
+        return False
+    return True
+
+
+def _check_for_seq_len_0_and_consistent_head_dim_nested_helper(
+    param: torch.Tensor, param_name: str, debug=False
+) -> bool:
+    assert isinstance(param, NestedTensor), "param should be a jagged NT"
+
+    if param._ragged_idx == 1:
+        # num_head_dims is ragged
+        if debug:
+            log.warning(
+                "Fused kernels do not support ragged num_head_dims, %s has a ragged num_heads.",
+                param_name,
+            )
+        return False
+
+    # This is being called inside sdp with shape [batch, heads, {seq_len}, dim]
+    if param._get_min_seqlen() == 0:
+        if debug:
+            log.warning(
+                "Fused kernels do not support seq_len == 0, %s has a seq len of 0.",
+                param_name,
+            )
+        return False
+
+    return True
+
+
+def _try_broadcast_param_size(q_size, k_size, v_size, param_name, debug=False) -> bool:
+    max_size = max(q_size, k_size, v_size)
+    if (
+        (q_size != max_size and q_size != 1)
+        or (k_size != max_size and k_size != 1)
+        or (v_size != max_size and v_size != 1)
+    ):
+        if debug:
+            log.warning(
+                "Both fused kernels require query, key and value to have broadcastable %s, "
+                "got Query %s %d, Key %s %d, Value %s %d instead.",
+                param_name,
+                param_name,
+                q_size,
+                param_name,
+                k_size,
+                param_name,
+                v_size,
+            )
+        return False
+    return True
+
+
+def _check_for_seq_len_0_nested(params: SDPAParams, debug=False) -> bool:
+    # When this function is called we are assured that the nt is dim==4
+    q_is_safe = (
+        _check_for_seq_len_0_and_consistent_head_dim_nested_helper(
+            params.query, "query", debug
+        )
+        if params.query.is_nested
+        else True
+    )
+    # short circuit if any is unsafe
+    if not q_is_safe:
+        return False
+
+    k_is_safe = (
+        _check_for_seq_len_0_and_consistent_head_dim_nested_helper(
+            params.key, "key", debug
+        )
+        if params.key.is_nested
+        else True
+    )
+    # short circuit if any is unsafe
+    if not k_is_safe:
+        return False
+
+    v_is_safe = (
+        _check_for_seq_len_0_and_consistent_head_dim_nested_helper(
+            params.value, "value", debug
+        )
+        if params.value.is_nested
+        else True
+    )
+    # short circuit if any is unsafe
+    if not v_is_safe:
+        return False
+
+    # We now know none of the inputs have ragged num_heads, so we can safely
+    # access .size(1)
+    q_num_heads = params.query.size(1)
+    k_num_heads = params.key.size(1)
+    v_num_heads = params.value.size(1)
+    same_num_heads = q_num_heads == k_num_heads and q_num_heads == v_num_heads
+
+    if not same_num_heads:
+        if (
+            params.query.requires_grad
+            or params.key.requires_grad
+            or params.value.requires_grad
+        ):
+            if debug:
+                log.warning(
+                    "Both fused kernels do not support training with broadcasted NT inputs."
+                )
+            return False
+        return _try_broadcast_param_size(
+            q_num_heads, k_num_heads, v_num_heads, "num heads", debug
+        )
+    return True
+
+
+def _can_use_flash_sdpa_jagged(params: SDPAParams, debug=False) -> bool:
+    constraints = (
+        _check_batch_size_nested,
+        _check_head_dim_size_flash_nested,
+        _check_for_seq_len_0_nested,
+    )
+    for constraint in constraints:
+        if not constraint(params, debug):
+            return False
+    return True
+
+
+def _can_use_efficient_sdpa_jagged(params: SDPAParams, debug=False) -> bool:
+    constraints = (
+        _check_batch_size_nested,
+        _check_for_seq_len_0_nested,
+    )
+    for constraint in constraints:
+        if not constraint(params, debug):
+            return False
+    return True
+
+
+def _can_use_math_sdpa_jagged(params: SDPAParams, debug=False) -> bool:
+    if (
+        not params.query.transpose(1, 2).is_contiguous()
+        or not params.key.transpose(1, 2).is_contiguous()
+        or not params.value.transpose(1, 2).is_contiguous()
+    ):
+        if debug:
+            log.warning(
+                "If inputs are nested tensors they must be contiguous after transposing."
+            )
+        return False
+    if params.is_causal:
+        if debug:
+            log.warning(
+                "Nested tensors for query / key are not supported when is_causal=True."
+            )
+        return False
+    return True
+
+
+def _select_sdp_backend(query, key, value, attn_mask, dropout, is_causal, enable_gqa):
+    if (
+        not flash_sdp_enabled()
+        and not mem_efficient_sdp_enabled()
+        and not math_sdp_enabled()
+        and not cudnn_sdp_enabled()
+    ):
+        return SDPBackend.ERROR
+
+    ordering = (
+        SDPBackend.FLASH_ATTENTION,
+        SDPBackend.EFFICIENT_ATTENTION,
+        SDPBackend.MATH,
+        SDPBackend.CUDNN_ATTENTION,
+    )
+
+    params = SDPAParams(query, key, value, attn_mask, dropout, is_causal, enable_gqa)
+
+    for backend in ordering:
+        if backend == SDPBackend.CUDNN_ATTENTION:
+            if can_use_cudnn_attention(params):
+                return SDPBackend.CUDNN_ATTENTION
+        if backend == SDPBackend.FLASH_ATTENTION:
+            if can_use_flash_attention(params) and _can_use_flash_sdpa_jagged(params):
+                return SDPBackend.FLASH_ATTENTION
+        if backend == SDPBackend.EFFICIENT_ATTENTION:
+            if can_use_efficient_attention(params) and _can_use_efficient_sdpa_jagged(
+                params
+            ):
+                return SDPBackend.EFFICIENT_ATTENTION
+        if backend == SDPBackend.MATH:
+            if math_sdp_enabled() and _can_use_math_sdpa_jagged(params):
+                return SDPBackend.MATH
+
+    log.warning("Memory efficient kernel not used because:")
+    can_use_efficient_attention(params, debug=True)
+    _can_use_efficient_sdpa_jagged(params, debug=True)
+    log.warning("Flash attention kernel not used because:")
+    can_use_flash_attention(params, debug=True)
+    _can_use_flash_sdpa_jagged(params, debug=True)
+    log.warning("Math attention kernel not used because:")
+    _can_use_math_sdpa_jagged(params, debug=True)
+    log.warning("cuDNN attention kernel not used because:")
+    can_use_cudnn_attention(params, debug=True)
+    return SDPBackend.ERROR
+
+
+def _cumulative_and_max_seq_len_nnz(qkv: torch.Tensor) -> tuple[torch.Tensor, int, int]:
+    # This function is used to calculate two pieces of metadata that are needed
+    # for use with flash-attention and efficient_attention kernels. They are the
+    # cumulative sequence_length over a batch of sequences and the maximum
+    # sequence length.
+
+    # It returns a tuple of cumulative sequence lengths and the maximum sequence
+    # length, and the last element in the cumulative_sequence_lengths
+    if not isinstance(qkv, NestedTensor):
+        raise ValueError("QKV must be nested for flash cumulative_seq_len calculation.")
+
+    if qkv.lengths() is None:
+        # TODO: Explore performance impact of copying
+        cumulative_seqlen = qkv.offsets().to(dtype=torch.int32, device=qkv.device)
+        max_seqlen = qkv._get_max_seqlen()
+        n_elem = qkv.values().shape[0]
+    else:
+        # TODO: Explore performance impact of copying
+        cumulative_seqlen = (
+            qkv.lengths().cumsum(0).to(dtype=torch.int32, device=qkv.device)
+        )
+        max_seqlen = qkv._get_max_seqlen()
+        # TODO: Explore performance impact when compiling
+        n_elem = int(cumulative_seqlen[-1].item())
+    return cumulative_seqlen, max_seqlen, n_elem
+
+
+def _is_safe_to_get_storage_as_tensor(tensor: torch.Tensor):
+    # This function checks if a nested tensor is valid for
+    # use with the flash-attention and efficient_attention kernels without
+    # needing to call contiguous on the nested tensor input.
+    # It checks that the storage offsets' adjacent_differences are a constant
+    # mutiple of the previous tensor in the nested tensor and that the strides
+    # are monitonically decreasing. This check is done after calling transpose on
+    # the nested tensor resulting in a Nt of shape [bsz, {seq_len}, num_heads, dim]
+
+    # Returns a boolean indicating if contiguous needs to be called for input
+    assert isinstance(tensor, NestedTensor)
+    offsets = tensor.offsets()
+    strides = tensor._strides
+
+    n_tensors = offsets.size(0) - 1
+    if n_tensors <= 1:
+        return True
+
+    # Check initially that the tensor strides are in strictly descending order
+    prev_stride = strides[1]
+    for stride in strides[2:]:
+        if prev_stride <= stride:
+            # This would mean that the last stride is greater than the seq_len
+            # stride
+            return False
+        prev_stride = stride
+
+    # Congrats you made it!
+    return True
+
+
+def _view_as_dense(
+    tensor: torch.Tensor, Nnz: int, num_heads: int, head_dim: int
+) -> torch.Tensor:
+    if tensor.is_nested:
+        return tensor.values()
+    return tensor.view(Nnz, num_heads, head_dim)
+
+
+# TODO: Next iteration should add test cases and check it works
+# def _sdpa_nested_preprocessing_with_broadcast(query, key, value):
+#     # Query (Batch x Num_heads x {Q_seq_len}  x Dim_per_head)
+#     # Key   (Batch x Num_heads x {KV_seq_len} x Dim_per_head)
+#     # Value (Batch x Num_heads x {KV_seq_len} x Dim_per_head)
+#     q_batch_size = query.size(0)
+#     k_batch_size = key.size(0)
+#     v_batch_size = value.size(0)
+
+#     output_batch_size = max(q_batch_size, k_batch_size, v_batch_size)
+
+#     q_num_heads = query.size(1)
+#     k_num_heads = key.size(1)
+#     v_num_heads = value.size(1)
+
+#     output_num_heads = max(q_num_heads, k_num_heads, v_num_heads)
+
+#     head_dim_qk = query.size(3)
+#     head_dim_v = value.size(3)
+
+#     q_t = query.transpose(1, 2)
+#     k_t = key.transpose(1, 2)
+#     v_t = value.transpose(1, 2)
+
+#     # Checks in sdp_utils ensure that if {*}_batch_size/{*}_num_heads !=
+#     # output_batch_size/num_heads then they are 1
+#     q_batch_size_needs_broadcast = q_batch_size != output_batch_size
+#     k_batch_size_needs_broadcast = k_batch_size != output_batch_size
+#     v_batch_size_needs_broadcast = v_batch_size != output_batch_size
+
+#     # If {*}_batch_size_needs_broadcast, then
+#     # (1) max_seqlen_batch_{*} is given by {*}_t.size(1)
+#     #     this is because needs_broadcast indicates that the batch_size is 1
+#     #     and hence there is only 1 value for seq_len
+#     # (2) The cum_seq_lens are given by [0, {*}_t.size(1), 2 * {*}_t.size(1),
+#     # ..., outut_batch_size * {*}_t.size(1)]
+#     # (3) Nnz_{*} is given by output_batch_size * {*}_t.size(1)
+
+#     if q_batch_size_needs_broadcast or not q_t.is_nested:
+#         max_seqlen_batch_q = q_t.size(1)
+#         cumulative_sequence_length_q = torch.arange(
+#             0,
+#             (output_batch_size + 1) * max_seqlen_batch_q,
+#             max_seqlen_batch_q,
+#             device=q_t.device,
+#             dtype=torch.int32,
+#         )
+#         Nnz_q = output_batch_size * max_seqlen_batch_q
+#     else:
+#         (
+#             cumulative_sequence_length_q,
+#             max_seqlen_batch_q,
+#             Nnz_q,
+#         ) = _cumulative_and_max_seq_len_nnz(q_t)
+
+#     if k_batch_size_needs_broadcast and v_batch_size_needs_broadcast:
+#         assert k_t.size(1) == v_t.size(1)
+#         max_seqlen_batch_kv = k_t.size(1)
+#         cumulative_sequence_length_kv = torch.arange(
+#             0,
+#             (output_batch_size + 1) * max_seqlen_batch_kv,
+#             max_seqlen_batch_kv,
+#             device=k_t.device,
+#             dtype=torch.int32,
+#         )
+#         Nnz_kv = output_batch_size * max_seqlen_batch_kv
+#     else:
+#         cumulative_sequence_length_kv, max_seqlen_batch_kv, Nnz_kv = (
+#             _cumulative_and_max_seq_len_nnz(v_t)
+#             if k_batch_size_needs_broadcast
+#             else _cumulative_and_max_seq_len_nnz(k_t)
+#         )
+
+#     q_num_heads_needs_broadcast = q_num_heads != output_num_heads
+#     k_num_heads_needs_broadcast = k_num_heads != output_num_heads
+#     v_num_heads_needs_broadcast = v_num_heads != output_num_heads
+
+#     if not q_t.is_nested:
+#         query_buffer_reshaped = q_t.expand(
+#             output_batch_size, q_t.size(1), output_num_heads, head_dim_qk
+#         )
+#         query_buffer_reshaped = query_buffer_reshaped.reshape(
+#             Nnz_q, output_num_heads, head_dim_qk
+#         )
+#     else:
+#         if not q_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(q_t):
+#             q_t = q_t.contiguous()
+#         # If we are broadcasting then Nnz_q will be the output_batch_size since
+#         # seq_len is 1
+#         effective_batch_size_q = (
+#             output_batch_size if q_batch_size_needs_broadcast else Nnz_q
+#         )
+#         query_buffer_reshaped = _view_as_dense(
+#             q_t, effective_batch_size_q, output_num_heads, head_dim_qk
+#         )
+
+#     # If the physical layout of the NestedTensor's storage
+#     # is not: batch, {seq_len}, num_heads, head_dim then we need
+#     # to call contiguous
+#     if not k_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(k_t):
+#         k_t = k_t.contiguous()
+#     if not v_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(v_t):
+#         v_t = v_t.contiguous()
+
+#     effective_batch_size_k = (
+#         output_batch_size if k_batch_size_needs_broadcast else Nnz_kv
+#     )
+#     key_buffer_reshaped = _view_as_dense(
+#         k_t, effective_batch_size_k, output_num_heads, head_dim_qk
+#     )
+
+#     effective_batch_size_v = (
+#         output_batch_size if v_batch_size_needs_broadcast else Nnz_kv
+#     )
+#     value_buffer_reshaped = _view_as_dense(
+#         v_t, effective_batch_size_v, output_num_heads, head_dim_v
+#     )
+
+#     if not q_batch_size_needs_broadcast:
+#         output_shape = q_t._size
+#         if head_dim_v != head_dim_qk:
+#             output_shape[-1] = head_dim_v
+#         if q_num_heads_needs_broadcast:
+#             output_shape[1] = output_num_heads
+#     else:
+#         output_shape = torch.empty(3, dtype=torch.int64, device=torch.device("cpu"))
+#         output_shape[0] = q_t.size(1)
+#         output_shape[1] = output_num_heads
+#         output_shape[2] = head_dim_v
+
+#     return (
+#         query_buffer_reshaped,
+#         key_buffer_reshaped,
+#         value_buffer_reshaped,
+#         cumulative_sequence_length_q,
+#         cumulative_sequence_length_kv,
+#         max_seqlen_batch_q,
+#         max_seqlen_batch_kv,
+#         output_shape,
+#     )
+
+
+def _sdpa_nested_preprocessing(query, key, value):
+    # Query (Batch x Num_heads x {Q_seq_len}  x Dim_per_head)
+    # Key   (Batch x Num_heads x {KV_seq_len} x Dim_per_head)
+    # Value (Batch x Num_heads x {KV_seq_len} x Dim_per_head)
+    q_batch_size = query.size(0)
+    k_batch_size = key.size(0)
+    v_batch_size = value.size(0)
+
+    q_num_heads = query.size(1)
+    k_num_heads = key.size(1)
+    v_num_heads = value.size(1)
+
+    if not (q_batch_size == k_batch_size and q_batch_size == v_batch_size) or not (
+        q_num_heads == k_num_heads and k_num_heads == v_num_heads
+    ):
+        raise RuntimeError(
+            "This path is currently not implemented for jagged layout NT."
+        )
+        # return _sdpa_nested_preprocessing_with_broadcast(query, key, value)
+
+    num_heads = query.size(1)
+    head_dim_qk = query.size(3)
+    head_dim_v = value.size(3)
+    q_t = query.transpose(1, 2)
+    k_t = key.transpose(1, 2)
+    v_t = value.transpose(1, 2)
+
+    (
+        cumulative_sequence_length_q,
+        max_seqlen_batch_q,
+        Nnz_q,
+    ) = _cumulative_and_max_seq_len_nnz(q_t)
+    (
+        cumulative_sequence_length_kv,
+        max_seqlen_batch_kv,
+        Nnz_kv,
+    ) = _cumulative_and_max_seq_len_nnz(k_t)
+
+    # [TODO] K and V have to have the same Nnz, should probably torch_check
+    # assume in order to not iterate over v
+
+    # If the physical layout of the NestedTensor's storage
+    # is not: batch, {seq_len}, num_heads, head_dim then we need
+    # to call contiguous
+    if not q_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(q_t):
+        q_t = q_t.contiguous()
+    if not k_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(k_t):
+        k_t = k_t.contiguous()
+    if not v_t.is_contiguous() and not _is_safe_to_get_storage_as_tensor(v_t):
+        v_t = v_t.contiguous()
+
+    query_buffer_reshaped = _view_as_dense(q_t, Nnz_q, num_heads, head_dim_qk)
+    key_buffer_reshaped = _view_as_dense(k_t, Nnz_kv, num_heads, head_dim_qk)
+    value_buffer_reshaped = _view_as_dense(v_t, Nnz_kv, num_heads, head_dim_v)
+
+    output_nt_info = {
+        "offsets": q_t.offsets(),
+        "lengths": q_t.lengths(),
+        "max_seqlen": q_t._get_max_seqlen(),
+        "min_seqlen": q_t._get_min_seqlen(),
+    }
+
+    return (
+        query_buffer_reshaped,
+        key_buffer_reshaped,
+        value_buffer_reshaped,
+        cumulative_sequence_length_q,
+        cumulative_sequence_length_kv,
+        max_seqlen_batch_q,
+        max_seqlen_batch_kv,
+        output_nt_info,
+    )
+
+
+def _pad_last_dim(
+    tensor: torch.Tensor, alignment_size: int, slice: bool
+) -> torch.Tensor:
+    # FlashAttentionV2 requires that head dimension be a multiple of 8
+    # This was previously done within the kernel, however
+    # This causes the kernel to maybe alias query, key, value
+    # So instead we pad the head_dimensions to be a multiple of 8
+    # in the composite region
+    last_dim_size = tensor.size(-1)
+    if last_dim_size % alignment_size == 0:
+        return tensor
+    pad_count = alignment_size - (last_dim_size % alignment_size)
+    tensor = torch.nn.functional.pad(tensor, [0, pad_count])
+    if slice:
+        return tensor[..., 0:last_dim_size]
+    return tensor
+
+
+# TODO: coalesce with torch/nn/utils/attention.py
+def _calculate_scale(query, scale):
+    # TODO: Investigate why math.sqrt() isn't properly handled by Dynamo?
+    softmax_scale = scale if scale is not None else torch.sym_sqrt(1.0 / query.size(-1))
+    return softmax_scale
+
+
+def _post_process_flash_output(out: torch.Tensor, og_size):
+    if not out.is_nested and out.size(-1) != og_size:
+        out = out[..., 0:og_size]
+    return out
+
+
+def _is_computing_meta_flops(x):
+    # Note: there's a use case of using meta tensors & the dispatch-based flop counter.
+    # We can use this function to check for this scenario in order to handle it specially.
+    if not torch.jit.is_scripting() and x.device.type == "meta":
+        torch_dispatch_mode_stack = (
+            torch.utils._python_dispatch._get_current_dispatch_mode_stack()
+        )
+        return any(
+            type(x) == torch.utils.flop_counter._FlopCounterMode
+            for x in torch_dispatch_mode_stack
+        )
+    return False
+
+
+def _autocast(
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    attn_mask: Optional[torch.Tensor],
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+    """
+    [Autocasting SDPA for NJT]
+
+    Normal autocasting doesn't work for NJT+SDPA right now:
+    * NJT intercepts the __torch_function__ call for scaled_dot_product_attention, which happens
+      before we get to any aten ops or dispatcher logic; then the torch_function logic calls into
+      efficient attention or flash attention. So, autocasting on the scaled_dot_product_attention
+      op won't work because we never see that aten op.
+    * If we put autocasting on `_flash_attention_forward`, then we'll get autocasting to run, but
+      the kernel selection logic in torch_function handling (ie. jagged_scaled_dot_product_attention)
+      won't work correctly: the kernel selection logic will run before autocasting, and choose
+      a kernel based on the un-autocasted dtypes; but then autocasting will run and the actual
+      attention computation will happen in a different dtype.
+
+    An alternative is to just change the backend selection logic for SDPA+NJT to be autocast-aware
+    and rely on autocasting to do the actual conversions for flash attention / efficient attention.
+    However, by manually doing the actual autocast before the backend selection, we ensure that the
+    autocast handling for backend selection doesn't diverge from the autocast handling for the
+    actual dtype conversions.
+    """
+    device_type = query.device.type
+    # meta device is not supported by autocast, so break early for it
+    if _is_computing_meta_flops(query) or not torch.is_autocast_enabled(device_type):
+        return query, key, value, attn_mask
+
+    def cvt(x):
+        if x is None:
+            return x
+        target_dtype = torch.get_autocast_dtype(device_type)
+        if (
+            (not x.dtype.is_floating_point)
+            or x.dtype == target_dtype
+            or x.dtype == torch.float64
+        ):
+            return x
+        return x.to(target_dtype)
+
+    return cvt(query), cvt(key), cvt(value), cvt(attn_mask)
+
+
+def jagged_scaled_dot_product_attention(
+    query: torch.Tensor,
+    key: torch.Tensor,
+    value: torch.Tensor,
+    attn_mask: Optional[torch.Tensor] = None,
+    dropout_p=0.0,
+    is_causal=False,
+    scale=None,
+    enable_gqa=False,
+):
+    query, key, value, attn_mask = _autocast(query, key, value, attn_mask)
+    _validate_sdpa_input(query, key, value, attn_mask, dropout_p, is_causal, scale)
+    # for mypy, ugh
+    assert (
+        isinstance(query, NestedTensor)
+        and isinstance(key, NestedTensor)
+        and isinstance(value, NestedTensor)
+    )
+    from torch.nested._internal.nested_tensor import (
+        nested_view_from_values_offsets_lengths,
+    )
+
+    # Special path for non-ragged sequence length (e.g. for SAM where we have a ragged
+    # second batch dim instead). For this case, we can just send the dense buffers through
+    # vanilla SDPA.
+    if query.dim() > 3 and key.dim() > 3 and value.dim() > 3 and query._ragged_idx == 1:
+        output = F.scaled_dot_product_attention(
+            query.values(),
+            key.values(),
+            value.values(),
+            attn_mask=(
+                attn_mask.values() if isinstance(attn_mask, NestedTensor) else attn_mask
+            ),
+            dropout_p=dropout_p,
+            is_causal=is_causal,
+            scale=scale,
+        )
+        return nested_view_from_values_offsets_lengths(
+            output,
+            query.offsets(),
+            query.lengths(),
+            min_seqlen=query._maybe_min_seqlen,  # type: ignore[attr-defined]
+            max_seqlen=query._maybe_max_seqlen,  # type: ignore[attr-defined]
+        )
+
+    compute_logsumexp = query.requires_grad or key.requires_grad or value.requires_grad
+
+    backend_choice = _select_sdp_backend(
+        query, key, value, attn_mask, dropout_p, is_causal, enable_gqa
+    )
+
+    if _is_computing_meta_flops(query):
+        # Backend choice will probably not be correct if we have a meta device,
+        # because backend choice is device-aware. In this case, we mostly just
+        # want to avoid using math backend (which does a .item() call).
+        # Arbitrarily choose flash attention.
+        backend_choice = SDPBackend.FLASH_ATTENTION
+
+    if backend_choice == SDPBackend.FLASH_ATTENTION:
+        og_size = query.size(-1)
+        query_padded = _pad_last_dim(query, 8, False)
+        key_padded = _pad_last_dim(key, 8, False)
+        value_padded = _pad_last_dim(value, 8, False)
+        # We need to calculate the scale based off the OG head dim size
+        og_scale = _calculate_scale(query, scale)
+        (
+            query_buffer_reshaped,
+            key_buffer_reshaped,
+            value_buffer_reshaped,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            output_nt_info,
+        ) = _sdpa_nested_preprocessing(query_padded, key_padded, value_padded)
+        (
+            attention,
+            _logsumexp,
+            _philox_seed,
+            _philox_offset,
+            _debug_attn_mask,
+        ) = torch.ops.aten._flash_attention_forward(
+            query_buffer_reshaped,
+            key_buffer_reshaped,
+            value_buffer_reshaped,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            dropout_p,
+            is_causal,
+            False,
+            scale=og_scale,
+        )
+        # Reshape output to convert nnz to batch_size and seq_len
+        attention = nested_view_from_values_offsets_lengths(
+            attention,  # output from flash_attn is [total_q, num_heads, head_size_og]
+            **output_nt_info,
+        ).transpose(1, 2)
+        return _post_process_flash_output(attention, og_size)
+    elif backend_choice == SDPBackend.EFFICIENT_ATTENTION:
+        (
+            query_reshaped,
+            key_reshaped,
+            value_reshaped,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            output_nt_info,
+        ) = _sdpa_nested_preprocessing(query, key, value)
+        (
+            attention,
+            log_sumexp,
+            seed,
+            offset,
+            max_seqlen_q,
+            max_seqlen_batch_kv,
+        ) = torch.ops.aten._efficient_attention_forward(
+            query_reshaped.unsqueeze(0),
+            key_reshaped.unsqueeze(0),
+            value_reshaped.unsqueeze(0),
+            None,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            dropout_p,
+            int(is_causal),
+            compute_logsumexp,
+            scale=scale,
+        )
+        # Reshape output to convert nnz to batch_size and seq_len
+        return nested_view_from_values_offsets_lengths(
+            attention.squeeze(0),
+            **output_nt_info,
+        ).transpose(1, 2)
+    elif backend_choice == SDPBackend.CUDNN_ATTENTION:
+        (
+            query_reshaped,
+            key_reshaped,
+            value_reshaped,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            output_nt_info,
+        ) = _sdpa_nested_preprocessing(query, key, value)
+        (
+            attention,
+            logsumexp,
+            cum_seqlen_q,
+            cum_seqlen_kv,
+            max_seqlen_q,
+            max_seqlen_kv,
+            seed,
+            offset,
+            _,
+        ) = torch.ops.aten._cudnn_attention_forward(
+            query_reshaped,
+            key_reshaped,
+            value_reshaped,
+            attn_mask,
+            cumulative_sequence_length_q,
+            cumulative_sequence_length_kv,
+            max_seqlen_batch_q,
+            max_seqlen_batch_kv,
+            compute_logsumexp,
+            dropout_p,
+            is_causal,
+            False,
+            scale=scale,
+        )
+        return nested_view_from_values_offsets_lengths(
+            attention,
+            **output_nt_info,
+        ).transpose(1, 2)
+    elif backend_choice == SDPBackend.MATH:
+        # save the offsets and shape of the inputs, so we can reshape the final output
+        # query @ key = attn: [B, D1, j0, D'] @ [B, D1, D' j1] = [B, D1, j0, j1]
+        # attn @ value = out: [B, D1, j0, j1] @ [B, D1, j1, D2] = [B, D1, j0, D2]
+        offsets = query.offsets()
+        q_lengths = query.lengths()
+        min_seqlen = query._maybe_min_seqlen
+        max_seqlen = query._maybe_max_seqlen
+        d1 = query._size[1]
+        d2 = value._size[-1]
+
+        # convert jagged layout Nested Tensor to strided layout Nested Tensor
+        # which support the math implementation of SDPA
+        def get_strided_layout_nested_tensor(jagged_layout_nt):
+            lengths = jagged_layout_nt._offsets[1:] - jagged_layout_nt._offsets[:-1]
+            transpose = torch.transpose(jagged_layout_nt, 1, 2)
+            tensor_list = transpose.values().split(list(lengths), dim=0)
+            strided_nt = torch.nested.as_nested_tensor(list(tensor_list))
+            strided_nt = strided_nt.transpose(1, 2).contiguous()
+            return strided_nt
+
+        query = get_strided_layout_nested_tensor(query)
+        key = get_strided_layout_nested_tensor(key)
+        value = get_strided_layout_nested_tensor(value)
+
+        attn_out = torch._scaled_dot_product_attention_math(
+            query, key, value, attn_mask, dropout_p, is_causal, scale=scale
+        )[0]
+
+        # convert strided layout Nested Tensor back to jagged layout Nested Tensor
+        attn_out = attn_out.transpose(1, 2).contiguous().values()
+        attn_out = attn_out.view(-1, d1, d2)
+        attn_out = nested_view_from_values_offsets_lengths(
+            attn_out,
+            offsets,
+            lengths=q_lengths,
+            min_seqlen=min_seqlen,
+            max_seqlen=max_seqlen,
+        ).transpose(1, 2)
+
+        return attn_out
+    else:
+        raise RuntimeError(
+            "No viable backend for scaled_dot_product_attention was found."
+        )
diff --git a/shared/package-files/e6/e658d358854b9b1800df4bf2c67955f3fb944e437d729f94ecfc36ec5c6587e2/miopen_rnn_backward_native.h b/shared/package-files/e6/e658d358854b9b1800df4bf2c67955f3fb944e437d729f94ecfc36ec5c6587e2/miopen_rnn_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..060c6e5e8a7705505b9e7ec8f87dd05009aedbde
--- /dev/null
+++ b/shared/package-files/e6/e658d358854b9b1800df4bf2c67955f3fb944e437d729f94ecfc36ec5c6587e2/miopen_rnn_backward_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API void miopen_rnn_backward_out(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const ::std::optional & cx, const at::Tensor & output, const ::std::optional & grad_output, const ::std::optional & grad_hy, const ::std::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3);
+TORCH_API ::std::tuple> miopen_rnn_backward(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const ::std::optional & cx, const at::Tensor & output, const ::std::optional & grad_output, const ::std::optional & grad_hy, const ::std::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e659da3585d7cbb3c5b19fdc9e9200fb040bc42ae2b1e030deff322d4141a5b9/utils.cpython-311.pyc b/shared/package-files/e6/e659da3585d7cbb3c5b19fdc9e9200fb040bc42ae2b1e030deff322d4141a5b9/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a614dd3802bf845050e38545fc192aa06cfc48e
Binary files /dev/null and b/shared/package-files/e6/e659da3585d7cbb3c5b19fdc9e9200fb040bc42ae2b1e030deff322d4141a5b9/utils.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e65d3d492c657f618a4a71856f34454f8ee801f6e1f12a9472bb7fb73dfd594d/python_util.h b/shared/package-files/e6/e65d3d492c657f618a4a71856f34454f8ee801f6e1f12a9472bb7fb73dfd594d/python_util.h
new file mode 100644
index 0000000000000000000000000000000000000000..6399b224dbffbed1490ece21837c40647b4c7936
--- /dev/null
+++ b/shared/package-files/e6/e65d3d492c657f618a4a71856f34454f8ee801f6e1f12a9472bb7fb73dfd594d/python_util.h
@@ -0,0 +1,13 @@
+#pragma once
+#include 
+#include 
+#include 
+#include 
+
+namespace torch::lazy {
+
+std::optional TORCH_PYTHON_API GetPythonFrameTop();
+
+std::vector TORCH_PYTHON_API GetPythonFrames();
+
+} // namespace torch::lazy
diff --git a/shared/package-files/e6/e65ff6f3e49da0ed2beabfa756a917b1f4911564cb4cf80e144a57cd98aa87a5/extension_type.h b/shared/package-files/e6/e65ff6f3e49da0ed2beabfa756a917b1f4911564cb4cf80e144a57cd98aa87a5/extension_type.h
new file mode 100644
index 0000000000000000000000000000000000000000..a4526e31c2b93edce10a60bc9260627b614f4e9e
--- /dev/null
+++ b/shared/package-files/e6/e65ff6f3e49da0ed2beabfa756a917b1f4911564cb4cf80e144a57cd98aa87a5/extension_type.h
@@ -0,0 +1,230 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include 
+#include 
+#include 
+
+#include "arrow/extension_type.h"
+#include "arrow/testing/visibility.h"
+#include "arrow/util/macros.h"
+
+namespace arrow {
+
+class ARROW_TESTING_EXPORT ExampleUuidArray : public ExtensionArray {
+ public:
+  using ExtensionArray::ExtensionArray;
+};
+
+class ARROW_TESTING_EXPORT ExampleUuidType : public ExtensionType {
+ public:
+  ExampleUuidType() : ExtensionType(fixed_size_binary(16)) {}
+
+  std::string extension_name() const override { return "uuid"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "uuid-serialized"; }
+};
+
+class ARROW_TESTING_EXPORT SmallintArray : public ExtensionArray {
+ public:
+  using ExtensionArray::ExtensionArray;
+};
+
+class ARROW_TESTING_EXPORT TinyintArray : public ExtensionArray {
+ public:
+  using ExtensionArray::ExtensionArray;
+};
+
+class ARROW_TESTING_EXPORT ListExtensionArray : public ExtensionArray {
+ public:
+  using ExtensionArray::ExtensionArray;
+};
+
+class ARROW_TESTING_EXPORT SmallintType : public ExtensionType {
+ public:
+  SmallintType() : ExtensionType(int16()) {}
+
+  std::string extension_name() const override { return "smallint"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "smallint"; }
+};
+
+class ARROW_TESTING_EXPORT TinyintType : public ExtensionType {
+ public:
+  TinyintType() : ExtensionType(int8()) {}
+
+  std::string extension_name() const override { return "tinyint"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "tinyint"; }
+};
+
+class ARROW_TESTING_EXPORT ListExtensionType : public ExtensionType {
+ public:
+  ListExtensionType() : ExtensionType(list(int32())) {}
+
+  std::string extension_name() const override { return "list-ext"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "list-ext"; }
+};
+
+class ARROW_TESTING_EXPORT DictExtensionType : public ExtensionType {
+ public:
+  DictExtensionType() : ExtensionType(dictionary(int8(), utf8())) {}
+
+  std::string extension_name() const override { return "dict-extension"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "dict-extension-serialized"; }
+};
+
+// A minimal extension type that does not error when passed blank extension information
+class ARROW_TESTING_EXPORT MetadataOptionalExtensionType : public ExtensionType {
+ public:
+  MetadataOptionalExtensionType() : ExtensionType(null()) {}
+  std::string extension_name() const override { return "metadata.optional"; }
+  std::string Serialize() const override { return ""; }
+  std::shared_ptr MakeArray(std::shared_ptr data) const override {
+    return nullptr;
+  }
+  bool ExtensionEquals(const ExtensionType& other) const override {
+    return other.extension_name() == extension_name();
+  }
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized_data) const override {
+    return std::make_shared();
+  }
+};
+
+class ARROW_TESTING_EXPORT Complex128Array : public ExtensionArray {
+ public:
+  using ExtensionArray::ExtensionArray;
+};
+
+class ARROW_TESTING_EXPORT Complex128Type : public ExtensionType {
+ public:
+  Complex128Type()
+      : ExtensionType(struct_({::arrow::field("real", float64(), /*nullable=*/false),
+                               ::arrow::field("imag", float64(), /*nullable=*/false)})) {}
+
+  std::string extension_name() const override { return "complex128"; }
+
+  bool ExtensionEquals(const ExtensionType& other) const override;
+
+  std::shared_ptr MakeArray(std::shared_ptr data) const override;
+
+  Result> Deserialize(
+      std::shared_ptr storage_type,
+      const std::string& serialized) const override;
+
+  std::string Serialize() const override { return "complex128-serialized"; }
+};
+
+ARROW_TESTING_EXPORT
+std::shared_ptr uuid();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr smallint();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr tinyint();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr list_extension_type();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr dict_extension_type();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr complex128();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr ExampleUuid();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr ExampleSmallint();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr ExampleTinyint();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr ExampleDictExtension();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr ExampleComplex128();
+
+ARROW_TESTING_EXPORT
+std::shared_ptr MakeComplex128(const std::shared_ptr& real,
+                                      const std::shared_ptr& imag);
+
+// A RAII class that registers an extension type on construction
+// and unregisters it on destruction.
+class ARROW_TESTING_EXPORT ExtensionTypeGuard {
+ public:
+  explicit ExtensionTypeGuard(const std::shared_ptr& type);
+  explicit ExtensionTypeGuard(const DataTypeVector& types);
+  ~ExtensionTypeGuard();
+  ARROW_DEFAULT_MOVE_AND_ASSIGN(ExtensionTypeGuard);
+
+ protected:
+  ARROW_DISALLOW_COPY_AND_ASSIGN(ExtensionTypeGuard);
+
+  std::vector extension_names_;
+};
+
+}  // namespace arrow
diff --git a/shared/package-files/e6/e6600790b220833912c80b5a894b1bca869ab129025e8253f1c398a0751f29e7/test_is_full.cpython-311.pyc b/shared/package-files/e6/e6600790b220833912c80b5a894b1bca869ab129025e8253f1c398a0751f29e7/test_is_full.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4e3fdef6172ecb115409917b5a3d1011c7573fb
Binary files /dev/null and b/shared/package-files/e6/e6600790b220833912c80b5a894b1bca869ab129025e8253f1c398a0751f29e7/test_is_full.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e66021a3c167613414f08cb381cc23061e711fcebb05b0235e2239dbe657d1fc/PythonTorchFunctionTLS.h b/shared/package-files/e6/e66021a3c167613414f08cb381cc23061e711fcebb05b0235e2239dbe657d1fc/PythonTorchFunctionTLS.h
new file mode 100644
index 0000000000000000000000000000000000000000..a245a55ebdc4852542abedd3f730c08e9a5381eb
--- /dev/null
+++ b/shared/package-files/e6/e66021a3c167613414f08cb381cc23061e711fcebb05b0235e2239dbe657d1fc/PythonTorchFunctionTLS.h
@@ -0,0 +1,36 @@
+#pragma once
+
+#include 
+#include 
+
+namespace at::impl {
+
+enum TorchFunctionDisabledState { ENABLED, SUBCLASSES_DISABLED, ALL_DISABLED };
+
+struct TORCH_API PythonTorchFunctionTLS {
+  static void set_disabled_state(TorchFunctionDisabledState disabled_state_);
+  static TorchFunctionDisabledState get_disabled_state();
+
+  static void push_onto_stack(std::shared_ptr mode);
+  static const std::shared_ptr pop_stack();
+  static const std::shared_ptr& get_stack_at(int64_t idx);
+  static int64_t stack_len();
+
+  static const PythonTorchFunctionTLS& get_state();
+  static void set_state(const PythonTorchFunctionTLS& state);
+
+ private:
+  // The mode TLS is split into
+  //   - disabled_state, which says which part of torch function are disabled
+  //   - stack_, which is a vector of modes representing the stack of user
+  //   defined modes
+  TorchFunctionDisabledState disabled_state_ =
+      TorchFunctionDisabledState::ENABLED;
+  std::vector> stack_;
+};
+
+TORCH_API bool torch_function_mode_enabled();
+
+TORCH_API bool torch_function_all_disabled();
+
+} // namespace at::impl
diff --git a/shared/package-files/e6/e66065b56e5a0249649a96d4108710e64188191702cc5e1775e0bcc49cc57099/sparse_resize_and_clear_ops.h b/shared/package-files/e6/e66065b56e5a0249649a96d4108710e64188191702cc5e1775e0bcc49cc57099/sparse_resize_and_clear_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f4ea8c0f2d7186a3dbb1dedf9448d239ca95c74
--- /dev/null
+++ b/shared/package-files/e6/e66065b56e5a0249649a96d4108710e64188191702cc5e1775e0bcc49cc57099/sparse_resize_and_clear_ops.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API sparse_resize_and_clear_ {
+  using schema = const at::Tensor & (const at::Tensor &, at::IntArrayRef, int64_t, int64_t);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sparse_resize_and_clear_";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)";
+  static const at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
+  static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
+};
+
+struct TORCH_API sparse_resize_and_clear_out {
+  using schema = const at::Tensor & (const at::Tensor &, at::IntArrayRef, int64_t, int64_t, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sparse_resize_and_clear";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "sparse_resize_and_clear.out(Tensor self, int[] size, int sparse_dim, int dense_dim, *, Tensor(a!) out) -> Tensor(a!)";
+  static const at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim, const at::Tensor & out);
+  static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim, const at::Tensor & out);
+};
+
+struct TORCH_API sparse_resize_and_clear {
+  using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, int64_t, int64_t);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::sparse_resize_and_clear";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "sparse_resize_and_clear(Tensor self, int[] size, int sparse_dim, int dense_dim) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e662a5896a7167a78d266501bd6ca634afba09bab3575eda0fafd13850ccd912/libcfaidx.pxd b/shared/package-files/e6/e662a5896a7167a78d266501bd6ca634afba09bab3575eda0fafd13850ccd912/libcfaidx.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c17d0ba0f568c77798538cc2fbb3e224cb7d6422
--- /dev/null
+++ b/shared/package-files/e6/e662a5896a7167a78d266501bd6ca634afba09bab3575eda0fafd13850ccd912/libcfaidx.pxd
@@ -0,0 +1,81 @@
+# cython: language_level=3
+from libc.stdint cimport int8_t, int16_t, int32_t, int64_t
+from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
+from libc.stdlib cimport malloc, calloc, realloc, free
+from libc.string cimport memcpy, memcmp, strncpy, strlen, strdup
+from libc.stdio cimport FILE, printf
+cimport cython
+
+from cpython cimport array
+from pysam.libchtslib cimport faidx_t, kstring_t, BGZF
+
+# These functions are put here and not in chtslib.pxd in order
+# to avoid warnings for unused functions.
+cdef extern from "pysam_stream.h" nogil:
+
+    ctypedef struct kstream_t:
+        pass
+
+    ctypedef struct kseq_t:
+        kstring_t name
+        kstring_t comment
+        kstring_t seq
+        kstring_t qual
+
+    kseq_t *kseq_init(BGZF *)
+    int kseq_read(kseq_t *)
+    void kseq_destroy(kseq_t *)
+    kstream_t *ks_init(BGZF *)
+    void ks_destroy(kstream_t *)
+
+    # Retrieve characters from stream until delimiter
+    # is reached placing results in str.
+    int ks_getuntil(kstream_t *,
+                    int delimiter,
+                    kstring_t * str,
+                    int * dret)
+
+cdef class FastaFile:
+    cdef bint is_remote
+    cdef object _filename, _references, _lengths, reference2length
+    cdef faidx_t* fastafile
+    cdef char* _fetch(self, char* reference,
+                      int start, int end, int* length) except? NULL
+
+
+cdef class FastqProxy:
+    cdef kseq_t * _delegate
+    cdef cython.str to_string(self)
+    cdef cython.str tostring(self)
+    cpdef array.array get_quality_array(self, int offset=*)
+
+
+cdef class FastxRecord:
+    """
+    Python container for pysam.libcfaidx.FastqProxy with persistence.
+    """
+    cdef public str comment, quality, sequence, name
+    cdef cython.str to_string(self)
+    cdef cython.str tostring(self)
+    cpdef array.array get_quality_array(self, int offset=*)
+
+cdef class FastxFile:
+    cdef object _filename
+    cdef BGZF * fastqfile
+    cdef kseq_t * entry
+    cdef bint persist
+    cdef bint is_remote
+
+    cdef kseq_t * getCurrent(self)
+    cdef int cnext(self)
+
+
+# Compatibility Layer for pysam 0.8.1
+cdef class FastqFile(FastxFile):
+    pass
+
+
+# Compatibility Layer for pysam < 0.8
+cdef class Fastafile(FastaFile):
+    pass
+
diff --git a/shared/package-files/e6/e6646dcdb11c3f700a3f31ea1b89286edb5c95fdb856e7e649345f80885e3fe9/linalg_lu_factor_ex_meta.h b/shared/package-files/e6/e6646dcdb11c3f700a3f31ea1b89286edb5c95fdb856e7e649345f80885e3fe9/linalg_lu_factor_ex_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..b809d9589f00ac30d69edad98ad129fcad1d53c7
--- /dev/null
+++ b/shared/package-files/e6/e6646dcdb11c3f700a3f31ea1b89286edb5c95fdb856e7e649345f80885e3fe9/linalg_lu_factor_ex_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_linalg_lu_factor_ex : public at::impl::MetaBase {
+    
+    
+    void meta(const at::Tensor & A, bool pivot, bool check_errors);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e666e5c108259bd02015ac1a65b4e332d03a50e04f11b7cdfad5806a38383135/_linalg_eigvals.h b/shared/package-files/e6/e666e5c108259bd02015ac1a65b4e332d03a50e04f11b7cdfad5806a38383135/_linalg_eigvals.h
new file mode 100644
index 0000000000000000000000000000000000000000..60b3a7b952f2a605a3683abc650602dc525dacf4
--- /dev/null
+++ b/shared/package-files/e6/e666e5c108259bd02015ac1a65b4e332d03a50e04f11b7cdfad5806a38383135/_linalg_eigvals.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::_linalg_eigvals(Tensor self) -> Tensor
+inline at::Tensor _linalg_eigvals(const at::Tensor & self) {
+    return at::_ops::_linalg_eigvals::call(self);
+}
+
+}
diff --git a/shared/package-files/e6/e667e7efd9a8ac1ca947411a3aa4d78bd0300afe781a48e5e658debf4affdb65/parser.cpython-311.pyc b/shared/package-files/e6/e667e7efd9a8ac1ca947411a3aa4d78bd0300afe781a48e5e658debf4affdb65/parser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..385c74ea4ded3b69fcb999b3299c98fba61d7487
Binary files /dev/null and b/shared/package-files/e6/e667e7efd9a8ac1ca947411a3aa4d78bd0300afe781a48e5e658debf4affdb65/parser.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e66bb5beded435694b6974a40163690123a1de2d4d41226cacc30d7485536ccd/_log_softmax_meta.h b/shared/package-files/e6/e66bb5beded435694b6974a40163690123a1de2d4d41226cacc30d7485536ccd/_log_softmax_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..96f7ce727e0c095dc2c018d3b0d5f9048fb01344
--- /dev/null
+++ b/shared/package-files/e6/e66bb5beded435694b6974a40163690123a1de2d4d41226cacc30d7485536ccd/_log_softmax_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured__log_softmax : public at::impl::MetaBase {
+    
+    
+    void meta(const at::Tensor & self, int64_t dim, bool half_to_float);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e66be3f0deda42f5fc54dc29f4691f6a10dcbad56ecca09fa69c0b4bda6d7987/smooth_l1_loss_ops.h b/shared/package-files/e6/e66be3f0deda42f5fc54dc29f4691f6a10dcbad56ecca09fa69c0b4bda6d7987/smooth_l1_loss_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..d14eafcc11b21108cf1ee88196083944ae80d8a9
--- /dev/null
+++ b/shared/package-files/e6/e66be3f0deda42f5fc54dc29f4691f6a10dcbad56ecca09fa69c0b4bda6d7987/smooth_l1_loss_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API smooth_l1_loss_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, int64_t, double, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::smooth_l1_loss";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & out);
+};
+
+struct TORCH_API smooth_l1_loss {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, double);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::smooth_l1_loss";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e673d83019a33b21333998f4973fc2b549890125ebac4afadd8267572b4f4d0b/dropout.py b/shared/package-files/e6/e673d83019a33b21333998f4973fc2b549890125ebac4afadd8267572b4f4d0b/dropout.py
new file mode 100644
index 0000000000000000000000000000000000000000..3744ca30d5a49ba92cbb86690f2683af02d594fe
--- /dev/null
+++ b/shared/package-files/e6/e673d83019a33b21333998f4973fc2b549890125ebac4afadd8267572b4f4d0b/dropout.py
@@ -0,0 +1,30 @@
+# mypy: allow-untyped-defs
+import torch
+
+
+__all__ = ["Dropout"]
+
+
+class Dropout(torch.nn.Dropout):
+    r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
+        And this is a placeholder to enable models where fp32 tensors
+        had dropout to work with quantized tensors in train and eval mode.
+
+    Args:
+        p: probability of an element to be zeroed
+        inplace: can optionally do the operation in-place. Default: ``False``
+    """
+
+    def forward(self, input):
+        return input
+
+    def _get_name(self):
+        return "QuantizedDropout"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return cls(mod.p, mod.inplace)
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(mod.p, mod.inplace)
diff --git a/shared/package-files/e6/e67a795eb7971a4ef6b78b1c0950a231d9f56f771ac14d27187ace23113c7c1c/cpp_wrapper_cpu_array_ref.cpython-311.pyc b/shared/package-files/e6/e67a795eb7971a4ef6b78b1c0950a231d9f56f771ac14d27187ace23113c7c1c/cpp_wrapper_cpu_array_ref.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afbae20343996773eac96d6821df395248fdb016
Binary files /dev/null and b/shared/package-files/e6/e67a795eb7971a4ef6b78b1c0950a231d9f56f771ac14d27187ace23113c7c1c/cpp_wrapper_cpu_array_ref.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e689128930a0054d6028d226e17895d97373e40742112dbb0ad9b8fa25f8a1b7/combined_traceback.h b/shared/package-files/e6/e689128930a0054d6028d226e17895d97373e40742112dbb0ad9b8fa25f8a1b7/combined_traceback.h
new file mode 100644
index 0000000000000000000000000000000000000000..03b3846822dee309d95b10485a0cb5a965e68667
--- /dev/null
+++ b/shared/package-files/e6/e689128930a0054d6028d226e17895d97373e40742112dbb0ad9b8fa25f8a1b7/combined_traceback.h
@@ -0,0 +1,22 @@
+#include 
+
+#include 
+#include 
+
+namespace torch {
+
+// symbolize combined traceback objects, converting them into lists of
+// dictionaries that are easily consumed in python.
+
+// returns std::vector because one use is to call it with a batch of
+// tracebacks that come from a larger datastructure (e.g. a memory snapshot)
+// and then have more c++ code to put those objects in the right place.
+TORCH_API std::vector py_symbolize(
+    std::vector& to_symbolize);
+
+// requires GIL to be held, frees any pending free frames
+TORCH_PYTHON_API void freeDeadCapturedTracebackFrames();
+
+TORCH_PYTHON_API void installCapturedTracebackPython();
+
+} // namespace torch
diff --git a/shared/package-files/e6/e689adfcf92bdded298a11917a51df90a8ae27dc57ef25fc2772cf7bbb698e89/fmax_meta.h b/shared/package-files/e6/e689adfcf92bdded298a11917a51df90a8ae27dc57ef25fc2772cf7bbb698e89/fmax_meta.h
new file mode 100644
index 0000000000000000000000000000000000000000..20492b854dc7970c97060c4e362b5967f98efd18
--- /dev/null
+++ b/shared/package-files/e6/e689adfcf92bdded298a11917a51df90a8ae27dc57ef25fc2772cf7bbb698e89/fmax_meta.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeMetaFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+struct TORCH_API structured_fmax : public TensorIteratorBase {
+    
+    
+    void meta(const at::Tensor & self, const at::Tensor & other);
+};
+
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e68e7ed308290ec9149bbbcaa9265fe54392435dfd5c15fab30b6d46972535f2/trsock.cpython-311.pyc b/shared/package-files/e6/e68e7ed308290ec9149bbbcaa9265fe54392435dfd5c15fab30b6d46972535f2/trsock.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4cc276a7ed1825c29dff28d42a8bc5005b6139b
Binary files /dev/null and b/shared/package-files/e6/e68e7ed308290ec9149bbbcaa9265fe54392435dfd5c15fab30b6d46972535f2/trsock.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6910678532594f6949eb9514a6ab903eae55821a2a26d0ad90bf9fcd88bb7e5/gff.h b/shared/package-files/e6/e6910678532594f6949eb9514a6ab903eae55821a2a26d0ad90bf9fcd88bb7e5/gff.h
new file mode 100644
index 0000000000000000000000000000000000000000..afa945e8169dd2b6953442858a3a24751569b414
--- /dev/null
+++ b/shared/package-files/e6/e6910678532594f6949eb9514a6ab903eae55821a2a26d0ad90bf9fcd88bb7e5/gff.h
@@ -0,0 +1,317 @@
+/* The MIT License
+
+   Copyright (c) 2023-2024 Genome Research Ltd.
+
+   Author: Petr Danecek 
+
+   Permission is hereby granted, free of charge, to any person obtaining a copy
+   of this software and associated documentation files (the "Software"), to deal
+   in the Software without restriction, including without limitation the rights
+   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+   copies of the Software, and to permit persons to whom the Software is
+   furnished to do so, subject to the following conditions:
+
+   The above copyright notice and this permission notice shall be included in
+   all copies or substantial portions of the Software.
+
+   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+   THE SOFTWARE.
+
+ */
+/*
+    GFF parsing code refactored from csq.c
+
+    Things that would be nice to have
+        - dynamic N_REF_PAD
+        - for stop-lost events (also in frameshifts) report the number of truncated aa's
+        - memory could be greatly reduced by indexing gff (but it is quite compact already)
+        - deletions that go beyond transcript boundaries are not checked at sequence level
+            - alloc tscript->ref in hap_finalize, introduce fa_off_beg:16,fa_off_end:16
+            - see test/csq/ENST00000573314/insertion-overlap.vcf #1476288882
+
+    Read about transcript types here
+        http://vega.sanger.ac.uk/info/about/gene_and_transcript_types.html
+        https://www.ensembl.org/info/genome/variation/prediction/predicted_data.html
+        https://www.gencodegenes.org/pages/biotypes.html
+
+    List of supported biotypes
+        antisense
+        IG_C_gene
+        IG_D_gene
+        IG_J_gene
+        IG_LV_gene
+        IG_V_gene
+        lincRNA
+        lncRNA      .. generic term for 3prime_overlapping_ncRNA, antisense, bidirectional_promoter_lncRNA, lincRNA, macro_lncRNA, non_coding, processed_transcript, sense_intronic, sense_overlapping
+        macro_lncRNA
+        miRNA
+        misc_RNA
+        Mt_rRNA
+        Mt_tRNA
+        polymorphic_pseudogene
+        processed_transcript
+        protein_coding, mRNA
+        ribozyme
+        rRNA
+        sRNA
+        scRNA
+        scaRNA
+        sense_intronic
+        sense_overlapping
+        snRNA
+        snoRNA
+        TR_C_gene
+        TR_D_gene
+        TR_J_gene
+        TR_V_gene
+
+    The gff parsing logic
+        We collect features such by combining gff lines A,B,C as follows:
+            A .. gene line with a supported biotype
+                    A.ID=~/^gene:/
+
+            B .. transcript line referencing A with supported biotype
+                    B.ID=~/^transcript:/ && B.Parent=~/^gene:A.ID/
+
+            C .. corresponding CDS, exon, and UTR lines:
+                    C[3] in {"CDS","exon","three_prime_UTR","five_prime_UTR"} && C.Parent=~/^transcript:B.ID/
+
+        For coding biotypes ("protein_coding" or "polymorphic_pseudogene") the
+        complete chain link C -> B -> A is required. For the rest, link B -> A suffices.
+
+
+    The supported consequence types, sorted by impact:
+        splice_acceptor_variant .. end region of an intron changed (2bp at the 3' end of an intron)
+        splice_donor_variant    .. start region of an intron changed (2bp at the 5' end of an intron)
+        stop_gained             .. DNA sequence variant resulting in a stop codon
+        frameshift_variant      .. number of inserted/deleted bases not a multiple of three, disrupted translational frame
+        stop_lost               .. elongated transcript, stop codon changed
+        start_lost              .. the first codon changed
+        inframe_altering        .. combination of indels leading to unchanged reading frame and length
+        inframe_insertion       .. inserted coding sequence, unchanged reading frame
+        inframe_deletion        .. deleted coding sequence, unchanged reading frame
+        missense_variant        .. amino acid (aa) change, unchanged length
+        splice_region_variant   .. change within 1-3 bases of the exon or 3-8 bases of the intron
+        synonymous_variant      .. DNA sequence variant resulting in no amino acid change
+        stop_retained_variant   .. different stop codon
+        start_retained_variant  .. start codon retained by indel realignment
+        non_coding_variant      .. variant in non-coding sequence, such as RNA gene
+        5_prime_UTR_variant
+        3_prime_UTR_variant
+        intron_variant          .. reported only if none of the above
+        intergenic_variant      .. reported only if none of the above
+
+
+    The annotation algorithm.
+        The algorithm checks if the variant falls in a region of a supported type. The
+        search is performed in the following order, until a match is found:
+            1. idx_cds(gf_cds_t) - lookup CDS by position, create haplotypes, call consequences
+            2. idx_utr(gf_utr_t) - check UTR hits
+            3. idx_exon(gf_exon_t) - check for splice variants
+            4. idx_tscript(tscript_t) - check for intronic variants, RNAs, etc.
+
+        These regidx indexes are created by parsing a gff3 file as follows:
+            1.  create the array "ftr" of all UTR, CDS, exons. This will be
+            processed later and pruned based on transcript types we want to keep.
+            In the same go, create the hash "id2tr" of transcripts to keep
+            (based on biotype) which maps from transcript_id to a transcript. At
+            the same time also build the hash "gid2gene" which maps from gene_id to
+            gf_gene_t pointer.
+
+            2.  build "idx_cds", "idx_tscript", "idx_utr" and "idx_exon" indexes.
+            Use only features from "ftr" which are present in "id2tr".
+
+            3.  clean data that won't be needed anymore: ftr, id2tr, gid2gene.
+
+    Data structures.
+        idx_cds, idx_utr, idx_exon, idx_tscript:
+            as described above, regidx structures for fast lookup of exons/transcripts
+            overlapping a region, the payload is a pointer to tscript.cds
+*/
+
+#ifndef GFF_H__
+#define GFF_H__
+
+#include 
+
+#ifndef __FUNCTION__
+#  define __FUNCTION__ __func__
+#endif
+
+// Definition of splice_region, splice_acceptor and splice_donor
+#define N_SPLICE_DONOR         2
+#define N_SPLICE_REGION_EXON   3
+#define N_SPLICE_REGION_INTRON 8
+
+#define STRAND_REV 0
+#define STRAND_FWD 1
+#define STRAND_UNK 2
+
+#define TRIM_NONE   0
+#define TRIM_5PRIME 1
+#define TRIM_3PRIME 2
+
+
+// GFF line types
+#define GFF_UNKN_LINE    0
+#define GFF_TSCRIPT_LINE 1
+#define GFF_GENE_LINE    2
+
+
+/*
+    Genomic features, for fast lookup by position to overlapping features
+*/
+#define GF_coding_bit 6
+#define GF_is_coding(x) ((x) & (1<
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor";
+  static at::Tensor call(const at::Tensor & x, const at::Tensor & n);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, const at::Tensor & n);
+};
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w_x_scalar {
+  using schema = at::Tensor (const at::Scalar &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "x_scalar";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor";
+  static at::Tensor call(const at::Scalar & x, const at::Tensor & n);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & x, const at::Tensor & n);
+};
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w_n_scalar {
+  using schema = at::Tensor (const at::Tensor &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "n_scalar";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor";
+  static at::Tensor call(const at::Tensor & x, const at::Scalar & n);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, const at::Scalar & n);
+};
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & x, const at::Tensor & n, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, const at::Tensor & n, at::Tensor & out);
+};
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w_x_scalar_out {
+  using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "x_scalar_out";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Scalar & x, const at::Tensor & n, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & x, const at::Tensor & n, at::Tensor & out);
+};
+
+struct TORCH_API special_shifted_chebyshev_polynomial_w_n_scalar_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::special_shifted_chebyshev_polynomial_w";
+  static constexpr const char* overload_name = "n_scalar_out";
+  static constexpr const char* schema_str = "special_shifted_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & x, const at::Scalar & n, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, const at::Scalar & n, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e697d7321f87e770163756a823aec1af3d2152e838ecbac637fe67dce57dd087/_wrapped_quantized_linear_prepacked_native.h b/shared/package-files/e6/e697d7321f87e770163756a823aec1af3d2152e838ecbac637fe67dce57dd087/_wrapped_quantized_linear_prepacked_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..1fbe9cc1c71e17eb57f2247f19ff3dadcf3a25da
--- /dev/null
+++ b/shared/package-files/e6/e697d7321f87e770163756a823aec1af3d2152e838ecbac637fe67dce57dd087/_wrapped_quantized_linear_prepacked_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor _wrapped_quantized_linear_prepacked(const at::Tensor & input, const at::Tensor & input_scale, const at::Tensor & input_zero_point, const at::Tensor & packed_weight, const at::Tensor & output_scale, const at::Tensor & output_zero_point, int64_t out_channel);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e69ab9cea96ff68106ca4f2fd0a39417f042c27b28812d3cb849c2575705d329/test_dtypes.py b/shared/package-files/e6/e69ab9cea96ff68106ca4f2fd0a39417f042c27b28812d3cb849c2575705d329/test_dtypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..8620763988e0676e00d8e61affa75848fe38dd48
--- /dev/null
+++ b/shared/package-files/e6/e69ab9cea96ff68106ca4f2fd0a39417f042c27b28812d3cb849c2575705d329/test_dtypes.py
@@ -0,0 +1,294 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.generic import ABCIndex
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays.integer import (
+    Int8Dtype,
+    UInt32Dtype,
+)
+
+
+def test_dtypes(dtype):
+    # smoke tests on auto dtype construction
+
+    if dtype.is_signed_integer:
+        assert np.dtype(dtype.type).kind == "i"
+    else:
+        assert np.dtype(dtype.type).kind == "u"
+    assert dtype.name is not None
+
+
+@pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])
+def test_preserve_dtypes(op):
+    # for ops that enable (mean would actually work here
+    # but generally it is a float return value)
+    df = pd.DataFrame(
+        {
+            "A": ["a", "b", "b"],
+            "B": [1, None, 3],
+            "C": pd.array([1, None, 3], dtype="Int64"),
+        }
+    )
+
+    # op
+    result = getattr(df.C, op)()
+    if op in {"sum", "prod", "min", "max"}:
+        assert isinstance(result, np.int64)
+    else:
+        assert isinstance(result, int)
+
+    # groupby
+    result = getattr(df.groupby("A"), op)()
+
+    expected = pd.DataFrame(
+        {"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Int64")},
+        index=pd.Index(["a", "b"], name="A"),
+    )
+    tm.assert_frame_equal(result, expected)
+
+
+def test_astype_nansafe():
+    # see gh-22343
+    arr = pd.array([np.nan, 1, 2], dtype="Int8")
+    msg = "cannot convert NA to integer"
+
+    with pytest.raises(ValueError, match=msg):
+        arr.astype("uint32")
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_construct_index(all_data, dropna):
+    # ensure that we do not coerce to different Index dtype or non-index
+
+    all_data = all_data[:10]
+    if dropna:
+        other = np.array(all_data[~all_data.isna()])
+    else:
+        other = all_data
+
+    result = pd.Index(pd.array(other, dtype=all_data.dtype))
+    expected = pd.Index(other, dtype=all_data.dtype)
+    assert all_data.dtype == expected.dtype  # dont coerce to object
+
+    tm.assert_index_equal(result, expected)
+
+
+@pytest.mark.parametrize("dropna", [True, False])
+def test_astype_index(all_data, dropna):
+    # as an int/uint index to Index
+
+    all_data = all_data[:10]
+    if dropna:
+        other = all_data[~all_data.isna()]
+    else:
+        other = all_data
+
+    dtype = all_data.dtype
+    idx = pd.Index(np.array(other))
+    assert isinstance(idx, ABCIndex)
+
+    result = idx.astype(dtype)
+    expected = idx.astype(object).astype(dtype)
+    tm.assert_index_equal(result, expected)
+
+
+def test_astype(all_data):
+    all_data = all_data[:10]
+
+    ints = all_data[~all_data.isna()]
+    mixed = all_data
+    dtype = Int8Dtype()
+
+    # coerce to same type - ints
+    s = pd.Series(ints)
+    result = s.astype(all_data.dtype)
+    expected = pd.Series(ints)
+    tm.assert_series_equal(result, expected)
+
+    # coerce to same other - ints
+    s = pd.Series(ints)
+    result = s.astype(dtype)
+    expected = pd.Series(ints, dtype=dtype)
+    tm.assert_series_equal(result, expected)
+
+    # coerce to same numpy_dtype - ints
+    s = pd.Series(ints)
+    result = s.astype(all_data.dtype.numpy_dtype)
+    expected = pd.Series(ints._data.astype(all_data.dtype.numpy_dtype))
+    tm.assert_series_equal(result, expected)
+
+    # coerce to same type - mixed
+    s = pd.Series(mixed)
+    result = s.astype(all_data.dtype)
+    expected = pd.Series(mixed)
+    tm.assert_series_equal(result, expected)
+
+    # coerce to same other - mixed
+    s = pd.Series(mixed)
+    result = s.astype(dtype)
+    expected = pd.Series(mixed, dtype=dtype)
+    tm.assert_series_equal(result, expected)
+
+    # coerce to same numpy_dtype - mixed
+    s = pd.Series(mixed)
+    msg = "cannot convert NA to integer"
+    with pytest.raises(ValueError, match=msg):
+        s.astype(all_data.dtype.numpy_dtype)
+
+    # coerce to object
+    s = pd.Series(mixed)
+    result = s.astype("object")
+    expected = pd.Series(np.asarray(mixed, dtype=object))
+    tm.assert_series_equal(result, expected)
+
+
+def test_astype_copy():
+    arr = pd.array([1, 2, 3, None], dtype="Int64")
+    orig = pd.array([1, 2, 3, None], dtype="Int64")
+
+    # copy=True -> ensure both data and mask are actual copies
+    result = arr.astype("Int64", copy=True)
+    assert result is not arr
+    assert not tm.shares_memory(result, arr)
+    result[0] = 10
+    tm.assert_extension_array_equal(arr, orig)
+    result[0] = pd.NA
+    tm.assert_extension_array_equal(arr, orig)
+
+    # copy=False
+    result = arr.astype("Int64", copy=False)
+    assert result is arr
+    assert np.shares_memory(result._data, arr._data)
+    assert np.shares_memory(result._mask, arr._mask)
+    result[0] = 10
+    assert arr[0] == 10
+    result[0] = pd.NA
+    assert arr[0] is pd.NA
+
+    # astype to different dtype -> always needs a copy -> even with copy=False
+    # we need to ensure that also the mask is actually copied
+    arr = pd.array([1, 2, 3, None], dtype="Int64")
+    orig = pd.array([1, 2, 3, None], dtype="Int64")
+
+    result = arr.astype("Int32", copy=False)
+    assert not tm.shares_memory(result, arr)
+    result[0] = 10
+    tm.assert_extension_array_equal(arr, orig)
+    result[0] = pd.NA
+    tm.assert_extension_array_equal(arr, orig)
+
+
+def test_astype_to_larger_numpy():
+    a = pd.array([1, 2], dtype="Int32")
+    result = a.astype("int64")
+    expected = np.array([1, 2], dtype="int64")
+    tm.assert_numpy_array_equal(result, expected)
+
+    a = pd.array([1, 2], dtype="UInt32")
+    result = a.astype("uint64")
+    expected = np.array([1, 2], dtype="uint64")
+    tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", [Int8Dtype(), "Int8", UInt32Dtype(), "UInt32"])
+def test_astype_specific_casting(dtype):
+    s = pd.Series([1, 2, 3], dtype="Int64")
+    result = s.astype(dtype)
+    expected = pd.Series([1, 2, 3], dtype=dtype)
+    tm.assert_series_equal(result, expected)
+
+    s = pd.Series([1, 2, 3, None], dtype="Int64")
+    result = s.astype(dtype)
+    expected = pd.Series([1, 2, 3, None], dtype=dtype)
+    tm.assert_series_equal(result, expected)
+
+
+def test_astype_floating():
+    arr = pd.array([1, 2, None], dtype="Int64")
+    result = arr.astype("Float64")
+    expected = pd.array([1.0, 2.0, None], dtype="Float64")
+    tm.assert_extension_array_equal(result, expected)
+
+
+def test_astype_dt64():
+    # GH#32435
+    arr = pd.array([1, 2, 3, pd.NA]) * 10**9
+
+    result = arr.astype("datetime64[ns]")
+
+    expected = np.array([1, 2, 3, "NaT"], dtype="M8[s]").astype("M8[ns]")
+    tm.assert_numpy_array_equal(result, expected)
+
+
+def test_construct_cast_invalid(dtype):
+    msg = "cannot safely"
+    arr = [1.2, 2.3, 3.7]
+    with pytest.raises(TypeError, match=msg):
+        pd.array(arr, dtype=dtype)
+
+    with pytest.raises(TypeError, match=msg):
+        pd.Series(arr).astype(dtype)
+
+    arr = [1.2, 2.3, 3.7, np.nan]
+    with pytest.raises(TypeError, match=msg):
+        pd.array(arr, dtype=dtype)
+
+    with pytest.raises(TypeError, match=msg):
+        pd.Series(arr).astype(dtype)
+
+
+@pytest.mark.parametrize("in_series", [True, False])
+def test_to_numpy_na_nan(in_series):
+    a = pd.array([0, 1, None], dtype="Int64")
+    if in_series:
+        a = pd.Series(a)
+
+    result = a.to_numpy(dtype="float64", na_value=np.nan)
+    expected = np.array([0.0, 1.0, np.nan], dtype="float64")
+    tm.assert_numpy_array_equal(result, expected)
+
+    result = a.to_numpy(dtype="int64", na_value=-1)
+    expected = np.array([0, 1, -1], dtype="int64")
+    tm.assert_numpy_array_equal(result, expected)
+
+    result = a.to_numpy(dtype="bool", na_value=False)
+    expected = np.array([False, True, False], dtype="bool")
+    tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("in_series", [True, False])
+@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])
+def test_to_numpy_dtype(dtype, in_series):
+    a = pd.array([0, 1], dtype="Int64")
+    if in_series:
+        a = pd.Series(a)
+
+    result = a.to_numpy(dtype=dtype)
+    expected = np.array([0, 1], dtype=dtype)
+    tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("dtype", ["int64", "bool"])
+def test_to_numpy_na_raises(dtype):
+    a = pd.array([0, 1, None], dtype="Int64")
+    with pytest.raises(ValueError, match=dtype):
+        a.to_numpy(dtype=dtype)
+
+
+def test_astype_str():
+    a = pd.array([1, 2, None], dtype="Int64")
+    expected = np.array(["1", "2", ""], dtype=f"{tm.ENDIAN}U21")
+
+    tm.assert_numpy_array_equal(a.astype(str), expected)
+    tm.assert_numpy_array_equal(a.astype("str"), expected)
+
+
+def test_astype_boolean():
+    # https://github.com/pandas-dev/pandas/issues/31102
+    a = pd.array([1, 0, -1, 2, None], dtype="Int64")
+    result = a.astype("boolean")
+    expected = pd.array([True, False, True, True, None], dtype="boolean")
+    tm.assert_extension_array_equal(result, expected)
diff --git a/shared/package-files/e6/e6a10456df23aaae005e8a49223d5a3d495c7c22bf45d26cb029d429f9c439ab/crow_indices_copy_native.h b/shared/package-files/e6/e6a10456df23aaae005e8a49223d5a3d495c7c22bf45d26cb029d429f9c439ab/crow_indices_copy_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..5fc293f86bdfc0ae45063be5a14b8120c8f764bc
--- /dev/null
+++ b/shared/package-files/e6/e6a10456df23aaae005e8a49223d5a3d495c7c22bf45d26cb029d429f9c439ab/crow_indices_copy_native.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & crow_indices_copy_out(const at::Tensor & self, at::Tensor & out);
+TORCH_API at::Tensor crow_indices_copy(const at::Tensor & self);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e6aea6d8a481f72492a230c7ef7fc0368107d810a61566a39dffd62dbb60f542/two_canvases.cpython-311.pyc b/shared/package-files/e6/e6aea6d8a481f72492a230c7ef7fc0368107d810a61566a39dffd62dbb60f542/two_canvases.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..731ce4b53fae410c82fbeb546b552795d14e039a
Binary files /dev/null and b/shared/package-files/e6/e6aea6d8a481f72492a230c7ef7fc0368107d810a61566a39dffd62dbb60f542/two_canvases.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6b02f3a5546553dd5634bf9d85749d05e00cc46789c6c719b646aab3d9ac2fe/shim.h b/shared/package-files/e6/e6b02f3a5546553dd5634bf9d85749d05e00cc46789c6c719b646aab3d9ac2fe/shim.h
new file mode 100644
index 0000000000000000000000000000000000000000..f56f6eca74492a3e82083a076aa15027cec53d58
--- /dev/null
+++ b/shared/package-files/e6/e6b02f3a5546553dd5634bf9d85749d05e00cc46789c6c719b646aab3d9ac2fe/shim.h
@@ -0,0 +1,804 @@
+#ifndef AOTI_TORCH_SHIM
+#define AOTI_TORCH_SHIM
+
+#include 
+#include 
+
+// This header defines a stable C API for certain ATen functionality in
+// libtorch. The AOTInductor compiled model.so will only refer to this header
+// instead of other headers from aten/c10, which means it will NOT be able to
+// directly use any data structures or call functions from libtorch.
+//
+// What problems are we trying to solve here?  Direct use of aten/c10 APIs
+// means use of C++ APIs on a library that doesn't have any ABI compatibility
+// guarantees.  However, we want model.so to remain usable across updates
+// to the PyTorch C++ libraries, which requires a stable ABI.  By introducing
+// a C shim layer, we can minimize the surface that will cause breakage. The
+// corresponding software stack can be illustrated as follows:
+//
+// |--------------------------------|
+// |     inference service code     |
+// |--------------------------------|
+// |           model.so             |
+// |--------------|-----------------|
+// |                        |
+// |          libtorch.so           |
+// |--------------------------------|
+//
+// The general guidelines for the C API:
+//
+//  - No exceptions, return an explicit error code to be checked at call site
+//  - Only pointers (AtenTensorHandle counts), integers and floats in headers
+//
+// If you want to make changes to this header, you MUST MAINTAIN ABI
+// compatibility.  Typically, this means you will have to add a _v2 version
+// of a function that you, e.g., want to add a new function parameter to, and
+// maintain the old and new versions of the APIs until all old model.so
+// go out of use.
+
+#ifdef __GNUC__
+#define AOTI_TORCH_EXPORT __attribute__((__visibility__("default")))
+#else // !__GNUC__
+#ifdef _WIN32
+// PyTorch2 doesn't currently work on Windows. Exporting these APIs can lead
+// to symbol clashes at link time if libtorch is included in a DLL and binary
+// that depends on the DLL. As a short term fix, we don't export the symbols.
+// In the long term, this will need to be addressed when Windows is supported.
+#ifdef OVRSOURCE
+// Do not export AOTI on Windows for internal builds
+#define AOTI_TORCH_EXPORT
+#else /* OVRSOURCE */
+#ifdef EXPORT_AOTI_FUNCTIONS
+#define AOTI_TORCH_EXPORT __declspec(dllexport)
+#else
+#define AOTI_TORCH_EXPORT __declspec(dllimport)
+#endif
+#endif /* OVRSOURCE */
+#else // !_WIN32
+#define AOTI_TORCH_EXPORT
+#endif // _WIN32
+#endif // __GNUC__
+
+// The following files are implemented in a header-only way and are guarded by
+// test/cpp/aoti_abi_check
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// AtenTensorHandle represents an abstract notion of Tensor that can be passed
+// between model.so and libtorch.so.  The contents of the structure itself
+// are private; model.so is not allowed to access any fields directly, it must
+// go through functions defined in this ABI.  Under the hood, this is
+// represented as at::Tensor*, but we reserve the right to change this (and in
+// fact, we probably should change it to at::TensorImpl* at least).
+//
+// An AtenTensorHandle can be owning (please check the API reference for exact
+// ownership/borrow semantics).  If you have an owning AtenTensorHandle
+// in model.so, you are obligated to aoti_torch_delete_tensor_object when you
+// are done.  You can use the helper C++ class RAIIAtenTensorHandle
+// (see aot_runtime/model.h) to ensure the deallocator is called in RAII style
+// (note that RAIIAtenTensorHandle is private to model.so, and never crosses
+// the ABI boundary.)
+struct AtenTensorOpaque;
+using AtenTensorHandle = AtenTensorOpaque*;
+
+struct AtenGeneratorOpaque;
+using AtenGeneratorHandle = AtenGeneratorOpaque*;
+
+struct AOTIProxyExecutorOpaque;
+using AOTIProxyExecutorHandle = AOTIProxyExecutorOpaque*;
+
+using AOTITorchError = int32_t;
+#define AOTI_TORCH_SUCCESS 0
+#define AOTI_TORCH_FAILURE 1
+
+// Getter functions for retrieving various constants from the runtime, that
+// can subsequently be passed to other aoti_* functions.  By hiding these
+// behind functions, the precise value of device/dtype is NOT part of the
+// ABI contract.  (In practice, aten/c10 is pretty good about not renumbering
+// these, so we probably could later switch to having these in the ABI, if
+// desired for perf reasons.)
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cpu();
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cuda();
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_meta();
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_xpu();
+AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_privateuse1();
+
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fn();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2fnuz();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fnuz();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bfloat16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint8();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int8();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int16();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bool();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex32();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex64();
+AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex128();
+
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_strided();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_coo();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csr();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csc();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsr();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsc();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout__mkldnn();
+AOTI_TORCH_EXPORT int32_t aoti_torch_layout_jagged();
+
+AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_contiguous_format();
+AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last();
+AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last_3d();
+AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_preserve_format();
+
+// Get TORCH_ABI_VERSION of the built libtorch.so
+AOTI_TORCH_EXPORT uint64_t aoti_torch_abi_version();
+
+// Functions for converting a single-element tensor to a scalar value
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float16(AtenTensorHandle tensor, c10::Half* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float32(AtenTensorHandle tensor, float* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_float64(AtenTensorHandle tensor, double* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint8(AtenTensorHandle tensor, uint8_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint16(AtenTensorHandle tensor, uint16_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint32(AtenTensorHandle tensor, uint32_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_uint64(AtenTensorHandle tensor, uint64_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int8(AtenTensorHandle tensor, int8_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int16(AtenTensorHandle tensor, int16_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int32(AtenTensorHandle tensor, int32_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_int64(AtenTensorHandle tensor, int64_t* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_bool(AtenTensorHandle tensor, bool* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_item_bfloat16(AtenTensorHandle tensor, c10::BFloat16* ret_value);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_item_complex64(
+    AtenTensorHandle tensor,
+    c10::complex* ret_value);
+
+// Functions for wrapping a scalar value to a single-element tensor
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float32(
+    float value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float64(
+    double value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint8(
+    uint8_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint16(
+    uint16_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint32(
+    uint32_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint64(
+    uint64_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int8(
+    int8_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int16(
+    int16_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int32(
+    int32_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int64(
+    int64_t value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_scalar_to_tensor_bool(bool value, AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex64(
+    c10::complex value,
+    AtenTensorHandle* ret_new_tensor);
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex128(
+    c10::complex value,
+    AtenTensorHandle* ret_new_tensor);
+
+AOTI_TORCH_EXPORT bool aoti_torch_grad_mode_is_enabled();
+AOTI_TORCH_EXPORT void aoti_torch_grad_mode_set_enabled(bool enabled);
+
+// Free the tensor object
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_tensor_object(AtenTensorHandle tensor);
+
+// Get a pointer to the underlying storage data
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_data_ptr(
+    AtenTensorHandle tensor,
+    void** ret_data_ptr // returns borrowed reference
+);
+
+// Get the nbytes of the underlying storage
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_storage_size(AtenTensorHandle tensor, int64_t* ret_size);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_dim(AtenTensorHandle tensor, int64_t* ret_dim);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_numel(AtenTensorHandle tensor, int64_t* ret_numel);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_storage_numel(AtenTensorHandle tensor, int64_t* ret_numel);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_sizes(
+    AtenTensorHandle tensor,
+    int64_t** ret_sizes // returns borrowed reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_size(AtenTensorHandle tensor, int64_t d, int64_t* ret_size);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_strides(
+    AtenTensorHandle tensor,
+    int64_t** ret_strides // returns borrowed reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_stride(AtenTensorHandle tensor, int64_t d, int64_t* ret_stride);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_dtype(AtenTensorHandle tensor, int32_t* ret_dtype);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_device_type(AtenTensorHandle tensor, int32_t* ret_device_type);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_device_index(AtenTensorHandle tensor, int32_t* ret_device_index);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_storage_offset(
+    AtenTensorHandle tensor,
+    int64_t* ret_storage_offset);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_new_tensor_handle(
+    AtenTensorHandle orig_handle,
+    AtenTensorHandle* new_handle);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__alloc_from_pool(
+    AtenTensorHandle self,
+    int64_t offset_bytes,
+    int32_t dtype,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    AtenTensorHandle* ret_new_tensor);
+
+// This function will create a new tensor object and its pointer is returned
+// through *out. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__reinterpret_tensor(
+    AtenTensorHandle self,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    AtenTensorHandle* ret_new_tensor // returns new reference
+);
+
+// This function will create a new tensor object and its pointer is returned
+// through *out. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided(
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret_new_tensor // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_as_strided(
+    AtenTensorHandle self,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    AtenTensorHandle* ret);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob(
+    void* data,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob_v2(
+    void* data,
+    int64_t ndim,
+    const int64_t* sizes_ptr,
+    const int64_t* strides_ptr,
+    int64_t storage_offset,
+    int32_t dtype,
+    int32_t device_type,
+    int32_t device_index,
+    AtenTensorHandle* ret, // returns new reference
+    int32_t layout,
+    const uint8_t* opaque_metadata,
+    int64_t opaque_metadata_size);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__embedding_bag(
+    AtenTensorHandle weight,
+    AtenTensorHandle indices,
+    AtenTensorHandle offsets,
+    int32_t scale_grad_by_freq,
+    int32_t mode,
+    int32_t sparse,
+    AtenTensorHandle per_sample_weights, // optional argument
+    int32_t include_last_offset,
+    int32_t padding_idx,
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__fft_c2c(
+    AtenTensorHandle self,
+    const int64_t* dim_ptr,
+    int64_t dim_size,
+    int64_t normalization,
+    int32_t forward,
+    AtenTensorHandle* ret // returns new reference
+);
+
+// This version is deprecated. We will remove it later
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_dot_product_flash_attention(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    double dropout_p,
+    bool is_causal,
+    bool return_debug_mask,
+    double scale,
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3, // returns new reference
+    int64_t* ret4,
+    int64_t* ret5,
+    AtenTensorHandle* ret6, // returns new reference
+    AtenTensorHandle* ret7, // returns new reference
+    AtenTensorHandle* ret8 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch__scaled_dot_product_flash_attention_v2(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    double dropout_p,
+    int is_causal,
+    int return_debug_mask,
+    double* scale, // optional argument
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3, // returns new reference
+    int64_t* ret4,
+    int64_t* ret5,
+    AtenTensorHandle* ret6, // returns new reference
+    AtenTensorHandle* ret7, // returns new reference
+    AtenTensorHandle* ret8 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch__scaled_dot_product_efficient_attention(
+    AtenTensorHandle query,
+    AtenTensorHandle key,
+    AtenTensorHandle value,
+    AtenTensorHandle attn_bias, // optional argument
+    int compute_log_sumexp,
+    double dropout_p,
+    int is_causal,
+    double* scale, // optional argument
+    AtenTensorHandle* ret0, // returns new reference
+    AtenTensorHandle* ret1, // returns new reference
+    AtenTensorHandle* ret2, // returns new reference
+    AtenTensorHandle* ret3 // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm(
+    AtenTensorHandle self,
+    AtenTensorHandle mat2,
+    AtenTensorHandle bias,
+    int32_t* out_dtype,
+    AtenTensorHandle scale_a,
+    AtenTensorHandle scale_b,
+    AtenTensorHandle scale_result,
+    int8_t use_fast_accum,
+    AtenTensorHandle* ret0,
+    AtenTensorHandle* ret1);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm_v2(
+    AtenTensorHandle self,
+    AtenTensorHandle mat2,
+    AtenTensorHandle scale_a,
+    AtenTensorHandle scale_b,
+    AtenTensorHandle bias,
+    AtenTensorHandle scale_result,
+    int32_t* out_dtype,
+    int8_t use_fast_accum,
+    AtenTensorHandle* ret0);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_convolution(
+    AtenTensorHandle input,
+    AtenTensorHandle weight,
+    AtenTensorHandle bias, // optional argument
+    const int64_t* stride_ptr,
+    int64_t stride_size,
+    const int64_t* padding_ptr,
+    int64_t padding_size,
+    const int64_t* dilation_ptr,
+    int64_t dilation_size,
+    int transposed,
+    const int64_t* output_padding_ptr,
+    int64_t output_padding_size,
+    int64_t groups,
+    AtenTensorHandle* ret // returns new reference
+);
+
+// This function will create a new uninitialized tensor object
+// and its pointer is returned through *ret.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_new_uninitialized_tensor(AtenTensorHandle* ret);
+
+// WARNING: This will be deprecated. Use aoti_torch_copy_ instead.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_tensor_copy_(AtenTensorHandle src, AtenTensorHandle dst);
+
+// Make the tensor referred to by dst an alias for the tensor referred
+// to by src. The two tensors must still be deleted with
+// aoti_torch_delete_tensor separately (or not) as before the call.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_assign_tensors(AtenTensorHandle src, AtenTensorHandle dst);
+
+// Make a shallow copy of the tensor referred to by src and assign
+// it to the handle in the ret_dst. This is similar to the above
+// aoti_torch_assign_tensors function, but creates and sets the
+// ret_dst from within.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_assign_tensors_out(AtenTensorHandle src, AtenTensorHandle* ret_dst);
+
+// This function will create a new tensor object and its pointer is returned
+// through *ret. The caller is responsible for wrapping the tensor pointer
+// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object
+// when going out of scope.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_clone(AtenTensorHandle self, AtenTensorHandle* ret);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_clone_preserve_strides(AtenTensorHandle self, AtenTensorHandle* ret);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_addmm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat1,
+    AtenTensorHandle mat2,
+    float beta,
+    float alpha);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_bmm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat2);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_copy_(
+    AtenTensorHandle self,
+    AtenTensorHandle src,
+    int32_t non_blocking);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    AtenTensorHandle mat2);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch__mm_plus_mm_out(
+    AtenTensorHandle out,
+    AtenTensorHandle a,
+    AtenTensorHandle b,
+    AtenTensorHandle c,
+    AtenTensorHandle d);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu_wrapped_fbgemm_pack_gemm_matrix_fp16(
+    AtenTensorHandle weight,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__wrapped_linear_prepack(
+    AtenTensorHandle weight,
+    AtenTensorHandle weight_scale,
+    AtenTensorHandle weight_zero_point,
+    AtenTensorHandle bias,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu_wrapped_fbgemm_linear_fp16_weight(
+    AtenTensorHandle input,
+    AtenTensorHandle weight,
+    AtenTensorHandle bias,
+    int64_t out_channel,
+    AtenTensorHandle* out);
+
+// This will soon be deprecated after ao_quantization is complete.
+// Please refrain from using this or increasing callsites.
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cpu__wrapped_quantized_linear_prepacked(
+    AtenTensorHandle input,
+    AtenTensorHandle input_scale,
+    AtenTensorHandle input_zero_point,
+    AtenTensorHandle weight,
+    AtenTensorHandle out_scale,
+    AtenTensorHandle out_zeropoint,
+    int64_t out_channel,
+    AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_nonzero(AtenTensorHandle self, AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_zero_(AtenTensorHandle self);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_repeat_interleave_Tensor(
+    AtenTensorHandle repeats,
+    int64_t* output_size,
+    AtenTensorHandle* out);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_check_inf_and_nan(const char* tensor_name, AtenTensorHandle tensor);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    int64_t dim,
+    AtenTensorHandle index,
+    AtenTensorHandle src);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_reduce_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    int64_t dim,
+    AtenTensorHandle index,
+    AtenTensorHandle src,
+    const char* reduce,
+    int32_t include_self);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_index_put_out(
+    AtenTensorHandle out,
+    AtenTensorHandle self,
+    const AtenTensorHandle* indices,
+    const uint32_t num_indices,
+    const AtenTensorHandle values,
+    bool accumulate);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_as_real(
+    AtenTensorHandle self,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_dtype(
+    AtenTensorHandle self,
+    int32_t dtype,
+    AtenTensorHandle* ret // returns new reference
+);
+
+AOTI_TORCH_EXPORT void aoti_torch_print_tensor_handle(
+    AtenTensorHandle self,
+    const char* msg);
+
+// When AOTI debug printer option is enabled, this function will be invoked to
+// torch pickle save the intermediate tensor for debugging purpose.
+AOTI_TORCH_EXPORT void aoti_torch_save_tensor_handle(
+    AtenTensorHandle self,
+    const char* tensor_name,
+    const char* launch_prefix,
+    const char* kernel_name);
+
+// helpers for converting between StableIValue and actual IValues
+using StableIValue = uint64_t;
+
+class TorchLibraryOpaque;
+using TorchLibraryHandle = TorchLibraryOpaque*;
+
+// stable corollary to torch::Library constructor with Kind::IMPL
+// will create a new torch::Library object on the heap
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_impl(
+    const char* ns,
+    const char* k,
+    const char* file,
+    uint32_t line,
+    TorchLibraryHandle* ret_new_torch_lib);
+
+// stable corollary to torch::Library constructor with Kind::DEF
+// will create a new torch::Library object on the heap
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_def(
+    const char* ns,
+    const char* file,
+    uint32_t line,
+    TorchLibraryHandle* ret_new_torch_lib);
+
+// stable corollary to torch::Library constructor with Kind::FRAGMENT
+// will create a new torch::Library object on the heap
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_fragment(
+    const char* ns,
+    const char* file,
+    uint32_t line,
+    TorchLibraryHandle* ret_new_torch_lib);
+
+// stable corollary to torch::Library method m.impl(), should be
+// called from StableLibrary
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_impl(
+    TorchLibraryHandle self,
+    const char* name,
+    void (*fn)(StableIValue*, uint64_t, uint64_t));
+
+// stable corollary to torch::Library method m.def(), should be
+// called from StableLibrary
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_library_def(TorchLibraryHandle self, const char* schema);
+
+// the above stable constructors for torch::Library add Library objects
+// to the heap. if you are calling those functions directly, please use
+// this function to free the Library's memory. The more user friendly
+// alternative is to use StableLibrary, which will free its handle upon
+// destruction
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_library_object(TorchLibraryHandle tlh);
+
+// calls the op overload defined by a given opName, overloadName, and a
+// stack of StableIValues. This call will populate any return values of the
+// op into the stack in their StableIValue form, with ret0 at index 0, ret1
+// at index 1, and so on.
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_call_dispatcher(
+    const char* opName,
+    const char* overloadName,
+    StableIValue* stack);
+
+#ifdef USE_CUDA
+
+struct CUDAGuardOpaque;
+using CUDAGuardHandle = CUDAGuardOpaque*;
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_guard(
+    int32_t device_index,
+    CUDAGuardHandle* ret_guard // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_cuda_guard(CUDAGuardHandle guard);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_cuda_guard_set_index(CUDAGuardHandle guard, int32_t device_index);
+
+struct CUDAStreamGuardOpaque;
+using CUDAStreamGuardHandle = CUDAStreamGuardOpaque*;
+
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_stream_guard(
+    void* stream,
+    int32_t device_index,
+    CUDAStreamGuardHandle* ret_guard // returns new reference
+);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_delete_cuda_stream_guard(CUDAStreamGuardHandle guard);
+
+AOTI_TORCH_EXPORT AOTITorchError
+aoti_torch_get_current_cuda_stream(int32_t device_index, void** ret_stream);
+
+#endif // USE_CUDA
+
+// See `ProxyExecutor Design Note` in ir.py for more details
+AOTI_TORCH_EXPORT AOTITorchError aoti_torch_proxy_executor_call_function(
+    AOTIProxyExecutorHandle proxy_executor,
+    int extern_node_index,
+    int num_ints,
+    int64_t* flatten_int_args,
+    int num_tensors,
+    AtenTensorHandle* flatten_tensor_args);
+
+AOTI_TORCH_EXPORT void aoti_torch_check(
+    bool cond,
+    const char* func,
+    const char* file,
+    uint32_t line,
+    const char* msg);
+
+#ifdef STRIP_ERROR_MESSAGES
+#define AOTI_TORCH_CHECK(cond, ...)              \
+  if (!(cond)) {                                 \
+    aoti_torch_check(                            \
+        false,                                   \
+        __func__,                                \
+        __FILE__,                                \
+        static_cast(__LINE__),         \
+        TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \
+  }
+#else
+#define AOTI_TORCH_CHECK(cond, ...)                \
+  if (!(cond)) {                                   \
+    aoti_torch_check(                              \
+        false,                                     \
+        __func__,                                  \
+        __FILE__,                                  \
+        static_cast(__LINE__),           \
+        TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \
+  }
+#endif
+
+AOTI_TORCH_EXPORT void aoti_torch_warn(
+    const char* func,
+    const char* file,
+    uint32_t line,
+    const char* msg);
+
+#ifdef DISABLE_WARN
+#define AOTI_TORCH_WARN(...) ((void)0);
+#else
+#define AOTI_TORCH_WARN(...) \
+  aoti_torch_warn(           \
+      __func__, __FILE__, static_cast(__LINE__), #__VA_ARGS__);
+#endif
+
+#ifdef __cplusplus
+} // extern "C"
+
+template 
+int32_t aoti_torch_dtype() = delete;
+
+#define DEFINE_DTYPE_SPECIALIZATION(ctype, typename) \
+  template <>                                        \
+  inline int32_t aoti_torch_dtype() {         \
+    return aoti_torch_dtype_##typename();            \
+  }
+
+namespace c10 {
+struct BFloat16;
+struct Half;
+} // namespace c10
+
+DEFINE_DTYPE_SPECIALIZATION(c10::BFloat16, bfloat16)
+DEFINE_DTYPE_SPECIALIZATION(c10::Half, float16)
+DEFINE_DTYPE_SPECIALIZATION(c10::complex, complex64)
+DEFINE_DTYPE_SPECIALIZATION(float, float32)
+DEFINE_DTYPE_SPECIALIZATION(double, float64)
+DEFINE_DTYPE_SPECIALIZATION(uint8_t, uint8)
+DEFINE_DTYPE_SPECIALIZATION(int8_t, int8)
+DEFINE_DTYPE_SPECIALIZATION(int16_t, int16)
+DEFINE_DTYPE_SPECIALIZATION(int32_t, int32)
+DEFINE_DTYPE_SPECIALIZATION(int64_t, int64)
+DEFINE_DTYPE_SPECIALIZATION(bool, bool)
+
+#endif
+#endif // AOTI_TORCH_SHIM
diff --git a/shared/package-files/e6/e6bf5e62165c52afbab3df379ec8297ddaed83e118997b1d81384f859e5edfff/test_sysconfig.cpython-311.pyc b/shared/package-files/e6/e6bf5e62165c52afbab3df379ec8297ddaed83e118997b1d81384f859e5edfff/test_sysconfig.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6041e19043545ca820d1f2c74bc481c7708f221a
Binary files /dev/null and b/shared/package-files/e6/e6bf5e62165c52afbab3df379ec8297ddaed83e118997b1d81384f859e5edfff/test_sysconfig.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6c0230f321d8c6e29bfe9cf56efdaa0bce34ae31b4cb86c24a72c566459b245/dynamic_rendezvous.cpython-311.pyc b/shared/package-files/e6/e6c0230f321d8c6e29bfe9cf56efdaa0bce34ae31b4cb86c24a72c566459b245/dynamic_rendezvous.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..065df5a9c3604856f94397411a89960b77690b2d
Binary files /dev/null and b/shared/package-files/e6/e6c0230f321d8c6e29bfe9cf56efdaa0bce34ae31b4cb86c24a72c566459b245/dynamic_rendezvous.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6c06011313d86564a6fed7d24d48297dbc353fdaf6e93ce1e31c79a7af5dce8/test_deprecate_kwarg.cpython-311.pyc b/shared/package-files/e6/e6c06011313d86564a6fed7d24d48297dbc353fdaf6e93ce1e31c79a7af5dce8/test_deprecate_kwarg.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5029aa2b1ca18e8607516bb0afed8fce11a32d96
Binary files /dev/null and b/shared/package-files/e6/e6c06011313d86564a6fed7d24d48297dbc353fdaf6e93ce1e31c79a7af5dce8/test_deprecate_kwarg.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6c3a198535a74500a4f616e983ba4e54aa039cd1ed1c6244672537330a59c6f/test_jax.py b/shared/package-files/e6/e6c3a198535a74500a4f616e983ba4e54aa039cd1ed1c6244672537330a59c6f/test_jax.py
new file mode 100644
index 0000000000000000000000000000000000000000..365d87c5b91fdd49a8e46cfde9c2b5792c23a03c
--- /dev/null
+++ b/shared/package-files/e6/e6c3a198535a74500a4f616e983ba4e54aa039cd1ed1c6244672537330a59c6f/test_jax.py
@@ -0,0 +1,370 @@
+from sympy.concrete.summations import Sum
+from sympy.core.mod import Mod
+from sympy.core.relational import (Equality, Unequality)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.matrices.expressions.blockmatrix import BlockMatrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.utilities.lambdify import lambdify
+
+from sympy.abc import x, i, j, a, b, c, d
+from sympy.core import Function, Pow, Symbol
+from sympy.codegen.matrix_nodes import MatrixSolve
+from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
+from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
+from sympy.tensor.array import Array
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
+    PermuteDims, ArrayDiagonal
+from sympy.printing.numpy import JaxPrinter, _jax_known_constants, _jax_known_functions
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+
+from sympy.testing.pytest import skip, raises
+from sympy.external import import_module
+
+# Unlike NumPy which will aggressively promote operands to double precision,
+# jax always uses single precision. Double precision in jax can be
+# configured before the call to `import jax`, however this must be explicitly
+# configured and is not fully supported. Thus, the tests here have been modified
+# from the tests in test_numpy.py, only in the fact that they assert lambdify
+# function accuracy to only single precision accuracy.
+# https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
+
+jax = import_module('jax')
+
+if jax:
+    deafult_float_info = jax.numpy.finfo(jax.numpy.array([]).dtype)
+    JAX_DEFAULT_EPSILON = deafult_float_info.eps
+
+
+def test_jax_piecewise_regression():
+    """
+    NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
+    breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
+    See gh-9747 and gh-9749 for details.
+    """
+    printer = JaxPrinter()
+    p = Piecewise((1, x < 0), (0, True))
+    assert printer.doprint(p) == \
+        'jax.numpy.select([jax.numpy.less(x, 0),True], [1,0], default=jax.numpy.nan)'
+    assert printer.module_imports == {'jax.numpy': {'select', 'less', 'nan'}}
+
+
+def test_jax_logaddexp():
+    lae = logaddexp(a, b)
+    assert JaxPrinter().doprint(lae) == 'jax.numpy.logaddexp(a, b)'
+    lae2 = logaddexp2(a, b)
+    assert JaxPrinter().doprint(lae2) == 'jax.numpy.logaddexp2(a, b)'
+
+
+def test_jax_sum():
+    if not jax:
+        skip("JAX not installed")
+
+    s = Sum(x ** i, (i, a, b))
+    f = lambdify((a, b, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
+
+    s = Sum(i * x, (i, a, b))
+    f = lambdify((a, b, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
+
+
+def test_jax_multiple_sums():
+    if not jax:
+        skip("JAX not installed")
+
+    s = Sum((x + j) * i, (i, a, b), (j, c, d))
+    f = lambdify((a, b, c, d, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    c_, d_ = 11, 21
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, c_, d_, x_),
+                       sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
+
+
+def test_jax_codegen_einsum():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+
+    cg = convert_matrix_to_array(M * N)
+    f = lambdify((M, N), cg, 'jax')
+
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mb = jax.numpy.array([[1,-2], [-1, 3]])
+    assert (f(ma, mb) == jax.numpy.matmul(ma, mb)).all()
+
+
+def test_jax_codegen_extra():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+    P = MatrixSymbol("P", 2, 2)
+    Q = MatrixSymbol("Q", 2, 2)
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mb = jax.numpy.array([[1,-2], [-1, 3]])
+    mc = jax.numpy.array([[2, 0], [1, 2]])
+    md = jax.numpy.array([[1,-1], [4, 7]])
+
+    cg = ArrayTensorProduct(M, N)
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.einsum(ma, [0, 1], mb, [2, 3])).all()
+
+    cg = ArrayAdd(M, N)
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == ma+mb).all()
+
+    cg = ArrayAdd(M, N, P)
+    f = lambdify((M, N, P), cg, 'jax')
+    assert (f(ma, mb, mc) == ma+mb+mc).all()
+
+    cg = ArrayAdd(M, N, P, Q)
+    f = lambdify((M, N, P, Q), cg, 'jax')
+    assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
+
+    cg = PermuteDims(M, [1, 0])
+    f = lambdify((M,), cg, 'jax')
+    assert (f(ma) == ma.T).all()
+
+    cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.transpose(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
+
+    cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.diagonal(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
+
+
+def test_jax_relational():
+    if not jax:
+        skip("JAX not installed")
+
+    e = Equality(x, 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, False])
+
+    e = Unequality(x, 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, False, True])
+
+    e = (x < 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, False, False])
+
+    e = (x <= 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, True, False])
+
+    e = (x > 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, False, True])
+
+    e = (x >= 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, True])
+
+    # Multi-condition expressions
+    e = (x >= 1) & (x < 2)
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, False])
+
+    e = (x >= 1) | (x < 2)
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, True, True])
+
+def test_jax_mod():
+    if not jax:
+        skip("JAX not installed")
+
+    e = Mod(a, b)
+    f = lambdify((a, b), e, 'jax')
+
+    a_ = jax.numpy.array([0, 1, 2, 3])
+    b_ = 2
+    assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = jax.numpy.array([0, 1, 2, 3])
+    b_ = jax.numpy.array([2, 2, 2, 2])
+    assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = jax.numpy.array([2, 3, 4, 5])
+    b_ = jax.numpy.array([2, 3, 4, 5])
+    assert jax.numpy.array_equal(f(a_, b_), [0, 0, 0, 0])
+
+
+def test_jax_pow():
+    if not jax:
+        skip('JAX not installed')
+
+    expr = Pow(2, -1, evaluate=False)
+    f = lambdify([], expr, 'jax')
+    assert f() == 0.5
+
+
+def test_jax_expm1():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify((a,), expm1(a), 'jax')
+    assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * JAX_DEFAULT_EPSILON
+
+
+def test_jax_log1p():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify((a,), log1p(a), 'jax')
+    assert abs(f(1e-99) - 1e-99) <= 1e-99 * JAX_DEFAULT_EPSILON
+
+def test_jax_hypot():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a, b), hypot(a, b), 'jax')(3, 4) - 5) <= JAX_DEFAULT_EPSILON
+
+def test_jax_log10():
+    if not jax:
+        skip("JAX not installed")
+
+    assert abs(lambdify((a,), log10(a), 'jax')(100) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_exp2():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), exp2(a), 'jax')(5) - 32) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_log2():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), log2(a), 'jax')(256) - 8) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_Sqrt():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), Sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_sqrt():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_matsolve():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 3, 3)
+    x = MatrixSymbol("x", 3, 1)
+
+    expr = M**(-1) * x + x
+    matsolve_expr = MatrixSolve(M, x) + x
+
+    f = lambdify((M, x), expr, 'jax')
+    f_matsolve = lambdify((M, x), matsolve_expr, 'jax')
+
+    m0 = jax.numpy.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
+    assert jax.numpy.linalg.matrix_rank(m0) == 3
+
+    x0 = jax.numpy.array([3, 4, 5])
+
+    assert jax.numpy.allclose(f_matsolve(m0, x0), f(m0, x0))
+
+
+def test_16857():
+    if not jax:
+        skip("JAX not installed")
+
+    a_1 = MatrixSymbol('a_1', 10, 3)
+    a_2 = MatrixSymbol('a_2', 10, 3)
+    a_3 = MatrixSymbol('a_3', 10, 3)
+    a_4 = MatrixSymbol('a_4', 10, 3)
+    A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
+    assert A.shape == (20, 6)
+
+    printer = JaxPrinter()
+    assert printer.doprint(A) == 'jax.numpy.block([[a_1, a_2], [a_3, a_4]])'
+
+
+def test_issue_17006():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+
+    f = lambdify(M, M + Identity(2), 'jax')
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mr = jax.numpy.array([[2, 2], [3, 5]])
+
+    assert (f(ma) == mr).all()
+
+    from sympy.core.symbol import symbols
+    n = symbols('n', integer=True)
+    N = MatrixSymbol("M", n, n)
+    raises(NotImplementedError, lambda: lambdify(N, N + Identity(n), 'jax'))
+
+
+def test_jax_array():
+    assert JaxPrinter().doprint(Array(((1, 2), (3, 5)))) == 'jax.numpy.array([[1, 2], [3, 5]])'
+    assert JaxPrinter().doprint(Array((1, 2))) == 'jax.numpy.array([1, 2])'
+
+
+def test_jax_known_funcs_consts():
+    assert _jax_known_constants['NaN'] == 'jax.numpy.nan'
+    assert _jax_known_constants['EulerGamma'] == 'jax.numpy.euler_gamma'
+
+    assert _jax_known_functions['acos'] == 'jax.numpy.arccos'
+    assert _jax_known_functions['log'] == 'jax.numpy.log'
+
+
+def test_jax_print_methods():
+    prntr = JaxPrinter()
+    assert hasattr(prntr, '_print_acos')
+    assert hasattr(prntr, '_print_log')
+
+
+def test_jax_printmethod():
+    printer = JaxPrinter()
+    assert hasattr(printer, 'printmethod')
+    assert printer.printmethod == '_jaxcode'
+
+
+def test_jax_custom_print_method():
+
+    class expm1(Function):
+
+        def _jaxcode(self, printer):
+            x, = self.args
+            function = f'expm1({printer._print(x)})'
+            return printer._module_format(printer._module + '.' + function)
+
+    printer = JaxPrinter()
+    assert printer.doprint(expm1(Symbol('x'))) == 'jax.numpy.expm1(x)'
diff --git a/shared/package-files/e6/e6c85d446c5b42c45f7dba936b720c71d30c51f0e8f7ebc983ce89cdf4e41a77/adamax.py b/shared/package-files/e6/e6c85d446c5b42c45f7dba936b720c71d30c51f0e8f7ebc983ce89cdf4e41a77/adamax.py
new file mode 100644
index 0000000000000000000000000000000000000000..588950aa5be5b4bd43fccbd5f8eb32b4b56a8e1b
--- /dev/null
+++ b/shared/package-files/e6/e6c85d446c5b42c45f7dba936b720c71d30c51f0e8f7ebc983ce89cdf4e41a77/adamax.py
@@ -0,0 +1,472 @@
+# mypy: allow-untyped-defs
+from typing import cast, Optional, Union
+
+import torch
+from torch import Tensor
+
+from .optimizer import (
+    _capturable_doc,
+    _default_to_fused_or_foreach,
+    _differentiable_doc,
+    _disable_dynamo_if_unsupported,
+    _foreach_doc,
+    _get_capturable_supported_devices,
+    _get_scalar_dtype,
+    _get_value,
+    _maximize_doc,
+    _params_doc,
+    _use_grad_for_differentiable,
+    _view_as_real,
+    Optimizer,
+    ParamsT,
+)
+
+
+__all__ = ["Adamax", "adamax"]
+
+
+class Adamax(Optimizer):
+    def __init__(
+        self,
+        params: ParamsT,
+        lr: Union[float, Tensor] = 2e-3,
+        betas: tuple[float, float] = (0.9, 0.999),
+        eps: float = 1e-8,
+        weight_decay: float = 0,
+        foreach: Optional[bool] = None,
+        *,
+        maximize: bool = False,
+        differentiable: bool = False,
+        capturable: bool = False,
+    ):
+        if isinstance(lr, Tensor) and lr.numel() != 1:
+            raise ValueError("Tensor lr must be 1-element")
+        if not 0.0 <= lr:
+            raise ValueError(f"Invalid learning rate: {lr}")
+        if not 0.0 <= eps:
+            raise ValueError(f"Invalid epsilon value: {eps}")
+        if not 0.0 <= betas[0] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
+        if not 0.0 <= betas[1] < 1.0:
+            raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
+        if not 0.0 <= weight_decay:
+            raise ValueError(f"Invalid weight_decay value: {weight_decay}")
+
+        defaults = dict(
+            lr=lr,
+            betas=betas,
+            eps=eps,
+            weight_decay=weight_decay,
+            foreach=foreach,
+            maximize=maximize,
+            differentiable=differentiable,
+            capturable=capturable,
+        )
+        super().__init__(params, defaults)
+
+    def __setstate__(self, state):
+        super().__setstate__(state)
+        for group in self.param_groups:
+            group.setdefault("foreach", None)
+            group.setdefault("maximize", False)
+            group.setdefault("differentiable", False)
+            group.setdefault("capturable", False)
+            for p in group["params"]:
+                p_state = self.state.get(p, [])
+                if len(p_state) != 0 and not torch.is_tensor(p_state["step"]):
+                    step_val = float(p_state["step"])
+                    p_state["step"] = (
+                        torch.tensor(
+                            step_val, dtype=_get_scalar_dtype(), device=p.device
+                        )
+                        if group["capturable"]
+                        else torch.tensor(step_val, dtype=_get_scalar_dtype())
+                    )
+
+    def _init_group(
+        self, group, params_with_grad, grads, exp_avgs, exp_infs, state_steps
+    ):
+        has_complex = False
+        for p in group["params"]:
+            if p.grad is None:
+                continue
+            has_complex |= torch.is_complex(p)
+            params_with_grad.append(p)
+            if p.grad.is_sparse:
+                raise RuntimeError("Adamax does not support sparse gradients")
+            grads.append(p.grad)
+
+            state = self.state[p]
+
+            # State initialization
+            if len(state) == 0:
+                state["step"] = (
+                    torch.zeros((), dtype=_get_scalar_dtype(), device=p.device)
+                    if group["capturable"]
+                    else torch.tensor(0.0, dtype=_get_scalar_dtype())
+                )
+                state["exp_avg"] = torch.zeros_like(
+                    p, memory_format=torch.preserve_format
+                )
+                state["exp_inf"] = torch.zeros_like(
+                    p, memory_format=torch.preserve_format
+                )
+
+            exp_avgs.append(state["exp_avg"])
+            exp_infs.append(state["exp_inf"])
+            state_steps.append(state["step"])
+
+        return has_complex
+
+    @_use_grad_for_differentiable
+    def step(self, closure=None):
+        """Performs a single optimization step.
+
+        Args:
+            closure (Callable, optional): A closure that reevaluates the model
+                and returns the loss.
+        """
+        self._cuda_graph_capture_health_check()
+
+        loss = None
+        if closure is not None:
+            with torch.enable_grad():
+                loss = closure()
+
+        for group in self.param_groups:
+            params_with_grad: list[Tensor] = []
+            grads: list[Tensor] = []
+            exp_avgs: list[Tensor] = []
+            exp_infs: list[Tensor] = []
+            state_steps: list[Tensor] = []
+
+            beta1, beta2 = group["betas"]
+            eps = group["eps"]
+            lr = group["lr"]
+            weight_decay = group["weight_decay"]
+            foreach = group["foreach"]
+            maximize = group["maximize"]
+            differentiable = group["differentiable"]
+            capturable = group["capturable"]
+
+            has_complex = self._init_group(
+                group, params_with_grad, grads, exp_avgs, exp_infs, state_steps
+            )
+
+            adamax(
+                params_with_grad,
+                grads,
+                exp_avgs,
+                exp_infs,
+                state_steps,
+                eps=eps,
+                beta1=beta1,
+                beta2=beta2,
+                lr=lr,
+                weight_decay=weight_decay,
+                foreach=foreach,
+                maximize=maximize,
+                differentiable=differentiable,
+                capturable=capturable,
+                has_complex=has_complex,
+            )
+
+        return loss
+
+
+Adamax.__doc__ = (
+    r"""Implements Adamax algorithm (a variant of Adam based on infinity norm).
+
+    .. math::
+       \begin{aligned}
+            &\rule{110mm}{0.4pt}                                                                 \\
+            &\textbf{input}      : \gamma \text{ (lr)}, \beta_1, \beta_2
+                \text{ (betas)},\theta_0 \text{ (params)},f(\theta) \text{ (objective)},
+                \: \lambda \text{ (weight decay)},                                                \\
+            &\hspace{13mm}    \epsilon \text{ (epsilon)}                                          \\
+            &\textbf{initialize} :  m_0 \leftarrow 0 \text{ ( first moment)},
+                u_0 \leftarrow 0 \text{ ( infinity norm)}                                 \\[-1.ex]
+            &\rule{110mm}{0.4pt}                                                                 \\
+            &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do}                         \\
+            &\hspace{5mm}g_t           \leftarrow   \nabla_{\theta} f_t (\theta_{t-1})           \\
+            &\hspace{5mm}if \: \lambda \neq 0                                                    \\
+            &\hspace{10mm} g_t \leftarrow g_t + \lambda  \theta_{t-1}                            \\
+            &\hspace{5mm}m_t      \leftarrow   \beta_1 m_{t-1} + (1 - \beta_1) g_t               \\
+            &\hspace{5mm}u_t      \leftarrow   \mathrm{max}(\beta_2 u_{t-1}, |g_{t}|+\epsilon)   \\
+            &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \frac{\gamma m_t}{(1-\beta^t_1) u_t} \\
+            &\rule{110mm}{0.4pt}                                                          \\[-1.ex]
+            &\bf{return} \:  \theta_t                                                     \\[-1.ex]
+            &\rule{110mm}{0.4pt}                                                          \\[-1.ex]
+       \end{aligned}
+
+    For further details regarding the algorithm we refer to `Adam: A Method for Stochastic Optimization`_.
+    """
+    + rf"""
+    Args:
+        {_params_doc}
+        lr (float, Tensor, optional): learning rate (default: 2e-3)
+        betas (Tuple[float, float], optional): coefficients used for computing
+            running averages of gradient and its square
+        eps (float, optional): term added to the denominator to improve
+            numerical stability (default: 1e-8)
+        weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
+        {_foreach_doc}
+        {_maximize_doc}
+        {_differentiable_doc}
+        {_capturable_doc}
+
+    .. _Adam\: A Method for Stochastic Optimization:
+        https://arxiv.org/abs/1412.6980
+
+    """
+)
+
+
+def _single_tensor_adamax(
+    params: list[Tensor],
+    grads: list[Tensor],
+    exp_avgs: list[Tensor],
+    exp_infs: list[Tensor],
+    state_steps: list[Tensor],
+    *,
+    eps: float,
+    beta1: float,
+    beta2: float,
+    lr: float,
+    weight_decay: float,
+    maximize: bool,
+    differentiable: bool,
+    capturable: bool,
+    has_complex: bool,
+):
+    for i, param in enumerate(params):
+        grad = grads[i]
+        grad = grad if not maximize else -grad
+        exp_avg = exp_avgs[i]
+        exp_inf = exp_infs[i]
+        step_t = state_steps[i]
+
+        # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
+        if not torch.compiler.is_compiling() and capturable:
+            capturable_supported_devices = _get_capturable_supported_devices()
+            assert (
+                param.device.type == step_t.device.type
+                and param.device.type in capturable_supported_devices
+            ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
+
+        # update step
+        step_t += 1
+
+        if weight_decay != 0:
+            grad = grad.add(param, alpha=weight_decay)
+
+        if torch.is_complex(param):
+            param = torch.view_as_real(param)
+            grad = torch.view_as_real(grad)
+            exp_avg = torch.view_as_real(exp_avg)
+            exp_inf = torch.view_as_real(exp_inf)
+
+        # Update biased first moment estimate.
+        exp_avg.lerp_(grad, 1 - beta1)
+        # Update the exponentially weighted infinity norm.
+        if not differentiable:
+            torch.maximum(
+                exp_inf.mul_(beta2),
+                grad.abs().add_(eps),
+                out=exp_inf,
+            )
+        else:
+            norm_buf = torch.cat(
+                [exp_inf.mul_(beta2).unsqueeze(0), grad.abs().add_(eps).unsqueeze_(0)],
+                0,
+            )
+            exp_inf.copy_(torch.amax(norm_buf, 0, keepdim=False))
+
+        if capturable:
+            # why jump through extra hoops and negate bias_correction? check out #121238
+            # once fixed, we should use bias_correction with addcdiv value=-1 for readability
+            neg_bias_correction = beta1**step_t - 1
+            neg_bias_correction.div_(lr)
+            denom = exp_inf * neg_bias_correction
+            param.addcdiv_(exp_avg, denom)
+        else:
+            bias_correction = 1 - beta1 ** _get_value(step_t)
+            clr = lr / bias_correction
+
+            param.addcdiv_(exp_avg, exp_inf, value=-clr)
+
+
+def _multi_tensor_adamax(
+    params: list[Tensor],
+    grads: list[Tensor],
+    exp_avgs: list[Tensor],
+    exp_infs: list[Tensor],
+    state_steps: list[Tensor],
+    *,
+    eps: float,
+    beta1: float,
+    beta2: float,
+    lr: float,
+    weight_decay: float,
+    maximize: bool,
+    differentiable: bool,
+    capturable: bool,
+    has_complex: bool,
+):
+    assert not differentiable, "_foreach ops don't support autograd"
+
+    if len(params) == 0:
+        return
+
+    # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
+    if not torch.compiler.is_compiling() and capturable:
+        capturable_supported_devices = _get_capturable_supported_devices(
+            supports_xla=False
+        )
+        assert all(
+            p.device.type == step.device.type
+            and p.device.type in capturable_supported_devices
+            for p, step in zip(params, state_steps)
+        ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
+
+    grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(
+        [params, grads, exp_avgs, exp_infs, state_steps]  # type: ignore[list-item]
+    )
+    for (
+        grouped_params_,
+        grouped_grads_,
+        grouped_exp_avgs_,
+        grouped_exp_infs_,
+        grouped_state_steps_,
+    ), _ in grouped_tensors.values():
+        grouped_params = cast(list[Tensor], grouped_params_)
+        grouped_grads = cast(list[Tensor], grouped_grads_)
+        grouped_exp_avgs = cast(list[Tensor], grouped_exp_avgs_)
+        grouped_exp_infs = cast(list[Tensor], grouped_exp_infs_)
+        grouped_state_steps = cast(list[Tensor], grouped_state_steps_)
+
+        if has_complex:
+            _view_as_real(
+                grouped_params, grouped_grads, grouped_exp_avgs, grouped_exp_infs
+            )
+
+        if maximize:
+            grouped_grads = torch._foreach_neg(grouped_grads)  # type: ignore[assignment]
+
+        # Update steps
+        # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over
+        # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just
+        # wrapped it once now. The alpha is required to assure we go to the right overload.
+        if not torch.compiler.is_compiling() and grouped_state_steps[0].is_cpu:
+            torch._foreach_add_(
+                grouped_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0
+            )
+        else:
+            torch._foreach_add_(grouped_state_steps, 1)
+
+        if weight_decay != 0:
+            if maximize:
+                # Re-use the intermediate memory (grouped_grads) already allocated for maximize
+                torch._foreach_add_(grouped_grads, grouped_params, alpha=weight_decay)
+            else:
+                grouped_grads = torch._foreach_add(  # type: ignore[assignment]
+                    grouped_grads, grouped_params, alpha=weight_decay
+                )
+
+        # Update biased first moment estimate.
+        torch._foreach_lerp_(grouped_exp_avgs, grouped_grads, 1 - beta1)
+
+        # Update the exponentially weighted infinity norm.
+        torch._foreach_mul_(grouped_exp_infs, beta2)
+
+        # in this case, we need to introduce a copy of the grads
+        # since one has not been introduced previously
+        if not maximize and weight_decay == 0:
+            grouped_grads = torch._foreach_abs(grouped_grads)  # type: ignore[assignment]
+        else:
+            torch._foreach_abs_(grouped_grads)
+
+        torch._foreach_add_(grouped_grads, eps)
+        torch._foreach_maximum_(grouped_exp_infs, grouped_grads)
+
+        bias_corrections: Union[tuple[Tensor, ...], list[Tensor]]
+        if capturable:
+            bias_corrections = torch._foreach_pow(beta1, grouped_state_steps)
+            # foreach_sub doesn't allow a scalar as the first arg
+            torch._foreach_sub_(bias_corrections, 1)
+            torch._foreach_div_(bias_corrections, lr)
+
+            denom = torch._foreach_mul(grouped_exp_infs, bias_corrections)
+            torch._foreach_addcdiv_(grouped_params, grouped_exp_avgs, denom)
+        else:
+            bias_corrections = [
+                1 - beta1 ** _get_value(step) for step in grouped_state_steps
+            ]
+            step_size = [(_get_value(lr) / bc) * -1 for bc in bias_corrections]
+            torch._foreach_addcdiv_(
+                grouped_params, grouped_exp_avgs, grouped_exp_infs, step_size
+            )
+
+
+@_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_adamax)
+def adamax(
+    params: list[Tensor],
+    grads: list[Tensor],
+    exp_avgs: list[Tensor],
+    exp_infs: list[Tensor],
+    state_steps: list[Tensor],
+    # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
+    # setting this as kwarg for now as functional API is compiled by torch/distributed/optim
+    foreach: Optional[bool] = None,
+    maximize: bool = False,
+    differentiable: bool = False,
+    capturable: bool = False,
+    has_complex: bool = False,
+    *,
+    eps: float,
+    beta1: float,
+    beta2: float,
+    lr: float,
+    weight_decay: float,
+):
+    r"""Functional API that performs adamax algorithm computation.
+
+    See :class:`~torch.optim.Adamax` for details.
+    """
+
+    if not torch.compiler.is_compiling() and not all(
+        isinstance(t, torch.Tensor) for t in state_steps
+    ):
+        raise RuntimeError(
+            "API has changed, `state_steps` argument must contain a list of singleton tensors"
+        )
+
+    if foreach is None:
+        _, foreach = _default_to_fused_or_foreach(
+            params, differentiable, use_fused=False
+        )
+
+    if foreach and torch.jit.is_scripting():
+        raise RuntimeError("torch.jit.script not supported with foreach optimizers")
+
+    if foreach and not torch.jit.is_scripting():
+        func = _multi_tensor_adamax
+    else:
+        func = _single_tensor_adamax
+
+    func(
+        params,
+        grads,
+        exp_avgs,
+        exp_infs,
+        state_steps,
+        eps=eps,
+        beta1=beta1,
+        beta2=beta2,
+        lr=lr,
+        weight_decay=weight_decay,
+        maximize=maximize,
+        differentiable=differentiable,
+        has_complex=has_complex,
+        capturable=capturable,
+    )
diff --git a/shared/package-files/e6/e6cec2f14d10a3b53eea9955aff388fcc6eaf0497b07791a28c9b3f146f5db31/isinf_native.h b/shared/package-files/e6/e6cec2f14d10a3b53eea9955aff388fcc6eaf0497b07791a28c9b3f146f5db31/isinf_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..3b5a381f9789169e47b5e3b8ba50c8392d32c281
--- /dev/null
+++ b/shared/package-files/e6/e6cec2f14d10a3b53eea9955aff388fcc6eaf0497b07791a28c9b3f146f5db31/isinf_native.h
@@ -0,0 +1,26 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor isinf(const at::Tensor & self);
+TORCH_API at::Tensor & isinf_out(const at::Tensor & self, at::Tensor & out);
+TORCH_API at::Tensor NestedTensor_isinf(const at::Tensor & self);
+TORCH_API at::Tensor isinf_sparse(const at::Tensor & self);
+TORCH_API at::Tensor isinf_sparse_csr(const at::Tensor & self);
+TORCH_API at::Tensor isinf_sparse_meta(const at::Tensor & self);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/e6/e6dc67a918039496832c54293f170ee79ca8a8d9dd3ff542ff3d7691eea96ba0/rbuf.h b/shared/package-files/e6/e6dc67a918039496832c54293f170ee79ca8a8d9dd3ff542ff3d7691eea96ba0/rbuf.h
new file mode 100644
index 0000000000000000000000000000000000000000..ef2e206322dbcafdc51d0118d118847b0423da6d
--- /dev/null
+++ b/shared/package-files/e6/e6dc67a918039496832c54293f170ee79ca8a8d9dd3ff542ff3d7691eea96ba0/rbuf.h
@@ -0,0 +1,261 @@
+/*  rbuf.h -- round buffers.
+
+    Copyright (C) 2013-2014, 2017 Genome Research Ltd.
+
+    Author: Petr Danecek 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.  */
+
+#ifndef __RBUF_H__
+#define __RBUF_H__
+
+#include 
+
+typedef struct
+{
+    int m,n,f;    // m: allocated size, n: number of elements in the buffer, f: first element
+}
+rbuf_t;
+
+/**
+ *  rbuf_init() - initialize round buffer
+ *  @rbuf:  the rbuf_t holder
+ *  @size:  the maximum number of elements
+ *
+ */
+static inline void rbuf_init(rbuf_t *rbuf, int size)
+{
+    rbuf->m = size; rbuf->n = rbuf->f = 0;
+}
+/**
+ *  rbuf_kth() - get index of the k-th element of the round buffer
+ *  @rbuf:  the rbuf_t holder
+ *  @k:     0-based index. If negative, return k-th element from the end, 1-based
+ */
+static inline int rbuf_kth(rbuf_t *rbuf, int k)
+{
+    if ( k >= rbuf->n ) return -1;
+    if ( k < 0 )
+    {
+        k = rbuf->n + k; 
+        if ( k < 0 ) return -1;
+    }
+    int i = k + rbuf->f;
+    if ( i >= rbuf->m ) i -= rbuf->m;
+    return i;
+}
+/**
+ *  rbuf_last() - get index of the last element of the round buffer
+ *  @rbuf:  the rbuf_t holder
+ */
+#define rbuf_last(rbuf) rbuf_kth(rbuf, -1)
+
+/**
+ *  rbuf_l2ridx() - get 0-based rbuf index which corresponds to i-th linear index
+ *  @rbuf:  the rbuf_t holder
+ *  @idx:   0-based linear index
+ *
+ *  Returns 0-based circular index or -1 if out of bounds
+ */
+static inline int rbuf_l2ridx(rbuf_t *rbuf, int idx)
+{
+    if ( idx < 0 || idx >= rbuf->n ) return -1;
+    if ( idx >= rbuf->f )
+    {
+        int i = idx - rbuf->f;
+        if ( i >= rbuf->n ) return -1;
+        return i;
+    }
+    int i = rbuf->m - rbuf->f + idx;
+    if ( i >= rbuf->n ) return -1;
+    return i;
+}
+
+/**
+ *  rbuf_next() - get index of the next element in the round buffer
+ *  @rbuf:  the rbuf_t holder
+ *  @i:     pointer to the last rbuf index. Set to -1 before the first call.
+ *
+ *  Sets i to the next position in the buffer. The return value indicates if
+ *  the position points to a valid element (1) or if there are no more elements
+ *  after *i (0). When the end is reached, *i is set to the first element in the
+ *  buffer.
+ */
+static inline int rbuf_next(rbuf_t *rbuf, int *i)
+{
+    if ( !rbuf->n ) return 0;
+    if ( *i==-1 ) { *i = rbuf->f; return 1; }
+    int n = (rbuf->f <= *i) ? *i - rbuf->f + 1 : *i + rbuf->m - rbuf->f + 1;
+    if ( ++(*i) >= rbuf->m ) *i = 0;
+    if ( n < rbuf->n ) return 1;
+    *i = rbuf->f;
+    return 0;
+}
+/**
+ *  rbuf_prev() - get index of the previous element in the round buffer
+ *  @rbuf:  the rbuf_t holder
+ *  @i:     pointer to the last rbuf index. Set to -1 before the first call.
+ *
+ *  Sets i to the previous position in the buffer. The return value indicates if
+ *  the position points to a valid element (1) or if there are no more elements
+ *  before *i (0).
+ */
+static inline int rbuf_prev(rbuf_t *rbuf, int *i)
+{
+    if ( !rbuf->n || *i==rbuf->f ) return 0;
+    if ( *i==-1 )
+    {
+        *i = rbuf_last(rbuf);
+        return 1;
+    }
+    if ( --(*i) < 0 ) *i = rbuf->m - 1;
+    return 1;
+}
+/**
+ *  rbuf_prepend() - register new element at the start of the round buffer
+ *  @rbuf:  the rbuf_t holder
+ *
+ *  Returns index of the newly inserted element.
+ */
+static inline int rbuf_prepend(rbuf_t *rbuf)
+{
+    if ( rbuf->n < rbuf->m ) rbuf->n++;
+
+    rbuf->f = rbuf->f > 0 ? rbuf->f - 1 : rbuf->m - 1;
+    return rbuf->f;
+}
+/**
+ *  rbuf_append() - register new element at the end of the round buffer
+ *  @rbuf:  the rbuf_t holder
+ *
+ *  Returns index of the newly inserted element.
+ */
+static inline int rbuf_append(rbuf_t *rbuf)
+{
+    if ( rbuf->n < rbuf->m )
+    {
+        rbuf->n++;
+        int i = rbuf->f + rbuf->n;
+        return i <= rbuf->m ? i - 1 : i - rbuf->m - 1;
+    }
+
+    rbuf->f++;
+    if ( rbuf->f >= rbuf->m )
+    {
+        rbuf->f = 0;
+        return rbuf->m - 1;
+    }
+    return rbuf->f - 1;
+}
+/**
+ *  rbuf_shift() - removes first element from the buffer
+ *  @rbuf:  the rbuf_t holder
+ *
+ *  Returns index of the removed element.
+ */
+static inline int rbuf_shift(rbuf_t *rbuf)
+{
+    if ( !rbuf->n ) return -1;
+    int ret = rbuf->f;
+    rbuf->f++;
+    if ( rbuf->f >= rbuf->m ) rbuf->f = 0;
+    rbuf->n--;
+    return ret;
+}
+/**
+ *  rbuf_shift_n() - removes first n elements from the buffer
+ *  @rbuf:  the rbuf_t holder
+ *  @n:     number of elements to remove
+ */
+static inline void rbuf_shift_n(rbuf_t *rbuf, int n)
+{
+    if ( n >= rbuf->n )
+    {
+        rbuf->n = rbuf->f = 0;
+        return;
+    }
+    rbuf->n -= n;
+    rbuf->f += n;
+    if ( rbuf->f >= rbuf->m ) rbuf->f -= rbuf->m;
+}
+
+/**
+ *  rbuf_expand0() - expand round buffer and set the newly allocated elements to 0
+ *  @rbuf:      the rbuf holder
+ *  @type_t:    data type
+ *  @n:         requested number of elements
+ *  @data:      data array to be realloced
+ *
+ *  Note: The new array is linearized and leaves the rbuf.f offset untouched,
+ *  thus the size of the new buffer is determined by the current position.
+ */
+#define rbuf_expand0(rbuf,type_t,n,data) \
+{ \
+    if ( n > (rbuf)->m ) \
+    { \
+        int m = n + (rbuf)->f; \
+        m--, m|=m>>1, m|=m>>2, m|=m>>4, m|=m>>8, m|=m>>16, m++; /* kroundup32 */ \
+        data = (type_t*) realloc(data, sizeof(type_t)*m); \
+        type_t *ptr = data; \
+        memset(ptr+(rbuf)->m,0,sizeof(type_t)*(m-(rbuf)->m)); \
+        if ( (rbuf)->f ) \
+        { \
+            memcpy(ptr+(rbuf)->m,ptr,sizeof(type_t)*(rbuf)->f); \
+            memset(ptr,0,sizeof(type_t)*(rbuf)->f); \
+        } \
+        (rbuf)->m = m; \
+    } \
+}
+
+/**
+ *  rbuf_remove_kth() - remove k-th rbuf element (0-based) and memmove the data block
+ *  @rbuf:      the rbuf holder
+ *  @type_t:    data type
+ *  @k:         k-th element to remove
+ *  @data:      data array to be modified
+ */
+#define rbuf_remove_kth(rbuf, type_t, kth, data) \
+{ \
+    int k = rbuf_kth(rbuf, kth); \
+    if ( k < (rbuf)->f )    /* shrink from back */ \
+    { \
+        int l = rbuf_kth(rbuf, -1); \
+        if ( k < l ) \
+        { \
+            type_t tmp = (data)[k]; \
+            memmove(data+k, data+k+1, (l - k)*sizeof(type_t)); \
+            (data)[l] = tmp; \
+        } \
+        (rbuf)->n--; \
+    } \
+    else                    /* shrink from front */ \
+    { \
+        if ( k > (rbuf)->f ) \
+        { \
+            type_t tmp = (data)[k]; \
+            memmove(&data[(rbuf)->f+1], &data[(rbuf)->f], (k - (rbuf)->f)*sizeof(type_t)); \
+            (data)[(rbuf)->f] = tmp; \
+        } \
+        (rbuf)->f++; \
+        (rbuf)->n--; \
+        if ( (rbuf)->f == (rbuf)->m ) (rbuf)->f = 0; \
+    } \
+}
+
+#endif
diff --git a/shared/package-files/e6/e6ddce03c185d9099f51a6fb1ae8f82050eb9d1f60da380cfd2b84c5c2f59bf8/__init__.cpython-311.pyc b/shared/package-files/e6/e6ddce03c185d9099f51a6fb1ae8f82050eb9d1f60da380cfd2b84c5c2f59bf8/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2fcda6ef81222f8cf7148a5d546e5acbb177d6c
Binary files /dev/null and b/shared/package-files/e6/e6ddce03c185d9099f51a6fb1ae8f82050eb9d1f60da380cfd2b84c5c2f59bf8/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6e489b1f4c62941c2f07c3b6ccc10f186d578fcf6c6a8fa6ec67de88a2b5448/__init__.cpython-311.pyc b/shared/package-files/e6/e6e489b1f4c62941c2f07c3b6ccc10f186d578fcf6c6a8fa6ec67de88a2b5448/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35962ffbaf0c1940280d8d9cae14ef145f4e1f31
Binary files /dev/null and b/shared/package-files/e6/e6e489b1f4c62941c2f07c3b6ccc10f186d578fcf6c6a8fa6ec67de88a2b5448/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6e4ac8b023f8f1058c2e4eef7314143c34047488932c6a9b3f938cf1e04829a/fft_hfftn.h b/shared/package-files/e6/e6e4ac8b023f8f1058c2e4eef7314143c34047488932c6a9b3f938cf1e04829a/fft_hfftn.h
new file mode 100644
index 0000000000000000000000000000000000000000..cafd33c4878dc643969046c39afe1611cc70649b
--- /dev/null
+++ b/shared/package-files/e6/e6e4ac8b023f8f1058c2e4eef7314143c34047488932c6a9b3f938cf1e04829a/fft_hfftn.h
@@ -0,0 +1,92 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Function.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+
+#include 
+
+namespace at {
+
+
+// aten::fft_hfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+inline at::Tensor fft_hfftn(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
+}
+namespace symint {
+  template >>
+  at::Tensor fft_hfftn(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
+  }
+}
+
+// aten::fft_hfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+inline at::Tensor fft_hfftn_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn::call(self, s, dim, norm);
+}
+namespace symint {
+  template >>
+  at::Tensor fft_hfftn(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn::call(self, s, dim, norm);
+  }
+}
+
+// aten::fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fft_hfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & fft_hfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
+  }
+}
+
+// aten::fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fft_hfftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) {
+    return at::_ops::fft_hfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & fft_hfftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) {
+    return at::_ops::fft_hfftn_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
+  }
+}
+
+// aten::fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fft_hfftn_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn_out::call(self, s, dim, norm, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & fft_hfftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::OptionalIntArrayRef dim=::std::nullopt, ::std::optional norm=::std::nullopt) {
+    return at::_ops::fft_hfftn_out::call(self, s, dim, norm, out);
+  }
+}
+
+// aten::fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & fft_hfftn_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) {
+    return at::_ops::fft_hfftn_out::call(self, s, dim, norm, out);
+}
+namespace symint {
+  template >>
+  at::Tensor & fft_hfftn_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, ::std::optional norm, at::Tensor & out) {
+    return at::_ops::fft_hfftn_out::call(self, s, dim, norm, out);
+  }
+}
+
+}
diff --git a/shared/package-files/e6/e6e75879147ab0169b797d429aec3ae7f5d939ccfb13bc491531a3be4e62ff03/matmul_ops.h b/shared/package-files/e6/e6e75879147ab0169b797d429aec3ae7f5d939ccfb13bc491531a3be4e62ff03/matmul_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..57e6cf866db989a99ec384ed4c0526dfbe2a3a47
--- /dev/null
+++ b/shared/package-files/e6/e6e75879147ab0169b797d429aec3ae7f5d939ccfb13bc491531a3be4e62ff03/matmul_ops.h
@@ -0,0 +1,40 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API matmul {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::matmul";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "matmul(Tensor self, Tensor other) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
+};
+
+struct TORCH_API matmul_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::matmul";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e6ec0bd02d173bbaa9157b39c7bf820fbd66be8ffc55e1195be9f130a4352c88/symbolic_convert.py b/shared/package-files/e6/e6ec0bd02d173bbaa9157b39c7bf820fbd66be8ffc55e1195be9f130a4352c88/symbolic_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fc7454af6ef38f29a3f49618050f7aafefd006e
--- /dev/null
+++ b/shared/package-files/e6/e6ec0bd02d173bbaa9157b39c7bf820fbd66be8ffc55e1195be9f130a4352c88/symbolic_convert.py
@@ -0,0 +1,4202 @@
+# mypy: allow-untyped-defs
+
+"""
+Core module responsible for converting Python bytecode into TorchDynamo's symbolic execution format.
+
+This module implements the bytecode-level tracing system that allows TorchDynamo to analyze
+and transform Python code. It converts Python bytecode instructions into a symbolic format
+that tracks the flow of tensors and other values through the program.
+
+Key components:
+- InstructionTranslatorBase: Base class for converting bytecode to symbolic execution
+- InstructionTranslator: Main translator for function bytecode
+- InliningInstructionTranslator: Handles inlining of called functions
+- SpeculationLog: Manages state for speculative execution and rollback
+
+The symbolic conversion process handles:
+- Control flow (loops, conditionals, etc.)
+- Function inlining and call stack management
+- Tracking of program values and side effects
+- Graph breaks and resumption points
+- Exception handling and stack frame management
+
+This is a core part of TorchDynamo's tracing system that enables ahead-of-time
+optimization of PyTorch programs.
+"""
+
+import collections
+import collections.abc
+import contextlib
+import copy
+import dataclasses
+import dis
+import functools
+import importlib
+import inspect
+import itertools
+import linecache
+import logging
+import operator
+import re
+import sys
+import threading
+import traceback
+import types
+import typing
+import weakref
+from typing import Any, Callable, cast, NoReturn, Optional, Union
+from unittest.mock import patch
+
+import torch
+import torch._logging
+from torch._dynamo.exc import TensorifyScalarRestartAnalysis
+from torch._guards import tracing, TracingContext
+from torch.fx.experimental.symbolic_shapes import guard_bool
+from torch.utils._functools import cache_method
+
+from . import (
+    config,
+    exc,
+    graph_break_hints,
+    logging as torchdynamo_logging,
+    trace_rules,
+    variables,
+)
+from .bytecode_analysis import (
+    get_indexof,
+    JUMP_OPNAMES,
+    livevars_analysis,
+    propagate_line_nums,
+)
+from .bytecode_transformation import (
+    cleaned_instructions,
+    create_call_function,
+    create_instruction,
+    create_jump_absolute,
+    create_swap,
+    get_code_keys,
+    Instruction,
+    is_generator,
+    unique_id,
+)
+from .code_context import code_context
+from .codegen import PyCodegen
+from .exc import (
+    ArgsMismatchError,
+    BackendCompilerFailed,
+    collapse_resume_frames,
+    format_graph_break_message,
+    get_stack_above_dynamo,
+    unimplemented_v2,
+    Unsupported,
+)
+from .funcname_cache import get_funcname
+from .guards import GuardBuilder, install_guard
+from .output_graph import GraphCompileReason, OutputGraph
+from .replay_record import DummyModule, ExecutionRecorder
+from .resume_execution import ContinueExecutionCache, ReenterWith
+from .source import (
+    AttrSource,
+    DictGetItemSource,
+    GlobalSource,
+    GlobalWeakRefSource,
+    LocalCellSource,
+    LocalSource,
+    Source,
+)
+from .trace_rules import is_builtin_constant, is_forbidden
+from .utils import (
+    counters,
+    get_fake_value,
+    get_instruction_source_311,
+    get_metrics_context,
+    graph_break_dup_warning_checker,
+    istype,
+    LazyString,
+    proxy_args_kwargs,
+)
+from .variables.base import typestr, ValueMutationNew, VariableTracker
+from .variables.builder import FrameStateSizeEntry, wrap_fx_proxy
+from .variables.builtin import BuiltinVariable
+from .variables.constant import ConstantVariable
+from .variables.ctx_manager import (
+    ContextWrappingVariable,
+    GenericContextWrappingVariable,
+    WithExitFunctionVariable,
+)
+from .variables.dicts import ConstDictVariable, SetVariable
+from .variables.functions import (
+    BaseUserFunctionVariable,
+    LocalGeneratorFunctionVariable,
+    LocalGeneratorObjectVariable,
+    NestedUserFunctionVariable,
+    SkipFunctionVariable,
+    UserFunctionVariable,
+    UserMethodVariable,
+)
+from .variables.iter import MAX_ITERATOR_LIMIT
+from .variables.lazy import LazyVariableTracker
+from .variables.lists import (
+    BaseListVariable,
+    ListIteratorVariable,
+    ListVariable,
+    SliceVariable,
+    TupleVariable,
+)
+from .variables.misc import (
+    CellVariable,
+    ExceptionVariable,
+    GetAttrVariable,
+    NullVariable,
+    PythonModuleVariable,
+    UnknownVariable,
+)
+from .variables.nn_module import NNModuleVariable
+from .variables.tensor import supported_comparison_ops, SymNodeVariable, TensorVariable
+from .variables.torch_function import (
+    SymbolicTorchFunctionState,
+    TorchFunctionModeVariable,
+)
+from .variables.user_defined import (
+    RemovableHandleVariable,
+    UserDefinedClassVariable,
+    UserDefinedExceptionClassVariable,
+    UserDefinedExceptionObjectVariable,
+    UserDefinedObjectVariable,
+)
+
+
+log = logging.getLogger(__name__)
+graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks")
+trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call")
+trace_source_log = torch._logging.getArtifactLogger(__name__, "trace_source")
+trace_bytecode_log = torch._logging.getArtifactLogger(__name__, "trace_bytecode")
+tls = threading.local()
+compare_op_handlers: dict[str, Any] = {
+    k: BuiltinVariable(v).call_function for k, v in supported_comparison_ops.items()
+}
+handle_contains = BuiltinVariable(operator.contains).call_function
+handle_not = BuiltinVariable(operator.not_).call_function
+compare_op_handlers["in"] = lambda tx, args, _: handle_contains(
+    tx, [*reversed(args)], {}
+)
+compare_op_handlers["not in"] = lambda tx, args, _: handle_not(
+    tx, [handle_contains(tx, [*reversed(args)], {})], {}
+)
+
+
+PT2_ISSUE_TRACKER_URL = "https://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.yml"
+
+
+@functools.cache
+def _import_module(name: str) -> types.ModuleType:
+    """
+    Import the named module and cache the result. importlib.import_module()
+    seems to do some filesystem checking to validate the name so not caching
+    this can be slow.
+    """
+    return importlib.import_module(name)
+
+
+@dataclasses.dataclass
+class SpeculationEntry:
+    filename: str
+    lineno: int
+    instruction_pointer: int
+    inst: Instruction  # for debugging only
+    failed: bool = False
+    reason: Optional[GraphCompileReason] = None
+
+    def fail_and_restart_analysis(self):
+        """
+        Start tracing of the current frame over again, and don't take this branch.
+        """
+        self.failed = True
+        if self.reason is not None:
+            restart_reason = self.reason.reason
+        else:
+            restart_reason = "Unknown fail_and_restart_analysis"
+        raise exc.SpeculationRestartAnalysis(restart_reason=restart_reason)
+
+
+@dataclasses.dataclass
+class SpeculationLog:
+    """
+    SpeculationLog replaces the prior copy_graphstate/restore_graphstate
+    checkpointing.  Rather than saving/restoring state, we restart the
+    dynamo conversion process over from the beginning -- but when we
+    hit the start of the speculation that failed, we instead generate
+    a graph break.
+    """
+
+    entries: list[SpeculationEntry] = dataclasses.field(default_factory=list)
+    index: int = 0
+
+    def restart(self):
+        self.index = 0
+
+    def clear(self):
+        self.entries.clear()
+        self.index = 0
+
+    def next(
+        self, filename: str, lineno: int, instruction_pointer, inst
+    ) -> SpeculationEntry:
+        """
+        Lookup or create a SpeculationEntry() that is shared across
+        RestartAnalysis calls.  Args are used only for debug checks.
+        """
+        if len(self.entries) == self.index:
+            self.entries.append(
+                SpeculationEntry(filename, lineno, instruction_pointer, inst)
+            )
+        entry = self.entries[self.index]
+        prev_entry_msg = ""
+        if self.index != 0:
+            prev_entry = self.entries[self.index - 1]
+            prev_entry_msg = (
+                f"Previous instruction: {prev_entry.filename}:{prev_entry.lineno}"
+                f"({prev_entry.inst.opname} @ {prev_entry.instruction_pointer})\n"
+            )
+        if not (
+            entry.instruction_pointer == instruction_pointer
+            and entry.filename == filename
+            and entry.lineno == lineno
+        ):
+            raise SpeculationLogDivergence(
+                f"""
+SpeculationLog diverged at index {self.index} (log had {len(self.entries)} entries):
+- Expected: {entry.filename}:{entry.lineno} ({entry.inst.opname} at ip={entry.instruction_pointer})
+- Actual: {filename}:{lineno} ({inst.opname} at ip={instruction_pointer})
+{prev_entry_msg}
+There are two usual reasons why this may have occured:
+- When Dynamo analysis restarted, the second run took a different path than
+  the first.  If this occurred, the previous instruction is the critical instruction that
+  behaved differently.
+- Speculation entries are only added under certain conditions (as seen in
+  step()), e.g., there must exist operators in the graph; those conditions may
+  have changed on restart.
+
+If this divergence was intentional, clear the speculation log before restarting (do NOT
+do this for graph breaks, you will infinite loop).
+
+Otherwise, please submit a bug report, ideally including the contents of TORCH_LOGS=+dynamo
+"""
+            )
+        self.index += 1
+        return entry
+
+
+@dataclasses.dataclass
+class LocalState:
+    automatic_dynamic: dict[str, FrameStateSizeEntry] = dataclasses.field(
+        default_factory=dict
+    )
+
+    def render(self) -> str:
+        return "\n".join(
+            f"{k}: {v.render()}" for k, v in self.automatic_dynamic.items()
+        )
+
+
+# Mutable box that is shared across restarts
+@dataclasses.dataclass
+class DistributedState:
+    compile_pg: Any
+    local_state: LocalState
+    all_states: Optional[list[LocalState]] = None
+
+
+class TensorifyState:
+    # These are the set of string symfloats names (eg. "zf0") that we collect
+    # from the tensorify_python_scalars.py joint fx pass to inform us about
+    # which float inputs we should specialize when we restart analysis.
+    force_specializations: set[str] = set()
+
+    @classmethod
+    def specialize(cls, index: str) -> None:
+        cls.force_specializations.add(index)
+
+    @classmethod
+    def should_specialize(cls, index: str) -> bool:
+        return index in cls.force_specializations
+
+    @classmethod
+    def clear(cls) -> None:
+        cls.force_specializations.clear()
+
+    @classmethod
+    def empty(cls) -> bool:
+        return len(cls.force_specializations) == 0
+
+
+@functools.lru_cache(None)
+def _step_logger():
+    return torchdynamo_logging.get_step_logger(log)
+
+
+@contextlib.contextmanager
+def save_and_restart_speculation_log(tx: "InstructionTranslatorBase"):
+    # When reconstructing a generator after a graph break, we advance it until
+    # it is fully exhausted. This process adds new entries to the speculation
+    # log that were not previously observed. Without temporarily clearing the
+    # speculation log, this could lead to a divergence error.
+
+    entries = tx.speculation_log.entries
+    index = tx.speculation_log.index
+    try:
+        tx.speculation_log.entries = []
+        tx.speculation_log.index = 0
+        yield
+    finally:
+        tx.speculation_log.entries = entries
+        tx.speculation_log.index = index
+
+
+@contextlib.contextmanager
+def temporarely_allow_writes_to_output_graph(tx: "InstructionTranslatorBase"):
+    try:
+        tmp = tx.output.should_exit
+        tx.output.should_exit = False
+        yield
+    finally:
+        tx.output.should_exit = tmp
+
+
+@dataclasses.dataclass
+class BlockStackEntry:
+    # Current instruction that pushes something to block_stack
+    inst: Instruction
+    target: Instruction
+    stack_index: int
+    with_context: Optional[
+        Union[ContextWrappingVariable, GenericContextWrappingVariable]
+    ] = None
+
+    def can_restore(self):
+        return self.with_context is not None
+
+    def resume_fn(self):
+        assert self.stack_index is not None
+        if (
+            self.with_context
+            and hasattr(self.with_context, "target_values")
+            and self.with_context.target_values
+        ):
+            return ReenterWith(
+                self.stack_index - 1, tuple(self.with_context.target_values)
+            )
+        else:
+            return ReenterWith(self.stack_index - 1)
+
+    def exit(self, tx, is_graph_break):
+        assert self.with_context is not None
+        if (
+            is_graph_break and self.with_context.exit_on_graph_break()
+        ) or not is_graph_break:
+            return self.with_context.exit(tx)
+
+
+class SpeculationLogDivergence(AssertionError):
+    pass
+
+
+class ReturnValueOp(Exception):
+    pass
+
+
+class YieldValueOp(Exception):
+    """
+    Signal to the symbolic tracer to stop and return control flow to the
+    caller
+    """
+
+
+def stack_op(fn: typing.Callable[..., object]):
+    nargs = len(inspect.signature(fn).parameters)
+    fn_var = BuiltinVariable(fn)
+
+    @functools.wraps(fn)
+    def impl(self: "InstructionTranslator", inst: Instruction):
+        self.push(fn_var.call_function(self, self.popn(nargs), {}))
+
+    return impl
+
+
+def _detect_and_normalize_assert_statement(
+    self: "InstructionTranslatorBase",
+    truth_fn: typing.Callable[[object], bool],
+    push: bool,
+):
+    # Detect if this jump instruction is assert and normalize the assert
+    # by pushing dummy error message when nothing is given.
+    #
+    # Python 3.9 assertion is in following format:
+    # 18 POP_JUMP_IF_TRUE       28
+    # 20 LOAD_ASSERTION_ERROR
+    # 22 LOAD_CONST               3 ('Assert message') -> optional instruction
+    # 24 CALL_FUNCTION            1                    -> optional instruction
+    # 26 RAISE_VARARGS
+    #
+    # Python 3.8 assertion is in following format:
+    # 18 POP_JUMP_IF_TRUE       28
+    # 20 LOAD_GLOBAL              0 (Assertion type)
+    # 22 LOAD_CONST               3 ('Assert message') -> optional instruction
+    # 24 CALL_FUNCTION            1                    -> optional instruction
+    # 26 RAISE_VARARGS            1
+
+    if (truth_fn is not operator.truth) or push:
+        return False
+
+    assert isinstance(self.instruction_pointer, int)
+    current_instruction_pointer = self.instruction_pointer
+    inst = self.instructions[current_instruction_pointer]
+    # Detect LOAD_ASSERTION_ERROR or LOAD_GLOBAL 0
+    if inst.opname != "LOAD_ASSERTION_ERROR":
+        return False
+
+    current_instruction_pointer += 1
+
+    # Use dummy error message if its hard to extract
+    error_msg = "assertion error"
+
+    inst = self.instructions[current_instruction_pointer]
+    # DETECT RAISE_VARARGS or LOAD CONST
+    if inst.opname == "LOAD_CONST":
+        if not isinstance(inst.argval, str):
+            return False
+        error_msg = inst.argval
+
+        # if it is LOAD_CONSTANT, it must be followed by CALL_FUNCTION
+        # (PRECALL for Python 3.11, CALL for Python 3.12+)
+        current_instruction_pointer += 1
+        inst = self.instructions[current_instruction_pointer]
+        if inst.opname not in ("CALL_FUNCTION", "PRECALL", "CALL"):
+            return False
+
+        # for Python 3.11, PRECALL should be followed by CALL, then RAISE_VARARGS
+        # for Python != 3.11, CALL_FUNCTION/CALL should be followed by RAISE_VARARGS
+        current_instruction_pointer += 1
+        if inst.opname == "PRECALL":
+            current_instruction_pointer += 1
+        inst = self.instructions[current_instruction_pointer]
+
+    if inst.opname != "RAISE_VARARGS":
+        return False
+
+    self.push(ConstantVariable.create(error_msg))
+
+    return True
+
+
+explain = False
+
+
+def log_graph_break(code_options, reason="", exc_info=False, user_stack=None):
+    if user_stack is None:
+        user_stack = torch._guards.TracingContext.extract_stack()
+
+    try:
+        frame_loc = (user_stack[-1].filename, user_stack[-1].lineno)
+    except IndexError:
+        # first instruction
+        frame_loc = (
+            code_options["co_filename"],
+            code_options["co_firstlineno"],
+        )
+
+    stack_above_dynamo_formatted = ""
+    if config.verbose:
+        stack_above_dynamo = get_stack_above_dynamo()
+        stack_above_dynamo_formatted = "".join(
+            traceback.format_list(stack_above_dynamo)
+        )
+    else:
+        user_stack = get_stack_above_dynamo() + user_stack
+        user_stack = collapse_resume_frames(user_stack)
+    user_stack_formatted = "".join(traceback.format_list(user_stack))
+    user_stack_trace = (
+        f"Graph break in user code at {frame_loc[0]}:{frame_loc[1]}\n"
+        f"Graph Break Reason: {reason}\n"
+        "User code traceback:\n"
+    )
+
+    if config.verbose:
+        user_stack_trace += (
+            f"{stack_above_dynamo_formatted}\n"
+            "========== most recent `torch.compile` tracing attempt started here ==========\n\n"
+            f"{user_stack_formatted}\n"
+            "NOTE: the most recent `torch.compile` tracing attempt might not be where you applied `torch.compile`! "
+            "This is due to how graph breaks are implemented - the optimized code object returned by Dynamo will call another "
+            "Dynamo-generated resume function and tracing is re-enabled by calling the resume function as a normal Python "
+            "function, which Dynamo intercepts as a top-level frame.\n"
+        )
+    else:
+        user_stack_trace += str(user_stack_formatted)
+
+    torch._logging.trace_structured(
+        "artifact",
+        metadata_fn=lambda: {
+            "name": "dynamo_graph_break_reason",
+            "encoding": "string",
+        },
+        payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc() if exc_info else ''}",
+    )
+
+    # torch._dynamo.explain() formats this a little nicer, and presents a slightly
+    # more actionable user code pointer
+    if (
+        graph_break_log.isEnabledFor(logging.DEBUG)
+        and not explain
+        and graph_break_dup_warning_checker.add(frame_loc)
+    ):
+        # This log line MUST contain the string "Graph break in user code",
+        # This log line is exercised from
+        #   python test/dynamo/test_exc.py -k test_graph_break_log
+        graph_break_log.debug(
+            user_stack_trace,
+        )
+    else:
+        # This log line MUST not contain the string "Graph break in user code",
+        # exercised by
+        #   python test/dynamo/test_misc.py -k test_duplicate_graph_break_log
+        graph_break_log.debug(
+            "Graph break (user stack suppressed due to duplicate graph break) in user code at %s:%s\nGraph Break Reason: %s",
+            frame_loc[0],
+            frame_loc[1],
+            reason,
+        )
+
+
+def generic_jump(truth_fn: typing.Callable[[object], bool], push: bool):
+    # graph break message fields for data dependent branching
+    _gb_type = "Data-dependent branching"
+    _explanation = (
+        "Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). "
+        "Dynamo does not support tracing dynamic control flow."
+    )
+    _hints = [
+        *graph_break_hints.FUNDAMENTAL,
+        "Use `torch.cond` to express dynamic control flow.",
+    ]
+
+    def jump_graph_break(self, inst, value, extra_msg=""):
+        log_graph_break(
+            self.code_options,
+            reason=format_graph_break_message(
+                gb_type=_gb_type,
+                context=f"attempted to jump with {value}",
+                explanation=_explanation,
+                hints=_hints,
+            ),
+        )
+        if not self.should_compile_partial_graph():
+            unimplemented_v2(
+                gb_type="Should not compile partial graph (data-dependent branching)",
+                context="",
+                explanation="Dynamo has determined when encountering data-dependent "
+                "branching (e.g. `if my_tensor.item() > 0:`) that it should not "
+                "compile the partial graph.",
+                hints=[],
+            )
+        # compile a partial subgraph prefix then jump into user code
+        if self.maybe_has_backedge():
+            msg = (
+                "Skipping frame because there is a graph break in a for/while loop\n"
+                f"{self.frame_summary()}"
+            )
+            log.info(msg)
+            raise exc.SkipFrame(msg)
+
+        self.push(value)
+        log.debug("generic_jump triggered compile")
+        self.output.compile_subgraph(
+            self,
+            reason=GraphCompileReason(
+                f"generic_jump {typestr(value)}{extra_msg}", [self.frame_summary()]
+            ),
+        )
+        self.pop()
+
+        if_next = self.create_call_resume_at(self.next_instruction)
+        if push:
+            self.push(value)
+        if_jump = self.create_call_resume_at(inst.target)
+
+        if sys.version_info >= (3, 13):
+            # 3.13 requires stack[-1] to be bool type
+            self.output.add_output_instructions([create_instruction("TO_BOOL")])
+
+        jump_inst = create_instruction(inst.opname, target=if_jump[0])
+        jump_inst.copy_positions(inst)
+        self.output.add_output_instructions([jump_inst] + if_next + if_jump)
+
+    def inner(self: "InstructionTranslatorBase", inst: Instruction):
+        value: VariableTracker = self.pop()
+        if (
+            config.rewrite_assert_with_torch_assert
+            and _detect_and_normalize_assert_statement(self, truth_fn, push)
+        ):
+            error_msg: VariableTracker = self.pop()
+            # Skip over things like `assert True`
+            if value.is_python_constant():
+                if bool(value.as_python_constant()):
+                    return self.jump(inst)
+                else:
+                    jump_graph_break(self, inst, value)
+
+            # TODO maybe should respect DtoH sync intention of users later??
+            # Manually insert torch._assert_async instead of python assert and jump over
+            # assert related instructions as we don't need them anymore.
+
+            # if we see Tensor as assert statement, no need to call scalar_tensor
+            if isinstance(value, TensorVariable):
+                self.output.create_proxy(
+                    "call_function",
+                    torch._assert_async,
+                    *proxy_args_kwargs((value, error_msg), {}),
+                )
+                self.jump(inst)
+                return
+
+            if isinstance(value, SymNodeVariable):
+                # if the assertion is normal shape expression.
+                # just install guard and bail out.
+                sym_expr = value.sym_num
+                if not isinstance(sym_expr, torch.SymBool):
+                    sym_expr = sym_expr != 0
+
+                result = torch.fx.experimental.symbolic_shapes.expect_true(sym_expr)
+                if not result:
+                    unimplemented_v2(
+                        gb_type="Assertion failed on symbolic shapes",
+                        context=str(sym_expr),
+                        explanation="",
+                        hints=[*graph_break_hints.USER_ERROR],
+                    )
+                self.jump(inst)
+                return
+
+            scalar_to_tensor_proxy = self.output.create_proxy(
+                "call_function", torch.scalar_tensor, *proxy_args_kwargs((value,), {})
+            )
+
+            scalar_to_tensor = wrap_fx_proxy(
+                self,
+                scalar_to_tensor_proxy,
+                example_value=get_fake_value(scalar_to_tensor_proxy.node, self),
+            )
+
+            self.output.create_proxy(
+                "call_function",
+                torch._assert_async,
+                *proxy_args_kwargs((scalar_to_tensor, error_msg), {}),
+            )
+            self.jump(inst)
+            return
+
+        if value.is_python_constant():
+            # ConstDictVariable is optimized to be very lazy about insertion of
+            # guards, so we have to manually insert a SEQUENCE_LENGTH guard
+            # here.
+            if isinstance(value, ConstDictVariable) and value.source:
+                install_guard(value.source.make_guard(GuardBuilder.SEQUENCE_LENGTH))
+            if truth_fn(value.as_python_constant()):
+                if push:
+                    self.push(value)
+                self.jump(inst)
+        elif (
+            isinstance(value, (TensorVariable)) and self.should_compile_partial_graph()
+        ):
+            jump_graph_break(self, inst, value)
+        elif isinstance(value, NNModuleVariable):
+            # Equivalent of "self.nn_module is not None"
+            mod = self.output.get_submodule(value.module_key)
+            if truth_fn(mod):
+                if push:
+                    self.push(value)
+                self.jump(inst)
+        elif isinstance(value, UserDefinedObjectVariable):
+            try:
+                x = value.var_getattr(self, "__bool__")  # type: ignore[arg-type]
+            except exc.ObservedAttributeError:
+                exc.handle_observed_exception(self)
+                # if __bool__ is missing, trying __len__ to infer a truth value.
+                try:
+                    x = value.var_getattr(self, "__len__")  # type: ignore[arg-type]
+                except exc.ObservedAttributeError:
+                    exc.handle_observed_exception(self)
+                    x = None
+
+            # __bool__ or __len__ is function
+            if isinstance(x, UserMethodVariable):
+                result = x.call_function(self, [], {})  # type: ignore[arg-type, assignment]
+                if isinstance(result, ConstantVariable) and isinstance(
+                    result.value, (bool, int)
+                ):
+                    if truth_fn(result.value):
+                        if push:
+                            self.push(value)
+                        self.jump(inst)
+                elif isinstance(result, SymNodeVariable):
+                    if result.evaluate_expr():
+                        if push:
+                            self.push(value)
+                        self.jump(inst)
+                else:
+                    unimplemented_v2(
+                        gb_type="Data-dependent branching with non-constant __bool__",
+                        context=f"method: {x}, result: {result}",
+                        explanation="Attempted to perform data-dependent branching on a user-defined "
+                        "object with a __bool__ method that did not return a constant.",
+                        hints=[],
+                    )
+            # __bool__ or __len__ is non-function or not existed in the user defined object
+            else:
+                if truth_fn(True):
+                    if push:
+                        self.push(value)
+                    self.jump(inst)
+        elif not isinstance(value, TensorVariable) and value.has_unpack_var_sequence(
+            self
+        ):
+            if truth_fn(len(value.unpack_var_sequence(self))):
+                if push:
+                    self.push(value)
+                self.jump(inst)
+        elif isinstance(value, SymNodeVariable):
+            try:
+                # if the user is branching on a SymBool, guard on it
+                # if the user has code like:
+                #    if size:
+                #        ...
+                # then they are just testing truthiness: guard that the expr != 0
+                if isinstance(value.sym_num, torch.SymBool):
+                    eval_result = value.evaluate_expr(self.output)
+                else:
+                    eval_result = guard_bool(value.sym_num != 0)
+            except exc.UserError as e:
+                if self.should_compile_partial_graph():
+                    return jump_graph_break(self, inst, value, extra_msg=f"\n{e}")
+                raise
+            if truth_fn(eval_result):
+                if push:
+                    self.push(value)
+                self.jump(inst)
+        elif isinstance(value, variables.BackwardHookVariable):
+            if truth_fn(True):
+                if push:
+                    self.push(value)
+                self.jump(inst)
+        else:
+            from .source import is_constant_source
+
+            if value.source is not None and is_constant_source(value.source):
+                if truth_fn(value.get_real_value()):  # type: ignore[attr-defined]
+                    if push:
+                        self.push(value)
+                    self.jump(inst)
+            else:
+                unimplemented_v2(
+                    gb_type=_gb_type,
+                    context=f"attempted to jump with {value}",
+                    explanation=_explanation,
+                    hints=_hints,
+                )
+
+    return inner
+
+
+def break_graph_if_unsupported(*, push):
+    def decorator(inner_fn):
+        @functools.wraps(inner_fn)
+        def wrapper(self: "InstructionTranslatorBase", inst: Instruction):
+            speculation = self.speculate()
+            if speculation.failed:
+                assert speculation.reason is not None
+                return handle_graph_break(self, inst, speculation.reason)
+            try:
+                return inner_fn(self, inst)
+            except Unsupported as excp:
+                if self.active_generic_context_managers:
+                    # We don't support graph break under GenericContextWrappingVariable,
+                    # If there is, we roll back to the checkpoint and fall back.
+                    excp.remove_from_stats()
+                    unimplemented_v2(
+                        gb_type="Graph break under GenericContextWrappingVariable",
+                        context=f"Active generic context managers: {self.active_generic_context_managers}",
+                        explanation="Attempted to graph break in an active context manager(s) that doesn't support graph breaking.",
+                        hints=[
+                            "Move the offending context manager(s) to outside the compiled region.",
+                            *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK,
+                        ],
+                        from_exc=excp,
+                    )
+
+                if isinstance(excp, exc.UncapturedHigherOrderOpError):
+                    raise
+
+                if not self.should_compile_partial_graph():
+                    raise
+
+                log_graph_break(
+                    self.code_options,
+                    exc_info=True,
+                    reason=str(excp),
+                    user_stack=excp.real_stack,
+                )
+
+                if self.maybe_has_backedge():
+                    msg = (
+                        "Skipping frame because there is a graph break in a for/while loop\n"
+                        f"{self.frame_summary()}"
+                    )
+                    log.info(msg)
+                    raise exc.SkipFrame(msg) from excp
+
+                excp.remove_from_stats()
+                excp.add_to_stats("graph_break")
+                speculation.reason = GraphCompileReason(excp.msg, excp.real_stack)
+            speculation.fail_and_restart_analysis()
+
+        def handle_graph_break(
+            self: "InstructionTranslatorBase",
+            inst: Instruction,
+            reason: GraphCompileReason,
+        ):
+            self.output.compile_subgraph(self, reason=reason)
+            cg = PyCodegen(self)
+            cleanup: list[Instruction] = []
+            # Reconstruct the context variable CLASS in the block stack
+            for b in self.block_stack:
+                # Don't exit any modes we have entered,
+                # output bytecode will mutate the tf mode stack accordingly
+                if isinstance(b.with_context, TorchFunctionModeVariable):
+                    cg.extend_output(
+                        b.resume_fn().try_except_torch_function_mode(
+                            cg.code_options, cleanup
+                        )
+                    )
+                    continue
+                assert b.with_context is not None
+                assert isinstance(b.with_context, (ContextWrappingVariable))
+                b.with_context.reconstruct_type(cg)
+                cg.extend_output(b.resume_fn().try_finally(cg.code_options, cleanup))
+            self.output.add_output_instructions(cg.get_instructions())
+            del cg
+
+            if sys.version_info >= (3, 11) and inst.opname == "CALL":
+                kw_names = (
+                    self.kw_names.as_python_constant()
+                    if self.kw_names is not None
+                    else ()
+                )
+                if len(kw_names) > 0:
+                    # KW_NAMES no longer used in 3.13
+                    assert sys.version_info < (3, 13)
+                    self.output.add_output_instructions(
+                        [create_instruction("KW_NAMES", argval=kw_names)]
+                    )
+                call_insts = create_call_function(inst.arg, False)
+                call_insts[-1].copy_positions(inst)
+                self.output.add_output_instructions(call_insts)
+            else:
+                # copy instruction, but without exception table data
+                assert inst.target is None
+                inst_copy = copy.copy(inst)
+                inst_copy.exn_tab_entry = None
+                self.output.add_output_instructions([inst_copy])
+
+            self.output.add_output_instructions(cleanup)
+
+            if (
+                sys.version_info >= (3, 11)
+                and sys.version_info < (3, 12)
+                and inst.opname == "CALL"
+            ):
+                # stack effect for PRECALL + CALL is split between the two instructions
+                stack_effect = dis.stack_effect(
+                    dis.opmap["PRECALL"], inst.arg
+                ) + dis.stack_effect(dis.opmap["CALL"], inst.arg)
+            else:
+                stack_effect = dis.stack_effect(inst.opcode, inst.arg)
+            self.popn(push - stack_effect)
+
+            for _ in range(push):
+                self.push(UnknownVariable())
+            self.output.add_output_instructions(
+                self.create_call_resume_at(self.next_instruction)
+            )
+
+        return wrapper
+
+    return decorator
+
+
+class BytecodeDistpatchTableMeta(type):
+    """Installs a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()"""
+
+    def __init__(cls, name, bases, dct) -> None:
+        super().__init__(name, bases, dct)
+
+        def _missing(opname, *args):
+            unimplemented_v2(
+                gb_type="Missing bytecode handler",
+                context=f"{opname} with args {args}",
+                explanation=f"Dynamo does not know how to handle the bytecode instruction `{opname}`.",
+                hints=[
+                    f"Do not trace code that produces the `{opname}` bytecode instruction "
+                    "(see https://docs.python.org/3/library/dis.html for bytecode semantics).",
+                    *graph_break_hints.SUPPORTABLE,
+                ],
+            )
+
+        dispatch_table = {
+            op: getattr(cls, opname, functools.partial(_missing, opname))
+            for opname, op in dis.opmap.items()
+        }
+        cls.dispatch_table = [dispatch_table.get(i) for i in range(2**8)]
+
+
+@dataclasses.dataclass
+class ExceptionStack:
+    """
+    Exception stack that it is shared among all InstructionTranslator instances
+    """
+
+    # Exception handling in CPython is a bit confusing and some of the bytecode
+    # have a slightly different behavior than what is is documented. While reading
+    # the documentation, is important to notice that the terms "current exception"
+    # and "stack" sometimes refers to a C variable with the same name and the
+    # exception stack, respectively.
+    #
+    # The lifetime of an exception is (Python 3.11+):
+    #  + tx._raise_exception_variable(...) := sets the current_exception variable
+    #  + PUSH_EXC_INFO := pushes the current_exception to the *exception stack*
+    #  + POP_EXCEPT := pops TOS from the *exception stack*
+
+    _exc_stack: list[VariableTracker] = dataclasses.field(default_factory=list)
+    _current_exception: Optional[VariableTracker] = dataclasses.field(default=None)
+
+    def clear_current_exception(self):
+        self._current_exception = None
+
+    def set_current_exception(self, val):
+        self._set_context_and_break_context_reference_cycle(val)
+        self._current_exception = val
+
+    def move_current_exception_to_stack(self):
+        assert self._current_exception is not None
+        self.append(self._current_exception)
+        self.clear_current_exception()
+
+    def get_current_exception(self):
+        assert self._current_exception is not None
+        return self._current_exception
+
+    def _set_context_recursive(self, val, prev_idx):
+        if (ctx := val.__context__) and type(ctx) is not ConstantVariable:
+            return val
+        if len(self._exc_stack) + prev_idx > 0:
+            prev = self._exc_stack[prev_idx]
+            self._set_context_recursive(prev, prev_idx - 1)
+            val.set_context(prev)
+        return val
+
+    def _break_context_reference_cycle(self, val):
+        # See test_exceptions::test_raise_does_not_create_context_chain_cycle
+        # Based on https://github.com/python/cpython/blob/e635bf2e49797ecb976ce45a67fce2201a25ca68/Python/errors.c#L207-L228
+        # As noted on CPython, this is O(chain length) but the context chains
+        # are usually very small
+        o = slow_o = val
+        slow_update_toggle = False  # floyd's algorithm for detecting cycle
+        while True:
+            context = o.__context__
+            if type(context) is ConstantVariable:  # context not set
+                break
+
+            if context is val:
+                o.set_context(ConstantVariable(None))
+                break
+
+            o = context
+            if o is slow_o:
+                # pre-existing cycle - all exceptions on the path were
+                # visited and checked
+                break
+
+            if slow_update_toggle:
+                slow_o = slow_o.__context__  # visited all exceptions
+            slow_update_toggle = not slow_update_toggle
+
+    def _set_context_and_break_context_reference_cycle(self, val):
+        # set Exception.__context__
+        self._set_context_recursive(val, len(self._exc_stack) - 1)
+        self._break_context_reference_cycle(val)
+
+    def pop(self):
+        return self._exc_stack.pop()
+
+    def append(self, val):
+        self._exc_stack.append(val)
+
+    def __len__(self):
+        return len(self._exc_stack)
+
+    def __getitem__(self, index):
+        return self._exc_stack[index]
+
+    def __str__(self):
+        return f"{self._exc_stack=} - {self._current_exception=}"
+
+    __repr__ = __str__
+
+
+class InstructionTranslatorBase(
+    metaclass=BytecodeDistpatchTableMeta,
+):
+    output: OutputGraph
+    symbolic_locals: dict[str, VariableTracker]
+    symbolic_globals: dict[str, VariableTracker]
+    symbolic_torch_function_state: SymbolicTorchFunctionState
+    stack: list[VariableTracker]
+    instruction_pointer: Optional[int]
+    current_instruction: Instruction
+    block_stack: list[BlockStackEntry]
+    lineno: int
+    kw_names: Optional[ConstantVariable]
+    accept_prefix_inst: bool
+    prefix_insts: list[Instruction]
+    inline_depth: int
+    inconsistent_side_effects: bool
+    current_speculation: Optional[SpeculationEntry]
+    dispatch_table: list[Any]
+    exn_vt_stack: ExceptionStack
+    exec_recorder: Optional[ExecutionRecorder]
+    strict_checks_fn: Optional[Callable[[VariableTracker], bool]]
+    start_point: Optional[int]
+
+    def mark_inconsistent_side_effects(self):
+        """
+        InstructionTranslator has encountered instructions which may cause
+        dynamo to see a different version of history from eager
+        See: https://github.com/pytorch/pytorch/issues/110765
+        """
+        self.inconsistent_side_effects = True
+
+    def maybe_has_backedge(self):
+        # This function employs a heuristic. It does not reliably detect a backedge.
+        # The heuristic is straightforward: starting from the current instruction and
+        # continuing to the end, if any jump instruction targets an instruction before
+        # the current one, there might be a backedge.
+
+        # Python 3.12 introduced changes to bytecode that group common paths in
+        # blockstacks (with or try...else) and allow for early returns. Consequently,
+        # there can be multiple RETURN_VALUE instructions. Another heuristic is to
+        # halt detection upon encountering the first RETURN_VALUE or RETURN_CONST.
+
+        # These heuristics can result in both false positives and negatives, but
+        # in either case, the Dynamo code remains valid. For false positives
+        # (where an edge is incorrectly marked as a backedge), Dynamo will
+        # perform a SkipFrame instead of potentially applying optimizations. For
+        # false negatives (where an edge that should be marked as a backedge
+        # isn't), multiple graphs may be generated if there's a break in the
+        # graph during a for loop. In general, its better to have fewer false
+        # negatives so that Dynamo does not skip the whole frame.
+
+        cur_offset = self.current_instruction.offset
+        assert self.instruction_pointer is not None
+        for inst in self.instructions[self.instruction_pointer :]:
+            if inst.opname in ("RETURN_VALUE", "RETURN_CONST"):
+                return False
+            if inst.opname in JUMP_OPNAMES:
+                jump_offset = inst.argval
+                if jump_offset < cur_offset:
+                    return True
+        return False
+
+    def cellvars(self):
+        if not hasattr(self, "_cellvars"):
+            self._cellvars = tuple(self.code_options["co_cellvars"] or [])
+            # An inlined function might depend on the cellvar of the parent
+            # function. So, recursively obtain parent cellvars.
+            if isinstance(self, InliningInstructionTranslator):
+                self._cellvars += self.parent.cellvars()
+        return self._cellvars
+
+    def freevars(self):
+        if not hasattr(self, "_freevars"):
+            self._freevars = tuple(self.code_options["co_freevars"] or [])
+            # An inlined function might depend on the freevar of the parent
+            # function. So, recursively obtain parent freevars.
+            if isinstance(self, InliningInstructionTranslator):
+                self._freevars += self.parent.freevars()
+        return self._freevars
+
+    def cell_and_freevars(self):
+        if not hasattr(self, "_cell_and_freevars"):
+            self._cell_and_freevars = self.cellvars() + self.freevars()
+        return self._cell_and_freevars
+
+    def prune_dead_locals(self):
+        # Only keep the locals that must remain on the stack.
+        reads = livevars_analysis(self.instructions, self.current_instruction)
+        self.symbolic_locals = {
+            k: v for k, v in self.symbolic_locals.items() if k in reads
+        }
+        # "Garbage collect the heap".
+        self.output.side_effects.prune_dead_object_new(self)
+
+    def call_function(
+        self,
+        fn: VariableTracker,
+        args: list[VariableTracker],
+        kwargs: dict[str, VariableTracker],
+    ):
+        assert isinstance(fn, VariableTracker)
+        assert isinstance(args, list)
+        assert isinstance(kwargs, dict)
+        assert all(
+            isinstance(x, VariableTracker)
+            for x in itertools.chain(args, kwargs.values())
+        )
+        inner_fn = None
+        if hasattr(fn, "value"):
+            inner_fn = fn.value
+        if hasattr(fn, "fn"):
+            inner_fn = fn.fn
+        if inner_fn and callable(inner_fn) and is_forbidden(inner_fn):
+            raise AssertionError(f"Attempt to trace forbidden callable {inner_fn}")
+        self.push(fn.call_function(self, args, kwargs))  # type: ignore[arg-type]
+
+    def inline_generator_function(self, fn, args, kwargs):
+        """
+        Redirect the call to the generator "call_function"
+        """
+        if not isinstance(fn, LocalGeneratorFunctionVariable):
+            fn = LocalGeneratorFunctionVariable(fn)
+        return fn.call_function(self, args, kwargs)
+
+    def inline_user_function_return(self, fn, args, kwargs):
+        """
+        A call to some user defined function by inlining it.
+        """
+        if config.enable_faithful_generator_behavior and is_generator(fn.get_code()):
+            return self.inline_generator_function(fn, args, kwargs)
+        else:
+            return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
+
+    def get_line_of_code_header(self, lineno=None):
+        if lineno is None:
+            lineno = self.lineno
+        inline_depth_str = (
+            f" (inline depth: {self.inline_depth})" if self.inline_depth > 0 else ""
+        )
+        funcname = get_funcname(self.f_code.co_filename, lineno)
+        funcname_str = "" if funcname is None else f" ({funcname})"
+        return f"{self.f_code.co_filename}:{lineno} in {self.f_code.co_name}{funcname_str}{inline_depth_str}"
+
+    def get_log_starts_line_log_str(self):
+        log_str = f"TRACE starts_line {self.get_line_of_code_header()}\n"
+        line = linecache.getline(self.f_code.co_filename, self.lineno).rstrip()
+        log_str += f"    {line}"
+        return log_str
+
+    def starts_line(self, lineno):
+        if self.lineno == lineno:
+            return
+        self.lineno = lineno
+        TracingContext.set_current_loc(
+            self.f_code.co_filename, lineno, self.f_code.co_name
+        )
+        from torch._logging.structured import dump_file
+
+        dump_file(self.f_code.co_filename)
+        if trace_source_log.isEnabledFor(logging.DEBUG):
+            trace_source_log.debug("%s", LazyString(self.get_log_starts_line_log_str))
+
+    def step(self):
+        """Process exactly one instruction, return False we should exit"""
+        ip = self.instruction_pointer
+        if ip is None:
+            return False
+        self.current_instruction = inst = self.instructions[ip]
+        self.instruction_pointer = ip + 1
+
+        if inst.starts_line:
+            self.starts_line(inst.starts_line)
+
+        if (
+            not self.stack
+            and self.should_compile_partial_graph()
+            and self.is_non_empty_graph()
+        ):
+            self.current_speculation = self.speculate()
+            if self.current_speculation.failed:
+                return self.step_graph_break(inst)
+
+        if trace_bytecode_log.isEnabledFor(logging.DEBUG):
+            trace_bytecode_log.debug(
+                "TRACE %s %s %s", inst.opname, inst.argval, self.stack
+            )
+
+        self.update_block_stack(inst)
+
+        try:
+            self.dispatch_table[inst.opcode](self, inst)
+            return not self.output.should_exit
+        except TensorifyScalarRestartAnalysis:
+            raise
+        except exc.ObservedException as e:
+            self.exception_handler(e)
+            return True
+        except (ReturnValueOp, YieldValueOp):
+            return False
+        except Unsupported:
+            if self.current_speculation is None:
+                log.debug("empty checkpoint")
+                raise
+            log.debug("step triggered compile", exc_info=True)
+
+        self.current_speculation.fail_and_restart_analysis()
+
+    if sys.version_info >= (3, 11):
+
+        def update_block_stack(self, inst):
+            # 3.11+ no longer uses a block stack, but we still keep track of one
+            # so that we know which contexts are currently active.
+            # For our purposes, all exception table entries with the same target
+            # are considered to be part of the same "block".
+            # NOTE: we only keep track of with blocks that are not contained in try blocks.
+            # This is because we will not create continuation functions on graph breaks in try blocks,
+            # but we may for with blocks. We do not push blocks here since
+            # with blocks are pushed when handling BEFORE_WITH.
+            entry = inst.exn_tab_entry
+            if entry:
+                # Detect when we have exited the top with block.
+                # The with blocks on the block stack are not enclosed in try
+                # blocks, so a with block's cleanup code should be in the
+                # previous with block (if any).
+                if (
+                    len(self.block_stack) >= 2
+                    and entry.target is not self.block_stack[-1].target
+                    and entry.target is self.block_stack[-2].target
+                ):
+                    # exit the current block
+                    self.block_stack.pop()
+            else:
+                # no longer in any block
+                # It is possible for NOPs to be between two instructions
+                # in the same block, but the NOPs are not covered by an
+                # exception table entry. In this case, assume that we
+                # are still in the same block.
+                # In 3.12+, JUMP_BACKWARD might also not be covered by
+                # an exception table entry, so we also assume that we
+                # are still in the same block. It is probably safe to do
+                # this in 3.11, even though we haven't encountered this case before.
+                if self.block_stack and inst.opname not in ("NOP", "JUMP_BACKWARD"):
+                    # If we really escape from a block and the current
+                    # instruction is not in another block, then there
+                    # should be no other nested blocks that we are in.
+                    assert len(self.block_stack) == 1
+                    self.block_stack.pop()
+
+    else:
+
+        def update_block_stack(self, inst):
+            pass
+
+    @property
+    def next_instruction(self):
+        return self.instructions[self.instruction_pointer]  # type: ignore[index]
+
+    def step_graph_break(self, continue_inst):
+        # generate code from checkpoint
+        assert not self.output.output_instructions
+        assert self.current_speculation is not None
+        self.output.compile_subgraph(
+            self,
+            partial_convert=True,
+            reason=GraphCompileReason("step_unsupported", [self.frame_summary()]),
+        )
+        self.output.add_output_instructions(
+            [create_jump_absolute(continue_inst)] + self.instructions
+        )
+
+    def run_ctx_mgr(self):
+        # NB: Don't push the top level frame summary; set_current_loc will
+        # take care of it.  However, DO make sure we attach real_stack to
+        # exceptions
+        return TracingContext.current_frame(None)
+
+    def run(self):
+        with self.run_ctx_mgr():
+            try:
+                self.output.push_tx(self)
+                self.start_point = self.instruction_pointer
+                while self.step():
+                    pass
+            except TensorifyScalarRestartAnalysis:
+                raise
+            except BackendCompilerFailed:
+                raise
+            except RuntimeError as e:
+                if hasattr(e, "msg") and "Data-dependent" in e.msg:
+                    readable_graph = torch.fx.GraphModule(
+                        self.output.nn_modules, self.output.graph
+                    ).print_readable(
+                        print_output=False, include_stride=True, include_device=True
+                    )
+                    e.partial_fx_graph = readable_graph  # type: ignore[attr-defined]
+                    raise
+
+                raise
+            except Exception as e:
+                if self.exec_recorder:
+                    e.exec_record = self.exec_recorder.get_record()  # type: ignore[attr-defined]
+
+                raise
+            finally:
+                self.output.pop_tx()
+                # Cleanup the outputGraph to delete the held tensors. We perform the
+                # cleanup only for InstructionTranslator and not
+                # InliningInstructionTranslator. The InliningInstructionTranslator
+                # mutates the output object and is restored to original state if
+                # there was an exception.
+                if isinstance(self, InstructionTranslator):
+                    self.output.cleanup()
+
+    def push(self, val: Optional[VariableTracker]):
+        assert val is None or isinstance(val, VariableTracker), (
+            f"push expects VariableTracker, got {typestr(val)}"
+        )
+        self.stack.append(val)  # type: ignore[arg-type]
+
+    def push_many(self, vals: list[VariableTracker]):
+        for val in vals:
+            self.push(val)
+
+    def pop(self) -> VariableTracker:
+        return self.stack.pop()
+
+    def popn(self, n: int) -> list[VariableTracker]:
+        return [*reversed([self.pop() for _ in range(n)])]
+
+    def LOAD_FAST(self, inst):
+        name = inst.argval
+        if self.exec_recorder and name in self.f_locals:
+            self.exec_recorder.add_local_var(name, self.f_locals[name])
+
+        try:
+            self.push(self.symbolic_locals[name].unwrap())
+        except KeyError:
+            if name.startswith("."):
+                try:
+                    # This happens in dict/list comprehensions
+                    new_name = name.replace(".", "implicit")
+                    self.push(self.symbolic_locals[new_name])
+                except KeyError:
+                    unimplemented_v2(
+                        gb_type="Attempted to read undefined local variable (implicit)",
+                        context=f"LOAD_FAST {name}",
+                        explanation=f"Could not find an implicit local variable with name `{name}`",
+                        hints=[
+                            "This happens in dict/list comprehensions",
+                            *graph_break_hints.USER_ERROR,
+                        ],
+                    )
+            else:
+                unimplemented_v2(
+                    gb_type="Attempted to read undefined local variable",
+                    context=f"LOAD_FAST {name}",
+                    explanation=f"Could not find a local variable with name `{name}`",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+
+        # for continuation functions
+        if name.startswith("___stack"):
+            self.symbolic_locals.pop(name)
+
+    def LOAD_DEREF(self, inst):
+        assert inst.argval in self.cell_and_freevars()
+        cell = self.symbolic_locals[inst.argval]
+        contents_var = self.output.side_effects.load_cell(cell)
+        self.push(contents_var)
+
+        if self.exec_recorder and inst.argval in self.f_locals:
+            self.exec_recorder.add_local_var(inst.argval, self.f_locals[inst.argval])
+
+    def STORE_FAST(self, inst):
+        name = inst.argval
+        loaded_vt = self.pop()
+        loaded_vt.set_name_hint(name)
+        self.symbolic_locals[name] = loaded_vt
+
+    def DELETE_FAST(self, inst):
+        del self.symbolic_locals[inst.argval]
+
+    def STORE_DEREF(self, inst):  # type: ignore[override]
+        assert inst.argval in self.cell_and_freevars()
+        cell = self.symbolic_locals[inst.argval]
+        val = self.pop()
+        self.output.side_effects.store_cell(cell, val)
+
+        assert isinstance(cell, CellVariable)  # tame mypy
+        if cell.local_name is not None:
+            val.set_name_hint(cell.local_name)  # type: ignore[attr-defined]
+
+    LOAD_CLOSURE = LOAD_FAST
+
+    def _load_const(self, inst):
+        i = inst.arg
+        if i is None:
+            return ConstantVariable.create(value=inst.argval)
+        val = self._constants_cache[i]
+        if not val:
+            self._constants_cache[i] = val = ConstantVariable.create(value=inst.argval)
+        return val
+
+    def LOAD_CONST(self, inst):
+        self.push(self._load_const(inst))
+
+    def _load_global(self, inst):
+        name = inst.argval
+
+        if self.exec_recorder:
+            if name in self.f_globals:
+                self.exec_recorder.add_global_var(name, self.f_globals[name])
+            else:
+                assert name in self.f_builtins
+                self.exec_recorder.builtins[name] = self.f_builtins[name]
+
+        if name in self.symbolic_globals:
+            variable = self.output.side_effects[self.symbolic_globals[name]]
+            self.push(self.output.side_effects.load_global(variable, name))
+            return
+
+        try:
+            value = self.f_globals[name]
+        except KeyError:
+            return self.load_builtin(inst)
+
+        self.push(VariableTracker.build(self, value, GlobalSource(name)))
+
+    @functools.cached_property
+    def nn_modules_globals_vt(self):
+        module_name = "torch.nn.modules.module"
+        module_source = self.import_source(module_name)
+        fglobals_value = _import_module(module_name)
+        return VariableTracker.build(self, fglobals_value, module_source)
+
+    def LOAD_GLOBAL(self, inst):
+        if sys.version_info >= (3, 11) and sys.version_info < (3, 13) and inst.arg % 2:
+            self.PUSH_NULL(inst)
+        self._load_global(inst)
+        if sys.version_info >= (3, 13) and inst.arg % 2:
+            self.PUSH_NULL(inst)
+
+    def STORE_GLOBAL(self, inst):
+        value = self.pop()
+        name = inst.argval
+        source = GlobalSource(name)
+        if name not in self.symbolic_globals:
+            self.symbolic_globals[name] = object()  # type: ignore[assignment]  # sentinel object
+        variable = self.output.side_effects.track_global_existing(
+            source, self.symbolic_globals[name]
+        )
+        if isinstance(value, RemovableHandleVariable):
+            unimplemented_v2(
+                gb_type="Storing Tensor hook handle in globals",
+                context=name,
+                explanation="This is not supported.",
+                hints=[],
+            )
+        self.output.side_effects.store_global(variable, name, value)
+
+    # Cache note: This cache only exists for the duration of this
+    # InstructionTranslator - so it should be safe to do.
+    @cache_method
+    def import_source(self, module_name):
+        """Create an alias to a module for use in guards"""
+        if "torch_package" in module_name:
+            value = torch.package.package_importer._package_imported_modules[
+                module_name
+            ]
+            alias = (
+                module_name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
+            )
+        else:
+            value = _import_module(module_name)
+            alias = f"__import_{module_name.replace('.', '_dot_')}"
+        f_globals = self.output.global_scope
+        assert alias not in f_globals or f_globals[alias] is value
+        f_globals[alias] = value
+        self.output.update_co_names(alias)
+        return GlobalSource(alias)
+
+    def resolve_name(self, name, package, level):
+        """
+        Copied from the Cpython implementation of __import__
+        Resolve a relative module name to an absolute one.
+        https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L902
+        """
+        bits = package.rsplit(".", level - 1)
+        if len(bits) < level:
+            raise ImportError("attempted relative import beyond top-level package")
+        base = bits[0]
+        return f"{base}.{name}" if name else base
+
+    def calc_package(self):
+        """
+        Copied from the Cpython implementation of __import__
+        https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L1090
+        """
+        package = self.f_globals.get("__package__")
+        spec = self.f_globals.get("__spec__")
+        if package is not None:
+            if spec is not None and package != spec.parent:
+                log.warning(
+                    "__package__ != __spec__.parent (%r != %r)",
+                    package,
+                    spec.parent,
+                    stacklevel=3,
+                )
+            return package
+        elif spec is not None:
+            return spec.parent
+        else:
+            log.warning(
+                "can't resolve package from __spec__ or __package__, "
+                "falling back on __name__ and __path__",
+                stacklevel=3,
+            )
+            package = self.f_globals["__name__"]
+            if "__path__" not in self.f_globals:
+                package = package.rpartition(".")[0]
+        return package
+
+    def IMPORT_NAME(self, inst):
+        level, fromlist = self.popn(2)
+        level = level.as_python_constant()
+        fromlist = fromlist.as_python_constant()
+        module_name = inst.argval
+
+        # Are we replaying? if so, load recorded module
+        recorded_name = (
+            f"{ExecutionRecorder.LOCAL_MOD_PREFIX}_{level}_{fromlist}_{module_name}"
+        )
+        if recorded_name in self.f_globals:
+            value = self.f_globals[recorded_name]
+            source = GlobalSource(recorded_name)
+        else:
+            try:
+                value = __import__(
+                    module_name,
+                    fromlist=fromlist,
+                    level=level,
+                    globals=self.f_globals,
+                )
+            except ImportError:
+                unimplemented_v2(
+                    gb_type="Import failure",
+                    context=f"module_name: {module_name}, fromlist: {fromlist}, level={level}",
+                    explanation="Failure when attempting to import.",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+
+            if level != 0:
+                pkg = self.calc_package()
+                module_name = self.resolve_name(module_name, pkg, level)
+
+            # For __import__, when the name variable is of the form package.module,
+            # normally, the top-level package (the name up till the first dot) is
+            # returned, not the module named by module_name. However, when a
+            # non-empty fromlist argument is given, the module named by name is
+            # returned. Therefore, we set the source correctly here.
+            if not fromlist:
+                top_level_module_name = module_name.partition(".")[0]
+                source = self.import_source(top_level_module_name)
+            else:
+                source = self.import_source(module_name)
+
+        if self.exec_recorder:
+            self.exec_recorder.add_local_mod(recorded_name, value)
+
+        if istype(value, (types.ModuleType, DummyModule)):
+            self.push(PythonModuleVariable(value, source=source))
+        else:
+            unimplemented_v2(
+                gb_type="Bad import result",
+                context=typestr(value),
+                explanation="Import result is not a Python module.",
+                hints=[],
+            )
+
+    def IMPORT_FROM(self, inst):
+        self.DUP_TOP(inst)
+        self._load_attr(inst)
+
+    def load_builtin_from_argval(self, argval):
+        if argval not in self.f_builtins:
+            raise Unsupported(f"name '{argval}' is not defined")
+        val = self.f_builtins[argval]
+
+        if callable(val):
+            builtins_source = GlobalSource(
+                self.output.name_of_builtins_dict_key_in_fglobals
+            )
+            var_source = DictGetItemSource(builtins_source, argval)
+            self.push(VariableTracker.build(self, val, var_source))
+        else:
+            assert is_builtin_constant(val)
+            self.push(ConstantVariable.create(value=val))
+
+    def load_builtin(self, inst):
+        self.load_builtin_from_argval(inst.argval)
+
+    def jump(self, inst):
+        assert self.instruction_pointer is not None
+        assert self.start_point is not None
+        get_metrics_context().increment(
+            "ir_count", self.instruction_pointer - self.start_point
+        )
+        self.instruction_pointer = self.indexof[inst.target]
+        self.start_point = self.instruction_pointer
+
+    JUMP_FORWARD = jump
+    JUMP_ABSOLUTE = jump
+
+    POP_JUMP_IF_FALSE = generic_jump(operator.not_, False)
+    POP_JUMP_IF_TRUE = generic_jump(operator.truth, False)
+    JUMP_IF_FALSE_OR_POP = generic_jump(operator.not_, True)
+    JUMP_IF_TRUE_OR_POP = generic_jump(operator.truth, True)
+
+    def SETUP_LOOP(self, inst):
+        # only exists in python<=3.7
+        self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack)))
+
+    def SETUP_EXCEPT(self, inst):
+        # only exists in python<=3.7
+        self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack)))
+
+    def POP_BLOCK(self, inst):
+        self.block_stack.pop()
+
+    def SETUP_WITH(self, inst):
+        self.setup_or_before_with(inst)
+
+    def SETUP_FINALLY(self, inst):
+        self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack)))
+
+    def BEGIN_FINALLY(self, inst):
+        self.push(None)
+
+    def WITH_CLEANUP_START(self, inst):
+        exit, exc = self.popn(2)
+        assert exc is None
+        self.push(exc)
+        self.push(exit.call_function(self, [ConstantVariable.create(None)] * 3, {}))
+
+    def WITH_CLEANUP_FINISH(self, inst):
+        self.popn(2)
+        self.push(None)
+
+    def CALL_FINALLY(self, inst):
+        """
+        pushes the address of the next instruction onto the stack and increments
+        bytecode counter by delta
+        """
+        # Python 3.8 only
+        addr = self.indexof[self.next_instruction]
+        self.push(ConstantVariable.create(addr))
+        self.jump(inst)
+
+    def END_FINALLY(self, inst):
+        # Python 3.8 only
+        # https://docs.python.org/3.8/library/dis.html#opcode-END_FINALLY
+        tos = self.pop()
+        if isinstance(tos, ConstantVariable):
+            self.instruction_pointer = tos.as_python_constant()
+        else:
+            pass
+
+    def POP_FINALLY(self, inst):
+        # Python 3.8 only
+        preserve_tos = inst.argval
+        if preserve_tos:
+            tos = self.pop()
+        _ = self.pop()
+        if preserve_tos:
+            self.push(tos)  # type: ignore[possibly-undefined]
+
+    def FOR_ITER(self, inst):
+        it = self.pop().realize()
+        try:
+            val = it.next_variable(self)
+            self.push(it)
+            self.push(val)
+        except (StopIteration, exc.ObservedUserStopIteration) as e:
+            if isinstance(e, exc.ObservedUserStopIteration):
+                exc.handle_observed_exception(self)
+
+            # leave iterator upon exhaustion in 3.12
+            if sys.version_info >= (3, 12):
+                # CPython 3.12 actually jumps to the instruction after the END_FOR
+                # and performs the action of END_FOR as part of FOR_ITER. We jump
+                # to the END_FOR and run it, so we need to make sure 2 values are
+                # on the stack for it to pop.
+                self.push(it)
+                self.push(ConstantVariable.create(None))
+            self.jump(inst)
+
+    def _raise_exception_variable(self, val) -> NoReturn:
+        # User can raise exception in 2 ways
+        #   1) raise exception type - raise NotImplementedError
+        #   2) raise execption instance - raise NotImplemetedError("foo")
+
+        # 1) when user raises exception type
+        if isinstance(
+            val, (variables.BuiltinVariable, UserDefinedExceptionClassVariable)
+        ):
+            # Create the instance of the exception type
+            # https://github.com/python/cpython/blob/3.11/Python/ceval.c#L6547-L6549
+            val = val.call_function(self, [], {})  # type: ignore[arg-type]
+
+        # Handle https://peps.python.org/pep-0479/
+        # CPython 3.12+ has a specific bytecode instruction (CALL_INTRINSIC_1 3) for this
+        if (
+            is_generator(self.f_code)
+            and isinstance(val, variables.ExceptionVariable)
+            and val.exc_type is StopIteration
+        ):
+            val = variables.BuiltinVariable(RuntimeError).call_function(self, [], {})  # type: ignore[arg-type]
+
+        # Save the exception in a global data structure
+        self.exn_vt_stack.set_current_exception(val)
+
+        # 2) when user raises exception instance
+        if self._isinstance_exception(val):
+            observed_exception_type = exc.get_dynamo_observed_exception(val.exc_type)  # type: ignore[attr-defined]
+            raise observed_exception_type(f"raised exception {val}")
+        unimplemented_v2(
+            gb_type="Failed to raise exception",
+            context=str(exc),
+            explanation="Attempted to raise a non-Exception type/value.",
+            hints=[*graph_break_hints.USER_ERROR],
+        )
+
+    def RAISE_VARARGS(self, inst):
+        if inst.arg == 0:
+            # re-raise the previous exception. Here CPython refers to the exception
+            # on top of the exception stack
+            assert len(self.exn_vt_stack)
+            val = self.exn_vt_stack[-1]
+            assert self._isinstance_exception(val), val
+            self._raise_exception_variable(val)
+        elif inst.arg == 1:
+            # raise TOS
+            val = self.stack[-1]
+            self._raise_exception_variable(val)
+        else:
+            # raise .. from None
+            from_vt = self.pop()
+            if isinstance(from_vt, ConstantVariable) and from_vt.value is None:
+                val = self.pop()
+                try:
+                    self._raise_exception_variable(val)
+                finally:
+                    # Update __cause__/__supppress_context__ in the raised exception
+                    curr_exc = self.exn_vt_stack.get_current_exception()
+                    curr_exc.call_setattr(
+                        self, ConstantVariable("__cause__"), ConstantVariable(None)
+                    )
+            unimplemented_v2(
+                gb_type="Re-raise with 2 arguments",
+                context=str(from_vt),
+                explanation="Dynamo does not support `raise ... from [not-None]`",
+                hints=[],
+            )
+
+    def CLEANUP_THROW(self, inst):
+        # https://github.com/python/cpython/pull/96010
+        tos = self.stack[-1]
+        assert isinstance(tos, ExceptionVariable)
+        if tos.exc_type is StopIteration:
+            unimplemented_v2(
+                gb_type="CLEANUP_THROW with StopIteration",
+                context="",
+                explanation="Received StopIteration when handling generator.throw/close. This is not supported.",
+                hints=[],
+            )
+        else:
+            self.RERAISE(inst)
+
+    def RERAISE(self, inst):
+        # https://docs.python.org/3/library/dis.html#opcode-RERAISE
+        #   Re-raises the exception currently on top of the stack. If oparg is
+        #   non-zero, pops an additional value from the stack which is used to
+        #   set f_lasti of the current frame.
+
+        if sys.version_info >= (3, 11):
+            # RERAISE is currently supported in a narrow case of `raise ... from None`
+            val = self.pop()
+            if inst.argval:
+                # RERAISE 1
+                _ = self.pop()
+                self._raise_exception_variable(val)
+            else:
+                # RERAISE 0
+                self.push(val)
+                self._raise_exception_variable(val)
+        else:
+            _exc = self.pop()
+            val = self.pop()
+            _tb = self.pop()
+            self._raise_exception_variable(val)
+
+    def _isinstance_exception(self, val):
+        return isinstance(
+            val,
+            (
+                variables.ExceptionVariable,
+                UserDefinedExceptionClassVariable,
+                UserDefinedExceptionObjectVariable,
+            ),
+        )
+
+    def WITH_EXCEPT_START(self, inst):
+        if sys.version_info >= (3, 11):
+            # At the top of the stack are 4 values:
+            #    - TOP = exc_info()
+            #    - SECOND = previous exception
+            #    - THIRD: lasti of exception in exc_info()
+            #    - FOURTH: the context.__exit__ bound method
+            #    We call FOURTH(type(TOP), TOP, GetTraceback(TOP)).
+            #    Then we push the __exit__ return value.
+            assert len(self.stack) >= 4
+            fn = self.stack[-4]
+            val = self.stack[-1]
+            assert self._isinstance_exception(val)
+            typ = BuiltinVariable(val.exc_type)  # type: ignore[attr-defined]
+            tb = ConstantVariable(None)
+        else:
+            assert len(self.stack) >= 7
+            fn = self.stack[-7]
+            val = self.stack[-2]
+            assert self._isinstance_exception(val)
+            typ = BuiltinVariable(val.exc_type)  # type: ignore[attr-defined]
+            tb = ConstantVariable(None)
+
+        self.call_function(fn, [typ, val, tb], {})
+
+    def exception_handler(self, raised_exception):
+        observed_exn_gb_explanation = (
+            "Dynamo found no exception handler at the top-level compiled function "
+            "when encountering an exception. Exception will propagate outside the compiled region."
+        )
+
+        if sys.version_info >= (3, 11):
+            exn_tab_entry = self.current_instruction.exn_tab_entry
+            if exn_tab_entry:
+                # Implementation is based on https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt
+
+                # 1) pop values from the stack until it matches the stack depth
+                # for the handler
+                while len(self.stack) > exn_tab_entry.depth:
+                    self.pop()
+
+                # 2) if 'lasti' is true, then push the offset that the exception was raised at
+                if exn_tab_entry.lasti:
+                    self.push(
+                        variables.ConstantVariable(self.current_instruction.offset)
+                    )
+
+                # 3) push the exception to the stack
+                self.push(self.exn_vt_stack.get_current_exception())
+
+                # 4) jump to the handler
+                self.jump(exn_tab_entry)
+            else:
+                # No handler found. Bubble the exception to the parent
+                # instruction translater. We use special exception for this.
+                self.stack.clear()
+                if type(self) is InstructionTranslator:
+                    unimplemented_v2(
+                        gb_type="Observed exception",
+                        context=str(raised_exception),
+                        explanation=observed_exn_gb_explanation,
+                        hints=[
+                            *graph_break_hints.USER_ERROR,
+                            *graph_break_hints.SUPPORTABLE,
+                        ],
+                    )
+                raise raised_exception
+        else:
+            if len(self.block_stack):
+                # base implementation - https://github.com/python/cpython/blob/3.10/Python/ceval.c#L4455
+
+                block_stack_entry = self.block_stack.pop()
+
+                while block_stack_entry.inst.opname == "EXCEPT_HANDLER":
+                    # TODO(anijain2305) - This is not tested .. unable to create a testcase
+                    # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456
+                    self.popn(3)
+                    self.exn_vt_stack.pop()
+                    if len(self.block_stack) == 0:
+                        # No handler found in this frame. Bubble the exception to the parent
+                        # instruction translater.
+                        self.stack.clear()
+                        if type(self) is InstructionTranslator:
+                            unimplemented_v2(
+                                gb_type="Observed exception (EXCEPT_HANDLER)",
+                                context=str(raised_exception),
+                                explanation=observed_exn_gb_explanation
+                                + " This graph break is unexpected.",
+                                hints=[*graph_break_hints.DYNAMO_BUG],
+                            )
+
+                        raise raised_exception
+                    block_stack_entry = self.block_stack.pop()
+
+                exception_var = self.exn_vt_stack.get_current_exception()
+                self.exn_vt_stack.move_current_exception_to_stack()
+
+                # 1) pop values from the stack until it matches the stack depth
+                # for the handler
+                while len(self.stack) > block_stack_entry.stack_index:
+                    self.pop()
+
+                # Push a dummy block stack entry of EXCEPT_HANDLER
+                # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456
+                except_handler_inst = Instruction(1e6, "EXCEPT_HANDLER", None, 0)
+                self.block_stack.append(
+                    BlockStackEntry(except_handler_inst, None, len(self.stack))
+                )
+
+                # Push old exception
+                if len(self.exn_vt_stack) >= 2:
+                    old_exception = self.exn_vt_stack[-2]
+
+                    # Push the old exception on to stack - tb, value, type
+                    # Traceback is currently mapped to UnknownVariable
+                    self.push(variables.UnknownVariable())
+                    self.push(old_exception)
+                    self.push(variables.BuiltinVariable(old_exception.exc_type))
+                else:
+                    # Push empty exception tb, value, type
+                    self.push(variables.ConstantVariable(None))
+                    self.push(variables.ConstantVariable(None))
+                    self.push(variables.ConstantVariable(None))
+
+                # Push new exception - tb, val, type
+                # Traceback is currently mapped to UnknownVariable
+                self.push(variables.UnknownVariable())
+                self.push(exception_var)
+                self.push(variables.BuiltinVariable(exception_var.exc_type))
+
+                # Jump to target
+                self.jump(block_stack_entry)
+            else:
+                # No handler found. Bubble the exception to the parent
+                # instruction translater. We use special exception for this.
+                self.stack.clear()
+                if type(self) is InstructionTranslator:
+                    unimplemented_v2(
+                        gb_type="Observed exception",
+                        context=str(raised_exception),
+                        explanation=observed_exn_gb_explanation,
+                        hints=[
+                            *graph_break_hints.USER_ERROR,
+                            *graph_break_hints.SUPPORTABLE,
+                        ],
+                    )
+                raise raised_exception
+
+    def PUSH_EXC_INFO(self, inst):
+        # https://docs.python.org/3/library/dis.html#opcode-PUSH_EXC_INFO
+        #   Pops a value from the stack. Pushes the current exception to the top
+        #   of the stack. Pushes the value originally popped back to the stack.
+        #
+        # The behavior of this opcode in CPython is a bit different than what it
+        # is described. It pops a value from the stack, pushes the top of the
+        # exception stack to the interpreter stack and moves the
+        # "current exception" to the exception stack.
+        #
+        # As an example, suppose the stack is in the following state:
+        #   + stack = [..., ConstantVariable(1), ConstantVariable(2)]
+        #   + current_exception = TypeError
+        #   + exception_stack = [ValueError]
+        #
+        # After PUSH_EXC_INFO is executed
+        #   + stack = [..., ConstantVariable(1), ValueError, ConstantVariable(2)]
+        #   + current_exception = None
+        #   + exception_stack = [ValueError, TypeError]
+
+        val = self.pop()
+        if len(self.exn_vt_stack) == 0:
+            prev_exc = ConstantVariable(None)
+        else:
+            prev_exc = self.exn_vt_stack[-1]
+        self.push(prev_exc)
+        self.push(val)
+        self.exn_vt_stack.move_current_exception_to_stack()
+
+    def POP_EXCEPT(self, inst):
+        if sys.version_info >= (3, 11):
+            _ = self.pop()
+            # This exception is handled and therefore we can clear the error indicator
+            assert len(self.exn_vt_stack)
+            self.exn_vt_stack.pop()
+        else:
+            assert len(self.block_stack) > 0
+            if self.block_stack[-1].inst.opname != "EXCEPT_HANDLER":
+                raise AssertionError(
+                    "Bug in Dynamo tracing of exception handling."
+                    "Top of the block stack is not EXCEPT_HANDLER."
+                )
+            self.block_stack.pop()
+
+            self.popn(3)
+
+            # This exception is handled and therefore we can clear the error indicator
+            assert len(self.exn_vt_stack)
+            self.exn_vt_stack.pop()
+
+    def check_if_exc_matches(self):
+        assert len(self.stack) >= 2
+        expected_exc_types = self.pop()
+        if sys.version_info >= (3, 11):
+            # CHECK_EXC_MATCH (which is used from 3.11 onwards) does not pop.
+            # This is the description from the disassembly doc
+            #
+            # Performs exception matching for ``except``. Tests whether the ``STACK[-2]``
+            # is an exception matching ``STACK[-1]``. Pops ``STACK[-1]`` and pushes the boolean
+            # result of the test.
+            exc_instance = self.stack[-1]
+        else:
+            # This is used prior to 3.11 via opcode JUMP_IF_NOT_EXC_MATCH
+            # There is no documentation but here is the code pointer that does 2 pops
+            # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L3650-L3665
+            exc_instance = self.stack.pop()
+
+        # Users can check exception in 3 ways
+        # 1) except NotImplementedError --> BuiltinVariable
+        # 2) except CustomException --> UserDefinedExceptionClasVariable
+        # 3) except (NotImplemetedError, AttributeError) -> TupleVariable
+
+        if not isinstance(
+            expected_exc_types,
+            (
+                BuiltinVariable,
+                TupleVariable,
+                UserDefinedExceptionClassVariable,
+                UserDefinedExceptionObjectVariable,
+            ),
+        ):
+            unimplemented_v2(
+                gb_type="Exception with bad expected type",
+                context=str(expected_exc_types),
+                explanation=f"`except ...` has unsupported type {expected_exc_types}.",
+                hints=[*graph_break_hints.USER_ERROR],
+            )
+
+        if sys.version_info >= (3, 11):
+            if not self._isinstance_exception(exc_instance):
+                unimplemented_v2(
+                    gb_type="Caught non-Exception value",
+                    context=str(exc_instance),
+                    explanation=f"Except expects to recieve an object of Exception type but received {exc_instance}.",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+
+        if isinstance(expected_exc_types, TupleVariable):
+            expected_types = expected_exc_types.items
+        else:
+            expected_types = [
+                expected_exc_types,
+            ]
+
+        for expected_type in expected_types:
+            if not isinstance(
+                expected_type,
+                (
+                    BuiltinVariable,
+                    UserDefinedExceptionObjectVariable,
+                    UserDefinedExceptionClassVariable,
+                ),
+            ):
+                unimplemented_v2(
+                    gb_type="Exception with non-type expectation",
+                    context=str(expected_type),
+                    explanation=f"`except ...` expects a non-type: {expected_type}.",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+            if self._isinstance_exception(exc_instance) and issubclass(
+                exc_instance.exc_type,  # type: ignore[attr-defined]
+                expected_type.fn,  # type: ignore[attr-defined]
+            ):
+                return True
+            elif isinstance(exc_instance, variables.BuiltinVariable) and issubclass(
+                exc_instance.fn, expected_type.fn
+            ):
+                return True
+
+        return False
+
+    def CHECK_EXC_MATCH(self, inst):
+        self.push(variables.ConstantVariable(self.check_if_exc_matches()))
+
+    def JUMP_IF_NOT_EXC_MATCH(self, inst):
+        if not self.check_if_exc_matches():
+            self.jump(inst)
+
+    def COMPARE_OP(self, inst):
+        if inst.argval == "exception match":
+            self.CHECK_EXC_MATCH(inst)
+        else:
+            self.push(compare_op_handlers[inst.argval](self, self.popn(2), {}))
+
+    def GET_ITER(self, inst):
+        self.call_function(BuiltinVariable(iter), [self.pop()], {})
+
+    @break_graph_if_unsupported(push=1)
+    def CALL_FUNCTION(self, inst):
+        args = self.popn(inst.argval)
+        fn = self.pop()
+        self.call_function(fn, args, {})
+
+    @break_graph_if_unsupported(push=1)
+    def CALL_FUNCTION_EX(self, inst):
+        kwargsvars: VariableTracker
+        if inst.argval == 0:
+            kwargsvars = ConstDictVariable({})
+            argsvars = self.pop()
+        elif inst.argval == 1:
+            kwargsvars = self.pop()
+            argsvars = self.pop()
+        else:
+            unimplemented_v2(
+                gb_type="Variadic function call with bad flags",
+                context=f"flags: {inst.argval}",
+                explanation=f"Attempted to call a variadic function (CALL_FUNCTION_EX) with bad flags {inst.argval}",
+                hints=[*graph_break_hints.DYNAMO_BUG],
+            )
+
+        if sys.version_info >= (3, 13):
+            # 3.13 swapped null and callable
+            null = self.pop()
+            assert isinstance(null, NullVariable)
+
+        fn = self.pop()
+
+        if sys.version_info >= (3, 11) and sys.version_info < (3, 13):
+            null = self.pop()
+            assert isinstance(null, NullVariable)
+
+        if isinstance(fn, GetAttrVariable) and isinstance(fn.obj, TensorVariable):
+            # realize is requires for Python 3.8
+            kwargsvars = kwargsvars.realize()
+            if fn.name == "view" and isinstance(
+                argsvars, (ConstantVariable, TensorVariable)
+            ):
+                # Hack to handle special case in some bert models.  Converts
+                # x.view(*shape) into x.view(shape), which is correct for view()
+                # but not generally.  See test_transpose_for_scores().
+                argsvars = TupleVariable([argsvars])
+            elif (
+                fn.name == "random_"
+                and isinstance(argsvars, TupleVariable)
+                and len(argsvars.items) == 0
+                and isinstance(kwargsvars, ConstDictVariable)
+                and ConstantVariable.create("from") in kwargsvars
+            ):
+                # `from`` is python keyword. Adding random_ with `from` in the
+                # Fx graph causes syntax error. Even if we convert the kwargs to
+                # args, aot_autograd/inductor while lowering generates
+                # aten.random.from, again causing syntax errors. Since this
+                # usecase is uncommon, graph break.
+                unimplemented_v2(
+                    gb_type="Tensor.random_ op called with `from` keyword",
+                    context="",
+                    explanation="This is not supported.",
+                    hints=[],
+                )
+            elif (
+                fn.name == "uniform_"
+                and isinstance(argsvars, TupleVariable)
+                and len(argsvars.items) == 0
+                and isinstance(kwargsvars, ConstDictVariable)
+                and ConstantVariable.create("from") in kwargsvars
+            ):
+                # `from`` is python keyword. Adding uniform_ with `from` in the
+                # Fx graph causes syntax error. Even if we convert the kwargs to
+                # args, aot_autograd/inductor while lowering generates
+                # aten.uniform.from, again causing syntax errors. Since this
+                # usecase is uncommon, graph break.
+                unimplemented_v2(
+                    gb_type="Tensor.uniform_ op called with `from` keyword",
+                    context="",
+                    explanation="This is not supported.",
+                    hints=[],
+                )
+
+        if not isinstance(
+            argsvars, BaseListVariable
+        ) and argsvars.has_force_unpack_var_sequence(self):
+            argsvars = TupleVariable(argsvars.force_unpack_var_sequence(self))
+
+        # Unpack for cases like fn(**obj) where obj is a map
+        if isinstance(kwargsvars, UserDefinedObjectVariable):
+            kwargsvars = BuiltinVariable.call_custom_dict(self, dict, kwargsvars)  # type: ignore[arg-type]
+
+        if not isinstance(argsvars, BaseListVariable) or not isinstance(
+            kwargsvars, ConstDictVariable
+        ):
+            unimplemented_v2(
+                gb_type="Variadic function call with bad args/kwargs type",
+                context=f"args type: {typestr(argsvars)}, kwargs type: {typestr(kwargsvars)}",
+                explanation="Expected args to be a list and kwargs to be a dict",
+                hints=[*graph_break_hints.USER_ERROR],
+            )
+
+        # Map to a dictionary of str -> VariableTracker
+        kwargsvars = kwargsvars.keys_as_python_constant()
+        self.call_function(fn, argsvars.items, kwargsvars)
+
+    @break_graph_if_unsupported(push=1)
+    def CALL_FUNCTION_KW(self, inst):
+        argnames = self.pop()
+        args = self.popn(inst.argval)
+        fn = self.pop()
+        assert isinstance(argnames, TupleVariable) and argnames.is_python_constant()
+        argnames = argnames.as_python_constant()
+        args, kwargs_list = args[: -len(argnames)], args[-len(argnames) :]
+        kwargs = dict(zip(argnames, kwargs_list))
+        assert len(kwargs) == len(argnames)
+        self.call_function(fn, args, kwargs)
+
+    def LOAD_METHOD_SUPER(self, inst):
+        self.CALL_FUNCTION(dataclasses.replace(inst, argval=2))
+        arg = inst.argval[0]
+        argval = self.code_options["co_names"][arg]
+        if sys.version_info < (3, 11):
+            self._load_attr(dataclasses.replace(inst, argval=argval))
+        else:
+            self.LOAD_METHOD(dataclasses.replace(inst, argval=argval))
+
+    def LOAD_ATTR_SUPER(self, inst):
+        self.CALL_FUNCTION(dataclasses.replace(inst, argval=2))
+        arg = inst.argval[0]
+        argval = self.code_options["co_names"][arg]
+        self._load_attr(dataclasses.replace(inst, argval=argval))
+
+    def LOAD_METHOD(self, inst):
+        self._load_attr(inst)
+        obj = self.pop()
+        if sys.version_info >= (3, 13):
+            self.push(obj)
+            self.PUSH_NULL(inst)
+        elif sys.version_info >= (3, 11):
+            # always follow the NULL + fn convention, since if obj
+            # is actually a method, self is already bound to it, so it
+            # doesn't need to be passed in as an arg.
+            self.PUSH_NULL(inst)
+            self.push(obj)
+        else:
+            self.push(obj)
+            self.push(None)
+
+    def CALL_METHOD(self, inst):
+        args = self.popn(inst.argval)
+        dummy = self.pop()
+        assert dummy is None
+        fn = self.pop()
+        self.call_function(fn, args, {})
+
+    def _load_attr(self, inst):
+        obj = self.pop()
+        result = BuiltinVariable(getattr).call_function(
+            self,  # type: ignore[arg-type]
+            [obj, ConstantVariable.create(inst.argval)],
+            {},
+        )
+        self.push(result)
+
+    def LOAD_ATTR(self, inst):
+        if sys.version_info >= (3, 12):
+            if inst.arg % 2:
+                self.LOAD_METHOD(inst)
+                return
+        self._load_attr(inst)
+
+    def STORE_ATTR(self, inst):
+        speculation = self.speculate()
+        if speculation.failed:
+            return self.store_attr_graph_break(inst)
+        val, obj = self.popn(2)
+
+        if isinstance(obj, NNModuleVariable) and not isinstance(val, ConstantVariable):
+            # We don't allow side effects during export on non-constant values
+            # https://github.com/pytorch/torchdynamo/issues/1475
+            assert not self.export, (
+                f"Mutating module attribute {inst.argval} during export."
+            )
+
+        try:
+            BuiltinVariable(setattr).call_function(
+                self,  # type: ignore[arg-type]
+                [obj, ConstantVariable.create(inst.argval), val],
+                {},
+            )
+            return
+        except Unsupported as e:
+            if not self.should_compile_partial_graph():
+                raise
+            log.debug("STORE_ATTR triggered compile", exc_info=True)
+            e.remove_from_stats()
+            e.add_to_stats("graph_break")
+        speculation.fail_and_restart_analysis()
+
+    def store_attr_graph_break(self, inst):
+        log_graph_break(self.code_options, reason="STORE_ATTR-caused graph break")
+        if not self.should_compile_partial_graph():
+            unimplemented_v2(
+                gb_type="Should not compile partial graph (STORE_ATTR)",
+                context="",
+                explanation="Dynamo has determined when encountering an unsupported "
+                "STORE_ATTR instruction (i.e. `obj.attr = val`) that it should not compile the partial graph.",
+                hints=[],
+            )
+        self.output.compile_subgraph(
+            self, reason=GraphCompileReason("store_attr", [self.frame_summary()])
+        )
+        self.output.add_output_instructions([copy.copy(inst)])
+        self.popn(2)
+        self.output.add_output_instructions(
+            self.create_call_resume_at(self.next_instruction)
+        )
+
+    def DELETE_ATTR(self, inst):
+        obj = self.pop()
+        BuiltinVariable(delattr).call_function(
+            self,  # type: ignore[arg-type]
+            [obj, ConstantVariable.create(inst.argval)],
+            {},
+        )
+
+    def create_call_resume_at(self, offset):
+        raise AssertionError(
+            f"create_call_resume_at not overridden by subclass {type(self)}"
+        )
+
+    def should_compile_partial_graph(self) -> bool:
+        raise AssertionError(
+            f"should_compile_partial_graph not overridden by subclass {type(self)}"
+        )
+
+    @break_graph_if_unsupported(push=0)
+    def STORE_SUBSCR(self, inst):
+        val, obj, key = self.popn(3)
+        obj.call_method(self, "__setitem__", [key, val], {})
+
+    def DELETE_SUBSCR(self, inst):
+        obj, key = self.popn(2)
+        obj.call_method(self, "__delitem__", [key], {})
+
+    def BUILD_TUPLE(self, inst):
+        items = self.popn(inst.argval)
+        self.push(TupleVariable(items))
+
+    def BUILD_SLICE(self, inst):
+        items = self.popn(inst.argval)
+        self.push(SliceVariable(items))
+
+    def BUILD_LIST(self, inst):
+        items = self.popn(inst.argval)
+        self.push(ListVariable(items, mutation_type=ValueMutationNew()))
+
+    def BUILD_SET(self, inst):
+        if config.inject_BUILD_SET_unimplemented_TESTING_ONLY:
+            unimplemented_v2(
+                gb_type="missing BUILD_SET handler",
+                context="",
+                explanation="Missing BUILD_SET bytecode handler (for testing purposes).",
+                hints=[],
+            )
+        items = self.popn(inst.argval)
+        new_set = SetVariable(items, mutation_type=ValueMutationNew())
+        self.push(new_set)
+
+    def BUILD_LIST_UNPACK(self, inst, cls=ListVariable):
+        seqs = self.popn(inst.argval)
+        items = []
+        for seq in seqs:
+            try:
+                items.extend(seq.force_unpack_var_sequence(self))
+            except NotImplementedError:
+                unimplemented_v2(
+                    gb_type="Failed to unpack object for BUILD_LIST_UNPACK",
+                    context=str(seq),
+                    explanation=f"{seq} cannot be unpacked into a list for the BUILD_LIST_UNPACK "
+                    "bytecode (`[*x, *y, ...]`).",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+        self.push(cls(items, mutation_type=ValueMutationNew()))
+
+    def BUILD_TUPLE_UNPACK(self, inst):
+        self.BUILD_LIST_UNPACK(inst, cls=TupleVariable)
+
+    BUILD_TUPLE_UNPACK_WITH_CALL = BUILD_TUPLE_UNPACK
+
+    def BUILD_MAP(self, inst):
+        items = self.popn(inst.argval * 2)
+        d = dict(zip(items[::2], items[1::2]))
+        self.push(ConstDictVariable(d, mutation_type=ValueMutationNew()))
+
+    def BUILD_MAP_UNPACK(self, inst):
+        items = self.popn(inst.argval)
+        # ensure everything is a dict
+        items = [BuiltinVariable(dict).call_function(self, [x], {}) for x in items]  # type: ignore[arg-type]
+        result = {}
+        for x in items:
+            assert isinstance(x, ConstDictVariable)
+            result.update(x.items)
+        self.push(
+            ConstDictVariable(
+                result,
+                mutation_type=ValueMutationNew(),
+            )
+        )
+
+    BUILD_MAP_UNPACK_WITH_CALL = BUILD_MAP_UNPACK
+
+    def BUILD_CONST_KEY_MAP(self, inst):
+        keys = self.pop()
+        values = self.popn(inst.argval)
+        assert isinstance(keys, TupleVariable)
+        assert keys.is_python_constant()
+
+        keys = keys.force_unpack_var_sequence(self)
+        assert len(keys) == len(values)
+
+        self.push(
+            ConstDictVariable(
+                dict(zip(keys, values)),
+                mutation_type=ValueMutationNew(),
+            )
+        )
+
+    def MAP_ADD(self, inst):
+        k, v = self.popn(2)
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg].realize()
+        assert isinstance(obj, ConstDictVariable)
+        obj.call_method(self, "__setitem__", (k, v), {})  # type: ignore[arg-type]
+
+    def SET_ADD(self, inst):
+        v = self.pop()
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg]
+        assert isinstance(obj, SetVariable)
+        assert obj.is_mutable()
+        return obj.call_method(self, "add", [v], {})
+
+    def SET_UPDATE(self, inst):
+        v = self.pop()
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg]
+        assert isinstance(obj, SetVariable)
+        assert obj.is_mutable()
+        obj.call_method(self, "update", [v], {})
+
+    def LIST_APPEND(self, inst):
+        v = self.pop()
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg].realize()
+        assert isinstance(obj, ListVariable)
+        assert obj.is_mutable()
+        self.output.side_effects.mutation(obj)
+        obj.items.append(v)
+
+    def MAKE_FUNCTION(self, inst):
+        flags = inst.arg
+        if sys.version_info < (3, 11):
+            fn_name = self.pop()
+        code = self.pop()
+        if sys.version_info >= (3, 11):
+            # MAKE_FUNCTION behavior actually changed in 3.11, see
+            # https://github.com/python/cpython/pull/93189/
+            assert hasattr(code.value, "co_qualname")  # type: ignore[attr-defined]
+            fn_name = ConstantVariable.create(value=code.value.co_qualname)  # type: ignore[attr-defined]
+        defaults = None
+        closure = None
+        annotations = None
+        kwdefaults = None
+
+        if sys.version_info < (3, 13):
+            # in 3.13, this is handled in SET_FUNCTION_ATTRIBUTE
+            if flags & 0x08:
+                closure = self.pop()
+            if flags & 0x04:
+                annotations = self.pop()
+            if flags & 0x02:
+                kwdefaults = self.pop()
+            if flags & 0x01:
+                defaults = self.pop()
+
+        self.push(
+            NestedUserFunctionVariable(
+                fn_name,
+                code,
+                self.f_globals,
+                defaults,
+                kwdefaults,
+                annotations,
+                closure,
+            )
+        )
+
+    def UNPACK_SEQUENCE(self, inst):
+        seq = self.pop()
+        if isinstance(seq, TensorVariable):
+            val = seq.unpack_var_sequence(self, idxes=range(inst.argval))  # type: ignore[arg-type]
+        elif isinstance(seq, GetAttrVariable) and isinstance(seq.obj, TensorVariable):
+            # x, y = a.shape
+            proxy = getattr(seq.obj.as_proxy(), seq.name)
+            val = [wrap_fx_proxy(self, proxy[i]) for i in range(inst.argval)]
+        elif seq.has_force_unpack_var_sequence(self):
+            val = seq.force_unpack_var_sequence(self)
+        else:
+            unimplemented_v2(
+                gb_type="Failed to unpack object for UNPACK_SEQUENCE",
+                context=str(seq),
+                explanation=f"{seq} cannot be unpacked into a list for the UNPACK_SEQUENCE bytecode "
+                "(i.e. `a, b, c = d`).",
+                hints=[*graph_break_hints.USER_ERROR],
+            )
+        if len(val) != inst.argval:
+            unimplemented_v2(
+                gb_type="Length mismatch when unpacking object for UNPACK_SEQUENCE",
+                context=f"expected length: {inst.argval}, actual: {len(val)}",
+                explanation=f"{seq} unpacked to a list for the UNPACK_SEQUENCE bytecode "
+                "(i.e. `a, b, c = d`) with unexpected length.",
+                hints=[*graph_break_hints.DYNAMO_BUG],
+            )
+        for i in reversed(val):
+            self.push(i)
+
+    def UNPACK_EX(self, inst):
+        assert 0 <= inst.argval <= 0xFFFF
+        prefix = inst.argval & 0xFF  # low byte
+        suffix = inst.argval >> 8  # high byte
+        seq = self.pop()
+        if seq.has_force_unpack_var_sequence(self):
+            vals = list(seq.force_unpack_var_sequence(self))
+            assert len(vals) >= prefix + suffix
+            vals_prefix = vals[:prefix]
+            vals_list = vals[prefix : len(vals) - suffix]
+            vals_suffix = vals[len(vals) - suffix :]
+            for item in reversed(vals_suffix):
+                self.push(item)
+            self.push(TupleVariable(vals_list))
+            for item in reversed(vals_prefix):
+                self.push(item)
+        else:
+            unimplemented_v2(
+                gb_type="Failed to unpack object for UNPACK_EX",
+                context=str(seq),
+                explanation=f"{seq} cannot be unpacked into a list for the UNPACK_EX bytecode.",
+                hints=[*graph_break_hints.USER_ERROR],
+            )
+
+    def NOP(self, inst):
+        pass
+
+    def POP_TOP(self, inst):
+        self.pop()
+
+    def ROT_TWO(self, inst):
+        a = self.pop()
+        b = self.pop()
+        self.push(a)
+        self.push(b)
+
+    def ROT_THREE(self, inst):
+        a = self.pop()
+        b = self.pop()
+        c = self.pop()
+        self.push(a)
+        self.push(c)
+        self.push(b)
+
+    def ROT_FOUR(self, inst):
+        a = self.pop()
+        b = self.pop()
+        c = self.pop()
+        d = self.pop()
+        self.push(a)
+        self.push(d)
+        self.push(c)
+        self.push(b)
+
+    def DUP_TOP(self, inst):
+        a = self.pop()
+        self.push(a)
+        self.push(a)
+
+    def DUP_TOP_TWO(self, inst):
+        a = self.pop()
+        b = self.pop()
+        self.push(b)
+        self.push(a)
+        self.push(b)
+        self.push(a)
+
+    def _convert_value(self, value, flag):
+        if flag == 1:
+            return BuiltinVariable(str).call_function(self, [value], {})  # type: ignore[arg-type]
+        elif flag == 2:
+            return BuiltinVariable(repr).call_function(self, [value], {})  # type: ignore[arg-type]
+        elif flag == 3:
+            return BuiltinVariable(ascii).call_function(self, [value], {})  # type: ignore[arg-type]
+        return value
+
+    def _format_value(self, fmt_spec, flags):
+        value = self.pop()
+        if isinstance(value, SymNodeVariable):
+            from torch._dynamo.variables.lazy import (
+                LazySymNodeFormatString,
+                LazyVariableTracker,
+            )
+
+            value = LazyVariableTracker.create(
+                LazySymNodeFormatString(value, fmt_spec), source=value.source
+            )
+            self.push(value)
+            return
+
+        value = self._convert_value(value, flags & 0x03)
+
+        fmt_var = ConstantVariable.create("{:" + fmt_spec.as_python_constant() + "}")
+
+        self.call_function(BuiltinVariable(str.format), [fmt_var, value], {})
+
+    def FORMAT_VALUE(self, inst):
+        flags = inst.arg
+        if (flags & 0x04) == 0x04:
+            fmt_spec = self.pop()
+        else:
+            fmt_spec = ConstantVariable.create("")
+
+        return self._format_value(fmt_spec, flags)
+
+    def BUILD_STRING(self, inst):
+        format_string_parts: list[str] = []
+        args: list[VariableTracker] = []
+        kwargs: dict[str, VariableTracker] = {}
+        for part in self.popn(inst.arg):
+            if isinstance(part, ConstantVariable):
+                format_string_parts.append("{}")
+                args.append(part)
+            elif isinstance(part, variables.StringFormatVariable):
+                format_string_parts.append(part.format_string)
+                args.extend(part.sym_args)
+                if set(kwargs.keys()) & set(part.sym_kwargs.keys()):
+                    unimplemented_v2(
+                        gb_type="BUILD_STRING key conflict",
+                        context=f"format_string_parts: {format_string_parts}, kwargs: {kwargs}, part.sym_kwargs: {part.sym_kwargs}",
+                        explanation="Failed to build format string due to key conflict",
+                        hints=[*graph_break_hints.USER_ERROR],
+                    )
+                kwargs.update(part.sym_kwargs)
+            else:
+                unimplemented_v2(
+                    gb_type="BUILD_STRING type error",
+                    context=str(part),
+                    explanation="Format string part type is not correct - expected constant or format string.",
+                    hints=[*graph_break_hints.USER_ERROR],
+                )
+        self.push(
+            variables.StringFormatVariable.create(
+                "".join(format_string_parts), args, kwargs
+            )
+        )
+
+    def IS_OP(self, inst):
+        assert inst.argval == 0 or inst.argval == 1
+        if inst.argval == 0:
+            new_argval = "is"
+        else:
+            new_argval = "is not"
+        new_inst = create_instruction("COMPARE_OP", argval=new_argval)
+        self.COMPARE_OP(new_inst)
+
+    def CONTAINS_OP(self, inst):
+        assert inst.argval == 0 or inst.argval == 1
+        left, right = self.popn(2)
+        op = inst.argval
+        self.push(right.call_method(self, "__contains__", [left], {}))
+        if op == 1:
+            self.UNARY_NOT(inst)
+
+    def LIST_EXTEND(self, inst):
+        v = self.pop()
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg]
+        assert isinstance(obj, ListVariable)
+        assert obj.is_mutable()
+        obj.call_method(self, "extend", [v], {})
+
+    def LIST_TO_TUPLE(self, inst):
+        self.push(BuiltinVariable(tuple).call_function(self, [self.pop()], {}))  # type: ignore[arg-type]
+
+    def STOPITERATION_ERROR(self, inst):
+        # wrap the generator body in a try: ... except StopIteration: ... which
+        # converts the StopIteration into a RuntimeError
+        # https://peps.python.org/pep-0479/
+        # https://github.com/python/cpython/pull/99006
+        # https://github.com/python/cpython/commit/28187141cc34063ef857976ddbca87ba09a882c2
+        val = self.stack[-1]
+        assert self._isinstance_exception(val)
+        if val.exc_type is StopIteration:  # type: ignore[attr-defined]
+            new_val = variables.BuiltinVariable(RuntimeError).call_function(
+                self,  # type: ignore[arg-type]
+                [],
+                {},
+            )
+            self.stack[-1] = new_val
+
+    def DICT_MERGE(self, inst):
+        v = self.pop()
+        assert inst.argval > 0
+        obj = self.stack[-inst.arg].realize()
+        assert isinstance(obj, ConstDictVariable)
+        assert obj.is_mutable()
+        obj.call_method(self, "update", [v], {})
+
+    DICT_UPDATE = DICT_MERGE
+
+    def GEN_START(self, inst):
+        self.pop()
+
+    def GET_LEN(self, inst):
+        tos = self.stack[-1]
+        if tos.is_python_constant():
+            self.push(ConstantVariable.create(len(tos.as_python_constant())))
+        else:
+            self.push(tos.call_method(self, "__len__", [], {}))
+
+    def MATCH_MAPPING(self, inst):
+        tos = self.stack[-1]
+        assert isinstance(tos, ConstDictVariable)
+        if isinstance(tos.items, collections.abc.Mapping):
+            self.push(ConstantVariable.create(True))
+        else:
+            self.push(ConstantVariable.create(False))
+
+    def MATCH_SEQUENCE(self, inst):
+        tos = self.stack[-1]
+        assert tos.is_python_constant()
+        tos_value = tos.as_python_constant()
+        if isinstance(tos_value, collections.abc.Sequence) and not isinstance(
+            tos_value, (str, bytes, bytearray)
+        ):
+            self.push(ConstantVariable.create(True))
+        else:
+            self.push(ConstantVariable.create(False))
+
+    def MATCH_KEYS(self, inst):
+        tos = self.stack[-1]
+        tos1 = self.stack[-2]
+        assert isinstance(tos1, ConstDictVariable)
+
+        if all(k in tos1 for k in tos):  # type: ignore[attr-defined]
+            self.push(TupleVariable([tos1.getitem_const(self, k) for k in tos]))  # type: ignore[attr-defined,arg-type]
+            if sys.version_info < (3, 11):
+                self.push(ConstantVariable.create(True))
+        else:
+            self.push(ConstantVariable.create(None))
+            if sys.version_info < (3, 11):
+                self.push(ConstantVariable.create(False))
+
+    def LOAD_ASSERTION_ERROR(self, inst):
+        self.load_builtin_from_argval("AssertionError")
+
+    UNARY_POSITIVE = stack_op(operator.pos)
+    UNARY_NEGATIVE = stack_op(operator.neg)
+    UNARY_NOT = stack_op(operator.not_)
+    UNARY_INVERT = stack_op(operator.invert)
+
+    BINARY_POWER = stack_op(operator.pow)
+    BINARY_MULTIPLY = stack_op(operator.mul)
+    BINARY_MATRIX_MULTIPLY = stack_op(operator.matmul)
+    BINARY_FLOOR_DIVIDE = stack_op(operator.floordiv)
+    BINARY_TRUE_DIVIDE = stack_op(operator.truediv)
+    BINARY_MODULO = stack_op(operator.mod)
+    BINARY_REMAINDER = stack_op(operator.mod)
+    BINARY_ADD = stack_op(operator.add)
+    BINARY_SUBTRACT = stack_op(operator.sub)
+    BINARY_SUBSCR = break_graph_if_unsupported(push=1)(stack_op(operator.getitem))
+    BINARY_LSHIFT = stack_op(operator.lshift)
+    BINARY_RSHIFT = stack_op(operator.rshift)
+    BINARY_AND = stack_op(operator.and_)
+    BINARY_OR = stack_op(operator.or_)
+    BINARY_XOR = stack_op(operator.xor)
+
+    INPLACE_POWER = stack_op(operator.ipow)
+    INPLACE_MULTIPLY = stack_op(operator.imul)
+    INPLACE_MATRIX_MULTIPLY = stack_op(operator.imatmul)
+    INPLACE_FLOOR_DIVIDE = stack_op(operator.ifloordiv)
+    INPLACE_TRUE_DIVIDE = stack_op(operator.itruediv)
+    INPLACE_MODULO = stack_op(operator.imod)
+    INPLACE_REMAINDER = stack_op(operator.imod)
+    INPLACE_ADD = stack_op(operator.iadd)
+    INPLACE_SUBTRACT = stack_op(operator.isub)
+    INPLACE_LSHIFT = stack_op(operator.ilshift)
+    INPLACE_RSHIFT = stack_op(operator.irshift)
+    INPLACE_AND = stack_op(operator.iand)
+    INPLACE_XOR = stack_op(operator.ixor)
+    INPLACE_OR = stack_op(operator.ior)
+
+    # 3.11 opcodes
+    def RESUME(self, inst):
+        if inst.arg == 0:
+            self.append_prefix_inst(inst)
+            self.accept_prefix_inst = False
+        else:
+            assert not self.accept_prefix_inst
+
+    if sys.version_info >= (3, 11):
+
+        def BINARY_OP(self, inst):
+            return _binary_op_lookup[inst.arg](self, inst)
+
+    def PRECALL(self, inst):
+        pass
+
+    def KW_NAMES(self, inst):
+        kw_names = self.code_options["co_consts"][inst.arg]
+        assert isinstance(kw_names, tuple)
+        for name in kw_names:
+            assert isinstance(name, str)
+        assert self.kw_names is None
+        self.kw_names = ConstantVariable.create(value=kw_names)  # type: ignore[assignment]
+
+    def PUSH_NULL(self, inst):
+        self.push(NullVariable())
+
+    def _call(self, inst, call_kw=False):
+        # see https://docs.python.org/3.11/library/dis.html#opcode-CALL
+        # for convention
+        if call_kw:
+            # TOS is kw_names for CALL_KW instruction
+            assert sys.version_info >= (3, 13)
+            kw_names = self.pop()
+            assert isinstance(kw_names, TupleVariable) and kw_names.is_python_constant()
+            kw_names = kw_names.as_python_constant()
+        else:
+            kw_names = self.kw_names.value if self.kw_names else ()
+
+        contents = self.popn(inst.arg + 2)
+        if sys.version_info >= (3, 13):
+            # NULL and callable swapped
+            fn = contents[0]
+            args = [] if isinstance(contents[1], NullVariable) else [contents[1]]
+        else:
+            if isinstance(contents[0], NullVariable):
+                fn = contents[1]
+                args = []
+            else:
+                fn = contents[0]
+                args = [contents[1]]
+
+        if kw_names:
+            args = args + contents[2 : -len(kw_names)]
+            kwargs_list = contents[-len(kw_names) :]
+            kwargs = dict(zip(kw_names, kwargs_list))
+            assert len(kwargs) == len(kw_names)
+        else:
+            args = args + contents[2:]
+            kwargs = {}
+
+        try:
+            # if call_function fails, need to set kw_names to None, otherwise
+            # a subsequent call may have self.kw_names set to an old value
+            self.call_function(fn, args, kwargs)
+        finally:
+            self.kw_names = None
+
+    @break_graph_if_unsupported(push=1)
+    def CALL(self, inst):
+        self._call(inst)
+
+    def COPY(self, inst):
+        self.push(self.stack[-inst.arg])
+
+    def SWAP(self, inst):
+        self.stack[-1], self.stack[-inst.arg] = self.stack[-inst.arg], self.stack[-1]
+
+    JUMP_BACKWARD = jump
+    JUMP_BACKWARD_NO_INTERRUPT = jump
+
+    POP_JUMP_FORWARD_IF_TRUE = generic_jump(operator.truth, False)
+    POP_JUMP_BACKWARD_IF_TRUE = generic_jump(operator.truth, False)
+    POP_JUMP_FORWARD_IF_FALSE = generic_jump(operator.not_, False)
+    POP_JUMP_BACKWARD_IF_FALSE = generic_jump(operator.not_, False)
+
+    def CACHE(self, inst):
+        pass
+
+    def BEFORE_WITH(self, inst):
+        self.setup_or_before_with(inst)
+
+    def setup_or_before_with(self, inst):
+        ctx = self.pop()
+        if not isinstance(
+            ctx, (ContextWrappingVariable, GenericContextWrappingVariable)
+        ):
+            unimplemented_v2(
+                gb_type="Unsupported context manager",
+                context=f"Attempted SETUP_WITH/BEFORE_WITH on {ctx}",
+                explanation=f"Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.",
+                hints=[
+                    "Avoid using the unsupported context manager.",
+                    "File an issue to PyTorch. Simple context managers can potentially be supported, "
+                    "but note that context managers can't be supported in general",
+                ],
+            )
+
+        if (
+            isinstance(ctx, GenericContextWrappingVariable)
+            and not ctx.supports_graph_breaks()
+        ):
+            self.active_generic_context_managers.append(ctx)
+
+        # Need this redundant check for mypy
+        assert isinstance(
+            ctx, (ContextWrappingVariable, GenericContextWrappingVariable)
+        )
+
+        exit = WithExitFunctionVariable(
+            ctx,
+            inst.target,
+        )
+
+        if sys.version_info >= (3, 11):
+            # See create_call_resume_at for block stack details.
+            # Only push a block if the current instruction's block is a
+            # with block that is not nested in a try block - that is, the current
+            # instruction's block target is the same as the top block's target.
+            if inst.exn_tab_entry and (
+                not self.block_stack
+                or inst.exn_tab_entry.target is not self.block_stack[-1].target
+            ):
+                target = None
+            else:
+                target = self.next_instruction.exn_tab_entry.target
+        else:
+            target = inst.target
+
+        self.push(exit)
+
+        if target:
+            if isinstance(self, InstructionTranslator):
+                self.block_stack.append(
+                    BlockStackEntry(inst, target, len(self.stack), ctx)
+                )
+            else:
+                self.block_stack.append(BlockStackEntry(inst, target, len(self.stack)))
+
+        self.push(ctx.enter(self))
+
+    def append_prefix_inst(self, inst):
+        assert self.accept_prefix_inst
+        self.prefix_insts.append(inst)
+
+    def MAKE_CELL(self, inst):
+        if sys.version_info >= (3, 12) and not self.accept_prefix_inst:
+            # In 3.12+, MAKE_CELL is not longer necessarily a prefix instruction.
+            # It can be generated by inlined comprehensions.
+            assert isinstance(self.symbolic_locals[inst.argval], NullVariable)
+            self.symbolic_locals[inst.argval] = (
+                self.output.side_effects.track_cell_new()
+            )
+        else:
+            self.append_prefix_inst(inst)
+
+    def COPY_FREE_VARS(self, inst):
+        self.append_prefix_inst(inst)
+
+    def RETURN_GENERATOR(self, inst):
+        self.append_prefix_inst(inst)
+
+    # 3.12 opcodes
+    # BINARY/STORE_SLICE opcodes are broken down into
+    # BUILD_SLICE 2 and BINARY/STORE_SUBSCR
+
+    def END_FOR(self, inst):
+        if sys.version_info >= (3, 13):
+            self.pop()
+        else:
+            self.popn(2)
+
+    def LOAD_FAST_CHECK(self, inst):
+        if isinstance(self.symbolic_locals[inst.argval], NullVariable):
+            unimplemented_v2(
+                gb_type="LOAD_FAST_CHECK on uninitialized variable",
+                context=inst.argval,
+                explanation=f"Attempted to load uninitialized local variable {inst.argval}",
+                hints=[*graph_break_hints.USER_ERROR],
+            )
+        self.LOAD_FAST(inst)
+
+    def LOAD_FAST_AND_CLEAR(self, inst):
+        if inst.argval not in self.symbolic_locals:
+            self.push(NullVariable())
+        else:
+            self.LOAD_FAST(inst)
+        self.symbolic_locals[inst.argval] = NullVariable()
+
+    def LOAD_SUPER_ATTR(self, inst):
+        self.CALL_FUNCTION(dataclasses.replace(inst, argval=2))
+        if inst.arg & 1:
+            self.LOAD_METHOD(inst)
+        else:
+            self._load_attr(inst)
+
+    def CALL_INTRINSIC_1(self, inst):
+        if inst.argval == 3:
+            # INTRINSIC_STOPITERATION_ERROR
+            self.STOPITERATION_ERROR(inst)
+        elif inst.argval == 5:
+            # INTRINSIC_UNARY_POSITIVE
+            self.UNARY_POSITIVE(inst)
+        elif inst.argval == 6:
+            # INTRINSIC_LIST_TO_TUPLE
+            self.push(TupleVariable(self.pop().force_unpack_var_sequence(self)))
+        else:
+            unimplemented_v2(
+                gb_type="Missing CALL_INTRINSIC_1 handler",
+                context=f"CALL_INTRINSIC_1 operand: {inst.argval}",
+                explanation=f"No handler implemented for CALL_INTRINSIC_1 {inst.argval} instruction.",
+                hints=[*graph_break_hints.SUPPORTABLE],
+            )
+
+    def END_SEND(self, inst):
+        tos = self.pop()
+        self.pop()
+        self.push(tos)
+
+    # 3.13 opcodes
+    # fused instructions LOAD_FAST_LOAD_FAST, STORE_FAST_STORE_FAST, STORE_FAST_LOAD_FAST
+    # are broken down.
+    @break_graph_if_unsupported(push=1)
+    def CALL_KW(self, inst):
+        self._call(inst, call_kw=True)
+
+    def TO_BOOL(self, inst):
+        # TO_BOOL only precedes a conditional jump or UNARY_NOT (see compile.c in CPython)
+        # So we can skip this instruction as long as we remember to codegen a TO_BOOL
+        # before conditional jumps/UNARY_NOT.
+        assert self.next_instruction.opname in (
+            "POP_JUMP_IF_TRUE",
+            "POP_JUMP_IF_FALSE",
+            "UNARY_NOT",
+        )
+
+    def SET_FUNCTION_ATTRIBUTE(self, inst):
+        flags = inst.arg
+        fn = self.pop()
+        assert isinstance(fn, NestedUserFunctionVariable)
+        attr = self.pop()
+
+        if flags & 0x08:
+            fn.closure = attr
+        elif flags & 0x04:
+            fn.annotations = attr
+        elif flags & 0x02:
+            fn.kwdefaults = attr
+        elif flags & 0x01:
+            fn.defaults = attr
+
+        self.push(fn)
+
+    def CONVERT_VALUE(self, inst):
+        self.push(self._convert_value(self.pop(), inst.argval))
+
+    def FORMAT_SIMPLE(self, inst):
+        self._format_value(ConstantVariable.create(""), 0)
+
+    def FORMAT_WITH_SPEC(self, inst):
+        self._format_value(self.pop(), 0)
+
+    def is_non_empty_graph(self):
+        if self.output.count_calls() > 1:
+            # perf optimization only
+            self.is_non_empty_graph = lambda: True  # type: ignore[method-assign]
+            return True
+        return False
+
+    def format_frame_summary(self, additional_stack_frames=None):
+        if additional_stack_frames is None:
+            additional_stack_frames = []
+        return "".join(
+            traceback.format_list(
+                [self.frame_summary()] + list(reversed(additional_stack_frames))
+            )
+        )
+
+    def frame_summary(self):
+        return traceback.FrameSummary(
+            getattr(self.f_code, "co_filename", ""),
+            self.lineno,
+            getattr(self.f_code, "co_name", ""),
+            lookup_line=False,
+        )
+
+    def is_co_filename_from_nn_modules(self):
+        filename = getattr(self.f_code, "co_filename", "")
+        nn_modules_pattern = re.compile(r".*torch/nn/modules.*")
+        return nn_modules_pattern.match(filename) is not None
+
+    def store_global_weakref_by_id(self, prefix, value):
+        global_name = self.output.install_global_by_id(prefix, weakref.ref(value))
+        install_guard(
+            GlobalWeakRefSource(global_name).make_guard(GuardBuilder.WEAKREF_ALIVE)
+        )
+        return global_name
+
+    @property
+    def fake_mode(self):
+        return self.output.tracing_context.fake_mode
+
+    @contextlib.contextmanager
+    def strict_translation_mode(self, check_fn: Callable[[VariableTracker], bool]):
+        """
+        Strict mode is enabled on a per-VariableTracker level depending on the return value of check_fn(node).
+        """
+        prior = self.strict_checks_fn
+        self.strict_checks_fn = check_fn
+        try:
+            yield
+        finally:
+            self.strict_checks_fn = prior
+
+    def speculate(self) -> SpeculationEntry:
+        assert self.instruction_pointer is not None
+        assert self.instruction_pointer > 0
+        return self.speculation_log.next(
+            self.f_code.co_filename,
+            self.lineno,
+            self.instruction_pointer - 1,
+            self.instructions[self.instruction_pointer - 1],
+        )
+
+    def __init__(
+        self,
+        output: OutputGraph,
+        instructions: list[Instruction],
+        f_locals: dict[str, Any],
+        f_globals: dict[str, Any],
+        f_builtins: dict[str, Any],
+        code_options: dict[str, Any],
+        symbolic_locals: dict[str, VariableTracker],
+        symbolic_globals: dict[str, VariableTracker],
+        symbolic_torch_function_state: SymbolicTorchFunctionState,
+        f_code: types.CodeType,
+        export: bool,
+        inline_depth: int,
+        speculation_log: SpeculationLog,
+        exn_vt_stack: ExceptionStack,
+        distributed_state: Optional[DistributedState],
+        # This determines whether to use the execution recorder.
+        closure: Optional[tuple[types.CellType]] = None,
+    ) -> None:
+        super().__init__()
+        self.speculation_log = speculation_log
+        self.distributed_state = distributed_state
+
+        # Mutable state checkpointed by copy_graphstate()
+        self.output = output
+        self.symbolic_locals = symbolic_locals
+        self.symbolic_globals = symbolic_globals
+        self.symbolic_torch_function_state = symbolic_torch_function_state
+        self.stack = []
+        self.instruction_pointer = 0
+        self.start_point = None
+        self.current_instruction = create_instruction("NOP")
+        self.block_stack = []
+        # states before SETUP_WITH for checkpointing and fallback
+        self.active_generic_context_managers: list[GenericContextWrappingVariable] = []
+        self.lineno = -1
+        self.kw_names = None
+        self.accept_prefix_inst = True
+        self.prefix_insts = []
+        self.exn_vt_stack = exn_vt_stack
+
+        # Properties of the input/output code
+        self.instructions: list[Instruction] = instructions
+        self.indexof: dict[Instruction, int] = get_indexof(self.instructions)
+        self.f_locals: dict[str, Any] = (
+            f_locals  # needed for recording accessed locals for replay
+        )
+        self.f_globals: dict[str, Any] = f_globals
+        self.f_builtins: dict[str, Any] = f_builtins
+        self.code_options: dict[str, Any] = code_options
+        self.f_code: types.CodeType = f_code
+
+        # Execution record for replaying errors
+        if closure is not None and config.replay_record_enabled:
+            self.exec_recorder = ExecutionRecorder(
+                code=f_code, closure=closure, code_options=code_options
+            )
+        else:
+            self.exec_recorder = None
+        # Stack of module being parsed, current nn.module is at the end of ordered dict.
+        # The first field of tuple is the fully qualified name of current module
+        # in original hierarchy.  The second field is the type of current nn.module
+        self.nn_module_stack: dict[str, tuple[str, type[Any]]] = {}
+        self.num_calls: dict[str, int] = {}
+        # Flag to indicate whether tracing is used for export.
+        self.export = export
+        self.one_graph = False
+
+        self.current_speculation = None
+
+        self.strict_checks_fn = None
+
+        if sys.version_info >= (3, 10):
+            from .resume_execution import (
+                CO_ASYNC_GENERATOR,
+                CO_COROUTINE,
+                CO_GENERATOR,
+                CO_ITERABLE_COROUTINE,
+            )
+
+            if f_code.co_flags & (
+                CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR
+            ):
+                self.push(BuiltinVariable(None))
+
+        self.inline_depth = inline_depth
+        self.inconsistent_side_effects = False
+        self._constants_cache: list[Optional[VariableTracker]] = [None] * len(
+            f_code.co_consts
+        )
+        linecache.lazycache(f_code.co_filename, f_globals)
+
+
+class InstructionTranslator(InstructionTranslatorBase):
+    @staticmethod
+    def current_tx() -> "InstructionTranslator":
+        return tls.current_tx
+
+    @contextlib.contextmanager
+    def set_current_tx(self):
+        prior = getattr(tls, "current_tx", None)
+        tls.current_tx = self
+        try:
+            yield
+        finally:
+            tls.current_tx = prior
+
+    def __init__(
+        self,
+        instructions: list[Instruction],
+        f_code,
+        f_locals,
+        f_globals,
+        f_builtins,
+        closure,
+        torch_function_mode_stack,
+        code_options,
+        compiler_fn,
+        one_graph,
+        export,
+        export_constraints,
+        frame_state,
+        speculation_log: SpeculationLog,
+        exn_vt_stack: ExceptionStack,
+        distributed_state: Optional[DistributedState],
+    ) -> None:
+        _step_logger()(
+            logging.INFO,
+            f"torchdynamo start tracing {f_code.co_name} {code_options['co_filename']}:{code_options['co_firstlineno']}",
+        )
+        super().__init__(
+            output=OutputGraph(
+                code_options,
+                compiler_fn,
+                self,
+                export,
+                export_constraints,
+                frame_state,
+                local_scope=f_locals,
+                global_scope=f_globals,
+                f_code=f_code,
+                torch_function_mode_stack=torch_function_mode_stack,
+            ),
+            instructions=instructions,
+            f_locals=f_locals,
+            f_globals=f_globals,
+            f_builtins=f_builtins,
+            closure=closure,
+            code_options=code_options,
+            symbolic_locals={},  # set below
+            # A global var is inserted only after a STORE_GLOBAL happens to it
+            symbolic_globals={},
+            symbolic_torch_function_state=None,  # type: ignore[arg-type] # set below
+            f_code=f_code,
+            export=export,
+            inline_depth=0,
+            speculation_log=speculation_log,
+            exn_vt_stack=exn_vt_stack,
+            distributed_state=distributed_state,
+        )
+
+        self._throw_if_in_functorch()
+
+        # as soon as we create the tracing context we should keep it active, so any calls
+        # into dynamo apis can rely on finding it
+        with tracing(self.output.tracing_context), self.set_current_tx():
+            self.one_graph: bool = one_graph
+            self.export = export
+            if self.export:
+                assert self.one_graph, (
+                    "Export without one graph - something has gone wrong."
+                )
+
+            self.symbolic_locals = {}
+            # Populate `symbolic_locals` with non-cell variables.
+            cell_and_freevars: set[str] = set(self.cell_and_freevars())
+
+            dynamism = code_context.get_context(f_code).get("dynamism", None)
+            for name, value in f_locals.items():
+                if name not in cell_and_freevars:
+                    local_dynamism = None
+                    if dynamism:
+                        local_dynamism = frozenset(dynamism.get(name, {}).items())
+                    var = LazyVariableTracker.create(
+                        value,
+                        LocalSource(
+                            name,
+                            is_input=True,
+                            dynamism=local_dynamism,
+                        ),
+                    )
+                    self.symbolic_locals[name] = var
+
+            # Populate `symbolic_locals` with cells created by this frame,
+            # effectively implementing the `MAKE_CELL` instructions.
+            side_effects = self.output.side_effects
+            for name in self.cellvars():
+                if name in f_locals:
+                    # This models cells that are also function inputs.
+                    value = f_locals[name]
+                    # NOTE: root frame inputs that are captured by a nested
+                    # function become special cell objects -- they exist in
+                    # `f_locals` as contents of the cells, rather than the cells
+                    # objects themselves.
+                    #
+                    # In Dynamo, we choose to represent such input cell objects
+                    # as newly created (rather than pre-existing) cell objects,
+                    # because
+                    #
+                    # 1. The reason for representing a pre-existing cell object
+                    # is to emit guard or codegen mutations. However, local
+                    # cells should never be used for guards. Moreover, at this
+                    # point these input cell objects should've never been
+                    # accessed by anyone else, since Dynamo intercepts the frame
+                    # right after its evaluation starts, i.e., right after these
+                    # cell objects are created. So they should have no external
+                    # reference, meaning no mutation needs to be propagated.
+                    #
+                    # 2. This conveniently allows codegen to prune away
+                    # mutations to these cells, unless they escape the frame.
+                    contents_source = LocalSource(
+                        name, is_input=True, is_derefed_cell_contents=True
+                    )
+                    contents_var: VariableTracker = LazyVariableTracker.create(
+                        value, contents_source
+                    )
+                    cell_var = side_effects.track_cell_new()
+                    side_effects.store_cell(cell_var, contents_var)
+                else:
+                    cell_var = side_effects.track_cell_new()
+                cell_var.local_name = name
+                self.symbolic_locals[name] = cell_var
+
+            # Populate `symbolic_locals` with cells captured by this frame,
+            # effectively implementing the `COPY_FREE_VARS` instruction.
+            for name, cell in zip(self.freevars(), closure):
+                cell_source = LocalCellSource(name)
+                contents_source = LocalSource(name, is_derefed_cell_contents=True)
+                try:
+                    contents_var = LazyVariableTracker.create(
+                        cell.cell_contents, contents_source
+                    )
+                except ValueError:
+                    # Cell has not yet been assigned
+                    contents_var = variables.DeletedVariable()
+                cell_var = side_effects.track_cell_existing(
+                    cell_source, cell, contents_var
+                )
+                cell_var.local_name = name
+                self.symbolic_locals[name] = cell_var
+
+            self.symbolic_torch_function_state = SymbolicTorchFunctionState(
+                torch_function_mode_stack
+            )
+
+            self.debug_locals: list[tuple[VariableTracker, list[VariableTracker]]] = []
+            if export:
+                # export gets confused if we never realize unused inputs
+                # in export mode just eagerly realize everything
+                self.symbolic_locals = variables.LazyVariableTracker.realize_all(
+                    self.symbolic_locals
+                )
+
+    def _throw_if_in_functorch(self):
+        # Fallback to eager in case of a graph break inside vmap
+        eager = torch._dynamo.lookup_backend("eager")
+        compiler_fn = inspect.getattr_static(
+            self.output.compiler_fn, "compiler_fn", self.output.compiler_fn
+        )
+        ci = torch._C._functorch.peek_interpreter_stack()
+        forbidden_keys = (
+            torch._C._functorch.TransformType.Vmap,
+            torch._C._functorch.TransformType.Grad,
+            torch._C._functorch.TransformType.Jvp,
+        )
+
+        if ci is not None and ci.key() in forbidden_keys and compiler_fn is not eager:
+            name = ci.key().name.lower()
+            msg = (
+                "If you are reaching here, it means dynamo failed for one of the following reasons:\n"
+                # Calling a torch.compiled function
+                f"- Calling torch.func.{name}(compiled_fn) function from eager mode is not supported. "
+                f"Ensure that torch.func.{name} is also wrapped within a torch.compile function. "
+                "For more information, see PyTorch issue #128711.\n"
+                # if it reaches here, it means Dynamo failed to inline a functorch function
+                f"- torch.func.{name}(fn) requires the function to be inlined by dynamo"
+            )
+            unimplemented_v2(
+                gb_type="Unsupported functorch tracing attempt",
+                context="",
+                explanation=msg,
+                hints=[],
+            )
+
+    def get_example_value(self, source: Source):
+        if isinstance(source, LocalSource):
+            return self.f_locals[source.local_name]
+        if isinstance(source, GlobalSource):
+            return self.f_globals[source.global_name]
+        raise KeyError
+
+    def run(self):
+        super().run()
+
+    def should_compile_partial_graph(self):
+        if sys.version_info >= (3, 11):
+            # Do not compile if current instruction's block is not the top with block
+            entry = self.current_instruction.exn_tab_entry
+            if entry and (
+                not self.block_stack or entry.target is not self.block_stack[-1].target
+            ):
+                return False
+        return (
+            all(b.can_restore() for b in self.block_stack)
+            and not self.one_graph
+            and not self.active_generic_context_managers
+        )
+
+    def create_call_resume_at(self, inst):
+        self.instruction_pointer = None
+
+        if inst.opname == "RETURN_VALUE":
+            return [create_instruction("RETURN_VALUE")]
+        elif inst.opname == "RETURN_CONST":
+            return [create_instruction("RETURN_CONST", argval=inst.argval)]
+
+        reads = livevars_analysis(self.instructions, inst)
+        all_argnames = tuple(
+            k
+            for k in self.symbolic_locals.keys()
+            if k in reads and k not in self.cell_and_freevars()
+        )
+        # NOTE: do not use isinstance, since it realizes lazy VT's
+        argnames = tuple(
+            k
+            for k in all_argnames
+            if not type.__instancecheck__(NullVariable, self.symbolic_locals[k])
+        )
+        argnames_null = tuple(
+            k
+            for k in all_argnames
+            if type.__instancecheck__(NullVariable, self.symbolic_locals[k])
+        )
+        if sys.version_info < (3, 12):
+            assert len(argnames_null) == 0, "variables should not be NULL in < 3.12"
+
+        cg = PyCodegen(self)
+
+        # Handle inactive context variables.
+        # The resume function assumes that context variables are the class, NOT the object.
+        # e.g. torch.set_grad_enabled(True) will be reconstructed as torch.set_grad_enabled
+        stack_ctx_vars = []
+        for i, var in enumerate(self.stack):
+            if type.__instancecheck__(ContextWrappingVariable, var):
+                ctx = cast(ContextWrappingVariable, var)
+                target_values = (
+                    () if ctx.target_values is None else tuple(ctx.target_values)
+                )
+                stack_ctx_vars.append((i, target_values))
+                # Replace the current stack var with the context class
+                ctx.reconstruct_type(cg)
+                cg.extend_output(create_swap(len(self.stack) - i + 1))
+                cg.append_output(create_instruction("POP_TOP"))
+
+        argnames_ctx_vars = []
+        for name in argnames:
+            if type.__instancecheck__(
+                ContextWrappingVariable, var := self.symbolic_locals[name]
+            ):
+                ctx = cast(ContextWrappingVariable, var)
+                target_values = (
+                    () if ctx.target_values is None else tuple(ctx.target_values)
+                )
+                argnames_ctx_vars.append((name, target_values))
+                # Replace the local with the context class
+                ctx.reconstruct_type(cg)
+                cg.append_output(create_instruction("STORE_FAST", argval=name))
+
+        # Python does not allow null to be an arg to a function, so
+        # we remove nulls from the stack and restore them in the
+        # prologue of the resume function
+
+        # sorted list of indices of nulls on the stack
+        null_idxes: list[int] = []
+        if sys.version_info >= (3, 11):
+            # find indices of NullVariables
+            for i, var in enumerate(self.stack):
+                if type.__instancecheck__(NullVariable, var):
+                    null_idxes.append(i)
+            # generate bytecode to pop the nulls
+            null_cnt = 0
+            for i, var in enumerate(reversed(self.stack)):
+                if type.__instancecheck__(NullVariable, var):
+                    for j in range(2, i + 2 - null_cnt):
+                        cg.append_output(create_instruction("SWAP", arg=j))
+                    cg.extend_output(cg.pop_null())
+                    null_cnt += 1
+
+        # we popped all nulls from the stack at runtime,
+        # so we should not count NullVariables
+        stack_len = len(self.stack) - len(null_idxes)
+        nargs = stack_len + len(argnames)
+
+        name = unique_id(f"__resume_at_{inst.offset}")
+
+        new_code: types.CodeType = ContinueExecutionCache.lookup(
+            self.f_code,
+            self.lineno,
+            inst.offset,
+            tuple(b.target.offset for b in self.block_stack),
+            stack_len,
+            argnames,
+            argnames_null,
+            tuple(b.resume_fn() for b in self.block_stack),
+            tuple(stack_ctx_vars),
+            tuple(argnames_ctx_vars),
+            tuple(null_idxes),
+        )
+
+        # Add original GraphModule context to the resume function to handle
+        # the case of a graph break while tracing a GraphModule
+        orig_graphmodule_maybe = code_context.get_context(self.f_code).get(
+            "orig_graphmodule", lambda: None
+        )()
+        if orig_graphmodule_maybe is not None:
+            code_context.get_context(new_code)["orig_graphmodule"] = weakref.ref(
+                orig_graphmodule_maybe
+            )
+
+        if new_code.co_freevars:
+            # expose code object for debugging purposes
+            self.output.install_global_unsafe(name, new_code)
+            cg.make_function_with_closure(name, new_code, True, stack_len)
+        else:
+            # This is safe: we pre-generate a unique name
+            self.output.install_global_unsafe(
+                name, types.FunctionType(new_code, self.f_globals, name)
+            )
+            cg.extend_output(cg.load_function_name(name, True, stack_len))
+
+        cg.extend_output([cg.create_load(k) for k in argnames])
+        cg.extend_output(create_call_function(nargs, False))
+        cg.append_output(create_instruction("RETURN_VALUE"))
+        return cg.get_instructions()
+
+    def symbolic_locals_contain_module_class(self):
+        for v in self.symbolic_locals.values():
+            if isinstance(v, UserDefinedClassVariable) and issubclass(
+                v.as_python_constant(), torch.nn.Module
+            ):
+                return True
+        return False
+
+    def replace_tos_if_return_is_generator(self):
+        if (
+            len(self.stack)
+            and (tos := self.stack[-1])
+            and isinstance(tos, LocalGeneratorObjectVariable)
+        ):
+            self.stack[-1] = ListIteratorVariable(
+                tos.force_unpack_var_sequence(self),
+                mutation_type=ValueMutationNew(),
+            )
+
+    def _return(self, inst):
+        self.replace_tos_if_return_is_generator()
+        assert self.instruction_pointer is not None
+        assert self.start_point is not None
+        get_metrics_context().increment(
+            "ir_count", self.instruction_pointer - self.start_point
+        )
+
+        if (
+            not config.allow_empty_graphs
+            and self.output.count_calls() == 0
+            and not self.inconsistent_side_effects
+            and not self.symbolic_locals_contain_module_class()
+            and not self.export
+            and not self.one_graph
+        ):
+            raise exc.SkipFrame("because no content in function call")
+
+        self.instruction_pointer = None
+        _step_logger()(
+            logging.INFO,
+            f"torchdynamo done tracing {self.f_code.co_name} ({inst.opname})",
+        )
+        log.debug("%s triggered compile", inst.opname)
+        self.output.compile_subgraph(
+            self,
+            reason=GraphCompileReason(
+                "return_value", [self.frame_summary()], graph_break=False
+            ),
+        )
+        return_inst = (
+            create_instruction("RETURN_VALUE")
+            if inst.opname == "RETURN_VALUE"
+            else create_instruction("RETURN_CONST", argval=inst.argval)
+        )
+        self.output.add_output_instructions([return_inst])
+        raise ReturnValueOp
+
+    def RETURN_VALUE(self, inst):
+        self._return(inst)
+
+    def RETURN_CONST(self, inst):
+        self._return(inst)
+
+
+if sys.version_info >= (3, 11):
+    _binary_op_lookup = [
+        getattr(
+            InstructionTranslator,
+            opname[3:] if "INPLACE" in opname else f"BINARY_{opname[3:]}",
+        )
+        for opname, _ in dis._nb_ops  # type: ignore[attr-defined]
+    ]
+
+
+class InliningInstructionTranslator(InstructionTranslatorBase):
+    """Trace and inline a called method"""
+
+    symbolic_result: Optional[VariableTracker]
+
+    @classmethod
+    def inline_call(cls, parent, func, args, kwargs):
+        with patch.dict(counters, {"unimplemented": counters["inline_call"]}):
+            tracer = cls.build_inline_tracer(parent, func, args, kwargs)
+            return tracer.inline_call_()
+
+    @staticmethod
+    def check_inlineable(func):
+        if func.has_self():
+            unimplemented_v2(
+                gb_type="Inline attempt with __self__",
+                context=str(func),
+                explanation="Attempted to inline a function with the `__self__` attribute. "
+                "Dynamo is expected to decompose method calls into function calls with a `self` argument.",
+                hints=[],
+            )
+
+        result = trace_rules.check_verbose(func, is_inlined_call=True)
+        if result.skipped:
+            from torch._dynamo.variables.misc import produce_trampoline_autograd_apply
+
+            # _origin marks this as coming from an internal dynamo known function that is safe to
+            # trace through.
+            if hasattr(getattr(func, "fn", None), "_origin") and func.fn._origin in [
+                produce_trampoline_autograd_apply,
+            ]:
+                # Known sound
+                return trace_rules.SkipResult(
+                    False, "allowlist in dynamo known function"
+                )
+            fn_qualname = func.fn.__qualname__ if hasattr(func, "fn") else ""
+            hints = [
+                f"Avoid calling the function `{fn_qualname}`.",
+            ]
+            if "_dynamo" not in func.get_filename():
+                hints += [
+                    f"Remove the function `{fn_qualname}` or the file `{func.get_filename()}` "
+                    "from torch/_dynamo/trace_rules.py. More graph breaks may occur as a result of "
+                    "attempting to trace into the function.",
+                    "Please file an issue to PyTorch.",
+                    # TODO suggest mark_force_inline when implemented
+                ]
+            unimplemented_v2(
+                gb_type="Attempted to inline function marked as skipped",
+                context=f"qualname: {fn_qualname}, name: {func.get_name()}, "
+                f"filename: `{func.get_filename()}`, skip reason: {result.reason}",
+                explanation=f"Dynamo developers have intentionally marked that the function `{fn_qualname}` "
+                "should not be traced.",
+                hints=hints,
+            )
+
+        if isinstance(func, UserFunctionVariable) and inspect.getattr_static(
+            func.get_function(), "_torchdynamo_disable", False
+        ):
+            unimplemented_v2(
+                gb_type="Skip inlining `torch.compiler.disable()`d function",
+                context=str(func.get_function()),
+                explanation=f"Skip inlining function {func.get_function()} since it was wrapped with `torch.compiler.disable`",
+                hints=[
+                    "Remove the `torch.compiler.disable` call",
+                ],
+            )
+        else:
+            return result
+
+    @staticmethod
+    def build_inline_tracer(
+        parent,
+        func: VariableTracker,
+        args: list[VariableTracker],
+        kwargs,
+    ):
+        if isinstance(func, SkipFunctionVariable):
+            unimplemented_v2(
+                gb_type="Attempted to inline function marked as skipped (SkipFunctionVariable)",
+                context=f"Attempted to inline a SkipFunctionVariable {func}",
+                explanation="Attempted to inline a function that was previously determined to be marked as intentionally skipped.",
+                hints=[],
+            )
+        assert isinstance(
+            func,
+            (
+                UserFunctionVariable,
+                NestedUserFunctionVariable,
+                LocalGeneratorFunctionVariable,
+                LocalGeneratorObjectVariable,
+            ),
+        )
+        result = InliningInstructionTranslator.check_inlineable(func)
+        assert result.skipped is False
+        try:
+            sub_locals = func.bind_args(parent, args, kwargs)
+        except TypeError as e:
+            # Wrap the general TypeError during bind_args() to the internal ArgsMismatchError with detailed info
+            raise ArgsMismatchError(  # noqa: B904
+                "{reason}.\n  func = {func}, args = {args}, kwargs = {kwargs}".format(
+                    reason=str(e),
+                    func=f"'{func.get_name()}' {func.get_filename()}:{func.get_code().co_firstlineno}",
+                    args=[arg.python_type() for arg in args],
+                    kwargs=kwargs,
+                ),
+            )
+
+        for v in itertools.chain(sub_locals.values()):
+            if not isinstance(v, VariableTracker):
+                unimplemented_v2(
+                    gb_type="Encountered unconverted argument when attempting to inline",
+                    context=f"func: {func}, arg: {v}",
+                    explanation="An argument to an inlined function was not successfully converted to a VariableTracker.",
+                    hints=[*graph_break_hints.DYNAMO_BUG],
+                )
+
+        code: types.CodeType = func.get_code()
+        if code.co_name in ("__setitem__", "__setattr__") and not (
+            args and isinstance(args[0], variables.UserDefinedObjectVariable)
+        ):
+            unimplemented_v2(
+                gb_type="Unsupported __setitem__/__setattr__ inline attempt",
+                context=f"code name: {code.co_name}, args: {args}",
+                explanation=f"Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.",
+                hints=[],
+            )
+
+        suffix = ""
+        # TODO: mlazos, add support for enabling multiple artifact logs
+        # with a single alias
+        if torch._logging._internal.log_state.is_artifact_enabled("bytecode"):
+            suffix = f"\n{dis.Bytecode(code).dis()}"
+        if sys.version_info >= (3, 11):
+            cur_inst = parent.current_instruction
+            parent_code = parent.f_code
+            header = parent.get_line_of_code_header(lineno=cur_inst.positions.lineno)
+
+            def get_trace_call_log_str():
+                line = get_instruction_source_311(parent_code, cur_inst).rstrip()
+                return f"TRACE inlined call {code.co_name} from {header}\n{line}"
+
+            trace_call_log.debug("%s", LazyString(get_trace_call_log_str))
+        log.debug("INLINING %s%s, %s", code, suffix, result.reason)
+
+        # Detect inline GraphModule calls in order to propagate node metadata,
+        # by checking if the first argument (self) is a variable tracking a GraphModule.
+        if args and isinstance(args[0], NNModuleVariable):
+            module = parent.output.get_submodule(args[0].module_key)
+            if isinstance(module, torch.fx.GraphModule):
+                # The inline call might not actually be a call to `forward`,
+                # but it is enough to add a context for `forward` in case it is called.
+                code_context.get_context(module.forward.__code__)[
+                    "orig_graphmodule"
+                ] = weakref.ref(module)
+
+        tracer: InliningInstructionTranslator
+        if is_generator(code):
+            tracer = InliningGeneratorInstructionTranslator(
+                parent,
+                code,
+                sub_locals,
+                parent.symbolic_globals,
+                parent.symbolic_torch_function_state,
+                func,
+            )
+        else:
+            # need the line below to make MyPy happy
+            assert not isinstance(func, LocalGeneratorObjectVariable)
+            tracer = InliningInstructionTranslator(
+                parent,
+                code,
+                sub_locals,
+                parent.symbolic_globals,
+                parent.symbolic_torch_function_state,
+                func,
+            )
+        return tracer
+
+    def inline_call_(self):
+        parent = self.parent
+        code = self.f_code
+
+        strict_ctx: Any = contextlib.nullcontext()
+        if parent.strict_checks_fn:
+            strict_ctx = self.strict_translation_mode(parent.strict_checks_fn)
+        try:
+            with strict_ctx:
+                self.run()
+        except exc.ObservedException as e:
+            msg = f"Observed exception DURING INLING {code} : {e}"
+            log.debug(msg)
+            # bubble up the exception to the parent frame.
+            raise
+        except exc.SkipFrame as e:
+            msg = f"SKIPPED INLINING {code}: {e}"
+            log.debug(msg)
+            raise Unsupported(msg) from e
+        except Exception:
+            log.debug("FAILED INLINING %s", code)
+            raise
+        assert self.symbolic_result is not None
+
+        if self.f_globals is parent.f_globals:
+            # Merge symbolic_globals back if parent and child are in the same namespace
+            parent.symbolic_globals.update(self.symbolic_globals)
+
+        parent.inconsistent_side_effects |= self.inconsistent_side_effects
+
+        log.debug("DONE INLINING %s", code)
+
+        if config.enable_faithful_generator_behavior or (
+            isinstance(self, InliningGeneratorInstructionTranslator)
+            and self.is_generator_from_ctx_manager
+        ):
+            if (
+                is_generator(code)
+                and isinstance(self, InliningGeneratorInstructionTranslator)
+                and self.generator_exhausted
+            ):
+                assert isinstance(self, InliningGeneratorInstructionTranslator)
+                # When the generator returns None, we raise StopIteration
+                exc.raise_observed_exception(StopIteration, self)
+            else:
+                return self.symbolic_result
+        else:
+            if is_generator(code):
+                assert isinstance(self, InliningGeneratorInstructionTranslator)
+                assert self.symbolic_result.as_python_constant() is None
+                return ListIteratorVariable(
+                    self.generated_items,
+                    mutation_type=ValueMutationNew(),
+                )
+            else:
+                return self.symbolic_result
+
+    def __init__(
+        self,
+        parent: InstructionTranslatorBase,
+        code: types.CodeType,
+        symbolic_locals: dict[str, VariableTracker],
+        symbolic_globals: dict[str, VariableTracker],
+        symbolic_torch_function_state: SymbolicTorchFunctionState,
+        funcvar: BaseUserFunctionVariable,
+    ) -> None:
+        f_globals = funcvar.get_globals()  # type: ignore[attr-defined]
+        f_builtins = f_globals["__builtins__"]
+        if not isinstance(f_builtins, dict):
+            f_builtins = f_builtins.__dict__
+        instructions = cleaned_instructions(code)
+        propagate_line_nums(instructions)
+        super().__init__(
+            output=parent.output,
+            f_locals={},
+            f_globals=f_globals,
+            f_builtins=f_builtins,
+            symbolic_locals=symbolic_locals,
+            symbolic_globals=symbolic_globals,
+            symbolic_torch_function_state=symbolic_torch_function_state,
+            instructions=instructions,
+            code_options={k: getattr(code, k) for k in get_code_keys()},
+            f_code=code,
+            export=parent.export,
+            inline_depth=parent.inline_depth + 1,
+            speculation_log=parent.speculation_log,
+            exn_vt_stack=parent.exn_vt_stack,
+            distributed_state=parent.distributed_state,
+        )
+        self.funcvar = funcvar
+        self.parent = parent
+        self.num_calls = parent.num_calls
+        self.symbolic_result = None
+        self.nn_module_stack = parent.nn_module_stack.copy()
+        self.one_graph = parent.one_graph
+
+    @property
+    def fake_mode(self):
+        return self.parent.fake_mode
+
+    def run_ctx_mgr(self):
+        return TracingContext.current_frame(self.parent.frame_summary())
+
+    def should_compile_partial_graph(self):
+        return False  # inlining functions is all-or-nothing
+
+    def create_call_resume_at(self, offset):
+        unimplemented_v2(
+            gb_type="Graph break in inlined function",
+            context="",
+            explanation="Graph breaks in an inlined call are not supported.",
+            hints=[],
+        )
+
+    def RETURN_VALUE(self, inst):
+        self.symbolic_result = self.pop()  # type: ignore[assignment]
+        self.instruction_pointer = None
+        raise ReturnValueOp
+
+    def RETURN_CONST(self, inst):
+        self.symbolic_result = self._load_const(inst)
+        self.instruction_pointer = None
+        raise ReturnValueOp
+
+    def get_globals_source_and_value(self, name):
+        if "__name__" in self.f_globals:
+            module_name = self.f_globals["__name__"]
+            module_source = self.import_source(module_name)
+            if "torch_package" in module_name:
+                fglobals_value = (
+                    torch.package.package_importer._package_imported_modules[
+                        module_name
+                    ]
+                )  # type: ignore[assignment]
+            else:
+                fglobals_value = _import_module(module_name)
+            fglobals_vt = VariableTracker.build(self, fglobals_value, module_source)
+            global_source = AttrSource(module_source, name)
+        else:
+            globals_name = self.output.install_global_by_id(
+                "___unnamed_scope", self.f_globals
+            )
+            globals_source = GlobalSource(globals_name)
+            fglobals_value = self.f_globals  # type: ignore[assignment]
+            fglobals_vt = VariableTracker.build(self, fglobals_value, globals_source)
+            global_source = DictGetItemSource(globals_source, name)  # type: ignore[assignment]
+        return fglobals_value, fglobals_vt, global_source
+
+    def _load_global(self, inst):
+        if self.output.global_scope is self.f_globals:
+            # If the global scope matches that of the root frame, use handler in
+            # root frame instruction translator, to enforce consistency.
+            super()._load_global(inst)
+        else:
+            name = inst.argval
+
+            _, fglobals_vt, global_source = self.get_globals_source_and_value(name)
+            if self.output.side_effects.has_pending_mutation_of_attr(fglobals_vt, name):
+                self.push(self.output.side_effects.load_attr(fglobals_vt, name))
+            else:
+                try:
+                    value = self.f_globals[name]
+                except KeyError:
+                    return self.load_builtin(inst)
+
+                self.push(VariableTracker.build(self, value, global_source))
+
+    def STORE_GLOBAL(self, inst):
+        if self.output.global_scope is self.f_globals:
+            # If the global scope matches that of the root frame, use handler in
+            # root frame instruction translator, to enforce consistency.
+            super().STORE_GLOBAL(inst)
+        else:
+            value = self.pop()
+            if isinstance(value, RemovableHandleVariable):
+                unimplemented_v2(
+                    gb_type="Storing Tensor hook handle in globals (inline call)",
+                    context=inst.argval,
+                    explanation="This is not supported.",
+                    hints=[],
+                )
+            name = inst.argval
+            _fglobals_value, fglobals_vt, _ = self.get_globals_source_and_value(name)
+            self.output.side_effects.store_attr(fglobals_vt, name, value)
+
+
+class InliningGeneratorInstructionTranslator(InliningInstructionTranslator):
+    generated_items: list[VariableTracker]
+    # Flag wether or not the InlineGenerator should consume the entire iterator
+
+    def __init__(self, *args, **kwargs) -> None:
+        super().__init__(*args, **kwargs)
+        self.generated_items = []
+        self.generator_exhausted = False
+        self.is_generator_from_ctx_manager = False
+
+    def YIELD_VALUE(self, inst: Instruction):
+        top = self.pop()
+        self.generated_items.append(top)
+        if len(self.generated_items) > MAX_ITERATOR_LIMIT:
+            raise exc.InfiniteGeneratorError(
+                "Too many yield values in generator. Maybe you are inlining an infinite generator. "
+                f"If not, please report a bug at {PT2_ISSUE_TRACKER_URL}",
+            )
+        self.push(ConstantVariable.create(None))
+        if (
+            config.enable_faithful_generator_behavior
+            or self.is_generator_from_ctx_manager
+        ):
+            self.symbolic_result = top
+            # Stop tracing
+            raise YieldValueOp
+
+    def GET_YIELD_FROM_ITER(self, inst):
+        tos = self.stack[-1]
+        if not isinstance(tos, ListIteratorVariable):
+            self.pop()
+            res = BuiltinVariable(iter).call_function(self, [tos], {})  # type: ignore[arg-type]
+            self.push(res)
+
+    def RETURN_VALUE(self, inst):
+        self.generator_exhausted = True
+        return super().RETURN_VALUE(inst)
+
+    def RETURN_CONST(self, inst):
+        self.generator_exhausted = True
+        return super().RETURN_CONST(inst)
+
+    def YIELD_FROM(self, inst):
+        assert len(self.stack) >= 2
+        val = self.pop()
+        tos = self.stack[-1]
+        if not (isinstance(val, ConstantVariable) and val.value is None):
+            # invoke send
+            # Unreachable code - if you hit this, you are implementing generator support and have
+            # lifted the `unimplemented("generator")` in frame conversion. This codepath handles
+            # subgenerator and lines up with this line in Python 3.10
+            # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L2599
+            unimplemented_v2(
+                gb_type="Unreachable sub-generator code",
+                context="",
+                explanation="Should only be encountered while implementing generator support.",
+                hints=[],
+            )
+
+        try:
+            val = tos.next_variable(self)
+        except (StopIteration, exc.ObservedUserStopIteration) as ex:
+            if isinstance(ex, exc.ObservedUserStopIteration):
+                exc.handle_observed_exception(self)
+
+            # The iterator is exhausted. Stop the loop and return.
+            self.pop()
+            self.push(ConstantVariable.create(ex.value))
+        else:
+            # Repeat the YIELD_FROM instruction in the next eval loop
+            assert (
+                isinstance(self.instruction_pointer, int)
+                and self.instruction_pointer > 0
+            )
+            self.instruction_pointer -= 1
+
+            self.push(val)
+            # Add the value to yield into generated_items and replace the top of the stack with None
+            self.YIELD_VALUE(inst)
+
+    def SEND(self, inst):
+        assert len(self.stack) >= 2
+        val = self.pop()
+        tos = self.stack[-1]
+        if isinstance(tos, (ListIteratorVariable, LocalGeneratorObjectVariable)) or (
+            isinstance(tos, UserDefinedObjectVariable)
+            and isinstance(tos.value, collections.abc.Iterator)
+        ):
+            if isinstance(val, ConstantVariable) and val.value is None:
+                try:
+                    val = tos.next_variable(self)
+                except (StopIteration, exc.ObservedUserStopIteration) as ex:
+                    # To implement SEND, we have to look at the implementation
+                    # when the iterator returns StopIteration. This translates to this code
+                    # 3.11: https://github.com/python/cpython/blob/3.11/Python/ceval.c#L2613-L2619
+                    # 3.12: https://github.com/python/cpython/blob/3.12/Python/bytecodes.c#L863-L866
+                    # The implementation is different in 3.11 and 3.12. In 3.12, we rely
+                    # on END_SEND to clean up. In 3.11, SEND does the cleanup as well.
+                    if sys.version_info < (3, 12):
+                        self.pop()  # Python 3.12 uses new opcode END_SEND
+                    self.push(ConstantVariable.create(ex.value))
+                    self.jump(inst)
+                else:
+                    self.push(val)
+            else:
+                # invoke send
+                # Unreachable code - if you hit this, you are implementing generator support and have
+                # lifted the `unimplemented("generator")` in frame conversion. This codepath handles
+                # subgenerator and lines up with this line in Python 3.11
+                # https://github.com/python/cpython/blob/3.11/Python/ceval.c#L2597
+                unimplemented_v2(
+                    gb_type="Unreachable sub-generator code",
+                    context="",
+                    explanation="Should only be encountered while implementing generator support.",
+                    hints=[],
+                )
+        else:
+            unimplemented_v2(
+                gb_type="SEND with bad type",
+                context=f"TOS type: {typestr(tos)}",
+                explanation=f"Attempted to SEND with unsupported type {typestr(tos)}.",
+                hints=[],
+            )
diff --git a/shared/package-files/e6/e6f1b3de95c9e4bdead5792898f757f9966d20822f74353bb40dead613cccd31/linalg_matrix_rank_ops.h b/shared/package-files/e6/e6f1b3de95c9e4bdead5792898f757f9966d20822f74353bb40dead613cccd31/linalg_matrix_rank_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..9a0ca4360f72ff775fb4fbc050d9bcf3331e6d99
--- /dev/null
+++ b/shared/package-files/e6/e6f1b3de95c9e4bdead5792898f757f9966d20822f74353bb40dead613cccd31/linalg_matrix_rank_ops.h
@@ -0,0 +1,106 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API linalg_matrix_rank_atol_rtol_tensor {
+  using schema = at::Tensor (const at::Tensor &, const ::std::optional &, const ::std::optional &, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "atol_rtol_tensor";
+  static constexpr const char* schema_str = "linalg_matrix_rank.atol_rtol_tensor(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor";
+  static at::Tensor call(const at::Tensor & input, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian);
+};
+
+struct TORCH_API linalg_matrix_rank_atol_rtol_tensor_out {
+  using schema = at::Tensor & (const at::Tensor &, const ::std::optional &, const ::std::optional &, bool, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "atol_rtol_tensor_out";
+  static constexpr const char* schema_str = "linalg_matrix_rank.atol_rtol_tensor_out(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & input, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian, at::Tensor & out);
+};
+
+struct TORCH_API linalg_matrix_rank_atol_rtol_float {
+  using schema = at::Tensor (const at::Tensor &, ::std::optional, ::std::optional, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "atol_rtol_float";
+  static constexpr const char* schema_str = "linalg_matrix_rank.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, ::std::optional atol, ::std::optional rtol, bool hermitian);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional atol, ::std::optional rtol, bool hermitian);
+};
+
+struct TORCH_API linalg_matrix_rank_atol_rtol_float_out {
+  using schema = at::Tensor & (const at::Tensor &, ::std::optional, ::std::optional, bool, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "atol_rtol_float_out";
+  static constexpr const char* schema_str = "linalg_matrix_rank.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, ::std::optional atol, ::std::optional rtol, bool hermitian, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional atol, ::std::optional rtol, bool hermitian, at::Tensor & out);
+};
+
+struct TORCH_API linalg_matrix_rank {
+  using schema = at::Tensor (const at::Tensor &, double, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "linalg_matrix_rank(Tensor self, float tol, bool hermitian=False) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, double tol, bool hermitian);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double tol, bool hermitian);
+};
+
+struct TORCH_API linalg_matrix_rank_out {
+  using schema = at::Tensor & (const at::Tensor &, double, bool, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "linalg_matrix_rank.out(Tensor self, float tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, double tol, bool hermitian, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double tol, bool hermitian, at::Tensor & out);
+};
+
+struct TORCH_API linalg_matrix_rank_tol_tensor {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "tol_tensor";
+  static constexpr const char* schema_str = "linalg_matrix_rank.tol_tensor(Tensor input, Tensor tol, bool hermitian=False) -> Tensor";
+  static at::Tensor call(const at::Tensor & input, const at::Tensor & tol, bool hermitian);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & tol, bool hermitian);
+};
+
+struct TORCH_API linalg_matrix_rank_out_tol_tensor {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::linalg_matrix_rank";
+  static constexpr const char* overload_name = "out_tol_tensor";
+  static constexpr const char* schema_str = "linalg_matrix_rank.out_tol_tensor(Tensor input, Tensor tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & input, const at::Tensor & tol, bool hermitian, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & tol, bool hermitian, at::Tensor & out);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e6f21452dc6a7e7a0dfbf415e61c4e53b75a9a2d95fcd9f45049e2f783584858/_scaled_dot_product_flash_attention_ops.h b/shared/package-files/e6/e6f21452dc6a7e7a0dfbf415e61c4e53b75a9a2d95fcd9f45049e2f783584858/_scaled_dot_product_flash_attention_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..54bee24c40c2ad328d3a261b39f43c0258d07064
--- /dev/null
+++ b/shared/package-files/e6/e6f21452dc6a7e7a0dfbf415e61c4e53b75a9a2d95fcd9f45049e2f783584858/_scaled_dot_product_flash_attention_ops.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _scaled_dot_product_flash_attention {
+  using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, double, bool, bool, ::std::optional);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::_scaled_dot_product_flash_attention";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "_scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask)";
+  static ::std::tuple call(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p, bool is_causal, bool return_debug_mask, ::std::optional scale);
+  static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p, bool is_causal, bool return_debug_mask, ::std::optional scale);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/e6/e6f9202633ca3c8a14cceffe00ed9f46ee62e19e7460a9fd7f50d268e546a839/common.cpython-311.pyc b/shared/package-files/e6/e6f9202633ca3c8a14cceffe00ed9f46ee62e19e7460a9fd7f50d268e546a839/common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a39e6474f27038832339098b157ca825bdad867
Binary files /dev/null and b/shared/package-files/e6/e6f9202633ca3c8a14cceffe00ed9f46ee62e19e7460a9fd7f50d268e546a839/common.cpython-311.pyc differ
diff --git a/shared/package-files/e6/e6fa967bffd646f26e0fab160b63530ded6a11c4e80464c66b27bd9738ab81fe/qapply.py b/shared/package-files/e6/e6fa967bffd646f26e0fab160b63530ded6a11c4e80464c66b27bd9738ab81fe/qapply.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2d8c92e51552c8114d65a1304fcd1925ae752f4
--- /dev/null
+++ b/shared/package-files/e6/e6fa967bffd646f26e0fab160b63530ded6a11c4e80464c66b27bd9738ab81fe/qapply.py
@@ -0,0 +1,263 @@
+"""Logic for applying operators to states.
+
+Todo:
+* Sometimes the final result needs to be expanded, we should do this by hand.
+"""
+
+from sympy.concrete import Sum
+from sympy.core.add import Add
+from sympy.core.kind import NumberKind
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify, _sympify
+
+from sympy.physics.quantum.anticommutator import AntiCommutator
+from sympy.physics.quantum.commutator import Commutator
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.innerproduct import InnerProduct
+from sympy.physics.quantum.operator import OuterProduct, Operator
+from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
+from sympy.physics.quantum.tensorproduct import TensorProduct
+
+__all__ = [
+    'qapply'
+]
+
+
+#-----------------------------------------------------------------------------
+# Main code
+#-----------------------------------------------------------------------------
+
+
+def ip_doit_func(e):
+    """Transform the inner products in an expression by calling ``.doit()``."""
+    return e.replace(InnerProduct, lambda *args: InnerProduct(*args).doit())
+
+
+def sum_doit_func(e):
+    """Transform the sums in an expression by calling ``.doit()``."""
+    return e.replace(Sum, lambda *args: Sum(*args).doit())
+
+
+def qapply(e, **options):
+    """Apply operators to states in a quantum expression.
+
+    Parameters
+    ==========
+
+    e : Expr
+        The expression containing operators and states. This expression tree
+        will be walked to find operators acting on states symbolically.
+    options : dict
+        A dict of key/value pairs that determine how the operator actions
+        are carried out.
+
+        The following options are valid:
+
+        * ``dagger``: try to apply Dagger operators to the left
+          (default: False).
+        * ``ip_doit``: call ``.doit()`` in inner products when they are
+          encountered (default: True).
+        * ``sum_doit``: call ``.doit()`` on sums when they are encountered
+          (default: False). This is helpful for collapsing sums over Kronecker
+          delta's that are created when calling ``qapply``.
+
+    Returns
+    =======
+
+    e : Expr
+        The original expression, but with the operators applied to states.
+
+    Examples
+    ========
+
+        >>> from sympy.physics.quantum import qapply, Ket, Bra
+        >>> b = Bra('b')
+        >>> k = Ket('k')
+        >>> A = k * b
+        >>> A
+        |k>>> qapply(A * b.dual / (b * b.dual))
+        |k>
+        >>> qapply(k.dual * A / (k.dual * k))
+         and A*(|a>+|b>) and all Commutators and
+    # TensorProducts. The only problem with this is that if we can't apply
+    # all the Operators, we have just expanded everything.
+    # TODO: don't expand the scalars in front of each Mul.
+    e = e.expand(commutator=True, tensorproduct=True)
+
+    # If we just have a raw ket, return it.
+    if isinstance(e, KetBase):
+        return e
+
+    # We have an Add(a, b, c, ...) and compute
+    # Add(qapply(a), qapply(b), ...)
+    elif isinstance(e, Add):
+        result = 0
+        for arg in e.args:
+            result += qapply(arg, **options)
+        return result.expand()
+
+    # For a Density operator call qapply on its state
+    elif isinstance(e, Density):
+        new_args = [(qapply(state, **options), prob) for (state,
+                     prob) in e.args]
+        return Density(*new_args)
+
+    # For a raw TensorProduct, call qapply on its args.
+    elif isinstance(e, TensorProduct):
+        return TensorProduct(*[qapply(t, **options) for t in e.args])
+
+    # For a Sum, call qapply on its function.
+    elif isinstance(e, Sum):
+        result = Sum(qapply(e.function, **options), *e.limits)
+        result = sum_doit_func(result) if sum_doit else result
+        return result
+
+    # For a Pow, call qapply on its base.
+    elif isinstance(e, Pow):
+        return qapply(e.base, **options)**e.exp
+
+    # We have a Mul where there might be actual operators to apply to kets.
+    elif isinstance(e, Mul):
+        c_part, nc_part = e.args_cnc()
+        c_mul = Mul(*c_part)
+        nc_mul = Mul(*nc_part)
+        if not nc_part: # If we only have a commuting part, just return it.
+            result = c_mul
+        elif isinstance(nc_mul, Mul):
+            result = c_mul*qapply_Mul(nc_mul, **options)
+        else:
+            result = c_mul*qapply(nc_mul, **options)
+        if result == e and dagger:
+            result = Dagger(qapply_Mul(Dagger(e), **options))
+        result = ip_doit_func(result) if ip_doit else result
+        result = sum_doit_func(result) if sum_doit else result
+        return result
+
+    # In all other cases (State, Operator, Pow, Commutator, InnerProduct,
+    # OuterProduct) we won't ever have operators to apply to kets.
+    else:
+        return e
+
+
+def qapply_Mul(e, **options):
+
+    args = list(e.args)
+    extra = S.One
+    result = None
+
+    # If we only have 0 or 1 args, we have nothing to do and return.
+    if len(args) <= 1 or not isinstance(e, Mul):
+        return e
+    rhs = args.pop()
+    lhs = args.pop()
+
+    # Make sure we have two non-commutative objects before proceeding.
+    if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \
+            (not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative):
+        return e
+
+    # For a Pow with an integer exponent, apply one of them and reduce the
+    # exponent by one.
+    if isinstance(lhs, Pow) and lhs.exp.is_Integer:
+        args.append(lhs.base**(lhs.exp - 1))
+        lhs = lhs.base
+
+    # Pull OuterProduct apart
+    if isinstance(lhs, OuterProduct):
+        args.append(lhs.ket)
+        lhs = lhs.bra
+
+    if isinstance(rhs, OuterProduct):
+        extra = rhs.bra # Append to the right of the result
+        rhs = rhs.ket
+
+    # Call .doit() on Commutator/AntiCommutator.
+    if isinstance(lhs, (Commutator, AntiCommutator)):
+        comm = lhs.doit()
+        if isinstance(comm, Add):
+            return qapply(
+                e.func(*(args + [comm.args[0], rhs])) +
+                e.func(*(args + [comm.args[1], rhs])),
+                **options
+            )*extra
+        else:
+            return qapply(e.func(*args)*comm*rhs, **options)*extra
+
+    # Apply tensor products of operators to states
+    if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
+            isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
+            len(lhs.args) == len(rhs.args):
+        result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
+        return qapply_Mul(e.func(*args), **options)*result*extra
+
+    # For Sums, move the Sum to the right.
+    if isinstance(rhs, Sum):
+        if isinstance(lhs, Sum):
+            if set(lhs.variables).intersection(set(rhs.variables)):
+                raise ValueError('Duplicated dummy indices in separate sums in qapply.')
+            limits = lhs.limits + rhs.limits
+            result = Sum(qapply(lhs.function*rhs.function, **options), *limits)
+            return qapply_Mul(e.func(*args)*result, **options)
+        else:
+            result = Sum(qapply(lhs*rhs.function, **options), *rhs.limits)
+            return qapply_Mul(e.func(*args)*result, **options)
+
+    if isinstance(lhs, Sum):
+        result = Sum(qapply(lhs.function*rhs, **options), *lhs.limits)
+        return qapply_Mul(e.func(*args)*result, **options)
+
+    # Now try to actually apply the operator and build an inner product.
+    _apply = getattr(lhs, '_apply_operator', None)
+    if _apply is not None:
+        try:
+            result = _apply(rhs, **options)
+        except NotImplementedError:
+            result = None
+    else:
+        result = None
+
+    if result is None:
+        _apply_right = getattr(rhs, '_apply_from_right_to', None)
+        if _apply_right is not None:
+            try:
+                result = _apply_right(lhs, **options)
+            except NotImplementedError:
+                result = None
+
+    if result is None:
+        if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
+            result = InnerProduct(lhs, rhs)
+
+    # TODO: I may need to expand before returning the final result.
+    if isinstance(result, (int, complex, float)):
+        return _sympify(result)
+    elif result is None:
+        if len(args) == 0:
+            # We had two args to begin with so args=[].
+            return e
+        else:
+            return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs*extra
+    elif isinstance(result, InnerProduct):
+        return result*qapply_Mul(e.func(*args), **options)*extra
+    else:  # result is a scalar times a Mul, Add or TensorProduct
+        return qapply(e.func(*args)*result, **options)*extra
diff --git a/shared/package-files/e6/e6faef86aa5d746da120b69ea943c8ee137c98ed52e5bf20b88807a8dfc64ecb/_wrapped_linear_prepack_compositeimplicitautograd_dispatch.h b/shared/package-files/e6/e6faef86aa5d746da120b69ea943c8ee137c98ed52e5bf20b88807a8dfc64ecb/_wrapped_linear_prepack_compositeimplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..1c09e5e8cdf1fecf85cd43a2132dfd3335941183
--- /dev/null
+++ b/shared/package-files/e6/e6faef86aa5d746da120b69ea943c8ee137c98ed52e5bf20b88807a8dfc64ecb/_wrapped_linear_prepack_compositeimplicitautograd_dispatch.h
@@ -0,0 +1,23 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeimplicitautograd {
+
+TORCH_API at::Tensor _wrapped_linear_prepack(const at::Tensor & weight, const at::Tensor & weight_scale, const at::Tensor & weight_zero_point, const at::Tensor & bias);
+
+} // namespace compositeimplicitautograd
+} // namespace at
diff --git a/shared/package-files/e6/e6fc6dc49ced415d6ec285aaf1076148b8c4cb253d3a4d2384a7bab994d394bf/opcode.py b/shared/package-files/e6/e6fc6dc49ced415d6ec285aaf1076148b8c4cb253d3a4d2384a7bab994d394bf/opcode.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc3c02af2bccb3d3e7894e48957997312cdbdcb9
--- /dev/null
+++ b/shared/package-files/e6/e6fc6dc49ced415d6ec285aaf1076148b8c4cb253d3a4d2384a7bab994d394bf/opcode.py
@@ -0,0 +1,407 @@
+
+"""
+opcode module - potentially shared between dis and other modules which
+operate on bytecodes (e.g. peephole optimizers).
+"""
+
+__all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs",
+           "haslocal", "hascompare", "hasfree", "opname", "opmap",
+           "HAVE_ARGUMENT", "EXTENDED_ARG", "hasnargs"]
+
+# It's a chicken-and-egg I'm afraid:
+# We're imported before _opcode's made.
+# With exception unheeded
+# (stack_effect is not needed)
+# Both our chickens and eggs are allayed.
+#     --Larry Hastings, 2013/11/23
+
+try:
+    from _opcode import stack_effect
+    __all__.append('stack_effect')
+except ImportError:
+    pass
+
+cmp_op = ('<', '<=', '==', '!=', '>', '>=')
+
+hasconst = []
+hasname = []
+hasjrel = []
+hasjabs = []
+haslocal = []
+hascompare = []
+hasfree = []
+hasnargs = [] # unused
+
+opmap = {}
+opname = ['<%r>' % (op,) for op in range(256)]
+
+def def_op(name, op):
+    opname[op] = name
+    opmap[name] = op
+
+def name_op(name, op):
+    def_op(name, op)
+    hasname.append(op)
+
+def jrel_op(name, op):
+    def_op(name, op)
+    hasjrel.append(op)
+
+def jabs_op(name, op):
+    def_op(name, op)
+    hasjabs.append(op)
+
+# Instruction opcodes for compiled code
+# Blank lines correspond to available opcodes
+
+def_op('CACHE', 0)
+def_op('POP_TOP', 1)
+def_op('PUSH_NULL', 2)
+
+def_op('NOP', 9)
+def_op('UNARY_POSITIVE', 10)
+def_op('UNARY_NEGATIVE', 11)
+def_op('UNARY_NOT', 12)
+
+def_op('UNARY_INVERT', 15)
+
+def_op('BINARY_SUBSCR', 25)
+
+def_op('GET_LEN', 30)
+def_op('MATCH_MAPPING', 31)
+def_op('MATCH_SEQUENCE', 32)
+def_op('MATCH_KEYS', 33)
+
+def_op('PUSH_EXC_INFO', 35)
+def_op('CHECK_EXC_MATCH', 36)
+def_op('CHECK_EG_MATCH', 37)
+
+def_op('WITH_EXCEPT_START', 49)
+def_op('GET_AITER', 50)
+def_op('GET_ANEXT', 51)
+def_op('BEFORE_ASYNC_WITH', 52)
+def_op('BEFORE_WITH', 53)
+def_op('END_ASYNC_FOR', 54)
+
+def_op('STORE_SUBSCR', 60)
+def_op('DELETE_SUBSCR', 61)
+
+def_op('GET_ITER', 68)
+def_op('GET_YIELD_FROM_ITER', 69)
+def_op('PRINT_EXPR', 70)
+def_op('LOAD_BUILD_CLASS', 71)
+
+def_op('LOAD_ASSERTION_ERROR', 74)
+def_op('RETURN_GENERATOR', 75)
+
+def_op('LIST_TO_TUPLE', 82)
+def_op('RETURN_VALUE', 83)
+def_op('IMPORT_STAR', 84)
+def_op('SETUP_ANNOTATIONS', 85)
+def_op('YIELD_VALUE', 86)
+def_op('ASYNC_GEN_WRAP', 87)
+def_op('PREP_RERAISE_STAR', 88)
+def_op('POP_EXCEPT', 89)
+
+HAVE_ARGUMENT = 90              # Opcodes from here have an argument:
+
+name_op('STORE_NAME', 90)       # Index in name list
+name_op('DELETE_NAME', 91)      # ""
+def_op('UNPACK_SEQUENCE', 92)   # Number of tuple items
+jrel_op('FOR_ITER', 93)
+def_op('UNPACK_EX', 94)
+name_op('STORE_ATTR', 95)       # Index in name list
+name_op('DELETE_ATTR', 96)      # ""
+name_op('STORE_GLOBAL', 97)     # ""
+name_op('DELETE_GLOBAL', 98)    # ""
+def_op('SWAP', 99)
+def_op('LOAD_CONST', 100)       # Index in const list
+hasconst.append(100)
+name_op('LOAD_NAME', 101)       # Index in name list
+def_op('BUILD_TUPLE', 102)      # Number of tuple items
+def_op('BUILD_LIST', 103)       # Number of list items
+def_op('BUILD_SET', 104)        # Number of set items
+def_op('BUILD_MAP', 105)        # Number of dict entries
+name_op('LOAD_ATTR', 106)       # Index in name list
+def_op('COMPARE_OP', 107)       # Comparison operator
+hascompare.append(107)
+name_op('IMPORT_NAME', 108)     # Index in name list
+name_op('IMPORT_FROM', 109)     # Index in name list
+jrel_op('JUMP_FORWARD', 110)    # Number of words to skip
+jrel_op('JUMP_IF_FALSE_OR_POP', 111) # Number of words to skip
+jrel_op('JUMP_IF_TRUE_OR_POP', 112)  # ""
+jrel_op('POP_JUMP_FORWARD_IF_FALSE', 114)
+jrel_op('POP_JUMP_FORWARD_IF_TRUE', 115)
+name_op('LOAD_GLOBAL', 116)     # Index in name list
+def_op('IS_OP', 117)
+def_op('CONTAINS_OP', 118)
+def_op('RERAISE', 119)
+def_op('COPY', 120)
+def_op('BINARY_OP', 122)
+jrel_op('SEND', 123) # Number of bytes to skip
+def_op('LOAD_FAST', 124)        # Local variable number
+haslocal.append(124)
+def_op('STORE_FAST', 125)       # Local variable number
+haslocal.append(125)
+def_op('DELETE_FAST', 126)      # Local variable number
+haslocal.append(126)
+jrel_op('POP_JUMP_FORWARD_IF_NOT_NONE', 128)
+jrel_op('POP_JUMP_FORWARD_IF_NONE', 129)
+def_op('RAISE_VARARGS', 130)    # Number of raise arguments (1, 2, or 3)
+def_op('GET_AWAITABLE', 131)
+def_op('MAKE_FUNCTION', 132)    # Flags
+def_op('BUILD_SLICE', 133)      # Number of items
+jrel_op('JUMP_BACKWARD_NO_INTERRUPT', 134) # Number of words to skip (backwards)
+def_op('MAKE_CELL', 135)
+hasfree.append(135)
+def_op('LOAD_CLOSURE', 136)
+hasfree.append(136)
+def_op('LOAD_DEREF', 137)
+hasfree.append(137)
+def_op('STORE_DEREF', 138)
+hasfree.append(138)
+def_op('DELETE_DEREF', 139)
+hasfree.append(139)
+jrel_op('JUMP_BACKWARD', 140)    # Number of words to skip (backwards)
+
+def_op('CALL_FUNCTION_EX', 142)  # Flags
+
+def_op('EXTENDED_ARG', 144)
+EXTENDED_ARG = 144
+def_op('LIST_APPEND', 145)
+def_op('SET_ADD', 146)
+def_op('MAP_ADD', 147)
+def_op('LOAD_CLASSDEREF', 148)
+hasfree.append(148)
+def_op('COPY_FREE_VARS', 149)
+
+def_op('RESUME', 151)   # This must be kept in sync with deepfreeze.py
+def_op('MATCH_CLASS', 152)
+
+def_op('FORMAT_VALUE', 155)
+def_op('BUILD_CONST_KEY_MAP', 156)
+def_op('BUILD_STRING', 157)
+
+name_op('LOAD_METHOD', 160)
+
+def_op('LIST_EXTEND', 162)
+def_op('SET_UPDATE', 163)
+def_op('DICT_MERGE', 164)
+def_op('DICT_UPDATE', 165)
+def_op('PRECALL', 166)
+
+def_op('CALL', 171)
+def_op('KW_NAMES', 172)
+hasconst.append(172)
+
+jrel_op('POP_JUMP_BACKWARD_IF_NOT_NONE', 173)
+jrel_op('POP_JUMP_BACKWARD_IF_NONE', 174)
+jrel_op('POP_JUMP_BACKWARD_IF_FALSE', 175)
+jrel_op('POP_JUMP_BACKWARD_IF_TRUE', 176)
+
+
+del def_op, name_op, jrel_op, jabs_op
+
+_nb_ops = [
+    ("NB_ADD", "+"),
+    ("NB_AND", "&"),
+    ("NB_FLOOR_DIVIDE", "//"),
+    ("NB_LSHIFT", "<<"),
+    ("NB_MATRIX_MULTIPLY", "@"),
+    ("NB_MULTIPLY", "*"),
+    ("NB_REMAINDER", "%"),
+    ("NB_OR", "|"),
+    ("NB_POWER", "**"),
+    ("NB_RSHIFT", ">>"),
+    ("NB_SUBTRACT", "-"),
+    ("NB_TRUE_DIVIDE", "/"),
+    ("NB_XOR", "^"),
+    ("NB_INPLACE_ADD", "+="),
+    ("NB_INPLACE_AND", "&="),
+    ("NB_INPLACE_FLOOR_DIVIDE", "//="),
+    ("NB_INPLACE_LSHIFT", "<<="),
+    ("NB_INPLACE_MATRIX_MULTIPLY", "@="),
+    ("NB_INPLACE_MULTIPLY", "*="),
+    ("NB_INPLACE_REMAINDER", "%="),
+    ("NB_INPLACE_OR", "|="),
+    ("NB_INPLACE_POWER", "**="),
+    ("NB_INPLACE_RSHIFT", ">>="),
+    ("NB_INPLACE_SUBTRACT", "-="),
+    ("NB_INPLACE_TRUE_DIVIDE", "/="),
+    ("NB_INPLACE_XOR", "^="),
+]
+
+_specializations = {
+    "BINARY_OP": [
+        "BINARY_OP_ADAPTIVE",
+        "BINARY_OP_ADD_FLOAT",
+        "BINARY_OP_ADD_INT",
+        "BINARY_OP_ADD_UNICODE",
+        "BINARY_OP_INPLACE_ADD_UNICODE",
+        "BINARY_OP_MULTIPLY_FLOAT",
+        "BINARY_OP_MULTIPLY_INT",
+        "BINARY_OP_SUBTRACT_FLOAT",
+        "BINARY_OP_SUBTRACT_INT",
+    ],
+    "BINARY_SUBSCR": [
+        "BINARY_SUBSCR_ADAPTIVE",
+        "BINARY_SUBSCR_DICT",
+        "BINARY_SUBSCR_GETITEM",
+        "BINARY_SUBSCR_LIST_INT",
+        "BINARY_SUBSCR_TUPLE_INT",
+    ],
+    "CALL": [
+        "CALL_ADAPTIVE",
+        "CALL_PY_EXACT_ARGS",
+        "CALL_PY_WITH_DEFAULTS",
+    ],
+    "COMPARE_OP": [
+        "COMPARE_OP_ADAPTIVE",
+        "COMPARE_OP_FLOAT_JUMP",
+        "COMPARE_OP_INT_JUMP",
+        "COMPARE_OP_STR_JUMP",
+    ],
+    "EXTENDED_ARG": [
+        "EXTENDED_ARG_QUICK",
+    ],
+    "JUMP_BACKWARD": [
+        "JUMP_BACKWARD_QUICK",
+    ],
+    "LOAD_ATTR": [
+        "LOAD_ATTR_ADAPTIVE",
+        "LOAD_ATTR_INSTANCE_VALUE",
+        "LOAD_ATTR_MODULE",
+        "LOAD_ATTR_SLOT",
+        "LOAD_ATTR_WITH_HINT",
+    ],
+    "LOAD_CONST": [
+        "LOAD_CONST__LOAD_FAST",
+    ],
+    "LOAD_FAST": [
+        "LOAD_FAST__LOAD_CONST",
+        "LOAD_FAST__LOAD_FAST",
+    ],
+    "LOAD_GLOBAL": [
+        "LOAD_GLOBAL_ADAPTIVE",
+        "LOAD_GLOBAL_BUILTIN",
+        "LOAD_GLOBAL_MODULE",
+    ],
+    "LOAD_METHOD": [
+        "LOAD_METHOD_ADAPTIVE",
+        "LOAD_METHOD_CLASS",
+        "LOAD_METHOD_MODULE",
+        "LOAD_METHOD_NO_DICT",
+        "LOAD_METHOD_WITH_DICT",
+        "LOAD_METHOD_WITH_VALUES",
+    ],
+    "PRECALL": [
+        "PRECALL_ADAPTIVE",
+        "PRECALL_BOUND_METHOD",
+        "PRECALL_BUILTIN_CLASS",
+        "PRECALL_BUILTIN_FAST_WITH_KEYWORDS",
+        "PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS",
+        "PRECALL_NO_KW_BUILTIN_FAST",
+        "PRECALL_NO_KW_BUILTIN_O",
+        "PRECALL_NO_KW_ISINSTANCE",
+        "PRECALL_NO_KW_LEN",
+        "PRECALL_NO_KW_LIST_APPEND",
+        "PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST",
+        "PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS",
+        "PRECALL_NO_KW_METHOD_DESCRIPTOR_O",
+        "PRECALL_NO_KW_STR_1",
+        "PRECALL_NO_KW_TUPLE_1",
+        "PRECALL_NO_KW_TYPE_1",
+        "PRECALL_PYFUNC",
+    ],
+    "RESUME": [
+        "RESUME_QUICK",
+    ],
+    "STORE_ATTR": [
+        "STORE_ATTR_ADAPTIVE",
+        "STORE_ATTR_INSTANCE_VALUE",
+        "STORE_ATTR_SLOT",
+        "STORE_ATTR_WITH_HINT",
+    ],
+    "STORE_FAST": [
+        "STORE_FAST__LOAD_FAST",
+        "STORE_FAST__STORE_FAST",
+    ],
+    "STORE_SUBSCR": [
+        "STORE_SUBSCR_ADAPTIVE",
+        "STORE_SUBSCR_DICT",
+        "STORE_SUBSCR_LIST_INT",
+    ],
+    "UNPACK_SEQUENCE": [
+        "UNPACK_SEQUENCE_ADAPTIVE",
+        "UNPACK_SEQUENCE_LIST",
+        "UNPACK_SEQUENCE_TUPLE",
+        "UNPACK_SEQUENCE_TWO_TUPLE",
+    ],
+}
+_specialized_instructions = [
+    opcode for family in _specializations.values() for opcode in family
+]
+_specialization_stats = [
+    "success",
+    "failure",
+    "hit",
+    "deferred",
+    "miss",
+    "deopt",
+]
+
+_cache_format = {
+    "LOAD_GLOBAL": {
+        "counter": 1,
+        "index": 1,
+        "module_keys_version": 2,
+        "builtin_keys_version": 1,
+    },
+    "BINARY_OP": {
+        "counter": 1,
+    },
+    "UNPACK_SEQUENCE": {
+        "counter": 1,
+    },
+    "COMPARE_OP": {
+        "counter": 1,
+        "mask": 1,
+    },
+    "BINARY_SUBSCR": {
+        "counter": 1,
+        "type_version": 2,
+        "func_version": 1,
+    },
+    "LOAD_ATTR": {
+        "counter": 1,
+        "version": 2,
+        "index": 1,
+    },
+    "STORE_ATTR": {
+        "counter": 1,
+        "version": 2,
+        "index": 1,
+    },
+    "LOAD_METHOD": {
+        "counter": 1,
+        "type_version": 2,
+        "dict_offset": 1,
+        "keys_version": 2,
+        "descr": 4,
+    },
+    "CALL": {
+        "counter": 1,
+        "func_version": 2,
+        "min_args": 1,
+    },
+    "PRECALL": {
+        "counter": 1,
+    },
+    "STORE_SUBSCR": {
+        "counter": 1,
+    },
+}
+
+_inline_cache_entries = [
+    sum(_cache_format.get(opname[opcode], {}).values()) for opcode in range(256)
+]
diff --git a/shared/package-files/ef/ef02eba74c0e509b8f9b007dffd04b58e9b80406224076a14b2d2e9ad83b6086/string_arrow.py b/shared/package-files/ef/ef02eba74c0e509b8f9b007dffd04b58e9b80406224076a14b2d2e9ad83b6086/string_arrow.py
new file mode 100644
index 0000000000000000000000000000000000000000..50527dace0b82113d282a332b29a007f41345a2d
--- /dev/null
+++ b/shared/package-files/ef/ef02eba74c0e509b8f9b007dffd04b58e9b80406224076a14b2d2e9ad83b6086/string_arrow.py
@@ -0,0 +1,719 @@
+from __future__ import annotations
+
+from functools import partial
+import operator
+import re
+from typing import (
+    TYPE_CHECKING,
+    Callable,
+    Union,
+)
+import warnings
+
+import numpy as np
+
+from pandas._libs import (
+    lib,
+    missing as libmissing,
+)
+from pandas.compat import (
+    pa_version_under10p1,
+    pa_version_under13p0,
+)
+from pandas.util._exceptions import find_stack_level
+
+from pandas.core.dtypes.common import (
+    is_bool_dtype,
+    is_integer_dtype,
+    is_object_dtype,
+    is_scalar,
+    is_string_dtype,
+    pandas_dtype,
+)
+from pandas.core.dtypes.missing import isna
+
+from pandas.core.arrays._arrow_string_mixins import ArrowStringArrayMixin
+from pandas.core.arrays.arrow import ArrowExtensionArray
+from pandas.core.arrays.boolean import BooleanDtype
+from pandas.core.arrays.integer import Int64Dtype
+from pandas.core.arrays.numeric import NumericDtype
+from pandas.core.arrays.string_ import (
+    BaseStringArray,
+    StringDtype,
+)
+from pandas.core.ops import invalid_comparison
+from pandas.core.strings.object_array import ObjectStringArrayMixin
+
+if not pa_version_under10p1:
+    import pyarrow as pa
+    import pyarrow.compute as pc
+
+    from pandas.core.arrays.arrow._arrow_utils import fallback_performancewarning
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+    from pandas._typing import (
+        ArrayLike,
+        AxisInt,
+        Dtype,
+        Scalar,
+        npt,
+    )
+
+    from pandas import Series
+
+
+ArrowStringScalarOrNAT = Union[str, libmissing.NAType]
+
+
+def _chk_pyarrow_available() -> None:
+    if pa_version_under10p1:
+        msg = "pyarrow>=10.0.1 is required for PyArrow backed ArrowExtensionArray."
+        raise ImportError(msg)
+
+
+# TODO: Inherit directly from BaseStringArrayMethods. Currently we inherit from
+# ObjectStringArrayMixin because we want to have the object-dtype based methods as
+# fallback for the ones that pyarrow doesn't yet support
+
+
+class ArrowStringArray(ObjectStringArrayMixin, ArrowExtensionArray, BaseStringArray):
+    """
+    Extension array for string data in a ``pyarrow.ChunkedArray``.
+
+    .. warning::
+
+       ArrowStringArray is considered experimental. The implementation and
+       parts of the API may change without warning.
+
+    Parameters
+    ----------
+    values : pyarrow.Array or pyarrow.ChunkedArray
+        The array of data.
+
+    Attributes
+    ----------
+    None
+
+    Methods
+    -------
+    None
+
+    See Also
+    --------
+    :func:`pandas.array`
+        The recommended function for creating a ArrowStringArray.
+    Series.str
+        The string methods are available on Series backed by
+        a ArrowStringArray.
+
+    Notes
+    -----
+    ArrowStringArray returns a BooleanArray for comparison methods.
+
+    Examples
+    --------
+    >>> pd.array(['This is', 'some text', None, 'data.'], dtype="string[pyarrow]")
+    
+    ['This is', 'some text', , 'data.']
+    Length: 4, dtype: string
+    """
+
+    # error: Incompatible types in assignment (expression has type "StringDtype",
+    # base class "ArrowExtensionArray" defined the type as "ArrowDtype")
+    _dtype: StringDtype  # type: ignore[assignment]
+    _storage = "pyarrow"
+
+    def __init__(self, values) -> None:
+        _chk_pyarrow_available()
+        if isinstance(values, (pa.Array, pa.ChunkedArray)) and pa.types.is_string(
+            values.type
+        ):
+            values = pc.cast(values, pa.large_string())
+
+        super().__init__(values)
+        self._dtype = StringDtype(storage=self._storage)
+
+        if not pa.types.is_large_string(self._pa_array.type) and not (
+            pa.types.is_dictionary(self._pa_array.type)
+            and pa.types.is_large_string(self._pa_array.type.value_type)
+        ):
+            raise ValueError(
+                "ArrowStringArray requires a PyArrow (chunked) array of "
+                "large_string type"
+            )
+
+    @classmethod
+    def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar:
+        pa_scalar = super()._box_pa_scalar(value, pa_type)
+        if pa.types.is_string(pa_scalar.type) and pa_type is None:
+            pa_scalar = pc.cast(pa_scalar, pa.large_string())
+        return pa_scalar
+
+    @classmethod
+    def _box_pa_array(
+        cls, value, pa_type: pa.DataType | None = None, copy: bool = False
+    ) -> pa.Array | pa.ChunkedArray:
+        pa_array = super()._box_pa_array(value, pa_type)
+        if pa.types.is_string(pa_array.type) and pa_type is None:
+            pa_array = pc.cast(pa_array, pa.large_string())
+        return pa_array
+
+    def __len__(self) -> int:
+        """
+        Length of this array.
+
+        Returns
+        -------
+        length : int
+        """
+        return len(self._pa_array)
+
+    @classmethod
+    def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False):
+        from pandas.core.arrays.masked import BaseMaskedArray
+
+        _chk_pyarrow_available()
+
+        if dtype and not (isinstance(dtype, str) and dtype == "string"):
+            dtype = pandas_dtype(dtype)
+            assert isinstance(dtype, StringDtype) and dtype.storage in (
+                "pyarrow",
+                "pyarrow_numpy",
+            )
+
+        if isinstance(scalars, BaseMaskedArray):
+            # avoid costly conversion to object dtype in ensure_string_array and
+            # numerical issues with Float32Dtype
+            na_values = scalars._mask
+            result = scalars._data
+            result = lib.ensure_string_array(result, copy=copy, convert_na_value=False)
+            return cls(pa.array(result, mask=na_values, type=pa.large_string()))
+        elif isinstance(scalars, (pa.Array, pa.ChunkedArray)):
+            return cls(pc.cast(scalars, pa.large_string()))
+
+        # convert non-na-likes to str
+        result = lib.ensure_string_array(scalars, copy=copy)
+        return cls(pa.array(result, type=pa.large_string(), from_pandas=True))
+
+    @classmethod
+    def _from_sequence_of_strings(
+        cls, strings, dtype: Dtype | None = None, copy: bool = False
+    ):
+        return cls._from_sequence(strings, dtype=dtype, copy=copy)
+
+    @property
+    def dtype(self) -> StringDtype:  # type: ignore[override]
+        """
+        An instance of 'string[pyarrow]'.
+        """
+        return self._dtype
+
+    def insert(self, loc: int, item) -> ArrowStringArray:
+        if not isinstance(item, str) and item is not libmissing.NA:
+            raise TypeError("Scalar must be NA or str")
+        return super().insert(loc, item)
+
+    @classmethod
+    def _result_converter(cls, values, na=None):
+        return BooleanDtype().__from_arrow__(values)
+
+    def _maybe_convert_setitem_value(self, value):
+        """Maybe convert value to be pyarrow compatible."""
+        if is_scalar(value):
+            if isna(value):
+                value = None
+            elif not isinstance(value, str):
+                raise TypeError("Scalar must be NA or str")
+        else:
+            value = np.array(value, dtype=object, copy=True)
+            value[isna(value)] = None
+            for v in value:
+                if not (v is None or isinstance(v, str)):
+                    raise TypeError("Scalar must be NA or str")
+        return super()._maybe_convert_setitem_value(value)
+
+    def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]:
+        value_set = [
+            pa_scalar.as_py()
+            for pa_scalar in [pa.scalar(value, from_pandas=True) for value in values]
+            if pa_scalar.type in (pa.string(), pa.null(), pa.large_string())
+        ]
+
+        # short-circuit to return all False array.
+        if not len(value_set):
+            return np.zeros(len(self), dtype=bool)
+
+        result = pc.is_in(
+            self._pa_array, value_set=pa.array(value_set, type=self._pa_array.type)
+        )
+        # pyarrow 2.0.0 returned nulls, so we explicily specify dtype to convert nulls
+        # to False
+        return np.array(result, dtype=np.bool_)
+
+    def astype(self, dtype, copy: bool = True):
+        dtype = pandas_dtype(dtype)
+
+        if dtype == self.dtype:
+            if copy:
+                return self.copy()
+            return self
+        elif isinstance(dtype, NumericDtype):
+            data = self._pa_array.cast(pa.from_numpy_dtype(dtype.numpy_dtype))
+            return dtype.__from_arrow__(data)
+        elif isinstance(dtype, np.dtype) and np.issubdtype(dtype, np.floating):
+            return self.to_numpy(dtype=dtype, na_value=np.nan)
+
+        return super().astype(dtype, copy=copy)
+
+    @property
+    def _data(self):
+        # dask accesses ._data directlys
+        warnings.warn(
+            f"{type(self).__name__}._data is a deprecated and will be removed "
+            "in a future version, use ._pa_array instead",
+            FutureWarning,
+            stacklevel=find_stack_level(),
+        )
+        return self._pa_array
+
+    # ------------------------------------------------------------------------
+    # String methods interface
+
+    # error: Incompatible types in assignment (expression has type "NAType",
+    # base class "ObjectStringArrayMixin" defined the type as "float")
+    _str_na_value = libmissing.NA  # type: ignore[assignment]
+
+    def _str_map(
+        self, f, na_value=None, dtype: Dtype | None = None, convert: bool = True
+    ):
+        # TODO: de-duplicate with StringArray method. This method is moreless copy and
+        # paste.
+
+        from pandas.arrays import (
+            BooleanArray,
+            IntegerArray,
+        )
+
+        if dtype is None:
+            dtype = self.dtype
+        if na_value is None:
+            na_value = self.dtype.na_value
+
+        mask = isna(self)
+        arr = np.asarray(self)
+
+        if is_integer_dtype(dtype) or is_bool_dtype(dtype):
+            constructor: type[IntegerArray | BooleanArray]
+            if is_integer_dtype(dtype):
+                constructor = IntegerArray
+            else:
+                constructor = BooleanArray
+
+            na_value_is_na = isna(na_value)
+            if na_value_is_na:
+                na_value = 1
+            result = lib.map_infer_mask(
+                arr,
+                f,
+                mask.view("uint8"),
+                convert=False,
+                na_value=na_value,
+                # error: Argument 1 to "dtype" has incompatible type
+                # "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected
+                # "Type[object]"
+                dtype=np.dtype(dtype),  # type: ignore[arg-type]
+            )
+
+            if not na_value_is_na:
+                mask[:] = False
+
+            return constructor(result, mask)
+
+        elif is_string_dtype(dtype) and not is_object_dtype(dtype):
+            # i.e. StringDtype
+            result = lib.map_infer_mask(
+                arr, f, mask.view("uint8"), convert=False, na_value=na_value
+            )
+            result = pa.array(
+                result, mask=mask, type=pa.large_string(), from_pandas=True
+            )
+            return type(self)(result)
+        else:
+            # This is when the result type is object. We reach this when
+            # -> We know the result type is truly object (e.g. .encode returns bytes
+            #    or .findall returns a list).
+            # -> We don't know the result type. E.g. `.get` can return anything.
+            return lib.map_infer_mask(arr, f, mask.view("uint8"))
+
+    def _str_contains(
+        self, pat, case: bool = True, flags: int = 0, na=np.nan, regex: bool = True
+    ):
+        if flags:
+            fallback_performancewarning()
+            return super()._str_contains(pat, case, flags, na, regex)
+
+        if regex:
+            result = pc.match_substring_regex(self._pa_array, pat, ignore_case=not case)
+        else:
+            result = pc.match_substring(self._pa_array, pat, ignore_case=not case)
+        result = self._result_converter(result, na=na)
+        if not isna(na):
+            result[isna(result)] = bool(na)
+        return result
+
+    def _str_startswith(self, pat: str | tuple[str, ...], na: Scalar | None = None):
+        if isinstance(pat, str):
+            result = pc.starts_with(self._pa_array, pattern=pat)
+        else:
+            if len(pat) == 0:
+                # mimic existing behaviour of string extension array
+                # and python string method
+                result = pa.array(
+                    np.zeros(len(self._pa_array), dtype=bool), mask=isna(self._pa_array)
+                )
+            else:
+                result = pc.starts_with(self._pa_array, pattern=pat[0])
+
+                for p in pat[1:]:
+                    result = pc.or_(result, pc.starts_with(self._pa_array, pattern=p))
+        if not isna(na):
+            result = result.fill_null(na)
+        return self._result_converter(result)
+
+    def _str_endswith(self, pat: str | tuple[str, ...], na: Scalar | None = None):
+        if isinstance(pat, str):
+            result = pc.ends_with(self._pa_array, pattern=pat)
+        else:
+            if len(pat) == 0:
+                # mimic existing behaviour of string extension array
+                # and python string method
+                result = pa.array(
+                    np.zeros(len(self._pa_array), dtype=bool), mask=isna(self._pa_array)
+                )
+            else:
+                result = pc.ends_with(self._pa_array, pattern=pat[0])
+
+                for p in pat[1:]:
+                    result = pc.or_(result, pc.ends_with(self._pa_array, pattern=p))
+        if not isna(na):
+            result = result.fill_null(na)
+        return self._result_converter(result)
+
+    def _str_replace(
+        self,
+        pat: str | re.Pattern,
+        repl: str | Callable,
+        n: int = -1,
+        case: bool = True,
+        flags: int = 0,
+        regex: bool = True,
+    ):
+        if isinstance(pat, re.Pattern) or callable(repl) or not case or flags:
+            fallback_performancewarning()
+            return super()._str_replace(pat, repl, n, case, flags, regex)
+
+        func = pc.replace_substring_regex if regex else pc.replace_substring
+        result = func(self._pa_array, pattern=pat, replacement=repl, max_replacements=n)
+        return type(self)(result)
+
+    def _str_repeat(self, repeats: int | Sequence[int]):
+        if not isinstance(repeats, int):
+            return super()._str_repeat(repeats)
+        else:
+            return type(self)(pc.binary_repeat(self._pa_array, repeats))
+
+    def _str_match(
+        self, pat: str, case: bool = True, flags: int = 0, na: Scalar | None = None
+    ):
+        if not pat.startswith("^"):
+            pat = f"^{pat}"
+        return self._str_contains(pat, case, flags, na, regex=True)
+
+    def _str_fullmatch(
+        self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
+    ):
+        if not pat.endswith("$") or pat.endswith("\\$"):
+            pat = f"{pat}$"
+        return self._str_match(pat, case, flags, na)
+
+    def _str_slice(
+        self, start: int | None = None, stop: int | None = None, step: int | None = None
+    ):
+        if stop is None:
+            return super()._str_slice(start, stop, step)
+        if start is None:
+            start = 0
+        if step is None:
+            step = 1
+        return type(self)(
+            pc.utf8_slice_codeunits(self._pa_array, start=start, stop=stop, step=step)
+        )
+
+    def _str_isalnum(self):
+        result = pc.utf8_is_alnum(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isalpha(self):
+        result = pc.utf8_is_alpha(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isdecimal(self):
+        result = pc.utf8_is_decimal(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isdigit(self):
+        result = pc.utf8_is_digit(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_islower(self):
+        result = pc.utf8_is_lower(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isnumeric(self):
+        result = pc.utf8_is_numeric(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isspace(self):
+        result = pc.utf8_is_space(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_istitle(self):
+        result = pc.utf8_is_title(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_isupper(self):
+        result = pc.utf8_is_upper(self._pa_array)
+        return self._result_converter(result)
+
+    def _str_len(self):
+        result = pc.utf8_length(self._pa_array)
+        return self._convert_int_dtype(result)
+
+    def _str_lower(self):
+        return type(self)(pc.utf8_lower(self._pa_array))
+
+    def _str_upper(self):
+        return type(self)(pc.utf8_upper(self._pa_array))
+
+    def _str_strip(self, to_strip=None):
+        if to_strip is None:
+            result = pc.utf8_trim_whitespace(self._pa_array)
+        else:
+            result = pc.utf8_trim(self._pa_array, characters=to_strip)
+        return type(self)(result)
+
+    def _str_lstrip(self, to_strip=None):
+        if to_strip is None:
+            result = pc.utf8_ltrim_whitespace(self._pa_array)
+        else:
+            result = pc.utf8_ltrim(self._pa_array, characters=to_strip)
+        return type(self)(result)
+
+    def _str_rstrip(self, to_strip=None):
+        if to_strip is None:
+            result = pc.utf8_rtrim_whitespace(self._pa_array)
+        else:
+            result = pc.utf8_rtrim(self._pa_array, characters=to_strip)
+        return type(self)(result)
+
+    def _str_removeprefix(self, prefix: str):
+        if not pa_version_under13p0:
+            starts_with = pc.starts_with(self._pa_array, pattern=prefix)
+            removed = pc.utf8_slice_codeunits(self._pa_array, len(prefix))
+            result = pc.if_else(starts_with, removed, self._pa_array)
+            return type(self)(result)
+        return super()._str_removeprefix(prefix)
+
+    def _str_removesuffix(self, suffix: str):
+        ends_with = pc.ends_with(self._pa_array, pattern=suffix)
+        removed = pc.utf8_slice_codeunits(self._pa_array, 0, stop=-len(suffix))
+        result = pc.if_else(ends_with, removed, self._pa_array)
+        return type(self)(result)
+
+    def _str_count(self, pat: str, flags: int = 0):
+        if flags:
+            return super()._str_count(pat, flags)
+        result = pc.count_substring_regex(self._pa_array, pat)
+        return self._convert_int_dtype(result)
+
+    def _str_find(self, sub: str, start: int = 0, end: int | None = None):
+        if start != 0 and end is not None:
+            slices = pc.utf8_slice_codeunits(self._pa_array, start, stop=end)
+            result = pc.find_substring(slices, sub)
+            not_found = pc.equal(result, -1)
+            offset_result = pc.add(result, end - start)
+            result = pc.if_else(not_found, result, offset_result)
+        elif start == 0 and end is None:
+            slices = self._pa_array
+            result = pc.find_substring(slices, sub)
+        else:
+            return super()._str_find(sub, start, end)
+        return self._convert_int_dtype(result)
+
+    def _str_get_dummies(self, sep: str = "|"):
+        dummies_pa, labels = ArrowExtensionArray(self._pa_array)._str_get_dummies(sep)
+        if len(labels) == 0:
+            return np.empty(shape=(0, 0), dtype=np.int64), labels
+        dummies = np.vstack(dummies_pa.to_numpy())
+        return dummies.astype(np.int64, copy=False), labels
+
+    def _convert_int_dtype(self, result):
+        return Int64Dtype().__from_arrow__(result)
+
+    def _reduce(
+        self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs
+    ):
+        result = self._reduce_calc(name, skipna=skipna, keepdims=keepdims, **kwargs)
+        if name in ("argmin", "argmax") and isinstance(result, pa.Array):
+            return self._convert_int_dtype(result)
+        elif isinstance(result, pa.Array):
+            return type(self)(result)
+        else:
+            return result
+
+    def _rank(
+        self,
+        *,
+        axis: AxisInt = 0,
+        method: str = "average",
+        na_option: str = "keep",
+        ascending: bool = True,
+        pct: bool = False,
+    ):
+        """
+        See Series.rank.__doc__.
+        """
+        return self._convert_int_dtype(
+            self._rank_calc(
+                axis=axis,
+                method=method,
+                na_option=na_option,
+                ascending=ascending,
+                pct=pct,
+            )
+        )
+
+
+class ArrowStringArrayNumpySemantics(ArrowStringArray):
+    _storage = "pyarrow_numpy"
+
+    @classmethod
+    def _result_converter(cls, values, na=None):
+        if not isna(na):
+            values = values.fill_null(bool(na))
+        return ArrowExtensionArray(values).to_numpy(na_value=np.nan)
+
+    def __getattribute__(self, item):
+        # ArrowStringArray and we both inherit from ArrowExtensionArray, which
+        # creates inheritance problems (Diamond inheritance)
+        if item in ArrowStringArrayMixin.__dict__ and item not in (
+            "_pa_array",
+            "__dict__",
+        ):
+            return partial(getattr(ArrowStringArrayMixin, item), self)
+        return super().__getattribute__(item)
+
+    def _str_map(
+        self, f, na_value=None, dtype: Dtype | None = None, convert: bool = True
+    ):
+        if dtype is None:
+            dtype = self.dtype
+        if na_value is None:
+            na_value = self.dtype.na_value
+
+        mask = isna(self)
+        arr = np.asarray(self)
+
+        if is_integer_dtype(dtype) or is_bool_dtype(dtype):
+            if is_integer_dtype(dtype):
+                na_value = np.nan
+            else:
+                na_value = False
+            try:
+                result = lib.map_infer_mask(
+                    arr,
+                    f,
+                    mask.view("uint8"),
+                    convert=False,
+                    na_value=na_value,
+                    dtype=np.dtype(dtype),  # type: ignore[arg-type]
+                )
+                return result
+
+            except ValueError:
+                result = lib.map_infer_mask(
+                    arr,
+                    f,
+                    mask.view("uint8"),
+                    convert=False,
+                    na_value=na_value,
+                )
+                if convert and result.dtype == object:
+                    result = lib.maybe_convert_objects(result)
+                return result
+
+        elif is_string_dtype(dtype) and not is_object_dtype(dtype):
+            # i.e. StringDtype
+            result = lib.map_infer_mask(
+                arr, f, mask.view("uint8"), convert=False, na_value=na_value
+            )
+            result = pa.array(
+                result, mask=mask, type=pa.large_string(), from_pandas=True
+            )
+            return type(self)(result)
+        else:
+            # This is when the result type is object. We reach this when
+            # -> We know the result type is truly object (e.g. .encode returns bytes
+            #    or .findall returns a list).
+            # -> We don't know the result type. E.g. `.get` can return anything.
+            return lib.map_infer_mask(arr, f, mask.view("uint8"))
+
+    def _convert_int_dtype(self, result):
+        if isinstance(result, pa.Array):
+            result = result.to_numpy(zero_copy_only=False)
+        else:
+            result = result.to_numpy()
+        if result.dtype == np.int32:
+            result = result.astype(np.int64)
+        return result
+
+    def _cmp_method(self, other, op):
+        try:
+            result = super()._cmp_method(other, op)
+        except pa.ArrowNotImplementedError:
+            return invalid_comparison(self, other, op)
+        if op == operator.ne:
+            return result.to_numpy(np.bool_, na_value=True)
+        else:
+            return result.to_numpy(np.bool_, na_value=False)
+
+    def value_counts(self, dropna: bool = True) -> Series:
+        from pandas import Series
+
+        result = super().value_counts(dropna)
+        return Series(
+            result._values.to_numpy(), index=result.index, name=result.name, copy=False
+        )
+
+    def _reduce(
+        self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs
+    ):
+        if name in ["any", "all"]:
+            if not skipna and name == "all":
+                nas = pc.invert(pc.is_null(self._pa_array))
+                arr = pc.and_kleene(nas, pc.not_equal(self._pa_array, ""))
+            else:
+                arr = pc.not_equal(self._pa_array, "")
+            return ArrowExtensionArray(arr)._reduce(
+                name, skipna=skipna, keepdims=keepdims, **kwargs
+            )
+        else:
+            return super()._reduce(name, skipna=skipna, keepdims=keepdims, **kwargs)
+
+    def insert(self, loc: int, item) -> ArrowStringArrayNumpySemantics:
+        if item is np.nan:
+            item = libmissing.NA
+        return super().insert(loc, item)  # type: ignore[return-value]
diff --git a/shared/package-files/ef/ef036a259c874a18ffea1d09ba1e87b7571e14c6241281c36d024d8d5ebb2436/framework.cpython-311.pyc b/shared/package-files/ef/ef036a259c874a18ffea1d09ba1e87b7571e14c6241281c36d024d8d5ebb2436/framework.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..085ef7c5478b20cb1e5022c6d2abcd19961287be
Binary files /dev/null and b/shared/package-files/ef/ef036a259c874a18ffea1d09ba1e87b7571e14c6241281c36d024d8d5ebb2436/framework.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef0ca373836cfbfa5e39eb32c27838b680bec75e807d472619cf35ef5a26aec1/cpp_intrinsics.h b/shared/package-files/ef/ef0ca373836cfbfa5e39eb32c27838b680bec75e807d472619cf35ef5a26aec1/cpp_intrinsics.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e4bb6a615254b043825cd316cc4b85e09f5fb58
--- /dev/null
+++ b/shared/package-files/ef/ef0ca373836cfbfa5e39eb32c27838b680bec75e807d472619cf35ef5a26aec1/cpp_intrinsics.h
@@ -0,0 +1,32 @@
+#pragma once
+
+namespace torch::jit::tensorexpr {
+
+constexpr auto cpp_intrinsics_definition = R"(
+namespace std {
+
+template , int> = 0>
+T rsqrt(T v) {
+  return 1.0f / std::sqrt(v);
+}
+
+template , int> = 0>
+T frac(T v) {
+  T intpart;
+  return std::modf(v, &intpart);
+}
+
+template 
+To bitcast(const From& v) {
+  assert(sizeof(To) == sizeof(From));
+  To res;
+  std::memcpy(&res, &v, sizeof(From));
+  return res;
+}
+
+} // namespace std
+)";
+
+} // namespace torch::jit::tensorexpr
diff --git a/shared/package-files/ef/ef10b25da0467b1abfc3c8f405e8bb269fd530a2cae6679497db9d3d0f53fae4/graph_settings.cpython-311.pyc b/shared/package-files/ef/ef10b25da0467b1abfc3c8f405e8bb269fd530a2cae6679497db9d3d0f53fae4/graph_settings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f3777c2dfbbade32b7cd53b167171882e2a7608
Binary files /dev/null and b/shared/package-files/ef/ef10b25da0467b1abfc3c8f405e8bb269fd530a2cae6679497db9d3d0f53fae4/graph_settings.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef1603823d34454f3fc82952d845e0f67298baf81a0dc298abcec91e1c7e831f/__init__.cpython-311.pyc b/shared/package-files/ef/ef1603823d34454f3fc82952d845e0f67298baf81a0dc298abcec91e1c7e831f/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..007931c1ad3c21912b60ef25a2ceca078580e027
Binary files /dev/null and b/shared/package-files/ef/ef1603823d34454f3fc82952d845e0f67298baf81a0dc298abcec91e1c7e831f/__init__.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef1a184386ba165c14afcb1ea8d7e494f6ac3bd3d89c314d0b1b81b25eb1b315/dyld.cpython-311.pyc b/shared/package-files/ef/ef1a184386ba165c14afcb1ea8d7e494f6ac3bd3d89c314d0b1b81b25eb1b315/dyld.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b49f5ca540e6d7bba8b7792e0aeab22e124900e
Binary files /dev/null and b/shared/package-files/ef/ef1a184386ba165c14afcb1ea8d7e494f6ac3bd3d89c314d0b1b81b25eb1b315/dyld.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef1c70a2424e0414319dba31de518b80ca3d464546560b5f3c1b6c29c6866931/_onnx.pyi b/shared/package-files/ef/ef1c70a2424e0414319dba31de518b80ca3d464546560b5f3c1b6c29c6866931/_onnx.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..349e0b9ad12f0dd9306fde89a40718f26b158f0e
--- /dev/null
+++ b/shared/package-files/ef/ef1c70a2424e0414319dba31de518b80ca3d464546560b5f3c1b6c29c6866931/_onnx.pyi
@@ -0,0 +1,39 @@
+# Defined in torch/csrc/onnx/init.cpp
+
+from enum import Enum
+
+PRODUCER_VERSION: str
+
+class TensorProtoDataType(Enum):
+    UNDEFINED = ...
+    FLOAT = ...
+    UINT8 = ...
+    INT8 = ...
+    UINT16 = ...
+    INT16 = ...
+    INT32 = ...
+    INT64 = ...
+    STRING = ...
+    BOOL = ...
+    FLOAT16 = ...
+    DOUBLE = ...
+    UINT32 = ...
+    UINT64 = ...
+    COMPLEX64 = ...
+    COMPLEX128 = ...
+    BFLOAT16 = ...
+    FLOAT8E5M2 = ...
+    FLOAT8E4M3FN = ...
+    FLOAT8E5M2FNUZ = ...
+    FLOAT8E4M3FNUZ = ...
+
+class OperatorExportTypes(Enum):
+    ONNX = ...
+    ONNX_ATEN = ...
+    ONNX_ATEN_FALLBACK = ...
+    ONNX_FALLTHROUGH = ...
+
+class TrainingMode(Enum):
+    EVAL = ...
+    PRESERVE = ...
+    TRAINING = ...
diff --git a/shared/package-files/ef/ef257b54007a392c7554c2a25c74b3ce4f95dca778ca7484473a7685ee430877/test_isomorphvf2.cpython-311.pyc b/shared/package-files/ef/ef257b54007a392c7554c2a25c74b3ce4f95dca778ca7484473a7685ee430877/test_isomorphvf2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30bd6972174c8e7d03848838db12857440191941
Binary files /dev/null and b/shared/package-files/ef/ef257b54007a392c7554c2a25c74b3ce4f95dca778ca7484473a7685ee430877/test_isomorphvf2.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef25bfd769f8fe3eb840436cab3111813bed9830fe3a260183c8de1b179ed075/cp720.cpython-311.pyc b/shared/package-files/ef/ef25bfd769f8fe3eb840436cab3111813bed9830fe3a260183c8de1b179ed075/cp720.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e329f895f882acb2300e89be6f3845fe8efc4fd
Binary files /dev/null and b/shared/package-files/ef/ef25bfd769f8fe3eb840436cab3111813bed9830fe3a260183c8de1b179ed075/cp720.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef262a3032f36dd01c66981d4f1092481e484a4d5d8bcdea715439bb92898e05/_upsample_bilinear2d_aa_cuda_dispatch.h b/shared/package-files/ef/ef262a3032f36dd01c66981d4f1092481e484a4d5d8bcdea715439bb92898e05/_upsample_bilinear2d_aa_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..b0d567e2ab2354fc390afa6a6e9c88c84cb58bee
--- /dev/null
+++ b/shared/package-files/ef/ef262a3032f36dd01c66981d4f1092481e484a4d5d8bcdea715439bb92898e05/_upsample_bilinear2d_aa_cuda_dispatch.h
@@ -0,0 +1,28 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API at::Tensor _upsample_bilinear2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor _upsample_bilinear2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bilinear2d_aa_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bilinear2d_aa_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & out);
+TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt);
+TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & out);
+
+} // namespace cuda
+} // namespace at
diff --git a/shared/package-files/ef/ef2c29000a5730361229e8dcdc56866e6f3c9b95456e93be1cbfeaaa92aaa768/sys.cpython-311.pyc b/shared/package-files/ef/ef2c29000a5730361229e8dcdc56866e6f3c9b95456e93be1cbfeaaa92aaa768/sys.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db73ebf1470890fa2b088d9783acaa476b310ff0
Binary files /dev/null and b/shared/package-files/ef/ef2c29000a5730361229e8dcdc56866e6f3c9b95456e93be1cbfeaaa92aaa768/sys.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef2ed4a105f4020266d118ba68b8692017e2c0825b72288a558efd4d43c64dfb/special_chebyshev_polynomial_t_native.h b/shared/package-files/ef/ef2ed4a105f4020266d118ba68b8692017e2c0825b72288a558efd4d43c64dfb/special_chebyshev_polynomial_t_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..084acb3fb3eb78a007629e10d8c86ca33ad31120
--- /dev/null
+++ b/shared/package-files/ef/ef2ed4a105f4020266d118ba68b8692017e2c0825b72288a558efd4d43c64dfb/special_chebyshev_polynomial_t_native.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+struct TORCH_API structured_special_chebyshev_polynomial_t_out : public at::meta::structured_special_chebyshev_polynomial_t {
+void impl(const at::Tensor & x, const at::Tensor & n, const at::Tensor & out);
+};
+TORCH_API at::Tensor special_chebyshev_polynomial_t(const at::Scalar & x, const at::Tensor & n);
+TORCH_API at::Tensor & special_chebyshev_polynomial_t_out(const at::Scalar & x, const at::Tensor & n, at::Tensor & out);
+TORCH_API at::Tensor special_chebyshev_polynomial_t(const at::Tensor & x, const at::Scalar & n);
+TORCH_API at::Tensor & special_chebyshev_polynomial_t_out(const at::Tensor & x, const at::Scalar & n, at::Tensor & out);
+} // namespace native
+} // namespace at
diff --git a/shared/package-files/ef/ef3224cf53de60e95d6cc66286a868015da456022abbe302d9f7266e23986140/registry.cpython-311.pyc b/shared/package-files/ef/ef3224cf53de60e95d6cc66286a868015da456022abbe302d9f7266e23986140/registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75eb8531b97fc3445aaeafe1505175075b405707
Binary files /dev/null and b/shared/package-files/ef/ef3224cf53de60e95d6cc66286a868015da456022abbe302d9f7266e23986140/registry.cpython-311.pyc differ
diff --git a/shared/package-files/ef/ef32921f5c331cd189c8ee42e1c1bbb0596ab98d20835b11a9427685aab197c1/addmm_ops.h b/shared/package-files/ef/ef32921f5c331cd189c8ee42e1c1bbb0596ab98d20835b11a9427685aab197c1/addmm_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..160d6cdd530158cf83538ad1e2c5972011569e61
--- /dev/null
+++ b/shared/package-files/ef/ef32921f5c331cd189c8ee42e1c1bbb0596ab98d20835b11a9427685aab197c1/addmm_ops.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API addmm_out {
+  using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::addmm";
+  static constexpr const char* overload_name = "out";
+  static constexpr const char* schema_str = "addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)";
+  static at::Tensor & call(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out);
+};
+
+struct TORCH_API addmm {
+  using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::addmm";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor";
+  static at::Tensor call(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha);
+};
+
+struct TORCH_API addmm_ {
+  using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::addmm_";
+  static constexpr const char* overload_name = "";
+  static constexpr const char* schema_str = "addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)";
+  static at::Tensor & call(at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha);
+  static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha);
+};
+
+}} // namespace at::_ops
diff --git a/shared/package-files/ef/ef3420607dc3f2d9d7bf5238d1865942036ebb8e37c7c9a3ad8663043565a1da/smtpd.py b/shared/package-files/ef/ef3420607dc3f2d9d7bf5238d1865942036ebb8e37c7c9a3ad8663043565a1da/smtpd.py
new file mode 100644
index 0000000000000000000000000000000000000000..b23579f120716fe7a356a3510d93bd1cdd892a77
--- /dev/null
+++ b/shared/package-files/ef/ef3420607dc3f2d9d7bf5238d1865942036ebb8e37c7c9a3ad8663043565a1da/smtpd.py
@@ -0,0 +1,885 @@
+#! /usr/bin/env python3
+"""An RFC 5321 smtp proxy with optional RFC 1870 and RFC 6531 extensions.
+
+Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
+
+Options:
+
+    --nosetuid
+    -n
+        This program generally tries to setuid `nobody', unless this flag is
+        set.  The setuid call will fail if this program is not run as root (in
+        which case, use this flag).
+
+    --version
+    -V
+        Print the version number and exit.
+
+    --class classname
+    -c classname
+        Use `classname' as the concrete SMTP proxy class.  Uses `PureProxy' by
+        default.
+
+    --size limit
+    -s limit
+        Restrict the total size of the incoming message to "limit" number of
+        bytes via the RFC 1870 SIZE extension.  Defaults to 33554432 bytes.
+
+    --smtputf8
+    -u
+        Enable the SMTPUTF8 extension and behave as an RFC 6531 smtp proxy.
+
+    --debug
+    -d
+        Turn on debugging prints.
+
+    --help
+    -h
+        Print this message and exit.
+
+Version: %(__version__)s
+
+If localhost is not given then `localhost' is used, and if localport is not
+given then 8025 is used.  If remotehost is not given then `localhost' is used,
+and if remoteport is not given, then 25 is used.
+"""
+
+# Overview:
+#
+# This file implements the minimal SMTP protocol as defined in RFC 5321.  It
+# has a hierarchy of classes which implement the backend functionality for the
+# smtpd.  A number of classes are provided:
+#
+#   SMTPServer - the base class for the backend.  Raises NotImplementedError
+#   if you try to use it.
+#
+#   DebuggingServer - simply prints each message it receives on stdout.
+#
+#   PureProxy - Proxies all messages to a real smtpd which does final
+#   delivery.  One known problem with this class is that it doesn't handle
+#   SMTP errors from the backend server at all.  This should be fixed
+#   (contributions are welcome!).
+#
+#
+# Author: Barry Warsaw 
+#
+# TODO:
+#
+# - support mailbox delivery
+# - alias files
+# - Handle more ESMTP extensions
+# - handle error codes from the backend smtpd
+
+import sys
+import os
+import errno
+import getopt
+import time
+import socket
+import collections
+from warnings import _deprecated, warn
+from email._header_value_parser import get_addr_spec, get_angle_addr
+
+__all__ = [
+    "SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy",
+]
+
+_DEPRECATION_MSG = ('The {name} module is deprecated and unmaintained and will '
+                    'be removed in Python {remove}.  Please see aiosmtpd '
+                    '(https://aiosmtpd.readthedocs.io/) for the recommended '
+                    'replacement.')
+_deprecated(__name__, _DEPRECATION_MSG, remove=(3, 12))
+
+
+# These are imported after the above warning so that users get the correct
+# deprecation warning.
+import asyncore
+import asynchat
+
+
+program = sys.argv[0]
+__version__ = 'Python SMTP proxy version 0.3'
+
+
+class Devnull:
+    def write(self, msg): pass
+    def flush(self): pass
+
+
+DEBUGSTREAM = Devnull()
+NEWLINE = '\n'
+COMMASPACE = ', '
+DATA_SIZE_DEFAULT = 33554432
+
+
+def usage(code, msg=''):
+    print(__doc__ % globals(), file=sys.stderr)
+    if msg:
+        print(msg, file=sys.stderr)
+    sys.exit(code)
+
+
+class SMTPChannel(asynchat.async_chat):
+    COMMAND = 0
+    DATA = 1
+
+    command_size_limit = 512
+    command_size_limits = collections.defaultdict(lambda x=command_size_limit: x)
+
+    @property
+    def max_command_size_limit(self):
+        try:
+            return max(self.command_size_limits.values())
+        except ValueError:
+            return self.command_size_limit
+
+    def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT,
+                 map=None, enable_SMTPUTF8=False, decode_data=False):
+        asynchat.async_chat.__init__(self, conn, map=map)
+        self.smtp_server = server
+        self.conn = conn
+        self.addr = addr
+        self.data_size_limit = data_size_limit
+        self.enable_SMTPUTF8 = enable_SMTPUTF8
+        self._decode_data = decode_data
+        if enable_SMTPUTF8 and decode_data:
+            raise ValueError("decode_data and enable_SMTPUTF8 cannot"
+                             " be set to True at the same time")
+        if decode_data:
+            self._emptystring = ''
+            self._linesep = '\r\n'
+            self._dotsep = '.'
+            self._newline = NEWLINE
+        else:
+            self._emptystring = b''
+            self._linesep = b'\r\n'
+            self._dotsep = ord(b'.')
+            self._newline = b'\n'
+        self._set_rset_state()
+        self.seen_greeting = ''
+        self.extended_smtp = False
+        self.command_size_limits.clear()
+        self.fqdn = socket.getfqdn()
+        try:
+            self.peer = conn.getpeername()
+        except OSError as err:
+            # a race condition  may occur if the other end is closing
+            # before we can get the peername
+            self.close()
+            if err.errno != errno.ENOTCONN:
+                raise
+            return
+        print('Peer:', repr(self.peer), file=DEBUGSTREAM)
+        self.push('220 %s %s' % (self.fqdn, __version__))
+
+    def _set_post_data_state(self):
+        """Reset state variables to their post-DATA state."""
+        self.smtp_state = self.COMMAND
+        self.mailfrom = None
+        self.rcpttos = []
+        self.require_SMTPUTF8 = False
+        self.num_bytes = 0
+        self.set_terminator(b'\r\n')
+
+    def _set_rset_state(self):
+        """Reset all state variables except the greeting."""
+        self._set_post_data_state()
+        self.received_data = ''
+        self.received_lines = []
+
+
+    # properties for backwards-compatibility
+    @property
+    def __server(self):
+        warn("Access to __server attribute on SMTPChannel is deprecated, "
+            "use 'smtp_server' instead", DeprecationWarning, 2)
+        return self.smtp_server
+    @__server.setter
+    def __server(self, value):
+        warn("Setting __server attribute on SMTPChannel is deprecated, "
+            "set 'smtp_server' instead", DeprecationWarning, 2)
+        self.smtp_server = value
+
+    @property
+    def __line(self):
+        warn("Access to __line attribute on SMTPChannel is deprecated, "
+            "use 'received_lines' instead", DeprecationWarning, 2)
+        return self.received_lines
+    @__line.setter
+    def __line(self, value):
+        warn("Setting __line attribute on SMTPChannel is deprecated, "
+            "set 'received_lines' instead", DeprecationWarning, 2)
+        self.received_lines = value
+
+    @property
+    def __state(self):
+        warn("Access to __state attribute on SMTPChannel is deprecated, "
+            "use 'smtp_state' instead", DeprecationWarning, 2)
+        return self.smtp_state
+    @__state.setter
+    def __state(self, value):
+        warn("Setting __state attribute on SMTPChannel is deprecated, "
+            "set 'smtp_state' instead", DeprecationWarning, 2)
+        self.smtp_state = value
+
+    @property
+    def __greeting(self):
+        warn("Access to __greeting attribute on SMTPChannel is deprecated, "
+            "use 'seen_greeting' instead", DeprecationWarning, 2)
+        return self.seen_greeting
+    @__greeting.setter
+    def __greeting(self, value):
+        warn("Setting __greeting attribute on SMTPChannel is deprecated, "
+            "set 'seen_greeting' instead", DeprecationWarning, 2)
+        self.seen_greeting = value
+
+    @property
+    def __mailfrom(self):
+        warn("Access to __mailfrom attribute on SMTPChannel is deprecated, "
+            "use 'mailfrom' instead", DeprecationWarning, 2)
+        return self.mailfrom
+    @__mailfrom.setter
+    def __mailfrom(self, value):
+        warn("Setting __mailfrom attribute on SMTPChannel is deprecated, "
+            "set 'mailfrom' instead", DeprecationWarning, 2)
+        self.mailfrom = value
+
+    @property
+    def __rcpttos(self):
+        warn("Access to __rcpttos attribute on SMTPChannel is deprecated, "
+            "use 'rcpttos' instead", DeprecationWarning, 2)
+        return self.rcpttos
+    @__rcpttos.setter
+    def __rcpttos(self, value):
+        warn("Setting __rcpttos attribute on SMTPChannel is deprecated, "
+            "set 'rcpttos' instead", DeprecationWarning, 2)
+        self.rcpttos = value
+
+    @property
+    def __data(self):
+        warn("Access to __data attribute on SMTPChannel is deprecated, "
+            "use 'received_data' instead", DeprecationWarning, 2)
+        return self.received_data
+    @__data.setter
+    def __data(self, value):
+        warn("Setting __data attribute on SMTPChannel is deprecated, "
+            "set 'received_data' instead", DeprecationWarning, 2)
+        self.received_data = value
+
+    @property
+    def __fqdn(self):
+        warn("Access to __fqdn attribute on SMTPChannel is deprecated, "
+            "use 'fqdn' instead", DeprecationWarning, 2)
+        return self.fqdn
+    @__fqdn.setter
+    def __fqdn(self, value):
+        warn("Setting __fqdn attribute on SMTPChannel is deprecated, "
+            "set 'fqdn' instead", DeprecationWarning, 2)
+        self.fqdn = value
+
+    @property
+    def __peer(self):
+        warn("Access to __peer attribute on SMTPChannel is deprecated, "
+            "use 'peer' instead", DeprecationWarning, 2)
+        return self.peer
+    @__peer.setter
+    def __peer(self, value):
+        warn("Setting __peer attribute on SMTPChannel is deprecated, "
+            "set 'peer' instead", DeprecationWarning, 2)
+        self.peer = value
+
+    @property
+    def __conn(self):
+        warn("Access to __conn attribute on SMTPChannel is deprecated, "
+            "use 'conn' instead", DeprecationWarning, 2)
+        return self.conn
+    @__conn.setter
+    def __conn(self, value):
+        warn("Setting __conn attribute on SMTPChannel is deprecated, "
+            "set 'conn' instead", DeprecationWarning, 2)
+        self.conn = value
+
+    @property
+    def __addr(self):
+        warn("Access to __addr attribute on SMTPChannel is deprecated, "
+            "use 'addr' instead", DeprecationWarning, 2)
+        return self.addr
+    @__addr.setter
+    def __addr(self, value):
+        warn("Setting __addr attribute on SMTPChannel is deprecated, "
+            "set 'addr' instead", DeprecationWarning, 2)
+        self.addr = value
+
+    # Overrides base class for convenience.
+    def push(self, msg):
+        asynchat.async_chat.push(self, bytes(
+            msg + '\r\n', 'utf-8' if self.require_SMTPUTF8 else 'ascii'))
+
+    # Implementation of base class abstract method
+    def collect_incoming_data(self, data):
+        limit = None
+        if self.smtp_state == self.COMMAND:
+            limit = self.max_command_size_limit
+        elif self.smtp_state == self.DATA:
+            limit = self.data_size_limit
+        if limit and self.num_bytes > limit:
+            return
+        elif limit:
+            self.num_bytes += len(data)
+        if self._decode_data:
+            self.received_lines.append(str(data, 'utf-8'))
+        else:
+            self.received_lines.append(data)
+
+    # Implementation of base class abstract method
+    def found_terminator(self):
+        line = self._emptystring.join(self.received_lines)
+        print('Data:', repr(line), file=DEBUGSTREAM)
+        self.received_lines = []
+        if self.smtp_state == self.COMMAND:
+            sz, self.num_bytes = self.num_bytes, 0
+            if not line:
+                self.push('500 Error: bad syntax')
+                return
+            if not self._decode_data:
+                line = str(line, 'utf-8')
+            i = line.find(' ')
+            if i < 0:
+                command = line.upper()
+                arg = None
+            else:
+                command = line[:i].upper()
+                arg = line[i+1:].strip()
+            max_sz = (self.command_size_limits[command]
+                        if self.extended_smtp else self.command_size_limit)
+            if sz > max_sz:
+                self.push('500 Error: line too long')
+                return
+            method = getattr(self, 'smtp_' + command, None)
+            if not method:
+                self.push('500 Error: command "%s" not recognized' % command)
+                return
+            method(arg)
+            return
+        else:
+            if self.smtp_state != self.DATA:
+                self.push('451 Internal confusion')
+                self.num_bytes = 0
+                return
+            if self.data_size_limit and self.num_bytes > self.data_size_limit:
+                self.push('552 Error: Too much mail data')
+                self.num_bytes = 0
+                return
+            # Remove extraneous carriage returns and de-transparency according
+            # to RFC 5321, Section 4.5.2.
+            data = []
+            for text in line.split(self._linesep):
+                if text and text[0] == self._dotsep:
+                    data.append(text[1:])
+                else:
+                    data.append(text)
+            self.received_data = self._newline.join(data)
+            args = (self.peer, self.mailfrom, self.rcpttos, self.received_data)
+            kwargs = {}
+            if not self._decode_data:
+                kwargs = {
+                    'mail_options': self.mail_options,
+                    'rcpt_options': self.rcpt_options,
+                }
+            status = self.smtp_server.process_message(*args, **kwargs)
+            self._set_post_data_state()
+            if not status:
+                self.push('250 OK')
+            else:
+                self.push(status)
+
+    # SMTP and ESMTP commands
+    def smtp_HELO(self, arg):
+        if not arg:
+            self.push('501 Syntax: HELO hostname')
+            return
+        # See issue #21783 for a discussion of this behavior.
+        if self.seen_greeting:
+            self.push('503 Duplicate HELO/EHLO')
+            return
+        self._set_rset_state()
+        self.seen_greeting = arg
+        self.push('250 %s' % self.fqdn)
+
+    def smtp_EHLO(self, arg):
+        if not arg:
+            self.push('501 Syntax: EHLO hostname')
+            return
+        # See issue #21783 for a discussion of this behavior.
+        if self.seen_greeting:
+            self.push('503 Duplicate HELO/EHLO')
+            return
+        self._set_rset_state()
+        self.seen_greeting = arg
+        self.extended_smtp = True
+        self.push('250-%s' % self.fqdn)
+        if self.data_size_limit:
+            self.push('250-SIZE %s' % self.data_size_limit)
+            self.command_size_limits['MAIL'] += 26
+        if not self._decode_data:
+            self.push('250-8BITMIME')
+        if self.enable_SMTPUTF8:
+            self.push('250-SMTPUTF8')
+            self.command_size_limits['MAIL'] += 10
+        self.push('250 HELP')
+
+    def smtp_NOOP(self, arg):
+        if arg:
+            self.push('501 Syntax: NOOP')
+        else:
+            self.push('250 OK')
+
+    def smtp_QUIT(self, arg):
+        # args is ignored
+        self.push('221 Bye')
+        self.close_when_done()
+
+    def _strip_command_keyword(self, keyword, arg):
+        keylen = len(keyword)
+        if arg[:keylen].upper() == keyword:
+            return arg[keylen:].strip()
+        return ''
+
+    def _getaddr(self, arg):
+        if not arg:
+            return '', ''
+        if arg.lstrip().startswith('<'):
+            address, rest = get_angle_addr(arg)
+        else:
+            address, rest = get_addr_spec(arg)
+        if not address:
+            return address, rest
+        return address.addr_spec, rest
+
+    def _getparams(self, params):
+        # Return params as dictionary. Return None if not all parameters
+        # appear to be syntactically valid according to RFC 1869.
+        result = {}
+        for param in params:
+            param, eq, value = param.partition('=')
+            if not param.isalnum() or eq and not value:
+                return None
+            result[param] = value if eq else True
+        return result
+
+    def smtp_HELP(self, arg):
+        if arg:
+            extended = ' [SP ]'
+            lc_arg = arg.upper()
+            if lc_arg == 'EHLO':
+                self.push('250 Syntax: EHLO hostname')
+            elif lc_arg == 'HELO':
+                self.push('250 Syntax: HELO hostname')
+            elif lc_arg == 'MAIL':
+                msg = '250 Syntax: MAIL FROM: 
' + if self.extended_smtp: + msg += extended + self.push(msg) + elif lc_arg == 'RCPT': + msg = '250 Syntax: RCPT TO:
' + if self.extended_smtp: + msg += extended + self.push(msg) + elif lc_arg == 'DATA': + self.push('250 Syntax: DATA') + elif lc_arg == 'RSET': + self.push('250 Syntax: RSET') + elif lc_arg == 'NOOP': + self.push('250 Syntax: NOOP') + elif lc_arg == 'QUIT': + self.push('250 Syntax: QUIT') + elif lc_arg == 'VRFY': + self.push('250 Syntax: VRFY
') + else: + self.push('501 Supported commands: EHLO HELO MAIL RCPT ' + 'DATA RSET NOOP QUIT VRFY') + else: + self.push('250 Supported commands: EHLO HELO MAIL RCPT DATA ' + 'RSET NOOP QUIT VRFY') + + def smtp_VRFY(self, arg): + if arg: + address, params = self._getaddr(arg) + if address: + self.push('252 Cannot VRFY user, but will accept message ' + 'and attempt delivery') + else: + self.push('502 Could not VRFY %s' % arg) + else: + self.push('501 Syntax: VRFY
') + + def smtp_MAIL(self, arg): + if not self.seen_greeting: + self.push('503 Error: send HELO first') + return + print('===> MAIL', arg, file=DEBUGSTREAM) + syntaxerr = '501 Syntax: MAIL FROM:
' + if self.extended_smtp: + syntaxerr += ' [SP ]' + if arg is None: + self.push(syntaxerr) + return + arg = self._strip_command_keyword('FROM:', arg) + address, params = self._getaddr(arg) + if not address: + self.push(syntaxerr) + return + if not self.extended_smtp and params: + self.push(syntaxerr) + return + if self.mailfrom: + self.push('503 Error: nested MAIL command') + return + self.mail_options = params.upper().split() + params = self._getparams(self.mail_options) + if params is None: + self.push(syntaxerr) + return + if not self._decode_data: + body = params.pop('BODY', '7BIT') + if body not in ['7BIT', '8BITMIME']: + self.push('501 Error: BODY can only be one of 7BIT, 8BITMIME') + return + if self.enable_SMTPUTF8: + smtputf8 = params.pop('SMTPUTF8', False) + if smtputf8 is True: + self.require_SMTPUTF8 = True + elif smtputf8 is not False: + self.push('501 Error: SMTPUTF8 takes no arguments') + return + size = params.pop('SIZE', None) + if size: + if not size.isdigit(): + self.push(syntaxerr) + return + elif self.data_size_limit and int(size) > self.data_size_limit: + self.push('552 Error: message size exceeds fixed maximum message size') + return + if len(params.keys()) > 0: + self.push('555 MAIL FROM parameters not recognized or not implemented') + return + self.mailfrom = address + print('sender:', self.mailfrom, file=DEBUGSTREAM) + self.push('250 OK') + + def smtp_RCPT(self, arg): + if not self.seen_greeting: + self.push('503 Error: send HELO first'); + return + print('===> RCPT', arg, file=DEBUGSTREAM) + if not self.mailfrom: + self.push('503 Error: need MAIL command') + return + syntaxerr = '501 Syntax: RCPT TO:
' + if self.extended_smtp: + syntaxerr += ' [SP ]' + if arg is None: + self.push(syntaxerr) + return + arg = self._strip_command_keyword('TO:', arg) + address, params = self._getaddr(arg) + if not address: + self.push(syntaxerr) + return + if not self.extended_smtp and params: + self.push(syntaxerr) + return + self.rcpt_options = params.upper().split() + params = self._getparams(self.rcpt_options) + if params is None: + self.push(syntaxerr) + return + # XXX currently there are no options we recognize. + if len(params.keys()) > 0: + self.push('555 RCPT TO parameters not recognized or not implemented') + return + self.rcpttos.append(address) + print('recips:', self.rcpttos, file=DEBUGSTREAM) + self.push('250 OK') + + def smtp_RSET(self, arg): + if arg: + self.push('501 Syntax: RSET') + return + self._set_rset_state() + self.push('250 OK') + + def smtp_DATA(self, arg): + if not self.seen_greeting: + self.push('503 Error: send HELO first'); + return + if not self.rcpttos: + self.push('503 Error: need RCPT command') + return + if arg: + self.push('501 Syntax: DATA') + return + self.smtp_state = self.DATA + self.set_terminator(b'\r\n.\r\n') + self.push('354 End data with .') + + # Commands that have not been implemented + def smtp_EXPN(self, arg): + self.push('502 EXPN not implemented') + + +class SMTPServer(asyncore.dispatcher): + # SMTPChannel class to use for managing client connections + channel_class = SMTPChannel + + def __init__(self, localaddr, remoteaddr, + data_size_limit=DATA_SIZE_DEFAULT, map=None, + enable_SMTPUTF8=False, decode_data=False): + self._localaddr = localaddr + self._remoteaddr = remoteaddr + self.data_size_limit = data_size_limit + self.enable_SMTPUTF8 = enable_SMTPUTF8 + self._decode_data = decode_data + if enable_SMTPUTF8 and decode_data: + raise ValueError("decode_data and enable_SMTPUTF8 cannot" + " be set to True at the same time") + asyncore.dispatcher.__init__(self, map=map) + try: + gai_results = socket.getaddrinfo(*localaddr, + type=socket.SOCK_STREAM) + self.create_socket(gai_results[0][0], gai_results[0][1]) + # try to re-use a server port if possible + self.set_reuse_addr() + self.bind(localaddr) + self.listen(5) + except: + self.close() + raise + else: + print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( + self.__class__.__name__, time.ctime(time.time()), + localaddr, remoteaddr), file=DEBUGSTREAM) + + def handle_accepted(self, conn, addr): + print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) + channel = self.channel_class(self, + conn, + addr, + self.data_size_limit, + self._map, + self.enable_SMTPUTF8, + self._decode_data) + + # API for "doing something useful with the message" + def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): + """Override this abstract method to handle messages from the client. + + peer is a tuple containing (ipaddr, port) of the client that made the + socket connection to our smtp port. + + mailfrom is the raw address the client claims the message is coming + from. + + rcpttos is a list of raw addresses the client wishes to deliver the + message to. + + data is a string containing the entire full text of the message, + headers (if supplied) and all. It has been `de-transparencied' + according to RFC 821, Section 4.5.2. In other words, a line + containing a `.' followed by other text has had the leading dot + removed. + + kwargs is a dictionary containing additional information. It is + empty if decode_data=True was given as init parameter, otherwise + it will contain the following keys: + 'mail_options': list of parameters to the mail command. All + elements are uppercase strings. Example: + ['BODY=8BITMIME', 'SMTPUTF8']. + 'rcpt_options': same, for the rcpt command. + + This function should return None for a normal `250 Ok' response; + otherwise, it should return the desired response string in RFC 821 + format. + + """ + raise NotImplementedError + + +class DebuggingServer(SMTPServer): + + def _print_message_content(self, peer, data): + inheaders = 1 + lines = data.splitlines() + for line in lines: + # headers first + if inheaders and not line: + peerheader = 'X-Peer: ' + peer[0] + if not isinstance(data, str): + # decoded_data=false; make header match other binary output + peerheader = repr(peerheader.encode('utf-8')) + print(peerheader) + inheaders = 0 + if not isinstance(data, str): + # Avoid spurious 'str on bytes instance' warning. + line = repr(line) + print(line) + + def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): + print('---------- MESSAGE FOLLOWS ----------') + if kwargs: + if kwargs.get('mail_options'): + print('mail options: %s' % kwargs['mail_options']) + if kwargs.get('rcpt_options'): + print('rcpt options: %s\n' % kwargs['rcpt_options']) + self._print_message_content(peer, data) + print('------------ END MESSAGE ------------') + + +class PureProxy(SMTPServer): + def __init__(self, *args, **kwargs): + if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: + raise ValueError("PureProxy does not support SMTPUTF8.") + super(PureProxy, self).__init__(*args, **kwargs) + + def process_message(self, peer, mailfrom, rcpttos, data): + lines = data.split('\n') + # Look for the last header + i = 0 + for line in lines: + if not line: + break + i += 1 + lines.insert(i, 'X-Peer: %s' % peer[0]) + data = NEWLINE.join(lines) + refused = self._deliver(mailfrom, rcpttos, data) + # TBD: what to do with refused addresses? + print('we got some refusals:', refused, file=DEBUGSTREAM) + + def _deliver(self, mailfrom, rcpttos, data): + import smtplib + refused = {} + try: + s = smtplib.SMTP() + s.connect(self._remoteaddr[0], self._remoteaddr[1]) + try: + refused = s.sendmail(mailfrom, rcpttos, data) + finally: + s.quit() + except smtplib.SMTPRecipientsRefused as e: + print('got SMTPRecipientsRefused', file=DEBUGSTREAM) + refused = e.recipients + except (OSError, smtplib.SMTPException) as e: + print('got', e.__class__, file=DEBUGSTREAM) + # All recipients were refused. If the exception had an associated + # error code, use it. Otherwise,fake it with a non-triggering + # exception code. + errcode = getattr(e, 'smtp_code', -1) + errmsg = getattr(e, 'smtp_error', 'ignore') + for r in rcpttos: + refused[r] = (errcode, errmsg) + return refused + + +class Options: + setuid = True + classname = 'PureProxy' + size_limit = None + enable_SMTPUTF8 = False + + +def parseargs(): + global DEBUGSTREAM + try: + opts, args = getopt.getopt( + sys.argv[1:], 'nVhc:s:du', + ['class=', 'nosetuid', 'version', 'help', 'size=', 'debug', + 'smtputf8']) + except getopt.error as e: + usage(1, e) + + options = Options() + for opt, arg in opts: + if opt in ('-h', '--help'): + usage(0) + elif opt in ('-V', '--version'): + print(__version__) + sys.exit(0) + elif opt in ('-n', '--nosetuid'): + options.setuid = False + elif opt in ('-c', '--class'): + options.classname = arg + elif opt in ('-d', '--debug'): + DEBUGSTREAM = sys.stderr + elif opt in ('-u', '--smtputf8'): + options.enable_SMTPUTF8 = True + elif opt in ('-s', '--size'): + try: + int_size = int(arg) + options.size_limit = int_size + except: + print('Invalid size: ' + arg, file=sys.stderr) + sys.exit(1) + + # parse the rest of the arguments + if len(args) < 1: + localspec = 'localhost:8025' + remotespec = 'localhost:25' + elif len(args) < 2: + localspec = args[0] + remotespec = 'localhost:25' + elif len(args) < 3: + localspec = args[0] + remotespec = args[1] + else: + usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) + + # split into host/port pairs + i = localspec.find(':') + if i < 0: + usage(1, 'Bad local spec: %s' % localspec) + options.localhost = localspec[:i] + try: + options.localport = int(localspec[i+1:]) + except ValueError: + usage(1, 'Bad local port: %s' % localspec) + i = remotespec.find(':') + if i < 0: + usage(1, 'Bad remote spec: %s' % remotespec) + options.remotehost = remotespec[:i] + try: + options.remoteport = int(remotespec[i+1:]) + except ValueError: + usage(1, 'Bad remote port: %s' % remotespec) + return options + + +if __name__ == '__main__': + options = parseargs() + # Become nobody + classname = options.classname + if "." in classname: + lastdot = classname.rfind(".") + mod = __import__(classname[:lastdot], globals(), locals(), [""]) + classname = classname[lastdot+1:] + else: + import __main__ as mod + class_ = getattr(mod, classname) + proxy = class_((options.localhost, options.localport), + (options.remotehost, options.remoteport), + options.size_limit, enable_SMTPUTF8=options.enable_SMTPUTF8) + if options.setuid: + try: + import pwd + except ImportError: + print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) + sys.exit(1) + nobody = pwd.getpwnam('nobody')[2] + try: + os.setuid(nobody) + except PermissionError: + print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) + sys.exit(1) + try: + asyncore.loop() + except KeyboardInterrupt: + pass diff --git a/shared/package-files/ef/ef37f8ea37aaa5c9d8ac82d27ce5b098ee9c3734b9d35bee146bd1011ee83005/_foobar_native.h b/shared/package-files/ef/ef37f8ea37aaa5c9d8ac82d27ce5b098ee9c3734b9d35bee146bd1011ee83005/_foobar_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e4e8550ce77e6bceb602c6fa088fd08cad767bfc --- /dev/null +++ b/shared/package-files/ef/ef37f8ea37aaa5c9d8ac82d27ce5b098ee9c3734b9d35bee146bd1011ee83005/_foobar_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _foobar_out(const at::Tensor & self, bool arg1, bool arg2, bool arg3, at::Tensor & out); +TORCH_API at::Tensor foobar(const at::Tensor & self, bool arg1=true, bool arg2=true, bool arg3=true); +} // namespace native +} // namespace at diff --git a/shared/package-files/ef/ef380c07c6b691c117fd459ad049a10b6a3e2fae5085734bf28a7ee9c3367ffd/vec_mask.h b/shared/package-files/ef/ef380c07c6b691c117fd459ad049a10b6a3e2fae5085734bf28a7ee9c3367ffd/vec_mask.h new file mode 100644 index 0000000000000000000000000000000000000000..c547e5911ecbd653d6cfde9c6e6363390490c60a --- /dev/null +++ b/shared/package-files/ef/ef380c07c6b691c117fd459ad049a10b6a3e2fae5085734bf28a7ee9c3367ffd/vec_mask.h @@ -0,0 +1,295 @@ +#pragma once + +#include +#include +namespace at::vec { +inline namespace CPU_CAPABILITY { + +/** + * The `VecMask` class provides a convenient interface for working with + * vectorized masks in SIMD operations. It encapsulates a `Vectorized` + * mask that can be directly usable in masked vectorized operations. It provides + * various methods for manipulating and accessing the mask elements: + * 1. `from` and `to`: Conversion between a vector of boolean values and a + * vectorized mask. + * 2. `cast`: Casts the mask to a different base type. + * 3. `all_zero`: Checks if all mask elements are zero. + * 4. `is_masked`: Checks if a specific element is masked. + * 5. `loadu`: Loads data from memory using the mask. + * 6. `all_masked`: Checks if all mask elements are masked. + * + * Some helper template classes are provided to simplify the specialization of + * the `VecMask` for the specific CPU arch: + * 1. `VecMaskLoad`: Loads data from memory using the mask. + * 2. `VecMaskTo`: Converts the mask to boolean. + * 3. `VecMaskCast`: Casts the mask to a different base type. + * + */ +template +class VecMask; + +template < + typename data_t, + int data_n, + typename mask_t, + int mask_n, + typename Enabled = void> +struct VecMaskLoad { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + constexpr typename VecMask::size_type size = + VecMask::size(); + static_assert(VectorizedN::size() >= size); + __at_align__ data_t data[size]; + __at_align__ mask_t mask[size]; + auto mask_ = VectorizedN(vec_mask); + mask_.store(mask); + for (int i = 0; i < size; i++) { + data[i] = mask[i] ? ptr[i] : static_cast(0); + } + return VectorizedN::loadu(data, size); + } +}; + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + typename Enabled = void> +struct VecMaskTo { + static inline VecMask apply( + const VecMask& vec_mask) { + auto zeros = VectorizedN(static_cast(0)); + auto ones = VectorizedN(static_cast(1)); + return VectorizedN::blendv( + zeros, ones, vec_mask.template cast()); + } +}; + +template +struct VecMaskCast { + static inline VecMask apply( + const VecMask& vec_mask) { + return VecMask::from(VectorizedN(vec_mask)); + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + return vec_mask; + } +}; + +template +struct VecMaskCheck { + static inline bool all_zero(const VectorizedN& vec_mask) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return std::all_of( + mask, mask + VectorizedN::size(), [](T m) { return m == static_cast(0); }); + } + + static inline bool all_masked(const VectorizedN& vec_mask) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return std::all_of( + mask, mask + VectorizedN::size(), [](T m) { return m != static_cast(0); }); + } + + static inline bool is_masked(const VectorizedN& vec_mask, int i) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return mask[i] != static_cast(0); + } +}; + +template +class VecMask { + public: + using size_type = int; + static constexpr size_type size() { + return VectorizedN::size(); + } + + private: + VectorizedN mask_; + + public: + VecMask() : mask_(static_cast(0)) {} + VecMask(const VectorizedN& mask) : mask_(mask) {} + + template = 0> + VecMask(const Vectorized& mask) : mask_(mask) {} + + template + static VecMask from(const VectorizedN& b_vec) { + __at_align__ U b_buf[size()]; + if constexpr (size() >= VectorizedN::size()) { + b_vec.store(b_buf); + for (int i = VectorizedN::size(); i < size(); i++) { + b_buf[i] = static_cast(0); + } + } else { + b_vec.store(b_buf, size()); + } + return from(b_buf); + } + + template + static VecMask from(U b) { + using int_t = int_same_size_t; + T mask = b ? c10::bit_cast((int_t)(~(int_t)0)) : (T)0; + return VectorizedN(mask); + } + + template + static VecMask from(U* b) { + using int_t = int_same_size_t; + __at_align__ T mask[size()]; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (int i = 0; i < size(); i++) { + *(int_t*)(mask + i) = b[i] ? ~(int_t)0 : (int_t)0; + } + return VectorizedN(VectorizedN::loadu(mask)); + } + + static VecMask blendv( + const VecMask& c, + const VecMask& b, + const VecMask& a) { + VectorizedN result = VectorizedN::blendv( + VectorizedN(c), + VectorizedN(b), + VectorizedN(a)); + return result; + } + + static VecMask set( + const VecMask& a, + const VecMask& b, + int64_t count = size()) { + VectorizedN result = VectorizedN::set( + VectorizedN(a), + VectorizedN(b), + count); + return result; + } + + void store(bool* b, int count = size()) { + constexpr int L = (VectorizedN::size() + Vectorized::size() - 1)/ Vectorized::size(); + auto res = this->to(); + res.store(b, count); + return; + } + + template = 2, int> = 0> + inline VectorizedN to() const { + return VecMaskTo::apply(*this); + } + + template = 0> + inline Vectorized to() const { + return VecMaskTo::apply(*this); + } + + template + inline VecMask cast() const { + return VecMaskCast::apply(*this); + } + + inline bool all_zero() const { + return VecMaskCheck::all_zero(mask_); + } + + inline bool all_masked() const { + return VecMaskCheck::all_masked(mask_); + } + + inline bool is_masked(int i) const { + return VecMaskCheck::is_masked(mask_, i); + } + + inline operator VectorizedN() const { + return mask_; + } + + template = 0> + inline operator Vectorized() const { + return mask_[0]; + } + + inline Vectorized operator[](int i) const { + return mask_[i]; + } + + template < + typename U, + int L, + std::enable_if_t= 2 && VectorizedN::size() >= size(), int> = 0> + VectorizedN loadu(const U* ptr) const { + return VecMaskLoad::apply(ptr, *this); + } + + template < + typename U, + int L, + std::enable_if_t::size() >= size(), int> = 0> + Vectorized loadu(const U* ptr) const { + return VecMaskLoad::apply(ptr, *this); + } +}; + +#define VEC_MASK_DEFINE_UNARY_OP_GLOBAL(op) \ + template \ + inline VecMask op(const VecMask& a) { \ + return op(VectorizedN(a)); \ + } + +#define VEC_MASK_DEFINE_BINARY_OP_GLOBAL(op) \ + template < \ + typename T, \ + int N, \ + typename V, \ + int M, \ + std::enable_if_t::size() == VecMask::size(), int> = \ + 0> \ + inline VecMask op(const VecMask& a, const VecMask& b) { \ + return op( \ + VectorizedN(a), VectorizedN(b.template cast())); \ + } + +#define VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(op, EXPR) \ + template < \ + typename T, \ + int N, \ + typename V, \ + int M, \ + std::enable_if_t::size() == VecMask::size(), int> = \ + 0> \ + inline VecMask op(const VecMask& a, const VecMask& b) { \ + return EXPR; \ + } + +VEC_MASK_DEFINE_UNARY_OP_GLOBAL(operator~) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator&) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator|) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator^) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator*) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator>, a & ~b) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator<, ~a& b) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator==, ~(a ^ b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator>=, (a == b) | (a > b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator<=, (a == b) | (a < b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator!=, (a ^ b)) + +#undef VEC_MASK_DEFINE_UNARY_OP_GLOBAL +#undef VEC_MASK_DEFINE_BINARY_OP_GLOBAL +#undef VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/shared/package-files/ef/ef3b0046330d656c376c2a384c34617d88298dc9341dd5478956417946326658/base.cpython-311.pyc b/shared/package-files/ef/ef3b0046330d656c376c2a384c34617d88298dc9341dd5478956417946326658/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..377e8374fae65c9647db1d077afca117feae37fb Binary files /dev/null and b/shared/package-files/ef/ef3b0046330d656c376c2a384c34617d88298dc9341dd5478956417946326658/base.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef3c3f1017f2aeb91230ec8f224a98ba1d4dc43a28ceca81deef26a8f668a259/repeat_interleave_cpu_dispatch.h b/shared/package-files/ef/ef3c3f1017f2aeb91230ec8f224a98ba1d4dc43a28ceca81deef26a8f668a259/repeat_interleave_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1dedeba48290706ff10dcfe0a0a7a3c31bd8e65c --- /dev/null +++ b/shared/package-files/ef/ef3c3f1017f2aeb91230ec8f224a98ba1d4dc43a28ceca81deef26a8f668a259/repeat_interleave_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor repeat_interleave(const at::Tensor & repeats, ::std::optional output_size=::std::nullopt); +TORCH_API at::Tensor repeat_interleave_symint(const at::Tensor & repeats, ::std::optional output_size=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/ef/ef3c8d7541659a56165d9c343eb785cdaaafada40a86cec49530c331dca61321/utils.cpython-311.pyc b/shared/package-files/ef/ef3c8d7541659a56165d9c343eb785cdaaafada40a86cec49530c331dca61321/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90586804a4853b4fc1fa247d5cb18352bb79cf11 Binary files /dev/null and b/shared/package-files/ef/ef3c8d7541659a56165d9c343eb785cdaaafada40a86cec49530c331dca61321/utils.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef442289c11d35a39a1d68a45d28b2e6ead1fcf49fb4584619411b9d7b13f133/eval_frame.py b/shared/package-files/ef/ef442289c11d35a39a1d68a45d28b2e6ead1fcf49fb4584619411b9d7b13f133/eval_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..dcdc5b3874d374ec7e7814c10ffce49b3fe9a0e4 --- /dev/null +++ b/shared/package-files/ef/ef442289c11d35a39a1d68a45d28b2e6ead1fcf49fb4584619411b9d7b13f133/eval_frame.py @@ -0,0 +1,1968 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="method-assign" + +""" +This module implements the core frame evaluation handler for TorchDynamo's compilation system. +The eval frame handler intercepts Python bytecode execution at runtime to enable dynamic +compilation and optimization of PyTorch code. + +Key components defined here: +- Frame evaluation handlers that intercept and analyze Python execution frames +- Guards management for tracking dependencies and invalidating compiled code +- Optimization contexts and decorators (optimize, run_once, disable, etc.) +- Export functionality for saving optimized graphs +- Backend compiler integrations and callback management + +Functions in this file are responsible for modifying the eval frame handler at RUNTIME. +Therefore, all functions in this file are hot and performance-critical. Functions that +only execute at compile time should be placed in torch._dynamo.convert_frame. + +The eval frame handler is the core mechanism that enables TorchDynamo to dynamically +intercept, analyze and optimize PyTorch code during execution. It works by registering +a custom frame evaluation function that gets called for every Python frame, allowing +us to detect PyTorch operations and trigger compilation as needed. +""" + +from __future__ import annotations + +import atexit +import contextlib +import functools +import inspect +import logging +import os +import sys +import sysconfig +import textwrap +import threading +import traceback +import types +import warnings +import weakref +from dataclasses import dataclass +from enum import Enum +from os.path import dirname, join +from typing import Any, Callable, NamedTuple, Optional, TYPE_CHECKING, Union +from unittest.mock import patch + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +import torch.utils.checkpoint +from torch import _guards + +# see discussion at https://github.com/pytorch/pytorch/issues/120699 +from torch._C._dynamo.eval_frame import ( # noqa: F401 + reset_code, + set_code_exec_strategy, + set_eval_frame, + set_guard_error_hook, + set_skip_guard_eval_unsafe, + unsupported, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.types import ConvertFrameReturn, FrameAction, FrameExecStrategy +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch._utils_internal import justknobs_check, log_export_usage +from torch.export.dynamic_shapes import ( + _combine_args, + _process_dynamic_shapes, + _RelaxedConstraint, +) +from torch.fx import GraphModule +from torch.fx.experimental._dynamism import ( + clone_and_convert_to_meta, + track_dynamism_across_examples, +) +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + ShapeEnv, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from . import config, convert_frame, external_utils, trace_rules, utils +from .backends.registry import CompilerFn, lookup_backend +from .code_context import code_context +from .exc import ( + CondOpArgsMismatchError, + ShortenTraceback, + Unsupported, + UserError, + UserErrorType, +) +from .hooks import Hooks +from .mutation_guard import install_generation_tagging_init +from .utils import common_constant_types, compile_times + + +if TYPE_CHECKING: + from torch._subclasses import fake_tensor + + from .types import CacheEntry, DynamoCallback + + +log = logging.getLogger(__name__) + + +always_optimize_code_objects = utils.ExactWeakKeyDictionary() +null_context = contextlib.nullcontext + + +# See https://github.com/python/typing/pull/240 +class Unset(Enum): + token = 0 + + +cached_backends: dict[int, CompilerFn] = {} + +unset = Unset.token + + +def _maybe_set_eval_frame(callback: DynamoCallback): + # A wrapper on set_eval_frame that is guarded by a Justknob. + # Users can disable torchDynamo by setting the JK to False. + if not justknobs_check("pytorch/compiler:enable_compiler_set_eval_frame"): + torch._dynamo.utils.warn_once( + "Dynamo disabled by Justknob: enable_compiler_set_eval_frame, skipping set_eval_frame" + ) + return callback + else: + return set_eval_frame(callback) + + +@dataclass +class DynamoStance: + stance: str = "default" + skip_guard_eval_unsafe: bool = False + backend: Union[str, Callable[..., Any], None] = None + + +_stance = DynamoStance() + + +def _set_stance(stance: DynamoStance) -> DynamoStance: + global _stance + + from torch._C._dynamo.eval_frame import get_eval_frame_callback + + callback = get_eval_frame_callback() + + if callback is not False and callback is not None: + raise RuntimeError("attempted to set_stance in a torch.compile region") + + prior = _stance + _stance = stance + return prior + + +_set_stance._dynamo_forbidden = True # type: ignore[attr-defined] + +_EXAMPLE_INPUTS: Optional[dict[str, list[Any]]] = None + + +def get_example_inputs(key) -> list[Any]: + global _EXAMPLE_INPUTS + if _EXAMPLE_INPUTS is None: + _EXAMPLE_INPUTS = {} + + if key not in _EXAMPLE_INPUTS: + _EXAMPLE_INPUTS[key] = [] + + return _EXAMPLE_INPUTS[key] + + +def _callback_from_stance(callback): + if _stance.stance == "default": + # force_backend + if _stance.backend is not None and callback not in (False, None): + callback = _create_wrapped_callback(get_compiler_fn(_stance.backend)) + + return callback + elif _stance.stance == "eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "aot_eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "force_eager": + # disable + return None + elif _stance.stance == "eager_on_recompile": + # run mode + return False + elif _stance.stance == "fail_on_recompile": + if callback in (False, None): + return callback + + def fail_callback(*args, **kwargs): + raise RuntimeError( + "Detected recompile when torch.compile stance is 'fail_on_recompile'" + ) + + # to prevent cache miss due to different callback + fail_callback._torchdynamo_orig_callable = callback # type: ignore[attr-defined] + + return fail_callback + else: + raise RuntimeError(f"invalid torch.compile stance '{_stance}'") + + +def _create_wrapped_callback(compiler_fn, dynamism=None): + hooks = Hooks() + return convert_frame.catch_errors_wrapper( + convert_frame.convert_frame( # type: ignore[arg-type] + compiler_fn, + hooks, + ), + hooks, + ) + + +def _get_or_add_example_inputs(frame): + key = frame.f_code.co_filename + str(frame.f_code.co_firstlineno) + example_inputs = get_example_inputs(key) + + if len(example_inputs) < 2: + example_inputs.append(clone_and_convert_to_meta(frame.f_locals)) + + return example_inputs + + +def _create_delayed_compile_callback(callback, stance): + def callback_fn(*args, **kwargs): + frame = args[0] + example_inputs = _get_or_add_example_inputs(frame) + + if len(example_inputs) == 1: + if stance == "eager_then_compile": + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.DEFAULT, FrameAction.DEFAULT + ) + ) + elif stance == "aot_eager_then_compile": + aot_eager_fn = get_compiler_fn("aot_eager") + return _create_wrapped_callback(aot_eager_fn)(*args, **kwargs) + + dynamism = track_dynamism_across_examples(example_inputs) + code_context.get_context(frame.f_code)["dynamism"] = dynamism + compiler_fn = callback._torchdynamo_orig_callable._torchdynamo_orig_callable + return _create_wrapped_callback(compiler_fn, dynamism)(*args, **kwargs) + + return callback_fn + + +def _is_skip_guard_eval_unsafe_stance(): + return _stance.skip_guard_eval_unsafe + + +def _reset_guarded_backend_cache(): + global cached_backends + for backend in cached_backends.values(): + if hasattr(backend, "reset"): + backend.reset() + cached_backends.clear() + + +DONT_WRAP_FILES = { + # For tracing into fx modules + inspect.getsourcefile(GraphModule), + join(dirname(dirname(__file__)), "onnx/_internal/fx/dynamo_graph_extractor.py"), +} + + +def _debug_get_cache_entry_list( + code: Union[types.CodeType, Callable[..., Any]], +) -> list[CacheEntry]: + """ + Given a code object or a callable object, retrieve the cache entries + stored in this code. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._debug_get_cache_entry_list(code) + + +class OptimizedModule(torch.nn.Module): + """ + Wraps the original nn.Module object and later patches its + forward method to optimized self.forward method. + """ + + _torchdynamo_orig_callable: Callable[..., Any] + get_compiler_config: Callable[[], Any] + + _opt_mod_attributes = { + "_orig_mod", + "dynamo_ctx", + "_torchdynamo_orig_callable", + "get_compiler_config", + "forward", + "_forward", + "__dict__", + "named_children_walk", + } + + def __init__(self, mod: torch.nn.Module, dynamo_ctx) -> None: + super().__init__() + # Installs the params/buffer + self._orig_mod = mod + self.dynamo_ctx = dynamo_ctx + self._initialize() + self.training = self._orig_mod.training + + def _initialize(self): + # Do this stuff in constructor to lower overhead slightly + if isinstance(self.dynamo_ctx, DisableContext): + # No need to check trace rules + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + elif isinstance(self._orig_mod.forward, types.MethodType) and ( + trace_rules.check(self._orig_mod.forward) + or getattr(self._orig_mod, "_is_fsdp_managed_module", False) + ): + # This may be a torch.nn.* instance in trace_rules.py which + # won't trigger a frame evaluation workaround to add an extra + # frame we can capture + self.forward = self.dynamo_ctx(external_utils.wrap_inline(self._orig_mod)) + else: + # Invoke hooks outside of dynamo then pickup the inner frame + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + + if hasattr(self._orig_mod, "_initialize_hook"): + self._forward = self.forward + self.forward = self._call_lazy_check + + def __reduce__(self): + return (self.__class__, (self._orig_mod, self.dynamo_ctx)) + + def __getstate__(self): + state = dict(self.__dict__) + state.pop("forward", None) + state.pop("__call__", None) + return state + + def __setstate__(self, state): + self.__dict__ = state + self._initialize() + + @property + def training(self): + return self._orig_mod.training + + @training.setter + def training(self, value): + try: + super().__getattr__("_orig_mod") + self._orig_mod.training = value + except AttributeError: + # still initializing + pass + + def __getattr__(self, name): + if name == "_orig_mod": + return self._modules["_orig_mod"] + return getattr(self._orig_mod, name) + + def __setattr__(self, name, val) -> None: + # Allow patching over class attributes + if hasattr(type(self), name): + return super().__setattr__(name, val) + + if name in OptimizedModule._opt_mod_attributes: + return super().__setattr__(name, val) + return setattr(self._orig_mod, name, val) + + def _call_lazy_check(self, *args, **kwargs): + if ( + hasattr(self._orig_mod, "_initialize_hook") + and hasattr(self._orig_mod, "_infer_parameters") + and callable(self._orig_mod._infer_parameters) + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + self._orig_mod._infer_parameters(self._orig_mod, args, kwargs) + return self._forward(*args, **kwargs) + + def __dir__(self): + orig_mod_attrs = self._orig_mod.__dir__() + return orig_mod_attrs + [ + attr for attr in super().__dir__() if attr not in orig_mod_attrs + ] + + +def remove_from_cache(f): + """ + Make sure f.__code__ is not cached to force a recompile + """ + if isinstance(f, types.CodeType): + reset_code(f) + elif hasattr(f, "__code__"): + reset_code(f.__code__) + elif hasattr(getattr(f, "forward", None), "__code__"): + reset_code(f.forward.__code__) + else: + from . import reset # type: ignore[attr-defined] + + reset() + log.warning("could not determine __code__ for %s", f) + + +def nothing(): + pass + + +def always_false(): + return False + + +def innermost_fn(fn): + """ + In case of nesting of _TorchDynamoContext calls, find the innermost + function. TorchDynamo caches on fn.__code__ object, so its necessary to find + the innermost function to pass on the optimize, run, disable etc. + """ + unaltered_fn = fn + while hasattr(unaltered_fn, "_torchdynamo_orig_callable"): + unaltered_fn = unaltered_fn._torchdynamo_orig_callable + assert callable(unaltered_fn) + return unaltered_fn + + +def make_set_enable_dynamic(enable: bool): + assert isinstance(enable, bool) + if enable: + # Assume everything is dynamic by default + return config._make_closure_patcher(assume_static_by_default=False) + else: + return config._make_closure_patcher( + automatic_dynamic_shapes=False, assume_static_by_default=True + ) + + +# A thread local storage that serves to store information as Dynamo traces +# through a user provided function. +class DynamoTLS(threading.local): + # Each string is a summary of a frame Dynamo attempted to trace, stored in + # temporal order. + traced_frame_infos: list[str] = [] + + +dynamo_tls = DynamoTLS() + + +def clear_dynamo_tls(): + dynamo_tls.traced_frame_infos.clear() + + +@atexit.register +def _log_traced_frames(): + """ + At program exit, log all of the frames Dynamo has attempted to trace from, + excluding the continuation frames generated by Dynamo. + """ + msg = "\n".join(dynamo_tls.traced_frame_infos) + msg = textwrap.indent(msg, " * ") + msg = f"TorchDynamo attempted to trace the following frames: [\n{msg}\n]" + log.info(msg) + + +class _TorchDynamoContext: + def __init__( + self, + callback: DynamoCallback, + on_enter=nothing, + backend_ctx_ctor=null_context, + patch_fn=nothing, + first_ctx=False, + *, + export=False, + dynamic=None, + compiler_config=None, + ) -> None: + super().__init__() + assert callable(callback) or callback is False or callback is None + self.callback: DynamoCallback = callback + self._backend_ctx_ctor = backend_ctx_ctor + self.prior: Union[Unset, DynamoCallback] = unset + self.first_ctx = first_ctx + self.export = export + self._dynamic = dynamic + self.compiler_config = compiler_config + self.cleanup_fns: list[Callable[[], Any]] = [] + self.enter_exit_hooks = [] + patch_fn() + + # Save the backends so that we can reset them during torch._dynamo.reset + backend = innermost_fn(callback) + cached_backends.setdefault(id(backend), backend) + + if dynamic is not None: + self.enter_exit_hooks.append(make_set_enable_dynamic(dynamic)) + + if on_enter is not nothing: + # this case is not common + def call_on_enter(): + on_enter() + return nothing + + self.enter_exit_hooks.append(call_on_enter) + + if backend_ctx_ctor is not contextlib.nullcontext: + # this case is not common + def call_backend_ctx(): + ctx = backend_ctx_ctor() + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_backend_ctx) + + def __enter__(self): + if config.raise_on_ctx_manager_usage: + raise RuntimeError( + "torch._dynamo.optimize(...) is used with a context manager. " + "Please refer to https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html " + "to use torch._dynamo.optimize(...) as an annotation/decorator. " + ) + self.prior = set_eval_frame(None) + self.cleanup_fns = [enter() for enter in self.enter_exit_hooks] + self.prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + + def __exit__(self, exc_type, exc_val, exc_tb): + assert self.prior is not unset + set_eval_frame(None) + set_skip_guard_eval_unsafe(self.prior_skip_guard_eval_unsafe) + for cleanup in self.cleanup_fns: + cleanup() + self.cleanup_fns.clear() + _maybe_set_eval_frame(_callback_from_stance(self.prior)) + self.prior = unset + + def __call__(self, fn): + # public api for compiler config/options + def get_compiler_config(): + return self.compiler_config + + fn = innermost_fn(fn) + + # add context containing GraphModule to any GraphModule forward functions + if isinstance(fn, GraphModule): + # add context containing GraphModule to any GraphModule forward functions + code_context.get_context(fn.forward.__code__)["orig_graphmodule"] = ( + weakref.ref(fn) + ) + + # Optimize the forward method of torch.nn.Module object + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + # Save the function pointer to find the original callable while nesting + # of decorators. + new_mod._torchdynamo_orig_callable = mod.forward + + # when compiling torch.nn.Module, + # provide public api OptimizedModule.get_compiler_config() + assert not hasattr(new_mod, "get_compiler_config") + new_mod.get_compiler_config = get_compiler_config + + return new_mod + + if inspect.isclass(fn): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + assert callable(fn) + + try: + filename = inspect.getsourcefile(fn) + except TypeError: + filename = None + if ( + (filename is None or trace_rules.check(fn)) + and ( + getattr(fn, "__name__", "") + not in ["_call_impl", "_wrapped_call_impl", "_lazy_forward"] + ) + and filename not in DONT_WRAP_FILES + ): + # call to a builtin without a frame for us to capture + fn = external_utils.wrap_inline(fn) + + def do_nothing(*arg, **kwargs): + pass + + if hasattr(self, "callback"): + callback = self.callback + else: + callback = do_nothing + + is_jit_tracing = torch._C._is_tracing + is_fx_tracing = torch.fx._symbolic_trace.is_fx_tracing + + @functools.wraps(fn) + def _fn(*args, **kwargs): + prior = set_eval_frame(None) + try: + if is_fx_tracing(): + if config.error_on_nested_fx_trace: + raise RuntimeError( + "Detected that you are using FX to symbolically trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + else: + return fn(*args, **kwargs) + + if is_jit_tracing(): + raise RuntimeError( + "Detected that you are using FX to torch.jit.trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + + cleanups = [enter() for enter in self.enter_exit_hooks] + prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + + # Ensure that if an assertion occurs after graph pushes + # something onto the DynamicLayerStack then we pop it off (the + # constructed graph code isn't guarded with try/finally). + # + # This used to be a context but putting a `with` here is a noticible + # perf regression (#126293) + saved_dynamic_layer_stack_depth = ( + torch._C._functorch.get_dynamic_layer_stack_depth() + ) + _maybe_set_eval_frame(_callback_from_stance(callback)) + + try: + return fn(*args, **kwargs) + except Unsupported as e: + if config.verbose: + raise + raise e.with_traceback(None) from None + except ShortenTraceback as e: + # Failures in the backend likely don't have useful + # data in the TorchDynamo frames, so we strip them out. + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + finally: + # Restore the dynamic layer stack depth if necessary. + set_eval_frame(None) + torch._C._functorch.pop_dynamic_layer_stack_and_undo_to_depth( + saved_dynamic_layer_stack_depth + ) + + set_skip_guard_eval_unsafe(prior_skip_guard_eval_unsafe) + for cleanup in cleanups: + cleanup() + finally: + _maybe_set_eval_frame(prior) + + # hooks to properly handle inlining + _fn._torchdynamo_inline = fn # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + + # when compiling user function instead of nn.Module + # provide public api _fn.get_compiler_config() + assert not hasattr(_fn, "get_compiler_config") + _fn.get_compiler_config = get_compiler_config # type: ignore[attr-defined] + + # If the function is called using torch._dynamo.optimize decorator, we + # should prevent any type of skipping. + if callback not in (None, False): + if not hasattr(fn, "__code__"): + raise RuntimeError( + textwrap.dedent( + """ + + torch._dynamo.optimize is called on a non function object. + If this is a callable class, please wrap the relevant code into a function and optimize the + wrapper function. + + >> class CallableClass: + >> def __init__(self) -> None: + >> super().__init__() + >> self.relu = torch.nn.ReLU() + >> + >> def __call__(self, x): + >> return self.relu(torch.sin(x)) + >> + >> def print_hello(self): + >> print("Hello world") + >> + >> mod = CallableClass() + + If you want to optimize the __call__ function and other code, wrap that up in a function + + >> def wrapper_fn(x): + >> y = mod(x) + >> return y.sum() + + and then optimize the wrapper_fn + + >> opt_wrapper_fn = torch._dynamo.optimize(wrapper_fn) + """ + ) + ) + always_optimize_code_objects[fn.__code__] = True + + return _fn + + +class OptimizeContext(_TorchDynamoContext): + def __init__( + self, + callback, + backend_ctx_ctor, + first_ctx=False, + *, + export=False, + dynamic=None, + compiler_config=None, + rebuild_ctx: Optional[ + Callable[[], Union[OptimizeContext, _NullDecorator]] + ] = None, + ) -> None: + def on_enter(): + install_generation_tagging_init() + + super().__init__( + callback=callback, + on_enter=on_enter, + backend_ctx_ctor=backend_ctx_ctor, + patch_fn=TorchPatcher.patch, + first_ctx=first_ctx, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + ) + + if config.compiled_autograd: + + def call_compiled_autograd(): + assert rebuild_ctx is not None + compiler_fn = rebuild_ctx() + ctx = torch._dynamo.compiled_autograd._enable( + compiler_fn, dynamic=self._dynamic + ) + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_compiled_autograd) + + def __reduce__(self): + return ( + self.__class__, + (self.callback, self._backend_ctx_ctor, self.first_ctx), + { + "export": self.export, + "dynamic": self._dynamic, + "compiler_config": self.compiler_config, + }, + ) + + +class RunOnlyContext(_TorchDynamoContext): + def __init__(self) -> None: + # cudagraph trees relies on generation increment + def on_enter(): + torch._dynamo.mutation_guard.GenerationTracker.generation += 1 + + super().__init__(callback=False, on_enter=on_enter) + + def __reduce__(self): + return (self.__class__, ()) + + +class DisableContext(_TorchDynamoContext): + def __init__(self) -> None: + super().__init__(callback=None) + + def __call__(self, fn): + # Earlier this code was in the base class _TorchDynamoContext. But we + # moved it here to have better code organization. For disable, we just + # want the callback to be None. We don't have to check trace_rules or + # create any wrapper. + fn = innermost_fn(fn) + + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + new_mod._torchdynamo_orig_callable = mod.forward + return new_mod + + if inspect.isclass(fn): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + # Disable on init is useful for reconstruction of bytecodes where we + # want to prevent Dynamo from tracing into the init function. Check + # test_reconstruction in test_model_output.py. + cls_obj.__init__ = self(cls_obj.__init__) + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. Disable it. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + assert callable(fn) + + @functools.wraps(fn) + def _fn(*args, **kwargs): + prior = set_eval_frame(None) + try: + prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + try: + return fn(*args, **kwargs) + finally: + set_eval_frame(None) + set_skip_guard_eval_unsafe(prior_skip_guard_eval_unsafe) + finally: + _maybe_set_eval_frame(prior) + + _fn._torchdynamo_disable = True # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + + return _fn + + def __reduce__(self): + return (self.__class__, ()) + + +def _optimize_catch_errors( + compile_fn, + hooks: Hooks, + backend_ctx_ctor=null_context, + export=False, + dynamic=None, + compiler_config=None, + rebuild_ctx=None, +): + return OptimizeContext( + convert_frame.catch_errors_wrapper(compile_fn, hooks), + backend_ctx_ctor=backend_ctx_ctor, + first_ctx=True, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + rebuild_ctx=rebuild_ctx, + ) + + +def get_compiler_fn(compiler_fn): + from .repro.after_dynamo import wrap_backend_debug + + if hasattr(compiler_fn, "compiler_name"): + compiler_str = compiler_fn.compiler_name + elif isinstance(compiler_fn, str): + compiler_str = compiler_fn + else: + compiler_str = None + compiler_fn = lookup_backend(compiler_fn) + return wrap_backend_debug(compiler_fn, compiler_str) + + +class _NullDecorator(contextlib.nullcontext): # type: ignore[type-arg] + def __call__(self, fn): + assert callable(fn) + return fn + + +def check_if_dynamo_supported(): + if sys.version_info >= (3, 14): + raise RuntimeError("Python 3.14+ not yet supported for torch.compile") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1: + raise RuntimeError( + "torch.compile is not supported on Python built with GIL disabled" + ) + + +def is_dynamo_supported(): + try: + check_if_dynamo_supported() + return True + except Exception: + return False + + +def check_if_inductor_supported(): + check_if_dynamo_supported() + + +def is_inductor_supported(): + try: + check_if_inductor_supported() + return True + except Exception: + return False + + +def check_for_incompatible_configs(): + # Some of the configs should be mutually exclusive + assert not (config.suppress_errors and config.fail_on_recompile_limit_hit), ( + "Dynamo configs suppress_error and fail_on_recompile_limit_hit can not both be active at the same time." + ) + + +def optimize(*args, **kwargs): + def rebuild_ctx(): + ca_kwargs_override = config.compiled_autograd_kwargs_override + if ca_kwargs_override: + # NOTE: The process of translating other `torch.compile` kwargs to `torch._dynamo.optimize` kwargs + # is more complicated, we will add it in the future when needed. + assert set(ca_kwargs_override.keys()) == {"fullgraph"}, ( + f"Only `fullgraph` kwarg override is supported for now, but got {ca_kwargs_override.keys()}" + ) + kwargs["nopython"] = ca_kwargs_override["fullgraph"] + return optimize(*args, **kwargs) + + return _optimize(rebuild_ctx, *args, **kwargs) + + +def _optimize( + rebuild_ctx: Callable[[], Union[OptimizeContext, _NullDecorator]], + backend="inductor", + *, + nopython=False, + guard_export_fn=None, + guard_fail_fn=None, + disable=False, + dynamic=None, +) -> Union[OptimizeContext, _NullDecorator]: + """ + The main entrypoint of TorchDynamo. Do graph capture and call + backend() to optimize extracted graphs. + + Args: + backend: One of the two things: + - Either, a function/callable taking a torch.fx.GraphModule and + example_inputs and returning a python callable that runs the + graph faster. + One can also provide additional context for the backend, like + torch.jit.fuser("fuser2"), by setting the backend_ctx_ctor attribute. + See AOTAutogradMemoryEfficientFusionWithContext for the usage. + - Or, a string backend name in `torch._dynamo.list_backends()` + nopython: If True, graph breaks will be errors and there will + be a single whole-program graph. + disable: If True, turn this decorator into a no-op + dynamic: If True, upfront compile as dynamic a kernel as possible. If False, + disable all dynamic shapes support (always specialize). If None, automatically + detect when sizes vary and generate dynamic kernels upon recompile. + + Example Usage:: + + @torch._dynamo.optimize() + def toy_example(a, b): ... + """ + check_if_dynamo_supported() + check_for_incompatible_configs() + # Note: The hooks object could be global instead of passed around, *however* that would make + # for a confusing API usage and plumbing story wherein we nest multiple .optimize calls. + # There is some prior art around this, w/r/t nesting backend calls are enforced to be the same + # compiler, however, this feels onerous for callback and hooks, and it feels better to give our users an + # easier to understand UX at the cost of a little more plumbing on our end. + hooks = Hooks(guard_export_fn=guard_export_fn, guard_fail_fn=guard_fail_fn) + torch._C._log_api_usage_once("torch._dynamo.optimize") + if ( + disable + or os.environ.get("TORCHDYNAMO_DISABLE", "") == "1" + or (not justknobs_check("pytorch/compiler:enable_dynamo")) + ): + return _NullDecorator() + + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + if nopython: + return optimize_assert( + backend, + dynamic=dynamic, + hooks=hooks, + rebuild_ctx=rebuild_ctx, + ) + # The backend function is stashed in the callable returned by + # _optimize_catch_errors in the field _torchdynamo_orig_callable. This can + # be used by eval_frame.c to insert a guard on the backend. + return _optimize_catch_errors( + convert_frame.convert_frame(backend, hooks=hooks), + hooks, + backend_ctx_ctor, + dynamic=dynamic, + compiler_config=( + backend.get_compiler_config() + if hasattr(backend, "get_compiler_config") + else None + ), + rebuild_ctx=rebuild_ctx, + ) + + +# TODO(voz): Consider making "explain" output alongside a run / part of a run +@patch("torch._dynamo.symbolic_convert.explain", True) +def explain(f, *extra_args, **extra_kwargs): + def inner(*args, **kwargs): + # TODO(voz): Do we want a decorator for this? + from . import reset # type: ignore[attr-defined] + + reset() + + graphs: list[torch.fx.GraphModule] = [] + break_reasons: list[Any] = [] + op_count: int = 0 + ops_per_graph: list[torch.fx.Node] = [] + out_guards: list[_guards.Guard] = [] + + def dynamo_graph_accumulating_compiler( + gm: torch.fx.GraphModule, example_inputs + ): + from .backends.debugging import _explain_graph_detail + + nonlocal graphs + nonlocal op_count + nonlocal ops_per_graph + nonlocal break_reasons + + gm, graphs, op_count, ops_per_graph, break_reasons = _explain_graph_detail( + gm, graphs, op_count, ops_per_graph, break_reasons + ) + + return gm.forward + + def guard_export_print(guards): + nonlocal out_guards + out_guards.extend(guards) + + opt_f = optimize( + dynamo_graph_accumulating_compiler, + nopython=False, + guard_export_fn=guard_export_print, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + opt_f(*args, **kwargs) + + graph_count = len(graphs) + graph_break_count = graph_count - 1 + compile_time = compile_times(repr="str") + + # TODO(voz): Do we want a decorator for this? + reset() + from .backends.debugging import ExplainOutput + + return ExplainOutput( + graphs, + graph_count, + graph_break_count, + break_reasons, + op_count, + ops_per_graph, + out_guards, + compile_time, + ) + + if extra_args or extra_kwargs: + warnings.warn( + "explain(f, *args, **kwargs) is deprecated, use explain(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your explain call in the future if your user defined kwargs " + "conflict with future kwargs added to explain(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) + else: + return inner + + +class FlattenInputOutputSignature(torch.fx.Transformer): + def __init__( + self, + m: torch.fx.GraphModule, + flat_args: tuple[Any], + matched_input_elements_positions: list[int], + flat_results: list[Any], + matched_output_elements_positions: list[int], + example_fake_inputs: list[torch.Tensor], + flat_args_dynamic_dims: list[set[int]], + fake_mode: Optional[fake_tensor.FakeTensorMode] = None, + ) -> None: + super().__init__(m) + + assert len(flat_args_dynamic_dims) == len(flat_args) + matched_input_elements_to_fake = { + val: example_fake_inputs[ix] + for ix, val in enumerate(matched_input_elements_positions) + } + + self.new_args = [] + for i in range(0, len(flat_args)): + arg = super().placeholder(f"arg{i}", (), {}) + if i in matched_input_elements_to_fake: + arg.node.meta["val"] = matched_input_elements_to_fake[i] + else: + # Fill node.mata["val"] with faketensor from the input, + # if it's not found in matched_input_elements_positions + if fake_mode is not None and isinstance(flat_args[i], torch.Tensor): + # TODO(zhxchen17) Also preserve all the user constraints here. + arg.node.meta["val"] = fake_mode.from_tensor( + flat_args[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(flat_args[i].shape)) + ], + constraint_sizes=[None] * len(flat_args[i].shape), + ), + ) + self.new_args.append(arg) + self.old_args_gen = (self.new_args[i] for i in matched_input_elements_positions) + self.matched_output_elements_positions = matched_output_elements_positions + self.flat_results = flat_results + + def placeholder(self, target, args, kwargs): + arg = next(self.old_args_gen) + if "val" in self.current_node.meta: + arg.node.meta["val"] = self.current_node.meta["val"] + if "tensor_dict" in self.current_node.meta: + arg.node.meta["tensor_dict"] = self.current_node.meta["tensor_dict"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + arg.node.meta["example_value"] = self.current_node.meta["example_value"] + if "unbacked_bindings" in self.current_node.meta: + arg.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + return arg + + def output(self, target, args, kwargs): + dynamo_result_flat = args[0] + lookup = [*dynamo_result_flat, *self.new_args] + new_results_flat = [] + for i in range(len(self.flat_results)): + if self.matched_output_elements_positions[i] is not None: + new_results_flat.append( + lookup[self.matched_output_elements_positions[i]] + ) + else: + const_val = self.flat_results[i] + assert isinstance(const_val, tuple(common_constant_types)) + new_results_flat.append(const_val) + return super().output(target, (new_results_flat,), {}) + + def run_node(self, n): + self.current_node = n + result_proxy = super().run_node(n) + if "val" in self.current_node.meta: + result_proxy.node.meta["val"] = self.current_node.meta["val"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + result_proxy.node.meta["example_value"] = self.current_node.meta[ + "example_value" + ] + if "unbacked_bindings" in self.current_node.meta: + result_proxy.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + if self.current_node.op != "output": + result_proxy.node._rename( + getattr(self.current_node, "name", result_proxy.node.name) + ) + return result_proxy + + def transform(self): + result_gm = super().transform() + if "dynamo_flat_name_to_original_fqn" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ # type: ignore[index] + "dynamo_flat_name_to_original_fqn" # type: ignore[index] + ] + if "dynamo_compile_id" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_compile_id"] = self.module.meta["dynamo_compile_id"] # type: ignore[index] + return result_gm + + +class ExportResult(NamedTuple): + graph_module: torch.fx.GraphModule + guards: _guards.GuardsSet + # NB: Do not add new fields without overriding __iter__; people are + # destructuring so it is BC-breaking + + +# NOTE: this function only supports graphs created by Dynamo's OutputGraph module +def check_signature_rewritable(graph): + input_errors = [] + for node in graph.graph.find_nodes(op="placeholder"): + # set in OutputGraph._call_user_compiler + assert hasattr(node, "_dynamo_source") + assert hasattr(graph, "_source_to_user_stacks") + + source = node._dynamo_source + user_stacks = graph._source_to_user_stacks.get(source) + if user_stacks is None: + continue + assert len(user_stacks) > 0 + # In some cases we may not have a useful stack. Look for a + # useful stack + stack = None + for s in user_stacks: + if len(s) == 0: + continue + stack = s + break + if stack is None: + msg = f"{source.name()}, a closed over free variable" + else: + tb = "".join(traceback.format_list(stack)) + extra = "" + if len(user_stacks) > 1: + extra = f"(elided {len(user_stacks) - 1} more accesses)" + msg = f"{source.name()}, accessed at:\n{tb}{extra}" + # TODO: option to print ALL of the stack traces at once + input_errors.append(msg) + + if input_errors: + raise UserError( + UserErrorType.INVALID_INPUT, + "Cannot export model which references tensors that are neither " + "buffers/parameters/constants nor are direct inputs. For each tensor, if you'd " + "like this tensor to be an explicit input, add it as a dummy argument " + "to the top-level model definition you are exporting; if you would " + "like its value to be embedded as an exported constant, wrap its access " + "in a function marked with @assume_constant_result.\n\n" + + "\n\n".join(input_errors), + ) + + +def rewrite_signature( + f_sig, + graph, + fake_mode, + flat_args, + in_spec, + example_fake_inputs, + graph_captured_input, + graph_captured_output, + dynamo_traced_result, + flat_args_dynamic_dims, +): + orig_args, orig_kwargs = pytree.tree_unflatten(flat_args, in_spec) + + def check_user_input_output(flat_values, error_type): + supported_types = [ + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + torch._C.ScriptObject, + ] + list(common_constant_types) + + def is_supported_type(val): + return isinstance(val, tuple(supported_types)) + + value_type = "input" if error_type == UserErrorType.INVALID_INPUT else "output" + # We only check that the outputs are not None. Inputs can be None. + for v in flat_values: + if not is_supported_type(v): + if error_type == UserErrorType.INVALID_INPUT and v is None: + continue + + raise UserError( + error_type, + f"It looks like one of the {value_type}s with type `{type(v)}` " + "is not supported or pytree-flattenable. \n" + f"Exported graphs {value_type}s can only contain the " + f"following supported types: {supported_types}. \n" + "If you are using a custom class object, " + "please register a pytree_flatten/unflatten function " + "using `torch.utils._pytree.register_pytree_node` or " + "`torch.export.register_dataclass`.", + ) + + check_user_input_output(flat_args, UserErrorType.INVALID_INPUT) + flat_results_traced, out_spec_traced = pytree.tree_flatten(dynamo_traced_result) + check_user_input_output(flat_results_traced, UserErrorType.INVALID_OUTPUT) + + def check_optional_input_and_error(f_sig: inspect.Signature): + # Check if function has optional input. + for name, param in f_sig.parameters.items(): + if param.default is not inspect.Parameter.empty: + from torch._dynamo.exc import Unsupported + + log.error( + "Parameter %s is optional with a default value of %s", + name, + param.default, + ) + raise Unsupported( + "Tracing through optional input is not supported yet", + case_name="optional_input", + ) + + def produce_matching(debug_type, sources, candidates): + matched_elements_positions: list[Optional[int]] = [] + dict_of_source_vals = {} + for i, val in enumerate(sources): + dict_of_source_vals[id(val)] = i + + for i, val in enumerate(candidates): + if isinstance(val, tuple(common_constant_types)): + matched_elements_positions.append(None) + elif id(val) not in dict_of_source_vals: + if debug_type == "inputs": + check_optional_input_and_error(f_sig) + raise AssertionError( + f"Unexpectedly found a {type(val)} in the {debug_type}.\n" + 'Please file an issue along with a paste of the logs from TORCH_LOGS="+export"', + ) + else: + matched_elements_positions.append(dict_of_source_vals[id(val)]) + + return matched_elements_positions + + matched_input_elements_positions = produce_matching( + "inputs", flat_args, graph_captured_input + ) + + assert graph_captured_output is not None + matched_output_elements_positions = produce_matching( + "outputs", list(graph_captured_output) + flat_args, flat_results_traced + ) + + new_graph = FlattenInputOutputSignature( + graph, + flat_args, + matched_input_elements_positions, + flat_results_traced, + matched_output_elements_positions, + example_fake_inputs, + flat_args_dynamic_dims, + fake_mode, + ).transform() + + # Make dynamo graph to have same input/output spec as user code + def argument_names(f_sig, args, kwargs) -> list[str]: + def signature_to_fullargspec(sig: inspect.Signature): + # Get a list of Parameter objects from the Signature object + params = list(sig.parameters.values()) + # Separate positional arguments, keyword-only arguments and varargs/varkw + args = [ + p.name + for p in params + if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwonlyargs = [ + p.name for p in params if p.kind == inspect.Parameter.KEYWORD_ONLY + ] + varargs = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_POSITIONAL), + None, + ) + varkw = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_KEYWORD), + None, + ) + # Get default values for positional arguments and keyword-only arguments + defaults = tuple( + p.default + for p in params + if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and p.default is not inspect.Parameter.empty + ) + kwonlydefaults = { + p.name: p.default + for p in params + if p.kind == inspect.Parameter.KEYWORD_ONLY + and p.default is not inspect.Parameter.empty + } + # Get annotations for parameters and return value + annotations = {} + if sig.return_annotation: + annotations = {"return": sig.return_annotation} + for parameter in params: + annotations[parameter.name] = parameter.annotation + # Return a FullArgSpec object with the extracted attributes + return inspect.FullArgSpec( + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations + ) + + fullargspec = signature_to_fullargspec(f_sig) + + # 1. Map `args` 1-to-1 to positional arguments in original signature. + input_strs = fullargspec.args[: len(args)] + + if len(args) > len(fullargspec.args): + # 2. If there are more arguments left in `args`, they map to varargs in original + # signature. Assign names as {varargs}_0, {varargs}_1, ... + assert fullargspec.varargs is not None, "More arguments than expected" + input_strs += [ + f"{fullargspec.varargs}_{i}" + for i in range(0, len(args) - len(input_strs)) + ] + elif len(args) < len(fullargspec.args): + # 3. If there are fewer arguments in `args` than `fullargspec.args`, + # it implies these are arguments either with default values, or provided in + # `kwargs`. The former can be safely ignored. Because Dynamo.export does not + # export them as part of the function signature. The latter will be handled + # in the next step. + for unprovided_arg in fullargspec.args[ + len(args) : -len(fullargspec.defaults or []) + ]: + assert unprovided_arg in kwargs, f"Missing argument {unprovided_arg}" + + # 4. Keyword arguments provided in `kwargs`. + input_strs += list(kwargs.keys()) + + # 5. Keyword-only arguments with default values if not provided are not exported + # as part of the function signature. + for kwonly_arg in fullargspec.kwonlyargs: + kwonlydefaults = fullargspec.kwonlydefaults or {} + assert kwonly_arg in kwargs or kwonly_arg in kwonlydefaults, ( + f"Missing keyword only argument {kwonly_arg}" + ) + + return input_strs + + new_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(f_sig, orig_args, orig_kwargs), + in_spec, + out_spec_traced, + ) + ) + new_graph.recompile() + return new_graph + + +def export( + f: Callable[..., Any], + *extra_args, + aten_graph: bool = False, + pre_dispatch: bool = False, + decomposition_table: Optional[ + dict[torch._ops.OpOverload, Callable[..., Any]] + ] = None, + tracing_mode: str = "symbolic", + dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]] = None, + specialize_float: bool = True, + assume_static_by_default: bool = False, + same_signature: bool = True, + disable_constraint_solver: bool = False, + prefer_deferred_runtime_asserts_over_guards: bool = False, + allow_complex_guards_as_runtime_asserts: bool = False, + _log_export_usage: bool = True, + **extra_kwargs, +) -> Callable[..., ExportResult]: + """ + Export an input function f to a format that can be executed outside of PyTorch using the FX graph. + + Args: + f (callable): A PyTorch function to be exported. + + aten_graph (bool): If True, exports a graph with ATen operators. + If False, exports a graph with Python operators. Default is False. + + pre_dispatch (bool): If True, exports a graph with ATen operators, + but before any logic in the PyTorch dispatcher has run. + This can be useful if you want to apply further transformations on a graph before running it + through autograd, autocast, or any other functionalities that are integrated into the dispatcher. + This flag is only valid if aten_graph=True is set. + Default is False. + + decomposition_table (dict): A dictionary that maps operators to their decomposition functions. + Required if aten_graph or tracing_mode is specified. Default is None. + + tracing_mode (str): If "symbolic", turn on dynamic shapes support. Default is "symbolic". + + dynamic_shapes: + An optional argument where the type should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + same_signature (bool): If True, rewrite the returned graph's signature to be the same as f. + + disable_constraint_solver (bool): Whether the dim constraint solver must be disabled. + + Returns: + A function that given args and kwargs, returns a tuple of (graph, guards) + Graph: An FX graph representing the execution of the input PyTorch function with the provided arguments and options. + Guards: The guards we accumulated during tracing f above + + Raises: + AssertionError: If decomposition_table is specified without setting aten_graph=True, + or if graph breaks during tracing in export. + + AssertionError: If Dynamo input and output is not consistent with traced input/output. + + Note - this headerdoc was authored by ChatGPT, with slight modifications by the author. + """ + if _log_export_usage: + log_export_usage(event="export.private_api", flags={"_dynamo"}) + + # Deal with "local variable referenced before assignment" + _f = f + _specialize_float = specialize_float + _assume_static_by_default = assume_static_by_default + + def inner(*args, **kwargs): + combined_args = _combine_args(_f, args, kwargs) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + f = _f + specialize_float = _specialize_float + assume_static_by_default = _assume_static_by_default + check_if_dynamo_supported() + torch._C._log_api_usage_once("torch._dynamo.export") + if decomposition_table is not None: + assert aten_graph, ( + "Specifying a decomposition_table table or tracing mode is illegal without setting aten_graph=True" + ) + if pre_dispatch: + assert aten_graph, "pre_dispatch=True can only be used when aten_graph=True" + f = innermost_fn(f) + call_to_inspect = f.forward if isinstance(f, torch.nn.Module) else f + original_signature = inspect.signature(call_to_inspect) + graph = None + out_guards = None + graph_captured_input = None + graph_captured_result: Optional[tuple[torch.Tensor, ...]] = None + fake_mode = None + result_traced = None + + def guard_export_print(guards: _guards.GuardsSet): + nonlocal out_guards + assert out_guards is None, ( + "whole graph export entails exactly one guard export" + ) + out_guards = guards + + example_inputs = [] + + def dynamo_normalization_capturing_compiler( + gm: torch.fx.GraphModule, inner_example_inputs + ): + nonlocal graph + assert graph is None, ( + "Tried to emit a second graph during export. Tracing through 'f' must produce a single graph." + ) + graph = gm + + nonlocal fake_mode, example_inputs + # NB: do NOT pass inner_example_inputs here, we are detecting the + # Dynamo allocated fake mode, which should be DISTINCT from a + # potential outer ambient fake mode which the user provided. + # example_inputs is always the user specified inputs, so they + # would have the wrong fake mode attached to them + fake_mode = _guards.detect_fake_mode() + example_inputs = inner_example_inputs + + def result_capturing_wrapper(*graph_inputs): + nonlocal graph_captured_result + nonlocal graph_captured_input + + graph_captured_input = graph_inputs + assert graph is not None + + named_parameters = dict(graph.named_parameters(remove_duplicate=False)) + named_buffers = dict(graph.named_buffers(remove_duplicate=False)) + + ambient_fake_mode = ( + _guards.detect_fake_mode(graph_inputs) + if _guards.detect_fake_mode(graph_inputs) is not None + else fake_mode + ) + + # We reran fake tensor propagation, but we didn't do + # anything with the resulting unbacked SymInts. Drop them + # from the pending list. + # NB: this is wrong if graph_captured_result has + # data-dependent output size! + ignore_fresh_unbacked = null_context() + assert ambient_fake_mode is not None + if shape_env := ambient_fake_mode.shape_env: + ignore_fresh_unbacked = shape_env.ignore_fresh_unbacked_symbols() + + with ( + ambient_fake_mode, + enable_python_dispatcher(), + ignore_fresh_unbacked, + ): + params_and_buffers = { + **named_parameters, + **named_buffers, + } + fake_params_buffers = {} + + for name, value in params_and_buffers.items(): + fake_params_buffers[name] = ambient_fake_mode.from_tensor( + value, static_shapes=True + ) + + fake_graph_inputs = pytree.tree_map( + ambient_fake_mode.from_tensor, graph_inputs + ) + graph_captured_result = torch.func.functional_call( + graph, fake_params_buffers, fake_graph_inputs + ) + + return graph_captured_result + + return result_capturing_wrapper + + # Note: This is needed by rewrite_signature. We need to put it before + # optimize_assert since user program may mutate the inputs. + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + remove_from_cache(f) + constraint_violation_error = None + if tracing_mode != "symbolic": + assume_static_by_default = True + with config.patch( + specialize_int=True, + specialize_float=specialize_float, + assume_static_by_default=assume_static_by_default, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + allow_complex_guards_as_runtime_asserts=allow_complex_guards_as_runtime_asserts, + ): + opt_f = optimize_assert( + dynamo_normalization_capturing_compiler, + hooks=Hooks( + guard_export_fn=guard_export_print, + guard_fail_fn=None, + ), + export=True, + export_constraints=constraints, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + try: + result_traced = opt_f(*args, **kwargs) + except ConstraintViolationError as e: + constraint_violation_error = e + remove_from_cache(f) + + if ( + not disable_constraint_solver + and (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + call_to_inspect, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + and not trace_rules.check(call_to_inspect) + ): + dim_constraints.solve() + forced_specializations = dim_constraints.forced_specializations() + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + for k in shape_env.var_to_range.keys(): + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + raise constraint_violation_error + + if graph is None: + assert same_signature, ( + "Failed to produce a graph during tracing as no tensor operations were found and same_signature is False." + ) + # If the module does not contain any tensor computation, we would create a graph with inputs and outputs. + # To be consitant with the graph traced by dynano, `graph` will have only tensor inputs as placeholders + # and tensor outputs as output nodes. non-tensor inputs and outputs will be added when rewriting signature. + # We will also construct the `example_inputs`, `graph_captured_input`, and `graph_captured_result` corresponding + # to `graph`. + example_inputs = [] + graph_captured_input = () + graph_captured_result = () + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=ShapeEnv(), export=True + ) + if out_guards is None: + out_guards = _guards.GuardsSet() + assert out_guards is not None # suppress mypy error + parameter_names = list(original_signature.parameters.keys()) + fx_graph = torch.fx.Graph() + for i, name in enumerate(parameter_names): + if torch.is_tensor(flat_args[i]): + node = fx_graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor( + flat_args[i], static_shapes=True + ) + graph_captured_input = graph_captured_input + (flat_args[i],) + example_inputs.append(flat_args[i]) + fx_graph.output(graph_captured_result) + module = torch.nn.Module() + graph = torch.fx.GraphModule(module, fx_graph) + log.info( + "Failed to capture a graph during tracing as no tensor operations were found.:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + else: + assert out_guards is not None, "Failed to produce guards during tracing" + assert fake_mode is not None + + log.info( + "Dynamo captured graph:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + + # This check need to happened before aten_graph + # because placeholder's _source_node attribute is not preserved by make_fx + if same_signature: + check_signature_rewritable(graph) + + # NB: This is mostly hitting the cache; Dynamo already converted these + example_fake_inputs = [fake_mode.from_tensor(t) for t in example_inputs] + + if aten_graph: + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args): + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(graph).run(*args) # type: ignore[arg-type] + + with unset_fake_temporarily(), enable_python_dispatcher(), fake_mode: + try: + graph = make_fx( + graph_with_interpreter, + decomposition_table=decomposition_table, + tracing_mode="real", + _allow_non_fake_inputs=True, + pre_dispatch=pre_dispatch, + _allow_fake_constant=False, + )(*example_fake_inputs) + except CondOpArgsMismatchError as e: + # Wrap the internal error to the user-facing error + raise UserError( # noqa: B904 + UserErrorType.DYNAMIC_CONTROL_FLOW, + str(e), + case_name="cond_operands", + ) + + assert graph is not None + for node in graph.graph.find_nodes(op="get_attr"): + if isinstance(getattr(graph, node.target), torch.Tensor): # type: ignore[arg-type] + node.meta["val"] = fake_mode.from_tensor( + getattr(graph, node.target), # type: ignore[arg-type] + static_shapes=True, + ) + + if same_signature: + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_args + ] + graph = rewrite_signature( + original_signature, + graph, + fake_mode, + flat_args, + in_spec, + example_fake_inputs, + graph_captured_input, + graph_captured_result, + result_traced, # type: ignore[possibly-undefined] + flat_args_dynamic_dims, + ) + return ExportResult(graph, out_guards) # type: ignore[arg-type] + + if extra_args or extra_kwargs: + warnings.warn( + "export(f, *args, **kwargs) is deprecated, use export(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your export call in the future if your user defined kwargs " + "conflict with future kwargs added to export(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) + else: + return inner + + +def optimize_assert( + backend, + *, + hooks=Hooks(None, None), + export=False, + export_constraints=None, + dynamic=None, + rebuild_ctx=None, +): + """ + The same as `torch._dynamo.optimize(backend, nopython=True)` + """ + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + return _optimize_catch_errors( + convert_frame.convert_frame_assert( + backend, export=export, export_constraints=export_constraints + ), + hooks, + backend_ctx_ctor, + export=export, + dynamic=dynamic, + rebuild_ctx=rebuild_ctx, + ) + + +class TorchPatcher: + @staticmethod + @functools.lru_cache(None) + def patch(): + # A better way to disable the following would be decorate the source + # functions with @torch._disable_dynamo. However, this causes issues + # with torch.deploy internally. + from .decorators import disable + + torch.jit.trace = disable(torch.jit.trace) + torch.jit.trace_module = disable(torch.jit.trace_module) + torch.jit._get_trace_graph = disable(torch.jit._get_trace_graph) + torch.fx._symbolic_trace.Tracer.trace = disable( + torch.fx._symbolic_trace.Tracer.trace + ) + torch.distributions.Distribution.set_default_validate_args(False) + + from torch.optim import ( + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + ) + + optimizer_modules = { + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + } + + for opt_mod in optimizer_modules: + opt_name = opt_mod.__name__.split(".")[-1] + fused_fn_name = f"_fused_{opt_name}" + + if hasattr(opt_mod, fused_fn_name): + setattr( + opt_mod, fused_fn_name, disable(getattr(opt_mod, fused_fn_name)) + ) + + optimizer_classes = [ + opt + for opt in torch.optim.__dict__.values() + if inspect.isclass(opt) and issubclass(opt, torch.optim.Optimizer) + ] + + # Note: we don't support sparsity or tracing through backwards + excluded_optimizer_classes = { + torch.optim.SparseAdam, + torch.optim.LBFGS, + } + + for opt in optimizer_classes: + if opt in excluded_optimizer_classes: + opt.step = disable(opt.step) + + if hasattr(opt, "_init_group"): + opt._init_group = disable(opt._init_group) + + @staticmethod + def suppress_torch_distributed_warnings(fn): + def inner_fn(*args, **kwargs): + warnings.filterwarnings( + "ignore", category=UserWarning, module="torch.distributed" + ) + return fn(*args, **kwargs) + + return inner_fn + + +def skip_code(code: types.CodeType): + set_code_exec_strategy( + code, FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) diff --git a/shared/package-files/ef/ef455ce3dcb02df719e8898f5e6e0753fa893c18ca711b0ae2a6bbb63f8f6e36/_distributor_init.cpython-311.pyc b/shared/package-files/ef/ef455ce3dcb02df719e8898f5e6e0753fa893c18ca711b0ae2a6bbb63f8f6e36/_distributor_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b082595b9fb482ba9b7b7438e886735c90bca5a Binary files /dev/null and b/shared/package-files/ef/ef455ce3dcb02df719e8898f5e6e0753fa893c18ca711b0ae2a6bbb63f8f6e36/_distributor_init.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef480001c142958bede2a1c874238838bf0a852fe94bff077132b91397c564c4/__init__.cpython-311.pyc b/shared/package-files/ef/ef480001c142958bede2a1c874238838bf0a852fe94bff077132b91397c564c4/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cbccc91e915252d5f8f6c0d4f44a94bd50330e2 Binary files /dev/null and b/shared/package-files/ef/ef480001c142958bede2a1c874238838bf0a852fe94bff077132b91397c564c4/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef4a58028fd5e527f1e49bde587c41cfb657840da98b863f76dbc3db3454ccee/__init__.cpython-311.pyc b/shared/package-files/ef/ef4a58028fd5e527f1e49bde587c41cfb657840da98b863f76dbc3db3454ccee/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4463e8e3c1f2dce461a96f02bcbdd579e3c17bc5 Binary files /dev/null and b/shared/package-files/ef/ef4a58028fd5e527f1e49bde587c41cfb657840da98b863f76dbc3db3454ccee/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef4fc079d329afe6318980c71e3c3a7e3be6616efe628ce7106c14786b49a341/test_perm_groups.py b/shared/package-files/ef/ef4fc079d329afe6318980c71e3c3a7e3be6616efe628ce7106c14786b49a341/test_perm_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..763b8fb0ae357500d68c29fe1c9e6b156e224949 --- /dev/null +++ b/shared/package-files/ef/ef4fc079d329afe6318980c71e3c3a7e3be6616efe628ce7106c14786b49a341/test_perm_groups.py @@ -0,0 +1,1243 @@ +from sympy.core.containers import Tuple +from sympy.combinatorics.generators import rubik_cube_generators +from sympy.combinatorics.homomorphisms import is_isomorphic +from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup,\ + DihedralGroup, AlternatingGroup, AbelianGroup, RubikGroup +from sympy.combinatorics.perm_groups import (PermutationGroup, + _orbit_transversal, Coset, SymmetricPermutationGroup) +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.polyhedron import tetrahedron as Tetra, cube +from sympy.combinatorics.testutil import _verify_bsgs, _verify_centralizer,\ + _verify_normal_closure +from sympy.testing.pytest import skip, XFAIL, slow + +rmul = Permutation.rmul + + +def test_has(): + a = Permutation([1, 0]) + G = PermutationGroup([a]) + assert G.is_abelian + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + assert not G.is_abelian + + G = PermutationGroup([a]) + assert G.has(a) + assert not G.has(b) + + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([0, 2, 1, 3, 4]) + assert PermutationGroup(a, b).degree == \ + PermutationGroup(a, b).degree == 6 + + g = PermutationGroup(Permutation(0, 2, 1)) + assert Tuple(1, g).has(g) + + +def test_generate(): + a = Permutation([1, 0]) + g = list(PermutationGroup([a]).generate()) + assert g == [Permutation([0, 1]), Permutation([1, 0])] + assert len(list(PermutationGroup(Permutation((0, 1))).generate())) == 1 + g = PermutationGroup([a]).generate(method='dimino') + assert list(g) == [Permutation([0, 1]), Permutation([1, 0])] + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + g = G.generate() + v1 = [p.array_form for p in list(g)] + v1.sort() + assert v1 == [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, + 1], [2, 1, 0]] + v2 = list(G.generate(method='dimino', af=True)) + assert v1 == sorted(v2) + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + g = PermutationGroup([a, b]).generate(af=True) + assert len(list(g)) == 360 + + +def test_order(): + a = Permutation([2, 0, 1, 3, 4, 5, 6, 7, 8, 9]) + b = Permutation([2, 1, 3, 4, 5, 6, 7, 8, 9, 0]) + g = PermutationGroup([a, b]) + assert g.order() == 1814400 + assert PermutationGroup().order() == 1 + + +def test_equality(): + p_1 = Permutation(0, 1, 3) + p_2 = Permutation(0, 2, 3) + p_3 = Permutation(0, 1, 2) + p_4 = Permutation(0, 1, 3) + g_1 = PermutationGroup(p_1, p_2) + g_2 = PermutationGroup(p_3, p_4) + g_3 = PermutationGroup(p_2, p_1) + g_4 = PermutationGroup(p_1, p_2) + + assert g_1 != g_2 + assert g_1.generators != g_2.generators + assert g_1.equals(g_2) + assert g_1 != g_3 + assert g_1.equals(g_3) + assert g_1 == g_4 + + +def test_stabilizer(): + S = SymmetricGroup(2) + H = S.stabilizer(0) + assert H.generators == [Permutation(1)] + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + G = PermutationGroup([a, b]) + G0 = G.stabilizer(0) + assert G0.order() == 60 + + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + G2 = G.stabilizer(2) + assert G2.order() == 6 + G2_1 = G2.stabilizer(1) + v = list(G2_1.generate(af=True)) + assert v == [[0, 1, 2, 3, 4, 5, 6, 7], [3, 1, 2, 0, 7, 5, 6, 4]] + + gens = ( + (1, 2, 0, 4, 5, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), + (0, 1, 2, 3, 4, 5, 19, 6, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 7, 17, 18), + (0, 1, 2, 3, 4, 5, 6, 7, 9, 18, 16, 11, 12, 13, 14, 15, 8, 17, 10, 19)) + gens = [Permutation(p) for p in gens] + G = PermutationGroup(gens) + G2 = G.stabilizer(2) + assert G2.order() == 181440 + S = SymmetricGroup(3) + assert [G.order() for G in S.basic_stabilizers] == [6, 2] + + +def test_center(): + # the center of the dihedral group D_n is of order 2 for even n + for i in (4, 6, 10): + D = DihedralGroup(i) + assert (D.center()).order() == 2 + # the center of the dihedral group D_n is of order 1 for odd n>2 + for i in (3, 5, 7): + D = DihedralGroup(i) + assert (D.center()).order() == 1 + # the center of an abelian group is the group itself + for i in (2, 3, 5): + for j in (1, 5, 7): + for k in (1, 1, 11): + G = AbelianGroup(i, j, k) + assert G.center().is_subgroup(G) + # the center of a nonabelian simple group is trivial + for i in(1, 5, 9): + A = AlternatingGroup(i) + assert (A.center()).order() == 1 + # brute-force verifications + D = DihedralGroup(5) + A = AlternatingGroup(3) + C = CyclicGroup(4) + G.is_subgroup(D*A*C) + assert _verify_centralizer(G, G) + + +def test_centralizer(): + # the centralizer of the trivial group is the entire group + S = SymmetricGroup(2) + assert S.centralizer(Permutation(list(range(2)))).is_subgroup(S) + A = AlternatingGroup(5) + assert A.centralizer(Permutation(list(range(5)))).is_subgroup(A) + # a centralizer in the trivial group is the trivial group itself + triv = PermutationGroup([Permutation([0, 1, 2, 3])]) + D = DihedralGroup(4) + assert triv.centralizer(D).is_subgroup(triv) + # brute-force verifications for centralizers of groups + for i in (4, 5, 6): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + C = CyclicGroup(i) + D = DihedralGroup(i) + for gp in (S, A, C, D): + for gp2 in (S, A, C, D): + if not gp2.is_subgroup(gp): + assert _verify_centralizer(gp, gp2) + # verify the centralizer for all elements of several groups + S = SymmetricGroup(5) + elements = list(S.generate_dimino()) + for element in elements: + assert _verify_centralizer(S, element) + A = AlternatingGroup(5) + elements = list(A.generate_dimino()) + for element in elements: + assert _verify_centralizer(A, element) + D = DihedralGroup(7) + elements = list(D.generate_dimino()) + for element in elements: + assert _verify_centralizer(D, element) + # verify centralizers of small groups within small groups + small = [] + for i in (1, 2, 3): + small.append(SymmetricGroup(i)) + small.append(AlternatingGroup(i)) + small.append(DihedralGroup(i)) + small.append(CyclicGroup(i)) + for gp in small: + for gp2 in small: + if gp.degree == gp2.degree: + assert _verify_centralizer(gp, gp2) + + +def test_coset_rank(): + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + i = 0 + for h in G.generate(af=True): + rk = G.coset_rank(h) + assert rk == i + h1 = G.coset_unrank(rk, af=True) + assert h == h1 + i += 1 + assert G.coset_unrank(48) is None + assert G.coset_unrank(G.coset_rank(gens[0])) == gens[0] + + +def test_coset_factor(): + a = Permutation([0, 2, 1]) + G = PermutationGroup([a]) + c = Permutation([2, 1, 0]) + assert not G.coset_factor(c) + assert G.coset_rank(c) is None + + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + g = PermutationGroup([a, b]) + assert g.order() == 360 + d = Permutation([1, 0, 2, 3, 4, 5]) + assert not g.coset_factor(d.array_form) + assert not g.contains(d) + assert Permutation(2) in G + c = Permutation([1, 0, 2, 3, 5, 4]) + v = g.coset_factor(c, True) + tr = g.basic_transversals + p = Permutation.rmul(*[tr[i][v[i]] for i in range(len(g.base))]) + assert p == c + v = g.coset_factor(c) + p = Permutation.rmul(*v) + assert p == c + assert g.contains(c) + G = PermutationGroup([Permutation([2, 1, 0])]) + p = Permutation([1, 0, 2]) + assert G.coset_factor(p) == [] + + +def test_orbits(): + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + g = PermutationGroup([a, b]) + assert g.orbit(0) == {0, 1, 2} + assert g.orbits() == [{0, 1, 2}] + assert g.is_transitive() and g.is_transitive(strict=False) + assert g.orbit_transversal(0) == \ + [Permutation( + [0, 1, 2]), Permutation([2, 0, 1]), Permutation([1, 2, 0])] + assert g.orbit_transversal(0, True) == \ + [(0, Permutation([0, 1, 2])), (2, Permutation([2, 0, 1])), + (1, Permutation([1, 2, 0]))] + + G = DihedralGroup(6) + transversal, slps = _orbit_transversal(G.degree, G.generators, 0, True, slp=True) + for i, t in transversal: + slp = slps[i] + w = G.identity + for s in slp: + w = G.generators[s]*w + assert w == t + + a = Permutation(list(range(1, 100)) + [0]) + G = PermutationGroup([a]) + assert [min(o) for o in G.orbits()] == [0] + G = PermutationGroup(rubik_cube_generators()) + assert [min(o) for o in G.orbits()] == [0, 1] + assert not G.is_transitive() and not G.is_transitive(strict=False) + G = PermutationGroup([Permutation(0, 1, 3), Permutation(3)(0, 1)]) + assert not G.is_transitive() and G.is_transitive(strict=False) + assert PermutationGroup( + Permutation(3)).is_transitive(strict=False) is False + + +def test_is_normal(): + gens_s5 = [Permutation(p) for p in [[1, 2, 3, 4, 0], [2, 1, 4, 0, 3]]] + G1 = PermutationGroup(gens_s5) + assert G1.order() == 120 + gens_a5 = [Permutation(p) for p in [[1, 0, 3, 2, 4], [2, 1, 4, 3, 0]]] + G2 = PermutationGroup(gens_a5) + assert G2.order() == 60 + assert G2.is_normal(G1) + gens3 = [Permutation(p) for p in [[2, 1, 3, 0, 4], [1, 2, 0, 3, 4]]] + G3 = PermutationGroup(gens3) + assert not G3.is_normal(G1) + assert G3.order() == 12 + G4 = G1.normal_closure(G3.generators) + assert G4.order() == 60 + gens5 = [Permutation(p) for p in [[1, 2, 3, 0, 4], [1, 2, 0, 3, 4]]] + G5 = PermutationGroup(gens5) + assert G5.order() == 24 + G6 = G1.normal_closure(G5.generators) + assert G6.order() == 120 + assert G1.is_subgroup(G6) + assert not G1.is_subgroup(G4) + assert G2.is_subgroup(G4) + I5 = PermutationGroup(Permutation(4)) + assert I5.is_normal(G5) + assert I5.is_normal(G6, strict=False) + p1 = Permutation([1, 0, 2, 3, 4]) + p2 = Permutation([0, 1, 2, 4, 3]) + p3 = Permutation([3, 4, 2, 1, 0]) + id_ = Permutation([0, 1, 2, 3, 4]) + H = PermutationGroup([p1, p3]) + H_n1 = PermutationGroup([p1, p2]) + H_n2_1 = PermutationGroup(p1) + H_n2_2 = PermutationGroup(p2) + H_id = PermutationGroup(id_) + assert H_n1.is_normal(H) + assert H_n2_1.is_normal(H_n1) + assert H_n2_2.is_normal(H_n1) + assert H_id.is_normal(H_n2_1) + assert H_id.is_normal(H_n1) + assert H_id.is_normal(H) + assert not H_n2_1.is_normal(H) + assert not H_n2_2.is_normal(H) + + +def test_eq(): + a = [[1, 2, 0, 3, 4, 5], [1, 0, 2, 3, 4, 5], [2, 1, 0, 3, 4, 5], [ + 1, 2, 0, 3, 4, 5]] + a = [Permutation(p) for p in a + [[1, 2, 3, 4, 5, 0]]] + g = Permutation([1, 2, 3, 4, 5, 0]) + G1, G2, G3 = [PermutationGroup(x) for x in [a[:2], a[2:4], [g, g**2]]] + assert G1.order() == G2.order() == G3.order() == 6 + assert G1.is_subgroup(G2) + assert not G1.is_subgroup(G3) + G4 = PermutationGroup([Permutation([0, 1])]) + assert not G1.is_subgroup(G4) + assert G4.is_subgroup(G1, 0) + assert PermutationGroup(g, g).is_subgroup(PermutationGroup(g)) + assert SymmetricGroup(3).is_subgroup(SymmetricGroup(4), 0) + assert SymmetricGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + assert not CyclicGroup(5).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + assert CyclicGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + + +def test_derived_subgroup(): + a = Permutation([1, 0, 2, 4, 3]) + b = Permutation([0, 1, 3, 2, 4]) + G = PermutationGroup([a, b]) + C = G.derived_subgroup() + assert C.order() == 3 + assert C.is_normal(G) + assert C.is_subgroup(G, 0) + assert not G.is_subgroup(C, 0) + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + C = G.derived_subgroup() + assert C.order() == 12 + + +def test_is_solvable(): + a = Permutation([1, 2, 0]) + b = Permutation([1, 0, 2]) + G = PermutationGroup([a, b]) + assert G.is_solvable + G = PermutationGroup([a]) + assert G.is_solvable + a = Permutation([1, 2, 3, 4, 0]) + b = Permutation([1, 0, 2, 3, 4]) + G = PermutationGroup([a, b]) + assert not G.is_solvable + P = SymmetricGroup(10) + S = P.sylow_subgroup(3) + assert S.is_solvable + +def test_rubik1(): + gens = rubik_cube_generators() + gens1 = [gens[-1]] + [p**2 for p in gens[1:]] + G1 = PermutationGroup(gens1) + assert G1.order() == 19508428800 + gens2 = [p**2 for p in gens] + G2 = PermutationGroup(gens2) + assert G2.order() == 663552 + assert G2.is_subgroup(G1, 0) + C1 = G1.derived_subgroup() + assert C1.order() == 4877107200 + assert C1.is_subgroup(G1, 0) + assert not G2.is_subgroup(C1, 0) + + G = RubikGroup(2) + assert G.order() == 3674160 + + +@XFAIL +def test_rubik(): + skip('takes too much time') + G = PermutationGroup(rubik_cube_generators()) + assert G.order() == 43252003274489856000 + G1 = PermutationGroup(G[:3]) + assert G1.order() == 170659735142400 + assert not G1.is_normal(G) + G2 = G.normal_closure(G1.generators) + assert G2.is_subgroup(G) + + +def test_direct_product(): + C = CyclicGroup(4) + D = DihedralGroup(4) + G = C*C*C + assert G.order() == 64 + assert G.degree == 12 + assert len(G.orbits()) == 3 + assert G.is_abelian is True + H = D*C + assert H.order() == 32 + assert H.is_abelian is False + + +def test_orbit_rep(): + G = DihedralGroup(6) + assert G.orbit_rep(1, 3) in [Permutation([2, 3, 4, 5, 0, 1]), + Permutation([4, 3, 2, 1, 0, 5])] + H = CyclicGroup(4)*G + assert H.orbit_rep(1, 5) is False + + +def test_schreier_vector(): + G = CyclicGroup(50) + v = [0]*50 + v[23] = -1 + assert G.schreier_vector(23) == v + H = DihedralGroup(8) + assert H.schreier_vector(2) == [0, 1, -1, 0, 0, 1, 0, 0] + L = SymmetricGroup(4) + assert L.schreier_vector(1) == [1, -1, 0, 0] + + +def test_random_pr(): + D = DihedralGroup(6) + r = 11 + n = 3 + _random_prec_n = {} + _random_prec_n[0] = {'s': 7, 't': 3, 'x': 2, 'e': -1} + _random_prec_n[1] = {'s': 5, 't': 5, 'x': 1, 'e': -1} + _random_prec_n[2] = {'s': 3, 't': 4, 'x': 2, 'e': 1} + D._random_pr_init(r, n, _random_prec_n=_random_prec_n) + assert D._random_gens[11] == [0, 1, 2, 3, 4, 5] + _random_prec = {'s': 2, 't': 9, 'x': 1, 'e': -1} + assert D.random_pr(_random_prec=_random_prec) == \ + Permutation([0, 5, 4, 3, 2, 1]) + + +def test_is_alt_sym(): + G = DihedralGroup(10) + assert G.is_alt_sym() is False + assert G._eval_is_alt_sym_naive() is False + assert G._eval_is_alt_sym_naive(only_alt=True) is False + assert G._eval_is_alt_sym_naive(only_sym=True) is False + + S = SymmetricGroup(10) + assert S._eval_is_alt_sym_naive() is True + assert S._eval_is_alt_sym_naive(only_alt=True) is False + assert S._eval_is_alt_sym_naive(only_sym=True) is True + + N_eps = 10 + _random_prec = {'N_eps': N_eps, + 0: Permutation([[2], [1, 4], [0, 6, 7, 8, 9, 3, 5]]), + 1: Permutation([[1, 8, 7, 6, 3, 5, 2, 9], [0, 4]]), + 2: Permutation([[5, 8], [4, 7], [0, 1, 2, 3, 6, 9]]), + 3: Permutation([[3], [0, 8, 2, 7, 4, 1, 6, 9, 5]]), + 4: Permutation([[8], [4, 7, 9], [3, 6], [0, 5, 1, 2]]), + 5: Permutation([[6], [0, 2, 4, 5, 1, 8, 3, 9, 7]]), + 6: Permutation([[6, 9, 8], [4, 5], [1, 3, 7], [0, 2]]), + 7: Permutation([[4], [0, 2, 9, 1, 3, 8, 6, 5, 7]]), + 8: Permutation([[1, 5, 6, 3], [0, 2, 7, 8, 4, 9]]), + 9: Permutation([[8], [6, 7], [2, 3, 4, 5], [0, 1, 9]])} + assert S.is_alt_sym(_random_prec=_random_prec) is True + + A = AlternatingGroup(10) + assert A._eval_is_alt_sym_naive() is True + assert A._eval_is_alt_sym_naive(only_alt=True) is True + assert A._eval_is_alt_sym_naive(only_sym=True) is False + + _random_prec = {'N_eps': N_eps, + 0: Permutation([[1, 6, 4, 2, 7, 8, 5, 9, 3], [0]]), + 1: Permutation([[1], [0, 5, 8, 4, 9, 2, 3, 6, 7]]), + 2: Permutation([[1, 9, 8, 3, 2, 5], [0, 6, 7, 4]]), + 3: Permutation([[6, 8, 9], [4, 5], [1, 3, 7, 2], [0]]), + 4: Permutation([[8], [5], [4], [2, 6, 9, 3], [1], [0, 7]]), + 5: Permutation([[3, 6], [0, 8, 1, 7, 5, 9, 4, 2]]), + 6: Permutation([[5], [2, 9], [1, 8, 3], [0, 4, 7, 6]]), + 7: Permutation([[1, 8, 4, 7, 2, 3], [0, 6, 9, 5]]), + 8: Permutation([[5, 8, 7], [3], [1, 4, 2, 6], [0, 9]]), + 9: Permutation([[4, 9, 6], [3, 8], [1, 2], [0, 5, 7]])} + assert A.is_alt_sym(_random_prec=_random_prec) is False + + G = PermutationGroup( + Permutation(1, 3, size=8)(0, 2, 4, 6), + Permutation(5, 7, size=8)(0, 2, 4, 6)) + assert G.is_alt_sym() is False + + # Tests for monte-carlo c_n parameter setting, and which guarantees + # to give False. + G = DihedralGroup(10) + assert G._eval_is_alt_sym_monte_carlo() is False + G = DihedralGroup(20) + assert G._eval_is_alt_sym_monte_carlo() is False + + # A dry-running test to check if it looks up for the updated cache. + G = DihedralGroup(6) + G.is_alt_sym() + assert G.is_alt_sym() is False + + +def test_minimal_block(): + D = DihedralGroup(6) + block_system = D.minimal_block([0, 3]) + for i in range(3): + assert block_system[i] == block_system[i + 3] + S = SymmetricGroup(6) + assert S.minimal_block([0, 1]) == [0, 0, 0, 0, 0, 0] + + assert Tetra.pgroup.minimal_block([0, 1]) == [0, 0, 0, 0] + + P1 = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + P2 = PermutationGroup(Permutation(0, 1, 2, 3, 4, 5), Permutation(1, 5)(2, 4)) + assert P1.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1] + assert P2.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1] + + +def test_minimal_blocks(): + P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + assert P.minimal_blocks() == [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] + + P = SymmetricGroup(5) + assert P.minimal_blocks() == [[0]*5] + + P = PermutationGroup(Permutation(0, 3)) + assert P.minimal_blocks() is False + + +def test_max_div(): + S = SymmetricGroup(10) + assert S.max_div == 5 + + +def test_is_primitive(): + S = SymmetricGroup(5) + assert S.is_primitive() is True + C = CyclicGroup(7) + assert C.is_primitive() is True + + a = Permutation(0, 1, 2, size=6) + b = Permutation(3, 4, 5, size=6) + G = PermutationGroup(a, b) + assert G.is_primitive() is False + + +def test_random_stab(): + S = SymmetricGroup(5) + _random_el = Permutation([1, 3, 2, 0, 4]) + _random_prec = {'rand': _random_el} + g = S.random_stab(2, _random_prec=_random_prec) + assert g == Permutation([1, 3, 2, 0, 4]) + h = S.random_stab(1) + assert h(1) == 1 + + +def test_transitivity_degree(): + perm = Permutation([1, 2, 0]) + C = PermutationGroup([perm]) + assert C.transitivity_degree == 1 + gen1 = Permutation([1, 2, 0, 3, 4]) + gen2 = Permutation([1, 2, 3, 4, 0]) + # alternating group of degree 5 + Alt = PermutationGroup([gen1, gen2]) + assert Alt.transitivity_degree == 3 + + +def test_schreier_sims_random(): + assert sorted(Tetra.pgroup.base) == [0, 1] + + S = SymmetricGroup(3) + base = [0, 1] + strong_gens = [Permutation([1, 2, 0]), Permutation([1, 0, 2]), + Permutation([0, 2, 1])] + assert S.schreier_sims_random(base, strong_gens, 5) == (base, strong_gens) + D = DihedralGroup(3) + _random_prec = {'g': [Permutation([2, 0, 1]), Permutation([1, 2, 0]), + Permutation([1, 0, 2])]} + base = [0, 1] + strong_gens = [Permutation([1, 2, 0]), Permutation([2, 1, 0]), + Permutation([0, 2, 1])] + assert D.schreier_sims_random([], D.generators, 2, + _random_prec=_random_prec) == (base, strong_gens) + + +def test_baseswap(): + S = SymmetricGroup(4) + S.schreier_sims() + base = S.base + strong_gens = S.strong_gens + assert base == [0, 1, 2] + deterministic = S.baseswap(base, strong_gens, 1, randomized=False) + randomized = S.baseswap(base, strong_gens, 1) + assert deterministic[0] == [0, 2, 1] + assert _verify_bsgs(S, deterministic[0], deterministic[1]) is True + assert randomized[0] == [0, 2, 1] + assert _verify_bsgs(S, randomized[0], randomized[1]) is True + + +def test_schreier_sims_incremental(): + identity = Permutation([0, 1, 2, 3, 4]) + TrivialGroup = PermutationGroup([identity]) + base, strong_gens = TrivialGroup.schreier_sims_incremental(base=[0, 1, 2]) + assert _verify_bsgs(TrivialGroup, base, strong_gens) is True + S = SymmetricGroup(5) + base, strong_gens = S.schreier_sims_incremental(base=[0, 1, 2]) + assert _verify_bsgs(S, base, strong_gens) is True + D = DihedralGroup(2) + base, strong_gens = D.schreier_sims_incremental(base=[1]) + assert _verify_bsgs(D, base, strong_gens) is True + A = AlternatingGroup(7) + gens = A.generators[:] + gen0 = gens[0] + gen1 = gens[1] + gen1 = rmul(gen1, ~gen0) + gen0 = rmul(gen0, gen1) + gen1 = rmul(gen0, gen1) + base, strong_gens = A.schreier_sims_incremental(base=[0, 1], gens=gens) + assert _verify_bsgs(A, base, strong_gens) is True + C = CyclicGroup(11) + gen = C.generators[0] + base, strong_gens = C.schreier_sims_incremental(gens=[gen**3]) + assert _verify_bsgs(C, base, strong_gens) is True + + +def _subgroup_search(i, j, k): + prop_true = lambda x: True + prop_fix_points = lambda x: [x(point) for point in points] == points + prop_comm_g = lambda x: rmul(x, g) == rmul(g, x) + prop_even = lambda x: x.is_even + for i in range(i, j, k): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + C = CyclicGroup(i) + Sym = S.subgroup_search(prop_true) + assert Sym.is_subgroup(S) + Alt = S.subgroup_search(prop_even) + assert Alt.is_subgroup(A) + Sym = S.subgroup_search(prop_true, init_subgroup=C) + assert Sym.is_subgroup(S) + points = [7] + assert S.stabilizer(7).is_subgroup(S.subgroup_search(prop_fix_points)) + points = [3, 4] + assert S.stabilizer(3).stabilizer(4).is_subgroup( + S.subgroup_search(prop_fix_points)) + points = [3, 5] + fix35 = A.subgroup_search(prop_fix_points) + points = [5] + fix5 = A.subgroup_search(prop_fix_points) + assert A.subgroup_search(prop_fix_points, init_subgroup=fix35 + ).is_subgroup(fix5) + base, strong_gens = A.schreier_sims_incremental() + g = A.generators[0] + comm_g = \ + A.subgroup_search(prop_comm_g, base=base, strong_gens=strong_gens) + assert _verify_bsgs(comm_g, base, comm_g.generators) is True + assert [prop_comm_g(gen) is True for gen in comm_g.generators] + + +def test_subgroup_search(): + _subgroup_search(10, 15, 2) + + +@XFAIL +def test_subgroup_search2(): + skip('takes too much time') + _subgroup_search(16, 17, 1) + + +def test_normal_closure(): + # the normal closure of the trivial group is trivial + S = SymmetricGroup(3) + identity = Permutation([0, 1, 2]) + closure = S.normal_closure(identity) + assert closure.is_trivial + # the normal closure of the entire group is the entire group + A = AlternatingGroup(4) + assert A.normal_closure(A).is_subgroup(A) + # brute-force verifications for subgroups + for i in (3, 4, 5): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + D = DihedralGroup(i) + C = CyclicGroup(i) + for gp in (A, D, C): + assert _verify_normal_closure(S, gp) + # brute-force verifications for all elements of a group + S = SymmetricGroup(5) + elements = list(S.generate_dimino()) + for element in elements: + assert _verify_normal_closure(S, element) + # small groups + small = [] + for i in (1, 2, 3): + small.append(SymmetricGroup(i)) + small.append(AlternatingGroup(i)) + small.append(DihedralGroup(i)) + small.append(CyclicGroup(i)) + for gp in small: + for gp2 in small: + if gp2.is_subgroup(gp, 0) and gp2.degree == gp.degree: + assert _verify_normal_closure(gp, gp2) + + +def test_derived_series(): + # the derived series of the trivial group consists only of the trivial group + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert triv.derived_series()[0].is_subgroup(triv) + # the derived series for a simple group consists only of the group itself + for i in (5, 6, 7): + A = AlternatingGroup(i) + assert A.derived_series()[0].is_subgroup(A) + # the derived series for S_4 is S_4 > A_4 > K_4 > triv + S = SymmetricGroup(4) + series = S.derived_series() + assert series[1].is_subgroup(AlternatingGroup(4)) + assert series[2].is_subgroup(DihedralGroup(2)) + assert series[3].is_trivial + + +def test_lower_central_series(): + # the lower central series of the trivial group consists of the trivial + # group + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert triv.lower_central_series()[0].is_subgroup(triv) + # the lower central series of a simple group consists of the group itself + for i in (5, 6, 7): + A = AlternatingGroup(i) + assert A.lower_central_series()[0].is_subgroup(A) + # GAP-verified example + S = SymmetricGroup(6) + series = S.lower_central_series() + assert len(series) == 2 + assert series[1].is_subgroup(AlternatingGroup(6)) + + +def test_commutator(): + # the commutator of the trivial group and the trivial group is trivial + S = SymmetricGroup(3) + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert S.commutator(triv, triv).is_subgroup(triv) + # the commutator of the trivial group and any other group is again trivial + A = AlternatingGroup(3) + assert S.commutator(triv, A).is_subgroup(triv) + # the commutator is commutative + for i in (3, 4, 5): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + D = DihedralGroup(i) + assert S.commutator(A, D).is_subgroup(S.commutator(D, A)) + # the commutator of an abelian group is trivial + S = SymmetricGroup(7) + A1 = AbelianGroup(2, 5) + A2 = AbelianGroup(3, 4) + triv = PermutationGroup([Permutation([0, 1, 2, 3, 4, 5, 6])]) + assert S.commutator(A1, A1).is_subgroup(triv) + assert S.commutator(A2, A2).is_subgroup(triv) + # examples calculated by hand + S = SymmetricGroup(3) + A = AlternatingGroup(3) + assert S.commutator(A, S).is_subgroup(A) + + +def test_is_nilpotent(): + # every abelian group is nilpotent + for i in (1, 2, 3): + C = CyclicGroup(i) + Ab = AbelianGroup(i, i + 2) + assert C.is_nilpotent + assert Ab.is_nilpotent + Ab = AbelianGroup(5, 7, 10) + assert Ab.is_nilpotent + # A_5 is not solvable and thus not nilpotent + assert AlternatingGroup(5).is_nilpotent is False + + +def test_is_trivial(): + for i in range(5): + triv = PermutationGroup([Permutation(list(range(i)))]) + assert triv.is_trivial + + +def test_pointwise_stabilizer(): + S = SymmetricGroup(2) + stab = S.pointwise_stabilizer([0]) + assert stab.generators == [Permutation(1)] + S = SymmetricGroup(5) + points = [] + stab = S + for point in (2, 0, 3, 4, 1): + stab = stab.stabilizer(point) + points.append(point) + assert S.pointwise_stabilizer(points).is_subgroup(stab) + + +def test_make_perm(): + assert cube.pgroup.make_perm(5, seed=list(range(5))) == \ + Permutation([4, 7, 6, 5, 0, 3, 2, 1]) + assert cube.pgroup.make_perm(7, seed=list(range(7))) == \ + Permutation([6, 7, 3, 2, 5, 4, 0, 1]) + + +def test_elements(): + from sympy.sets.sets import FiniteSet + + p = Permutation(2, 3) + assert set(PermutationGroup(p).elements) == {Permutation(3), Permutation(2, 3)} + assert FiniteSet(*PermutationGroup(p).elements) \ + == FiniteSet(Permutation(2, 3), Permutation(3)) + + +def test_is_group(): + assert PermutationGroup(Permutation(1,2), Permutation(2,4)).is_group is True + assert SymmetricGroup(4).is_group is True + + +def test_PermutationGroup(): + assert PermutationGroup() == PermutationGroup(Permutation()) + assert (PermutationGroup() == 0) is False + + +def test_coset_transvesal(): + G = AlternatingGroup(5) + H = PermutationGroup(Permutation(0,1,2),Permutation(1,2)(3,4)) + assert G.coset_transversal(H) == \ + [Permutation(4), Permutation(2, 3, 4), Permutation(2, 4, 3), + Permutation(1, 2, 4), Permutation(4)(1, 2, 3), Permutation(1, 3)(2, 4), + Permutation(0, 1, 2, 3, 4), Permutation(0, 1, 2, 4, 3), + Permutation(0, 1, 3, 2, 4), Permutation(0, 2, 4, 1, 3)] + + +def test_coset_table(): + G = PermutationGroup(Permutation(0,1,2,3), Permutation(0,1,2), + Permutation(0,4,2,7), Permutation(5,6), Permutation(0,7)) + H = PermutationGroup(Permutation(0,1,2,3), Permutation(0,7)) + assert G.coset_table(H) == \ + [[0, 0, 0, 0, 1, 2, 3, 3, 0, 0], [4, 5, 2, 5, 6, 0, 7, 7, 1, 1], + [5, 4, 5, 1, 0, 6, 8, 8, 6, 6], [3, 3, 3, 3, 7, 8, 0, 0, 3, 3], + [2, 1, 4, 4, 4, 4, 9, 9, 4, 4], [1, 2, 1, 2, 5, 5, 10, 10, 5, 5], + [6, 6, 6, 6, 2, 1, 11, 11, 2, 2], [9, 10, 8, 10, 11, 3, 1, 1, 7, 7], + [10, 9, 10, 7, 3, 11, 2, 2, 11, 11], [8, 7, 9, 9, 9, 9, 4, 4, 9, 9], + [7, 8, 7, 8, 10, 10, 5, 5, 10, 10], [11, 11, 11, 11, 8, 7, 6, 6, 8, 8]] + + +def test_subgroup(): + G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) + H = G.subgroup([Permutation(0,1,3)]) + assert H.is_subgroup(G) + + +def test_generator_product(): + G = SymmetricGroup(5) + p = Permutation(0, 2, 3)(1, 4) + gens = G.generator_product(p) + assert all(g in G.strong_gens for g in gens) + w = G.identity + for g in gens: + w = g*w + assert w == p + + +def test_sylow_subgroup(): + P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + S = P.sylow_subgroup(2) + assert S.order() == 4 + + P = DihedralGroup(12) + S = P.sylow_subgroup(3) + assert S.order() == 3 + + P = PermutationGroup( + Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5), Permutation(0, 2)) + S = P.sylow_subgroup(3) + assert S.order() == 9 + S = P.sylow_subgroup(2) + assert S.order() == 8 + + P = SymmetricGroup(10) + S = P.sylow_subgroup(2) + assert S.order() == 256 + S = P.sylow_subgroup(3) + assert S.order() == 81 + S = P.sylow_subgroup(5) + assert S.order() == 25 + + # the length of the lower central series + # of a p-Sylow subgroup of Sym(n) grows with + # the highest exponent exp of p such + # that n >= p**exp + exp = 1 + length = 0 + for i in range(2, 9): + P = SymmetricGroup(i) + S = P.sylow_subgroup(2) + ls = S.lower_central_series() + if i // 2**exp > 0: + # length increases with exponent + assert len(ls) > length + length = len(ls) + exp += 1 + else: + assert len(ls) == length + + G = SymmetricGroup(100) + S = G.sylow_subgroup(3) + assert G.order() % S.order() == 0 + assert G.order()/S.order() % 3 > 0 + + G = AlternatingGroup(100) + S = G.sylow_subgroup(2) + assert G.order() % S.order() == 0 + assert G.order()/S.order() % 2 > 0 + + G = DihedralGroup(18) + S = G.sylow_subgroup(p=2) + assert S.order() == 4 + + G = DihedralGroup(50) + S = G.sylow_subgroup(p=2) + assert S.order() == 4 + + +@slow +def test_presentation(): + def _test(P): + G = P.presentation() + return G.order() == P.order() + + def _strong_test(P): + G = P.strong_presentation() + chk = len(G.generators) == len(P.strong_gens) + return chk and G.order() == P.order() + + P = PermutationGroup(Permutation(0,1,5,2)(3,7,4,6), Permutation(0,3,5,4)(1,6,2,7)) + assert _test(P) + + P = AlternatingGroup(5) + assert _test(P) + + P = SymmetricGroup(5) + assert _test(P) + + P = PermutationGroup( + [Permutation(0,3,1,2), Permutation(3)(0,1), Permutation(0,1)(2,3)]) + assert _strong_test(P) + + P = DihedralGroup(6) + assert _strong_test(P) + + a = Permutation(0,1)(2,3) + b = Permutation(0,2)(3,1) + c = Permutation(4,5) + P = PermutationGroup(c, a, b) + assert _strong_test(P) + + +def test_polycyclic(): + a = Permutation([0, 1, 2]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + assert G.is_polycyclic is True + + a = Permutation([1, 2, 3, 4, 0]) + b = Permutation([1, 0, 2, 3, 4]) + G = PermutationGroup([a, b]) + assert G.is_polycyclic is False + + +def test_elementary(): + a = Permutation([1, 5, 2, 0, 3, 6, 4]) + G = PermutationGroup([a]) + assert G.is_elementary(7) is False + + a = Permutation(0, 1)(2, 3) + b = Permutation(0, 2)(3, 1) + G = PermutationGroup([a, b]) + assert G.is_elementary(2) is True + c = Permutation(4, 5, 6) + G = PermutationGroup([a, b, c]) + assert G.is_elementary(2) is False + + G = SymmetricGroup(4).sylow_subgroup(2) + assert G.is_elementary(2) is False + H = AlternatingGroup(4).sylow_subgroup(2) + assert H.is_elementary(2) is True + + +def test_perfect(): + G = AlternatingGroup(3) + assert G.is_perfect is False + G = AlternatingGroup(5) + assert G.is_perfect is True + + +def test_index(): + G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) + H = G.subgroup([Permutation(0,1,3)]) + assert G.index(H) == 4 + + +def test_cyclic(): + G = SymmetricGroup(2) + assert G.is_cyclic + G = AbelianGroup(3, 7) + assert G.is_cyclic + G = AbelianGroup(7, 7) + assert not G.is_cyclic + G = AlternatingGroup(3) + assert G.is_cyclic + G = AlternatingGroup(4) + assert not G.is_cyclic + + # Order less than 6 + G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 1)) + assert G.is_cyclic + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(0, 2)(1, 3) + ) + assert G.is_cyclic + G = PermutationGroup( + Permutation(3), + Permutation(0, 1)(2, 3), + Permutation(0, 2)(1, 3), + Permutation(0, 3)(1, 2) + ) + assert G.is_cyclic is False + + # Order 15 + G = PermutationGroup( + Permutation(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), + Permutation(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13) + ) + assert G.is_cyclic + + # Distinct prime orders + assert PermutationGroup._distinct_primes_lemma([3, 5]) is True + assert PermutationGroup._distinct_primes_lemma([5, 7]) is True + assert PermutationGroup._distinct_primes_lemma([2, 3]) is None + assert PermutationGroup._distinct_primes_lemma([3, 5, 7]) is None + assert PermutationGroup._distinct_primes_lemma([5, 7, 13]) is True + + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(0, 2)(1, 3)) + assert G.is_cyclic + assert G._is_abelian + + # Non-abelian and therefore not cyclic + G = PermutationGroup(*SymmetricGroup(3).generators) + assert G.is_cyclic is False + + # Abelian and cyclic + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(4, 5, 6) + ) + assert G.is_cyclic + + # Abelian but not cyclic + G = PermutationGroup( + Permutation(0, 1), + Permutation(2, 3), + Permutation(4, 5, 6) + ) + assert G.is_cyclic is False + + +def test_dihedral(): + G = SymmetricGroup(2) + assert G.is_dihedral + G = SymmetricGroup(3) + assert G.is_dihedral + + G = AbelianGroup(2, 2) + assert G.is_dihedral + G = CyclicGroup(4) + assert not G.is_dihedral + + G = AbelianGroup(3, 5) + assert not G.is_dihedral + G = AbelianGroup(2) + assert G.is_dihedral + G = AbelianGroup(6) + assert not G.is_dihedral + + # D6, generated by two adjacent flips + G = PermutationGroup( + Permutation(1, 5)(2, 4), + Permutation(0, 1)(3, 4)(2, 5)) + assert G.is_dihedral + + # D7, generated by a flip and a rotation + G = PermutationGroup( + Permutation(1, 6)(2, 5)(3, 4), + Permutation(0, 1, 2, 3, 4, 5, 6)) + assert G.is_dihedral + + # S4, presented by three generators, fails due to having exactly 9 + # elements of order 2: + G = PermutationGroup( + Permutation(0, 1), Permutation(0, 2), + Permutation(0, 3)) + assert not G.is_dihedral + + # D7, given by three generators + G = PermutationGroup( + Permutation(1, 6)(2, 5)(3, 4), + Permutation(2, 0)(3, 6)(4, 5), + Permutation(0, 1, 2, 3, 4, 5, 6)) + assert G.is_dihedral + + +def test_abelian_invariants(): + G = AbelianGroup(2, 3, 4) + assert G.abelian_invariants() == [2, 3, 4] + G=PermutationGroup([Permutation(1, 2, 3, 4), Permutation(1, 2), Permutation(5, 6)]) + assert G.abelian_invariants() == [2, 2] + G = AlternatingGroup(7) + assert G.abelian_invariants() == [] + G = AlternatingGroup(4) + assert G.abelian_invariants() == [3] + G = DihedralGroup(4) + assert G.abelian_invariants() == [2, 2] + + G = PermutationGroup([Permutation(1, 2, 3, 4, 5, 6, 7)]) + assert G.abelian_invariants() == [7] + G = DihedralGroup(12) + S = G.sylow_subgroup(3) + assert S.abelian_invariants() == [3] + G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 3)) + assert G.abelian_invariants() == [3] + G = PermutationGroup([Permutation(0, 1), Permutation(0, 2, 4, 6)(1, 3, 5, 7)]) + assert G.abelian_invariants() == [2, 4] + G = SymmetricGroup(30) + S = G.sylow_subgroup(2) + assert S.abelian_invariants() == [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + S = G.sylow_subgroup(3) + assert S.abelian_invariants() == [3, 3, 3, 3] + S = G.sylow_subgroup(5) + assert S.abelian_invariants() == [5, 5, 5] + + +def test_composition_series(): + a = Permutation(1, 2, 3) + b = Permutation(1, 2) + G = PermutationGroup([a, b]) + comp_series = G.composition_series() + assert comp_series == G.derived_series() + # The first group in the composition series is always the group itself and + # the last group in the series is the trivial group. + S = SymmetricGroup(4) + assert S.composition_series()[0] == S + assert len(S.composition_series()) == 5 + A = AlternatingGroup(4) + assert A.composition_series()[0] == A + assert len(A.composition_series()) == 4 + + # the composition series for C_8 is C_8 > C_4 > C_2 > triv + G = CyclicGroup(8) + series = G.composition_series() + assert is_isomorphic(series[1], CyclicGroup(4)) + assert is_isomorphic(series[2], CyclicGroup(2)) + assert series[3].is_trivial + + +def test_is_symmetric(): + a = Permutation(0, 1, 2) + b = Permutation(0, 1, size=3) + assert PermutationGroup(a, b).is_symmetric is True + + a = Permutation(0, 2, 1) + b = Permutation(1, 2, size=3) + assert PermutationGroup(a, b).is_symmetric is True + + a = Permutation(0, 1, 2, 3) + b = Permutation(0, 3)(1, 2) + assert PermutationGroup(a, b).is_symmetric is False + +def test_conjugacy_class(): + S = SymmetricGroup(4) + x = Permutation(1, 2, 3) + C = {Permutation(0, 1, 2, size = 4), Permutation(0, 1, 3), + Permutation(0, 2, 1, size = 4), Permutation(0, 2, 3), + Permutation(0, 3, 1), Permutation(0, 3, 2), + Permutation(1, 2, 3), Permutation(1, 3, 2)} + assert S.conjugacy_class(x) == C + +def test_conjugacy_classes(): + S = SymmetricGroup(3) + expected = [{Permutation(size = 3)}, + {Permutation(0, 1, size = 3), Permutation(0, 2), Permutation(1, 2)}, + {Permutation(0, 1, 2), Permutation(0, 2, 1)}] + computed = S.conjugacy_classes() + + assert len(expected) == len(computed) + assert all(e in computed for e in expected) + +def test_coset_class(): + a = Permutation(1, 2) + b = Permutation(0, 1) + G = PermutationGroup([a, b]) + #Creating right coset + rht_coset = G*a + #Checking whether it is left coset or right coset + assert rht_coset.is_right_coset + assert not rht_coset.is_left_coset + #Creating list representation of coset + list_repr = rht_coset.as_list() + expected = [Permutation(0, 2), Permutation(0, 2, 1), Permutation(1, 2), + Permutation(2), Permutation(2)(0, 1), Permutation(0, 1, 2)] + for ele in list_repr: + assert ele in expected + #Creating left coset + left_coset = a*G + #Checking whether it is left coset or right coset + assert not left_coset.is_right_coset + assert left_coset.is_left_coset + #Creating list representation of Coset + list_repr = left_coset.as_list() + expected = [Permutation(2)(0, 1), Permutation(0, 1, 2), Permutation(1, 2), + Permutation(2), Permutation(0, 2), Permutation(0, 2, 1)] + for ele in list_repr: + assert ele in expected + + G = PermutationGroup(Permutation(1, 2, 3, 4), Permutation(2, 3, 4)) + H = PermutationGroup(Permutation(1, 2, 3, 4)) + g = Permutation(1, 3)(2, 4) + rht_coset = Coset(g, H, G, dir='+') + assert rht_coset.is_right_coset + list_repr = rht_coset.as_list() + expected = [Permutation(1, 2, 3, 4), Permutation(4), Permutation(1, 3)(2, 4), + Permutation(1, 4, 3, 2)] + for ele in list_repr: + assert ele in expected + +def test_symmetricpermutationgroup(): + a = SymmetricPermutationGroup(5) + assert a.degree == 5 + assert a.order() == 120 + assert a.identity() == Permutation(4) diff --git a/shared/package-files/ef/ef5281bb8560eb466e7efef9b4850629d5ad308f534ca579576863dd0cf0bebc/_make_dual_ops.h b/shared/package-files/ef/ef5281bb8560eb466e7efef9b4850629d5ad308f534ca579576863dd0cf0bebc/_make_dual_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..75aa751551da2f34150fbb8830647c2ada3343c9 --- /dev/null +++ b/shared/package-files/ef/ef5281bb8560eb466e7efef9b4850629d5ad308f534ca579576863dd0cf0bebc/_make_dual_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _make_dual { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_make_dual"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & primal, const at::Tensor & tangent, int64_t level); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & primal, const at::Tensor & tangent, int64_t level); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/ef55cbb9b9e1b463da4a911104543c2f2274351f116ff99e0b2436bf0b98024b/upsample_nearest2d_backward_cuda_dispatch.h b/shared/package-files/ef/ef55cbb9b9e1b463da4a911104543c2f2274351f116ff99e0b2436bf0b98024b/upsample_nearest2d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..dffe70d946d53cc2110a59b66e30cd22b4c9ff9c --- /dev/null +++ b/shared/package-files/ef/ef55cbb9b9e1b463da4a911104543c2f2274351f116ff99e0b2436bf0b98024b/upsample_nearest2d_backward_cuda_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor upsample_nearest2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor upsample_nearest2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & upsample_nearest2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/ef/ef578c2b328482c283ad0a0bda8e3aac2f867ed977c556c662fbad74a7b7af3a/__init__.cpython-311.pyc b/shared/package-files/ef/ef578c2b328482c283ad0a0bda8e3aac2f867ed977c556c662fbad74a7b7af3a/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c951a0c70dc8bb1988b6f7726b302a1dbe662dae Binary files /dev/null and b/shared/package-files/ef/ef578c2b328482c283ad0a0bda8e3aac2f867ed977c556c662fbad74a7b7af3a/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef588dd2382705bcb24c72b0147719fefc17abca2067376887503a17e3cc6ece/test_xxm.cpython-311.pyc b/shared/package-files/ef/ef588dd2382705bcb24c72b0147719fefc17abca2067376887503a17e3cc6ece/test_xxm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8070d92c12c3c0cab956d966e2d71aaba9f1fd6f Binary files /dev/null and b/shared/package-files/ef/ef588dd2382705bcb24c72b0147719fefc17abca2067376887503a17e3cc6ece/test_xxm.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef5e75d2355d22bbd85409ff6d9b875670560435172b6623adbd04955c49c5cf/install_headers.cpython-311.pyc b/shared/package-files/ef/ef5e75d2355d22bbd85409ff6d9b875670560435172b6623adbd04955c49c5cf/install_headers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0e87ca139640edd1c7de2c1a4459a7011270743 Binary files /dev/null and b/shared/package-files/ef/ef5e75d2355d22bbd85409ff6d9b875670560435172b6623adbd04955c49c5cf/install_headers.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef5e87755772b6c65ba99a6388eee67126f1da4d3df8ad698d9c1a359f9b93d4/registry.cpython-311.pyc b/shared/package-files/ef/ef5e87755772b6c65ba99a6388eee67126f1da4d3df8ad698d9c1a359f9b93d4/registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f2a5c9cd57295a8e295bece0892ef196bdfdd6c Binary files /dev/null and b/shared/package-files/ef/ef5e87755772b6c65ba99a6388eee67126f1da4d3df8ad698d9c1a359f9b93d4/registry.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef5edb74f5935dd91e59ebd8dc7734995385eb943d0c8828c1a4222b2f1a76f1/numpy_distribution.cpython-311.pyc b/shared/package-files/ef/ef5edb74f5935dd91e59ebd8dc7734995385eb943d0c8828c1a4222b2f1a76f1/numpy_distribution.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b8df9a834a431d8ccbfc891b6cf5071f28b0275 Binary files /dev/null and b/shared/package-files/ef/ef5edb74f5935dd91e59ebd8dc7734995385eb943d0c8828c1a4222b2f1a76f1/numpy_distribution.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef613a02297acb820a280205e484d9df78c1928da13336b037da6da90857c0bb/symbolic_probability.cpython-311.pyc b/shared/package-files/ef/ef613a02297acb820a280205e484d9df78c1928da13336b037da6da90857c0bb/symbolic_probability.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fef770130abf4e07bf9e52dc55332e63a2dea56 Binary files /dev/null and b/shared/package-files/ef/ef613a02297acb820a280205e484d9df78c1928da13336b037da6da90857c0bb/symbolic_probability.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef63d7c5cafd10d23ed4abc91f40ba83922fb6d4561198a03ecbbe94b28fe4fd/one_hot_native.h b/shared/package-files/ef/ef63d7c5cafd10d23ed4abc91f40ba83922fb6d4561198a03ecbbe94b28fe4fd/one_hot_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a76eb8d0760ae847484682e98772b8210c8272f8 --- /dev/null +++ b/shared/package-files/ef/ef63d7c5cafd10d23ed4abc91f40ba83922fb6d4561198a03ecbbe94b28fe4fd/one_hot_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor one_hot(const at::Tensor & self, int64_t num_classes=-1); +} // namespace native +} // namespace at diff --git a/shared/package-files/ef/ef69388714f5f9c1d6bb9c6c0bbc0c002f39451dc3fc814d588f32719904fd97/dist_autograd_test.py b/shared/package-files/ef/ef69388714f5f9c1d6bb9c6c0bbc0c002f39451dc3fc814d588f32719904fd97/dist_autograd_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ac87036bc7516eece5dc5cfe072ec8fc8eda2d --- /dev/null +++ b/shared/package-files/ef/ef69388714f5f9c1d6bb9c6c0bbc0c002f39451dc3fc814d588f32719904fd97/dist_autograd_test.py @@ -0,0 +1,114 @@ +# mypy: allow-untyped-defs + + +import torch +import torch.distributed.autograd as dist_autograd +import torch.distributed.rpc as rpc +from torch import Tensor +from torch.distributed.rpc import rpc_async +from torch.testing import FileCheck +from torch.testing._internal.dist_utils import dist_init, worker_name +from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import ( + RpcAgentTestFixture, +) + + +@torch.jit.script +def local_add(t1, t2): + return torch.add(t1, t2) + + +@torch.jit.script +def remote_add(t1, t2, dst: str): # noqa: E999 + return rpc_async(dst, local_add, (t1, t2)).wait() + + +@torch.jit.script +def fork_add(t1, t2, dst: str): + fut = torch.jit._fork(remote_add, t1, t2, dst) + return torch.jit._wait(fut) + + +class JitDistAutogradTest(RpcAgentTestFixture): + @dist_init + def test_get_gradients(self): + + @torch.jit.script + def dist_get_gradients(context_id: int) -> (dict[Tensor, Tensor]): + return dist_autograd.get_gradients(context_id) + + FileCheck().check("get_gradients").run(str(dist_get_gradients.graph)) + with dist_autograd.context() as context_id: + t1 = torch.rand((3, 3), requires_grad=True) + t2 = torch.rand((3, 3), requires_grad=True) + t3 = torch.add(t1, t2) + + dist_autograd.backward(context_id, [t3.sum()]) + grads = dist_get_gradients(context_id) + + self.assertEqual(2, len(grads)) + self.assertIn(t1, grads) + self.assertIn(t2, grads) + self.assertEqual(torch.ones(3, 3), grads[t1]) + self.assertEqual(torch.ones(3, 3), grads[t2]) + + @dist_init + def test_dist_backward(self): + if self.rank != 0: + return + + @torch.jit.script + def dist_backward_script(context_id: int, loss: torch.Tensor): + dist_autograd.backward(context_id, [loss]) + + FileCheck().check("dist_backward").run(str(dist_backward_script.graph)) + with dist_autograd.context() as context_id: + t1 = torch.rand(3, 3, requires_grad=True) + t2 = torch.rand(3, 3, requires_grad=True) + dst_worker_name = worker_name((self.rank + 1) % self.world_size) + loss = rpc.rpc_sync(dst_worker_name, torch.add, args=(t1, t2)).sum() + dist_backward_script(context_id, loss) + + @dist_init + def test_jit_fork_within_context(self): + with dist_autograd.context() as context_id: + t1 = torch.rand((3, 3), requires_grad=True) + t2 = torch.rand((3, 3), requires_grad=True) + dst_worker_name = worker_name((self.rank + 1) % self.world_size) + res = fork_add(t1, t2, dst_worker_name) + loss = res.sum() + dist_autograd.backward(context_id, [loss]) + + grads = dist_autograd.get_gradients(context_id) + self.assertEqual(2, len(grads)) + self.assertIn(t1, grads) + self.assertIn(t2, grads) + + @dist_init + def test_restore_context_after_swtich_to_jit_thread(self): + if self.rank != 0: + return + + @torch.jit.script + def forward_script( + context_id: int, dst_worker_name: str, t1: Tensor, t2: Tensor + ) -> tuple[Tensor, Tensor]: + res1_fut = rpc.rpc_async(dst_worker_name, local_add, (t1, t1)) + res1 = res1_fut.wait() # After this, the script runs in a new JIT thread. + loss1 = res1.sum() + + # SendRpcBackward is not attached, since DistAutogradContext is lost here. + res2_fut = rpc.rpc_async(dst_worker_name, local_add, (t2, t2)) + res2 = res2_fut.wait() + loss2 = res2.sum() + + return loss1, loss2 + + with dist_autograd.context() as context_id: + t1 = torch.ones((2, 3), requires_grad=True) + t2 = torch.ones((2, 3), requires_grad=True) + dst_worker_name = worker_name((self.rank + 1) % self.world_size) + loss0, loss1 = forward_script(context_id, dst_worker_name, t1, t2) + dist_autograd.backward(context_id, [loss0, loss1]) + grad0, grad1 = dist_autograd.get_gradients(context_id) + self.assertEqual(grad0, grad1) diff --git a/shared/package-files/ef/ef6d438a49defe557fd2d96093d8f22a61cbe96fb9313d21d8b286bce6104cf2/arrow.py b/shared/package-files/ef/ef6d438a49defe557fd2d96093d8f22a61cbe96fb9313d21d8b286bce6104cf2/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..530df901a7225bab4afb9f08d06540bc18e91aef --- /dev/null +++ b/shared/package-files/ef/ef6d438a49defe557fd2d96093d8f22a61cbe96fb9313d21d8b286bce6104cf2/arrow.py @@ -0,0 +1,304 @@ +import errno +import io +import os +import secrets +import shutil +from contextlib import suppress +from functools import cached_property, wraps +from urllib.parse import parse_qs + +from fsspec.spec import AbstractFileSystem +from fsspec.utils import ( + get_package_version_without_import, + infer_storage_options, + mirror_from, + tokenize, +) + + +def wrap_exceptions(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except OSError as exception: + if not exception.args: + raise + + message, *args = exception.args + if isinstance(message, str) and "does not exist" in message: + raise FileNotFoundError(errno.ENOENT, message) from exception + else: + raise + + return wrapper + + +PYARROW_VERSION = None + + +class ArrowFSWrapper(AbstractFileSystem): + """FSSpec-compatible wrapper of pyarrow.fs.FileSystem. + + Parameters + ---------- + fs : pyarrow.fs.FileSystem + + """ + + root_marker = "/" + + def __init__(self, fs, **kwargs): + global PYARROW_VERSION + PYARROW_VERSION = get_package_version_without_import("pyarrow") + self.fs = fs + super().__init__(**kwargs) + + @property + def protocol(self): + return self.fs.type_name + + @cached_property + def fsid(self): + return "hdfs_" + tokenize(self.fs.host, self.fs.port) + + @classmethod + def _strip_protocol(cls, path): + ops = infer_storage_options(path) + path = ops["path"] + if path.startswith("//"): + # special case for "hdfs://path" (without the triple slash) + path = path[1:] + return path + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + from pyarrow.fs import FileSelector + + entries = [ + self._make_entry(entry) + for entry in self.fs.get_file_info(FileSelector(path)) + ] + if detail: + return entries + else: + return [entry["name"] for entry in entries] + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + [info] = self.fs.get_file_info([path]) + return self._make_entry(info) + + def exists(self, path): + path = self._strip_protocol(path) + try: + self.info(path) + except FileNotFoundError: + return False + else: + return True + + def _make_entry(self, info): + from pyarrow.fs import FileType + + if info.type is FileType.Directory: + kind = "directory" + elif info.type is FileType.File: + kind = "file" + elif info.type is FileType.NotFound: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path) + else: + kind = "other" + + return { + "name": info.path, + "size": info.size, + "type": kind, + "mtime": info.mtime, + } + + @wrap_exceptions + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + + with self._open(path1, "rb") as lstream: + tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}" + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.fs.move(tmp_fname, path2) + except BaseException: + with suppress(FileNotFoundError): + self.fs.delete_file(tmp_fname) + raise + + @wrap_exceptions + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + self.fs.move(path1, path2) + + @wrap_exceptions + def rm_file(self, path): + path = self._strip_protocol(path) + self.fs.delete_file(path) + + @wrap_exceptions + def rm(self, path, recursive=False, maxdepth=None): + path = self._strip_protocol(path).rstrip("/") + if self.isdir(path): + if recursive: + self.fs.delete_dir(path) + else: + raise ValueError("Can't delete directories without recursive=False") + else: + self.fs.delete_file(path) + + @wrap_exceptions + def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs): + if mode == "rb": + if seekable: + method = self.fs.open_input_file + else: + method = self.fs.open_input_stream + elif mode == "wb": + method = self.fs.open_output_stream + elif mode == "ab": + method = self.fs.open_append_stream + else: + raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}") + + _kwargs = {} + if mode != "rb" or not seekable: + if int(PYARROW_VERSION.split(".")[0]) >= 4: + # disable compression auto-detection + _kwargs["compression"] = None + stream = method(path, **_kwargs) + + return ArrowFile(self, stream, path, mode, block_size, **kwargs) + + @wrap_exceptions + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + self.fs.create_dir(path, recursive=False) + + @wrap_exceptions + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + self.fs.create_dir(path, recursive=True) + + @wrap_exceptions + def rmdir(self, path): + path = self._strip_protocol(path) + self.fs.delete_dir(path) + + @wrap_exceptions + def modified(self, path): + path = self._strip_protocol(path) + return self.fs.get_file_info(path).mtime + + def cat_file(self, path, start=None, end=None, **kwargs): + kwargs["seekable"] = start not in [None, 0] + return super().cat_file(path, start=None, end=None, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + kwargs["seekable"] = False + super().get_file(rpath, lpath, **kwargs) + + +@mirror_from( + "stream", + [ + "read", + "seek", + "tell", + "write", + "readable", + "writable", + "close", + "size", + "seekable", + ], +) +class ArrowFile(io.IOBase): + def __init__(self, fs, stream, path, mode, block_size=None, **kwargs): + self.path = path + self.mode = mode + + self.fs = fs + self.stream = stream + + self.blocksize = self.block_size = block_size + self.kwargs = kwargs + + def __enter__(self): + return self + + def __exit__(self, *args): + return self.close() + + +class HadoopFileSystem(ArrowFSWrapper): + """A wrapper on top of the pyarrow.fs.HadoopFileSystem + to connect it's interface with fsspec""" + + protocol = "hdfs" + + def __init__( + self, + host="default", + port=0, + user=None, + kerb_ticket=None, + replication=3, + extra_conf=None, + **kwargs, + ): + """ + + Parameters + ---------- + host: str + Hostname, IP or "default" to try to read from Hadoop config + port: int + Port to connect on, or default from Hadoop config if 0 + user: str or None + If given, connect as this username + kerb_ticket: str or None + If given, use this ticket for authentication + replication: int + set replication factor of file for write operations. default value is 3. + extra_conf: None or dict + Passed on to HadoopFileSystem + """ + from pyarrow.fs import HadoopFileSystem + + fs = HadoopFileSystem( + host=host, + port=port, + user=user, + kerb_ticket=kerb_ticket, + replication=replication, + extra_conf=extra_conf, + ) + super().__init__(fs=fs, **kwargs) + + @staticmethod + def _get_kwargs_from_urls(path): + ops = infer_storage_options(path) + out = {} + if ops.get("host", None): + out["host"] = ops["host"] + if ops.get("username", None): + out["user"] = ops["username"] + if ops.get("port", None): + out["port"] = ops["port"] + if ops.get("url_query", None): + queries = parse_qs(ops["url_query"]) + if queries.get("replication", None): + out["replication"] = int(queries["replication"][0]) + return out diff --git a/shared/package-files/ef/ef715a18bbd2eaee57fc66897f0bd590694f09be9f618cee0cdc0902281fe731/_sfdp_pattern_19.py b/shared/package-files/ef/ef715a18bbd2eaee57fc66897f0bd590694f09be9f618cee0cdc0902281fe731/_sfdp_pattern_19.py new file mode 100644 index 0000000000000000000000000000000000000000..3cba2215bc7619e367660e47f0f3c27889063fa8 --- /dev/null +++ b/shared/package-files/ef/ef715a18bbd2eaee57fc66897f0bd590694f09be9f618cee0cdc0902281fe731/_sfdp_pattern_19.py @@ -0,0 +1,208 @@ +# mypy: ignore-errors + +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored()) +where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), fma_default, scalar_tensor_default) +div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_19_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_19_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored()) +where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), convert_element_type_default_3, scalar_tensor_default) +div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_19_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_19_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/shared/package-files/ef/ef7363adbdd81fa7c63272fef71d7fae54f8fe319139d339b1521078245a53e0/test_categorical.py b/shared/package-files/ef/ef7363adbdd81fa7c63272fef71d7fae54f8fe319139d339b1521078245a53e0/test_categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..f60ff65536f20458220a763b946198842d9bf07e --- /dev/null +++ b/shared/package-files/ef/ef7363adbdd81fa7c63272fef71d7fae54f8fe319139d339b1521078245a53e0/test_categorical.py @@ -0,0 +1,2169 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + Series, + qcut, +) +import pandas._testing as tm +from pandas.api.typing import SeriesGroupBy +from pandas.tests.groupby import get_groupby_method_args + + +def cartesian_product_for_groupers(result, args, names, fill_value=np.nan): + """Reindex to a cartesian production for the groupers, + preserving the nature (Categorical) of each grouper + """ + + def f(a): + if isinstance(a, (CategoricalIndex, Categorical)): + categories = a.categories + a = Categorical.from_codes( + np.arange(len(categories)), categories=categories, ordered=a.ordered + ) + return a + + index = MultiIndex.from_product(map(f, args), names=names) + return result.reindex(index, fill_value=fill_value).sort_index() + + +_results_for_groupbys_with_missing_categories = { + # This maps the builtin groupby functions to their expected outputs for + # missing categories when they are called on a categorical grouper with + # observed=False. Some functions are expected to return NaN, some zero. + # These expected values can be used across several tests (i.e. they are + # the same for SeriesGroupBy and DataFrameGroupBy) but they should only be + # hardcoded in one place. + "all": np.nan, + "any": np.nan, + "count": 0, + "corrwith": np.nan, + "first": np.nan, + "idxmax": np.nan, + "idxmin": np.nan, + "last": np.nan, + "max": np.nan, + "mean": np.nan, + "median": np.nan, + "min": np.nan, + "nth": np.nan, + "nunique": 0, + "prod": np.nan, + "quantile": np.nan, + "sem": np.nan, + "size": 0, + "skew": np.nan, + "std": np.nan, + "sum": 0, + "var": np.nan, +} + + +def test_apply_use_categorical_name(df): + cats = qcut(df.C, 4) + + def get_stats(group): + return { + "min": group.min(), + "max": group.max(), + "count": group.count(), + "mean": group.mean(), + } + + result = df.groupby(cats, observed=False).D.apply(get_stats) + assert result.index.names[0] == "C" + + +def test_basic(using_infer_string): # TODO: split this test + cats = Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) + + exp_index = CategoricalIndex(list("abcd"), name="b", ordered=True) + expected = DataFrame({"a": [1, 2, 4, np.nan]}, index=exp_index) + result = data.groupby("b", observed=False).mean() + tm.assert_frame_equal(result, expected) + + cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + + # single grouper + gb = df.groupby("A", observed=False) + exp_idx = CategoricalIndex(["a", "b", "z"], name="A", ordered=True) + expected = DataFrame({"values": Series([3, 7, 0], index=exp_idx)}) + result = gb.sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + # GH 8623 + x = DataFrame( + [[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]], + columns=["person_id", "person_name"], + ) + x["person_name"] = Categorical(x.person_name) + + g = x.groupby(["person_id"], observed=False) + result = g.transform(lambda x: x) + tm.assert_frame_equal(result, x[["person_name"]]) + + result = x.drop_duplicates("person_name") + expected = x.iloc[[0, 1]] + tm.assert_frame_equal(result, expected) + + def f(x): + return x.drop_duplicates("person_name").iloc[0] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + result = g.apply(f) + expected = x.iloc[[0, 1]].copy() + expected.index = Index([1, 2], name="person_id") + dtype = "string[pyarrow_numpy]" if using_infer_string else object + expected["person_name"] = expected["person_name"].astype(dtype) + tm.assert_frame_equal(result, expected) + + # GH 9921 + # Monotonic + df = DataFrame({"a": [5, 15, 25]}) + c = pd.cut(df.a, bins=[0, 10, 20, 30, 40]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.a.groupby(c, observed=False).transform(sum) + tm.assert_series_equal(result, df["a"]) + + tm.assert_series_equal( + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] + ) + msg = "using DataFrameGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.groupby(c, observed=False).transform(sum) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + gbc = df.groupby(c, observed=False) + result = gbc.transform(lambda xs: np.max(xs, axis=0)) + tm.assert_frame_equal(result, df[["a"]]) + + result2 = gbc.transform(lambda xs: np.max(xs, axis=0)) + msg = "using DataFrameGroupBy.max" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result3 = gbc.transform(max) + result4 = gbc.transform(np.maximum.reduce) + result5 = gbc.transform(lambda xs: np.maximum.reduce(xs)) + tm.assert_frame_equal(result2, df[["a"]], check_dtype=False) + tm.assert_frame_equal(result3, df[["a"]], check_dtype=False) + tm.assert_frame_equal(result4, df[["a"]]) + tm.assert_frame_equal(result5, df[["a"]]) + + # Filter + tm.assert_series_equal(df.a.groupby(c, observed=False).filter(np.all), df["a"]) + tm.assert_frame_equal(df.groupby(c, observed=False).filter(np.all), df) + + # Non-monotonic + df = DataFrame({"a": [5, 15, 25, -5]}) + c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.a.groupby(c, observed=False).transform(sum) + tm.assert_series_equal(result, df["a"]) + + tm.assert_series_equal( + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] + ) + msg = "using DataFrameGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.groupby(c, observed=False).transform(sum) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + tm.assert_frame_equal( + df.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df[["a"]] + ) + + # GH 9603 + df = DataFrame({"a": [1, 0, 0, 0]}) + c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list("abcd"))) + result = df.groupby(c, observed=False).apply(len) + + exp_index = CategoricalIndex(c.values.categories, ordered=c.values.ordered) + expected = Series([1, 0, 0, 0], index=exp_index) + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + # more basic + levels = ["foo", "bar", "baz", "qux"] + codes = np.random.default_rng(2).integers(0, 4, size=100) + + cats = Categorical.from_codes(codes, levels, ordered=True) + + data = DataFrame(np.random.default_rng(2).standard_normal((100, 4))) + + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + exp_idx = CategoricalIndex(levels, categories=cats.categories, ordered=True) + expected = expected.reindex(exp_idx) + + tm.assert_frame_equal(result, expected) + + grouped = data.groupby(cats, observed=False) + desc_result = grouped.describe() + + idx = cats.codes.argsort() + ord_labels = np.asarray(cats).take(idx) + ord_data = data.take(idx) + + exp_cats = Categorical( + ord_labels, ordered=True, categories=["foo", "bar", "baz", "qux"] + ) + expected = ord_data.groupby(exp_cats, sort=False, observed=False).describe() + tm.assert_frame_equal(desc_result, expected) + + # GH 10460 + expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = CategoricalIndex(expc) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(0)), exp + ) + exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(1)), exp + ) + + +def test_level_get_group(observed): + # GH15155 + df = DataFrame( + data=np.arange(2, 22, 2), + index=MultiIndex( + levels=[CategoricalIndex(["a", "b"]), range(10)], + codes=[[0] * 5 + [1] * 5, range(10)], + names=["Index1", "Index2"], + ), + ) + g = df.groupby(level=["Index1"], observed=observed) + + # expected should equal test.loc[["a"]] + # GH15166 + expected = DataFrame( + data=np.arange(2, 12, 2), + index=MultiIndex( + levels=[CategoricalIndex(["a", "b"]), range(5)], + codes=[[0] * 5, range(5)], + names=["Index1", "Index2"], + ), + ) + msg = "you will need to pass a length-1 tuple" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#25971 - warn when not passing a length-1 tuple + result = g.get_group("a") + + tm.assert_frame_equal(result, expected) + + +def test_sorting_with_different_categoricals(): + # GH 24271 + df = DataFrame( + { + "group": ["A"] * 6 + ["B"] * 6, + "dose": ["high", "med", "low"] * 4, + "outcomes": np.arange(12.0), + } + ) + + df.dose = Categorical(df.dose, categories=["low", "med", "high"], ordered=True) + + result = df.groupby("group")["dose"].value_counts() + result = result.sort_index(level=0, sort_remaining=True) + index = ["low", "med", "high", "low", "med", "high"] + index = Categorical(index, categories=["low", "med", "high"], ordered=True) + index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)] + index = MultiIndex.from_arrays(index, names=["group", "dose"]) + expected = Series([2] * 6, index=index, name="count") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_apply(ordered): + # GH 10138 + + dense = Categorical(list("abc"), ordered=ordered) + + # 'b' is in the categories but not in the list + missing = Categorical(list("aaa"), categories=["a", "b"], ordered=ordered) + values = np.arange(len(dense)) + df = DataFrame({"missing": missing, "dense": dense, "values": values}) + grouped = df.groupby(["missing", "dense"], observed=True) + + # missing category 'b' should still exist in the output index + idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = DataFrame([0, 1, 2.0], index=idx, columns=["values"]) + + result = grouped.apply(lambda x: np.mean(x, axis=0)) + tm.assert_frame_equal(result, expected) + + result = grouped.mean() + tm.assert_frame_equal(result, expected) + + msg = "using DataFrameGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = grouped.agg(np.mean) + tm.assert_frame_equal(result, expected) + + # but for transform we should still get back the original index + idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = Series(1, index=idx) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + result = grouped.apply(lambda x: 1) + tm.assert_series_equal(result, expected) + + +def test_observed(observed): + # multiple groupers, don't re-expand the output space + # of the grouper + # gh-14942 (implement) + # gh-10132 (back-compat) + # gh-8138 (back-compat) + # gh-8869 + + cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + df["C"] = ["foo", "bar"] * 2 + + # multiple groupers with a non-cat + gb = df.groupby(["A", "B", "C"], observed=observed) + exp_index = MultiIndex.from_arrays( + [cat1, cat2, ["foo", "bar"] * 2], names=["A", "B", "C"] + ) + expected = DataFrame({"values": Series([1, 2, 3, 4], index=exp_index)}).sort_index() + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, [cat1, cat2, ["foo", "bar"]], list("ABC"), fill_value=0 + ) + + tm.assert_frame_equal(result, expected) + + gb = df.groupby(["A", "B"], observed=observed) + exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) + expected = DataFrame( + {"values": [1, 2, 3, 4], "C": ["foo", "bar", "foo", "bar"]}, index=exp_index + ) + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, [cat1, cat2], list("AB"), fill_value=0 + ) + + tm.assert_frame_equal(result, expected) + + # https://github.com/pandas-dev/pandas/issues/8138 + d = { + "cat": Categorical( + ["a", "b", "a", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 1, 2, 2], + "val": [10, 20, 30, 40], + } + df = DataFrame(d) + + # Grouping on a single column + groups_single_key = df.groupby("cat", observed=observed) + result = groups_single_key.mean() + + exp_index = CategoricalIndex( + list("ab"), name="cat", categories=list("abc"), ordered=True + ) + expected = DataFrame({"ints": [1.5, 1.5], "val": [20.0, 30]}, index=exp_index) + if not observed: + index = CategoricalIndex( + list("abc"), name="cat", categories=list("abc"), ordered=True + ) + expected = expected.reindex(index) + + tm.assert_frame_equal(result, expected) + + # Grouping on two columns + groups_double_key = df.groupby(["cat", "ints"], observed=observed) + result = groups_double_key.agg("mean") + expected = DataFrame( + { + "val": [10.0, 30.0, 20.0, 40.0], + "cat": Categorical( + ["a", "a", "b", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 2, 1, 2], + } + ).set_index(["cat", "ints"]) + if not observed: + expected = cartesian_product_for_groupers( + expected, [df.cat.values, [1, 2]], ["cat", "ints"] + ) + + tm.assert_frame_equal(result, expected) + + # GH 10132 + for key in [("a", 1), ("b", 2), ("b", 1), ("a", 2)]: + c, i = key + result = groups_double_key.get_group(key) + expected = df[(df.cat == c) & (df.ints == i)] + tm.assert_frame_equal(result, expected) + + # gh-8869 + # with as_index + d = { + "foo": [10, 8, 4, 8, 4, 1, 1], + "bar": [10, 20, 30, 40, 50, 60, 70], + "baz": ["d", "c", "e", "a", "a", "d", "c"], + } + df = DataFrame(d) + cat = pd.cut(df["foo"], np.linspace(0, 10, 3)) + df["range"] = cat + groups = df.groupby(["range", "baz"], as_index=False, observed=observed) + result = groups.agg("mean") + + groups2 = df.groupby(["range", "baz"], as_index=True, observed=observed) + expected = groups2.agg("mean").reset_index() + tm.assert_frame_equal(result, expected) + + +def test_observed_codes_remap(observed): + d = {"C1": [3, 3, 4, 5], "C2": [1, 2, 3, 4], "C3": [10, 100, 200, 34]} + df = DataFrame(d) + values = pd.cut(df["C1"], [1, 2, 3, 6]) + values.name = "cat" + groups_double_key = df.groupby([values, "C2"], observed=observed) + + idx = MultiIndex.from_arrays([values, [1, 2, 3, 4]], names=["cat", "C2"]) + expected = DataFrame( + {"C1": [3.0, 3.0, 4.0, 5.0], "C3": [10.0, 100.0, 200.0, 34.0]}, index=idx + ) + if not observed: + expected = cartesian_product_for_groupers( + expected, [values.values, [1, 2, 3, 4]], ["cat", "C2"] + ) + + result = groups_double_key.agg("mean") + tm.assert_frame_equal(result, expected) + + +def test_observed_perf(): + # we create a cartesian product, so this is + # non-performant if we don't use observed values + # gh-14942 + df = DataFrame( + { + "cat": np.random.default_rng(2).integers(0, 255, size=30000), + "int_id": np.random.default_rng(2).integers(0, 255, size=30000), + "other_id": np.random.default_rng(2).integers(0, 10000, size=30000), + "foo": 0, + } + ) + df["cat"] = df.cat.astype(str).astype("category") + + grouped = df.groupby(["cat", "int_id", "other_id"], observed=True) + result = grouped.count() + assert result.index.levels[0].nunique() == df.cat.nunique() + assert result.index.levels[1].nunique() == df.int_id.nunique() + assert result.index.levels[2].nunique() == df.other_id.nunique() + + +def test_observed_groups(observed): + # gh-20583 + # test that we have the appropriate groups + + cat = Categorical(["a", "c", "a"], categories=["a", "b", "c"]) + df = DataFrame({"cat": cat, "vals": [1, 2, 3]}) + g = df.groupby("cat", observed=observed) + + result = g.groups + if observed: + expected = {"a": Index([0, 2], dtype="int64"), "c": Index([1], dtype="int64")} + else: + expected = { + "a": Index([0, 2], dtype="int64"), + "b": Index([], dtype="int64"), + "c": Index([1], dtype="int64"), + } + + tm.assert_dict_equal(result, expected) + + +@pytest.mark.parametrize( + "keys, expected_values, expected_index_levels", + [ + ("a", [15, 9, 0], CategoricalIndex([1, 2, 3], name="a")), + ( + ["a", "b"], + [7, 8, 0, 0, 0, 9, 0, 0, 0], + [CategoricalIndex([1, 2, 3], name="a"), Index([4, 5, 6])], + ), + ( + ["a", "a2"], + [15, 0, 0, 0, 9, 0, 0, 0, 0], + [ + CategoricalIndex([1, 2, 3], name="a"), + CategoricalIndex([1, 2, 3], name="a"), + ], + ), + ], +) +@pytest.mark.parametrize("test_series", [True, False]) +def test_unobserved_in_index(keys, expected_values, expected_index_levels, test_series): + # GH#49354 - ensure unobserved cats occur when grouping by index levels + df = DataFrame( + { + "a": Categorical([1, 1, 2], categories=[1, 2, 3]), + "a2": Categorical([1, 1, 2], categories=[1, 2, 3]), + "b": [4, 5, 6], + "c": [7, 8, 9], + } + ).set_index(["a", "a2"]) + if "b" not in keys: + # Only keep b when it is used for grouping for consistent columns in the result + df = df.drop(columns="b") + + gb = df.groupby(keys, observed=False) + if test_series: + gb = gb["c"] + result = gb.sum() + + if len(keys) == 1: + index = expected_index_levels + else: + codes = [[0, 0, 0, 1, 1, 1, 2, 2, 2], 3 * [0, 1, 2]] + index = MultiIndex( + expected_index_levels, + codes=codes, + names=keys, + ) + expected = DataFrame({"c": expected_values}, index=index) + if test_series: + expected = expected["c"] + tm.assert_equal(result, expected) + + +def test_observed_groups_with_nan(observed): + # GH 24740 + df = DataFrame( + { + "cat": Categorical(["a", np.nan, "a"], categories=["a", "b", "d"]), + "vals": [1, 2, 3], + } + ) + g = df.groupby("cat", observed=observed) + result = g.groups + if observed: + expected = {"a": Index([0, 2], dtype="int64")} + else: + expected = { + "a": Index([0, 2], dtype="int64"), + "b": Index([], dtype="int64"), + "d": Index([], dtype="int64"), + } + tm.assert_dict_equal(result, expected) + + +def test_observed_nth(): + # GH 26385 + cat = Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"]) + ser = Series([1, 2, 3]) + df = DataFrame({"cat": cat, "ser": ser}) + + result = df.groupby("cat", observed=False)["ser"].nth(0) + expected = df["ser"].iloc[[0]] + tm.assert_series_equal(result, expected) + + +def test_dataframe_categorical_with_nan(observed): + # GH 21151 + s1 = Categorical([np.nan, "a", np.nan, "a"], categories=["a", "b", "c"]) + s2 = Series([1, 2, 3, 4]) + df = DataFrame({"s1": s1, "s2": s2}) + result = df.groupby("s1", observed=observed).first().reset_index() + if observed: + expected = DataFrame( + {"s1": Categorical(["a"], categories=["a", "b", "c"]), "s2": [2]} + ) + else: + expected = DataFrame( + { + "s1": Categorical(["a", "b", "c"], categories=["a", "b", "c"]), + "s2": [2, np.nan, np.nan], + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +@pytest.mark.parametrize("observed", [True, False]) +@pytest.mark.parametrize("sort", [True, False]) +def test_dataframe_categorical_ordered_observed_sort(ordered, observed, sort): + # GH 25871: Fix groupby sorting on ordered Categoricals + # GH 25167: Groupby with observed=True doesn't sort + + # Build a dataframe with cat having one unobserved category ('missing'), + # and a Series with identical values + label = Categorical( + ["d", "a", "b", "a", "d", "b"], + categories=["a", "b", "missing", "d"], + ordered=ordered, + ) + val = Series(["d", "a", "b", "a", "d", "b"]) + df = DataFrame({"label": label, "val": val}) + + # aggregate on the Categorical + result = df.groupby("label", observed=observed, sort=sort)["val"].aggregate("first") + + # If ordering works, we expect index labels equal to aggregation results, + # except for 'observed=False': label 'missing' has aggregation None + label = Series(result.index.array, dtype="object") + aggr = Series(result.array) + if not observed: + aggr[aggr.isna()] = "missing" + if not all(label == aggr): + msg = ( + "Labels and aggregation results not consistently sorted\n" + f"for (ordered={ordered}, observed={observed}, sort={sort})\n" + f"Result:\n{result}" + ) + assert False, msg + + +def test_datetime(): + # GH9049: ensure backward compatibility + levels = pd.date_range("2014-01-01", periods=4) + codes = np.random.default_rng(2).integers(0, 4, size=100) + + cats = Categorical.from_codes(codes, levels, ordered=True) + + data = DataFrame(np.random.default_rng(2).standard_normal((100, 4))) + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + expected = expected.reindex(levels) + expected.index = CategoricalIndex( + expected.index, categories=expected.index, ordered=True + ) + + tm.assert_frame_equal(result, expected) + + grouped = data.groupby(cats, observed=False) + desc_result = grouped.describe() + + idx = cats.codes.argsort() + ord_labels = cats.take(idx) + ord_data = data.take(idx) + expected = ord_data.groupby(ord_labels, observed=False).describe() + tm.assert_frame_equal(desc_result, expected) + tm.assert_index_equal(desc_result.index, expected.index) + tm.assert_index_equal( + desc_result.index.get_level_values(0), expected.index.get_level_values(0) + ) + + # GH 10460 + expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = CategoricalIndex(expc) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(0)), exp + ) + exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(1)), exp + ) + + +def test_categorical_index(): + s = np.random.default_rng(2) + levels = ["foo", "bar", "baz", "qux"] + codes = s.integers(0, 4, size=20) + cats = Categorical.from_codes(codes, levels, ordered=True) + df = DataFrame(np.repeat(np.arange(20), 4).reshape(-1, 4), columns=list("abcd")) + df["cats"] = cats + + # with a cat index + result = df.set_index("cats").groupby(level=0, observed=False).sum() + expected = df[list("abcd")].groupby(cats.codes, observed=False).sum() + expected.index = CategoricalIndex( + Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" + ) + tm.assert_frame_equal(result, expected) + + # with a cat column, should produce a cat index + result = df.groupby("cats", observed=False).sum() + expected = df[list("abcd")].groupby(cats.codes, observed=False).sum() + expected.index = CategoricalIndex( + Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" + ) + tm.assert_frame_equal(result, expected) + + +def test_describe_categorical_columns(): + # GH 11558 + cats = CategoricalIndex( + ["qux", "foo", "baz", "bar"], + categories=["foo", "bar", "baz", "qux"], + ordered=True, + ) + df = DataFrame(np.random.default_rng(2).standard_normal((20, 4)), columns=cats) + result = df.groupby([1, 2, 3, 4] * 5).describe() + + tm.assert_index_equal(result.stack(future_stack=True).columns, cats) + tm.assert_categorical_equal( + result.stack(future_stack=True).columns.values, cats.values + ) + + +def test_unstack_categorical(): + # GH11558 (example is taken from the original issue) + df = DataFrame( + {"a": range(10), "medium": ["A", "B"] * 5, "artist": list("XYXXY") * 2} + ) + df["medium"] = df["medium"].astype("category") + + gcat = df.groupby(["artist", "medium"], observed=False)["a"].count().unstack() + result = gcat.describe() + + exp_columns = CategoricalIndex(["A", "B"], ordered=False, name="medium") + tm.assert_index_equal(result.columns, exp_columns) + tm.assert_categorical_equal(result.columns.values, exp_columns.values) + + result = gcat["A"] + gcat["B"] + expected = Series([6, 4], index=Index(["X", "Y"], name="artist")) + tm.assert_series_equal(result, expected) + + +def test_bins_unequal_len(): + # GH3011 + series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4]) + bins = pd.cut(series.dropna().values, 4) + + # len(bins) != len(series) here + with pytest.raises(ValueError, match="Grouper and axis must be same length"): + series.groupby(bins).mean() + + +@pytest.mark.parametrize( + ["series", "data"], + [ + # Group a series with length and index equal to those of the grouper. + (Series(range(4)), {"A": [0, 3], "B": [1, 2]}), + # Group a series with length equal to that of the grouper and index unequal to + # that of the grouper. + (Series(range(4)).rename(lambda idx: idx + 1), {"A": [2], "B": [0, 1]}), + # GH44179: Group a series with length unequal to that of the grouper. + (Series(range(7)), {"A": [0, 3], "B": [1, 2]}), + ], +) +def test_categorical_series(series, data): + # Group the given series by a series with categorical data type such that group A + # takes indices 0 and 3 and group B indices 1 and 2, obtaining the values mapped in + # the given data. + groupby = series.groupby(Series(list("ABBA"), dtype="category"), observed=False) + result = groupby.aggregate(list) + expected = Series(data, index=CategoricalIndex(data.keys())) + tm.assert_series_equal(result, expected) + + +def test_as_index(): + # GH13204 + df = DataFrame( + { + "cat": Categorical([1, 2, 2], [1, 2, 3]), + "A": [10, 11, 11], + "B": [101, 102, 103], + } + ) + result = df.groupby(["cat", "A"], as_index=False, observed=True).sum() + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 11], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + tm.assert_frame_equal(result, expected) + + # function grouper + f = lambda r: df.loc[r, "A"] + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["cat", f], as_index=False, observed=True).sum() + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 22], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + tm.assert_frame_equal(result, expected) + + # another not in-axis grouper (conflicting names in index) + s = Series(["a", "b", "b"], name="cat") + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["cat", s], as_index=False, observed=True).sum() + tm.assert_frame_equal(result, expected) + + # is original index dropped? + group_columns = ["cat", "A"] + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 11], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + + for name in [None, "X", "B"]: + df.index = Index(list("abc"), name=name) + result = df.groupby(group_columns, as_index=False, observed=True).sum() + + tm.assert_frame_equal(result, expected) + + +def test_preserve_categories(): + # GH-13179 + categories = list("abc") + + # ordered=True + df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)}) + sort_index = CategoricalIndex(categories, categories, ordered=True, name="A") + nosort_index = CategoricalIndex(list("bac"), categories, ordered=True, name="A") + tm.assert_index_equal( + df.groupby("A", sort=True, observed=False).first().index, sort_index + ) + # GH#42482 - don't sort result when sort=False, even when ordered=True + tm.assert_index_equal( + df.groupby("A", sort=False, observed=False).first().index, nosort_index + ) + + # ordered=False + df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)}) + sort_index = CategoricalIndex(categories, categories, ordered=False, name="A") + # GH#48749 - don't change order of categories + # GH#42482 - don't sort result when sort=False, even when ordered=True + nosort_index = CategoricalIndex(list("bac"), list("abc"), ordered=False, name="A") + tm.assert_index_equal( + df.groupby("A", sort=True, observed=False).first().index, sort_index + ) + tm.assert_index_equal( + df.groupby("A", sort=False, observed=False).first().index, nosort_index + ) + + +def test_preserve_categorical_dtype(): + # GH13743, GH13854 + df = DataFrame( + { + "A": [1, 2, 1, 1, 2], + "B": [10, 16, 22, 28, 34], + "C1": Categorical(list("abaab"), categories=list("bac"), ordered=False), + "C2": Categorical(list("abaab"), categories=list("bac"), ordered=True), + } + ) + # single grouper + exp_full = DataFrame( + { + "A": [2.0, 1.0, np.nan], + "B": [25.0, 20.0, np.nan], + "C1": Categorical(list("bac"), categories=list("bac"), ordered=False), + "C2": Categorical(list("bac"), categories=list("bac"), ordered=True), + } + ) + for col in ["C1", "C2"]: + result1 = df.groupby(by=col, as_index=False, observed=False).mean( + numeric_only=True + ) + result2 = ( + df.groupby(by=col, as_index=True, observed=False) + .mean(numeric_only=True) + .reset_index() + ) + expected = exp_full.reindex(columns=result1.columns) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, expected) + + +@pytest.mark.parametrize( + "func, values", + [ + ("first", ["second", "first"]), + ("last", ["fourth", "third"]), + ("min", ["fourth", "first"]), + ("max", ["second", "third"]), + ], +) +def test_preserve_on_ordered_ops(func, values): + # gh-18502 + # preserve the categoricals on ops + c = Categorical(["first", "second", "third", "fourth"], ordered=True) + df = DataFrame({"payload": [-1, -2, -1, -2], "col": c}) + g = df.groupby("payload") + result = getattr(g, func)() + expected = DataFrame( + {"payload": [-2, -1], "col": Series(values, dtype=c.dtype)} + ).set_index("payload") + tm.assert_frame_equal(result, expected) + + # we should also preserve categorical for SeriesGroupBy + sgb = df.groupby("payload")["col"] + result = getattr(sgb, func)() + expected = expected["col"] + tm.assert_series_equal(result, expected) + + +def test_categorical_no_compress(): + data = Series(np.random.default_rng(2).standard_normal(9)) + + codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) + cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True) + + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean() + + exp.index = CategoricalIndex( + exp.index, categories=cats.categories, ordered=cats.ordered + ) + tm.assert_series_equal(result, exp) + + codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3]) + cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True) + + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean().reindex(cats.categories) + exp.index = CategoricalIndex( + exp.index, categories=cats.categories, ordered=cats.ordered + ) + tm.assert_series_equal(result, exp) + + cats = Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) + + result = data.groupby("b", observed=False).mean() + result = result["a"].values + exp = np.array([1, 2, 4, np.nan]) + tm.assert_numpy_array_equal(result, exp) + + +def test_groupby_empty_with_category(): + # GH-9614 + # test fix for when group by on None resulted in + # coercion of dtype categorical -> float + df = DataFrame({"A": [None] * 3, "B": Categorical(["train", "train", "test"])}) + result = df.groupby("A").first()["B"] + expected = Series( + Categorical([], categories=["test", "train"]), + index=Series([], dtype="object", name="A"), + name="B", + ) + tm.assert_series_equal(result, expected) + + +def test_sort(): + # https://stackoverflow.com/questions/23814368/sorting-pandas- + # categorical-labels-after-groupby + # This should result in a properly sorted Series so that the plot + # has a sorted x axis + # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar') + + df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)}) + labels = [f"{i} - {i+499}" for i in range(0, 10000, 500)] + cat_labels = Categorical(labels, labels) + + df = df.sort_values(by=["value"], ascending=True) + df["value_group"] = pd.cut( + df.value, range(0, 10500, 500), right=False, labels=cat_labels + ) + + res = df.groupby(["value_group"], observed=False)["value_group"].count() + exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))] + exp.index = CategoricalIndex(exp.index, name=exp.index.name) + tm.assert_series_equal(res, exp) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_sort2(sort, ordered): + # dataframe groupby sort was being ignored # GH 8868 + # GH#48749 - don't change order of categories + # GH#42482 - don't sort result when sort=False, even when ordered=True + df = DataFrame( + [ + ["(7.5, 10]", 10, 10], + ["(7.5, 10]", 8, 20], + ["(2.5, 5]", 5, 30], + ["(5, 7.5]", 6, 40], + ["(2.5, 5]", 4, 50], + ["(0, 2.5]", 1, 60], + ["(5, 7.5]", 7, 70], + ], + columns=["range", "foo", "bar"], + ) + df["range"] = Categorical(df["range"], ordered=ordered) + result = df.groupby("range", sort=sort, observed=False).first() + + if sort: + data_values = [[1, 60], [5, 30], [6, 40], [10, 10]] + index_values = ["(0, 2.5]", "(2.5, 5]", "(5, 7.5]", "(7.5, 10]"] + else: + data_values = [[10, 10], [5, 30], [6, 40], [1, 60]] + index_values = ["(7.5, 10]", "(2.5, 5]", "(5, 7.5]", "(0, 2.5]"] + expected = DataFrame( + data_values, + columns=["foo", "bar"], + index=CategoricalIndex(index_values, name="range", ordered=ordered), + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_sort_datetimelike(sort, ordered): + # GH10505 + # GH#42482 - don't sort result when sort=False, even when ordered=True + + # use same data as test_groupby_sort_categorical, which category is + # corresponding to datetime.month + df = DataFrame( + { + "dt": [ + datetime(2011, 7, 1), + datetime(2011, 7, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 2, 1), + datetime(2011, 1, 1), + datetime(2011, 5, 1), + ], + "foo": [10, 8, 5, 6, 4, 1, 7], + "bar": [10, 20, 30, 40, 50, 60, 70], + }, + columns=["dt", "foo", "bar"], + ) + + # ordered=True + df["dt"] = Categorical(df["dt"], ordered=ordered) + if sort: + data_values = [[1, 60], [5, 30], [6, 40], [10, 10]] + index_values = [ + datetime(2011, 1, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 7, 1), + ] + else: + data_values = [[10, 10], [5, 30], [6, 40], [1, 60]] + index_values = [ + datetime(2011, 7, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 1, 1), + ] + expected = DataFrame( + data_values, + columns=["foo", "bar"], + index=CategoricalIndex(index_values, name="dt", ordered=ordered), + ) + result = df.groupby("dt", sort=sort, observed=False).first() + tm.assert_frame_equal(result, expected) + + +def test_empty_sum(): + # https://github.com/pandas-dev/pandas/issues/18678 + df = DataFrame( + {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]} + ) + expected_idx = CategoricalIndex(["a", "b", "c"], name="A") + + # 0 by default + result = df.groupby("A", observed=False).B.sum() + expected = Series([3, 1, 0], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=0 + result = df.groupby("A", observed=False).B.sum(min_count=0) + expected = Series([3, 1, 0], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=1 + result = df.groupby("A", observed=False).B.sum(min_count=1) + expected = Series([3, 1, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count>1 + result = df.groupby("A", observed=False).B.sum(min_count=2) + expected = Series([3, np.nan, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + +def test_empty_prod(): + # https://github.com/pandas-dev/pandas/issues/18678 + df = DataFrame( + {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]} + ) + + expected_idx = CategoricalIndex(["a", "b", "c"], name="A") + + # 1 by default + result = df.groupby("A", observed=False).B.prod() + expected = Series([2, 1, 1], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=0 + result = df.groupby("A", observed=False).B.prod(min_count=0) + expected = Series([2, 1, 1], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=1 + result = df.groupby("A", observed=False).B.prod(min_count=1) + expected = Series([2, 1, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + +def test_groupby_multiindex_categorical_datetime(): + # https://github.com/pandas-dev/pandas/issues/21390 + + df = DataFrame( + { + "key1": Categorical(list("abcbabcba")), + "key2": Categorical( + list(pd.date_range("2018-06-01 00", freq="1min", periods=3)) * 3 + ), + "values": np.arange(9), + } + ) + result = df.groupby(["key1", "key2"], observed=False).mean() + + idx = MultiIndex.from_product( + [ + Categorical(["a", "b", "c"]), + Categorical(pd.date_range("2018-06-01 00", freq="1min", periods=3)), + ], + names=["key1", "key2"], + ) + expected = DataFrame({"values": [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "as_index, expected", + [ + ( + True, + Series( + index=MultiIndex.from_arrays( + [Series([1, 1, 2], dtype="category"), [1, 2, 2]], names=["a", "b"] + ), + data=[1, 2, 3], + name="x", + ), + ), + ( + False, + DataFrame( + { + "a": Series([1, 1, 2], dtype="category"), + "b": [1, 2, 2], + "x": [1, 2, 3], + } + ), + ), + ], +) +def test_groupby_agg_observed_true_single_column(as_index, expected): + # GH-23970 + df = DataFrame( + {"a": Series([1, 1, 2], dtype="category"), "b": [1, 2, 2], "x": [1, 2, 3]} + ) + + result = df.groupby(["a", "b"], as_index=as_index, observed=True)["x"].sum() + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("fill_value", [None, np.nan, pd.NaT]) +def test_shift(fill_value): + ct = Categorical( + ["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False + ) + expected = Categorical( + [None, "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False + ) + res = ct.shift(1, fill_value=fill_value) + tm.assert_equal(res, expected) + + +@pytest.fixture +def df_cat(df): + """ + DataFrame with multiple categorical columns and a column of integers. + Shortened so as not to contain all possible combinations of categories. + Useful for testing `observed` kwarg functionality on GroupBy objects. + + Parameters + ---------- + df: DataFrame + Non-categorical, longer DataFrame from another fixture, used to derive + this one + + Returns + ------- + df_cat: DataFrame + """ + df_cat = df.copy()[:4] # leave out some groups + df_cat["A"] = df_cat["A"].astype("category") + df_cat["B"] = df_cat["B"].astype("category") + df_cat["C"] = Series([1, 2, 3, 4]) + df_cat = df_cat.drop(["D"], axis=1) + return df_cat + + +@pytest.mark.parametrize("operation", ["agg", "apply"]) +def test_seriesgroupby_observed_true(df_cat, operation): + # GH#24880 + # GH#49223 - order of results was wrong when grouping by index levels + lev_a = Index(["bar", "bar", "foo", "foo"], dtype=df_cat["A"].dtype, name="A") + lev_b = Index(["one", "three", "one", "two"], dtype=df_cat["B"].dtype, name="B") + index = MultiIndex.from_arrays([lev_a, lev_b]) + expected = Series(data=[2, 4, 1, 3], index=index, name="C").sort_index() + + grouped = df_cat.groupby(["A", "B"], observed=True)["C"] + msg = "using np.sum" if operation == "apply" else "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("operation", ["agg", "apply"]) +@pytest.mark.parametrize("observed", [False, None]) +def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation): + # GH 24880 + # GH#49223 - order of results was wrong when grouping by index levels + index, _ = MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + ], + names=["A", "B"], + ).sortlevel() + + expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C") + if operation == "agg": + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = expected.fillna(0, downcast="infer") + grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] + msg = "using SeriesGroupBy.sum" if operation == "agg" else "using np.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "observed, index, data", + [ + ( + True, + MultiIndex.from_arrays( + [ + Index(["bar"] * 4 + ["foo"] * 4, dtype="category", name="A"), + Index( + ["one", "one", "three", "three", "one", "one", "two", "two"], + dtype="category", + name="B", + ), + Index(["min", "max"] * 4), + ] + ), + [2, 2, 4, 4, 1, 1, 3, 3], + ), + ( + False, + MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + Index(["min", "max"]), + ], + names=["A", "B", None], + ), + [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3], + ), + ( + None, + MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + Index(["min", "max"]), + ], + names=["A", "B", None], + ), + [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3], + ), + ], +) +def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data): + # GH 24880 + expected = Series(data=data, index=index, name="C") + result = df_cat.groupby(["A", "B"], observed=observed)["C"].apply( + lambda x: {"min": x.min(), "max": x.max()} + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_series_dataframe_consistent(df_cat): + # GH 20416 + expected = df_cat.groupby(["A", "B"], observed=False)["C"].mean() + result = df_cat.groupby(["A", "B"], observed=False).mean()["C"] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])]) +def test_groupby_categorical_axis_1(code): + # GH 13420 + df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]}) + cat = Categorical.from_codes(code, categories=list("abc")) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(cat, axis=1, observed=False) + result = gb.mean() + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.T.groupby(cat, axis=0, observed=False) + expected = gb2.mean().T + tm.assert_frame_equal(result, expected) + + +def test_groupby_cat_preserves_structure(observed, ordered): + # GH 28787 + df = DataFrame( + {"Name": Categorical(["Bob", "Greg"], ordered=ordered), "Item": [1, 2]}, + columns=["Name", "Item"], + ) + expected = df.copy() + + result = ( + df.groupby("Name", observed=observed) + .agg(DataFrame.sum, skipna=True) + .reset_index() + ) + + tm.assert_frame_equal(result, expected) + + +def test_get_nonexistent_category(): + # Accessing a Category that is not in the dataframe + df = DataFrame({"var": ["a", "a", "b", "b"], "val": range(4)}) + with pytest.raises(KeyError, match="'vau'"): + df.groupby("var").apply( + lambda rows: DataFrame( + {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]} + ) + ) + + +def test_series_groupby_on_2_categoricals_unobserved(reduction_func, observed): + # GH 17605 + if reduction_func == "ngroup": + pytest.skip("ngroup is not truly a reduction") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABCD")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABCD")), + "value": [0.1] * 4, + } + ) + args = get_groupby_method_args(reduction_func, df) + + expected_length = 4 if observed else 16 + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=observed)["value"] + + if reduction_func == "corrwith": + # TODO: implemented SeriesGroupBy.corrwith. See GH 32293 + assert not hasattr(series_groupby, reduction_func) + return + + agg = getattr(series_groupby, reduction_func) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + result = agg(*args) + + assert len(result) == expected_length + + +def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( + reduction_func, request +): + # GH 17605 + # Tests whether the unobserved categories in the result contain 0 or NaN + + if reduction_func == "ngroup": + pytest.skip("ngroup is not truly a reduction") + + if reduction_func == "corrwith": # GH 32293 + mark = pytest.mark.xfail( + reason="TODO: implemented SeriesGroupBy.corrwith. See GH 32293" + ) + request.applymarker(mark) + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABC")), + "value": [0.1] * 4, + } + ) + unobserved = [tuple("AC"), tuple("BC"), tuple("CA"), tuple("CB"), tuple("CC")] + args = get_groupby_method_args(reduction_func, df) + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=False)["value"] + agg = getattr(series_groupby, reduction_func) + + if reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + result = agg(*args) + + zero_or_nan = _results_for_groupbys_with_missing_categories[reduction_func] + + for idx in unobserved: + val = result.loc[idx] + assert (pd.isna(zero_or_nan) and pd.isna(val)) or (val == zero_or_nan) + + # If we expect unobserved values to be zero, we also expect the dtype to be int. + # Except for .sum(). If the observed categories sum to dtype=float (i.e. their + # sums have decimals), then the zeros for the missing categories should also be + # floats. + if zero_or_nan == 0 and reduction_func != "sum": + assert np.issubdtype(result.dtype, np.integer) + + +def test_dataframe_groupby_on_2_categoricals_when_observed_is_true(reduction_func): + # GH 23865 + # GH 27075 + # Ensure that df.groupby, when 'by' is two Categorical variables, + # does not return the categories that are not in df when observed=True + if reduction_func == "ngroup": + pytest.skip("ngroup does not return the Categories on the index") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), + "value": [0.1, 0.1, 0.1, 0.1], + } + ) + unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")] + + df_grp = df.groupby(["cat_1", "cat_2"], observed=True) + + args = get_groupby_method_args(reduction_func, df) + res = getattr(df_grp, reduction_func)(*args) + + for cat in unobserved_cats: + assert cat not in res.index + + +@pytest.mark.parametrize("observed", [False, None]) +def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( + reduction_func, observed +): + # GH 23865 + # GH 27075 + # Ensure that df.groupby, when 'by' is two Categorical variables, + # returns the categories that are not in df when observed=False/None + + if reduction_func == "ngroup": + pytest.skip("ngroup does not return the Categories on the index") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), + "value": [0.1, 0.1, 0.1, 0.1], + } + ) + unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")] + + df_grp = df.groupby(["cat_1", "cat_2"], observed=observed) + + args = get_groupby_method_args(reduction_func, df) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(df_grp, reduction_func)(*args) + return + + res = getattr(df_grp, reduction_func)(*args) + + expected = _results_for_groupbys_with_missing_categories[reduction_func] + + if expected is np.nan: + assert res.loc[unobserved_cats].isnull().all().all() + else: + assert (res.loc[unobserved_cats] == expected).all().all() + + +def test_series_groupby_categorical_aggregation_getitem(): + # GH 8870 + d = {"foo": [10, 8, 4, 1], "bar": [10, 20, 30, 40], "baz": ["d", "c", "d", "c"]} + df = DataFrame(d) + cat = pd.cut(df["foo"], np.linspace(0, 20, 5)) + df["range"] = cat + groups = df.groupby(["range", "baz"], as_index=True, sort=True, observed=False) + result = groups["foo"].agg("mean") + expected = groups.agg("mean")["foo"] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, expected_values", + [(Series.nunique, [1, 1, 2]), (Series.count, [1, 2, 2])], +) +def test_groupby_agg_categorical_columns(func, expected_values): + # 31256 + df = DataFrame( + { + "id": [0, 1, 2, 3, 4], + "groups": [0, 1, 1, 2, 2], + "value": Categorical([0, 0, 0, 0, 1]), + } + ).set_index("id") + result = df.groupby("groups").agg(func) + + expected = DataFrame( + {"value": expected_values}, index=Index([0, 1, 2], name="groups") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_non_numeric(): + df = DataFrame({"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"])}) + expected = DataFrame({"A": [2, 1]}, index=np.array([1, 2])) + + result = df.groupby([1, 2, 1]).agg(Series.nunique) + tm.assert_frame_equal(result, expected) + + result = df.groupby([1, 2, 1]).nunique() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_first_returned_categorical_instead_of_dataframe(func): + # GH 28641: groupby drops index, when grouping over categorical column with + # first/last. Renamed Categorical instead of DataFrame previously. + df = DataFrame({"A": [1997], "B": Series(["b"], dtype="category").cat.as_ordered()}) + df_grouped = df.groupby("A")["B"] + result = getattr(df_grouped, func)() + + # ordered categorical dtype should be preserved + expected = Series( + ["b"], index=Index([1997], name="A"), name="B", dtype=df["B"].dtype + ) + tm.assert_series_equal(result, expected) + + +def test_read_only_category_no_sort(): + # GH33410 + cats = np.array([1, 2]) + cats.flags.writeable = False + df = DataFrame( + {"a": [1, 3, 5, 7], "b": Categorical([1, 1, 2, 2], categories=Index(cats))} + ) + expected = DataFrame(data={"a": [2.0, 6.0]}, index=CategoricalIndex(cats, name="b")) + result = df.groupby("b", sort=False, observed=False).mean() + tm.assert_frame_equal(result, expected) + + +def test_sorted_missing_category_values(): + # GH 28597 + df = DataFrame( + { + "foo": [ + "small", + "large", + "large", + "large", + "medium", + "large", + "large", + "medium", + ], + "bar": ["C", "A", "A", "C", "A", "C", "A", "C"], + } + ) + df["foo"] = ( + df["foo"] + .astype("category") + .cat.set_categories(["tiny", "small", "medium", "large"], ordered=True) + ) + + expected = DataFrame( + { + "tiny": {"A": 0, "C": 0}, + "small": {"A": 0, "C": 1}, + "medium": {"A": 1, "C": 1}, + "large": {"A": 3, "C": 2}, + } + ) + expected = expected.rename_axis("bar", axis="index") + expected.columns = CategoricalIndex( + ["tiny", "small", "medium", "large"], + categories=["tiny", "small", "medium", "large"], + ordered=True, + name="foo", + dtype="category", + ) + + result = df.groupby(["bar", "foo"], observed=False).size().unstack() + + tm.assert_frame_equal(result, expected) + + +def test_agg_cython_category_not_implemented_fallback(): + # https://github.com/pandas-dev/pandas/issues/31450 + df = DataFrame({"col_num": [1, 1, 2, 3]}) + df["col_cat"] = df["col_num"].astype("category") + + result = df.groupby("col_num").col_cat.first() + + # ordered categorical dtype should definitely be preserved; + # this is unordered, so is less-clear case (if anything, it should raise) + expected = Series( + [1, 2, 3], + index=Index([1, 2, 3], name="col_num"), + name="col_cat", + dtype=df["col_cat"].dtype, + ) + tm.assert_series_equal(result, expected) + + result = df.groupby("col_num").agg({"col_cat": "first"}) + expected = expected.to_frame() + tm.assert_frame_equal(result, expected) + + +def test_aggregate_categorical_with_isnan(): + # GH 29837 + df = DataFrame( + { + "A": [1, 1, 1, 1], + "B": [1, 2, 1, 2], + "numerical_col": [0.1, 0.2, np.nan, 0.3], + "object_col": ["foo", "bar", "foo", "fee"], + "categorical_col": ["foo", "bar", "foo", "fee"], + } + ) + + df = df.astype({"categorical_col": "category"}) + + result = df.groupby(["A", "B"]).agg(lambda df: df.isna().sum()) + index = MultiIndex.from_arrays([[1, 1], [1, 2]], names=("A", "B")) + expected = DataFrame( + data={ + "numerical_col": [1, 0], + "object_col": [0, 0], + "categorical_col": [0, 0], + }, + index=index, + ) + tm.assert_frame_equal(result, expected) + + +def test_categorical_transform(): + # GH 29037 + df = DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + } + ) + + delivery_status_type = pd.CategoricalDtype( + categories=["Waiting", "OnTheWay", "Delivered"], ordered=True + ) + df["status"] = df["status"].astype(delivery_status_type) + msg = "using SeriesGroupBy.max" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + df["last_status"] = df.groupby("package_id")["status"].transform(max) + result = df.copy() + + expected = DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + "last_status": [ + "Delivered", + "Delivered", + "Delivered", + "OnTheWay", + "OnTheWay", + "Waiting", + ], + } + ) + + expected["status"] = expected["status"].astype(delivery_status_type) + + # .transform(max) should preserve ordered categoricals + expected["last_status"] = expected["last_status"].astype(delivery_status_type) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_series_groupby_first_on_categorical_col_grouped_on_2_categoricals( + func: str, observed: bool +): + # GH 34951 + cat = Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = Categorical([0, 1]) + idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": Series([1, np.nan, np.nan, 0], idx, name="c"), + } + + expected = expected_dict[func] + if observed: + expected = expected.dropna().astype(np.int64) + + srs_grp = df.groupby(["a", "b"], observed=observed)["c"] + result = getattr(srs_grp, func)() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals( + func: str, observed: bool +): + # GH 34951 + cat = Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = Categorical([0, 1]) + idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": Series([1, np.nan, np.nan, 0], idx, name="c"), + } + + expected = expected_dict[func].to_frame() + if observed: + expected = expected.dropna().astype(np.int64) + + df_grp = df.groupby(["a", "b"], observed=observed) + result = getattr(df_grp, func)() + tm.assert_frame_equal(result, expected) + + +def test_groupby_categorical_indices_unused_categories(): + # GH#38642 + df = DataFrame( + { + "key": Categorical(["b", "b", "a"], categories=["a", "b", "c"]), + "col": range(3), + } + ) + grouped = df.groupby("key", sort=False, observed=False) + result = grouped.indices + expected = { + "b": np.array([0, 1], dtype="intp"), + "a": np.array([2], dtype="intp"), + "c": np.array([], dtype="intp"), + } + assert result.keys() == expected.keys() + for key in result.keys(): + tm.assert_numpy_array_equal(result[key], expected[key]) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_last_first_preserve_categoricaldtype(func): + # GH#33090 + df = DataFrame({"a": [1, 2, 3]}) + df["b"] = df["a"].astype("category") + result = getattr(df.groupby("a")["b"], func)() + expected = Series( + Categorical([1, 2, 3]), name="b", index=Index([1, 2, 3], name="a") + ) + tm.assert_series_equal(expected, result) + + +def test_groupby_categorical_observed_nunique(): + # GH#45128 + df = DataFrame({"a": [1, 2], "b": [1, 2], "c": [10, 11]}) + df = df.astype(dtype={"a": "category", "b": "category"}) + result = df.groupby(["a", "b"], observed=True).nunique()["c"] + expected = Series( + [1, 1], + index=MultiIndex.from_arrays( + [CategoricalIndex([1, 2], name="a"), CategoricalIndex([1, 2], name="b")] + ), + name="c", + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_aggregate_functions(): + # GH#37275 + dtype = pd.CategoricalDtype(categories=["small", "big"], ordered=True) + df = DataFrame( + [[1, "small"], [1, "big"], [2, "small"]], columns=["grp", "description"] + ).astype({"description": dtype}) + + result = df.groupby("grp")["description"].max() + expected = Series( + ["big", "small"], + index=Index([1, 2], name="grp"), + name="description", + dtype=pd.CategoricalDtype(categories=["small", "big"], ordered=True), + ) + + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_dropna(observed, dropna): + # GH#48645 - dropna should have no impact on the result when there are no NA values + cat = Categorical([1, 2], categories=[1, 2, 3]) + df = DataFrame({"x": Categorical([1, 2], categories=[1, 2, 3]), "y": [3, 4]}) + gb = df.groupby("x", observed=observed, dropna=dropna) + result = gb.sum() + + if observed: + expected = DataFrame({"y": [3, 4]}, index=cat) + else: + index = CategoricalIndex([1, 2, 3], [1, 2, 3]) + expected = DataFrame({"y": [3, 4, 0]}, index=index) + expected.index.name = "x" + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_reducer( + request, as_index, sort, observed, reduction_func, index_kind, ordered +): + # GH#48749 + if reduction_func == "corrwith" and not as_index: + msg = "GH#49950 - corrwith with as_index=False may not have grouping column" + request.applymarker(pytest.mark.xfail(reason=msg)) + elif index_kind != "range" and not as_index: + pytest.skip(reason="Result doesn't have categories, nothing to test") + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + args = get_groupby_method_args(reduction_func, df) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(gb, reduction_func)(*args) + return + + op_result = getattr(gb, reduction_func)(*args) + if as_index: + result = op_result.index.get_level_values("a").categories + else: + result = op_result["a"].cat.categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["single", "multi"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_transformer( + as_index, sort, observed, transformation_func, index_kind, ordered +): + # GH#48749 + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + args = get_groupby_method_args(transformation_func, df) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + warn = FutureWarning if transformation_func == "fillna" else None + msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=msg): + op_result = getattr(gb, transformation_func)(*args) + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("method", ["head", "tail"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_head_tail( + as_index, sort, observed, method, index_kind, ordered +): + # GH#48749 + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + op_result = getattr(gb, method)() + if index_kind == "range": + result = op_result["a"].cat.categories + else: + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("method", ["apply", "agg", "transform"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_apply(as_index, sort, observed, method, index_kind, ordered): + # GH#48749 + if (method == "transform" and index_kind == "range") or ( + not as_index and index_kind != "range" + ): + pytest.skip("No categories in result, nothing to test") + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + warn = DeprecationWarning if method == "apply" and index_kind == "range" else None + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(warn, match=msg): + op_result = getattr(gb, method)(lambda x: x.sum(numeric_only=True)) + if (method == "transform" or not as_index) and index_kind == "range": + result = op_result["a"].cat.categories + else: + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +def test_many_categories(as_index, sort, index_kind, ordered): + # GH#48749 - Test when the grouper has many categories + if index_kind != "range" and not as_index: + pytest.skip(reason="Result doesn't have categories, nothing to test") + categories = np.arange(9999, -1, -1) + grouper = Categorical([2, 1, 2, 3], categories=categories, ordered=ordered) + df = DataFrame({"a": grouper, "b": range(4)}) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=True) + result = gb.sum() + + # Test is setup so that data and index are the same values + data = [3, 2, 1] if sort else [2, 1, 3] + + index = CategoricalIndex( + data, categories=grouper.categories, ordered=ordered, name="a" + ) + if as_index: + expected = DataFrame({"b": data}) + if index_kind == "multi": + expected.index = MultiIndex.from_frame(DataFrame({"a": index, "a2": index})) + else: + expected.index = index + elif index_kind == "multi": + expected = DataFrame({"a": Series(index), "a2": Series(index), "b": data}) + else: + expected = DataFrame({"a": Series(index), "b": data}) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("cat_columns", ["a", "b", ["a", "b"]]) +@pytest.mark.parametrize("keys", ["a", "b", ["a", "b"]]) +def test_groupby_default_depr(cat_columns, keys): + # GH#43999 + df = DataFrame({"a": [1, 1, 2, 3], "b": [4, 5, 6, 7]}) + df[cat_columns] = df[cat_columns].astype("category") + msg = "The default of observed=False is deprecated" + klass = FutureWarning if set(cat_columns) & set(keys) else None + with tm.assert_produces_warning(klass, match=msg): + df.groupby(keys) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_agg_list(request, as_index, observed, reduction_func, test_series, keys): + # GH#52760 + if test_series and reduction_func == "corrwith": + assert not hasattr(SeriesGroupBy, "corrwith") + pytest.skip("corrwith not implemented for SeriesGroupBy") + elif reduction_func == "corrwith": + msg = "GH#32293: attempts to call SeriesGroupBy.corrwith" + request.applymarker(pytest.mark.xfail(reason=msg)) + elif ( + reduction_func == "nunique" + and not test_series + and len(keys) != 1 + and not observed + and not as_index + ): + msg = "GH#52848 - raises a ValueError" + request.applymarker(pytest.mark.xfail(reason=msg)) + + df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) + df = df.astype({"a1": "category", "a2": "category"}) + if "a2" not in keys: + df = df.drop(columns="a2") + gb = df.groupby(by=keys, as_index=as_index, observed=observed) + if test_series: + gb = gb["b"] + args = get_groupby_method_args(reduction_func, df) + + if not observed and reduction_func in ["idxmin", "idxmax"] and keys == ["a1", "a2"]: + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + gb.agg([reduction_func], *args) + return + + result = gb.agg([reduction_func], *args) + expected = getattr(gb, reduction_func)(*args) + + if as_index and (test_series or reduction_func == "size"): + expected = expected.to_frame(reduction_func) + if not test_series: + expected.columns = MultiIndex.from_tuples( + [(ind, "") for ind in expected.columns[:-1]] + [("b", reduction_func)] + ) + elif not as_index: + expected.columns = keys + [reduction_func] + + tm.assert_equal(result, expected) diff --git a/shared/package-files/ef/ef740aacdf4a368699ce16d7e723c20996be15a00bc177bc4cf94347bd898015/_compat.py b/shared/package-files/ef/ef740aacdf4a368699ce16d7e723c20996be15a00bc177bc4cf94347bd898015/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..df312b1cbbf18a337278df0e618fb9e8c862e5f6 --- /dev/null +++ b/shared/package-files/ef/ef740aacdf4a368699ce16d7e723c20996be15a00bc177bc4cf94347bd898015/_compat.py @@ -0,0 +1,57 @@ +import sys +import platform + + +__all__ = ['install', 'NullFinder'] + + +def install(cls): + """ + Class decorator for installation on sys.meta_path. + + Adds the backport DistributionFinder to sys.meta_path and + attempts to disable the finder functionality of the stdlib + DistributionFinder. + """ + sys.meta_path.append(cls()) + disable_stdlib_finder() + return cls + + +def disable_stdlib_finder(): + """ + Give the backport primacy for discovering path-based distributions + by monkey-patching the stdlib O_O. + + See #91 for more background for rationale on this sketchy + behavior. + """ + + def matches(finder): + return getattr( + finder, '__module__', None + ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions') + + for finder in filter(matches, sys.meta_path): # pragma: nocover + del finder.find_distributions + + +class NullFinder: + """ + A "Finder" (aka "MetaPathFinder") that never finds any modules, + but may find distributions. + """ + + @staticmethod + def find_spec(*args, **kwargs): + return None + + +def pypy_partial(val): + """ + Adjust for variable stacklevel on partial under PyPy. + + Workaround for #327. + """ + is_pypy = platform.python_implementation() == 'PyPy' + return val + is_pypy diff --git a/shared/package-files/ef/ef756a4470a7123ac6c259cc07b4cd2fb8976e30169527c5b03e87bc20cd95e9/wrappers.cpython-311.pyc b/shared/package-files/ef/ef756a4470a7123ac6c259cc07b4cd2fb8976e30169527c5b03e87bc20cd95e9/wrappers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d68fa5f81ced35cc64855be6c6670f9080ca1b9 Binary files /dev/null and b/shared/package-files/ef/ef756a4470a7123ac6c259cc07b4cd2fb8976e30169527c5b03e87bc20cd95e9/wrappers.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef79ed57283cafc7f32b2e55224eb2baf0b8e460de59ea5a2c8a8893e337462f/texture_types.h b/shared/package-files/ef/ef79ed57283cafc7f32b2e55224eb2baf0b8e460de59ea5a2c8a8893e337462f/texture_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a3e3e90ef5c02d7f3e62178792fd10f93ba4d85f --- /dev/null +++ b/shared/package-files/ef/ef79ed57283cafc7f32b2e55224eb2baf0b8e460de59ea5a2c8a8893e337462f/texture_types.h @@ -0,0 +1,180 @@ +/* + * Copyright 1993-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__TEXTURE_TYPES_H__) +#define __TEXTURE_TYPES_H__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "driver_types.h" + +#ifndef __CUDACC_RTC_MINIMAL__ + +/** + * \addtogroup CUDART_TYPES + * + * @{ + */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#define cudaTextureType1D 0x01 +#define cudaTextureType2D 0x02 +#define cudaTextureType3D 0x03 +#define cudaTextureTypeCubemap 0x0C +#define cudaTextureType1DLayered 0xF1 +#define cudaTextureType2DLayered 0xF2 +#define cudaTextureTypeCubemapLayered 0xFC + +/** + * CUDA texture address modes + */ +enum __device_builtin__ cudaTextureAddressMode +{ + cudaAddressModeWrap = 0, /**< Wrapping address mode */ + cudaAddressModeClamp = 1, /**< Clamp to edge address mode */ + cudaAddressModeMirror = 2, /**< Mirror address mode */ + cudaAddressModeBorder = 3 /**< Border address mode */ +}; + +/** + * CUDA texture filter modes + */ +enum __device_builtin__ cudaTextureFilterMode +{ + cudaFilterModePoint = 0, /**< Point filter mode */ + cudaFilterModeLinear = 1 /**< Linear filter mode */ +}; + +/** + * CUDA texture read modes + */ +enum __device_builtin__ cudaTextureReadMode +{ + cudaReadModeElementType = 0, /**< Read texture as specified element type */ + cudaReadModeNormalizedFloat = 1 /**< Read texture as normalized float */ +}; + +/** + * CUDA texture descriptor + */ +struct __device_builtin__ cudaTextureDesc +{ + /** + * Texture address mode for up to 3 dimensions + */ + enum cudaTextureAddressMode addressMode[3]; + /** + * Texture filter mode + */ + enum cudaTextureFilterMode filterMode; + /** + * Texture read mode + */ + enum cudaTextureReadMode readMode; + /** + * Perform sRGB->linear conversion during texture read + */ + int sRGB; + /** + * Texture Border Color + */ + float borderColor[4]; + /** + * Indicates whether texture reads are normalized or not + */ + int normalizedCoords; + /** + * Limit to the anisotropy ratio + */ + unsigned int maxAnisotropy; + /** + * Mipmap filter mode + */ + enum cudaTextureFilterMode mipmapFilterMode; + /** + * Offset applied to the supplied mipmap level + */ + float mipmapLevelBias; + /** + * Lower end of the mipmap level range to clamp access to + */ + float minMipmapLevelClamp; + /** + * Upper end of the mipmap level range to clamp access to + */ + float maxMipmapLevelClamp; + /** + * Disable any trilinear filtering optimizations. + */ + int disableTrilinearOptimization; + /** + * Enable seamless cube map filtering. + */ + int seamlessCubemap; +}; + +/** + * An opaque value that represents a CUDA texture object + */ +typedef __device_builtin__ unsigned long long cudaTextureObject_t; + +/** @} */ +/** @} */ /* END CUDART_TYPES */ + +#endif /* !__CUDACC_RTC_MINIMAL__ */ +#endif /* !__TEXTURE_TYPES_H__ */ diff --git a/shared/package-files/ef/ef7ae953ddcfc62488aa4c353442f405110e6ce180c69d74b0f60da48ad6ab6d/histograms.cpython-311.pyc b/shared/package-files/ef/ef7ae953ddcfc62488aa4c353442f405110e6ce180c69d74b0f60da48ad6ab6d/histograms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77330fb16be958d5b349030e9c7144f4a71f43f6 Binary files /dev/null and b/shared/package-files/ef/ef7ae953ddcfc62488aa4c353442f405110e6ce180c69d74b0f60da48ad6ab6d/histograms.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef839bd7d4c021f9428409be8df1a68b92930bc7e74241efa6b1c1c4b61210b3/test_setops.py b/shared/package-files/ef/ef839bd7d4c021f9428409be8df1a68b92930bc7e74241efa6b1c1c4b61210b3/test_setops.py new file mode 100644 index 0000000000000000000000000000000000000000..0abb56ecf9de7182dd38e45d5a8938cb81248034 --- /dev/null +++ b/shared/package-files/ef/ef839bd7d4c021f9428409be8df1a68b92930bc7e74241efa6b1c1c4b61210b3/test_setops.py @@ -0,0 +1,772 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + CategoricalIndex, + DataFrame, + Index, + IntervalIndex, + MultiIndex, + Series, +) +import pandas._testing as tm +from pandas.api.types import ( + is_float_dtype, + is_unsigned_integer_dtype, +) + + +@pytest.mark.parametrize("case", [0.5, "xxx"]) +@pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_set_ops_error_cases(idx, case, sort, method): + # non-iterable input + msg = "Input must be Index or array-like" + with pytest.raises(TypeError, match=msg): + getattr(idx, method)(case, sort=sort) + + +@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list]) +def test_intersection_base(idx, sort, klass): + first = idx[2::-1] # first 3 elements reversed + second = idx[:5] + + if klass is not MultiIndex: + second = klass(second.values) + + intersect = first.intersection(second, sort=sort) + if sort is None: + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(intersect, expected) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.intersection([1, 2, 3], sort=sort) + + +@pytest.mark.arm_slow +@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list]) +def test_union_base(idx, sort, klass): + first = idx[::-1] + second = idx[:5] + + if klass is not MultiIndex: + second = klass(second.values) + + union = first.union(second, sort=sort) + if sort is None: + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(union, expected) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.union([1, 2, 3], sort=sort) + + +def test_difference_base(idx, sort): + second = idx[4:] + answer = idx[:4] + result = idx.difference(second, sort=sort) + + if sort is None: + answer = answer.sort_values() + + assert result.equals(answer) + tm.assert_index_equal(result, answer) + + # GH 10149 + cases = [klass(second.values) for klass in [np.array, Series, list]] + for case in cases: + result = idx.difference(case, sort=sort) + tm.assert_index_equal(result, answer) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + idx.difference([1, 2, 3], sort=sort) + + +def test_symmetric_difference(idx, sort): + first = idx[1:] + second = idx[:-1] + answer = idx[[-1, 0]] + result = first.symmetric_difference(second, sort=sort) + + if sort is None: + answer = answer.sort_values() + + tm.assert_index_equal(result, answer) + + # GH 10149 + cases = [klass(second.values) for klass in [np.array, Series, list]] + for case in cases: + result = first.symmetric_difference(case, sort=sort) + tm.assert_index_equal(result, answer) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.symmetric_difference([1, 2, 3], sort=sort) + + +def test_multiindex_symmetric_difference(): + # GH 13490 + idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"]) + result = idx.symmetric_difference(idx) + assert result.names == idx.names + + idx2 = idx.copy().rename(["A", "B"]) + result = idx.symmetric_difference(idx2) + assert result.names == [None, None] + + +def test_empty(idx): + # GH 15270 + assert not idx.empty + assert idx[:0].empty + + +def test_difference(idx, sort): + first = idx + result = first.difference(idx[-3:], sort=sort) + vals = idx[:-3].values + + if sort is None: + vals = sorted(vals) + + expected = MultiIndex.from_tuples(vals, sortorder=0, names=idx.names) + + assert isinstance(result, MultiIndex) + assert result.equals(expected) + assert result.names == idx.names + tm.assert_index_equal(result, expected) + + # empty difference: reflexive + result = idx.difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # empty difference: superset + result = idx[-3:].difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # empty difference: degenerate + result = idx[:0].difference(idx, sort=sort) + expected = idx[:0] + assert result.equals(expected) + assert result.names == idx.names + + # names not the same + chunklet = idx[-3:] + chunklet.names = ["foo", "baz"] + result = first.difference(chunklet, sort=sort) + assert result.names == (None, None) + + # empty, but non-equal + result = idx.difference(idx.sortlevel(1)[0], sort=sort) + assert len(result) == 0 + + # raise Exception called with non-MultiIndex + result = first.difference(first.values, sort=sort) + assert result.equals(first[:0]) + + # name from empty array + result = first.difference([], sort=sort) + assert first.equals(result) + assert first.names == result.names + + # name from non-empty array + result = first.difference([("foo", "one")], sort=sort) + expected = MultiIndex.from_tuples( + [("bar", "one"), ("baz", "two"), ("foo", "two"), ("qux", "one"), ("qux", "two")] + ) + expected.names = first.names + assert first.names == result.names + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + first.difference([1, 2, 3, 4, 5], sort=sort) + + +def test_difference_sort_special(): + # GH-24959 + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + # sort=None, the default + result = idx.difference([]) + tm.assert_index_equal(result, idx) + + +def test_difference_sort_special_true(): + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + result = idx.difference([], sort=True) + expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) + tm.assert_index_equal(result, expected) + + +def test_difference_sort_incomparable(): + # GH-24959 + idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) + + other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]]) + # sort=None, the default + msg = "sort order is undefined for incomparable objects" + with tm.assert_produces_warning(RuntimeWarning, match=msg): + result = idx.difference(other) + tm.assert_index_equal(result, idx) + + # sort=False + result = idx.difference(other, sort=False) + tm.assert_index_equal(result, idx) + + +def test_difference_sort_incomparable_true(): + idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) + other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]]) + + # TODO: this is raising in constructing a Categorical when calling + # algos.safe_sort. Should we catch and re-raise with a better message? + msg = "'values' is not ordered, please explicitly specify the categories order " + with pytest.raises(TypeError, match=msg): + idx.difference(other, sort=True) + + +def test_union(idx, sort): + piece1 = idx[:5][::-1] + piece2 = idx[3:] + + the_union = piece1.union(piece2, sort=sort) + + if sort in (None, False): + tm.assert_index_equal(the_union.sort_values(), idx.sort_values()) + else: + tm.assert_index_equal(the_union, idx) + + # corner case, pass self or empty thing: + the_union = idx.union(idx, sort=sort) + tm.assert_index_equal(the_union, idx) + + the_union = idx.union(idx[:0], sort=sort) + tm.assert_index_equal(the_union, idx) + + tuples = idx.values + result = idx[:4].union(tuples[4:], sort=sort) + if sort is None: + tm.assert_index_equal(result.sort_values(), idx.sort_values()) + else: + assert result.equals(idx) + + +def test_union_with_regular_index(idx, using_infer_string): + other = Index(["A", "B", "C"]) + + result = other.union(idx) + assert ("foo", "one") in result + assert "B" in result + + if using_infer_string: + with pytest.raises(NotImplementedError, match="Can only union"): + idx.union(other) + else: + msg = "The values in the array are unorderable" + with tm.assert_produces_warning(RuntimeWarning, match=msg): + result2 = idx.union(other) + # This is more consistent now, if sorting fails then we don't sort at all + # in the MultiIndex case. + assert not result.equals(result2) + + +def test_intersection(idx, sort): + piece1 = idx[:5][::-1] + piece2 = idx[3:] + + the_int = piece1.intersection(piece2, sort=sort) + + if sort in (None, True): + tm.assert_index_equal(the_int, idx[3:5]) + else: + tm.assert_index_equal(the_int.sort_values(), idx[3:5]) + + # corner case, pass self + the_int = idx.intersection(idx, sort=sort) + tm.assert_index_equal(the_int, idx) + + # empty intersection: disjoint + empty = idx[:2].intersection(idx[2:], sort=sort) + expected = idx[:0] + assert empty.equals(expected) + + tuples = idx.values + result = idx.intersection(tuples) + assert result.equals(idx) + + +@pytest.mark.parametrize( + "method", ["intersection", "union", "difference", "symmetric_difference"] +) +def test_setop_with_categorical(idx, sort, method): + other = idx.to_flat_index().astype("category") + res_names = [None] * idx.nlevels + + result = getattr(idx, method)(other, sort=sort) + expected = getattr(idx, method)(idx, sort=sort).rename(res_names) + tm.assert_index_equal(result, expected) + + result = getattr(idx, method)(other[:5], sort=sort) + expected = getattr(idx, method)(idx[:5], sort=sort).rename(res_names) + tm.assert_index_equal(result, expected) + + +def test_intersection_non_object(idx, sort): + other = Index(range(3), name="foo") + + result = idx.intersection(other, sort=sort) + expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=None) + tm.assert_index_equal(result, expected, exact=True) + + # if we pass a length-0 ndarray (i.e. no name, we retain our idx.name) + result = idx.intersection(np.asarray(other)[:0], sort=sort) + expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=idx.names) + tm.assert_index_equal(result, expected, exact=True) + + msg = "other must be a MultiIndex or a list of tuples" + with pytest.raises(TypeError, match=msg): + # With non-zero length non-index, we try and fail to convert to tuples + idx.intersection(np.asarray(other), sort=sort) + + +def test_intersect_equal_sort(): + # GH-24959 + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + tm.assert_index_equal(idx.intersection(idx, sort=False), idx) + tm.assert_index_equal(idx.intersection(idx, sort=None), idx) + + +def test_intersect_equal_sort_true(): + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) + result = idx.intersection(idx, sort=True) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("slice_", [slice(None), slice(0)]) +def test_union_sort_other_empty(slice_): + # https://github.com/pandas-dev/pandas/issues/24959 + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + + # default, sort=None + other = idx[slice_] + tm.assert_index_equal(idx.union(other), idx) + tm.assert_index_equal(other.union(idx), idx) + + # sort=False + tm.assert_index_equal(idx.union(other, sort=False), idx) + + +def test_union_sort_other_empty_sort(): + idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) + other = idx[:0] + result = idx.union(other, sort=True) + expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) + tm.assert_index_equal(result, expected) + + +def test_union_sort_other_incomparable(): + # https://github.com/pandas-dev/pandas/issues/24959 + idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) + + # default, sort=None + with tm.assert_produces_warning(RuntimeWarning): + result = idx.union(idx[:1]) + tm.assert_index_equal(result, idx) + + # sort=False + result = idx.union(idx[:1], sort=False) + tm.assert_index_equal(result, idx) + + +def test_union_sort_other_incomparable_sort(): + idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) + msg = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=msg): + idx.union(idx[:1], sort=True) + + +def test_union_non_object_dtype_raises(): + # GH#32646 raise NotImplementedError instead of less-informative error + mi = MultiIndex.from_product([["a", "b"], [1, 2]]) + + idx = mi.levels[1] + + msg = "Can only union MultiIndex with MultiIndex or Index of tuples" + with pytest.raises(NotImplementedError, match=msg): + mi.union(idx) + + +def test_union_empty_self_different_names(): + # GH#38423 + mi = MultiIndex.from_arrays([[]]) + mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + result = mi.union(mi2) + expected = MultiIndex.from_arrays([[1, 2], [3, 4]]) + tm.assert_index_equal(result, expected) + + +def test_union_multiindex_empty_rangeindex(): + # GH#41234 + mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + ri = pd.RangeIndex(0) + + result_left = mi.union(ri) + tm.assert_index_equal(mi, result_left, check_names=False) + + result_right = ri.union(mi) + tm.assert_index_equal(mi, result_right, check_names=False) + + +@pytest.mark.parametrize( + "method", ["union", "intersection", "difference", "symmetric_difference"] +) +def test_setops_sort_validation(method): + idx1 = MultiIndex.from_product([["a", "b"], [1, 2]]) + idx2 = MultiIndex.from_product([["b", "c"], [1, 2]]) + + with pytest.raises(ValueError, match="The 'sort' keyword only takes"): + getattr(idx1, method)(idx2, sort=2) + + # sort=True is supported as of GH#? + getattr(idx1, method)(idx2, sort=True) + + +@pytest.mark.parametrize("val", [pd.NA, 100]) +def test_difference_keep_ea_dtypes(any_numeric_ea_dtype, val): + # GH#48606 + midx = MultiIndex.from_arrays( + [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = MultiIndex.from_arrays( + [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.difference(midx2) + expected = MultiIndex.from_arrays([Series([1], dtype=any_numeric_ea_dtype), [2]]) + tm.assert_index_equal(result, expected) + + result = midx.difference(midx.sort_values(ascending=False)) + expected = MultiIndex.from_arrays( + [Series([], dtype=any_numeric_ea_dtype), Series([], dtype=np.int64)], + names=["a", None], + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("val", [pd.NA, 5]) +def test_symmetric_difference_keeping_ea_dtype(any_numeric_ea_dtype, val): + # GH#48607 + midx = MultiIndex.from_arrays( + [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = MultiIndex.from_arrays( + [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.symmetric_difference(midx2) + expected = MultiIndex.from_arrays( + [Series([1, 1, val], dtype=any_numeric_ea_dtype), [1, 2, 3]] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + ("tuples", "exp_tuples"), + [ + ([("val1", "test1")], [("val1", "test1")]), + ([("val1", "test1"), ("val1", "test1")], [("val1", "test1")]), + ( + [("val2", "test2"), ("val1", "test1")], + [("val2", "test2"), ("val1", "test1")], + ), + ], +) +def test_intersect_with_duplicates(tuples, exp_tuples): + # GH#36915 + left = MultiIndex.from_tuples(tuples, names=["first", "second"]) + right = MultiIndex.from_tuples( + [("val1", "test1"), ("val1", "test1"), ("val2", "test2")], + names=["first", "second"], + ) + result = left.intersection(right) + expected = MultiIndex.from_tuples(exp_tuples, names=["first", "second"]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "data, names, expected", + [ + ((1,), None, [None, None]), + ((1,), ["a"], [None, None]), + ((1,), ["b"], [None, None]), + ((1, 2), ["c", "d"], [None, None]), + ((1, 2), ["b", "a"], [None, None]), + ((1, 2, 3), ["a", "b", "c"], [None, None]), + ((1, 2), ["a", "c"], ["a", None]), + ((1, 2), ["c", "b"], [None, "b"]), + ((1, 2), ["a", "b"], ["a", "b"]), + ((1, 2), [None, "b"], [None, "b"]), + ], +) +def test_maybe_match_names(data, names, expected): + # GH#38323 + mi = MultiIndex.from_tuples([], names=["a", "b"]) + mi2 = MultiIndex.from_tuples([data], names=names) + result = mi._maybe_match_names(mi2) + assert result == expected + + +def test_intersection_equal_different_names(): + # GH#30302 + mi1 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"]) + mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) + + result = mi1.intersection(mi2) + expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"]) + tm.assert_index_equal(result, expected) + + +def test_intersection_different_names(): + # GH#38323 + mi = MultiIndex.from_arrays([[1], [3]], names=["c", "b"]) + mi2 = MultiIndex.from_arrays([[1], [3]]) + result = mi.intersection(mi2) + tm.assert_index_equal(result, mi2) + + +def test_intersection_with_missing_values_on_both_sides(nulls_fixture): + # GH#38623 + mi1 = MultiIndex.from_arrays([[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]]) + mi2 = MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]]) + result = mi1.intersection(mi2) + expected = MultiIndex.from_arrays([[3, nulls_fixture], [1, 2]]) + tm.assert_index_equal(result, expected) + + +def test_union_with_missing_values_on_both_sides(nulls_fixture): + # GH#38623 + mi1 = MultiIndex.from_arrays([[1, nulls_fixture]]) + mi2 = MultiIndex.from_arrays([[1, nulls_fixture, 3]]) + result = mi1.union(mi2) + expected = MultiIndex.from_arrays([[1, 3, nulls_fixture]]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["float64", "Float64"]) +@pytest.mark.parametrize("sort", [None, False]) +def test_union_nan_got_duplicated(dtype, sort): + # GH#38977, GH#49010 + mi1 = MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]]) + mi2 = MultiIndex.from_arrays([pd.array([1.0, np.nan, 3.0], dtype=dtype), [2, 3, 4]]) + result = mi1.union(mi2, sort=sort) + if sort is None: + expected = MultiIndex.from_arrays( + [pd.array([1.0, 3.0, np.nan], dtype=dtype), [2, 4, 3]] + ) + else: + expected = mi2 + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("val", [4, 1]) +def test_union_keep_ea_dtype(any_numeric_ea_dtype, val): + # GH#48505 + + arr1 = Series([val, 2], dtype=any_numeric_ea_dtype) + arr2 = Series([2, 1], dtype=any_numeric_ea_dtype) + midx = MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None]) + midx2 = MultiIndex.from_arrays([arr2, [2, 1]]) + result = midx.union(midx2) + if val == 4: + expected = MultiIndex.from_arrays( + [Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]] + ) + else: + expected = MultiIndex.from_arrays( + [Series([1, 2], dtype=any_numeric_ea_dtype), [1, 2]] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dupe_val", [3, pd.NA]) +def test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype): + # GH48900 + mi1 = MultiIndex.from_arrays( + [ + Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), + Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), + ] + ) + mi2 = MultiIndex.from_arrays( + [ + Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + ] + ) + result = mi1.union(mi2) + expected = MultiIndex.from_arrays( + [ + Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), + ] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") +def test_union_duplicates(index, request): + # GH#38977 + if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)): + pytest.skip(f"No duplicates in an empty {type(index).__name__}") + + values = index.unique().values.tolist() + mi1 = MultiIndex.from_arrays([values, [1] * len(values)]) + mi2 = MultiIndex.from_arrays([[values[0]] + values, [1] * (len(values) + 1)]) + result = mi2.union(mi1) + expected = mi2.sort_values() + tm.assert_index_equal(result, expected) + + if ( + is_unsigned_integer_dtype(mi2.levels[0]) + and (mi2.get_level_values(0) < 2**63).all() + ): + # GH#47294 - union uses lib.fast_zip, converting data to Python integers + # and loses type information. Result is then unsigned only when values are + # sufficiently large to require unsigned dtype. This happens only if other + # has dups or one of both have missing values + expected = expected.set_levels( + [expected.levels[0].astype(np.int64), expected.levels[1]] + ) + elif is_float_dtype(mi2.levels[0]): + # mi2 has duplicates witch is a different path than above, Fix that path + # to use correct float dtype? + expected = expected.set_levels( + [expected.levels[0].astype(float), expected.levels[1]] + ) + + result = mi1.union(mi2) + tm.assert_index_equal(result, expected) + + +def test_union_keep_dtype_precision(any_real_numeric_dtype): + # GH#48498 + arr1 = Series([4, 1, 1], dtype=any_real_numeric_dtype) + arr2 = Series([1, 4], dtype=any_real_numeric_dtype) + midx = MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None]) + midx2 = MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None]) + + result = midx.union(midx2) + expected = MultiIndex.from_arrays( + ([Series([1, 1, 4], dtype=any_real_numeric_dtype), [1, 1, 2]]), + names=["a", None], + ) + tm.assert_index_equal(result, expected) + + +def test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype): + # GH#48498 + arr1 = Series([4, pd.NA], dtype=any_numeric_ea_dtype) + arr2 = Series([1, pd.NA], dtype=any_numeric_ea_dtype) + midx = MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None]) + midx2 = MultiIndex.from_arrays([arr2, [1, 2]]) + result = midx.union(midx2) + expected = MultiIndex.from_arrays( + [Series([1, 4, pd.NA, pd.NA], dtype=any_numeric_ea_dtype), [1, 2, 1, 2]] + ) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "levels1, levels2, codes1, codes2, names", + [ + ( + [["a", "b", "c"], [0, ""]], + [["c", "d", "b"], [""]], + [[0, 1, 2], [1, 1, 1]], + [[0, 1, 2], [0, 0, 0]], + ["name1", "name2"], + ), + ], +) +def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names): + # GH#25169 + mi1 = MultiIndex(levels=levels1, codes=codes1, names=names) + mi2 = MultiIndex(levels=levels2, codes=codes2, names=names) + mi_int = mi1.intersection(mi2) + assert mi_int._lexsort_depth == 2 + + +@pytest.mark.parametrize( + "a", + [pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]], +) +@pytest.mark.parametrize( + "b", + [ + pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True), + pd.Categorical(["a", "b"], categories=["b", "a"]), + ], +) +def test_intersection_with_non_lex_sorted_categories(a, b): + # GH#49974 + other = ["1", "2"] + + df1 = DataFrame({"x": a, "y": other}) + df2 = DataFrame({"x": b, "y": other}) + + expected = MultiIndex.from_arrays([a, other], names=["x", "y"]) + + res1 = MultiIndex.from_frame(df1).intersection( + MultiIndex.from_frame(df2.sort_values(["x", "y"])) + ) + res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2)) + res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( + MultiIndex.from_frame(df2) + ) + res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( + MultiIndex.from_frame(df2.sort_values(["x", "y"])) + ) + + tm.assert_index_equal(res1, expected) + tm.assert_index_equal(res2, expected) + tm.assert_index_equal(res3, expected) + tm.assert_index_equal(res4, expected) + + +@pytest.mark.parametrize("val", [pd.NA, 100]) +def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype): + # GH#48604 + midx = MultiIndex.from_arrays( + [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] + ) + midx2 = MultiIndex.from_arrays( + [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] + ) + result = midx.intersection(midx2) + expected = MultiIndex.from_arrays([Series([2], dtype=any_numeric_ea_dtype), [1]]) + tm.assert_index_equal(result, expected) + + +def test_union_with_na_when_constructing_dataframe(): + # GH43222 + series1 = Series( + (1,), + index=MultiIndex.from_arrays( + [Series([None], dtype="string"), Series([None], dtype="string")] + ), + ) + series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b")))) + result = DataFrame([series1, series2]) + expected = DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]}) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/ef/ef840214fd788cd87dff1f2ec12a66d06ea476f4c87a6dcf49fd23639f00c798/test_expanders.cpython-311.pyc b/shared/package-files/ef/ef840214fd788cd87dff1f2ec12a66d06ea476f4c87a6dcf49fd23639f00c798/test_expanders.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7be2e7e7a27844c3eda7738baa9dc53f3fa241 Binary files /dev/null and b/shared/package-files/ef/ef840214fd788cd87dff1f2ec12a66d06ea476f4c87a6dcf49fd23639f00c798/test_expanders.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef854bfc0f36cda685c36a305b4262d5193095208357faab72a41cca58038b35/unixccompiler.cpython-311.pyc b/shared/package-files/ef/ef854bfc0f36cda685c36a305b4262d5193095208357faab72a41cca58038b35/unixccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42aeb3b01d1c28a5913f8e69d5640ad535ac9ea5 Binary files /dev/null and b/shared/package-files/ef/ef854bfc0f36cda685c36a305b4262d5193095208357faab72a41cca58038b35/unixccompiler.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef8561c4d265bc26539b6261dedebd37c419464953423a8cbea14c2d5c022909/__init__.py b/shared/package-files/ef/ef8561c4d265bc26539b6261dedebd37c419464953423a8cbea14c2d5c022909/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eded44ee3c0f34ad1324765ba06ee9d6eb5e9899 --- /dev/null +++ b/shared/package-files/ef/ef8561c4d265bc26539b6261dedebd37c419464953423a8cbea14c2d5c022909/__init__.py @@ -0,0 +1,122 @@ +"""Module with some functions for MathML, like transforming MathML +content in MathML presentation. + +To use this module, you will need lxml. +""" + +from pathlib import Path + +from sympy.utilities.decorator import doctest_depends_on + + +__doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']} + + +def add_mathml_headers(s): + return """""" + s + "" + + +def _read_binary(pkgname, filename): + import sys + + if sys.version_info >= (3, 10): + # files was added in Python 3.9 but only seems to work here in 3.10+ + from importlib.resources import files + return files(pkgname).joinpath(filename).read_bytes() + else: + # read_binary was deprecated in Python 3.11 + from importlib.resources import read_binary + return read_binary(pkgname, filename) + + +def _read_xsl(xsl): + # Previously these values were allowed: + if xsl == 'mathml/data/simple_mmlctop.xsl': + xsl = 'simple_mmlctop.xsl' + elif xsl == 'mathml/data/mmlctop.xsl': + xsl = 'mmlctop.xsl' + elif xsl == 'mathml/data/mmltex.xsl': + xsl = 'mmltex.xsl' + + if xsl in ['simple_mmlctop.xsl', 'mmlctop.xsl', 'mmltex.xsl']: + xslbytes = _read_binary('sympy.utilities.mathml.data', xsl) + else: + xslbytes = Path(xsl).read_bytes() + + return xslbytes + + +@doctest_depends_on(modules=('lxml',)) +def apply_xsl(mml, xsl): + """Apply a xsl to a MathML string. + + Parameters + ========== + + mml + A string with MathML code. + xsl + A string giving the name of an xsl (xml stylesheet) file which can be + found in sympy/utilities/mathml/data. The following files are supplied + with SymPy: + + - mmlctop.xsl + - mmltex.xsl + - simple_mmlctop.xsl + + Alternatively, a full path to an xsl file can be given. + + Examples + ======== + + >>> from sympy.utilities.mathml import apply_xsl + >>> xsl = 'simple_mmlctop.xsl' + >>> mml = ' a b ' + >>> res = apply_xsl(mml,xsl) + >>> print(res) + + + a + + + b + + """ + from lxml import etree + + parser = etree.XMLParser(resolve_entities=False) + ac = etree.XSLTAccessControl.DENY_ALL + + s = etree.XML(_read_xsl(xsl), parser=parser) + transform = etree.XSLT(s, access_control=ac) + doc = etree.XML(mml, parser=parser) + result = transform(doc) + s = str(result) + return s + + +@doctest_depends_on(modules=('lxml',)) +def c2p(mml, simple=False): + """Transforms a document in MathML content (like the one that sympy produces) + in one document in MathML presentation, more suitable for printing, and more + widely accepted + + Examples + ======== + + >>> from sympy.utilities.mathml import c2p + >>> mml = ' 2 ' + >>> c2p(mml,simple=True) != c2p(mml,simple=False) + True + + """ + + if not mml.startswith(' +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _euclidean_dist { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_euclidean_dist"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_euclidean_dist(Tensor x1, Tensor x2) -> Tensor"; + static at::Tensor call(const at::Tensor & x1, const at::Tensor & x2); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x1, const at::Tensor & x2); +}; + +struct TORCH_API _euclidean_dist_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_euclidean_dist"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_euclidean_dist.out(Tensor x1, Tensor x2, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & x1, const at::Tensor & x2, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x1, const at::Tensor & x2, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/ef902ef94722ad78adefd08a8697228e13cb9d27b24f9b6205f184eaca9fa337/xnnpack_quantizer.cpython-311.pyc b/shared/package-files/ef/ef902ef94722ad78adefd08a8697228e13cb9d27b24f9b6205f184eaca9fa337/xnnpack_quantizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7994311600252c0cb780d7aa09aa9dde3d51fc73 Binary files /dev/null and b/shared/package-files/ef/ef902ef94722ad78adefd08a8697228e13cb9d27b24f9b6205f184eaca9fa337/xnnpack_quantizer.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef915ef7c0b031ac53ba5726ace77e2a5a119ad61ca9d42c9063093fd363cbae/_cummin_helper_ops.h b/shared/package-files/ef/ef915ef7c0b031ac53ba5726ace77e2a5a119ad61ca9d42c9063093fd363cbae/_cummin_helper_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a33fe09430ac1f2c070964a63e0d53332a2cb89f --- /dev/null +++ b/shared/package-files/ef/ef915ef7c0b031ac53ba5726ace77e2a5a119ad61ca9d42c9063093fd363cbae/_cummin_helper_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _cummin_helper { + using schema = void (const at::Tensor &, at::Tensor &, at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_cummin_helper"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()"; + static void call(const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim); + static void redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/ef924b9bc2c4e63741e21ce6ec6a37f2bd3a8621faccc3d2508e8992f941c9b9/test_markers.cpython-311.pyc b/shared/package-files/ef/ef924b9bc2c4e63741e21ce6ec6a37f2bd3a8621faccc3d2508e8992f941c9b9/test_markers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42a233994e67c6f27d4a3fa8afbfaeb5bedcce50 Binary files /dev/null and b/shared/package-files/ef/ef924b9bc2c4e63741e21ce6ec6a37f2bd3a8621faccc3d2508e8992f941c9b9/test_markers.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef92d264c81a7c1de56c715f7998a04fdcd6e201e5e947e9c88e4db3435a24cf/cumprod_native.h b/shared/package-files/ef/ef92d264c81a7c1de56c715f7998a04fdcd6e201e5e947e9c88e4db3435a24cf/cumprod_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a2f27b8d988700d8af4fe296113d18d2ddbe3e64 --- /dev/null +++ b/shared/package-files/ef/ef92d264c81a7c1de56c715f7998a04fdcd6e201e5e947e9c88e4db3435a24cf/cumprod_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_cumprod_out : public at::meta::structured_cumprod { +void impl(const at::Tensor & self, int64_t dim, ::std::optional dtype, const at::Tensor & out); +}; +TORCH_API at::Tensor cumprod(const at::Tensor & self, at::Dimname dim, ::std::optional dtype=::std::nullopt); +TORCH_API at::Tensor & cumprod_out(const at::Tensor & self, at::Dimname dim, ::std::optional dtype, at::Tensor & out); +TORCH_API at::Tensor & cumprod_(at::Tensor & self, at::Dimname dim, ::std::optional dtype=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/ef/ef95eade0627efd2c8232bac125b5b1da9f46c4800b767bf09a2fb28b4bcf8a4/test_bdist_deprecations.py b/shared/package-files/ef/ef95eade0627efd2c8232bac125b5b1da9f46c4800b767bf09a2fb28b4bcf8a4/test_bdist_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d67b06161a2b36e7b15fab09f797c5c15575c2 --- /dev/null +++ b/shared/package-files/ef/ef95eade0627efd2c8232bac125b5b1da9f46c4800b767bf09a2fb28b4bcf8a4/test_bdist_deprecations.py @@ -0,0 +1,28 @@ +"""develop tests""" + +import sys +from unittest import mock + +import pytest + +from setuptools import SetuptoolsDeprecationWarning +from setuptools.dist import Distribution + + +@pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') +@pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #1988") +@mock.patch('distutils.command.bdist_rpm.bdist_rpm') +def test_bdist_rpm_warning(distutils_cmd, tmpdir_cwd): + dist = Distribution( + dict( + script_name='setup.py', + script_args=['bdist_rpm'], + name='foo', + py_modules=['hi'], + ) + ) + dist.parse_command_line() + with pytest.warns(SetuptoolsDeprecationWarning): + dist.run_commands() + + distutils_cmd.run.assert_called_once() diff --git a/shared/package-files/ef/ef967a0a25ab404f1d0e87dccc74563768adf17f39ec10ea9744269d39a5c718/test_trigonometry.cpython-311.pyc b/shared/package-files/ef/ef967a0a25ab404f1d0e87dccc74563768adf17f39ec10ea9744269d39a5c718/test_trigonometry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b3832e1d9fdb269fe4a5945aa0a05802b83dc3 Binary files /dev/null and b/shared/package-files/ef/ef967a0a25ab404f1d0e87dccc74563768adf17f39ec10ea9744269d39a5c718/test_trigonometry.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef9832af984833cd184e82bce62ea96a1ab7ad31f6f4ef1171bc7376125b7ac7/test_string.cpython-311.pyc b/shared/package-files/ef/ef9832af984833cd184e82bce62ea96a1ab7ad31f6f4ef1171bc7376125b7ac7/test_string.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1031875e1d78a007d7f6a9c40a77a18192acd21e Binary files /dev/null and b/shared/package-files/ef/ef9832af984833cd184e82bce62ea96a1ab7ad31f6f4ef1171bc7376125b7ac7/test_string.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef98b7fd81dd283425c9dbc30269e3fbf08f3a658653cd14f01bc0ba4dc25df3/test_interval_graph.cpython-311.pyc b/shared/package-files/ef/ef98b7fd81dd283425c9dbc30269e3fbf08f3a658653cd14f01bc0ba4dc25df3/test_interval_graph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ba5e990c193578a45058aa04d8716ecbb13f46e Binary files /dev/null and b/shared/package-files/ef/ef98b7fd81dd283425c9dbc30269e3fbf08f3a658653cd14f01bc0ba4dc25df3/test_interval_graph.cpython-311.pyc differ diff --git a/shared/package-files/ef/ef9920bb8d02fdbedf403af593c017da6dfe7d1248d9b8a474a2efa1bc1c382c/moveaxis_native.h b/shared/package-files/ef/ef9920bb8d02fdbedf403af593c017da6dfe7d1248d9b8a474a2efa1bc1c382c/moveaxis_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2639a91c4d9315c1b2ab5fc8ea413fb075dc4382 --- /dev/null +++ b/shared/package-files/ef/ef9920bb8d02fdbedf403af593c017da6dfe7d1248d9b8a474a2efa1bc1c382c/moveaxis_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor moveaxis(const at::Tensor & self, at::IntArrayRef source, at::IntArrayRef destination); +TORCH_API at::Tensor moveaxis(const at::Tensor & self, int64_t source, int64_t destination); +} // namespace native +} // namespace at diff --git a/shared/package-files/ef/ef9f24e8958c812e5d65a43680b1190f9fc15264342421cc04a14563a14b8bb0/test_ast.cpython-311.pyc b/shared/package-files/ef/ef9f24e8958c812e5d65a43680b1190f9fc15264342421cc04a14563a14b8bb0/test_ast.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0688d3ec2084c6fae26237c21b368bbd1b5e784 Binary files /dev/null and b/shared/package-files/ef/ef9f24e8958c812e5d65a43680b1190f9fc15264342421cc04a14563a14b8bb0/test_ast.cpython-311.pyc differ diff --git a/shared/package-files/ef/efa2413c6083904e287b92182f5698893f20161ea99df03e165e3c898fef7471/test_pandas.cpython-311.pyc b/shared/package-files/ef/efa2413c6083904e287b92182f5698893f20161ea99df03e165e3c898fef7471/test_pandas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53c52a349b0ca4a421fe55f069ea941c40a78e4d Binary files /dev/null and b/shared/package-files/ef/efa2413c6083904e287b92182f5698893f20161ea99df03e165e3c898fef7471/test_pandas.cpython-311.pyc differ diff --git a/shared/package-files/ef/efa3215013d8715d8758e453f66716a050022244287f55027576d059c0ee46bf/conflict.py b/shared/package-files/ef/efa3215013d8715d8758e453f66716a050022244287f55027576d059c0ee46bf/conflict.py new file mode 100644 index 0000000000000000000000000000000000000000..44a893ad56a40b69e600dca737860fd3df69e4f4 --- /dev/null +++ b/shared/package-files/ef/efa3215013d8715d8758e453f66716a050022244287f55027576d059c0ee46bf/conflict.py @@ -0,0 +1,139 @@ +# mypy: allow-untyped-defs +import operator + +from .utils import _toposort, groupby +from .variadic import isvariadic + + +__all__ = [ + "AmbiguityWarning", + "supercedes", + "consistent", + "ambiguous", + "ambiguities", + "super_signature", + "edge", + "ordering", +] + + +class AmbiguityWarning(Warning): + pass + + +def supercedes(a, b): + """A is consistent and strictly more specific than B""" + if len(a) < len(b): + # only case is if a is empty and b is variadic + return not a and len(b) == 1 and isvariadic(b[-1]) + elif len(a) == len(b): + return all(map(issubclass, a, b)) + else: + # len(a) > len(b) + p1 = 0 + p2 = 0 + while p1 < len(a) and p2 < len(b): + cur_a = a[p1] + cur_b = b[p2] + if not (isvariadic(cur_a) or isvariadic(cur_b)): + if not issubclass(cur_a, cur_b): + return False + p1 += 1 + p2 += 1 + elif isvariadic(cur_a): + assert p1 == len(a) - 1 + return p2 == len(b) - 1 and issubclass(cur_a, cur_b) + elif isvariadic(cur_b): + assert p2 == len(b) - 1 + if not issubclass(cur_a, cur_b): + return False + p1 += 1 + return p2 == len(b) - 1 and p1 == len(a) + + +def consistent(a, b): + """It is possible for an argument list to satisfy both A and B""" + + # Need to check for empty args + if not a: + return not b or isvariadic(b[0]) + if not b: + return not a or isvariadic(a[0]) + + # Non-empty args check for mutual subclasses + if len(a) == len(b): + return all(issubclass(aa, bb) or issubclass(bb, aa) for aa, bb in zip(a, b)) + else: + p1 = 0 + p2 = 0 + while p1 < len(a) and p2 < len(b): + cur_a = a[p1] + cur_b = b[p2] + if not issubclass(cur_b, cur_a) and not issubclass(cur_a, cur_b): + return False + if not (isvariadic(cur_a) or isvariadic(cur_b)): + p1 += 1 + p2 += 1 + elif isvariadic(cur_a): + p2 += 1 + elif isvariadic(cur_b): + p1 += 1 + # We only need to check for variadic ends + # Variadic types are guaranteed to be the last element + return ( + isvariadic(cur_a) # type: ignore[possibly-undefined] + and p2 == len(b) + or isvariadic(cur_b) # type: ignore[possibly-undefined] + and p1 == len(a) + ) + + +def ambiguous(a, b): + """A is consistent with B but neither is strictly more specific""" + return consistent(a, b) and not (supercedes(a, b) or supercedes(b, a)) + + +def ambiguities(signatures): + """All signature pairs such that A is ambiguous with B""" + signatures = list(map(tuple, signatures)) + return { + (a, b) + for a in signatures + for b in signatures + if hash(a) < hash(b) + and ambiguous(a, b) + and not any(supercedes(c, a) and supercedes(c, b) for c in signatures) + } + + +def super_signature(signatures): + """A signature that would break ambiguities""" + n = len(signatures[0]) + assert all(len(s) == n for s in signatures) + + return [max((type.mro(sig[i]) for sig in signatures), key=len)[0] for i in range(n)] + + +def edge(a, b, tie_breaker=hash): + """A should be checked before B + Tie broken by tie_breaker, defaults to ``hash`` + """ + # A either supercedes B and B does not supercede A or if B does then call + # tie_breaker + return supercedes(a, b) and ( + not supercedes(b, a) or tie_breaker(a) > tie_breaker(b) + ) + + +def ordering(signatures): + """A sane ordering of signatures to check, first to last + Topological sort of edges as given by ``edge`` and ``supercedes`` + """ + signatures = list(map(tuple, signatures)) + edges = [(a, b) for a in signatures for b in signatures if edge(a, b)] + edges = groupby(operator.itemgetter(0), edges) + for s in signatures: + if s not in edges: + edges[s] = [] + edges = {k: [b for a, b in v] for k, v in edges.items()} # type: ignore[assignment, attr-defined] + return _toposort(edges) diff --git a/shared/package-files/ef/efa3ccb8bfdbc1a79d6b805fc0ee734823e2b19e8fbbdcb2a62490d9960aeaf7/autotune_cache.py b/shared/package-files/ef/efa3ccb8bfdbc1a79d6b805fc0ee734823e2b19e8fbbdcb2a62490d9960aeaf7/autotune_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0c098f6afa46a4172d4ebe46e8deae8459da5288 --- /dev/null +++ b/shared/package-files/ef/efa3ccb8bfdbc1a79d6b805fc0ee734823e2b19e8fbbdcb2a62490d9960aeaf7/autotune_cache.py @@ -0,0 +1,533 @@ +from __future__ import annotations + +import dataclasses +import hashlib +import logging +import os +import os.path +import re +from typing import Any, Optional, TYPE_CHECKING +from typing_extensions import override + +import torch +from torch.compiler._cache import CacheArtifactManager, CacheArtifactType +from torch.utils._triton import has_triton + +from ..remote_cache import ( + create_cache, + JsonDataTy, + RemoteCache, + RemoteCacheBackend, + RemoteCacheJsonSerde, +) +from .triton_compat import Config + + +if TYPE_CHECKING: + from ..remote_cache import Sample + +log = logging.getLogger(__name__) + + +_InductorMetaTy = dict[str, object] + + +def inductor_meta_from_config() -> _InductorMetaTy: + from torch._inductor import config + + backend_hash = None + if has_triton(): + try: + backend_hash = torch.utils._triton.triton_hash_with_backend() + except RuntimeError: + # This can get the error: + # RuntimeError: 0 active drivers ([]). There should only be one. + pass + + is_hip = None + if torch.version.hip is not None: + is_hip = True + + return { + "autotune_local_cache": config.autotune_local_cache, + "autotune_remote_cache": config.autotune_remote_cache, + "backend_hash": backend_hash, + "bundled_autotune_remote_cache": config.bundled_autotune_remote_cache, + "coordinate_descent_tuning": config.coordinate_descent_tuning, + "is_fbcode": config.is_fbcode(), + "is_hip": is_hip, + } + + +@dataclasses.dataclass +class AutotuneCache: + configs_hash: str + local_cache: Optional[tuple[RemoteCache[JsonDataTy], str]] = None + remote_cache: Optional[tuple[RemoteCache[JsonDataTy], str]] = None + + # Create a AutotuneCache. Returns None if none of the caches can be used. + @staticmethod + def create( + inductor_meta: _InductorMetaTy, filename: str, configs_hash: str + ) -> Optional[AutotuneCache]: + cache = AutotuneCache(configs_hash) + key = AutotuneCache._prepare_key(filename) + cache._setup_local_cache(inductor_meta, os.path.dirname(filename), key) + cache._setup_remote_autotune_cache(inductor_meta, key) + if cache.local_cache or cache.remote_cache: + return cache + else: + return None + + @staticmethod + def _prepare_key(filename: str) -> str: + from torch.compiler import config as cconfig + + # base of filename is already sha256 hash the source contents + key = f"{os.path.basename(filename)}:{cconfig.cache_key_tag}" + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + # Read the best config options from the most local cache and return it. + def _read(self) -> Optional[dict[str, JsonDataTy]]: + if local_cache := self.local_cache: + cache, key = local_cache + if best_config := cache.get(key): + if isinstance(best_config, dict): + return best_config + + if remote_cache := self.remote_cache: + cache, key = remote_cache + if best_config := cache.get(key): + if isinstance(best_config, dict): + return best_config + + return None + + # Read the best config options from the most local cache and figure out + # which `configs` represents that option. + def read_best( + self, inductor_meta: _InductorMetaTy, configs: list[Config] + ) -> Optional[Config]: + if best := self._read(): + return _load_cached_autotuning( + best, self.configs_hash, configs, inductor_meta + ) + return None + + # Set up local filesystem caching information + def _setup_local_cache( + self, inductor_meta: _InductorMetaTy, dirname: str, cache_key: str + ) -> None: + if not inductor_meta.get("autotune_local_cache", True): + return + + cache_filename = f"{dirname}/{cache_key}.best_config" + local_cache = LocalAutotuneCache() + self.local_cache = (local_cache, cache_filename) + + # Set up remote caching information + def _setup_remote_autotune_cache( + self, inductor_meta: _InductorMetaTy, cache_key: str + ) -> None: + if not _should_use_remote_autotune_cache(inductor_meta): + return + + if (backend_hash := inductor_meta.get("backend_hash", None)) is None: + log.debug( + "backend_hash is not passed on the inductor_meta, unable to use autotune remote cache" + ) + return + assert isinstance(backend_hash, str) + + is_fbcode = bool(inductor_meta.get("is_fbcode", False)) + + salt = "autotune-best-config-v2" + key = backend_hash + self.configs_hash + salt + key = hashlib.sha256(key.encode("utf-8")).hexdigest() + + remote_cache = create_cache( + key, + is_fbcode, + "FbRemoteAutotuneCache", + "RemoteAutotuneCache", + ) + if not remote_cache: + return + + # Save the args passed to create_cache + # in case AutotuneCache needs to be pickled + self.remote_cache_full_key = key + self.is_fbcode = is_fbcode + self.remote_cache = (remote_cache, cache_key) + + # The AutotuneCache may be serialized/deserialized if we're using + # AsyncCompile worker processes to run triton compilation. + # This is because AutotuneCache instances are created on the worker + # process, but we need to run AutotuneCache.save on the parent process + # when actually doing autotuning. + def __getstate__(self) -> dict[str, Any]: + # The remote cache handles themselves may not be serializable + # So clear it and reconstruct it on setstate + remote_cache = getattr(self, "remote_cache", None) + return { + **self.__dict__, + # Save the cache_key portion + "remote_cache": remote_cache and remote_cache[1], + } + + def __setstate__(self, state: dict[str, Any]) -> None: + # Reconstruct the remote cache on the parent class + self.__dict__.update(state) + if self.remote_cache is not None: + assert isinstance(self.remote_cache, str) + assert hasattr(self, "remote_cache_full_key") + assert hasattr(self, "is_fbcode") + cache_key = self.remote_cache + remote_cache = create_cache( + self.remote_cache_full_key, + self.is_fbcode, + "FbRemoteAutotuneCache", + "RemoteAutotuneCache", + ) + if remote_cache is not None: + self.remote_cache = (remote_cache, cache_key) + else: + log.warning("Warning, failed to recreate remote cache after pickling") + self.remote_cache = None + + # Save the config in the caches + def save( + self, config: Config, time_taken_ns: int, found_by_coordesc: bool = False + ) -> None: + data = { + **config.kwargs, + "num_warps": config.num_warps, + "num_stages": config.num_stages, + "configs_hash": self.configs_hash, + "found_by_coordesc": found_by_coordesc, + "time_taken_ms": time_taken_ns // 1000000, # Convert from NS to MS + } + + if local_cache := self.local_cache: + cache, key = local_cache + cache.put(key, data) + AutotuneCacheBundler.put(key, data) + CacheArtifactManager.record_artifact( + CacheArtifactType.AUTOTUNE, os.path.basename(key), data + ) + + if log.isEnabledFor(logging.DEBUG): + type_str = "coordesc" if found_by_coordesc else "heuristic" + log.debug("Save %s tuning result to %s", type_str, key) + + if remote_cache := self.remote_cache: + cache, key = remote_cache + cache.put(key, data) + + +class _AutotuneCacheBundlerImpl: + """ + Caches a set of LocalAutotuneCacheBackend entries together in a single + cache. + """ + + _key: str + _cache: RemoteCache[JsonDataTy] + + # All known entries from LocalAutotuneCache.put() + _entries: dict[str, JsonDataTy] + + def end_compile(self) -> None: + # TODO: Do we need to compute time_taken_ms and encode that somehow? + if self._entries: + self._cache.put(self._key, self._entries) + + def put(self, basename: str, data: JsonDataTy) -> None: + # Do we need to worry about duplicates? We only have a single local fs + # entry - so probably not. + self._entries[basename] = data + + def __init__(self, key: str, cache: RemoteCache[JsonDataTy]) -> None: + self._key = key + self._cache = cache + self._entries = {} + + def sync(self) -> None: + # We don't currently use this - but we could async load starting at + # `begin_compile` and wait for the load to be finished here. + pass + + @classmethod + def _should_use_bundled_autotune_remote_cache( + cls, inductor_meta: _InductorMetaTy + ) -> bool: + # The bundled autotune cache is only available if you've also got local + # caching enabled (because we feed the bundled data to the local cache). + if not inductor_meta.get("autotune_local_cache", True): + return False + + # Check if the we're enabled via config + if ( + bundled_autotune_remote_cache := inductor_meta.get( + "bundled_autotune_remote_cache" + ) + ) is not None: + return bool(bundled_autotune_remote_cache) + + if not cls._get_is_fbcode(inductor_meta): + return False + if torch._utils_internal.is_fb_unit_test(): + return False + if inductor_meta.get("is_hip"): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + jk = torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:bundled_autotune_remote_cache_version" + ) + return REMOTE_CACHE_VERSION >= jk + + def _load_cache(self) -> bool: + from torch._inductor import codecache + + # The single key is defined on construction of the cache. + entries = self._cache.get(self._key) + if entries is None or not isinstance(entries, dict): + # We couldn't load the cache - so mark _entries as non-None so we + # store local cache values. + return False + + # Go through the entries we got from the cache and save them locally. + time_saved_ns = 0 + for basename, data in entries.items(): + # Reconstruct the final filename (see put()) + root, ext = _splitext_nodot(basename) + _, _, filename = codecache.get_path(root, ext) + if isinstance(data, dict) and (tsns := data.get("time_saved_ns")): + time_saved_ns += int(tsns) # type: ignore[arg-type] + local_cache = LocalAutotuneCache() + local_cache.put(filename, data) + + codecache.add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + + return True + + @staticmethod + def _get_is_fbcode(inductor_meta: _InductorMetaTy) -> bool: + return bool(inductor_meta.get("is_fbcode", False)) + + @staticmethod + def _get_backend_hash(inductor_meta: _InductorMetaTy) -> str: + backend_hash = inductor_meta["backend_hash"] + assert isinstance(backend_hash, str) + return backend_hash + + +class AutotuneCacheBundler: + _bundler: Optional[_AutotuneCacheBundlerImpl] = None + + def __init__(self) -> None: + pass + + # Call this before we start any autotune computation for an inductor python + # file. On a cache hit it copies the individual results into the local + # autotune caches. + @classmethod + def begin_compile( + cls, + inductor_meta: _InductorMetaTy, + *, + code: Optional[str] = None, + code_hash: Optional[str] = None, + ) -> None: + assert cls._bundler is None + + if code is not None: + assert code_hash is None, "Cannot specify both code and code_hash" + code_hash = _comment_stripped_hash(code) + assert code_hash is not None + + if not _AutotuneCacheBundlerImpl._should_use_bundled_autotune_remote_cache( + inductor_meta + ): + return + + cache = create_cache( + "bundled-autotune-v1", + _AutotuneCacheBundlerImpl._get_is_fbcode(inductor_meta), + "FbRemoteBundledAutotuneCache", + "RemoteBundledAutotuneCache", + ) + if not cache: + return + + # We're starting a compilation phase. We have a cache key for the code + # we're compiling. We'll get the individual autotune bundles later (via + # self.put()). For now create the AutotuneCacheBundler and try to load + # from the cache. + + salt = "bundled-autotune-best-configs-v1" + backend_hash = _AutotuneCacheBundlerImpl._get_backend_hash(inductor_meta) + # TODO: The autotune cache includes configs_hash in the key. The problem + # is that the configs_hash includes info from the individual pointwise() + # calls (size_hints, for example) which we can't know yet. I *think* + # that info is basically present in the `code_hash` (since it's a + # parameter to the pointwise decorator) - but is there other info we + # need to include from inductor_meta? + key = code_hash + backend_hash + salt + key = hashlib.sha256(key.encode("utf-8")).hexdigest() + + bundler = _AutotuneCacheBundlerImpl(key, cache) + if not bundler._load_cache(): + # We couldn't load from the cache - so save the data so we can store + # the saved autotunes. + cls._bundler = bundler + + # If we get a cache hit don't bother saving any of the individual + # autotune results. + + # Call this after all individual autotune results are finished for a + # inductor python file. If we gathered any individual results then we bundle + # those and put it into the cache. + @classmethod + def end_compile(cls) -> None: + if bundler := cls._bundler: + cls._bundler = None + bundler.end_compile() + + @classmethod + def sync(cls) -> None: + if bundler := cls._bundler: + bundler.sync() + + @classmethod + def put(cls, filename: str, data: JsonDataTy) -> None: + if bundler := cls._bundler: + # The filename comes in as something like + # "/tmp/tmp{random}/{aa}/{basename}.py" (where aa is + # basename[1:3]). Strip it down and make sure that it looks like a path + # we could reconstruct (because it's possible for the caller to + # customize the path). + basename = os.path.basename(filename) + + # TODO: check cache_dir() vs filename, then strip dirname + bundler.put(basename, data) + + +# Remove the comments from the code (which include things like run ids and file +# paths) and then hash the result. +def _comment_stripped_hash(code: str) -> str: + code = re.sub(r"#.*$", "", code, count=0, flags=re.MULTILINE) + return torch._inductor.codecache.code_hash(code) + + +def _should_use_remote_autotune_cache(inductor_meta: _InductorMetaTy) -> bool: + if (config := inductor_meta.get("autotune_remote_cache")) is not None: + return bool(config) + if not inductor_meta.get("is_fbcode"): + return False + if torch._utils_internal.is_fb_unit_test(): + return False + if inductor_meta.get("is_hip"): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:autotune_memcache_version" + ) + + +def _load_cached_autotuning( + best_config: dict[str, JsonDataTy], + configs_hash: str, + configs: list[Config], + inductor_meta: _InductorMetaTy, +) -> Optional[Config]: + if best_config is None: + return None + if best_config.pop("configs_hash", None) != configs_hash: + return None + + # Remove time taken for comparison + best_config.pop("time_taken_ms", None) + + if inductor_meta.get("coordinate_descent_tuning") and best_config.pop( + "found_by_coordesc", False + ): + num_warps = best_config.pop("num_warps") + num_stages = best_config.pop("num_stages") + triton_config = Config(best_config, num_warps=num_warps, num_stages=num_stages) + triton_config.found_by_coordesc = True + return triton_config + + matching_configs = [ + cfg + for cfg in configs + if all(val == best_config.get(key) for key, val in cfg.kwargs.items()) + and cfg.num_warps == best_config.get("num_warps") + and cfg.num_stages == best_config.get("num_stages") + ] + if len(matching_configs) != 1: + return None + + return matching_configs[0] + + +class _LocalAutotuneCacheBackend(RemoteCacheBackend[bytes]): + @override + def _get(self, key: str) -> Optional[bytes]: + try: + with open(key, "rb") as fd: + return fd.read() + except FileNotFoundError: + return None + + @override + def _put(self, key: str, data: bytes) -> None: + os.makedirs(os.path.dirname(key), exist_ok=True) + with open(key, "wb") as fd: + fd.write(data) + + +class LocalAutotuneCache(RemoteCache[JsonDataTy]): + def __init__(self) -> None: + backend = _LocalAutotuneCacheBackend() + serde = RemoteCacheJsonSerde() + super().__init__(backend, serde) + + @override + def _get(self, key: str, sample: Optional[Sample]) -> Optional[JsonDataTy]: + AutotuneCacheBundler.sync() + result = super()._get(key, sample) + if result is not None: + assert isinstance(result, dict) + # What? Why are we doing a put() here? Imagine we have a new model + # that reuses some existing kernels that have already been + # compiled. If we didn't do a `put` here (on cache hit) then the new + # model would only bundle *newly* compiled kernels, not existing + # kernels that were already compiled and cached. + AutotuneCacheBundler.put(key, result) + CacheArtifactManager.record_artifact( + CacheArtifactType.AUTOTUNE, os.path.basename(key), result + ) + return result + + @override + def _put(self, key: str, value: JsonDataTy, sample: Optional[Sample]) -> None: + AutotuneCacheBundler.put(key, value) + super()._put(key, value, sample) + + +def _splitext_nodot(basename: str) -> tuple[str, str]: + root, ext = os.path.splitext(basename) + if ext: + ext = ext[1:] + return root, ext diff --git a/shared/package-files/ef/efa3da2e9fc277d0408abcba55c5940f81ebafaf03ea54ce91271670bca198bd/test_util.py b/shared/package-files/ef/efa3da2e9fc277d0408abcba55c5940f81ebafaf03ea54ce91271670bca198bd/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3522af675d33275f322e2b731309e19bffde1e1d --- /dev/null +++ b/shared/package-files/ef/efa3da2e9fc277d0408abcba55c5940f81ebafaf03ea54ce91271670bca198bd/test_util.py @@ -0,0 +1,178 @@ +from sympy.core.containers import Tuple +from sympy.core.numbers import pi +from sympy.core.power import Pow +from sympy.core.symbol import symbols +from sympy.core.sympify import sympify +from sympy.printing.str import sstr +from sympy.physics.units import ( + G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin, + kilogram, kilometer, length, meter, mile, minute, newton, planck, + planck_length, planck_mass, planck_temperature, planck_time, radians, + second, speed_of_light, steradian, time, km) +from sympy.physics.units.util import convert_to, check_dimensions +from sympy.testing.pytest import raises +from sympy.functions.elementary.miscellaneous import sqrt + + +def NS(e, n=15, **options): + return sstr(sympify(e).evalf(n, **options), full_prec=True) + + +L = length +T = time + + +def test_dim_simplify_add(): + # assert Add(L, L) == L + assert L + L == L + + +def test_dim_simplify_mul(): + # assert Mul(L, T) == L*T + assert L*T == L*T + + +def test_dim_simplify_pow(): + assert Pow(L, 2) == L**2 + + +def test_dim_simplify_rec(): + # assert Mul(Add(L, L), T) == L*T + assert (L + L) * T == L*T + + +def test_convert_to_quantities(): + assert convert_to(3, meter) == 3 + + assert convert_to(mile, kilometer) == 25146*kilometer/15625 + assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458 + assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light + assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light + assert convert_to(speed_of_light, meter/second) == 299792458*meter/second + assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second + assert convert_to(day, second) == 86400*second + assert convert_to(2*hour, minute) == 120*minute + assert convert_to(mile, meter) == 201168*meter/125 + assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour) + assert convert_to(3*newton, meter/second) == 3*newton + assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2 + assert convert_to(kilometer + mile, meter) == 326168*meter/125 + assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125 + assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000 + assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000 + assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second) + assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second) + assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2 + + assert convert_to(steradian, coulomb) == steradian + assert convert_to(radians, degree) == 180*degree/pi + assert convert_to(radians, [meter, degree]) == 180*degree/pi + assert convert_to(pi*radians, degree) == 180*degree + assert convert_to(pi, degree) == 180*degree + + # https://github.com/sympy/sympy/issues/26263 + assert convert_to(sqrt(meter**2 + meter**2.0), meter) == sqrt(meter**2 + meter**2.0) + assert convert_to((meter**2 + meter**2.0)**2, meter) == (meter**2 + meter**2.0)**2 + + +def test_convert_to_tuples_of_quantities(): + from sympy.core.symbol import symbols + + alpha, beta = symbols('alpha beta') + + assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second + assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second + assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second + assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2 + assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2 + assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light + assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2 + # This doesn't make physically sense, but let's keep it as a conversion test: + assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second + assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G + + assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000/speed_of_light**1.500000' + assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram' + assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter' + assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second' + assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin' + assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter' + + # similar to https://github.com/sympy/sympy/issues/26263 + assert convert_to(sqrt(meter**2 + second**2.0), [meter, second]) == sqrt(meter**2 + second**2.0) + assert convert_to((meter**2 + second**2.0)**2, [meter, second]) == (meter**2 + second**2.0)**2 + + # similar to https://github.com/sympy/sympy/issues/21463 + assert convert_to(1/(beta*meter + meter), 1/meter) == 1/(beta*meter + meter) + assert convert_to(1/(beta*meter + alpha*meter), 1/kilometer) == (1/(kilometer*beta/1000 + alpha*kilometer/1000)) + +def test_eval_simplify(): + from sympy.physics.units import cm, mm, km, m, K, kilo + from sympy.core.symbol import symbols + + x, y = symbols('x y') + + assert (cm/mm).simplify() == 10 + assert (km/m).simplify() == 1000 + assert (km/cm).simplify() == 100000 + assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin + assert (cm/km/m).simplify() == 1/(10000000*centimeter) + + assert (3*kilo*meter).simplify() == 3000*meter + assert (4*kilo*meter/(2*kilometer)).simplify() == 2 + assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4 + + +def test_quantity_simplify(): + from sympy.physics.units.util import quantity_simplify + from sympy.physics.units import kilo, foot + from sympy.core.symbol import symbols + + x, y = symbols('x y') + + assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y) + assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12 + assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12 + assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12 + assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144 + +def test_quantity_simplify_across_dimensions(): + from sympy.physics.units.util import quantity_simplify + from sympy.physics.units import ampere, ohm, volt, joule, pascal, farad, second, watt, siemens, henry, tesla, weber, hour, newton + + assert quantity_simplify(ampere*ohm, across_dimensions=True, unit_system="SI") == volt + assert quantity_simplify(6*ampere*ohm, across_dimensions=True, unit_system="SI") == 6*volt + assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm + assert quantity_simplify(volt/ohm, across_dimensions=True, unit_system="SI") == ampere + assert quantity_simplify(joule/meter**3, across_dimensions=True, unit_system="SI") == pascal + assert quantity_simplify(farad*ohm, across_dimensions=True, unit_system="SI") == second + assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt + assert quantity_simplify(meter**3/second, across_dimensions=True, unit_system="SI") == meter**3/second + assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt + + assert quantity_simplify(joule/coulomb, across_dimensions=True, unit_system="SI") == volt + assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm + assert quantity_simplify(ampere/volt, across_dimensions=True, unit_system="SI") == siemens + assert quantity_simplify(coulomb/volt, across_dimensions=True, unit_system="SI") == farad + assert quantity_simplify(volt*second/ampere, across_dimensions=True, unit_system="SI") == henry + assert quantity_simplify(volt*second/meter**2, across_dimensions=True, unit_system="SI") == tesla + assert quantity_simplify(joule/ampere, across_dimensions=True, unit_system="SI") == weber + + assert quantity_simplify(5*kilometer/hour, across_dimensions=True, unit_system="SI") == 25*meter/(18*second) + assert quantity_simplify(5*kilogram*meter/second**2, across_dimensions=True, unit_system="SI") == 5*newton + +def test_check_dimensions(): + x = symbols('x') + assert check_dimensions(inch + x) == inch + x + assert check_dimensions(length + x) == length + x + # after subs we get 2*length; check will clear the constant + assert check_dimensions((length + x).subs(x, length)) == length + assert check_dimensions(newton*meter + joule) == joule + meter*newton + raises(ValueError, lambda: check_dimensions(inch + 1)) + raises(ValueError, lambda: check_dimensions(length + 1)) + raises(ValueError, lambda: check_dimensions(length + time)) + raises(ValueError, lambda: check_dimensions(meter + second)) + raises(ValueError, lambda: check_dimensions(2 * meter + second)) + raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second)) + raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter)) + raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km)) diff --git a/shared/package-files/ef/efa479c1ebcbc004c0f01090c06c0fd7f5386ac5ca627b56e26f99e9f05e61b7/test_misc.py b/shared/package-files/ef/efa479c1ebcbc004c0f01090c06c0fd7f5386ac5ca627b56e26f99e9f05e61b7/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d70d9a3161c8fd3f5091696382d3da5969a62b --- /dev/null +++ b/shared/package-files/ef/efa479c1ebcbc004c0f01090c06c0fd7f5386ac5ca627b56e26f99e9f05e61b7/test_misc.py @@ -0,0 +1,268 @@ +import random +from copy import copy + +import pytest + +import networkx as nx +from networkx.utils import ( + PythonRandomInterface, + PythonRandomViaNumpyBits, + arbitrary_element, + create_py_random_state, + create_random_state, + dict_to_numpy_array, + discrete_sequence, + flatten, + groups, + make_list_of_ints, + pairwise, + powerlaw_sequence, +) +from networkx.utils.misc import _dict_to_numpy_array1, _dict_to_numpy_array2 + +nested_depth = ( + 1, + 2, + (3, 4, ((5, 6, (7,), (8, (9, 10), 11), (12, 13, (14, 15)), 16), 17), 18, 19), + 20, +) + +nested_set = { + (1, 2, 3, 4), + (5, 6, 7, 8, 9), + (10, 11, (12, 13, 14), (15, 16, 17, 18)), + 19, + 20, +} + +nested_mixed = [ + 1, + (2, 3, {4, (5, 6), 7}, [8, 9]), + {10: "foo", 11: "bar", (12, 13): "baz"}, + {(14, 15): "qwe", 16: "asd"}, + (17, (18, "19"), 20), +] + + +@pytest.mark.parametrize("result", [None, [], ["existing"], ["existing1", "existing2"]]) +@pytest.mark.parametrize("nested", [nested_depth, nested_mixed, nested_set]) +def test_flatten(nested, result): + if result is None: + val = flatten(nested, result) + assert len(val) == 20 + else: + _result = copy(result) # because pytest passes parameters as is + nexisting = len(_result) + val = flatten(nested, _result) + assert len(val) == len(_result) == 20 + nexisting + + assert issubclass(type(val), tuple) + + +def test_make_list_of_ints(): + mylist = [1, 2, 3.0, 42, -2] + assert make_list_of_ints(mylist) is mylist + assert make_list_of_ints(mylist) == mylist + assert isinstance(make_list_of_ints(mylist)[2], int) + pytest.raises(nx.NetworkXError, make_list_of_ints, [1, 2, 3, "kermit"]) + pytest.raises(nx.NetworkXError, make_list_of_ints, [1, 2, 3.1]) + + +def test_random_number_distribution(): + # smoke test only + z = powerlaw_sequence(20, exponent=2.5) + z = discrete_sequence(20, distribution=[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3]) + + +class TestNumpyArray: + @classmethod + def setup_class(cls): + global np + np = pytest.importorskip("numpy") + + def test_numpy_to_list_of_ints(self): + a = np.array([1, 2, 3], dtype=np.int64) + b = np.array([1.0, 2, 3]) + c = np.array([1.1, 2, 3]) + assert isinstance(make_list_of_ints(a), list) + assert make_list_of_ints(b) == list(b) + B = make_list_of_ints(b) + assert isinstance(B[0], int) + pytest.raises(nx.NetworkXError, make_list_of_ints, c) + + def test__dict_to_numpy_array1(self): + d = {"a": 1, "b": 2} + a = _dict_to_numpy_array1(d, mapping={"a": 0, "b": 1}) + np.testing.assert_allclose(a, np.array([1, 2])) + a = _dict_to_numpy_array1(d, mapping={"b": 0, "a": 1}) + np.testing.assert_allclose(a, np.array([2, 1])) + + a = _dict_to_numpy_array1(d) + np.testing.assert_allclose(a.sum(), 3) + + def test__dict_to_numpy_array2(self): + d = {"a": {"a": 1, "b": 2}, "b": {"a": 10, "b": 20}} + + mapping = {"a": 1, "b": 0} + a = _dict_to_numpy_array2(d, mapping=mapping) + np.testing.assert_allclose(a, np.array([[20, 10], [2, 1]])) + + a = _dict_to_numpy_array2(d) + np.testing.assert_allclose(a.sum(), 33) + + def test_dict_to_numpy_array_a(self): + d = {"a": {"a": 1, "b": 2}, "b": {"a": 10, "b": 20}} + + mapping = {"a": 0, "b": 1} + a = dict_to_numpy_array(d, mapping=mapping) + np.testing.assert_allclose(a, np.array([[1, 2], [10, 20]])) + + mapping = {"a": 1, "b": 0} + a = dict_to_numpy_array(d, mapping=mapping) + np.testing.assert_allclose(a, np.array([[20, 10], [2, 1]])) + + a = _dict_to_numpy_array2(d) + np.testing.assert_allclose(a.sum(), 33) + + def test_dict_to_numpy_array_b(self): + d = {"a": 1, "b": 2} + + mapping = {"a": 0, "b": 1} + a = dict_to_numpy_array(d, mapping=mapping) + np.testing.assert_allclose(a, np.array([1, 2])) + + a = _dict_to_numpy_array1(d) + np.testing.assert_allclose(a.sum(), 3) + + +def test_pairwise(): + nodes = range(4) + node_pairs = [(0, 1), (1, 2), (2, 3)] + node_pairs_cycle = node_pairs + [(3, 0)] + assert list(pairwise(nodes)) == node_pairs + assert list(pairwise(iter(nodes))) == node_pairs + assert list(pairwise(nodes, cyclic=True)) == node_pairs_cycle + empty_iter = iter(()) + assert list(pairwise(empty_iter)) == [] + empty_iter = iter(()) + assert list(pairwise(empty_iter, cyclic=True)) == [] + + +def test_groups(): + many_to_one = dict(zip("abcde", [0, 0, 1, 1, 2])) + actual = groups(many_to_one) + expected = {0: {"a", "b"}, 1: {"c", "d"}, 2: {"e"}} + assert actual == expected + assert {} == groups({}) + + +def test_create_random_state(): + np = pytest.importorskip("numpy") + rs = np.random.RandomState + + assert isinstance(create_random_state(1), rs) + assert isinstance(create_random_state(None), rs) + assert isinstance(create_random_state(np.random), rs) + assert isinstance(create_random_state(rs(1)), rs) + # Support for numpy.random.Generator + rng = np.random.default_rng() + assert isinstance(create_random_state(rng), np.random.Generator) + pytest.raises(ValueError, create_random_state, "a") + + assert np.all(rs(1).rand(10) == create_random_state(1).rand(10)) + + +def test_create_py_random_state(): + pyrs = random.Random + + assert isinstance(create_py_random_state(1), pyrs) + assert isinstance(create_py_random_state(None), pyrs) + assert isinstance(create_py_random_state(pyrs(1)), pyrs) + pytest.raises(ValueError, create_py_random_state, "a") + + np = pytest.importorskip("numpy") + + rs = np.random.RandomState + rng = np.random.default_rng(1000) + rng_explicit = np.random.Generator(np.random.SFC64()) + old_nprs = PythonRandomInterface + nprs = PythonRandomViaNumpyBits + assert isinstance(create_py_random_state(np.random), nprs) + assert isinstance(create_py_random_state(rs(1)), old_nprs) + assert isinstance(create_py_random_state(rng), nprs) + assert isinstance(create_py_random_state(rng_explicit), nprs) + # test default rng input + assert isinstance(PythonRandomInterface(), old_nprs) + assert isinstance(PythonRandomViaNumpyBits(), nprs) + + # VeryLargeIntegers Smoke test (they raise error for np.random) + int64max = 9223372036854775807 # from np.iinfo(np.int64).max + for r in (rng, rs(1)): + prs = create_py_random_state(r) + prs.randrange(3, int64max + 5) + prs.randint(3, int64max + 5) + + +def test_PythonRandomInterface_RandomState(): + np = pytest.importorskip("numpy") + + seed = 42 + rs = np.random.RandomState + rng = PythonRandomInterface(rs(seed)) + rs42 = rs(seed) + + # make sure these functions are same as expected outcome + assert rng.randrange(3, 5) == rs42.randint(3, 5) + assert rng.choice([1, 2, 3]) == rs42.choice([1, 2, 3]) + assert rng.gauss(0, 1) == rs42.normal(0, 1) + assert rng.expovariate(1.5) == rs42.exponential(1 / 1.5) + assert np.all(rng.shuffle([1, 2, 3]) == rs42.shuffle([1, 2, 3])) + assert np.all( + rng.sample([1, 2, 3], 2) == rs42.choice([1, 2, 3], (2,), replace=False) + ) + assert np.all( + [rng.randint(3, 5) for _ in range(100)] + == [rs42.randint(3, 6) for _ in range(100)] + ) + assert rng.random() == rs42.random_sample() + + +def test_PythonRandomInterface_Generator(): + np = pytest.importorskip("numpy") + + seed = 42 + rng = np.random.default_rng(seed) + pri = PythonRandomInterface(np.random.default_rng(seed)) + + # make sure these functions are same as expected outcome + assert pri.randrange(3, 5) == rng.integers(3, 5) + assert pri.choice([1, 2, 3]) == rng.choice([1, 2, 3]) + assert pri.gauss(0, 1) == rng.normal(0, 1) + assert pri.expovariate(1.5) == rng.exponential(1 / 1.5) + assert np.all(pri.shuffle([1, 2, 3]) == rng.shuffle([1, 2, 3])) + assert np.all( + pri.sample([1, 2, 3], 2) == rng.choice([1, 2, 3], (2,), replace=False) + ) + assert np.all( + [pri.randint(3, 5) for _ in range(100)] + == [rng.integers(3, 6) for _ in range(100)] + ) + assert pri.random() == rng.random() + + +@pytest.mark.parametrize( + ("iterable_type", "expected"), ((list, 1), (tuple, 1), (str, "["), (set, 1)) +) +def test_arbitrary_element(iterable_type, expected): + iterable = iterable_type([1, 2, 3]) + assert arbitrary_element(iterable) == expected + + +@pytest.mark.parametrize( + "iterator", + ((i for i in range(3)), iter([1, 2, 3])), # generator +) +def test_arbitrary_element_raises(iterator): + """Value error is raised when input is an iterator.""" + with pytest.raises(ValueError, match="from an iterator"): + arbitrary_element(iterator) diff --git a/shared/package-files/ef/efa53d20bc5cbbbe884a16e9869114524c1d226057b0f5400b82300d4551cd6c/refine.cpython-311.pyc b/shared/package-files/ef/efa53d20bc5cbbbe884a16e9869114524c1d226057b0f5400b82300d4551cd6c/refine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e7d098faf5833645f8debd799c345e33c0e80e5 Binary files /dev/null and b/shared/package-files/ef/efa53d20bc5cbbbe884a16e9869114524c1d226057b0f5400b82300d4551cd6c/refine.cpython-311.pyc differ diff --git a/shared/package-files/ef/efa608e9041f3fb32814c2070f8ee408bc8403f593f21de487905ea72ba7500c/trace_dependencies.cpython-311.pyc b/shared/package-files/ef/efa608e9041f3fb32814c2070f8ee408bc8403f593f21de487905ea72ba7500c/trace_dependencies.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0957b798b832e1709cfb17620336ecdf996226ab Binary files /dev/null and b/shared/package-files/ef/efa608e9041f3fb32814c2070f8ee408bc8403f593f21de487905ea72ba7500c/trace_dependencies.cpython-311.pyc differ diff --git a/shared/package-files/ef/efa8227fc660f3789d81419c0d941f14516b441295bd0e5e384b0a73dd2a58b8/mkldnn_max_pool2d_backward_ops.h b/shared/package-files/ef/efa8227fc660f3789d81419c0d941f14516b441295bd0e5e384b0a73dd2a58b8/mkldnn_max_pool2d_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b795c8a035b44d704ccc60efa52c4292c0868e4c --- /dev/null +++ b/shared/package-files/ef/efa8227fc660f3789d81419c0d941f14516b441295bd0e5e384b0a73dd2a58b8/mkldnn_max_pool2d_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mkldnn_max_pool2d_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_max_pool2d_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "mkldnn_max_pool2d_backward(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +}; + +struct TORCH_API mkldnn_max_pool2d_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mkldnn_max_pool2d_backward"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "mkldnn_max_pool2d_backward.out(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/efa975f322318db258e12283934230514512e24bfe81143e6e5968e2d267ac5b/signal.cpython-311.pyc b/shared/package-files/ef/efa975f322318db258e12283934230514512e24bfe81143e6e5968e2d267ac5b/signal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5f5559d735f1013a9d464bdd2f8a4a42af7bf5d Binary files /dev/null and b/shared/package-files/ef/efa975f322318db258e12283934230514512e24bfe81143e6e5968e2d267ac5b/signal.cpython-311.pyc differ diff --git a/shared/package-files/ef/efad94f6a73f2dda074035887b6a9f8421c7a9e8b083e74f9441e9c066aff0f0/baddbmm_ops.h b/shared/package-files/ef/efad94f6a73f2dda074035887b6a9f8421c7a9e8b083e74f9441e9c066aff0f0/baddbmm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cec2a6f2a9747fa042e702b9b67d5e3bdfb37f8b --- /dev/null +++ b/shared/package-files/ef/efad94f6a73f2dda074035887b6a9f8421c7a9e8b083e74f9441e9c066aff0f0/baddbmm_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API baddbmm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::baddbmm"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); +}; + +struct TORCH_API baddbmm_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::baddbmm_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); +}; + +struct TORCH_API baddbmm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::baddbmm"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "baddbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/efadcdcae5ccad45836dba314b571040bc366635c5b4fbdc4e7c87acdb34acfb/rationaltools.cpython-311.pyc b/shared/package-files/ef/efadcdcae5ccad45836dba314b571040bc366635c5b4fbdc4e7c87acdb34acfb/rationaltools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48477a11afa0fa7a4abd4e4ea74aa08dac20e829 Binary files /dev/null and b/shared/package-files/ef/efadcdcae5ccad45836dba314b571040bc366635c5b4fbdc4e7c87acdb34acfb/rationaltools.cpython-311.pyc differ diff --git a/shared/package-files/ef/efb04a064da63daedb0382f040ba82df61bdcb4133981b599de39772f2142802/qconfig.py b/shared/package-files/ef/efb04a064da63daedb0382f040ba82df61bdcb4133981b599de39772f2142802/qconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..246d74b601c8386f92fe656074ab8e5aca917421 --- /dev/null +++ b/shared/package-files/ef/efb04a064da63daedb0382f040ba82df61bdcb4133981b599de39772f2142802/qconfig.py @@ -0,0 +1,700 @@ +# mypy: allow-untyped-defs +import copy +import warnings +from collections import namedtuple +from typing import Any, Optional, Union +from typing_extensions import deprecated + +import torch +import torch.nn as nn +from torch.ao.quantization.fake_quantize import ( + default_dynamic_fake_quant, + default_embedding_fake_quant, + default_embedding_fake_quant_4bit, + default_fake_quant, + default_fused_act_fake_quant, + default_fused_per_channel_wt_fake_quant, + default_fused_wt_fake_quant, + default_per_channel_weight_fake_quant, + default_weight_fake_quant, + FakeQuantize, + FakeQuantizeBase, + fused_per_channel_wt_fake_quant_range_neg_127_to_127, + fused_wt_fake_quant_range_neg_127_to_127, + FusedMovingAvgObsFakeQuantize, +) + +from .observer import ( + _PartialWrapper, + default_debug_observer, + default_dynamic_quant_observer, + default_float_qparams_observer, + default_float_qparams_observer_4bit, + default_observer, + default_per_channel_weight_observer, + default_placeholder_observer, + default_reuse_input_observer, + default_weight_observer, + HistogramObserver, + MinMaxObserver, + MovingAverageMinMaxObserver, + NoopObserver, + ObserverBase, + per_channel_weight_observer_range_neg_127_to_127, + PlaceholderObserver, + ReuseInputObserver, + weight_observer_range_neg_127_to_127, +) + + +__all__ = [ + "QConfig", + # TODO: deprecated, remove + "QConfigDynamic", + "default_qconfig", + "default_debug_qconfig", + "default_per_channel_qconfig", + "default_dynamic_qconfig", + "float16_dynamic_qconfig", + "float16_static_qconfig", + "per_channel_dynamic_qconfig", + "float_qparams_weight_only_qconfig", + "float_qparams_weight_only_qconfig_4bit", + "default_quint8_weight_qconfig", + "default_qat_qconfig", + "default_dynamic_qat_qconfig", + "default_weight_only_qconfig", + "default_activation_only_qconfig", + "default_qat_qconfig_v2", + "default_reuse_input_qconfig", + "default_symmetric_qnnpack_qconfig", + "default_per_channel_symmetric_qnnpack_qconfig", + "default_symmetric_qnnpack_qat_qconfig", + "default_per_channel_symmetric_qnnpack_qat_qconfig", + "default_embedding_qat_qconfig", + "default_embedding_qat_qconfig_4bit", + "get_default_qconfig", + "get_default_qat_qconfig", + "get_default_qconfig_dict", + "get_default_qat_qconfig_dict", + "QConfigAny", + "qconfig_equals", +] + + +class QConfig(namedtuple("QConfig", ["activation", "weight"])): + """ + Describes how to quantize a layer or a part of the network by providing + settings (observer classes) for activations and weights respectively. + + + Note that QConfig needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization preparation function will instantiate observers multiple times for each of the layers. + + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfig( + activation=MinMaxObserver.with_args(dtype=torch.qint8), + weight=default_observer.with_args(dtype=torch.qint8)) + + """ + + __slots__ = () + + def __new__(cls, activation, weight): + # catch common mistakes + if isinstance(activation, nn.Module) or isinstance(weight, nn.Module): + raise ValueError( + "QConfig received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed" + ) + return super().__new__(cls, activation, weight) + + +@deprecated( + "`QConfigDynamic` is going to be deprecated in PyTorch 1.12, please use `QConfig` instead", + category=FutureWarning, +) +class QConfigDynamic(namedtuple("QConfigDynamic", ["activation", "weight"])): + """ + Describes how to dynamically quantize a layer or a part of the network by providing + settings (observer classes) for weights. + + It's like QConfig, but for dynamic quantization. + + Note that QConfigDynamic needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization function will instantiate observers multiple times for each of the layers. + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfigDynamic(weight=default_observer.with_args(dtype=torch.qint8)) + """ + + __slots__ = () + + def __new__(cls, activation=torch.nn.Identity, weight=torch.nn.Identity): + # catch common mistakes + if isinstance(weight, nn.Module): + raise ValueError( + "QConfigDynamic received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed" + ) + return super().__new__(cls, activation, weight) + + +default_qconfig = QConfig(activation=default_observer, weight=default_weight_observer) +""" +Default qconfig configuration. +""" + +default_debug_qconfig = QConfig( + weight=default_weight_observer, activation=default_debug_observer +) +""" +Default qconfig configuration for debugging. +""" + +default_per_channel_qconfig = QConfig( + activation=default_observer, weight=default_per_channel_weight_observer +) +""" +Default qconfig configuration for per channel weight quantization. +""" + +default_dynamic_qconfig = QConfig( + activation=default_dynamic_quant_observer, weight=default_weight_observer +) +""" +Default dynamic qconfig. +""" + +float16_dynamic_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.float16, is_dynamic=True), + weight=PlaceholderObserver.with_args(dtype=torch.float16), +) +""" +Dynamic qconfig with weights quantized to `torch.float16`. +""" + +float16_static_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.float16), + weight=PlaceholderObserver.with_args(dtype=torch.float16), +) +""" +Dynamic qconfig with both activations and weights quantized to `torch.float16`. +""" + +per_channel_dynamic_qconfig = QConfig( + activation=default_dynamic_quant_observer, + weight=default_per_channel_weight_observer, +) +""" +Dynamic qconfig with weights quantized per channel. +""" + +float_qparams_weight_only_qconfig = QConfig( + activation=default_placeholder_observer, weight=default_float_qparams_observer +) +""" +Dynamic qconfig with weights quantized with a floating point zero_point. +""" + +float_qparams_weight_only_qconfig_4bit = QConfig( + activation=default_placeholder_observer, weight=default_float_qparams_observer_4bit +) + +default_qat_qconfig = QConfig( + activation=default_fake_quant, weight=default_weight_fake_quant +) +""" +Default qconfig for QAT. +""" + +default_dynamic_qat_qconfig = QConfig( + activation=default_dynamic_fake_quant, weight=default_weight_fake_quant +) +""" +Default qconfig for dynamic QAT. +""" + +default_weight_only_qconfig = QConfig( + activation=torch.nn.Identity, weight=default_weight_fake_quant +) +""" +Default qconfig for quantizing weights only. +""" + +default_activation_only_qconfig = QConfig( + activation=default_fake_quant, weight=torch.nn.Identity +) +""" +Default qconfig for quantizing activations only. +""" + +# QAT config that uses a fused observer + fake quant modules for optimized training performance. +# to modify the activation/weight observers, the default entries in fake_quantize.py can be modified. +default_qat_qconfig_v2 = QConfig( + activation=default_fused_act_fake_quant, weight=default_fused_wt_fake_quant +) +""" +Fused version of `default_qat_config`, has performance benefits. +""" + +default_reuse_input_qconfig = QConfig( + activation=default_reuse_input_observer, weight=NoopObserver +) +""" +Default qconfig for operators that reuse the observers from input Tensor, e.g. reshape +""" + + +def get_default_qconfig(backend="x86", version=0): + """ + Returns the default PTQ qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + if version == 0: + if backend == "fbgemm": + qconfig = QConfig( + activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer, + ) + elif backend == "qnnpack": + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig( + activation=HistogramObserver.with_args(reduce_range=False), + weight=default_weight_observer, + ) + elif backend == "onednn": + if not torch.cpu._is_vnni_supported(): + warnings.warn( + "Default qconfig of oneDNN backend with reduce_range of false may have accuracy issues " + "on CPU without Vector Neural Network Instruction support." + ) + qconfig = QConfig( + activation=HistogramObserver.with_args(reduce_range=False), + weight=default_per_channel_weight_observer, + ) + elif backend == "x86": + qconfig = QConfig( + activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer, + ) + else: + # won't reach + qconfig = default_qconfig + else: + raise AssertionError( + "Version number: " + + str(version) + + " in get_default_qconfig is not supported. Version number must be 0" + ) + + return qconfig + + +""" +Default, symmetric PTQ qconfig for the specified backend. And a per_channel +variant of the same. + +Symmetric here applies to signed weights with zero point = 0, and additional +value restrictions. The activations are also signed 8-bit integers with this +qconfig. + + * Once this change is merged [as of 3/17/22], with backend or qengine = + 'qnnpack', some quantized operators with this symmetric qconfig may use + operators from xnnpack library. + + ** Support to use xnnpack ops with `qnnpack` backed for asymmetric + qconfig (returned by get_default_qconfig()) is not available yet. + + * This qconfig uses signed activations and weights. Weights have added + restrictions such as zero point is forced to be 0, making the weights + symmetric, hence the name. And the 8-bit quantized values are + restricting to to [-127, +127], excluding -128. + + * xnnpack has a requantization scale value restriction, 0x1p-32 <= + requantization_scale < 256.0 where, `requantization_scale = (input_scale + * kernel_scale) / (output_scale)`. Using this eps (w/ assumed max value + of 256) is to prevent requantization_scale to go below xnnpack lower + threshold. +""" +default_symmetric_qnnpack_qconfig = QConfig( + activation=HistogramObserver.with_args( + dtype=torch.qint8, reduce_range=False, eps=2**-12 + ), + weight=weight_observer_range_neg_127_to_127, +) + +default_per_channel_symmetric_qnnpack_qconfig = QConfig( + activation=HistogramObserver.with_args( + dtype=torch.qint8, reduce_range=False, eps=2**-12 + ), + weight=per_channel_weight_observer_range_neg_127_to_127, +) + +default_embedding_qat_qconfig = QConfig( + activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant, +) + +default_embedding_qat_qconfig_4bit = QConfig( + activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant_4bit, +) + +default_quint8_weight_qconfig = QConfig( + activation=HistogramObserver, weight=MinMaxObserver +) + + +def get_default_qat_qconfig(backend="x86", version=1): + """ + Returns the default QAT qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + * `version`: version, for backwards compatibility. Can be `None` or `1`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + # Histogram observer is too slow for quantization aware training + if version == 0: + if backend == "fbgemm": + qconfig = QConfig( + activation=FakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True, + ), + weight=default_per_channel_weight_fake_quant, + ) + elif backend == "qnnpack": + qconfig = QConfig( + activation=FakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False, + ), + weight=default_weight_fake_quant, + ) + elif backend == "onednn": + qconfig = QConfig( + activation=FakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255 + ), + weight=default_per_channel_weight_fake_quant, + ) + elif backend == "x86": + qconfig = QConfig( + activation=FakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True, + ), + weight=default_per_channel_weight_fake_quant, + ) + else: + qconfig = default_qat_qconfig + # Use the fused observe + fake_quant modules for doing QAT. + elif version == 1: + if backend == "fbgemm": + qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True, + ), + weight=default_fused_per_channel_wt_fake_quant, + ) + elif backend == "qnnpack": + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False, + ), + weight=default_fused_wt_fake_quant, + ) + elif backend == "onednn": + qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255 + ), + weight=default_fused_per_channel_wt_fake_quant, + ) + elif backend == "x86": + qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True, + ), + weight=default_fused_per_channel_wt_fake_quant, + ) + else: + qconfig = default_qat_qconfig_v2 + else: + raise AssertionError( + "Version number: " + + str(version) + + "in get_default_qat_qconfig is not supported. Version number must be 0 or 1" + ) + + return qconfig + + +""" +Default symmetric QAT qconfig for qnnpack. And its per channel weight variant. +""" +default_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2**-12, + ), + weight=fused_wt_fake_quant_range_neg_127_to_127, +) + +default_per_channel_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2**-12, + ), + weight=fused_per_channel_wt_fake_quant_range_neg_127_to_127, +) + +_default_fp32_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.float32), + weight=PlaceholderObserver.with_args(dtype=torch.float32), +) + +_default_quint8_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.quint8), + # operators using this qconfig doesn't have weights + weight=None, +) + + +@deprecated( + "`torch.ao.quantization.get_default_qconfig_dict` is deprecated and will be removed in " + "a future version. Please use `torch.ao.quantization.get_default_qconfig_mapping` instead.", + category=FutureWarning, +) +def get_default_qconfig_dict(backend="x86", version=0): + return torch.ao.quantization.get_default_qconfig_mapping(backend, version).to_dict() + + +@deprecated( + "`torch.ao.quantization.get_default_qat_qconfig_dict` is deprecated and will be removed in " + "a future version. Please use `torch.ao.quantization.get_default_qat_qconfig_mapping` instead.", + category=FutureWarning, +) +def get_default_qat_qconfig_dict(backend="x86", version=1): + return torch.ao.quantization.get_default_qat_qconfig_mapping( + backend, version + ).to_dict() + + +def _assert_valid_qconfig(qconfig: Optional[QConfig], mod: torch.nn.Module) -> None: + """ + Verifies that this `qconfig` is valid. + """ + if qconfig is None: + return + is_conv_transpose_mod = isinstance( + mod, + (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d), + ) + if is_conv_transpose_mod: + if qconfig.weight is None: + # for now, we assume that any qconfig for ConvTranspose without a weight is valid + return + example_observer = qconfig.weight() + is_per_channel = isinstance( + example_observer, + ( + torch.ao.quantization.PerChannelMinMaxObserver, + torch.ao.quantization.MovingAveragePerChannelMinMaxObserver, + ), + ) + assert ( + not is_per_channel + ), "Per channel weight observer is not supported yet for ConvTranspose{n}d." + + +QConfigAny = Optional[QConfig] +QConfigAny.__module__ = "torch.ao.quantization.qconfig" + + +def _add_module_to_qconfig_obs_ctr( + qconfig: QConfigAny, module: Optional[nn.Module] +) -> Any: + r"""This is a helper function for use in quantization prepare that updates a qconfig so that + the constructors stored in the qconfig will create observers on the same device that + 'module' is on. This is intended to be used when the qconfigs are propagated to each + module in order to avoid potential device alignment issues. + + Args: + qconfig: QConfig with obs constructors stored in activation and weight + module: module which the qconfig is related to + + Return: + qconfig: configured so that obs constructors set to construct on the same device as module + """ + + if module is None or qconfig is None or qconfig._fields != ("activation", "weight"): + return qconfig + + def get_factory_kwargs_based_on_module_device(): + assert isinstance(module, torch.nn.Module) + devices = {p.device for p in module.parameters()} | { + p.device for p in module.buffers() + } + device = next(iter(devices)) if len(devices) > 0 else None + return None if device is None else {"device": device} + + def configure_constructor_to_put_obs_on_module_device(original_constructor): + try: + # check if constructor can accept factory_kwargs + check = original_constructor.with_args(factory_kwargs=None) + check() + return original_constructor.with_callable_args( + factory_kwargs=get_factory_kwargs_based_on_module_device + ) + except AttributeError: # qconfig doesn't have activation or weight + return original_constructor + except TypeError: # the class doesn't accept factory_kwargs argument + return original_constructor + + activation = configure_constructor_to_put_obs_on_module_device(qconfig.activation) + weight = configure_constructor_to_put_obs_on_module_device(qconfig.weight) + + return QConfig(activation, weight) + + +_ObserverOrFakeQuantizeConstructor = Union[ + _PartialWrapper, type[ObserverBase], type[FakeQuantizeBase] +] + + +def _obs_or_fq_ctr_equals( + obs_or_fq1: _ObserverOrFakeQuantizeConstructor, + obs_or_fq2: _ObserverOrFakeQuantizeConstructor, +): + if isinstance(obs_or_fq1, _PartialWrapper) and isinstance( + obs_or_fq2, _PartialWrapper + ): + return _partial_wrapper_equals(obs_or_fq1, obs_or_fq2) + return obs_or_fq1 == obs_or_fq2 + + +def _partial_wrapper_equals(obs_or_fq1: _PartialWrapper, obs_or_fq2: _PartialWrapper): + """ + Return whether the two partial wrappers are equal, + """ + # functools.partial has no __eq__ operator defined so '==' defaults to 'is' + obs_or_fq1_keywords = copy.copy(obs_or_fq1.p.keywords) + obs_or_fq2_keywords = copy.copy(obs_or_fq2.p.keywords) + keywords_equal = True + # compare observer constructor with _obs_or_fq_ctr_equals since direct compare would fail + if "observer" in obs_or_fq1_keywords and "observer" in obs_or_fq2_keywords: + keywords_equal = keywords_equal and _obs_or_fq_ctr_equals( + obs_or_fq1_keywords["observer"], obs_or_fq2_keywords["observer"] + ) + obs_or_fq1_keywords.pop("observer") + obs_or_fq2_keywords.pop("observer") + keywords_equal = keywords_equal and obs_or_fq1_keywords == obs_or_fq2_keywords + return ( + obs_or_fq1.p.func == obs_or_fq2.p.func + and obs_or_fq1.p.args == obs_or_fq2.p.args + and keywords_equal + ) + + +def qconfig_equals(q1: QConfigAny, q2: QConfigAny): + """ + Returns `True` if `q1` equals `q2`, and `False` otherwise. + """ + if q1 is None or q2 is None: + return q1 == q2 + else: + assert q1 is not None and q2 is not None + try: + # Qconfig weight and activation can be either a partial wrapper, + # or an observer class. Special handling is required (above) for + # comparing partial wrappers. + activation_same = _obs_or_fq_ctr_equals(q1.activation, q2.activation) + weight_same = _obs_or_fq_ctr_equals(q1.weight, q2.weight) + return activation_same and weight_same + except AttributeError: + return q1 == q2 + + +def _activation_is_memoryless(qconfig: QConfig): + """ + Return whether the observer for activations defined in the given QConfig is memoryless. + This means a MovingAverage observer with averaging constant equal to 1. + """ + + def _is_memoryless(observer): + return ( + hasattr(observer, "averaging_constant") and observer.averaging_constant == 1 + ) + + act = qconfig.activation() + if isinstance(act, FakeQuantizeBase) and hasattr(act, "activation_post_process"): + return _is_memoryless(act.activation_post_process) + else: + return _is_memoryless(act) + + +def _is_reuse_input_qconfig(qconfig: Optional[QConfig]): + return ( + qconfig is not None + and isinstance(qconfig.activation(), ReuseInputObserver) + and isinstance(qconfig.weight(), NoopObserver) + ) diff --git a/shared/package-files/ef/efb1c7f93191883c73a55acb4f61fcd95703e5f2afc8aec7763c96a75fc9adda/fft_rfft.h b/shared/package-files/ef/efb1c7f93191883c73a55acb4f61fcd95703e5f2afc8aec7763c96a75fc9adda/fft_rfft.h new file mode 100644 index 0000000000000000000000000000000000000000..6220b7ec1e2d792795a69fd30c73271f595e9b64 --- /dev/null +++ b/shared/package-files/ef/efb1c7f93191883c73a55acb4f61fcd95703e5f2afc8aec7763c96a75fc9adda/fft_rfft.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::fft_rfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor +inline at::Tensor fft_rfft(const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm); +} +namespace symint { + template >> + at::Tensor fft_rfft(const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm); + } +} + +// aten::fft_rfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor +inline at::Tensor fft_rfft_symint(const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft::call(self, n, dim, norm); +} +namespace symint { + template >> + at::Tensor fft_rfft(const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft::call(self, n, dim, norm); + } +} + +// aten::fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft_out(at::Tensor & out, const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft_out::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_rfft_out(at::Tensor & out, const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft_out::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft_outf(const at::Tensor & self, ::std::optional n, int64_t dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft_out::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_rfft_outf(const at::Tensor & self, ::std::optional n, int64_t dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft_out::call(self, n.has_value() ? ::std::make_optional(c10::SymInt(*n)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft_symint_out(at::Tensor & out, const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft_out::call(self, n, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_rfft_out(at::Tensor & out, const at::Tensor & self, ::std::optional n=::std::nullopt, int64_t dim=-1, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_rfft_out::call(self, n, dim, norm, out); + } +} + +// aten::fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_rfft_symint_outf(const at::Tensor & self, ::std::optional n, int64_t dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft_out::call(self, n, dim, norm, out); +} +namespace symint { + template >> + at::Tensor & fft_rfft_outf(const at::Tensor & self, ::std::optional n, int64_t dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_rfft_out::call(self, n, dim, norm, out); + } +} + +} diff --git a/shared/package-files/ef/efb2c22d7a0d294d111286befc7f8c7a534db5537f5a284fb2fb72a440c389eb/ck_gemm.h b/shared/package-files/ef/efb2c22d7a0d294d111286befc7f8c7a534db5537f5a284fb2fb72a440c389eb/ck_gemm.h new file mode 100644 index 0000000000000000000000000000000000000000..176cbabd5e01c40189b2d6115136d27a7e5865b6 --- /dev/null +++ b/shared/package-files/ef/efb2c22d7a0d294d111286befc7f8c7a534db5537f5a284fb2fb72a440c389eb/ck_gemm.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +namespace at::native { + + +template +inline void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas_gemm_internal_ck: not implemented"); +} + +template <> +void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(double)); +template <> +void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(float)); +template <> +void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(at::Half)); +template <> +void gemm_internal_ck(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)); + + + +} // namespace at::native diff --git a/shared/package-files/ef/efb51f017c3405afdef6cb90125f16df6386535a903e259b90d9d27c93ddefd0/__init__.cpython-311.pyc b/shared/package-files/ef/efb51f017c3405afdef6cb90125f16df6386535a903e259b90d9d27c93ddefd0/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c981277cd8fdfcc9fc9d0960d04e07c22c75423 Binary files /dev/null and b/shared/package-files/ef/efb51f017c3405afdef6cb90125f16df6386535a903e259b90d9d27c93ddefd0/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/efb7d9bddcae17fab2108cb714c240c82d1368087b6d2b91e02ec224ddebce12/multicall.py b/shared/package-files/ef/efb7d9bddcae17fab2108cb714c240c82d1368087b6d2b91e02ec224ddebce12/multicall.py new file mode 100644 index 0000000000000000000000000000000000000000..41f81813113062167b813f1400aff15ad140afc3 --- /dev/null +++ b/shared/package-files/ef/efb7d9bddcae17fab2108cb714c240c82d1368087b6d2b91e02ec224ddebce12/multicall.py @@ -0,0 +1,451 @@ +""" +MultiCall - a class which inherits its methods from a Tkinter widget (Text, for +example), but enables multiple calls of functions per virtual event - all +matching events will be called, not only the most specific one. This is done +by wrapping the event functions - event_add, event_delete and event_info. +MultiCall recognizes only a subset of legal event sequences. Sequences which +are not recognized are treated by the original Tk handling mechanism. A +more-specific event will be called before a less-specific event. + +The recognized sequences are complete one-event sequences (no emacs-style +Ctrl-X Ctrl-C, no shortcuts like <3>), for all types of events. +Key/Button Press/Release events can have modifiers. +The recognized modifiers are Shift, Control, Option and Command for Mac, and +Control, Alt, Shift, Meta/M for other platforms. + +For all events which were handled by MultiCall, a new member is added to the +event instance passed to the binded functions - mc_type. This is one of the +event type constants defined in this module (such as MC_KEYPRESS). +For Key/Button events (which are handled by MultiCall and may receive +modifiers), another member is added - mc_state. This member gives the state +of the recognized modifiers, as a combination of the modifier constants +also defined in this module (for example, MC_SHIFT). +Using these members is absolutely portable. + +The order by which events are called is defined by these rules: +1. A more-specific event will be called before a less-specific event. +2. A recently-binded event will be called before a previously-binded event, + unless this conflicts with the first rule. +Each function will be called at most once for each event. +""" +import re +import sys + +import tkinter + +# the event type constants, which define the meaning of mc_type +MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3; +MC_ACTIVATE=4; MC_CIRCULATE=5; MC_COLORMAP=6; MC_CONFIGURE=7; +MC_DEACTIVATE=8; MC_DESTROY=9; MC_ENTER=10; MC_EXPOSE=11; MC_FOCUSIN=12; +MC_FOCUSOUT=13; MC_GRAVITY=14; MC_LEAVE=15; MC_MAP=16; MC_MOTION=17; +MC_MOUSEWHEEL=18; MC_PROPERTY=19; MC_REPARENT=20; MC_UNMAP=21; MC_VISIBILITY=22; +# the modifier state constants, which define the meaning of mc_state +MC_SHIFT = 1<<0; MC_CONTROL = 1<<2; MC_ALT = 1<<3; MC_META = 1<<5 +MC_OPTION = 1<<6; MC_COMMAND = 1<<7 + +# define the list of modifiers, to be used in complex event types. +if sys.platform == "darwin": + _modifiers = (("Shift",), ("Control",), ("Option",), ("Command",)) + _modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND) +else: + _modifiers = (("Control",), ("Alt",), ("Shift",), ("Meta", "M")) + _modifier_masks = (MC_CONTROL, MC_ALT, MC_SHIFT, MC_META) + +# a dictionary to map a modifier name into its number +_modifier_names = {name: number + for number in range(len(_modifiers)) + for name in _modifiers[number]} + +# In 3.4, if no shell window is ever open, the underlying Tk widget is +# destroyed before .__del__ methods here are called. The following +# is used to selectively ignore shutdown exceptions to avoid +# 'Exception ignored' messages. See http://bugs.python.org/issue20167 +APPLICATION_GONE = "application has been destroyed" + +# A binder is a class which binds functions to one type of event. It has two +# methods: bind and unbind, which get a function and a parsed sequence, as +# returned by _parse_sequence(). There are two types of binders: +# _SimpleBinder handles event types with no modifiers and no detail. +# No Python functions are called when no events are binded. +# _ComplexBinder handles event types with modifiers and a detail. +# A Python function is called each time an event is generated. + +class _SimpleBinder: + def __init__(self, type, widget, widgetinst): + self.type = type + self.sequence = '<'+_types[type][0]+'>' + self.widget = widget + self.widgetinst = widgetinst + self.bindedfuncs = [] + self.handlerid = None + + def bind(self, triplet, func): + if not self.handlerid: + def handler(event, l = self.bindedfuncs, mc_type = self.type): + event.mc_type = mc_type + wascalled = {} + for i in range(len(l)-1, -1, -1): + func = l[i] + if func not in wascalled: + wascalled[func] = True + r = func(event) + if r: + return r + self.handlerid = self.widget.bind(self.widgetinst, + self.sequence, handler) + self.bindedfuncs.append(func) + + def unbind(self, triplet, func): + self.bindedfuncs.remove(func) + if not self.bindedfuncs: + self.widget.unbind(self.widgetinst, self.sequence, self.handlerid) + self.handlerid = None + + def __del__(self): + if self.handlerid: + try: + self.widget.unbind(self.widgetinst, self.sequence, + self.handlerid) + except tkinter.TclError as e: + if not APPLICATION_GONE in e.args[0]: + raise + +# An int in range(1 << len(_modifiers)) represents a combination of modifiers +# (if the least significant bit is on, _modifiers[0] is on, and so on). +# _state_subsets gives for each combination of modifiers, or *state*, +# a list of the states which are a subset of it. This list is ordered by the +# number of modifiers is the state - the most specific state comes first. +_states = range(1 << len(_modifiers)) +_state_names = [''.join(m[0]+'-' + for i, m in enumerate(_modifiers) + if (1 << i) & s) + for s in _states] + +def expand_substates(states): + '''For each item of states return a list containing all combinations of + that item with individual bits reset, sorted by the number of set bits. + ''' + def nbits(n): + "number of bits set in n base 2" + nb = 0 + while n: + n, rem = divmod(n, 2) + nb += rem + return nb + statelist = [] + for state in states: + substates = list({state & x for x in states}) + substates.sort(key=nbits, reverse=True) + statelist.append(substates) + return statelist + +_state_subsets = expand_substates(_states) + +# _state_codes gives for each state, the portable code to be passed as mc_state +_state_codes = [] +for s in _states: + r = 0 + for i in range(len(_modifiers)): + if (1 << i) & s: + r |= _modifier_masks[i] + _state_codes.append(r) + +class _ComplexBinder: + # This class binds many functions, and only unbinds them when it is deleted. + # self.handlerids is the list of seqs and ids of binded handler functions. + # The binded functions sit in a dictionary of lists of lists, which maps + # a detail (or None) and a state into a list of functions. + # When a new detail is discovered, handlers for all the possible states + # are binded. + + def __create_handler(self, lists, mc_type, mc_state): + def handler(event, lists = lists, + mc_type = mc_type, mc_state = mc_state, + ishandlerrunning = self.ishandlerrunning, + doafterhandler = self.doafterhandler): + ishandlerrunning[:] = [True] + event.mc_type = mc_type + event.mc_state = mc_state + wascalled = {} + r = None + for l in lists: + for i in range(len(l)-1, -1, -1): + func = l[i] + if func not in wascalled: + wascalled[func] = True + r = l[i](event) + if r: + break + if r: + break + ishandlerrunning[:] = [] + # Call all functions in doafterhandler and remove them from list + for f in doafterhandler: + f() + doafterhandler[:] = [] + if r: + return r + return handler + + def __init__(self, type, widget, widgetinst): + self.type = type + self.typename = _types[type][0] + self.widget = widget + self.widgetinst = widgetinst + self.bindedfuncs = {None: [[] for s in _states]} + self.handlerids = [] + # we don't want to change the lists of functions while a handler is + # running - it will mess up the loop and anyway, we usually want the + # change to happen from the next event. So we have a list of functions + # for the handler to run after it finishes calling the binded functions. + # It calls them only once. + # ishandlerrunning is a list. An empty one means no, otherwise - yes. + # this is done so that it would be mutable. + self.ishandlerrunning = [] + self.doafterhandler = [] + for s in _states: + lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]] + handler = self.__create_handler(lists, type, _state_codes[s]) + seq = '<'+_state_names[s]+self.typename+'>' + self.handlerids.append((seq, self.widget.bind(self.widgetinst, + seq, handler))) + + def bind(self, triplet, func): + if triplet[2] not in self.bindedfuncs: + self.bindedfuncs[triplet[2]] = [[] for s in _states] + for s in _states: + lists = [ self.bindedfuncs[detail][i] + for detail in (triplet[2], None) + for i in _state_subsets[s] ] + handler = self.__create_handler(lists, self.type, + _state_codes[s]) + seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2]) + self.handlerids.append((seq, self.widget.bind(self.widgetinst, + seq, handler))) + doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func) + if not self.ishandlerrunning: + doit() + else: + self.doafterhandler.append(doit) + + def unbind(self, triplet, func): + doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func) + if not self.ishandlerrunning: + doit() + else: + self.doafterhandler.append(doit) + + def __del__(self): + for seq, id in self.handlerids: + try: + self.widget.unbind(self.widgetinst, seq, id) + except tkinter.TclError as e: + if not APPLICATION_GONE in e.args[0]: + raise + +# define the list of event types to be handled by MultiEvent. the order is +# compatible with the definition of event type constants. +_types = ( + ("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"), + ("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",), + ("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",), + ("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",), + ("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",), + ("Visibility",), +) + +# which binder should be used for every event type? +_binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4) + +# A dictionary to map a type name into its number +_type_names = {name: number + for number in range(len(_types)) + for name in _types[number]} + +_keysym_re = re.compile(r"^\w+$") +_button_re = re.compile(r"^[1-5]$") +def _parse_sequence(sequence): + """Get a string which should describe an event sequence. If it is + successfully parsed as one, return a tuple containing the state (as an int), + the event type (as an index of _types), and the detail - None if none, or a + string if there is one. If the parsing is unsuccessful, return None. + """ + if not sequence or sequence[0] != '<' or sequence[-1] != '>': + return None + words = sequence[1:-1].split('-') + modifiers = 0 + while words and words[0] in _modifier_names: + modifiers |= 1 << _modifier_names[words[0]] + del words[0] + if words and words[0] in _type_names: + type = _type_names[words[0]] + del words[0] + else: + return None + if _binder_classes[type] is _SimpleBinder: + if modifiers or words: + return None + else: + detail = None + else: + # _ComplexBinder + if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]: + type_re = _keysym_re + else: + type_re = _button_re + + if not words: + detail = None + elif len(words) == 1 and type_re.match(words[0]): + detail = words[0] + else: + return None + + return modifiers, type, detail + +def _triplet_to_sequence(triplet): + if triplet[2]: + return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \ + triplet[2]+'>' + else: + return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>' + +_multicall_dict = {} +def MultiCallCreator(widget): + """Return a MultiCall class which inherits its methods from the + given widget class (for example, Tkinter.Text). This is used + instead of a templating mechanism. + """ + if widget in _multicall_dict: + return _multicall_dict[widget] + + class MultiCall (widget): + assert issubclass(widget, tkinter.Misc) + + def __init__(self, *args, **kwargs): + widget.__init__(self, *args, **kwargs) + # a dictionary which maps a virtual event to a tuple with: + # 0. the function binded + # 1. a list of triplets - the sequences it is binded to + self.__eventinfo = {} + self.__binders = [_binder_classes[i](i, widget, self) + for i in range(len(_types))] + + def bind(self, sequence=None, func=None, add=None): + #print("bind(%s, %s, %s)" % (sequence, func, add), + # file=sys.__stderr__) + if type(sequence) is str and len(sequence) > 2 and \ + sequence[:2] == "<<" and sequence[-2:] == ">>": + if sequence in self.__eventinfo: + ei = self.__eventinfo[sequence] + if ei[0] is not None: + for triplet in ei[1]: + self.__binders[triplet[1]].unbind(triplet, ei[0]) + ei[0] = func + if ei[0] is not None: + for triplet in ei[1]: + self.__binders[triplet[1]].bind(triplet, func) + else: + self.__eventinfo[sequence] = [func, []] + return widget.bind(self, sequence, func, add) + + def unbind(self, sequence, funcid=None): + if type(sequence) is str and len(sequence) > 2 and \ + sequence[:2] == "<<" and sequence[-2:] == ">>" and \ + sequence in self.__eventinfo: + func, triplets = self.__eventinfo[sequence] + if func is not None: + for triplet in triplets: + self.__binders[triplet[1]].unbind(triplet, func) + self.__eventinfo[sequence][0] = None + return widget.unbind(self, sequence, funcid) + + def event_add(self, virtual, *sequences): + #print("event_add(%s, %s)" % (repr(virtual), repr(sequences)), + # file=sys.__stderr__) + if virtual not in self.__eventinfo: + self.__eventinfo[virtual] = [None, []] + + func, triplets = self.__eventinfo[virtual] + for seq in sequences: + triplet = _parse_sequence(seq) + if triplet is None: + #print("Tkinter event_add(%s)" % seq, file=sys.__stderr__) + widget.event_add(self, virtual, seq) + else: + if func is not None: + self.__binders[triplet[1]].bind(triplet, func) + triplets.append(triplet) + + def event_delete(self, virtual, *sequences): + if virtual not in self.__eventinfo: + return + func, triplets = self.__eventinfo[virtual] + for seq in sequences: + triplet = _parse_sequence(seq) + if triplet is None: + #print("Tkinter event_delete: %s" % seq, file=sys.__stderr__) + widget.event_delete(self, virtual, seq) + else: + if func is not None: + self.__binders[triplet[1]].unbind(triplet, func) + triplets.remove(triplet) + + def event_info(self, virtual=None): + if virtual is None or virtual not in self.__eventinfo: + return widget.event_info(self, virtual) + else: + return tuple(map(_triplet_to_sequence, + self.__eventinfo[virtual][1])) + \ + widget.event_info(self, virtual) + + def __del__(self): + for virtual in self.__eventinfo: + func, triplets = self.__eventinfo[virtual] + if func: + for triplet in triplets: + try: + self.__binders[triplet[1]].unbind(triplet, func) + except tkinter.TclError as e: + if not APPLICATION_GONE in e.args[0]: + raise + + _multicall_dict[widget] = MultiCall + return MultiCall + + +def _multi_call(parent): # htest # + top = tkinter.Toplevel(parent) + top.title("Test MultiCall") + x, y = map(int, parent.geometry().split('+')[1:]) + top.geometry("+%d+%d" % (x, y + 175)) + text = MultiCallCreator(tkinter.Text)(top) + text.pack() + text.focus_set() + + def bindseq(seq, n=[0]): + def handler(event): + print(seq) + text.bind("<>"%n[0], handler) + text.event_add("<>"%n[0], seq) + n[0] += 1 + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + bindseq("") + + +if __name__ == "__main__": + from unittest import main + main('idlelib.idle_test.test_mainmenu', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(_multi_call) diff --git a/shared/package-files/ef/efba022f33ba5a99916a7dbb6fba8ec7a9cdc45c47c9fead59bf122eff2c6ff1/ones_like_ops.h b/shared/package-files/ef/efba022f33ba5a99916a7dbb6fba8ec7a9cdc45c47c9fead59bf122eff2c6ff1/ones_like_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9418d8b3a98de9d83382ee82764fc038550ef40f --- /dev/null +++ b/shared/package-files/ef/efba022f33ba5a99916a7dbb6fba8ec7a9cdc45c47c9fead59bf122eff2c6ff1/ones_like_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API ones_like { + using schema = at::Tensor (const at::Tensor &, ::std::optional, ::std::optional, ::std::optional, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::ones_like"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +}; + +struct TORCH_API ones_like_out { + using schema = at::Tensor & (const at::Tensor &, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::ones_like"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "ones_like.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, ::std::optional memory_format, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional memory_format, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/efc15f3f75441b0f6e4cca147a305c1931d66c80ada1a3ee1a744a254816571c/index_cpu_dispatch.h b/shared/package-files/ef/efc15f3f75441b0f6e4cca147a305c1931d66c80ada1a3ee1a744a254816571c/index_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..33b5003030f46842945bf85ea5f9948d9b25ab73 --- /dev/null +++ b/shared/package-files/ef/efc15f3f75441b0f6e4cca147a305c1931d66c80ada1a3ee1a744a254816571c/index_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor index(const at::Tensor & self, const c10::List<::std::optional> & indices); +TORCH_API at::Tensor & index_out(at::Tensor & out, const at::Tensor & self, const c10::List<::std::optional> & indices); +TORCH_API at::Tensor & index_outf(const at::Tensor & self, const c10::List<::std::optional> & indices, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/ef/efc611e62536d171df1be78c6949902582bd2d4b99b011bf3104b0ce098fde80/libcsamfile.pxd b/shared/package-files/ef/efc611e62536d171df1be78c6949902582bd2d4b99b011bf3104b0ce098fde80/libcsamfile.pxd new file mode 100644 index 0000000000000000000000000000000000000000..b9e901485e17dfbfe10b430d70a997220fbc9041 --- /dev/null +++ b/shared/package-files/ef/efc611e62536d171df1be78c6949902582bd2d4b99b011bf3104b0ce098fde80/libcsamfile.pxd @@ -0,0 +1,46 @@ +# cython: language_level=3 +from pysam.libcalignmentfile cimport AlignedSegment, AlignmentFile + +################################################# +# Compatibility Layer for pysam < 0.8 + +# import all declarations from htslib +from pysam.libchtslib cimport * + +cdef class AlignedRead(AlignedSegment): + pass + +cdef class Samfile(AlignmentFile): + pass + +# import the conversion functions +cdef extern from "htslib_util.h": + + # add *nbytes* into the variable length data of *src* at *pos* + bam1_t * pysam_bam_update(bam1_t * b, + size_t nbytes_old, + size_t nbytes_new, + uint8_t * pos) + + # now: static + int aux_type2size(int) + + char * pysam_bam_get_qname(bam1_t * b) + uint32_t * pysam_bam_get_cigar(bam1_t * b) + uint8_t * pysam_bam_get_seq(bam1_t * b) + uint8_t * pysam_bam_get_qual(bam1_t * b) + uint8_t * pysam_bam_get_aux(bam1_t * b) + int pysam_bam_get_l_aux(bam1_t * b) + char pysam_bam_seqi(uint8_t * s, int i) + + uint16_t pysam_get_bin(bam1_t * b) + uint8_t pysam_get_qual(bam1_t * b) + uint8_t pysam_get_l_qname(bam1_t * b) + uint16_t pysam_get_flag(bam1_t * b) + uint32_t pysam_get_n_cigar(bam1_t * b) + void pysam_set_bin(bam1_t * b, uint16_t v) + void pysam_set_qual(bam1_t * b, uint8_t v) + void pysam_set_l_qname(bam1_t * b, uint8_t v) + void pysam_set_flag(bam1_t * b, uint16_t v) + void pysam_set_n_cigar(bam1_t * b, uint32_t v) + void pysam_update_flag(bam1_t * b, uint16_t v, uint16_t flag) diff --git a/shared/package-files/ef/efc68d2c28e26f3c6242c7a44cbf3af2688fee5363bc3579be1a7b1045c58d92/_trilinear_ops.h b/shared/package-files/ef/efc68d2c28e26f3c6242c7a44cbf3af2688fee5363bc3579be1a7b1045c58d92/_trilinear_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..64f459716f311906e64773f533b5ebff74fa76ea --- /dev/null +++ b/shared/package-files/ef/efc68d2c28e26f3c6242c7a44cbf3af2688fee5363bc3579be1a7b1045c58d92/_trilinear_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _trilinear { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_trilinear"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor"; + static at::Tensor call(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim); +}; + +struct TORCH_API _trilinear_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_trilinear"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_trilinear.out(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/efc6a306b8451d59bc090564038afe8c5a7361356ee4a35a7991a227a2c33207/misc.cpython-311.pyc b/shared/package-files/ef/efc6a306b8451d59bc090564038afe8c5a7361356ee4a35a7991a227a2c33207/misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55caa52fbc77371c09a7199e1c291baf81a5011 Binary files /dev/null and b/shared/package-files/ef/efc6a306b8451d59bc090564038afe8c5a7361356ee4a35a7991a227a2c33207/misc.cpython-311.pyc differ diff --git a/shared/package-files/ef/efc6c5b8c548d982af4d170aaf762978b06b8701c5b0cfa934656e9463e068b9/_softmax.h b/shared/package-files/ef/efc6c5b8c548d982af4d170aaf762978b06b8701c5b0cfa934656e9463e068b9/_softmax.h new file mode 100644 index 0000000000000000000000000000000000000000..a634b8faa597237a77646bec4d0eac0be8fb6d42 --- /dev/null +++ b/shared/package-files/ef/efc6c5b8c548d982af4d170aaf762978b06b8701c5b0cfa934656e9463e068b9/_softmax.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_softmax(Tensor self, int dim, bool half_to_float) -> Tensor +inline at::Tensor _softmax(const at::Tensor & self, int64_t dim, bool half_to_float) { + return at::_ops::_softmax::call(self, dim, half_to_float); +} + +// aten::_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _softmax_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool half_to_float) { + return at::_ops::_softmax_out::call(self, dim, half_to_float, out); +} +// aten::_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _softmax_outf(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out) { + return at::_ops::_softmax_out::call(self, dim, half_to_float, out); +} + +} diff --git a/shared/package-files/ef/efc9da02f9849dc8f942826f523373cb42d1214625252b93412a8fd7bcf21e1e/api.py b/shared/package-files/ef/efc9da02f9849dc8f942826f523373cb42d1214625252b93412a8fd7bcf21e1e/api.py new file mode 100644 index 0000000000000000000000000000000000000000..975f499023d132b51a3bb0a31d5d2278f1e8cae8 --- /dev/null +++ b/shared/package-files/ef/efc9da02f9849dc8f942826f523373cb42d1214625252b93412a8fd7bcf21e1e/api.py @@ -0,0 +1,306 @@ +# mypy: allow-untyped-defs +from contextlib import contextmanager +from typing import Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +from torch.distributed import distributed_c10d +from torch.distributed._shard.sharded_tensor import ShardedTensor + +from .sharder import Sharder +from .sharding_plan import ShardingPlan +from .sharding_spec import ChunkShardingSpec, ShardingSpec + + +def _shard_tensor( + tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None +) -> ShardedTensor: + """ + Given a :class:`torch.Tensor`, it shards that tensor according to the provided + ``sharding_spec``. ``src_rank`` denotes the source rank which would be + used as the ground truth of the data which would be scattered as shards + across the rest of the ranks. + + Args: + tensor (:class:`torch.Tensor`): Tensor needs to be sharded. + sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification + describing how to shard the Tensor. + + Keyword args: + src_rank (int, optional): The source rank which is used as the ground truth of + the data for the parameter that would be sharded and scattered + across the rest of the ranks. + Default: 0. + process_group (ProcessGroup, optional): The process group to work on. If None, + the default process group will be used. + + Returns: + A :class:`ShardedTensor` sharded from the given tensor. + + .. warning:: + Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is + currently supported as the ``sharding_spec``. + """ + if not tensor.is_contiguous(): + raise ValueError("input tensor is not a contiguous Tensor") + + pg = ( + process_group + if process_group is not None + else distributed_c10d._get_default_group() + ) + world_size = dist.get_world_size(pg) + current_rank = dist.get_rank(pg) + + # Validate src_rank and sharding_spec are same across all ranks. + gathered_list = [None] * world_size + dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg) + + for idx, entry in enumerate(gathered_list): + if src_rank != entry[0]: # type: ignore[index] + raise ValueError( + f"src_rank={src_rank} on rank: {current_rank} does not " # type: ignore[index] + f"match with src_rank={entry[0]} on rank: {idx}" # type: ignore[index] + ) + if sharding_spec != entry[1]: # type: ignore[index] + raise ValueError( + f"sharding_spec={sharding_spec} on rank: {current_rank} does not " # type: ignore[index] + f"match with sharding_spec={entry[1]} on rank: {idx}" # type: ignore[index] + ) + + st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg) + + return st + + +def shard_parameter( + module: torch.nn.Module, + param_name: str, + sharding_spec: ShardingSpec, + src_rank=0, + process_group=None, +): + """ + Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that + module, it shards that parameter according to the provided + ``sharding_spec``. ``src_rank`` denotes the source rank which would be + used as the ground truth of the data which would be scattered as shards + across the rest of the ranks. + + This method replaces ``module.param_name`` with a + :class:`torch.distributed._sharded_tensor.ShardedTensor` + + Args: + module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded. + param_name (str): Name of the parameter of ``module`` that needs to be sharded. + sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification + describing how to shard the Tensor. + + Keyword args: + src_rank (int, optional): The source rank which is used as the ground truth of + the data for the parameter that would be sharded and scattered + across the rest of the ranks. + Default: 0. + process_group (ProcessGroup, optional): The process group to work on. If None, + the default process group will be used. + + .. warning:: + Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is + currently supported as the ``sharding_spec``. + """ + # Perform some validation first. + if not hasattr(module, param_name): + raise AttributeError(f"{module._get_name()} has no attribute `{param_name}`") + + tensor = getattr(module, param_name) + if not isinstance(tensor, torch.Tensor): + raise ValueError( + f"Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}" + ) + + if not tensor.is_contiguous(): + raise ValueError(f"param: {param_name} is not a contiguous Tensor") + + st = _shard_tensor(tensor, sharding_spec, src_rank, process_group) + + # Replace param with ShardedTensor. + module.register_parameter(param_name, nn.Parameter(st)) + + +# Tracks the current process group in the load context manager. +_CURRENT_PROCESS_GROUP: Optional[dist.ProcessGroup] = None + + +@contextmanager +def load_with_process_group(process_group): + """ + Context manager to set the process group with which to load a ShardedTensor. + """ + global _CURRENT_PROCESS_GROUP + if _CURRENT_PROCESS_GROUP is not None: + raise RuntimeError( + 'ProcessGroup already set by previous "load_with_process_group" ' + "context manager" + ) + _CURRENT_PROCESS_GROUP = process_group + try: + yield process_group + finally: + _CURRENT_PROCESS_GROUP = None + + +def _get_current_process_group(): + """ + Retrieves the current process group set by ``load_with_process_group``. + If not set, it just returns the default group. + """ + global _CURRENT_PROCESS_GROUP + if _CURRENT_PROCESS_GROUP is None: + return distributed_c10d._get_default_group() + else: + return _CURRENT_PROCESS_GROUP + + +def _reshard_output( + module: torch.nn.Module, resharding_spec: ShardingSpec +) -> torch.nn.Module: + """ + Hook a module with output resharding in the forward pass according + to the given ``resharding_spec``. + + Args: + module (:class:`torch.nn.Module`): Module whose output needs to be resharded. + resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): + The specification describing how the output of the module will be resharded. + + Returns: + A :class:`torch.nn.Module` object with reshard API hooked. + """ + + def hook_func(_module, _input, output): + if isinstance(output, ShardedTensor): + return output.reshard(resharding_spec) + return output + + module.register_forward_hook(hook_func) + return module + + +def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module: + """ + Hook a module with local shards collection in the forward pass. + + This API is typically used to convert a sharded representation back to data parallel + representation. In particular, it returns the local tensor for this Shard. If the + size along the sharding dimension for the local tensor is 1, this dimension is removed + from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically + a local Tensor of size [16] across each rank and not [1, 16] across each rank. + + Args: + module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the + local tensor value needs to be returned. + + Returns: + A :class:`torch.nn.Module` object with collection API hooked. + """ + + def hook_func(_module, _input, output): + if isinstance(output, ShardedTensor): + local_tensor = output.local_tensor() + # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec + sharding_spec = output._sharding_spec + if ( + isinstance(sharding_spec, ChunkShardingSpec) + and local_tensor.size(sharding_spec.dim) == 1 # type: ignore[attr-defined, arg-type] + ): + local_tensor = local_tensor.squeeze( + output._sharding_spec.dim # type: ignore[attr-defined] + ) + return local_tensor + + module.register_forward_hook(hook_func) + return module + + +def shard_module(module: nn.Module, plan: ShardingPlan, src_rank=0, process_group=None): + """ + Shards a given module according to the provided sharding `plan`. This method + first shards all the parameters according to the given sharding `plan`. Then if + `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it + will tag the output of modules according `output_plan`, convert the module's + output back to data parallel according to `return_local_tensor`. + + Needs to be called on all ranks in an SPMD fashion. + + Args: + module (:class:`torch.nn.Module`): The module to apply sharding to + plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`): + The ShardingPlan which specified param name to ShardingSpec to apply to + each parameter. + + Keyword args: + src_rank (int, optional): The source rank which is used as the ground truth of + the data for the module that would be sharded and scattered across the rest + of the ranks. + Default: 0. + process_group (ProcessGroup, optional): The process group to work on. If None, + the default process group will be used. + """ + # record Sharder paths for sanity check on the plan to ensure items in the plan + # does not conflict with the submodule tree that the Sharder is working with + sharder_paths = [] + for name, spec in plan.plan.items(): + if isinstance(spec, Sharder): + sharder_paths.append(name) + + # shard the parameter according to the ShardingPlan + for name, spec in plan.plan.items(): + if isinstance(spec, ShardingSpec): + # if found a sharding spec, try to shard the parameter + module_path, _, param_name = name.rpartition(".") + + for sharder_path in sharder_paths: + if module_path.startswith(sharder_path): + raise RuntimeError( + f"ShardingPlan is in-valid, trying to shard a parameter: {name}," + f" but there's already a Sharder entry for module {sharder_path}," + f" parameter sharding should not conflict with the submodule tree" + f" that a Sharder is working with!" + ) + + mod = module.get_submodule(module_path) + shard_parameter( + mod, param_name, spec, src_rank=src_rank, process_group=process_group + ) + elif isinstance(spec, Sharder): + parent_mod_path, _, _mod_name = name.rpartition(".") + if name == "": + raise KeyError("Module path must not be empty for custom sharder!") + mod = module.get_submodule(name) + parent_mod = module.get_submodule(parent_mod_path) + sharded_mod = spec.shard(mod) + # swap this submodule with the sharded module + parent_mod.mod_name = sharded_mod + else: + raise TypeError( + f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'" + ) + + # reshard output if there's an entry in `reshard_output` for this module + if plan.output_plan is not None: + for module_path, output_spec in plan.output_plan.items(): + if isinstance(output_spec, ShardingSpec): + mod = module.get_submodule(module_path) + _reshard_output(mod, output_spec) + else: + raise TypeError( + f"Only `ShardingSpec` is supported as output_plan for '{module_path}'" + ) + # convert the output back to data parallel for the modules appears in + # `return_local_tensor` of the plan, we will call `_collect_local_shard` + # to collect the local tensor for output of modules + if plan.return_local_tensor is not None: + for module_path in plan.return_local_tensor: + mod = module.get_submodule(module_path) + _collect_local_shard(mod) diff --git a/shared/package-files/ef/efcc8705f87ce8767d91850160ce2b8a1e8d00442e61f2331c0851be66ba357d/top_level.txt b/shared/package-files/ef/efcc8705f87ce8767d91850160ce2b8a1e8d00442e61f2331c0851be66ba357d/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..23f03dad8df7ad2627772c87fffb91fc4075ee68 --- /dev/null +++ b/shared/package-files/ef/efcc8705f87ce8767d91850160ce2b8a1e8d00442e61f2331c0851be66ba357d/top_level.txt @@ -0,0 +1 @@ +pysam diff --git a/shared/package-files/ef/efcdb028de992a51ceedc40b0bc08a085f524e2c6f2c68d7ae9fc2c11a97c95b/formatting.h b/shared/package-files/ef/efcdb028de992a51ceedc40b0bc08a085f524e2c6f2c68d7ae9fc2c11a97c95b/formatting.h new file mode 100644 index 0000000000000000000000000000000000000000..f2e3622ce60d529ddee20f049c98246f04b97ff9 --- /dev/null +++ b/shared/package-files/ef/efcdb028de992a51ceedc40b0bc08a085f524e2c6f2c68d7ae9fc2c11a97c95b/formatting.h @@ -0,0 +1,668 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This is a private header for number-to-string formatting utilities + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/double_conversion.h" +#include "arrow/util/macros.h" +#include "arrow/util/string.h" +#include "arrow/util/time.h" +#include "arrow/util/visibility.h" +#include "arrow/vendored/datetime.h" + +namespace arrow { +namespace internal { + +/// \brief The entry point for conversion to strings. +template +class StringFormatter; + +template +struct is_formattable { + template ::value_type> + static std::true_type Test(U*); + + template + static std::false_type Test(...); + + static constexpr bool value = decltype(Test(NULLPTR))::value; +}; + +template +using enable_if_formattable = enable_if_t::value, R>; + +template +using Return = decltype(std::declval()(std::string_view{})); + +///////////////////////////////////////////////////////////////////////// +// Boolean formatting + +template <> +class StringFormatter { + public: + explicit StringFormatter(const DataType* = NULLPTR) {} + + using value_type = bool; + + template + Return operator()(bool value, Appender&& append) { + if (value) { + const char string[] = "true"; + return append(std::string_view(string)); + } else { + const char string[] = "false"; + return append(std::string_view(string)); + } + } +}; + +///////////////////////////////////////////////////////////////////////// +// Decimals formatting + +template +class DecimalToStringFormatterMixin { + public: + explicit DecimalToStringFormatterMixin(const DataType* type) + : scale_(static_cast(type)->scale()) {} + + using value_type = typename TypeTraits::CType; + + template + Return operator()(const value_type& value, Appender&& append) { + return append(value.ToString(scale_)); + } + + private: + int32_t scale_; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Integer formatting + +namespace detail { + +// A 2x100 direct table mapping integers in [0..99] to their decimal representations. +ARROW_EXPORT extern const char digit_pairs[]; + +// Based on fmtlib's format_int class: +// Write digits from right to left into a stack allocated buffer. +// \pre *cursor points to the byte after the one that will be written. +// \post *cursor points to the byte that was written. +inline void FormatOneChar(char c, char** cursor) { *(--(*cursor)) = c; } + +template +void FormatOneDigit(Int value, char** cursor) { + assert(value >= 0 && value <= 9); + FormatOneChar(static_cast('0' + value), cursor); +} + +// GH-35662: I don't know why but the following combination causes SEGV: +// * template implementation without inline +// * MinGW +// * Release build +template +inline void FormatTwoDigits(Int value, char** cursor) { + assert(value >= 0 && value <= 99); + auto digit_pair = &digit_pairs[value * 2]; + FormatOneChar(digit_pair[1], cursor); + FormatOneChar(digit_pair[0], cursor); +} + +template +void FormatAllDigits(Int value, char** cursor) { + assert(value >= 0); + while (value >= 100) { + FormatTwoDigits(value % 100, cursor); + value /= 100; + } + + if (value >= 10) { + FormatTwoDigits(value, cursor); + } else { + FormatOneDigit(value, cursor); + } +} + +template +void FormatAllDigitsLeftPadded(Int value, size_t pad, char pad_char, char** cursor) { + auto end = *cursor - pad; + FormatAllDigits(value, cursor); + while (*cursor > end) { + FormatOneChar(pad_char, cursor); + } +} + +template +std::string_view ViewDigitBuffer(const std::array& buffer, + char* cursor) { + auto buffer_end = buffer.data() + BUFFER_SIZE; + return {cursor, static_cast(buffer_end - cursor)}; +} + +template ::type> +constexpr UInt Abs(Int value) { + return value < 0 ? ~static_cast(value) + 1 : static_cast(value); +} + +template +constexpr size_t Digits10(Int value) { + return value <= 9 ? 1 : Digits10(value / 10) + 1; +} + +} // namespace detail + +template +class IntToStringFormatterMixin { + public: + explicit IntToStringFormatterMixin(const DataType* = NULLPTR) {} + + using value_type = typename ARROW_TYPE::c_type; + + template + Return operator()(value_type value, Appender&& append) { + constexpr size_t buffer_size = + detail::Digits10(std::numeric_limits::max()) + 1; + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + detail::FormatAllDigits(detail::Abs(value), &cursor); + if (value < 0) { + detail::FormatOneChar('-', &cursor); + } + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Floating-point formatting + +class ARROW_EXPORT FloatToStringFormatter { + public: + FloatToStringFormatter(); + FloatToStringFormatter(int flags, const char* inf_symbol, const char* nan_symbol, + char exp_character, int decimal_in_shortest_low, + int decimal_in_shortest_high, + int max_leading_padding_zeroes_in_precision_mode, + int max_trailing_padding_zeroes_in_precision_mode); + ~FloatToStringFormatter(); + + // Returns the number of characters written + int FormatFloat(float v, char* out_buffer, int out_size); + int FormatFloat(double v, char* out_buffer, int out_size); + int FormatFloat(uint16_t v, char* out_buffer, int out_size); + + protected: + struct Impl; + std::unique_ptr impl_; +}; + +template +class FloatToStringFormatterMixin : public FloatToStringFormatter { + public: + using value_type = typename ARROW_TYPE::c_type; + + static constexpr int buffer_size = 50; + + explicit FloatToStringFormatterMixin(const DataType* = NULLPTR) {} + + FloatToStringFormatterMixin(int flags, const char* inf_symbol, const char* nan_symbol, + char exp_character, int decimal_in_shortest_low, + int decimal_in_shortest_high, + int max_leading_padding_zeroes_in_precision_mode, + int max_trailing_padding_zeroes_in_precision_mode) + : FloatToStringFormatter(flags, inf_symbol, nan_symbol, exp_character, + decimal_in_shortest_low, decimal_in_shortest_high, + max_leading_padding_zeroes_in_precision_mode, + max_trailing_padding_zeroes_in_precision_mode) {} + + template + Return operator()(value_type value, Appender&& append) { + char buffer[buffer_size]; + int size = FormatFloat(value, buffer, buffer_size); + return append(std::string_view(buffer, size)); + } +}; + +template <> +class StringFormatter : public FloatToStringFormatterMixin { + public: + using FloatToStringFormatterMixin::FloatToStringFormatterMixin; +}; + +template <> +class StringFormatter : public FloatToStringFormatterMixin { + public: + using FloatToStringFormatterMixin::FloatToStringFormatterMixin; +}; + +template <> +class StringFormatter : public FloatToStringFormatterMixin { + public: + using FloatToStringFormatterMixin::FloatToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Temporal formatting + +namespace detail { + +constexpr size_t BufferSizeYYYY_MM_DD() { + // "-"? "99999-12-31" + return 1 + detail::Digits10(99999) + 1 + detail::Digits10(12) + 1 + + detail::Digits10(31); +} + +inline void FormatYYYY_MM_DD(arrow_vendored::date::year_month_day ymd, char** cursor) { + FormatTwoDigits(static_cast(ymd.day()), cursor); + FormatOneChar('-', cursor); + FormatTwoDigits(static_cast(ymd.month()), cursor); + FormatOneChar('-', cursor); + auto year = static_cast(ymd.year()); + const auto is_neg_year = year < 0; + year = std::abs(year); + assert(year <= 99999); + FormatTwoDigits(year % 100, cursor); + year /= 100; + FormatTwoDigits(year % 100, cursor); + if (year >= 100) { + FormatOneDigit(year / 100, cursor); + } + if (is_neg_year) { + FormatOneChar('-', cursor); + } +} + +template +constexpr size_t BufferSizeHH_MM_SS() { + // "23:59:59" ("." "9"+)? + return detail::Digits10(23) + 1 + detail::Digits10(59) + 1 + detail::Digits10(59) + 1 + + detail::Digits10(Duration::period::den) - 1; +} + +template +void FormatHH_MM_SS(arrow_vendored::date::hh_mm_ss hms, char** cursor) { + constexpr size_t subsecond_digits = Digits10(Duration::period::den) - 1; + if (subsecond_digits != 0) { + FormatAllDigitsLeftPadded(hms.subseconds().count(), subsecond_digits, '0', cursor); + FormatOneChar('.', cursor); + } + FormatTwoDigits(hms.seconds().count(), cursor); + FormatOneChar(':', cursor); + FormatTwoDigits(hms.minutes().count(), cursor); + FormatOneChar(':', cursor); + FormatTwoDigits(hms.hours().count(), cursor); +} + +// Some out-of-bound datetime values would result in erroneous printing +// because of silent integer wraparound in the `arrow_vendored::date` library. +// +// To avoid such misprinting, we must therefore check the bounds explicitly. +// The bounds correspond to start of year -32767 and end of year 32767, +// respectively (-32768 is an invalid year value in `arrow_vendored::date`). +// +// Note these values are the same as documented for C++20: +// https://en.cppreference.com/w/cpp/chrono/year_month_day/operator_days +template +bool IsDateTimeInRange(Unit duration) { + constexpr Unit kMinIncl = + std::chrono::duration_cast(arrow_vendored::date::days{-12687428}); + constexpr Unit kMaxExcl = + std::chrono::duration_cast(arrow_vendored::date::days{11248738}); + return duration >= kMinIncl && duration < kMaxExcl; +} + +// IsDateTimeInRange() specialization for nanoseconds: a 64-bit number of +// nanoseconds cannot represent years outside of the [-32767, 32767] +// range, and the {kMinIncl, kMaxExcl} constants above would overflow. +constexpr bool IsDateTimeInRange(std::chrono::nanoseconds duration) { return true; } + +template +bool IsTimeInRange(Unit duration) { + constexpr Unit kMinIncl = std::chrono::duration_cast(std::chrono::seconds{0}); + constexpr Unit kMaxExcl = std::chrono::duration_cast(std::chrono::seconds{86400}); + return duration >= kMinIncl && duration < kMaxExcl; +} + +template +Return FormatOutOfRange(RawValue&& raw_value, Appender&& append) { + // XXX locale-sensitive but good enough for now + std::string formatted = ""; + return append(std::move(formatted)); +} + +const auto kEpoch = arrow_vendored::date::sys_days{arrow_vendored::date::jan / 1 / 1970}; + +} // namespace detail + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +class DateToStringFormatterMixin { + public: + explicit DateToStringFormatterMixin(const DataType* = NULLPTR) {} + + protected: + template + Return FormatDays(arrow_vendored::date::days since_epoch, Appender&& append) { + arrow_vendored::date::sys_days timepoint_days{since_epoch}; + + constexpr size_t buffer_size = detail::BufferSizeYYYY_MM_DD(); + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatYYYY_MM_DD(arrow_vendored::date::year_month_day{timepoint_days}, + &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter : public DateToStringFormatterMixin { + public: + using value_type = typename Date32Type::c_type; + + using DateToStringFormatterMixin::DateToStringFormatterMixin; + + template + Return operator()(value_type value, Appender&& append) { + const auto since_epoch = arrow_vendored::date::days{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + return FormatDays(since_epoch, std::forward(append)); + } +}; + +template <> +class StringFormatter : public DateToStringFormatterMixin { + public: + using value_type = typename Date64Type::c_type; + + using DateToStringFormatterMixin::DateToStringFormatterMixin; + + template + Return operator()(value_type value, Appender&& append) { + const auto since_epoch = std::chrono::milliseconds{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + return FormatDays(std::chrono::duration_cast(since_epoch), + std::forward(append)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = int64_t; + + explicit StringFormatter(const DataType* type) + : unit_(checked_cast(*type).unit()), + timezone_(checked_cast(*type).timezone()) {} + + template + Return operator()(Duration, value_type value, Appender&& append) { + using arrow_vendored::date::days; + + const Duration since_epoch{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + + const auto timepoint = detail::kEpoch + since_epoch; + // Round days towards zero + // (the naive approach of using arrow_vendored::date::floor() would + // result in UB for very large negative timestamps, similarly as + // https://github.com/HowardHinnant/date/issues/696) + auto timepoint_days = std::chrono::time_point_cast(timepoint); + Duration since_midnight; + if (timepoint_days <= timepoint) { + // Year >= 1970 + since_midnight = timepoint - timepoint_days; + } else { + // Year < 1970 + since_midnight = days(1) - (timepoint_days - timepoint); + timepoint_days -= days(1); + } + + // YYYY_MM_DD " " HH_MM_SS "Z"? + constexpr size_t buffer_size = + detail::BufferSizeYYYY_MM_DD() + 1 + detail::BufferSizeHH_MM_SS() + 1; + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + if (timezone_.size() > 0) { + detail::FormatOneChar('Z', &cursor); + } + detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor); + detail::FormatOneChar(' ', &cursor); + detail::FormatYYYY_MM_DD(timepoint_days, &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } + + template + Return operator()(value_type value, Appender&& append) { + return util::VisitDuration(unit_, *this, value, std::forward(append)); + } + + private: + TimeUnit::type unit_; + std::string timezone_; +}; + +template +class StringFormatter> { + public: + using value_type = typename T::c_type; + + explicit StringFormatter(const DataType* type) + : unit_(checked_cast(*type).unit()) {} + + template + Return operator()(Duration, value_type count, Appender&& append) { + const Duration since_midnight{count}; + if (!ARROW_PREDICT_TRUE(detail::IsTimeInRange(since_midnight))) { + return detail::FormatOutOfRange(count, append); + } + + constexpr size_t buffer_size = detail::BufferSizeHH_MM_SS(); + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } + + template + Return operator()(value_type value, Appender&& append) { + return util::VisitDuration(unit_, *this, value, std::forward(append)); + } + + private: + TimeUnit::type unit_; +}; + +template <> +class StringFormatter { + public: + using value_type = MonthIntervalType::c_type; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*'m'*/ 3 + /*negative signs*/ 1 + + /*months*/ detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('M', &cursor); + detail::FormatAllDigits(detail::Abs(interval), &cursor); + if (interval < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = DayTimeIntervalType::DayMilliseconds; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*d, ms*/ 3 + /*negative signs*/ 2 + + /*days/milliseconds*/ 2 * detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('s', &cursor); + detail::FormatOneChar('m', &cursor); + detail::FormatAllDigits(detail::Abs(interval.milliseconds), &cursor); + if (interval.milliseconds < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('d', &cursor); + detail::FormatAllDigits(detail::Abs(interval.days), &cursor); + if (interval.days < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = MonthDayNanoIntervalType::MonthDayNanos; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*m, d, ns*/ 4 + /*negative signs*/ 3 + + /*months/days*/ 2 * detail::Digits10(std::numeric_limits::max()) + + /*nanoseconds*/ detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('s', &cursor); + detail::FormatOneChar('n', &cursor); + detail::FormatAllDigits(detail::Abs(interval.nanoseconds), &cursor); + if (interval.nanoseconds < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('d', &cursor); + detail::FormatAllDigits(detail::Abs(interval.days), &cursor); + if (interval.days < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('M', &cursor); + detail::FormatAllDigits(detail::Abs(interval.months), &cursor); + if (interval.months < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/ef/efd052a95be5a0a73c2587a75107ea74f9b46b424066177d66577b9390a9da57/base64.py b/shared/package-files/ef/efd052a95be5a0a73c2587a75107ea74f9b46b424066177d66577b9390a9da57/base64.py new file mode 100644 index 0000000000000000000000000000000000000000..307c6d52b2b74807e08445b3d121ec0f19b374b0 --- /dev/null +++ b/shared/package-files/ef/efd052a95be5a0a73c2587a75107ea74f9b46b424066177d66577b9390a9da57/base64.py @@ -0,0 +1,26 @@ +import base64 as _base64 + +from .abc import Codec +from .compat import ensure_contiguous_ndarray, ndarray_copy + + +class Base64(Codec): + """Codec providing base64 compression via the Python standard library.""" + + codec_id = "base64" + + def encode(self, buf): + # normalise inputs + buf = ensure_contiguous_ndarray(buf) + # do compression + return _base64.standard_b64encode(buf) + + def decode(self, buf, out=None): + # normalise inputs + buf = ensure_contiguous_ndarray(buf) + if out is not None: + out = ensure_contiguous_ndarray(out) + # do decompression + decompressed = _base64.standard_b64decode(buf) + # handle destination + return ndarray_copy(decompressed, out) diff --git a/shared/package-files/ef/efd18d09547904367d2222edd64fe75bc54194afe401c0f852469fca2126e1e1/test_chaining_and_caching.cpython-311.pyc b/shared/package-files/ef/efd18d09547904367d2222edd64fe75bc54194afe401c0f852469fca2126e1e1/test_chaining_and_caching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca643ec7490e663066fff5efd1bcb6fdb4adc4a6 Binary files /dev/null and b/shared/package-files/ef/efd18d09547904367d2222edd64fe75bc54194afe401c0f852469fca2126e1e1/test_chaining_and_caching.cpython-311.pyc differ diff --git a/shared/package-files/ef/efd47a54c8678beea483d2e696607319edb61d7860d11bd2563c388d534f3094/test_zstd.py b/shared/package-files/ef/efd47a54c8678beea483d2e696607319edb61d7860d11bd2563c388d534f3094/test_zstd.py new file mode 100644 index 0000000000000000000000000000000000000000..de42d9e1eb19e68dc979f3f27f9bfe2293e5e4de --- /dev/null +++ b/shared/package-files/ef/efd47a54c8678beea483d2e696607319edb61d7860d11bd2563c388d534f3094/test_zstd.py @@ -0,0 +1,92 @@ +import itertools + +import numpy as np +import pytest + +try: + from numcodecs.zstd import Zstd +except ImportError: # pragma: no cover + pytest.skip("numcodecs.zstd not available", allow_module_level=True) + + +from numcodecs.tests.common import ( + check_backwards_compatibility, + check_config, + check_encode_decode, + check_err_decode_object_buffer, + check_err_encode_object_buffer, + check_repr, +) + +codecs = [ + Zstd(), + Zstd(level=-1), + Zstd(level=0), + Zstd(level=1), + Zstd(level=10), + Zstd(level=22), + Zstd(level=100), + Zstd(checksum=True), + Zstd(level=0, checksum=True), + Zstd(level=22, checksum=True), +] + + +# mix of dtypes: integer, float, bool, string +# mix of shapes: 1D, 2D, 3D +# mix of orders: C, F +arrays = [ + np.arange(1000, dtype="i4"), + np.linspace(1000, 1001, 1000, dtype="f8"), + np.random.normal(loc=1000, scale=1, size=(100, 10)), + np.random.randint(0, 2, size=1000, dtype=bool).reshape(100, 10, order='F'), + np.random.choice([b'a', b'bb', b'ccc'], size=1000).reshape(10, 10, 10), + np.random.randint(0, 2**60, size=1000, dtype='u8').view('M8[ns]'), + np.random.randint(0, 2**60, size=1000, dtype='u8').view('m8[ns]'), + np.random.randint(0, 2**25, size=1000, dtype='u8').view('M8[m]'), + np.random.randint(0, 2**25, size=1000, dtype='u8').view('m8[m]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('M8[ns]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('m8[ns]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('M8[m]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('m8[m]'), +] + + +def test_encode_decode(): + for arr, codec in itertools.product(arrays, codecs): + check_encode_decode(arr, codec) + + +def test_config(): + for codec in codecs: + check_config(codec) + + +def test_repr(): + check_repr("Zstd(level=3)") + + +def test_backwards_compatibility(): + check_backwards_compatibility(Zstd.codec_id, arrays, codecs) + + +def test_err_decode_object_buffer(): + check_err_decode_object_buffer(Zstd()) + + +def test_err_encode_object_buffer(): + check_err_encode_object_buffer(Zstd()) + + +def test_checksum(): + data = np.arange(0, 64, dtype="uint8") + assert len(Zstd(level=0, checksum=False).encode(data)) + 4 == len( + Zstd(level=0, checksum=True).encode(data) + ) + + +def test_native_functions(): + # Note, these assertions might need to be changed for new versions of zstd + assert Zstd.default_level() == 3 + assert Zstd.min_level() == -131072 + assert Zstd.max_level() == 22 diff --git a/shared/package-files/ef/efd586cf30003e518ecda2133bcb39b548990ee234199bbabd54f32139174f4d/__init__.cpython-311.pyc b/shared/package-files/ef/efd586cf30003e518ecda2133bcb39b548990ee234199bbabd54f32139174f4d/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a73539913506e13d9e2f09a79882ec6ec56f353 Binary files /dev/null and b/shared/package-files/ef/efd586cf30003e518ecda2133bcb39b548990ee234199bbabd54f32139174f4d/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/efd6d2fa66f012d6f59c148cc47bd5ffb3ae6046f5e3c9411a9b6443de2e8b61/_scaled_dot_product_attention_math.h b/shared/package-files/ef/efd6d2fa66f012d6f59c148cc47bd5ffb3ae6046f5e3c9411a9b6443de2e8b61/_scaled_dot_product_attention_math.h new file mode 100644 index 0000000000000000000000000000000000000000..633266da952be6f348a6d905b0d8fac4197bda5c --- /dev/null +++ b/shared/package-files/ef/efd6d2fa66f012d6f59c148cc47bd5ffb3ae6046f5e3c9411a9b6443de2e8b61/_scaled_dot_product_attention_math.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_scaled_dot_product_attention_math(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None, bool enable_gqa=False) -> (Tensor, Tensor) +inline ::std::tuple _scaled_dot_product_attention_math(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & attn_mask={}, double dropout_p=0.0, bool is_causal=false, const ::std::optional & dropout_mask={}, ::std::optional scale=::std::nullopt, bool enable_gqa=false) { + return at::_ops::_scaled_dot_product_attention_math::call(query, key, value, attn_mask, dropout_p, is_causal, dropout_mask, scale, enable_gqa); +} + +} diff --git a/shared/package-files/ef/efd75d38546c1288fb82545835cabe2fbacf079cb78c5c6e3859c20f99505bea/interval.py b/shared/package-files/ef/efd75d38546c1288fb82545835cabe2fbacf079cb78c5c6e3859c20f99505bea/interval.py new file mode 100644 index 0000000000000000000000000000000000000000..4fcdb879745112889dd510a00b39586a22ed3dea --- /dev/null +++ b/shared/package-files/ef/efd75d38546c1288fb82545835cabe2fbacf079cb78c5c6e3859c20f99505bea/interval.py @@ -0,0 +1,1136 @@ +""" define the IntervalIndex """ +from __future__ import annotations + +from operator import ( + le, + lt, +) +import textwrap +from typing import ( + TYPE_CHECKING, + Any, + Literal, +) + +import numpy as np + +from pandas._libs import lib +from pandas._libs.interval import ( + Interval, + IntervalMixin, + IntervalTree, +) +from pandas._libs.tslibs import ( + BaseOffset, + Period, + Timedelta, + Timestamp, + to_offset, +) +from pandas.errors import InvalidIndexError +from pandas.util._decorators import ( + Appender, + cache_readonly, +) +from pandas.util._exceptions import rewrite_exception + +from pandas.core.dtypes.cast import ( + find_common_type, + infer_dtype_from_scalar, + maybe_box_datetimelike, + maybe_downcast_numeric, + maybe_upcast_numeric_to_64bit, +) +from pandas.core.dtypes.common import ( + ensure_platform_int, + is_float_dtype, + is_integer, + is_integer_dtype, + is_list_like, + is_number, + is_object_dtype, + is_scalar, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, + IntervalDtype, +) +from pandas.core.dtypes.missing import is_valid_na_for_dtype + +from pandas.core.algorithms import unique +from pandas.core.arrays.datetimelike import validate_periods +from pandas.core.arrays.interval import ( + IntervalArray, + _interval_shared_docs, +) +import pandas.core.common as com +from pandas.core.indexers import is_valid_positional_slice +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import ( + Index, + _index_shared_docs, + ensure_index, + maybe_extract_name, +) +from pandas.core.indexes.datetimes import ( + DatetimeIndex, + date_range, +) +from pandas.core.indexes.extension import ( + ExtensionIndex, + inherit_names, +) +from pandas.core.indexes.multi import MultiIndex +from pandas.core.indexes.timedeltas import ( + TimedeltaIndex, + timedelta_range, +) + +if TYPE_CHECKING: + from collections.abc import Hashable + + from pandas._typing import ( + Dtype, + DtypeObj, + IntervalClosedType, + Self, + npt, + ) +_index_doc_kwargs = dict(ibase._index_doc_kwargs) + +_index_doc_kwargs.update( + { + "klass": "IntervalIndex", + "qualname": "IntervalIndex", + "target_klass": "IntervalIndex or list of Intervals", + "name": textwrap.dedent( + """\ + name : object, optional + Name to be stored in the index. + """ + ), + } +) + + +def _get_next_label(label): + # see test_slice_locs_with_ints_and_floats_succeeds + dtype = getattr(label, "dtype", type(label)) + if isinstance(label, (Timestamp, Timedelta)): + dtype = "datetime64[ns]" + dtype = pandas_dtype(dtype) + + if lib.is_np_dtype(dtype, "mM") or isinstance(dtype, DatetimeTZDtype): + return label + np.timedelta64(1, "ns") + elif is_integer_dtype(dtype): + return label + 1 + elif is_float_dtype(dtype): + return np.nextafter(label, np.inf) + else: + raise TypeError(f"cannot determine next label for type {repr(type(label))}") + + +def _get_prev_label(label): + # see test_slice_locs_with_ints_and_floats_succeeds + dtype = getattr(label, "dtype", type(label)) + if isinstance(label, (Timestamp, Timedelta)): + dtype = "datetime64[ns]" + dtype = pandas_dtype(dtype) + + if lib.is_np_dtype(dtype, "mM") or isinstance(dtype, DatetimeTZDtype): + return label - np.timedelta64(1, "ns") + elif is_integer_dtype(dtype): + return label - 1 + elif is_float_dtype(dtype): + return np.nextafter(label, -np.inf) + else: + raise TypeError(f"cannot determine next label for type {repr(type(label))}") + + +def _new_IntervalIndex(cls, d): + """ + This is called upon unpickling, rather than the default which doesn't have + arguments and breaks __new__. + """ + return cls.from_arrays(**d) + + +@Appender( + _interval_shared_docs["class"] + % { + "klass": "IntervalIndex", + "summary": "Immutable index of intervals that are closed on the same side.", + "name": _index_doc_kwargs["name"], + "extra_attributes": "is_overlapping\nvalues\n", + "extra_methods": "", + "examples": textwrap.dedent( + """\ + Examples + -------- + A new ``IntervalIndex`` is typically constructed using + :func:`interval_range`: + + >>> pd.interval_range(start=0, end=5) + IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]], + dtype='interval[int64, right]') + + It may also be constructed using one of the constructor + methods: :meth:`IntervalIndex.from_arrays`, + :meth:`IntervalIndex.from_breaks`, and :meth:`IntervalIndex.from_tuples`. + + See further examples in the doc strings of ``interval_range`` and the + mentioned constructor methods. + """ + ), + } +) +@inherit_names(["set_closed", "to_tuples"], IntervalArray, wrap=True) +@inherit_names( + [ + "__array__", + "overlaps", + "contains", + "closed_left", + "closed_right", + "open_left", + "open_right", + "is_empty", + ], + IntervalArray, +) +@inherit_names(["is_non_overlapping_monotonic", "closed"], IntervalArray, cache=True) +class IntervalIndex(ExtensionIndex): + _typ = "intervalindex" + + # annotate properties pinned via inherit_names + closed: IntervalClosedType + is_non_overlapping_monotonic: bool + closed_left: bool + closed_right: bool + open_left: bool + open_right: bool + + _data: IntervalArray + _values: IntervalArray + _can_hold_strings = False + _data_cls = IntervalArray + + # -------------------------------------------------------------------- + # Constructors + + def __new__( + cls, + data, + closed: IntervalClosedType | None = None, + dtype: Dtype | None = None, + copy: bool = False, + name: Hashable | None = None, + verify_integrity: bool = True, + ) -> Self: + name = maybe_extract_name(name, data, cls) + + with rewrite_exception("IntervalArray", cls.__name__): + array = IntervalArray( + data, + closed=closed, + copy=copy, + dtype=dtype, + verify_integrity=verify_integrity, + ) + + return cls._simple_new(array, name) + + @classmethod + @Appender( + _interval_shared_docs["from_breaks"] + % { + "klass": "IntervalIndex", + "name": textwrap.dedent( + """ + name : str, optional + Name of the resulting IntervalIndex.""" + ), + "examples": textwrap.dedent( + """\ + Examples + -------- + >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3]) + IntervalIndex([(0, 1], (1, 2], (2, 3]], + dtype='interval[int64, right]') + """ + ), + } + ) + def from_breaks( + cls, + breaks, + closed: IntervalClosedType | None = "right", + name: Hashable | None = None, + copy: bool = False, + dtype: Dtype | None = None, + ) -> IntervalIndex: + with rewrite_exception("IntervalArray", cls.__name__): + array = IntervalArray.from_breaks( + breaks, closed=closed, copy=copy, dtype=dtype + ) + return cls._simple_new(array, name=name) + + @classmethod + @Appender( + _interval_shared_docs["from_arrays"] + % { + "klass": "IntervalIndex", + "name": textwrap.dedent( + """ + name : str, optional + Name of the resulting IntervalIndex.""" + ), + "examples": textwrap.dedent( + """\ + Examples + -------- + >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3]) + IntervalIndex([(0, 1], (1, 2], (2, 3]], + dtype='interval[int64, right]') + """ + ), + } + ) + def from_arrays( + cls, + left, + right, + closed: IntervalClosedType = "right", + name: Hashable | None = None, + copy: bool = False, + dtype: Dtype | None = None, + ) -> IntervalIndex: + with rewrite_exception("IntervalArray", cls.__name__): + array = IntervalArray.from_arrays( + left, right, closed, copy=copy, dtype=dtype + ) + return cls._simple_new(array, name=name) + + @classmethod + @Appender( + _interval_shared_docs["from_tuples"] + % { + "klass": "IntervalIndex", + "name": textwrap.dedent( + """ + name : str, optional + Name of the resulting IntervalIndex.""" + ), + "examples": textwrap.dedent( + """\ + Examples + -------- + >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)]) + IntervalIndex([(0, 1], (1, 2]], + dtype='interval[int64, right]') + """ + ), + } + ) + def from_tuples( + cls, + data, + closed: IntervalClosedType = "right", + name: Hashable | None = None, + copy: bool = False, + dtype: Dtype | None = None, + ) -> IntervalIndex: + with rewrite_exception("IntervalArray", cls.__name__): + arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype) + return cls._simple_new(arr, name=name) + + # -------------------------------------------------------------------- + # error: Return type "IntervalTree" of "_engine" incompatible with return type + # "Union[IndexEngine, ExtensionEngine]" in supertype "Index" + @cache_readonly + def _engine(self) -> IntervalTree: # type: ignore[override] + # IntervalTree does not supports numpy array unless they are 64 bit + left = self._maybe_convert_i8(self.left) + left = maybe_upcast_numeric_to_64bit(left) + right = self._maybe_convert_i8(self.right) + right = maybe_upcast_numeric_to_64bit(right) + return IntervalTree(left, right, closed=self.closed) + + def __contains__(self, key: Any) -> bool: + """ + return a boolean if this key is IN the index + We *only* accept an Interval + + Parameters + ---------- + key : Interval + + Returns + ------- + bool + """ + hash(key) + if not isinstance(key, Interval): + if is_valid_na_for_dtype(key, self.dtype): + return self.hasnans + return False + + try: + self.get_loc(key) + return True + except KeyError: + return False + + def _getitem_slice(self, slobj: slice) -> IntervalIndex: + """ + Fastpath for __getitem__ when we know we have a slice. + """ + res = self._data[slobj] + return type(self)._simple_new(res, name=self._name) + + @cache_readonly + def _multiindex(self) -> MultiIndex: + return MultiIndex.from_arrays([self.left, self.right], names=["left", "right"]) + + def __reduce__(self): + d = { + "left": self.left, + "right": self.right, + "closed": self.closed, + "name": self.name, + } + return _new_IntervalIndex, (type(self), d), None + + @property + def inferred_type(self) -> str: + """Return a string of the type inferred from the values""" + return "interval" + + # Cannot determine type of "memory_usage" + @Appender(Index.memory_usage.__doc__) # type: ignore[has-type] + def memory_usage(self, deep: bool = False) -> int: + # we don't use an explicit engine + # so return the bytes here + return self.left.memory_usage(deep=deep) + self.right.memory_usage(deep=deep) + + # IntervalTree doesn't have a is_monotonic_decreasing, so have to override + # the Index implementation + @cache_readonly + def is_monotonic_decreasing(self) -> bool: + """ + Return True if the IntervalIndex is monotonic decreasing (only equal or + decreasing values), else False + """ + return self[::-1].is_monotonic_increasing + + @cache_readonly + def is_unique(self) -> bool: + """ + Return True if the IntervalIndex contains unique elements, else False. + """ + left = self.left + right = self.right + + if self.isna().sum() > 1: + return False + + if left.is_unique or right.is_unique: + return True + + seen_pairs = set() + check_idx = np.where(left.duplicated(keep=False))[0] + for idx in check_idx: + pair = (left[idx], right[idx]) + if pair in seen_pairs: + return False + seen_pairs.add(pair) + + return True + + @property + def is_overlapping(self) -> bool: + """ + Return True if the IntervalIndex has overlapping intervals, else False. + + Two intervals overlap if they share a common point, including closed + endpoints. Intervals that only have an open endpoint in common do not + overlap. + + Returns + ------- + bool + Boolean indicating if the IntervalIndex has overlapping intervals. + + See Also + -------- + Interval.overlaps : Check whether two Interval objects overlap. + IntervalIndex.overlaps : Check an IntervalIndex elementwise for + overlaps. + + Examples + -------- + >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)]) + >>> index + IntervalIndex([(0, 2], (1, 3], (4, 5]], + dtype='interval[int64, right]') + >>> index.is_overlapping + True + + Intervals that share closed endpoints overlap: + + >>> index = pd.interval_range(0, 3, closed='both') + >>> index + IntervalIndex([[0, 1], [1, 2], [2, 3]], + dtype='interval[int64, both]') + >>> index.is_overlapping + True + + Intervals that only have an open endpoint in common do not overlap: + + >>> index = pd.interval_range(0, 3, closed='left') + >>> index + IntervalIndex([[0, 1), [1, 2), [2, 3)], + dtype='interval[int64, left]') + >>> index.is_overlapping + False + """ + # GH 23309 + return self._engine.is_overlapping + + def _needs_i8_conversion(self, key) -> bool: + """ + Check if a given key needs i8 conversion. Conversion is necessary for + Timestamp, Timedelta, DatetimeIndex, and TimedeltaIndex keys. An + Interval-like requires conversion if its endpoints are one of the + aforementioned types. + + Assumes that any list-like data has already been cast to an Index. + + Parameters + ---------- + key : scalar or Index-like + The key that should be checked for i8 conversion + + Returns + ------- + bool + """ + key_dtype = getattr(key, "dtype", None) + if isinstance(key_dtype, IntervalDtype) or isinstance(key, Interval): + return self._needs_i8_conversion(key.left) + + i8_types = (Timestamp, Timedelta, DatetimeIndex, TimedeltaIndex) + return isinstance(key, i8_types) + + def _maybe_convert_i8(self, key): + """ + Maybe convert a given key to its equivalent i8 value(s). Used as a + preprocessing step prior to IntervalTree queries (self._engine), which + expects numeric data. + + Parameters + ---------- + key : scalar or list-like + The key that should maybe be converted to i8. + + Returns + ------- + scalar or list-like + The original key if no conversion occurred, int if converted scalar, + Index with an int64 dtype if converted list-like. + """ + if is_list_like(key): + key = ensure_index(key) + key = maybe_upcast_numeric_to_64bit(key) + + if not self._needs_i8_conversion(key): + return key + + scalar = is_scalar(key) + key_dtype = getattr(key, "dtype", None) + if isinstance(key_dtype, IntervalDtype) or isinstance(key, Interval): + # convert left/right and reconstruct + left = self._maybe_convert_i8(key.left) + right = self._maybe_convert_i8(key.right) + constructor = Interval if scalar else IntervalIndex.from_arrays + # error: "object" not callable + return constructor( + left, right, closed=self.closed + ) # type: ignore[operator] + + if scalar: + # Timestamp/Timedelta + key_dtype, key_i8 = infer_dtype_from_scalar(key) + if isinstance(key, Period): + key_i8 = key.ordinal + elif isinstance(key_i8, Timestamp): + key_i8 = key_i8._value + elif isinstance(key_i8, (np.datetime64, np.timedelta64)): + key_i8 = key_i8.view("i8") + else: + # DatetimeIndex/TimedeltaIndex + key_dtype, key_i8 = key.dtype, Index(key.asi8) + if key.hasnans: + # convert NaT from its i8 value to np.nan so it's not viewed + # as a valid value, maybe causing errors (e.g. is_overlapping) + key_i8 = key_i8.where(~key._isnan) + + # ensure consistency with IntervalIndex subtype + # error: Item "ExtensionDtype"/"dtype[Any]" of "Union[dtype[Any], + # ExtensionDtype]" has no attribute "subtype" + subtype = self.dtype.subtype # type: ignore[union-attr] + + if subtype != key_dtype: + raise ValueError( + f"Cannot index an IntervalIndex of subtype {subtype} with " + f"values of dtype {key_dtype}" + ) + + return key_i8 + + def _searchsorted_monotonic(self, label, side: Literal["left", "right"] = "left"): + if not self.is_non_overlapping_monotonic: + raise KeyError( + "can only get slices from an IntervalIndex if bounds are " + "non-overlapping and all monotonic increasing or decreasing" + ) + + if isinstance(label, (IntervalMixin, IntervalIndex)): + raise NotImplementedError("Interval objects are not currently supported") + + # GH 20921: "not is_monotonic_increasing" for the second condition + # instead of "is_monotonic_decreasing" to account for single element + # indexes being both increasing and decreasing + if (side == "left" and self.left.is_monotonic_increasing) or ( + side == "right" and not self.left.is_monotonic_increasing + ): + sub_idx = self.right + if self.open_right: + label = _get_next_label(label) + else: + sub_idx = self.left + if self.open_left: + label = _get_prev_label(label) + + return sub_idx._searchsorted_monotonic(label, side) + + # -------------------------------------------------------------------- + # Indexing Methods + + def get_loc(self, key) -> int | slice | np.ndarray: + """ + Get integer location, slice or boolean mask for requested label. + + Parameters + ---------- + key : label + + Returns + ------- + int if unique index, slice if monotonic index, else mask + + Examples + -------- + >>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2) + >>> index = pd.IntervalIndex([i1, i2]) + >>> index.get_loc(1) + 0 + + You can also supply a point inside an interval. + + >>> index.get_loc(1.5) + 1 + + If a label is in several intervals, you get the locations of all the + relevant intervals. + + >>> i3 = pd.Interval(0, 2) + >>> overlapping_index = pd.IntervalIndex([i1, i2, i3]) + >>> overlapping_index.get_loc(0.5) + array([ True, False, True]) + + Only exact matches will be returned if an interval is provided. + + >>> index.get_loc(pd.Interval(0, 1)) + 0 + """ + self._check_indexing_error(key) + + if isinstance(key, Interval): + if self.closed != key.closed: + raise KeyError(key) + mask = (self.left == key.left) & (self.right == key.right) + elif is_valid_na_for_dtype(key, self.dtype): + mask = self.isna() + else: + # assume scalar + op_left = le if self.closed_left else lt + op_right = le if self.closed_right else lt + try: + mask = op_left(self.left, key) & op_right(key, self.right) + except TypeError as err: + # scalar is not comparable to II subtype --> invalid label + raise KeyError(key) from err + + matches = mask.sum() + if matches == 0: + raise KeyError(key) + if matches == 1: + return mask.argmax() + + res = lib.maybe_booleans_to_slice(mask.view("u1")) + if isinstance(res, slice) and res.stop is None: + # TODO: DO this in maybe_booleans_to_slice? + res = slice(res.start, len(self), res.step) + return res + + def _get_indexer( + self, + target: Index, + method: str | None = None, + limit: int | None = None, + tolerance: Any | None = None, + ) -> npt.NDArray[np.intp]: + if isinstance(target, IntervalIndex): + # We only get here with not self.is_overlapping + # -> at most one match per interval in target + # want exact matches -> need both left/right to match, so defer to + # left/right get_indexer, compare elementwise, equality -> match + indexer = self._get_indexer_unique_sides(target) + + elif not is_object_dtype(target.dtype): + # homogeneous scalar index: use IntervalTree + # we should always have self._should_partial_index(target) here + target = self._maybe_convert_i8(target) + indexer = self._engine.get_indexer(target.values) + else: + # heterogeneous scalar index: defer elementwise to get_loc + # we should always have self._should_partial_index(target) here + return self._get_indexer_pointwise(target)[0] + + return ensure_platform_int(indexer) + + @Appender(_index_shared_docs["get_indexer_non_unique"] % _index_doc_kwargs) + def get_indexer_non_unique( + self, target: Index + ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + target = ensure_index(target) + + if not self._should_compare(target) and not self._should_partial_index(target): + # e.g. IntervalIndex with different closed or incompatible subtype + # -> no matches + return self._get_indexer_non_comparable(target, None, unique=False) + + elif isinstance(target, IntervalIndex): + if self.left.is_unique and self.right.is_unique: + # fastpath available even if we don't have self._index_as_unique + indexer = self._get_indexer_unique_sides(target) + missing = (indexer == -1).nonzero()[0] + else: + return self._get_indexer_pointwise(target) + + elif is_object_dtype(target.dtype) or not self._should_partial_index(target): + # target might contain intervals: defer elementwise to get_loc + return self._get_indexer_pointwise(target) + + else: + # Note: this case behaves differently from other Index subclasses + # because IntervalIndex does partial-int indexing + target = self._maybe_convert_i8(target) + indexer, missing = self._engine.get_indexer_non_unique(target.values) + + return ensure_platform_int(indexer), ensure_platform_int(missing) + + def _get_indexer_unique_sides(self, target: IntervalIndex) -> npt.NDArray[np.intp]: + """ + _get_indexer specialized to the case where both of our sides are unique. + """ + # Caller is responsible for checking + # `self.left.is_unique and self.right.is_unique` + + left_indexer = self.left.get_indexer(target.left) + right_indexer = self.right.get_indexer(target.right) + indexer = np.where(left_indexer == right_indexer, left_indexer, -1) + return indexer + + def _get_indexer_pointwise( + self, target: Index + ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + """ + pointwise implementation for get_indexer and get_indexer_non_unique. + """ + indexer, missing = [], [] + for i, key in enumerate(target): + try: + locs = self.get_loc(key) + if isinstance(locs, slice): + # Only needed for get_indexer_non_unique + locs = np.arange(locs.start, locs.stop, locs.step, dtype="intp") + elif lib.is_integer(locs): + locs = np.array(locs, ndmin=1) + else: + # otherwise we have ndarray[bool] + locs = np.where(locs)[0] + except KeyError: + missing.append(i) + locs = np.array([-1]) + except InvalidIndexError: + # i.e. non-scalar key e.g. a tuple. + # see test_append_different_columns_types_raises + missing.append(i) + locs = np.array([-1]) + + indexer.append(locs) + + indexer = np.concatenate(indexer) + return ensure_platform_int(indexer), ensure_platform_int(missing) + + @cache_readonly + def _index_as_unique(self) -> bool: + return not self.is_overlapping and self._engine._na_count < 2 + + _requires_unique_msg = ( + "cannot handle overlapping indices; use IntervalIndex.get_indexer_non_unique" + ) + + def _convert_slice_indexer(self, key: slice, kind: Literal["loc", "getitem"]): + if not (key.step is None or key.step == 1): + # GH#31658 if label-based, we require step == 1, + # if positional, we disallow float start/stop + msg = "label-based slicing with step!=1 is not supported for IntervalIndex" + if kind == "loc": + raise ValueError(msg) + if kind == "getitem": + if not is_valid_positional_slice(key): + # i.e. this cannot be interpreted as a positional slice + raise ValueError(msg) + + return super()._convert_slice_indexer(key, kind) + + @cache_readonly + def _should_fallback_to_positional(self) -> bool: + # integer lookups in Series.__getitem__ are unambiguously + # positional in this case + # error: Item "ExtensionDtype"/"dtype[Any]" of "Union[dtype[Any], + # ExtensionDtype]" has no attribute "subtype" + return self.dtype.subtype.kind in "mM" # type: ignore[union-attr] + + def _maybe_cast_slice_bound(self, label, side: str): + return getattr(self, side)._maybe_cast_slice_bound(label, side) + + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + if not isinstance(dtype, IntervalDtype): + return False + common_subtype = find_common_type([self.dtype, dtype]) + return not is_object_dtype(common_subtype) + + # -------------------------------------------------------------------- + + @cache_readonly + def left(self) -> Index: + return Index(self._data.left, copy=False) + + @cache_readonly + def right(self) -> Index: + return Index(self._data.right, copy=False) + + @cache_readonly + def mid(self) -> Index: + return Index(self._data.mid, copy=False) + + @property + def length(self) -> Index: + return Index(self._data.length, copy=False) + + # -------------------------------------------------------------------- + # Set Operations + + def _intersection(self, other, sort): + """ + intersection specialized to the case with matching dtypes. + """ + # For IntervalIndex we also know other.closed == self.closed + if self.left.is_unique and self.right.is_unique: + taken = self._intersection_unique(other) + elif other.left.is_unique and other.right.is_unique and self.isna().sum() <= 1: + # Swap other/self if other is unique and self does not have + # multiple NaNs + taken = other._intersection_unique(self) + else: + # duplicates + taken = self._intersection_non_unique(other) + + if sort is None: + taken = taken.sort_values() + + return taken + + def _intersection_unique(self, other: IntervalIndex) -> IntervalIndex: + """ + Used when the IntervalIndex does not have any common endpoint, + no matter left or right. + Return the intersection with another IntervalIndex. + Parameters + ---------- + other : IntervalIndex + Returns + ------- + IntervalIndex + """ + # Note: this is much more performant than super()._intersection(other) + lindexer = self.left.get_indexer(other.left) + rindexer = self.right.get_indexer(other.right) + + match = (lindexer == rindexer) & (lindexer != -1) + indexer = lindexer.take(match.nonzero()[0]) + indexer = unique(indexer) + + return self.take(indexer) + + def _intersection_non_unique(self, other: IntervalIndex) -> IntervalIndex: + """ + Used when the IntervalIndex does have some common endpoints, + on either sides. + Return the intersection with another IntervalIndex. + + Parameters + ---------- + other : IntervalIndex + + Returns + ------- + IntervalIndex + """ + # Note: this is about 3.25x faster than super()._intersection(other) + # in IntervalIndexMethod.time_intersection_both_duplicate(1000) + mask = np.zeros(len(self), dtype=bool) + + if self.hasnans and other.hasnans: + first_nan_loc = np.arange(len(self))[self.isna()][0] + mask[first_nan_loc] = True + + other_tups = set(zip(other.left, other.right)) + for i, tup in enumerate(zip(self.left, self.right)): + if tup in other_tups: + mask[i] = True + + return self[mask] + + # -------------------------------------------------------------------- + + def _get_engine_target(self) -> np.ndarray: + # Note: we _could_ use libjoin functions by either casting to object + # dtype or constructing tuples (faster than constructing Intervals) + # but the libjoin fastpaths are no longer fast in these cases. + raise NotImplementedError( + "IntervalIndex does not use libjoin fastpaths or pass values to " + "IndexEngine objects" + ) + + def _from_join_target(self, result): + raise NotImplementedError("IntervalIndex does not use libjoin fastpaths") + + # TODO: arithmetic operations + + +def _is_valid_endpoint(endpoint) -> bool: + """ + Helper for interval_range to check if start/end are valid types. + """ + return any( + [ + is_number(endpoint), + isinstance(endpoint, Timestamp), + isinstance(endpoint, Timedelta), + endpoint is None, + ] + ) + + +def _is_type_compatible(a, b) -> bool: + """ + Helper for interval_range to check type compat of start/end/freq. + """ + is_ts_compat = lambda x: isinstance(x, (Timestamp, BaseOffset)) + is_td_compat = lambda x: isinstance(x, (Timedelta, BaseOffset)) + return ( + (is_number(a) and is_number(b)) + or (is_ts_compat(a) and is_ts_compat(b)) + or (is_td_compat(a) and is_td_compat(b)) + or com.any_none(a, b) + ) + + +def interval_range( + start=None, + end=None, + periods=None, + freq=None, + name: Hashable | None = None, + closed: IntervalClosedType = "right", +) -> IntervalIndex: + """ + Return a fixed frequency IntervalIndex. + + Parameters + ---------- + start : numeric or datetime-like, default None + Left bound for generating intervals. + end : numeric or datetime-like, default None + Right bound for generating intervals. + periods : int, default None + Number of periods to generate. + freq : numeric, str, Timedelta, datetime.timedelta, or DateOffset, default None + The length of each interval. Must be consistent with the type of start + and end, e.g. 2 for numeric, or '5H' for datetime-like. Default is 1 + for numeric and 'D' for datetime-like. + name : str, default None + Name of the resulting IntervalIndex. + closed : {'left', 'right', 'both', 'neither'}, default 'right' + Whether the intervals are closed on the left-side, right-side, both + or neither. + + Returns + ------- + IntervalIndex + + See Also + -------- + IntervalIndex : An Index of intervals that are all closed on the same side. + + Notes + ----- + Of the four parameters ``start``, ``end``, ``periods``, and ``freq``, + exactly three must be specified. If ``freq`` is omitted, the resulting + ``IntervalIndex`` will have ``periods`` linearly spaced elements between + ``start`` and ``end``, inclusively. + + To learn more about datetime-like frequency strings, please see `this link + `__. + + Examples + -------- + Numeric ``start`` and ``end`` is supported. + + >>> pd.interval_range(start=0, end=5) + IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]], + dtype='interval[int64, right]') + + Additionally, datetime-like input is also supported. + + >>> pd.interval_range(start=pd.Timestamp('2017-01-01'), + ... end=pd.Timestamp('2017-01-04')) + IntervalIndex([(2017-01-01 00:00:00, 2017-01-02 00:00:00], + (2017-01-02 00:00:00, 2017-01-03 00:00:00], + (2017-01-03 00:00:00, 2017-01-04 00:00:00]], + dtype='interval[datetime64[ns], right]') + + The ``freq`` parameter specifies the frequency between the left and right. + endpoints of the individual intervals within the ``IntervalIndex``. For + numeric ``start`` and ``end``, the frequency must also be numeric. + + >>> pd.interval_range(start=0, periods=4, freq=1.5) + IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]], + dtype='interval[float64, right]') + + Similarly, for datetime-like ``start`` and ``end``, the frequency must be + convertible to a DateOffset. + + >>> pd.interval_range(start=pd.Timestamp('2017-01-01'), + ... periods=3, freq='MS') + IntervalIndex([(2017-01-01 00:00:00, 2017-02-01 00:00:00], + (2017-02-01 00:00:00, 2017-03-01 00:00:00], + (2017-03-01 00:00:00, 2017-04-01 00:00:00]], + dtype='interval[datetime64[ns], right]') + + Specify ``start``, ``end``, and ``periods``; the frequency is generated + automatically (linearly spaced). + + >>> pd.interval_range(start=0, end=6, periods=4) + IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]], + dtype='interval[float64, right]') + + The ``closed`` parameter specifies which endpoints of the individual + intervals within the ``IntervalIndex`` are closed. + + >>> pd.interval_range(end=5, periods=4, closed='both') + IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]], + dtype='interval[int64, both]') + """ + start = maybe_box_datetimelike(start) + end = maybe_box_datetimelike(end) + endpoint = start if start is not None else end + + if freq is None and com.any_none(periods, start, end): + freq = 1 if is_number(endpoint) else "D" + + if com.count_not_none(start, end, periods, freq) != 3: + raise ValueError( + "Of the four parameters: start, end, periods, and " + "freq, exactly three must be specified" + ) + + if not _is_valid_endpoint(start): + raise ValueError(f"start must be numeric or datetime-like, got {start}") + if not _is_valid_endpoint(end): + raise ValueError(f"end must be numeric or datetime-like, got {end}") + + periods = validate_periods(periods) + + if freq is not None and not is_number(freq): + try: + freq = to_offset(freq) + except ValueError as err: + raise ValueError( + f"freq must be numeric or convertible to DateOffset, got {freq}" + ) from err + + # verify type compatibility + if not all( + [ + _is_type_compatible(start, end), + _is_type_compatible(start, freq), + _is_type_compatible(end, freq), + ] + ): + raise TypeError("start, end, freq need to be type compatible") + + # +1 to convert interval count to breaks count (n breaks = n-1 intervals) + if periods is not None: + periods += 1 + + breaks: np.ndarray | TimedeltaIndex | DatetimeIndex + + if is_number(endpoint): + if com.all_not_none(start, end, freq): + # 0.1 ensures we capture end + breaks = np.arange(start, end + (freq * 0.1), freq) + else: + # compute the period/start/end if unspecified (at most one) + if periods is None: + periods = int((end - start) // freq) + 1 + elif start is None: + start = end - (periods - 1) * freq + elif end is None: + end = start + (periods - 1) * freq + + breaks = np.linspace(start, end, periods) + if all(is_integer(x) for x in com.not_none(start, end, freq)): + # np.linspace always produces float output + + # error: Argument 1 to "maybe_downcast_numeric" has incompatible type + # "Union[ndarray[Any, Any], TimedeltaIndex, DatetimeIndex]"; + # expected "ndarray[Any, Any]" [ + breaks = maybe_downcast_numeric( + breaks, # type: ignore[arg-type] + np.dtype("int64"), + ) + else: + # delegate to the appropriate range function + if isinstance(endpoint, Timestamp): + breaks = date_range(start=start, end=end, periods=periods, freq=freq) + else: + breaks = timedelta_range(start=start, end=end, periods=periods, freq=freq) + + return IntervalIndex.from_breaks(breaks, name=name, closed=closed) diff --git a/shared/package-files/ef/efd953c2ccc02e64df0410bb4af721d09e236120c55390e672851b21863d193c/graph_manipulation.py b/shared/package-files/ef/efd953c2ccc02e64df0410bb4af721d09e236120c55390e672851b21863d193c/graph_manipulation.py new file mode 100644 index 0000000000000000000000000000000000000000..f559aa0bfcb3d96733f479d864aaab40923c473c --- /dev/null +++ b/shared/package-files/ef/efd953c2ccc02e64df0410bb4af721d09e236120c55390e672851b21863d193c/graph_manipulation.py @@ -0,0 +1,113 @@ +# mypy: allow-untyped-defs +from typing import Any, NamedTuple, Optional + +import torch +from torch.fx._compatibility import compatibility +from torch.fx.graph import Graph +from torch.fx.graph_module import GraphModule +from torch.fx.node import map_arg, Node, Target +from torch.fx.passes.shape_prop import ShapeProp + + +__all__ = [ + "replace_target_nodes_with", + "size_bytes", + "get_size_of_all_nodes", + "get_tensor_meta", + "get_size_of_node", +] + + +@compatibility(is_backward_compatible=False) +def replace_target_nodes_with( + fx_module: GraphModule, + old_op: str, + old_target: Target, + new_op: str, + new_target: Target, +): + """Modifies all nodes in fx_module.graph.nodes which match the specified op code and target, + and updates them to match the new op code and target""" + new_graph = Graph() + val_map: dict[Node, Node] = {} + for node in fx_module.graph.nodes: + if node.op == old_op and node.target == old_target: + args = map_arg(node.args, lambda n: val_map[n]) + kwargs = map_arg(node.kwargs, lambda n: val_map[n]) + assert isinstance(args, tuple) + assert isinstance(kwargs, dict) + val_map[node] = new_graph.create_node( + new_op, new_target, args, kwargs, node.name + ) + else: + val_map[node] = new_graph.node_copy(node, lambda n: val_map[n]) + fx_module.graph = new_graph + + +@compatibility(is_backward_compatible=False) +class size_bytes(NamedTuple): + output_size: int + total_size: int + + +@compatibility(is_backward_compatible=False) +def get_size_of_all_nodes( + fx_module: GraphModule, args: Optional[list[torch.Tensor]] = None +) -> None: + """Given a fx graph module, update each node with its total size (weights + bias + output) + and its output_size(output). For a non-module node, the total size is the output size. + return total size""" + if args is not None: + # Mark shape and dtype for each node (node.shape and node.dtype) + ShapeProp(fx_module).propagate(*args) + # Calculate the total size of the whole fx graph + for node in fx_module.graph.nodes: + if node.op == "output": + break + node.size_bytes = get_size_of_node(fx_module, node) + return + + +@compatibility(is_backward_compatible=False) +def get_tensor_meta(node: Node) -> Any: + tensor_meta = node.meta.get("tensor_meta") + + if not tensor_meta: + raise RuntimeError( + f"Node {node} has no tensor metadata associated with it! " + f"Check that shape propagation has run." + ) + + return tensor_meta + + +@compatibility(is_backward_compatible=False) +def get_size_of_node(fx_module: GraphModule, node: Node) -> size_bytes: + """Given a node with node.dtype and node.shape, return its total size and its output size. + total_size = weights + bias + output_size + """ + # Total num of elements + total_num_of_elems = 0 + # For a module, conside all parameters + if node.op == "call_module": + submodule_dict = dict(fx_module.named_modules()) + submodule = submodule_dict[node.target] + parameters = submodule.named_parameters() + # Parameters are named tuples + for _name, p in parameters: + total_num_of_elems += p.numel() + # Don't forget the output size + # node.shape is the shape of this node's output + tensor_meta = get_tensor_meta(node) + output_elem = tensor_meta.shape.numel() + total_num_of_elems += output_elem + # Assume for now if it's quantized then it's qint8 or quint8 + if tensor_meta.is_quantized: + size_per_elem_bytes = torch._empty_affine_quantized( + [], dtype=tensor_meta.dtype + ).element_size() + else: + size_per_elem_bytes = torch.tensor([], dtype=tensor_meta.dtype).element_size() + total_size = size_per_elem_bytes * total_num_of_elems + output_size = size_per_elem_bytes * output_elem + return size_bytes(output_size, total_size) diff --git a/shared/package-files/ef/efdd051424dd640fb3eaa2ae109339ff01b6e12a934d5b728fb3ca9cb05eeff4/spaced.h b/shared/package-files/ef/efdd051424dd640fb3eaa2ae109339ff01b6e12a934d5b728fb3ca9cb05eeff4/spaced.h new file mode 100644 index 0000000000000000000000000000000000000000..8265e1d22ae0e78d7343b2fce6a0de4bc669ccc8 --- /dev/null +++ b/shared/package-files/ef/efdd051424dd640fb3eaa2ae109339ff01b6e12a934d5b728fb3ca9cb05eeff4/spaced.h @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/util/bit_run_reader.h" + +namespace arrow { +namespace util { +namespace internal { + +/// \brief Compress the buffer to spaced, excluding the null entries. +/// +/// \param[in] src the source buffer +/// \param[in] num_values the size of source buffer +/// \param[in] valid_bits bitmap data indicating position of valid slots +/// \param[in] valid_bits_offset offset into valid_bits +/// \param[out] output the output buffer spaced +/// \return The size of spaced buffer. +template +inline int SpacedCompress(const T* src, int num_values, const uint8_t* valid_bits, + int64_t valid_bits_offset, T* output) { + int num_valid_values = 0; + + arrow::internal::SetBitRunReader reader(valid_bits, valid_bits_offset, num_values); + while (true) { + const auto run = reader.NextRun(); + if (run.length == 0) { + break; + } + std::memcpy(output + num_valid_values, src + run.position, run.length * sizeof(T)); + num_valid_values += static_cast(run.length); + } + + return num_valid_values; +} + +/// \brief Relocate values in buffer into positions of non-null values as indicated by +/// a validity bitmap. +/// +/// \param[in, out] buffer the in-place buffer +/// \param[in] num_values total size of buffer including null slots +/// \param[in] null_count number of null slots +/// \param[in] valid_bits bitmap data indicating position of valid slots +/// \param[in] valid_bits_offset offset into valid_bits +/// \return The number of values expanded, including nulls. +template +inline int SpacedExpand(T* buffer, int num_values, int null_count, + const uint8_t* valid_bits, int64_t valid_bits_offset) { + // Point to end as we add the spacing from the back. + int idx_decode = num_values - null_count; + + // Depending on the number of nulls, some of the value slots in buffer may + // be uninitialized, and this will cause valgrind warnings / potentially UB + std::memset(static_cast(buffer + idx_decode), 0, null_count * sizeof(T)); + if (idx_decode == 0) { + // All nulls, nothing more to do + return num_values; + } + + arrow::internal::ReverseSetBitRunReader reader(valid_bits, valid_bits_offset, + num_values); + while (true) { + const auto run = reader.NextRun(); + if (run.length == 0) { + break; + } + idx_decode -= static_cast(run.length); + assert(idx_decode >= 0); + std::memmove(buffer + run.position, buffer + idx_decode, run.length * sizeof(T)); + } + + // Otherwise caller gave an incorrect null_count + assert(idx_decode == 0); + return num_values; +} + +} // namespace internal +} // namespace util +} // namespace arrow diff --git a/shared/package-files/ef/efe730fc7f7d838ca88ba7167e1f7bd16ca04f2b45721bf009c825a096b48d87/test_ellipse.cpython-311.pyc b/shared/package-files/ef/efe730fc7f7d838ca88ba7167e1f7bd16ca04f2b45721bf009c825a096b48d87/test_ellipse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a8ac1cc623160fd37b14dfd9321ccf5f529dd53 Binary files /dev/null and b/shared/package-files/ef/efe730fc7f7d838ca88ba7167e1f7bd16ca04f2b45721bf009c825a096b48d87/test_ellipse.cpython-311.pyc differ diff --git a/shared/package-files/ef/efef4f71a797b499c0a0f6eed191f9c343bba84bda76d19c665d5b782d24546e/__init__.cpython-311.pyc b/shared/package-files/ef/efef4f71a797b499c0a0f6eed191f9c343bba84bda76d19c665d5b782d24546e/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d7556f5dddf41106c5cd89ab93a7a509fc6eae3 Binary files /dev/null and b/shared/package-files/ef/efef4f71a797b499c0a0f6eed191f9c343bba84bda76d19c665d5b782d24546e/__init__.cpython-311.pyc differ diff --git a/shared/package-files/ef/eff28190331830e78fbad1c3fee4bc066bfb2f5ac31fd85fb25b6db2fd10f79a/_slow_conv2d_backward_ops.h b/shared/package-files/ef/eff28190331830e78fbad1c3fee4bc066bfb2f5ac31fd85fb25b6db2fd10f79a/_slow_conv2d_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e0491338c4952f10a68db7e8641378d3a3d11e53 --- /dev/null +++ b/shared/package-files/ef/eff28190331830e78fbad1c3fee4bc066bfb2f5ac31fd85fb25b6db2fd10f79a/_slow_conv2d_backward_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _slow_conv2d_backward_grad_input { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_slow_conv2d_backward"; + static constexpr const char* overload_name = "grad_input"; + static constexpr const char* schema_str = "_slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!))"; + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias); +}; + +struct TORCH_API _slow_conv2d_backward_output_mask { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, ::std::array); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_slow_conv2d_backward"; + static constexpr const char* overload_name = "output_mask"; + static constexpr const char* schema_str = "_slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)"; + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask); +}; + +struct TORCH_API _slow_conv2d_backward_output_mask_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, ::std::array, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_slow_conv2d_backward"; + static constexpr const char* overload_name = "output_mask_out"; + static constexpr const char* schema_str = "_slow_conv2d_backward.output_mask_out(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))"; + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/ef/eff3df4f1d65e13d690b8f427cada4dd3b88431dd1e7f319fda1bd0062113203/typing.py b/shared/package-files/ef/eff3df4f1d65e13d690b8f427cada4dd3b88431dd1e7f319fda1bd0062113203/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..c26d01f76ace55648e0385b6887feb9a9208b6bc --- /dev/null +++ b/shared/package-files/ef/eff3df4f1d65e13d690b8f427cada4dd3b88431dd1e7f319fda1bd0062113203/typing.py @@ -0,0 +1,3538 @@ +""" +The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs. + +Among other things, the module includes the following: +* Generic, Protocol, and internal machinery to support generic aliases. + All subscripted types like X[int], Union[int, str] are generic aliases. +* Various "special forms" that have unique meanings in type annotations: + NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others. +* Classes whose instances can be type arguments to generic classes and functions: + TypeVar, ParamSpec, TypeVarTuple. +* Public helper functions: get_type_hints, overload, cast, final, and others. +* Several protocols to support duck-typing: + SupportsFloat, SupportsIndex, SupportsAbs, and others. +* Special types: NewType, NamedTuple, TypedDict. +* Deprecated wrapper submodules for re and io related types. +* Deprecated aliases for builtin types and collections.abc ABCs. + +Any name not present in __all__ is an implementation detail +that may be changed without notice. Use at your own risk! +""" + +from abc import abstractmethod, ABCMeta +import collections +from collections import defaultdict +import collections.abc +import contextlib +import functools +import operator +import re as stdlib_re # Avoid confusion with the re we export. +import sys +import types +import warnings +from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias + + +try: + from _typing import _idfunc +except ImportError: + def _idfunc(_, x): + return x + +# Please keep __all__ alphabetized within each category. +__all__ = [ + # Super-special typing primitives. + 'Annotated', + 'Any', + 'Callable', + 'ClassVar', + 'Concatenate', + 'Final', + 'ForwardRef', + 'Generic', + 'Literal', + 'Optional', + 'ParamSpec', + 'Protocol', + 'Tuple', + 'Type', + 'TypeVar', + 'TypeVarTuple', + 'Union', + + # ABCs (from collections.abc). + 'AbstractSet', # collections.abc.Set. + 'ByteString', + 'Container', + 'ContextManager', + 'Hashable', + 'ItemsView', + 'Iterable', + 'Iterator', + 'KeysView', + 'Mapping', + 'MappingView', + 'MutableMapping', + 'MutableSequence', + 'MutableSet', + 'Sequence', + 'Sized', + 'ValuesView', + 'Awaitable', + 'AsyncIterator', + 'AsyncIterable', + 'Coroutine', + 'Collection', + 'AsyncGenerator', + 'AsyncContextManager', + + # Structural checks, a.k.a. protocols. + 'Reversible', + 'SupportsAbs', + 'SupportsBytes', + 'SupportsComplex', + 'SupportsFloat', + 'SupportsIndex', + 'SupportsInt', + 'SupportsRound', + + # Concrete collection types. + 'ChainMap', + 'Counter', + 'Deque', + 'Dict', + 'DefaultDict', + 'List', + 'OrderedDict', + 'Set', + 'FrozenSet', + 'NamedTuple', # Not really a type. + 'TypedDict', # Not really a type. + 'Generator', + + # Other concrete types. + 'BinaryIO', + 'IO', + 'Match', + 'Pattern', + 'TextIO', + + # One-off things. + 'AnyStr', + 'assert_type', + 'assert_never', + 'cast', + 'clear_overloads', + 'dataclass_transform', + 'final', + 'get_args', + 'get_origin', + 'get_overloads', + 'get_type_hints', + 'is_typeddict', + 'LiteralString', + 'Never', + 'NewType', + 'no_type_check', + 'no_type_check_decorator', + 'NoReturn', + 'NotRequired', + 'overload', + 'ParamSpecArgs', + 'ParamSpecKwargs', + 'Required', + 'reveal_type', + 'runtime_checkable', + 'Self', + 'Text', + 'TYPE_CHECKING', + 'TypeAlias', + 'TypeGuard', + 'Unpack', +] + +# The pseudo-submodules 're' and 'io' are part of the public +# namespace, but excluded from __all__ because they might stomp on +# legitimate imports of those modules. + + +def _type_convert(arg, module=None, *, allow_special_forms=False): + """For converting None to type(None), and strings to ForwardRef.""" + if arg is None: + return type(None) + if isinstance(arg, str): + return ForwardRef(arg, module=module, is_class=allow_special_forms) + return arg + + +def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False): + """Check that the argument is a type, and return it (internal helper). + + As a special case, accept None and return type(None) instead. Also wrap strings + into ForwardRef instances. Consider several corner cases, for example plain + special forms like Union are not valid, while Union[int, str] is OK, etc. + The msg argument is a human-readable error message, e.g.:: + + "Union[arg, ...]: arg should be a type." + + We append the repr() of the actual value (truncated to 100 chars). + """ + invalid_generic_forms = (Generic, Protocol) + if not allow_special_forms: + invalid_generic_forms += (ClassVar,) + if is_argument: + invalid_generic_forms += (Final,) + + arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms) + if (isinstance(arg, _GenericAlias) and + arg.__origin__ in invalid_generic_forms): + raise TypeError(f"{arg} is not valid as type argument") + if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias): + return arg + if allow_special_forms and arg in (ClassVar, Final): + return arg + if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol): + raise TypeError(f"Plain {arg} is not valid as type argument") + if type(arg) is tuple: + raise TypeError(f"{msg} Got {arg!r:.100}.") + return arg + + +def _is_param_expr(arg): + return arg is ... or isinstance(arg, + (tuple, list, ParamSpec, _ConcatenateGenericAlias)) + + +def _should_unflatten_callable_args(typ, args): + """Internal helper for munging collections.abc.Callable's __args__. + + The canonical representation for a Callable's __args__ flattens the + argument types, see https://github.com/python/cpython/issues/86361. + + For example:: + + >>> import collections.abc + >>> P = ParamSpec('P') + >>> collections.abc.Callable[[int, int], str].__args__ == (int, int, str) + True + >>> collections.abc.Callable[P, str].__args__ == (P, str) + True + + As a result, if we need to reconstruct the Callable from its __args__, + we need to unflatten it. + """ + return ( + typ.__origin__ is collections.abc.Callable + and not (len(args) == 2 and _is_param_expr(args[0])) + ) + + +def _type_repr(obj): + """Return the repr() of an object, special-casing types (internal helper). + + If obj is a type, we return a shorter version than the default + type.__repr__, based on the module and qualified name, which is + typically enough to uniquely identify a type. For everything + else, we fall back on repr(obj). + """ + if isinstance(obj, types.GenericAlias): + return repr(obj) + if isinstance(obj, type): + if obj.__module__ == 'builtins': + return obj.__qualname__ + return f'{obj.__module__}.{obj.__qualname__}' + if obj is ...: + return('...') + if isinstance(obj, types.FunctionType): + return obj.__name__ + return repr(obj) + + +def _collect_parameters(args): + """Collect all type variables and parameter specifications in args + in order of first appearance (lexicographic order). + + For example:: + + >>> P = ParamSpec('P') + >>> T = TypeVar('T') + >>> _collect_parameters((T, Callable[P, T])) + (~T, ~P) + """ + parameters = [] + for t in args: + if isinstance(t, type): + # We don't want __parameters__ descriptor of a bare Python class. + pass + elif isinstance(t, tuple): + # `t` might be a tuple, when `ParamSpec` is substituted with + # `[T, int]`, or `[int, *Ts]`, etc. + for x in t: + for collected in _collect_parameters([x]): + if collected not in parameters: + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: + parameters.append(t) + else: + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + return tuple(parameters) + + +def _check_generic(cls, parameters, elen): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + alen = len(parameters) + if alen != elen: + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};" + f" actual {alen}, expected {elen}") + +def _unpack_args(args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs is not None and not (subargs and subargs[-1] is ...): + newargs.extend(subargs) + else: + newargs.append(arg) + return newargs + +def _deduplicate(params, *, unhashable_fallback=False): + # Weed out strict duplicates, preserving the first of each occurrence. + try: + return dict.fromkeys(params) + except TypeError: + if not unhashable_fallback: + raise + # Happens for cases like `Annotated[dict, {'x': IntValidator()}]` + return _deduplicate_unhashable(params) + +def _deduplicate_unhashable(unhashable_params): + new_unhashable = [] + for t in unhashable_params: + if t not in new_unhashable: + new_unhashable.append(t) + return new_unhashable + +def _compare_args_orderless(first_args, second_args): + first_unhashable = _deduplicate_unhashable(first_args) + second_unhashable = _deduplicate_unhashable(second_args) + t = list(second_unhashable) + try: + for elem in first_unhashable: + t.remove(elem) + except ValueError: + return False + return not t + +def _remove_dups_flatten(parameters): + """Internal helper for Union creation and substitution. + + Flatten Unions among parameters, then remove duplicates. + """ + # Flatten out Union[Union[...], ...]. + params = [] + for p in parameters: + if isinstance(p, (_UnionGenericAlias, types.UnionType)): + params.extend(p.__args__) + else: + params.append(p) + + return tuple(_deduplicate(params, unhashable_fallback=True)) + + +def _flatten_literal_params(parameters): + """Internal helper for Literal creation: flatten Literals among parameters.""" + params = [] + for p in parameters: + if isinstance(p, _LiteralGenericAlias): + params.extend(p.__args__) + else: + params.append(p) + return tuple(params) + + +_cleanups = [] + + +def _tp_cache(func=None, /, *, typed=False): + """Internal wrapper caching __getitem__ of generic types. + + For non-hashable arguments, the original function is used as a fallback. + """ + def decorator(func): + cached = functools.lru_cache(typed=typed)(func) + _cleanups.append(cached.cache_clear) + + @functools.wraps(func) + def inner(*args, **kwds): + try: + return cached(*args, **kwds) + except TypeError: + pass # All real errors (not unhashable args) are raised below. + return func(*args, **kwds) + return inner + + if func is not None: + return decorator(func) + + return decorator + +def _eval_type(t, globalns, localns, recursive_guard=frozenset()): + """Evaluate all forward references in the given type t. + + For use of globalns and localns see the docstring for get_type_hints(). + recursive_guard is used to prevent infinite recursion with a recursive + ForwardRef. + """ + if isinstance(t, ForwardRef): + return t._evaluate(globalns, localns, recursive_guard) + if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)): + if isinstance(t, GenericAlias): + args = tuple( + ForwardRef(arg) if isinstance(arg, str) else arg + for arg in t.__args__ + ) + is_unpacked = t.__unpacked__ + if _should_unflatten_callable_args(t, args): + t = t.__origin__[(args[:-1], args[-1])] + else: + t = t.__origin__[args] + if is_unpacked: + t = Unpack[t] + ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__) + if ev_args == t.__args__: + return t + if isinstance(t, GenericAlias): + return GenericAlias(t.__origin__, ev_args) + if isinstance(t, types.UnionType): + return functools.reduce(operator.or_, ev_args) + else: + return t.copy_with(ev_args) + return t + + +class _Final: + """Mixin to prohibit subclassing.""" + + __slots__ = ('__weakref__',) + + def __init_subclass__(cls, /, *args, **kwds): + if '_root' not in kwds: + raise TypeError("Cannot subclass special typing classes") + +class _Immutable: + """Mixin to indicate that object should not be copied.""" + + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + +class _NotIterable: + """Mixin to prevent iteration, without being compatible with Iterable. + + That is, we could do:: + + def __iter__(self): raise TypeError() + + But this would make users of this mixin duck type-compatible with + collections.abc.Iterable - isinstance(foo, Iterable) would be True. + + Luckily, we can instead prevent iteration by setting __iter__ to None, which + is treated specially. + """ + + __slots__ = () + __iter__ = None + + +# Internal indicator of special typing constructs. +# See __doc__ instance attribute for specific docs. +class _SpecialForm(_Final, _NotIterable, _root=True): + __slots__ = ('_name', '__doc__', '_getitem') + + def __init__(self, getitem): + self._getitem = getitem + self._name = getitem.__name__ + self.__doc__ = getitem.__doc__ + + def __getattr__(self, item): + if item in {'__name__', '__qualname__'}: + return self._name + + raise AttributeError(item) + + def __mro_entries__(self, bases): + raise TypeError(f"Cannot subclass {self!r}") + + def __repr__(self): + return 'typing.' + self._name + + def __reduce__(self): + return self._name + + def __call__(self, *args, **kwds): + raise TypeError(f"Cannot instantiate {self!r}") + + def __or__(self, other): + return Union[self, other] + + def __ror__(self, other): + return Union[other, self] + + def __instancecheck__(self, obj): + raise TypeError(f"{self} cannot be used with isinstance()") + + def __subclasscheck__(self, cls): + raise TypeError(f"{self} cannot be used with issubclass()") + + @_tp_cache + def __getitem__(self, parameters): + return self._getitem(self, parameters) + + +class _LiteralSpecialForm(_SpecialForm, _root=True): + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + return self._getitem(self, *parameters) + + +class _AnyMeta(type): + def __instancecheck__(self, obj): + if self is Any: + raise TypeError("typing.Any cannot be used with isinstance()") + return super().__instancecheck__(obj) + + def __repr__(self): + if self is Any: + return "typing.Any" + return super().__repr__() # respect to subclasses + + +class Any(metaclass=_AnyMeta): + """Special type indicating an unconstrained type. + + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + checks. + """ + + def __new__(cls, *args, **kwargs): + if cls is Any: + raise TypeError("Any cannot be instantiated") + return super().__new__(cls) + + +@_SpecialForm +def NoReturn(self, parameters): + """Special type indicating functions that never return. + + Example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise Exception('no way') + + NoReturn can also be used as a bottom type, a type that + has no values. Starting in Python 3.11, the Never type should + be used for this concept instead. Type checkers should treat the two + equivalently. + """ + raise TypeError(f"{self} is not subscriptable") + +# This is semantically identical to NoReturn, but it is implemented +# separately so that type checkers can distinguish between the two +# if they want. +@_SpecialForm +def Never(self, parameters): + """The bottom type, a type that has no members. + + This can be used to define a function that should never be + called, or a function that never returns:: + + from typing import Never + + def never_call_me(arg: Never) -> None: + pass + + def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # OK, arg is of type Never + """ + raise TypeError(f"{self} is not subscriptable") + + +@_SpecialForm +def Self(self, parameters): + """Used to spell the type of "self" in classes. + + Example:: + + from typing import Self + + class Foo: + def return_self(self) -> Self: + ... + return self + + This is especially useful for: + - classmethods that are used as alternative constructors + - annotating an `__enter__` method which returns self + """ + raise TypeError(f"{self} is not subscriptable") + + +@_SpecialForm +def LiteralString(self, parameters): + """Represents an arbitrary literal string. + + Example:: + + from typing import LiteralString + + def run_query(sql: LiteralString) -> None: + ... + + def caller(arbitrary_string: str, literal_string: LiteralString) -> None: + run_query("SELECT * FROM students") # OK + run_query(literal_string) # OK + run_query("SELECT * FROM " + literal_string) # OK + run_query(arbitrary_string) # type checker error + run_query( # type checker error + f"SELECT * FROM students WHERE name = {arbitrary_string}" + ) + + Only string literals and other LiteralStrings are compatible + with LiteralString. This provides a tool to help prevent + security issues such as SQL injection. + """ + raise TypeError(f"{self} is not subscriptable") + + +@_SpecialForm +def ClassVar(self, parameters): + """Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. + + Usage:: + + class Starship: + stats: ClassVar[dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + """ + item = _type_check(parameters, f'{self} accepts only single type.') + return _GenericAlias(self, (item,)) + +@_SpecialForm +def Final(self, parameters): + """Special typing construct to indicate final names to type checkers. + + A final name cannot be re-assigned or overridden in a subclass. + + For example:: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + """ + item = _type_check(parameters, f'{self} accepts only single type.') + return _GenericAlias(self, (item,)) + +@_SpecialForm +def Union(self, parameters): + """Union type; Union[X, Y] means either X or Y. + + On Python 3.10 and higher, the | operator + can also be used to denote unions; + X | Y means the same thing to the type checker as Union[X, Y]. + + To define a union, use e.g. Union[int, str]. Details: + - The arguments must be types and there must be at least one. + - None as an argument is a special case and is replaced by + type(None). + - Unions of unions are flattened, e.g.:: + + assert Union[Union[int, str], float] == Union[int, str, float] + + - Unions of a single argument vanish, e.g.:: + + assert Union[int] == int # The constructor actually returns int + + - Redundant arguments are skipped, e.g.:: + + assert Union[int, str, int] == Union[int, str] + + - When comparing unions, the argument order is ignored, e.g.:: + + assert Union[int, str] == Union[str, int] + + - You cannot subclass or instantiate a union. + - You can use Optional[X] as a shorthand for Union[X, None]. + """ + if parameters == (): + raise TypeError("Cannot take a Union of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + msg = "Union[arg, ...]: each arg must be a type." + parameters = tuple(_type_check(p, msg) for p in parameters) + parameters = _remove_dups_flatten(parameters) + if len(parameters) == 1: + return parameters[0] + if len(parameters) == 2 and type(None) in parameters: + return _UnionGenericAlias(self, parameters, name="Optional") + return _UnionGenericAlias(self, parameters) + +@_SpecialForm +def Optional(self, parameters): + """Optional[X] is equivalent to Union[X, None].""" + arg = _type_check(parameters, f"{self} requires a single type.") + return Union[arg, type(None)] + +@_LiteralSpecialForm +@_tp_cache(typed=True) +def Literal(self, *parameters): + """Special typing form to define literal types (a.k.a. value types). + + This form can be used to indicate to type checkers that the corresponding + variable or function parameter has a value equivalent to the provided + literal (or one of several literals):: + + def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + + MODE = Literal['r', 'rb', 'w', 'wb'] + def open_helper(file: str, mode: MODE) -> str: + ... + + open_helper('/some/path', 'r') # Passes type check + open_helper('/other/path', 'typo') # Error in type checker + + Literal[...] cannot be subclassed. At runtime, an arbitrary value + is allowed as type argument to Literal[...], but type checkers may + impose restrictions. + """ + # There is no '_type_check' call because arguments to Literal[...] are + # values, not types. + parameters = _flatten_literal_params(parameters) + + try: + parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters)))) + except TypeError: # unhashable parameters + pass + + return _LiteralGenericAlias(self, parameters) + + +@_SpecialForm +def TypeAlias(self, parameters): + """Special form for marking type aliases. + + Use TypeAlias to indicate that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError(f"{self} is not subscriptable") + + +@_SpecialForm +def Concatenate(self, parameters): + """Special form for annotating higher-order functions. + + ``Concatenate`` can be used in conjunction with ``ParamSpec`` and + ``Callable`` to represent a higher-order function which adds, removes or + transforms the parameters of a callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = (*(_type_check(p, msg) for p in parameters[:-1]), parameters[-1]) + return _ConcatenateGenericAlias(self, parameters, + _paramspec_tvars=True) + + +@_SpecialForm +def TypeGuard(self, parameters): + """Special typing construct for marking user-defined type guard functions. + + ``TypeGuard`` can be used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = _type_check(parameters, f'{self} accepts only single type.') + return _GenericAlias(self, (item,)) + + +class ForwardRef(_Final, _root=True): + """Internal wrapper to hold a forward reference.""" + + __slots__ = ('__forward_arg__', '__forward_code__', + '__forward_evaluated__', '__forward_value__', + '__forward_is_argument__', '__forward_is_class__', + '__forward_module__') + + def __init__(self, arg, is_argument=True, module=None, *, is_class=False): + if not isinstance(arg, str): + raise TypeError(f"Forward reference must be a string -- got {arg!r}") + + # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`. + # Unfortunately, this isn't a valid expression on its own, so we + # do the unpacking manually. + if arg.startswith('*'): + arg_to_compile = f'({arg},)[0]' # E.g. (*Ts,)[0] or (*tuple[int, int],)[0] + else: + arg_to_compile = arg + try: + code = compile(arg_to_compile, '', 'eval') + except SyntaxError: + raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") + + self.__forward_arg__ = arg + self.__forward_code__ = code + self.__forward_evaluated__ = False + self.__forward_value__ = None + self.__forward_is_argument__ = is_argument + self.__forward_is_class__ = is_class + self.__forward_module__ = module + + def _evaluate(self, globalns, localns, recursive_guard): + if self.__forward_arg__ in recursive_guard: + return self + if not self.__forward_evaluated__ or localns is not globalns: + if globalns is None and localns is None: + globalns = localns = {} + elif globalns is None: + globalns = localns + elif localns is None: + localns = globalns + if self.__forward_module__ is not None: + globalns = getattr( + sys.modules.get(self.__forward_module__, None), '__dict__', globalns + ) + type_ = _type_check( + eval(self.__forward_code__, globalns, localns), + "Forward references must evaluate to types.", + is_argument=self.__forward_is_argument__, + allow_special_forms=self.__forward_is_class__, + ) + self.__forward_value__ = _eval_type( + type_, globalns, localns, recursive_guard | {self.__forward_arg__} + ) + self.__forward_evaluated__ = True + return self.__forward_value__ + + def __eq__(self, other): + if not isinstance(other, ForwardRef): + return NotImplemented + if self.__forward_evaluated__ and other.__forward_evaluated__: + return (self.__forward_arg__ == other.__forward_arg__ and + self.__forward_value__ == other.__forward_value__) + return (self.__forward_arg__ == other.__forward_arg__ and + self.__forward_module__ == other.__forward_module__) + + def __hash__(self): + return hash((self.__forward_arg__, self.__forward_module__)) + + def __or__(self, other): + return Union[self, other] + + def __ror__(self, other): + return Union[other, self] + + def __repr__(self): + if self.__forward_module__ is None: + module_repr = '' + else: + module_repr = f', module={self.__forward_module__!r}' + return f'ForwardRef({self.__forward_arg__!r}{module_repr})' + + +def _is_unpacked_typevartuple(x: Any) -> bool: + return ((not isinstance(x, type)) and + getattr(x, '__typing_is_unpacked_typevartuple__', False)) + + +def _is_typevar_like(x: Any) -> bool: + return isinstance(x, (TypeVar, ParamSpec)) or _is_unpacked_typevartuple(x) + + +class _PickleUsingNameMixin: + """Mixin enabling pickling based on self.__name__.""" + + def __reduce__(self): + return self.__name__ + + +class _BoundVarianceMixin: + """Mixin giving __init__ bound and variance arguments. + + This is used by TypeVar and ParamSpec, which both employ the notions of + a type 'bound' (restricting type arguments to be a subtype of some + specified type) and type 'variance' (determining subtype relations between + generic types). + """ + def __init__(self, bound, covariant, contravariant): + """Used to setup TypeVars and ParamSpec's bound, covariant and + contravariant attributes. + """ + if covariant and contravariant: + raise ValueError("Bivariant types are not supported.") + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + if bound: + self.__bound__ = _type_check(bound, "Bound must be a type.") + else: + self.__bound__ = None + + def __or__(self, right): + return Union[self, right] + + def __ror__(self, left): + return Union[left, self] + + def __repr__(self): + if self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + +class TypeVar(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin, + _root=True): + """Type variable. + + Usage:: + + T = TypeVar('T') # Can be anything + A = TypeVar('A', str, bytes) # Must be str or bytes + + Type variables exist primarily for the benefit of static type + checkers. They serve as the parameters for generic types as well + as for generic function definitions. See class Generic for more + information on generic types. Generic functions work as follows: + + def repeat(x: T, n: int) -> List[T]: + '''Return a list containing n references to x.''' + return [x]*n + + def longest(x: A, y: A) -> A: + '''Return the longest of two strings.''' + return x if len(x) >= len(y) else y + + The latter example's signature is essentially the overloading + of (str, str) -> str and (bytes, bytes) -> bytes. Also note + that if the arguments are instances of some subclass of str, + the return type is still plain str. + + At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. + + Type variables defined with covariant=True or contravariant=True + can be used to declare covariant or contravariant generic types. + See PEP 484 for more details. By default generic types are invariant + in all type variables. + + Type variables can be introspected. e.g.: + + T.__name__ == 'T' + T.__constraints__ == () + T.__covariant__ == False + T.__contravariant__ = False + A.__constraints__ == (str, bytes) + + Note that only type variables defined in global scope can be pickled. + """ + + def __init__(self, name, *constraints, bound=None, + covariant=False, contravariant=False): + self.__name__ = name + super().__init__(bound, covariant, contravariant) + if constraints and bound is not None: + raise TypeError("Constraints cannot be combined with bound=...") + if constraints and len(constraints) == 1: + raise TypeError("A single constraint is not allowed") + msg = "TypeVar(name, constraint, ...): constraints must be types." + self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) + def_mod = _caller() + if def_mod != 'typing': + self.__module__ = def_mod + + def __typing_subst__(self, arg): + msg = "Parameters to generic types must be types." + arg = _type_check(arg, msg, is_argument=True) + if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or + (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))): + raise TypeError(f"{arg} is not valid as type argument") + return arg + + +class TypeVarTuple(_Final, _Immutable, _PickleUsingNameMixin, _root=True): + """Type variable tuple. + + Usage: + + Ts = TypeVarTuple('Ts') # Can be given any name + + Just as a TypeVar (type variable) is a placeholder for a single type, + a TypeVarTuple is a placeholder for an *arbitrary* number of types. For + example, if we define a generic class using a TypeVarTuple: + + class C(Generic[*Ts]): ... + + Then we can parameterize that class with an arbitrary number of type + arguments: + + C[int] # Fine + C[int, str] # Also fine + C[()] # Even this is fine + + For more details, see PEP 646. + + Note that only TypeVarTuples defined in global scope can be pickled. + """ + + def __init__(self, name): + self.__name__ = name + + # Used for pickling. + def_mod = _caller() + if def_mod != 'typing': + self.__module__ = def_mod + + def __iter__(self): + yield Unpack[self] + + def __repr__(self): + return self.__name__ + + def __typing_subst__(self, arg): + raise TypeError("Substitution of bare TypeVarTuple is not supported") + + def __typing_prepare_subst__(self, alias, args): + params = alias.__parameters__ + typevartuple_index = params.index(self) + for param in params[typevartuple_index + 1:]: + if isinstance(param, TypeVarTuple): + raise TypeError(f"More than one TypeVarTuple parameter in {alias}") + + alen = len(args) + plen = len(params) + left = typevartuple_index + right = plen - typevartuple_index - 1 + var_tuple_index = None + fillarg = None + for k, arg in enumerate(args): + if not isinstance(arg, type): + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs and len(subargs) == 2 and subargs[-1] is ...: + if var_tuple_index is not None: + raise TypeError("More than one unpacked arbitrary-length tuple argument") + var_tuple_index = k + fillarg = subargs[0] + if var_tuple_index is not None: + left = min(left, var_tuple_index) + right = min(right, alen - var_tuple_index - 1) + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen-1}") + + return ( + *args[:left], + *([fillarg]*(typevartuple_index - left)), + tuple(args[left: alen - right]), + *([fillarg]*(plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) + + +class ParamSpecArgs(_Final, _Immutable, _root=True): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.args" + + def __eq__(self, other): + if not isinstance(other, ParamSpecArgs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +class ParamSpecKwargs(_Final, _Immutable, _root=True): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.kwargs" + + def __eq__(self, other): + if not isinstance(other, ParamSpecKwargs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +class ParamSpec(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin, + _root=True): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or as the first argument to ``Callable``, or as parameters for user-defined + Generics. See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'P' + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False): + self.__name__ = name + super().__init__(bound, covariant, contravariant) + def_mod = _caller() + if def_mod != 'typing': + self.__module__ = def_mod + + def __typing_subst__(self, arg): + if isinstance(arg, (list, tuple)): + arg = tuple(_type_check(a, "Expected a type.") for a in arg) + elif not _is_param_expr(arg): + raise TypeError(f"Expected a list of types, an ellipsis, " + f"ParamSpec, or Concatenate. Got {arg}") + return arg + + def __typing_prepare_subst__(self, alias, args): + params = alias.__parameters__ + i = params.index(self) + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. + if len(params) == 1 and not _is_param_expr(args[0]): + assert i == 0 + args = (args,) + # Convert lists to tuples to help other libraries cache the results. + elif isinstance(args[i], list): + args = (*args[:i], tuple(args[i]), *args[i+1:]) + return args + +def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') + +class _BaseGenericAlias(_Final, _root=True): + """The central part of the internal API. + + This represents a generic version of type 'origin' with type arguments 'params'. + There are two kind of these aliases: user defined and special. The special ones + are wrappers around builtin collections and ABCs in collections.abc. These must + have 'name' always set. If 'inst' is False, then the alias can't be instantiated; + this is used by e.g. typing.List and typing.Dict. + """ + + def __init__(self, origin, *, inst=True, name=None): + self._inst = inst + self._name = name + self.__origin__ = origin + self.__slots__ = None # This is not documented. + + def __call__(self, *args, **kwargs): + if not self._inst: + raise TypeError(f"Type {self._name} cannot be instantiated; " + f"use {self.__origin__.__name__}() instead") + result = self.__origin__(*args, **kwargs) + try: + result.__orig_class__ = self + # Some objects raise TypeError (or something even more exotic) + # if you try to set attributes on them; we guard against that here + except Exception: + pass + return result + + def __mro_entries__(self, bases): + res = [] + if self.__origin__ not in bases: + res.append(self.__origin__) + i = bases.index(self) + for b in bases[i+1:]: + if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic): + break + else: + res.append(Generic) + return tuple(res) + + def __getattr__(self, attr): + if attr in {'__name__', '__qualname__'}: + return self._name or self.__origin__.__name__ + + # We are careful for copy and pickle. + # Also for simplicity we don't relay any dunder names + if '__origin__' in self.__dict__ and not _is_dunder(attr): + return getattr(self.__origin__, attr) + raise AttributeError(attr) + + def __setattr__(self, attr, val): + if _is_dunder(attr) or attr in {'_name', '_inst', '_nparams', + '_paramspec_tvars'}: + super().__setattr__(attr, val) + else: + setattr(self.__origin__, attr, val) + + def __instancecheck__(self, obj): + return self.__subclasscheck__(type(obj)) + + def __subclasscheck__(self, cls): + raise TypeError("Subscripted generics cannot be used with" + " class and instance checks") + + def __dir__(self): + return list(set(super().__dir__() + + [attr for attr in dir(self.__origin__) if not _is_dunder(attr)])) + + +# Special typing constructs Union, Optional, Generic, Callable and Tuple +# use three special attributes for internal bookkeeping of generic types: +# * __parameters__ is a tuple of unique free type parameters of a generic +# type, for example, Dict[T, T].__parameters__ == (T,); +# * __origin__ keeps a reference to a type that was subscripted, +# e.g., Union[T, int].__origin__ == Union, or the non-generic version of +# the type. +# * __args__ is a tuple of all arguments used in subscripting, +# e.g., Dict[T, int].__args__ == (T, int). + + +class _GenericAlias(_BaseGenericAlias, _root=True): + # The type of parameterized generics. + # + # That is, for example, `type(List[int])` is `_GenericAlias`. + # + # Objects which are instances of this class include: + # * Parameterized container types, e.g. `Tuple[int]`, `List[int]`. + # * Note that native container types, e.g. `tuple`, `list`, use + # `types.GenericAlias` instead. + # * Parameterized classes: + # T = TypeVar('T') + # class C(Generic[T]): pass + # # C[int] is a _GenericAlias + # * `Callable` aliases, generic `Callable` aliases, and + # parameterized `Callable` aliases: + # T = TypeVar('T') + # # _CallableGenericAlias inherits from _GenericAlias. + # A = Callable[[], None] # _CallableGenericAlias + # B = Callable[[T], None] # _CallableGenericAlias + # C = B[int] # _CallableGenericAlias + # * Parameterized `Final`, `ClassVar` and `TypeGuard`: + # # All _GenericAlias + # Final[int] + # ClassVar[float] + # TypeVar[bool] + + def __init__(self, origin, args, *, inst=True, name=None, + _paramspec_tvars=False): + super().__init__(origin, inst=inst, name=name) + if not isinstance(args, tuple): + args = (args,) + self.__args__ = tuple(... if a is _TypingEllipsis else + a for a in args) + self.__parameters__ = _collect_parameters(args) + self._paramspec_tvars = _paramspec_tvars + if not name: + self.__module__ = origin.__module__ + + def __eq__(self, other): + if not isinstance(other, _GenericAlias): + return NotImplemented + return (self.__origin__ == other.__origin__ + and self.__args__ == other.__args__) + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + def __or__(self, right): + return Union[self, right] + + def __ror__(self, left): + return Union[left, self] + + @_tp_cache + def __getitem__(self, args): + # Parameterizes an already-parameterized object. + # + # For example, we arrive here doing something like: + # T1 = TypeVar('T1') + # T2 = TypeVar('T2') + # T3 = TypeVar('T3') + # class A(Generic[T1]): pass + # B = A[T2] # B is a _GenericAlias + # C = B[T3] # Invokes _GenericAlias.__getitem__ + # + # We also arrive here when parameterizing a generic `Callable` alias: + # T = TypeVar('T') + # C = Callable[[T], None] + # C[int] # Invokes _GenericAlias.__getitem__ + + if self.__origin__ in (Generic, Protocol): + # Can't subscript Generic[...] or Protocol[...]. + raise TypeError(f"Cannot subscript already-subscripted {self}") + if not self.__parameters__: + raise TypeError(f"{self} is not a generic class") + + # Preprocess `args`. + if not isinstance(args, tuple): + args = (args,) + args = tuple(_type_convert(p) for p in args) + args = _unpack_args(args) + new_args = self._determine_new_args(args) + r = self.copy_with(new_args) + return r + + def _determine_new_args(self, args): + # Determines new __args__ for __getitem__. + # + # For example, suppose we had: + # T1 = TypeVar('T1') + # T2 = TypeVar('T2') + # class A(Generic[T1, T2]): pass + # T3 = TypeVar('T3') + # B = A[int, T3] + # C = B[str] + # `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`. + # Unfortunately, this is harder than it looks, because if `T3` is + # anything more exotic than a plain `TypeVar`, we need to consider + # edge cases. + + params = self.__parameters__ + # In the example above, this would be {T3: str} + for param in params: + prepare = getattr(param, '__typing_prepare_subst__', None) + if prepare is not None: + args = prepare(self, args) + alen = len(args) + plen = len(params) + if alen != plen: + raise TypeError(f"Too {'many' if alen > plen else 'few'} arguments for {self};" + f" actual {alen}, expected {plen}") + new_arg_by_param = dict(zip(params, args)) + return tuple(self._make_substitution(self.__args__, new_arg_by_param)) + + def _make_substitution(self, args, new_arg_by_param): + """Create a list of new type arguments.""" + new_args = [] + for old_arg in args: + if isinstance(old_arg, type): + new_args.append(old_arg) + continue + + substfunc = getattr(old_arg, '__typing_subst__', None) + if substfunc: + new_arg = substfunc(new_arg_by_param[old_arg]) + else: + subparams = getattr(old_arg, '__parameters__', ()) + if not subparams: + new_arg = old_arg + else: + subargs = [] + for x in subparams: + if isinstance(x, TypeVarTuple): + subargs.extend(new_arg_by_param[x]) + else: + subargs.append(new_arg_by_param[x]) + new_arg = old_arg[tuple(subargs)] + + if self.__origin__ == collections.abc.Callable and isinstance(new_arg, tuple): + # Consider the following `Callable`. + # C = Callable[[int], str] + # Here, `C.__args__` should be (int, str) - NOT ([int], str). + # That means that if we had something like... + # P = ParamSpec('P') + # T = TypeVar('T') + # C = Callable[P, T] + # D = C[[int, str], float] + # ...we need to be careful; `new_args` should end up as + # `(int, str, float)` rather than `([int, str], float)`. + new_args.extend(new_arg) + elif _is_unpacked_typevartuple(old_arg): + # Consider the following `_GenericAlias`, `B`: + # class A(Generic[*Ts]): ... + # B = A[T, *Ts] + # If we then do: + # B[float, int, str] + # The `new_arg` corresponding to `T` will be `float`, and the + # `new_arg` corresponding to `*Ts` will be `(int, str)`. We + # should join all these types together in a flat list + # `(float, int, str)` - so again, we should `extend`. + new_args.extend(new_arg) + elif isinstance(old_arg, tuple): + # Corner case: + # P = ParamSpec('P') + # T = TypeVar('T') + # class Base(Generic[P]): ... + # Can be substituted like this: + # X = Base[[int, T]] + # In this case, `old_arg` will be a tuple: + new_args.append( + tuple(self._make_substitution(old_arg, new_arg_by_param)), + ) + else: + new_args.append(new_arg) + return new_args + + def copy_with(self, args): + return self.__class__(self.__origin__, args, name=self._name, inst=self._inst, + _paramspec_tvars=self._paramspec_tvars) + + def __repr__(self): + if self._name: + name = 'typing.' + self._name + else: + name = _type_repr(self.__origin__) + if self.__args__: + args = ", ".join([_type_repr(a) for a in self.__args__]) + else: + # To ensure the repr is eval-able. + args = "()" + return f'{name}[{args}]' + + def __reduce__(self): + if self._name: + origin = globals()[self._name] + else: + origin = self.__origin__ + args = tuple(self.__args__) + if len(args) == 1 and not isinstance(args[0], tuple): + args, = args + return operator.getitem, (origin, args) + + def __mro_entries__(self, bases): + if isinstance(self.__origin__, _SpecialForm): + raise TypeError(f"Cannot subclass {self!r}") + + if self._name: # generic version of an ABC or built-in class + return super().__mro_entries__(bases) + if self.__origin__ is Generic: + if Protocol in bases: + return () + i = bases.index(self) + for b in bases[i+1:]: + if isinstance(b, _BaseGenericAlias) and b is not self: + return () + return (self.__origin__,) + + def __iter__(self): + yield Unpack[self] + + +# _nparams is the number of accepted parameters, e.g. 0 for Hashable, +# 1 for List and 2 for Dict. It may be -1 if variable number of +# parameters are accepted (needs custom __getitem__). + +class _SpecialGenericAlias(_NotIterable, _BaseGenericAlias, _root=True): + def __init__(self, origin, nparams, *, inst=True, name=None): + if name is None: + name = origin.__name__ + super().__init__(origin, inst=inst, name=name) + self._nparams = nparams + if origin.__module__ == 'builtins': + self.__doc__ = f'A generic version of {origin.__qualname__}.' + else: + self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.' + + @_tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(_type_check(p, msg) for p in params) + _check_generic(self, params, self._nparams) + return self.copy_with(params) + + def copy_with(self, params): + return _GenericAlias(self.__origin__, params, + name=self._name, inst=self._inst) + + def __repr__(self): + return 'typing.' + self._name + + def __subclasscheck__(self, cls): + if isinstance(cls, _SpecialGenericAlias): + return issubclass(cls.__origin__, self.__origin__) + if not isinstance(cls, _GenericAlias): + return issubclass(cls, self.__origin__) + return super().__subclasscheck__(cls) + + def __reduce__(self): + return self._name + + def __or__(self, right): + return Union[self, right] + + def __ror__(self, left): + return Union[left, self] + +class _CallableGenericAlias(_NotIterable, _GenericAlias, _root=True): + def __repr__(self): + assert self._name == 'Callable' + args = self.__args__ + if len(args) == 2 and _is_param_expr(args[0]): + return super().__repr__() + return (f'typing.Callable' + f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], ' + f'{_type_repr(args[-1])}]') + + def __reduce__(self): + args = self.__args__ + if not (len(args) == 2 and _is_param_expr(args[0])): + args = list(args[:-1]), args[-1] + return operator.getitem, (Callable, args) + + +class _CallableType(_SpecialGenericAlias, _root=True): + def copy_with(self, params): + return _CallableGenericAlias(self.__origin__, params, + name=self._name, inst=self._inst, + _paramspec_tvars=True) + + def __getitem__(self, params): + if not isinstance(params, tuple) or len(params) != 2: + raise TypeError("Callable must be used as " + "Callable[[arg, ...], result].") + args, result = params + # This relaxes what args can be on purpose to allow things like + # PEP 612 ParamSpec. Responsibility for whether a user is using + # Callable[...] properly is deferred to static type checkers. + if isinstance(args, list): + params = (tuple(args), result) + else: + params = (args, result) + return self.__getitem_inner__(params) + + @_tp_cache + def __getitem_inner__(self, params): + args, result = params + msg = "Callable[args, result]: result must be a type." + result = _type_check(result, msg) + if args is Ellipsis: + return self.copy_with((_TypingEllipsis, result)) + if not isinstance(args, tuple): + args = (args,) + args = tuple(_type_convert(arg) for arg in args) + params = args + (result,) + return self.copy_with(params) + + +class _TupleType(_SpecialGenericAlias, _root=True): + @_tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + if len(params) >= 2 and params[-1] is ...: + msg = "Tuple[t, ...]: t must be a type." + params = tuple(_type_check(p, msg) for p in params[:-1]) + return self.copy_with((*params, _TypingEllipsis)) + msg = "Tuple[t0, t1, ...]: each t must be a type." + params = tuple(_type_check(p, msg) for p in params) + return self.copy_with(params) + + +class _UnionGenericAlias(_NotIterable, _GenericAlias, _root=True): + def copy_with(self, params): + return Union[params] + + def __eq__(self, other): + if not isinstance(other, (_UnionGenericAlias, types.UnionType)): + return NotImplemented + try: # fast path + return set(self.__args__) == set(other.__args__) + except TypeError: # not hashable, slow path + return _compare_args_orderless(self.__args__, other.__args__) + + def __hash__(self): + return hash(frozenset(self.__args__)) + + def __repr__(self): + args = self.__args__ + if len(args) == 2: + if args[0] is type(None): + return f'typing.Optional[{_type_repr(args[1])}]' + elif args[1] is type(None): + return f'typing.Optional[{_type_repr(args[0])}]' + return super().__repr__() + + def __instancecheck__(self, obj): + return self.__subclasscheck__(type(obj)) + + def __subclasscheck__(self, cls): + for arg in self.__args__: + if issubclass(cls, arg): + return True + + def __reduce__(self): + func, (origin, args) = super().__reduce__() + return func, (Union, args) + + +def _value_and_type_iter(parameters): + return ((p, type(p)) for p in parameters) + + +class _LiteralGenericAlias(_GenericAlias, _root=True): + def __eq__(self, other): + if not isinstance(other, _LiteralGenericAlias): + return NotImplemented + + return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__)) + + def __hash__(self): + return hash(frozenset(_value_and_type_iter(self.__args__))) + + +class _ConcatenateGenericAlias(_GenericAlias, _root=True): + def copy_with(self, params): + if isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + if isinstance(params[-1], _ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + return super().copy_with(params) + + +@_SpecialForm +def Unpack(self, parameters): + """Type unpack operator. + + The type unpack operator takes the child types from some container type, + such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. + + For example:: + + # For some generic class `Foo`: + Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] + + Ts = TypeVarTuple('Ts') + # Specifies that `Bar` is generic in an arbitrary number of types. + # (Think of `Ts` as a tuple of an arbitrary number of individual + # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the + # `Generic[]`.) + class Bar(Generic[Unpack[Ts]]): ... + Bar[int] # Valid + Bar[int, str] # Also valid + + From Python 3.11, this can also be done using the `*` operator:: + + Foo[*tuple[int, str]] + class Bar(Generic[*Ts]): ... + + Note that there is only some runtime checking of this operator. Not + everything the runtime allows may be accepted by static type checkers. + + For more information, see PEP 646. + """ + item = _type_check(parameters, f'{self} accepts only single type.') + return _UnpackGenericAlias(origin=self, args=(item,)) + + +class _UnpackGenericAlias(_GenericAlias, _root=True): + def __repr__(self): + # `Unpack` only takes one argument, so __args__ should contain only + # a single item. + return '*' + repr(self.__args__[0]) + + def __getitem__(self, args): + if self.__typing_is_unpacked_typevartuple__: + return args + return super().__getitem__(args) + + @property + def __typing_unpacked_tuple_args__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + arg, = self.__args__ + if isinstance(arg, _GenericAlias): + assert arg.__origin__ is tuple + return arg.__args__ + return None + + @property + def __typing_is_unpacked_typevartuple__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + return isinstance(self.__args__[0], TypeVarTuple) + + +class Generic: + """Abstract base class for generic types. + + A generic type is typically declared by inheriting from + this class parameterized with one or more type variables. + For example, a generic mapping type might be defined as:: + + class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. + + This class can then be used as follows:: + + def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: + try: + return mapping[key] + except KeyError: + return default + """ + __slots__ = () + _is_protocol = False + + @_tp_cache + def __class_getitem__(cls, params): + """Parameterizes a generic class. + + At least, parameterizing a generic class is the *main* thing this method + does. For example, for some generic class `Foo`, this is called when we + do `Foo[int]` - there, with `cls=Foo` and `params=int`. + + However, note that this method is also called when defining generic + classes in the first place with `class Foo(Generic[T]): ...`. + """ + if not isinstance(params, tuple): + params = (params,) + + params = tuple(_type_convert(p) for p in params) + if cls in (Generic, Protocol): + # Generic and Protocol can only be subscripted with unique type variables. + if not params: + raise TypeError( + f"Parameter list to {cls.__qualname__}[...] cannot be empty" + ) + if not all(_is_typevar_like(p) for p in params): + raise TypeError( + f"Parameters to {cls.__name__}[...] must all be type variables " + f"or parameter specification variables.") + if len(set(params)) != len(params): + raise TypeError( + f"Parameters to {cls.__name__}[...] must all be unique") + else: + # Subscripting a regular Generic subclass. + for param in cls.__parameters__: + prepare = getattr(param, '__typing_prepare_subst__', None) + if prepare is not None: + params = prepare(cls, params) + _check_generic(cls, params, len(cls.__parameters__)) + + new_args = [] + for param, new_arg in zip(cls.__parameters__, params): + if isinstance(param, TypeVarTuple): + new_args.extend(new_arg) + else: + new_args.append(new_arg) + params = tuple(new_args) + + return _GenericAlias(cls, params, + _paramspec_tvars=True) + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + tvars = [] + if '__orig_bases__' in cls.__dict__: + error = Generic in cls.__orig_bases__ + else: + error = (Generic in cls.__bases__ and + cls.__name__ != 'Protocol' and + type(cls) != _TypedDictMeta) + if error: + raise TypeError("Cannot inherit from plain Generic") + if '__orig_bases__' in cls.__dict__: + tvars = _collect_parameters(cls.__orig_bases__) + # Look for Generic[T1, ..., Tn]. + # If found, tvars must be a subset of it. + # If not found, tvars is it. + # Also check for and reject plain Generic, + # and reject multiple Generic[...]. + gvars = None + for base in cls.__orig_bases__: + if (isinstance(base, _GenericAlias) and + base.__origin__ is Generic): + if gvars is not None: + raise TypeError( + "Cannot inherit from Generic[...] multiple times.") + gvars = base.__parameters__ + if gvars is not None: + tvarset = set(tvars) + gvarset = set(gvars) + if not tvarset <= gvarset: + s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) + s_args = ', '.join(str(g) for g in gvars) + raise TypeError(f"Some type variables ({s_vars}) are" + f" not listed in Generic[{s_args}]") + tvars = gvars + cls.__parameters__ = tuple(tvars) + + +class _TypingEllipsis: + """Internal placeholder for ... (ellipsis).""" + + +_TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__', + '_is_protocol', '_is_runtime_protocol', '__final__'] + +_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__', + '__init__', '__module__', '__new__', '__slots__', + '__subclasshook__', '__weakref__', '__class_getitem__'] + +# These special attributes will be not collected as protocol members. +EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker'] + + +def _get_protocol_attrs(cls): + """Collect protocol members from a protocol class objects. + + This includes names actually defined in the class dictionary, as well + as names that appear in annotations. Special names (above) are skipped. + """ + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in ('Protocol', 'Generic'): + continue + annotations = getattr(base, '__annotations__', {}) + for attr in list(base.__dict__.keys()) + list(annotations.keys()): + if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES: + attrs.add(attr) + return attrs + + +def _is_callable_members_only(cls): + # PEP 544 prohibits using issubclass() with protocols that have non-method members. + return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls)) + + +def _no_init_or_replace_init(self, *args, **kwargs): + cls = type(self) + + if cls._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + # Already using a custom `__init__`. No need to calculate correct + # `__init__` to call. This can lead to RecursionError. See bpo-45121. + if cls.__init__ is not _no_init_or_replace_init: + return + + # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. + # The first instantiation of the subclass will call `_no_init_or_replace_init` which + # searches for a proper new `__init__` in the MRO. The new `__init__` + # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent + # instantiation of the protocol subclass will thus use the new + # `__init__` and no longer call `_no_init_or_replace_init`. + for base in cls.__mro__: + init = base.__dict__.get('__init__', _no_init_or_replace_init) + if init is not _no_init_or_replace_init: + cls.__init__ = init + break + else: + # should not happen + cls.__init__ = object.__init__ + + cls.__init__(self, *args, **kwargs) + + +def _caller(depth=1, default='__main__'): + try: + return sys._getframe(depth + 1).f_globals.get('__name__', default) + except (AttributeError, ValueError): # For platforms without _getframe() + return None + + +def _allow_reckless_class_checks(depth=3): + """Allow instance and class checks for special stdlib modules. + + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + """ + return _caller(depth) in {'abc', 'functools', None} + + +_PROTO_ALLOWLIST = { + 'collections.abc': [ + 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', + 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', + ], + 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], +} + + +class _ProtocolMeta(ABCMeta): + # This metaclass is really unfortunate and exists only because of + # the lack of __instancehook__. + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if ( + getattr(cls, '_is_protocol', False) and + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks(depth=2) + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + + if ((not getattr(cls, '_is_protocol', False) or + _is_callable_members_only(cls)) and + issubclass(instance.__class__, cls)): + return True + if cls._is_protocol: + if all(hasattr(instance, attr) and + # All *methods* can be blocked by setting them to None. + (not callable(getattr(cls, attr, None)) or + getattr(instance, attr) is not None) + for attr in _get_protocol_attrs(cls)): + return True + return super().__instancecheck__(instance) + + +class Protocol(Generic, metaclass=_ProtocolMeta): + """Base class for protocol classes. + + Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing). + + For example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing.runtime_checkable act as simple-minded runtime protocols that check + only the presence of given attributes, ignoring their type signatures. + Protocol classes can be generic, they are defined as:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + """ + + __slots__ = () + _is_protocol = True + _is_runtime_protocol = False + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', False): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + def _proto_hook(other): + if not cls.__dict__.get('_is_protocol', False): + return NotImplemented + + # First, perform various sanity checks. + if not getattr(cls, '_is_runtime_protocol', False): + if _allow_reckless_class_checks(): + return NotImplemented + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + if not _is_callable_members_only(cls): + if _allow_reckless_class_checks(): + return NotImplemented + raise TypeError("Protocols with non-method members" + " don't support issubclass()") + if not isinstance(other, type): + # Same error message as for issubclass(1, int). + raise TypeError('issubclass() arg 1 must be a class') + + # Second, perform the actual structural compatibility check. + for attr in _get_protocol_attrs(cls): + for base in other.__mro__: + # Check if the members appears in the class dictionary... + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + + # ...or in annotations, if it is a sub-protocol. + annotations = getattr(base, '__annotations__', {}) + if (isinstance(annotations, collections.abc.Mapping) and + attr in annotations and + issubclass(other, Generic) and other._is_protocol): + break + else: + return NotImplemented + return True + + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # We have nothing more to do for non-protocols... + if not cls._is_protocol: + return + + # ... otherwise check consistency of bases, and prohibit instantiation. + for base in cls.__bases__: + if not (base in (object, Generic) or + base.__module__ in _PROTO_ALLOWLIST and + base.__name__ in _PROTO_ALLOWLIST[base.__module__] or + issubclass(base, Generic) and base._is_protocol): + raise TypeError('Protocols can only inherit from other' + ' protocols, got %r' % base) + if cls.__init__ is Protocol.__init__: + cls.__init__ = _no_init_or_replace_init + + +class _AnnotatedAlias(_NotIterable, _GenericAlias, _root=True): + """Runtime representation of an annotated type. + + At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' + with extra annotations. The alias behaves like a normal typing alias. + Instantiating is the same as instantiating the underlying type; binding + it to types is also the same. + + The metadata itself is stored in a '__metadata__' attribute as a tuple. + """ + + def __init__(self, origin, metadata): + if isinstance(origin, _AnnotatedAlias): + metadata = origin.__metadata__ + metadata + origin = origin.__origin__ + super().__init__(origin, origin) + self.__metadata__ = metadata + + def copy_with(self, params): + assert len(params) == 1 + new_type = params[0] + return _AnnotatedAlias(new_type, self.__metadata__) + + def __repr__(self): + return "typing.Annotated[{}, {}]".format( + _type_repr(self.__origin__), + ", ".join(repr(a) for a in self.__metadata__) + ) + + def __reduce__(self): + return operator.getitem, ( + Annotated, (self.__origin__,) + self.__metadata__ + ) + + def __eq__(self, other): + if not isinstance(other, _AnnotatedAlias): + return NotImplemented + return (self.__origin__ == other.__origin__ + and self.__metadata__ == other.__metadata__) + + def __hash__(self): + return hash((self.__origin__, self.__metadata__)) + + def __getattr__(self, attr): + if attr in {'__name__', '__qualname__'}: + return 'Annotated' + return super().__getattr__(attr) + + +class Annotated: + """Add context-specific metadata to a type. + + Example: Annotated[int, runtime_check.Unsigned] indicates to the + hypothetical runtime_check module that this type is an unsigned int. + Every other consumer of this type can ignore this metadata and treat + this type as int. + + The first argument to Annotated must be a valid type. + + Details: + + - It's an error to call `Annotated` with less than two arguments. + - Access the metadata via the ``__metadata__`` attribute:: + + assert Annotated[int, '$'].__metadata__ == ('$',) + + - Nested Annotated types are flattened:: + + assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] + + - Instantiating an annotated type is equivalent to instantiating the + underlying type:: + + assert Annotated[C, Ann1](5) == C(5) + + - Annotated can be used as a generic type alias:: + + Optimized: TypeAlias = Annotated[T, runtime.Optimize()] + assert Optimized[int] == Annotated[int, runtime.Optimize()] + + OptimizedList: TypeAlias = Annotated[list[T], runtime.Optimize()] + assert OptimizedList[int] == Annotated[list[int], runtime.Optimize()] + + - Annotated cannot be used with an unpacked TypeVarTuple:: + + Variadic: TypeAlias = Annotated[*Ts, Ann1] # NOT valid + + This would be equivalent to:: + + Annotated[T1, T2, T3, ..., Ann1] + + where T1, T2 etc. are TypeVars, which would be invalid, because + only one type should be passed to Annotated. + """ + + __slots__ = () + + def __new__(cls, *args, **kwargs): + raise TypeError("Type Annotated cannot be instantiated.") + + def __class_getitem__(cls, params): + if not isinstance(params, tuple): + params = (params,) + return cls._class_getitem_inner(cls, *params) + + @_tp_cache(typed=True) + def _class_getitem_inner(cls, *params): + if len(params) < 2: + raise TypeError("Annotated[...] should be used " + "with at least two arguments (a type and an " + "annotation).") + if _is_unpacked_typevartuple(params[0]): + raise TypeError("Annotated[...] should not be used with an " + "unpacked TypeVarTuple") + msg = "Annotated[t, ...]: t must be a type." + origin = _type_check(params[0], msg, allow_special_forms=True) + metadata = tuple(params[1:]) + return _AnnotatedAlias(origin, metadata) + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "Cannot subclass {}.Annotated".format(cls.__module__) + ) + + +def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + """ + if not issubclass(cls, Generic) or not cls._is_protocol: + raise TypeError('@runtime_checkable can be only applied to protocol classes,' + ' got %r' % cls) + cls._is_runtime_protocol = True + return cls + + +def cast(typ, val): + """Cast a value to a type. + + This returns the value unchanged. To the type checker this + signals that the return value has the designated type, but at + runtime we intentionally don't check anything (we want this + to be as fast as possible). + """ + return val + + +def assert_type(val, typ, /): + """Ask a static type checker to confirm that the value is of the given type. + + At runtime this does nothing: it returns the first argument unchanged with no + checks or side effects, no matter the actual type of the argument. + + When a static type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # OK + assert_type(name, int) # type checker error + """ + return val + + +_allowed_types = (types.FunctionType, types.BuiltinFunctionType, + types.MethodType, types.ModuleType, + WrapperDescriptorType, MethodWrapperType, MethodDescriptorType) + + +def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals and recursively replaces all + 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. For classes, the search + order is globals first then locals. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + if getattr(obj, '__no_type_check__', None): + return {} + # Classes require a special treatment. + if isinstance(obj, type): + hints = {} + for base in reversed(obj.__mro__): + if globalns is None: + base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {}) + else: + base_globals = globalns + ann = base.__dict__.get('__annotations__', {}) + if isinstance(ann, types.GetSetDescriptorType): + ann = {} + base_locals = dict(vars(base)) if localns is None else localns + if localns is None and globalns is None: + # This is surprising, but required. Before Python 3.10, + # get_type_hints only evaluated the globalns of + # a class. To maintain backwards compatibility, we reverse + # the globalns and localns order so that eval() looks into + # *base_globals* first rather than *base_locals*. + # This only affects ForwardRefs. + base_globals, base_locals = base_locals, base_globals + for name, value in ann.items(): + if value is None: + value = type(None) + if isinstance(value, str): + value = ForwardRef(value, is_argument=False, is_class=True) + value = _eval_type(value, base_globals, base_locals) + hints[name] = value + return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()} + + if globalns is None: + if isinstance(obj, types.ModuleType): + globalns = obj.__dict__ + else: + nsobj = obj + # Find globalns for the unwrapped object. + while hasattr(nsobj, '__wrapped__'): + nsobj = nsobj.__wrapped__ + globalns = getattr(nsobj, '__globals__', {}) + if localns is None: + localns = globalns + elif localns is None: + localns = globalns + hints = getattr(obj, '__annotations__', None) + if hints is None: + # Return empty annotations for something that _could_ have them. + if isinstance(obj, _allowed_types): + return {} + else: + raise TypeError('{!r} is not a module, class, method, ' + 'or function.'.format(obj)) + hints = dict(hints) + for name, value in hints.items(): + if value is None: + value = type(None) + if isinstance(value, str): + # class-level forward refs were handled above, this must be either + # a module-level annotation or a function argument annotation + value = ForwardRef( + value, + is_argument=not isinstance(obj, types.ModuleType), + is_class=False, + ) + hints[name] = _eval_type(value, globalns, localns) + return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()} + + +def _strip_annotations(t): + """Strip the annotations from a given type.""" + if isinstance(t, _AnnotatedAlias): + return _strip_annotations(t.__origin__) + if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired): + return _strip_annotations(t.__args__[0]) + if isinstance(t, _GenericAlias): + stripped_args = tuple(_strip_annotations(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return t.copy_with(stripped_args) + if isinstance(t, GenericAlias): + stripped_args = tuple(_strip_annotations(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return GenericAlias(t.__origin__, stripped_args) + if isinstance(t, types.UnionType): + stripped_args = tuple(_strip_annotations(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return functools.reduce(operator.or_, stripped_args) + + return t + + +def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, + Annotated, and others. Return None for unsupported types. + + Examples:: + + >>> P = ParamSpec('P') + >>> assert get_origin(Literal[42]) is Literal + >>> assert get_origin(int) is None + >>> assert get_origin(ClassVar[int]) is ClassVar + >>> assert get_origin(Generic) is Generic + >>> assert get_origin(Generic[T]) is Generic + >>> assert get_origin(Union[T, int]) is Union + >>> assert get_origin(List[Tuple[T, T]][int]) is list + >>> assert get_origin(P.args) is P + """ + if isinstance(tp, _AnnotatedAlias): + return Annotated + if isinstance(tp, (_BaseGenericAlias, GenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is Generic: + return Generic + if isinstance(tp, types.UnionType): + return types.UnionType + return None + + +def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + + Examples:: + + >>> T = TypeVar('T') + >>> assert get_args(Dict[str, int]) == (str, int) + >>> assert get_args(int) == () + >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str) + >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + >>> assert get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, _AnnotatedAlias): + return (tp.__origin__,) + tp.__metadata__ + if isinstance(tp, (_GenericAlias, GenericAlias)): + res = tp.__args__ + if _should_unflatten_callable_args(tp, res): + res = (list(res[:-1]), res[-1]) + return res + if isinstance(tp, types.UnionType): + return tp.__args__ + return () + + +def is_typeddict(tp): + """Check if an annotation is a TypedDict class. + + For example:: + + >>> from typing import TypedDict + >>> class Film(TypedDict): + ... title: str + ... year: int + ... + >>> is_typeddict(Film) + True + >>> is_typeddict(dict) + False + """ + return isinstance(tp, _TypedDictMeta) + + +_ASSERT_NEVER_REPR_MAX_LENGTH = 100 + + +def assert_never(arg: Never, /) -> Never: + """Statically assert that a line of code is unreachable. + + Example:: + + def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + assert_never(arg) + + If a type checker finds that a call to assert_never() is + reachable, it will emit an error. + + At runtime, this throws an exception when called. + """ + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' + raise AssertionError(f"Expected code to be unreachable, but got: {value}") + + +def no_type_check(arg): + """Decorator to indicate that annotations are not type hints. + + The argument must be a class or function; if it is a class, it + applies recursively to all methods and classes defined in that class + (but not to methods defined in its superclasses or subclasses). + + This mutates the function(s) or class(es) in place. + """ + if isinstance(arg, type): + for key in dir(arg): + obj = getattr(arg, key) + if ( + not hasattr(obj, '__qualname__') + or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}' + or getattr(obj, '__module__', None) != arg.__module__ + ): + # We only modify objects that are defined in this type directly. + # If classes / methods are nested in multiple layers, + # we will modify them when processing their direct holders. + continue + # Instance, class, and static methods: + if isinstance(obj, types.FunctionType): + obj.__no_type_check__ = True + if isinstance(obj, types.MethodType): + obj.__func__.__no_type_check__ = True + # Nested types: + if isinstance(obj, type): + no_type_check(obj) + try: + arg.__no_type_check__ = True + except TypeError: # built-in classes + pass + return arg + + +def no_type_check_decorator(decorator): + """Decorator to give another decorator the @no_type_check effect. + + This wraps the decorator with something that wraps the decorated + function in @no_type_check. + """ + @functools.wraps(decorator) + def wrapped_decorator(*args, **kwds): + func = decorator(*args, **kwds) + func = no_type_check(func) + return func + + return wrapped_decorator + + +def _overload_dummy(*args, **kwds): + """Helper for @overload to raise when called.""" + raise NotImplementedError( + "You should not call an overloaded function. " + "A series of @overload-decorated functions " + "outside a stub module should always be followed " + "by an implementation that is not @overload-ed.") + + +# {module: {qualname: {firstlineno: func}}} +_overload_registry = defaultdict(functools.partial(defaultdict, dict)) + + +def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. + + For example:: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload:: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + ... # implementation goes here + + The overloads for a function can be retrieved at runtime using the + get_overloads() function. + """ + # classmethod and staticmethod + f = getattr(func, "__func__", func) + try: + _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func + except AttributeError: + # Not a normal function; ignore. + pass + return _overload_dummy + + +def get_overloads(func): + """Return all defined overloads for *func* as a sequence.""" + # classmethod and staticmethod + f = getattr(func, "__func__", func) + if f.__module__ not in _overload_registry: + return [] + mod_dict = _overload_registry[f.__module__] + if f.__qualname__ not in mod_dict: + return [] + return list(mod_dict[f.__qualname__].values()) + + +def clear_overloads(): + """Clear all overloads in the registry.""" + _overload_registry.clear() + + +def final(f): + """Decorator to indicate final methods and final classes. + + Use this decorator to indicate to type checkers that the decorated + method cannot be overridden, and decorated class cannot be subclassed. + + For example:: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + attempts to set the ``__final__`` attribute to ``True`` on the decorated + object to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = TypeVar('T') # Any type. +KT = TypeVar('KT') # Key type. +VT = TypeVar('VT') # Value type. +T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. +V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. +VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. +T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. +# Internal type variable used for Type[]. +CT_co = TypeVar('CT_co', covariant=True, bound=type) + +# A useful type variable with constraints. This represents string types. +# (This one *is* for export!) +AnyStr = TypeVar('AnyStr', bytes, str) + + +# Various ABCs mimicking those in collections.abc. +_alias = _SpecialGenericAlias + +Hashable = _alias(collections.abc.Hashable, 0) # Not generic. +Awaitable = _alias(collections.abc.Awaitable, 1) +Coroutine = _alias(collections.abc.Coroutine, 3) +AsyncIterable = _alias(collections.abc.AsyncIterable, 1) +AsyncIterator = _alias(collections.abc.AsyncIterator, 1) +Iterable = _alias(collections.abc.Iterable, 1) +Iterator = _alias(collections.abc.Iterator, 1) +Reversible = _alias(collections.abc.Reversible, 1) +Sized = _alias(collections.abc.Sized, 0) # Not generic. +Container = _alias(collections.abc.Container, 1) +Collection = _alias(collections.abc.Collection, 1) +Callable = _CallableType(collections.abc.Callable, 2) +Callable.__doc__ = \ + """Deprecated alias to collections.abc.Callable. + + Callable[[int], str] signifies a function that takes a single + parameter of type int and returns a str. + + The subscription syntax must always be used with exactly two + values: the argument list and the return type. + The argument list must be a list of types, a ParamSpec, + Concatenate or ellipsis. The return type must be a single type. + + There is no syntax to indicate optional or keyword arguments; + such function types are rarely used as callback types. + """ +AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet') +MutableSet = _alias(collections.abc.MutableSet, 1) +# NOTE: Mapping is only covariant in the value type. +Mapping = _alias(collections.abc.Mapping, 2) +MutableMapping = _alias(collections.abc.MutableMapping, 2) +Sequence = _alias(collections.abc.Sequence, 1) +MutableSequence = _alias(collections.abc.MutableSequence, 1) +ByteString = _alias(collections.abc.ByteString, 0) # Not generic +# Tuple accepts variable number of parameters. +Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') +Tuple.__doc__ = \ + """Deprecated alias to builtins.tuple. + + Tuple[X, Y] is the cross-product type of X and Y. + + Example: Tuple[T1, T2] is a tuple of two elements corresponding + to type variables T1 and T2. Tuple[int, float, str] is a tuple + of an int, a float and a string. + + To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. + """ +List = _alias(list, 1, inst=False, name='List') +Deque = _alias(collections.deque, 1, name='Deque') +Set = _alias(set, 1, inst=False, name='Set') +FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet') +MappingView = _alias(collections.abc.MappingView, 1) +KeysView = _alias(collections.abc.KeysView, 1) +ItemsView = _alias(collections.abc.ItemsView, 2) +ValuesView = _alias(collections.abc.ValuesView, 1) +ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager') +AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager') +Dict = _alias(dict, 2, inst=False, name='Dict') +DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict') +OrderedDict = _alias(collections.OrderedDict, 2) +Counter = _alias(collections.Counter, 1) +ChainMap = _alias(collections.ChainMap, 2) +Generator = _alias(collections.abc.Generator, 3) +AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) +Type = _alias(type, 1, inst=False, name='Type') +Type.__doc__ = \ + """Deprecated alias to builtins.type. + + builtins.type or typing.Type can be used to annotate class objects. + For example, suppose we have the following classes:: + + class User: ... # Abstract base for User classes + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + And a function that takes a class argument that's a subclass of + User and returns an instance of the corresponding class:: + + U = TypeVar('U', bound=User) + def new_user(user_class: Type[U]) -> U: + user = user_class() + # (Here we could write the user object to a database) + return user + + joe = new_user(BasicUser) + + At this point the type checker knows that joe has type BasicUser. + """ + + +@runtime_checkable +class SupportsInt(Protocol): + """An ABC with one abstract method __int__.""" + + __slots__ = () + + @abstractmethod + def __int__(self) -> int: + pass + + +@runtime_checkable +class SupportsFloat(Protocol): + """An ABC with one abstract method __float__.""" + + __slots__ = () + + @abstractmethod + def __float__(self) -> float: + pass + + +@runtime_checkable +class SupportsComplex(Protocol): + """An ABC with one abstract method __complex__.""" + + __slots__ = () + + @abstractmethod + def __complex__(self) -> complex: + pass + + +@runtime_checkable +class SupportsBytes(Protocol): + """An ABC with one abstract method __bytes__.""" + + __slots__ = () + + @abstractmethod + def __bytes__(self) -> bytes: + pass + + +@runtime_checkable +class SupportsIndex(Protocol): + """An ABC with one abstract method __index__.""" + + __slots__ = () + + @abstractmethod + def __index__(self) -> int: + pass + + +@runtime_checkable +class SupportsAbs(Protocol[T_co]): + """An ABC with one abstract method __abs__ that is covariant in its return type.""" + + __slots__ = () + + @abstractmethod + def __abs__(self) -> T_co: + pass + + +@runtime_checkable +class SupportsRound(Protocol[T_co]): + """An ABC with one abstract method __round__ that is covariant in its return type.""" + + __slots__ = () + + @abstractmethod + def __round__(self, ndigits: int = 0) -> T_co: + pass + + +def _make_nmtuple(name, types, module, defaults = ()): + fields = [n for n, t in types] + types = {n: _type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types + return nm_tpl + + +# attributes prohibited to set in NamedTuple class syntax +_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__', + '_fields', '_field_defaults', + '_make', '_replace', '_asdict', '_source'}) + +_special = frozenset({'__module__', '__name__', '__annotations__'}) + + +class NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + types = ns.get('__annotations__', {}) + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple(typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__']) + nm_tpl.__bases__ = bases + if Generic in bases: + class_getitem = Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key in ns: + if key in _prohibited: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special and key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + if Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + +def NamedTuple(typename, fields=None, /, **kwargs): + """Typed version of namedtuple. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + An alternative equivalent functional syntax is also accepted:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + """ + if fields is None: + fields = kwargs.items() + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + return _make_nmtuple(typename, fields, module=_caller()) + +_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {}) + +def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + +NamedTuple.__mro_entries__ = _namedtuple_mro_entries + + +class _TypedDictMeta(type): + def __new__(cls, name, bases, ns, total=True): + """Create a new typed dict class object. + + This method is called when TypedDict is subclassed, + or when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries. + """ + for base in bases: + if type(base) is not _TypedDictMeta and base is not Generic: + raise TypeError('cannot inherit from both a TypedDict type ' + 'and a non-TypedDict base class') + + if any(issubclass(b, Generic) for b in bases): + generic_base = (Generic,) + else: + generic_base = () + + tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns) + + annotations = {} + own_annotations = ns.get('__annotations__', {}) + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + own_annotations = { + n: _type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + + for base in bases: + annotations.update(base.__dict__.get('__annotations__', {})) + + base_required = base.__dict__.get('__required_keys__', set()) + required_keys |= base_required + optional_keys -= base_required + + base_optional = base.__dict__.get('__optional_keys__', set()) + required_keys -= base_optional + optional_keys |= base_optional + + annotations.update(own_annotations) + for annotation_key, annotation_type in own_annotations.items(): + annotation_origin = get_origin(annotation_type) + if annotation_origin is Annotated: + annotation_args = get_args(annotation_type) + if annotation_args: + annotation_type = annotation_args[0] + annotation_origin = get_origin(annotation_type) + + if annotation_origin is Required: + is_required = True + elif annotation_origin is NotRequired: + is_required = False + else: + is_required = total + + if is_required: + required_keys.add(annotation_key) + optional_keys.discard(annotation_key) + else: + optional_keys.add(annotation_key) + required_keys.discard(annotation_key) + + assert required_keys.isdisjoint(optional_keys), ( + f"Required keys overlap with optional keys in {name}:" + f" {required_keys=}, {optional_keys=}" + ) + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + if not hasattr(tp_dict, '__total__'): + tp_dict.__total__ = total + return tp_dict + + __call__ = dict # static method + + def __subclasscheck__(cls, other): + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + + __instancecheck__ = __subclasscheck__ + + +def TypedDict(typename, fields=None, /, *, total=True, **kwargs): + """A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type such that a type checker will expect all + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime. + + Usage:: + + >>> class Point2D(TypedDict): + ... x: int + ... y: int + ... label: str + ... + >>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + >>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + True + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports an additional equivalent form:: + + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + This means that a Point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The Required and NotRequired special forms can also be used to mark + individual keys as being required or not required:: + + class Point2D(TypedDict): + x: int # the "x" key must always be present (Required is the default) + y: NotRequired[int] # the "y" key can be omitted + + See PEP 655 for more details on Required and NotRequired. + """ + if fields is None: + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + if kwargs: + warnings.warn( + "The kwargs-based syntax for TypedDict definitions is deprecated " + "in Python 3.11, will be removed in Python 3.13, and may not be " + "understood by third-party type checkers.", + DeprecationWarning, + stacklevel=2, + ) + + ns = {'__annotations__': dict(fields)} + module = _caller() + if module is not None: + # Setting correct module is necessary to make typed dict classes pickleable. + ns['__module__'] = module + + return _TypedDictMeta(typename, (), ns, total=total) + +_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) +TypedDict.__mro_entries__ = lambda bases: (_TypedDict,) + + +@_SpecialForm +def Required(self, parameters): + """Special typing construct to mark a TypedDict key as required. + + This is mainly useful for total=False TypedDicts. + + For example:: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """ + item = _type_check(parameters, f'{self._name} accepts only a single type.') + return _GenericAlias(self, (item,)) + + +@_SpecialForm +def NotRequired(self, parameters): + """Special typing construct to mark a TypedDict key as potentially missing. + + For example:: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """ + item = _type_check(parameters, f'{self._name} accepts only a single type.') + return _GenericAlias(self, (item,)) + + +class NewType: + """NewType creates simple unique types with almost zero runtime overhead. + + NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy callable that simply returns its argument. + + Usage:: + + UserId = NewType('UserId', int) + + def name_by_id(user_id: UserId) -> str: + ... + + UserId('user') # Fails type check + + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + + num = UserId(5) + 1 # type: int + """ + + __call__ = _idfunc + + def __init__(self, name, tp): + self.__qualname__ = name + if '.' in name: + name = name.rpartition('.')[-1] + self.__name__ = name + self.__supertype__ = tp + def_mod = _caller() + if def_mod != 'typing': + self.__module__ = def_mod + + def __mro_entries__(self, bases): + # We defined __mro_entries__ to get a better error message + # if a user attempts to subclass a NewType instance. bpo-46170 + superclass_name = self.__name__ + + class Dummy: + def __init_subclass__(cls): + subclass_name = cls.__name__ + raise TypeError( + f"Cannot subclass an instance of NewType. Perhaps you were looking for: " + f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`" + ) + + return (Dummy,) + + def __repr__(self): + return f'{self.__module__}.{self.__qualname__}' + + def __reduce__(self): + return self.__qualname__ + + def __or__(self, other): + return Union[self, other] + + def __ror__(self, other): + return Union[other, self] + + +# Python-version-specific alias (Python 2: unicode; Python 3: str) +Text = str + + +# Constant that's True when type checking, but False here. +TYPE_CHECKING = False + + +class IO(Generic[AnyStr]): + """Generic base class for TextIO and BinaryIO. + + This is an abstract, generic version of the return of open(). + + NOTE: This does not distinguish between the different possible + classes (text vs. binary, read vs. write vs. read/write, + append-only, unbuffered). The TextIO and BinaryIO subclasses + below capture the distinctions between text vs. binary, which is + pervasive in the interface; however we currently do not offer a + way to track the other distinctions in the type system. + """ + + __slots__ = () + + @property + @abstractmethod + def mode(self) -> str: + pass + + @property + @abstractmethod + def name(self) -> str: + pass + + @abstractmethod + def close(self) -> None: + pass + + @property + @abstractmethod + def closed(self) -> bool: + pass + + @abstractmethod + def fileno(self) -> int: + pass + + @abstractmethod + def flush(self) -> None: + pass + + @abstractmethod + def isatty(self) -> bool: + pass + + @abstractmethod + def read(self, n: int = -1) -> AnyStr: + pass + + @abstractmethod + def readable(self) -> bool: + pass + + @abstractmethod + def readline(self, limit: int = -1) -> AnyStr: + pass + + @abstractmethod + def readlines(self, hint: int = -1) -> List[AnyStr]: + pass + + @abstractmethod + def seek(self, offset: int, whence: int = 0) -> int: + pass + + @abstractmethod + def seekable(self) -> bool: + pass + + @abstractmethod + def tell(self) -> int: + pass + + @abstractmethod + def truncate(self, size: int = None) -> int: + pass + + @abstractmethod + def writable(self) -> bool: + pass + + @abstractmethod + def write(self, s: AnyStr) -> int: + pass + + @abstractmethod + def writelines(self, lines: List[AnyStr]) -> None: + pass + + @abstractmethod + def __enter__(self) -> 'IO[AnyStr]': + pass + + @abstractmethod + def __exit__(self, type, value, traceback) -> None: + pass + + +class BinaryIO(IO[bytes]): + """Typed version of the return of open() in binary mode.""" + + __slots__ = () + + @abstractmethod + def write(self, s: Union[bytes, bytearray]) -> int: + pass + + @abstractmethod + def __enter__(self) -> 'BinaryIO': + pass + + +class TextIO(IO[str]): + """Typed version of the return of open() in text mode.""" + + __slots__ = () + + @property + @abstractmethod + def buffer(self) -> BinaryIO: + pass + + @property + @abstractmethod + def encoding(self) -> str: + pass + + @property + @abstractmethod + def errors(self) -> Optional[str]: + pass + + @property + @abstractmethod + def line_buffering(self) -> bool: + pass + + @property + @abstractmethod + def newlines(self) -> Any: + pass + + @abstractmethod + def __enter__(self) -> 'TextIO': + pass + + +class _DeprecatedType(type): + def __getattribute__(cls, name): + if name not in {"__dict__", "__module__", "__doc__"} and name in cls.__dict__: + warnings.warn( + f"{cls.__name__} is deprecated, import directly " + f"from typing instead. {cls.__name__} will be removed " + "in Python 3.12.", + DeprecationWarning, + stacklevel=2, + ) + return super().__getattribute__(name) + + +class io(metaclass=_DeprecatedType): + """Wrapper namespace for IO generic classes.""" + + __all__ = ['IO', 'TextIO', 'BinaryIO'] + IO = IO + TextIO = TextIO + BinaryIO = BinaryIO + + +io.__name__ = __name__ + '.io' +sys.modules[io.__name__] = io + +Pattern = _alias(stdlib_re.Pattern, 1) +Match = _alias(stdlib_re.Match, 1) + +class re(metaclass=_DeprecatedType): + """Wrapper namespace for re type aliases.""" + + __all__ = ['Pattern', 'Match'] + Pattern = Pattern + Match = Match + + +re.__name__ = __name__ + '.re' +sys.modules[re.__name__] = re + + +def reveal_type(obj: T, /) -> T: + """Ask a static type checker to reveal the inferred type of an expression. + + When a static type checker encounters a call to ``reveal_type()``, + it will emit the inferred type of the argument:: + + x: int = 1 + reveal_type(x) + + Running a static type checker (e.g., mypy) on this example + will produce output similar to 'Revealed type is "builtins.int"'. + + At runtime, the function prints the runtime type of the + argument and returns the argument unchanged. + """ + print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) + return obj + + +def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), + **kwargs: Any, +) -> Callable[[T], T]: + """Decorator to mark an object as providing dataclass-like behaviour. + + The decorator can be applied to a function, class, or metaclass. + + Example usage with a decorator function:: + + T = TypeVar("T") + + @dataclass_transform() + def create_model(cls: type[T]) -> type[T]: + ... + return cls + + @create_model + class CustomerModel: + id: int + name: str + + On a base class:: + + @dataclass_transform() + class ModelBase: ... + + class CustomerModel(ModelBase): + id: int + name: str + + On a metaclass:: + + @dataclass_transform() + class ModelMeta(type): ... + + class ModelBase(metaclass=ModelMeta): ... + + class CustomerModel(ModelBase): + id: int + name: str + + The ``CustomerModel`` classes defined above will + be treated by type checkers similarly to classes created with + ``@dataclasses.dataclass``. + For example, type checkers will assume these classes have + ``__init__`` methods that accept ``id`` and ``name``. + + The arguments to this decorator can be used to customize this behavior: + - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be + ``True`` or ``False`` if it is omitted by the caller. + - ``order_default`` indicates whether the ``order`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``kw_only_default`` indicates whether the ``kw_only`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``field_specifiers`` specifies a static list of supported classes + or functions that describe fields, similar to ``dataclasses.field()``. + - Arbitrary other keyword arguments are accepted in order to allow for + possible future extensions. + + At runtime, this decorator records its arguments in the + ``__dataclass_transform__`` attribute on the decorated object. + It has no other runtime effect. + + See PEP 681 for more details. + """ + def decorator(cls_or_fn): + cls_or_fn.__dataclass_transform__ = { + "eq_default": eq_default, + "order_default": order_default, + "kw_only_default": kw_only_default, + "field_specifiers": field_specifiers, + "kwargs": kwargs, + } + return cls_or_fn + return decorator diff --git a/shared/package-files/ef/eff8066141f8ed4ba020012deb4bd81f99c56be414c13a43c121202e0f5c66db/curand_mtgp32dc_p_11213.h b/shared/package-files/ef/eff8066141f8ed4ba020012deb4bd81f99c56be414c13a43c121202e0f5c66db/curand_mtgp32dc_p_11213.h new file mode 100644 index 0000000000000000000000000000000000000000..56a8994c7f2016e4cd2bed77cf6b6516a42f26be --- /dev/null +++ b/shared/package-files/ef/eff8066141f8ed4ba020012deb4bd81f99c56be414c13a43c121202e0f5c66db/curand_mtgp32dc_p_11213.h @@ -0,0 +1,11710 @@ +/* + * Copyright 2010-2014 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +/* + * Multiple sets of generator parameters for Mersenne Twister + * with period 2**11213 -1 + */ +/* + * Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. All rights reserved. + * Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + * University and University of Tokyo. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of the Hiroshima University nor the names of + * its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#if !defined CURAND_MTGP32DC_P_11213_H +#define CURAND_MTGP32DC_P_11213_H + +#include "curand_mtgp32.h" + + +#if (__cplusplus >= 201703L) && defined(__cpp_inline_variables) +inline const int mtgpdc_params_11213_num = 200; +#else +static const int mtgpdc_params_11213_num = 200; +#endif + +#if (__cplusplus >= 201703L) && defined(__cpp_inline_variables) +inline mtgp32_params_fast_t mtgp32dc_params_fast_11213[] +#else +static mtgp32_params_fast_t mtgp32dc_params_fast_11213[] +#endif + = { + { + /* No.0 delta:1599 weight:665 */ + 11213, + 88, + 19, + 5, + {(0x00000000), + (0xaba4d62c), + (0xbb076f87), + (0x10a3b9ab), + (0x22000000), + (0x89a4d62c), + (0x99076f87), + (0x32a3b9ab), + (0x000095ba), + (0xaba44396), + (0xbb07fa3d), + (0x10a32c11), + (0x220095ba), + (0x89a44396), + (0x9907fa3d), + (0x32a32c11)}, + {(0x00000000), + (0x06100000), + (0x25d80000), + (0x23c80000), + (0x282c0000), + (0x2e3c0000), + (0x0df40000), + (0x0be40000), + (0x3302de00), + (0x3512de00), + (0x16dade00), + (0x10cade00), + (0x1b2ede00), + (0x1d3ede00), + (0x3ef6de00), + (0x38e6de00)}, + {(0x3f800000), + (0x3f830800), + (0x3f92ec00), + (0x3f91e400), + (0x3f941600), + (0x3f971e00), + (0x3f86fa00), + (0x3f85f200), + (0x3f99816f), + (0x3f9a896f), + (0x3f8b6d6f), + (0x3f88656f), + (0x3f8d976f), + (0x3f8e9f6f), + (0x3f9f7b6f), + (0x3f9c736f)}, + (0xfff80000), + {0xcb,0xb0,0x3f,0xaa,0x65,0x0d,0xbd,0x1c,0x8c,0xc2, + 0x91,0x00,0x87,0x25,0x7f,0xf8,0x6f,0x23,0xf2,0x18,0x00} + }, + { + /* No.1 delta:1185 weight:1129 */ + 11213, + 84, + 15, + 12, + {(0x00000000), + (0x9a975707), + (0x75c21b11), + (0xef554c16), + (0x15500019), + (0x8fc7571e), + (0x60921b08), + (0xfa054c0f), + (0x0000d269), + (0x9a97856e), + (0x75c2c978), + (0xef559e7f), + (0x1550d270), + (0x8fc78577), + (0x6092c961), + (0xfa059e66)}, + {(0x00000000), + (0x00646c00), + (0x0810f000), + (0x08749c00), + (0x37028000), + (0x3766ec00), + (0x3f127000), + (0x3f761c00), + (0x00505e00), + (0x00343200), + (0x0840ae00), + (0x0824c200), + (0x3752de00), + (0x3736b200), + (0x3f422e00), + (0x3f264200)}, + {(0x3f800000), + (0x3f803236), + (0x3f840878), + (0x3f843a4e), + (0x3f9b8140), + (0x3f9bb376), + (0x3f9f8938), + (0x3f9fbb0e), + (0x3f80282f), + (0x3f801a19), + (0x3f842057), + (0x3f841261), + (0x3f9ba96f), + (0x3f9b9b59), + (0x3f9fa117), + (0x3f9f9321)}, + (0xfff80000), + {0x53,0xe0,0x89,0xe0,0x47,0x42,0x00,0xbd,0xe9,0x04, + 0xc9,0x11,0x5c,0xe3,0x97,0x94,0x94,0xd8,0xbb,0xfc,0x00} + }, + { + /* No.2 delta:2848 weight:755 */ + 11213, + 25, + 4, + 18, + {(0x00000000), + (0x507cbad4), + (0xe742103b), + (0xb73eaaef), + (0x71c00027), + (0x21bcbaf3), + (0x9682101c), + (0xc6feaac8), + (0x0000dd6c), + (0x507c67b8), + (0xe742cd57), + (0xb73e7783), + (0x71c0dd4b), + (0x21bc679f), + (0x9682cd70), + (0xc6fe77a4)}, + {(0x00000000), + (0x04210200), + (0x08040000), + (0x0c250200), + (0x11400000), + (0x15610200), + (0x19440000), + (0x1d650200), + (0x206f1e00), + (0x244e1c00), + (0x286b1e00), + (0x2c4a1c00), + (0x312f1e00), + (0x350e1c00), + (0x392b1e00), + (0x3d0a1c00)}, + {(0x3f800000), + (0x3f821081), + (0x3f840200), + (0x3f861281), + (0x3f88a000), + (0x3f8ab081), + (0x3f8ca200), + (0x3f8eb281), + (0x3f90378f), + (0x3f92270e), + (0x3f94358f), + (0x3f96250e), + (0x3f98978f), + (0x3f9a870e), + (0x3f9c958f), + (0x3f9e850e)}, + (0xfff80000), + {0x9e,0x64,0xa3,0x28,0x10,0x66,0x35,0x72,0xe3,0x07, + 0xf7,0xcf,0x5a,0xe3,0x57,0x6f,0x90,0x0c,0x28,0x79,0x00} + }, + { + /* No.3 delta:1100 weight:1261 */ + 11213, + 42, + 20, + 9, + {(0x00000000), + (0x3ef0ef20), + (0x9fddd9ea), + (0xa12d36ca), + (0x10300036), + (0x2ec0ef16), + (0x8fedd9dc), + (0xb11d36fc), + (0x00005ced), + (0x3ef0b3cd), + (0x9fdd8507), + (0xa12d6a27), + (0x10305cdb), + (0x2ec0b3fb), + (0x8fed8531), + (0xb11d6a11)}, + {(0x00000000), + (0x24470c00), + (0x00268200), + (0x24618e00), + (0x00530000), + (0x24140c00), + (0x00758200), + (0x24328e00), + (0x105c5e00), + (0x341b5200), + (0x107adc00), + (0x343dd000), + (0x100f5e00), + (0x34485200), + (0x1029dc00), + (0x346ed000)}, + {(0x3f800000), + (0x3f922386), + (0x3f801341), + (0x3f9230c7), + (0x3f802980), + (0x3f920a06), + (0x3f803ac1), + (0x3f921947), + (0x3f882e2f), + (0x3f9a0da9), + (0x3f883d6e), + (0x3f9a1ee8), + (0x3f8807af), + (0x3f9a2429), + (0x3f8814ee), + (0x3f9a3768)}, + (0xfff80000), + {0x9b,0x1d,0x8b,0x59,0x56,0x8e,0x7b,0x75,0x24,0x4a, + 0xaf,0x49,0x6e,0xcf,0xcb,0x5d,0x67,0x00,0x31,0xac,0x00} + }, + { + /* No.4 delta:5389 weight:1871 */ + 11213, + 22, + 1, + 5, + {(0x00000000), + (0xb004feb9), + (0x03b7c894), + (0xb3b3362d), + (0x0750004d), + (0xb754fef4), + (0x04e7c8d9), + (0xb4e33660), + (0x000049e4), + (0xb004b75d), + (0x03b78170), + (0xb3b37fc9), + (0x075049a9), + (0xb754b710), + (0x04e7813d), + (0xb4e37f84)}, + {(0x00000000), + (0x48698800), + (0x04010000), + (0x4c688800), + (0x60340000), + (0x285d8800), + (0x64350000), + (0x2c5c8800), + (0x20065e00), + (0x686fd600), + (0x24075e00), + (0x6c6ed600), + (0x40325e00), + (0x085bd600), + (0x44335e00), + (0x0c5ad600)}, + {(0x3f800000), + (0x3fa434c4), + (0x3f820080), + (0x3fa63444), + (0x3fb01a00), + (0x3f942ec4), + (0x3fb21a80), + (0x3f962e44), + (0x3f90032f), + (0x3fb437eb), + (0x3f9203af), + (0x3fb6376b), + (0x3fa0192f), + (0x3f842deb), + (0x3fa219af), + (0x3f862d6b)}, + (0xfff80000), + {0xbb,0x80,0x47,0x21,0x2c,0xbd,0xd4,0x7b,0xf3,0xb3, + 0xbd,0x4d,0x05,0x36,0xf5,0x4d,0xe7,0x89,0xdc,0x11,0x00} + }, + { + /* No.5 delta:2280 weight:1243 */ + 11213, + 11, + 16, + 1, + {(0x00000000), + (0x646a361c), + (0xe36e4823), + (0x87047e3f), + (0x2b20005f), + (0x4f4a3643), + (0xc84e487c), + (0xac247e60), + (0x0000caac), + (0x646afcb0), + (0xe36e828f), + (0x8704b493), + (0x2b20caf3), + (0x4f4afcef), + (0xc84e82d0), + (0xac24b4cc)}, + {(0x00000000), + (0xd49c4200), + (0x0b98f000), + (0xdf04b200), + (0x24007200), + (0xf09c3000), + (0x2f988200), + (0xfb04c000), + (0x5d311e00), + (0x89ad5c00), + (0x56a9ee00), + (0x8235ac00), + (0x79316c00), + (0xadad2e00), + (0x72a99c00), + (0xa635de00)}, + {(0x3f800000), + (0x3fea4e21), + (0x3f85cc78), + (0x3fef8259), + (0x3f920039), + (0x3ff84e18), + (0x3f97cc41), + (0x3ffd8260), + (0x3fae988f), + (0x3fc4d6ae), + (0x3fab54f7), + (0x3fc11ad6), + (0x3fbc98b6), + (0x3fd6d697), + (0x3fb954ce), + (0x3fd31aef)}, + (0xfff80000), + {0x24,0x94,0x81,0x62,0xb4,0x6f,0x10,0x4e,0x66,0xd1, + 0xb4,0xdd,0xa0,0x92,0x2e,0xdf,0x8d,0x6b,0x03,0xa3,0x00} + }, + { + /* No.6 delta:722 weight:1357 */ + 11213, + 76, + 16, + 6, + {(0x00000000), + (0x1bb96b3c), + (0x7c6323a4), + (0x67da4898), + (0x22400061), + (0x39f96b5d), + (0x5e2323c5), + (0x459a48f9), + (0x00004c61), + (0x1bb9275d), + (0x7c636fc5), + (0x67da04f9), + (0x22404c00), + (0x39f9273c), + (0x5e236fa4), + (0x459a0498)}, + {(0x00000000), + (0x08258800), + (0x1042c000), + (0x18674800), + (0x00203000), + (0x0805b800), + (0x1062f000), + (0x18477800), + (0x70c01e00), + (0x78e59600), + (0x6082de00), + (0x68a75600), + (0x70e02e00), + (0x78c5a600), + (0x60a2ee00), + (0x68876600)}, + {(0x3f800000), + (0x3f8412c4), + (0x3f882160), + (0x3f8c33a4), + (0x3f801018), + (0x3f8402dc), + (0x3f883178), + (0x3f8c23bc), + (0x3fb8600f), + (0x3fbc72cb), + (0x3fb0416f), + (0x3fb453ab), + (0x3fb87017), + (0x3fbc62d3), + (0x3fb05177), + (0x3fb443b3)}, + (0xfff80000), + {0x06,0x1a,0x0a,0x3e,0x05,0xb0,0xd2,0xab,0x76,0xef, + 0xe5,0xf6,0xe4,0x09,0x02,0x41,0x4b,0x21,0xef,0x76,0x00} + }, + { + /* No.7 delta:3952 weight:825 */ + 11213, + 11, + 15, + 16, + {(0x00000000), + (0xa49b7ddb), + (0xbc75e45f), + (0x18ee9984), + (0x75600076), + (0xd1fb7dad), + (0xc915e429), + (0x6d8e99f2), + (0x0000c4f9), + (0xa49bb922), + (0xbc7520a6), + (0x18ee5d7d), + (0x7560c48f), + (0xd1fbb954), + (0xc91520d0), + (0x6d8e5d0b)}, + {(0x00000000), + (0xf0015000), + (0x0a4c2c00), + (0xfa4d7c00), + (0x0482b000), + (0xf483e000), + (0x0ece9c00), + (0xfecfcc00), + (0x45105e00), + (0xb5110e00), + (0x4f5c7200), + (0xbf5d2200), + (0x4192ee00), + (0xb193be00), + (0x4bdec200), + (0xbbdf9200)}, + {(0x3f800000), + (0x3ff800a8), + (0x3f852616), + (0x3ffd26be), + (0x3f824158), + (0x3ffa41f0), + (0x3f87674e), + (0x3fff67e6), + (0x3fa2882f), + (0x3fda8887), + (0x3fa7ae39), + (0x3fdfae91), + (0x3fa0c977), + (0x3fd8c9df), + (0x3fa5ef61), + (0x3fddefc9)}, + (0xfff80000), + {0xa9,0x6f,0x34,0xf9,0xdd,0xff,0x0a,0x48,0x3c,0x3f, + 0x3e,0x6f,0x74,0x70,0x37,0x33,0x19,0xe4,0x24,0x9b,0x00} + }, + { + /* No.8 delta:4274 weight:1347 */ + 11213, + 42, + 6, + 11, + {(0x00000000), + (0x311b3c94), + (0xa1e0c93f), + (0x90fbf5ab), + (0x3c600082), + (0x0d7b3c16), + (0x9d80c9bd), + (0xac9bf529), + (0x0000b622), + (0x311b8ab6), + (0xa1e07f1d), + (0x90fb4389), + (0x3c60b6a0), + (0x0d7b8a34), + (0x9d807f9f), + (0xac9b430b)}, + {(0x00000000), + (0x80000000), + (0x00000000), + (0x80000000), + (0xc0000000), + (0x40000000), + (0xc0000000), + (0x40000000), + (0x20001e00), + (0xa0001e00), + (0x20001e00), + (0xa0001e00), + (0xe0001e00), + (0x60001e00), + (0xe0001e00), + (0x60001e00)}, + {(0x3f800000), + (0x3fc00000), + (0x3f800000), + (0x3fc00000), + (0x3fe00000), + (0x3fa00000), + (0x3fe00000), + (0x3fa00000), + (0x3f90000f), + (0x3fd0000f), + (0x3f90000f), + (0x3fd0000f), + (0x3ff0000f), + (0x3fb0000f), + (0x3ff0000f), + (0x3fb0000f)}, + (0xfff80000), + {0x3c,0x5a,0x73,0x0e,0xab,0x68,0x32,0x57,0x6f,0xe6, + 0x1d,0x93,0x6e,0xbd,0xef,0x1a,0x6f,0x25,0x1f,0x70,0x00} + }, + { + /* No.9 delta:1902 weight:1001 */ + 11213, + 60, + 6, + 11, + {(0x00000000), + (0xbc8ed6c0), + (0x4d9fbb3d), + (0xf1116dfd), + (0x8e70009d), + (0x32fed65d), + (0xc3efbba0), + (0x7f616d60), + (0x0000a00a), + (0xbc8e76ca), + (0x4d9f1b37), + (0xf111cdf7), + (0x8e70a097), + (0x32fe7657), + (0xc3ef1baa), + (0x7f61cd6a)}, + {(0x00000000), + (0xc0400400), + (0x00220000), + (0xc0620400), + (0x303e0000), + (0xf07e0400), + (0x301c0000), + (0xf05c0400), + (0x40021e00), + (0x80421a00), + (0x40201e00), + (0x80601a00), + (0x703c1e00), + (0xb07c1a00), + (0x701e1e00), + (0xb05e1a00)}, + {(0x3f800000), + (0x3fe02002), + (0x3f801100), + (0x3fe03102), + (0x3f981f00), + (0x3ff83f02), + (0x3f980e00), + (0x3ff82e02), + (0x3fa0010f), + (0x3fc0210d), + (0x3fa0100f), + (0x3fc0300d), + (0x3fb81e0f), + (0x3fd83e0d), + (0x3fb80f0f), + (0x3fd82f0d)}, + (0xfff80000), + {0x83,0x62,0x6c,0x11,0xe4,0x19,0x2b,0x9b,0x87,0x4d, + 0x8e,0x68,0xde,0x69,0x56,0xc5,0x44,0x33,0x4f,0x20,0x00} + }, + { + /* No.10 delta:1148 weight:927 */ + 11213, + 45, + 12, + 13, + {(0x00000000), + (0x06bc3338), + (0xdde8b9f9), + (0xdb548ac1), + (0xfb2000a5), + (0xfd9c339d), + (0x26c8b95c), + (0x20748a64), + (0x0000a4ec), + (0x06bc97d4), + (0xdde81d15), + (0xdb542e2d), + (0xfb20a449), + (0xfd9c9771), + (0x26c81db0), + (0x20742e88)}, + {(0x00000000), + (0x0c494c00), + (0x42040c00), + (0x4e4d4000), + (0x20090800), + (0x2c404400), + (0x620d0400), + (0x6e444800), + (0x10409e00), + (0x1c09d200), + (0x52449200), + (0x5e0dde00), + (0x30499600), + (0x3c00da00), + (0x724d9a00), + (0x7e04d600)}, + {(0x3f800000), + (0x3f8624a6), + (0x3fa10206), + (0x3fa726a0), + (0x3f900484), + (0x3f962022), + (0x3fb10682), + (0x3fb72224), + (0x3f88204f), + (0x3f8e04e9), + (0x3fa92249), + (0x3faf06ef), + (0x3f9824cb), + (0x3f9e006d), + (0x3fb926cd), + (0x3fbf026b)}, + (0xfff80000), + {0xf8,0x39,0x8a,0x36,0x0f,0x90,0x4f,0x3c,0x04,0x0c, + 0x0a,0x02,0xd4,0x04,0x1b,0xc9,0xc4,0x8e,0x15,0x55,0x00} + }, + { + /* No.11 delta:2163 weight:1669 */ + 11213, + 80, + 6, + 9, + {(0x00000000), + (0x247f444d), + (0xb70a5ab0), + (0x93751efd), + (0xc44000b5), + (0xe03f44f8), + (0x734a5a05), + (0x57351e48), + (0x0000554f), + (0x247f1102), + (0xb70a0fff), + (0x93754bb2), + (0xc44055fa), + (0xe03f11b7), + (0x734a0f4a), + (0x57354b07)}, + {(0x00000000), + (0x30200a00), + (0x106c0000), + (0x204c0a00), + (0x00180400), + (0x30380e00), + (0x10740400), + (0x20540e00), + (0x100a1e00), + (0x202a1400), + (0x00661e00), + (0x30461400), + (0x10121a00), + (0x20321000), + (0x007e1a00), + (0x305e1000)}, + {(0x3f800000), + (0x3f981005), + (0x3f883600), + (0x3f902605), + (0x3f800c02), + (0x3f981c07), + (0x3f883a02), + (0x3f902a07), + (0x3f88050f), + (0x3f90150a), + (0x3f80330f), + (0x3f98230a), + (0x3f88090d), + (0x3f901908), + (0x3f803f0d), + (0x3f982f08)}, + (0xfff80000), + {0x98,0xb0,0x30,0x32,0xcf,0x75,0x63,0xeb,0x3a,0xb6, + 0x4f,0x70,0x47,0x4e,0x6a,0xd1,0x7b,0x40,0xbd,0x90,0x00} + }, + { + /* No.12 delta:4985 weight:689 */ + 11213, + 81, + 8, + 18, + {(0x00000000), + (0xcdcab880), + (0xdedf1226), + (0x1315aaa6), + (0xd17000c6), + (0x1cbab846), + (0x0faf12e0), + (0xc265aa60), + (0x0000b647), + (0xcdca0ec7), + (0xdedfa461), + (0x13151ce1), + (0xd170b681), + (0x1cba0e01), + (0x0fafa4a7), + (0xc2651c27)}, + {(0x00000000), + (0x601c0000), + (0x08780000), + (0x68640000), + (0x00740000), + (0x60680000), + (0x080c0000), + (0x68100000), + (0x00a01e00), + (0x60bc1e00), + (0x08d81e00), + (0x68c41e00), + (0x00d41e00), + (0x60c81e00), + (0x08ac1e00), + (0x68b01e00)}, + {(0x3f800000), + (0x3fb00e00), + (0x3f843c00), + (0x3fb43200), + (0x3f803a00), + (0x3fb03400), + (0x3f840600), + (0x3fb40800), + (0x3f80500f), + (0x3fb05e0f), + (0x3f846c0f), + (0x3fb4620f), + (0x3f806a0f), + (0x3fb0640f), + (0x3f84560f), + (0x3fb4580f)}, + (0xfff80000), + {0x90,0xf2,0x51,0xc2,0x2d,0xc4,0x52,0x73,0x15,0xfa, + 0xeb,0xc3,0x64,0x51,0x48,0xf7,0xb1,0x26,0x38,0xb4,0x00} + }, + { + /* No.13 delta:6473 weight:513 */ + 11213, + 16, + 1, + 19, + {(0x00000000), + (0x2310a4f2), + (0x91c8cf8c), + (0xb2d86b7e), + (0x89c000d1), + (0xaad0a423), + (0x1808cf5d), + (0x3b186baf), + (0x0000f299), + (0x2310566b), + (0x91c83d15), + (0xb2d899e7), + (0x89c0f248), + (0xaad056ba), + (0x18083dc4), + (0x3b189936)}, + {(0x00000000), + (0x4c020000), + (0xa6800000), + (0xea820000), + (0x15000000), + (0x59020000), + (0xb3800000), + (0xff820000), + (0x29201e00), + (0x65221e00), + (0x8fa01e00), + (0xc3a21e00), + (0x3c201e00), + (0x70221e00), + (0x9aa01e00), + (0xd6a21e00)}, + {(0x3f800000), + (0x3fa60100), + (0x3fd34000), + (0x3ff54100), + (0x3f8a8000), + (0x3fac8100), + (0x3fd9c000), + (0x3fffc100), + (0x3f94900f), + (0x3fb2910f), + (0x3fc7d00f), + (0x3fe1d10f), + (0x3f9e100f), + (0x3fb8110f), + (0x3fcd500f), + (0x3feb510f)}, + (0xfff80000), + {0x89,0x7c,0x3c,0xc6,0x3d,0x0a,0xad,0xf2,0xa0,0xf5, + 0x0a,0x4c,0x4e,0x83,0xc5,0x45,0xdb,0xcb,0xb5,0x98,0x00} + }, + { + /* No.14 delta:1389 weight:725 */ + 11213, + 63, + 14, + 18, + {(0x00000000), + (0x81c7909c), + (0xecb46b0c), + (0x6d73fb90), + (0xf33000ef), + (0x72f79073), + (0x1f846be3), + (0x9e43fb7f), + (0x0000e902), + (0x81c7799e), + (0xecb4820e), + (0x6d731292), + (0xf330e9ed), + (0x72f77971), + (0x1f8482e1), + (0x9e43127d)}, + {(0x00000000), + (0x09001000), + (0x02010000), + (0x0b011000), + (0x00201800), + (0x09200800), + (0x02211800), + (0x0b210800), + (0x30039e00), + (0x39038e00), + (0x32029e00), + (0x3b028e00), + (0x30238600), + (0x39239600), + (0x32228600), + (0x3b229600)}, + {(0x3f800000), + (0x3f848008), + (0x3f810080), + (0x3f858088), + (0x3f80100c), + (0x3f849004), + (0x3f81108c), + (0x3f859084), + (0x3f9801cf), + (0x3f9c81c7), + (0x3f99014f), + (0x3f9d8147), + (0x3f9811c3), + (0x3f9c91cb), + (0x3f991143), + (0x3f9d914b)}, + (0xfff80000), + {0xb7,0x0b,0xee,0xcb,0xc6,0x29,0x7c,0xe3,0xc5,0x58, + 0x71,0xe7,0x4b,0xe5,0xc9,0x63,0xbd,0xa4,0x75,0xc7,0x00} + }, + { + /* No.15 delta:8365 weight:1135 */ + 11213, + 38, + 28, + 1, + {(0x00000000), + (0xe56c7b3b), + (0x759d951b), + (0x90f1ee20), + (0x1a6000fa), + (0xff0c7bc1), + (0x6ffd95e1), + (0x8a91eeda), + (0x00004474), + (0xe56c3f4f), + (0x759dd16f), + (0x90f1aa54), + (0x1a60448e), + (0xff0c3fb5), + (0x6ffdd195), + (0x8a91aaae)}, + {(0x00000000), + (0xc0410a00), + (0xe70c0400), + (0x274d0e00), + (0xfa3e8000), + (0x3a7f8a00), + (0x1d328400), + (0xdd738e00), + (0x20801e00), + (0xe0c11400), + (0xc78c1a00), + (0x07cd1000), + (0xdabe9e00), + (0x1aff9400), + (0x3db29a00), + (0xfdf39000)}, + {(0x3f800000), + (0x3fe02085), + (0x3ff38602), + (0x3f93a687), + (0x3ffd1f40), + (0x3f9d3fc5), + (0x3f8e9942), + (0x3feeb9c7), + (0x3f90400f), + (0x3ff0608a), + (0x3fe3c60d), + (0x3f83e688), + (0x3fed5f4f), + (0x3f8d7fca), + (0x3f9ed94d), + (0x3ffef9c8)}, + (0xfff80000), + {0xd2,0xa4,0x8f,0xf8,0x54,0x0f,0xe3,0x14,0x17,0xeb, + 0x17,0x78,0x41,0x78,0x69,0xbb,0x4b,0x01,0x85,0x8e,0x00} + }, + { + /* No.16 delta:6253 weight:641 */ + 11213, + 3, + 30, + 2, + {(0x00000000), + (0x83a2a3cb), + (0x52e0a64c), + (0xd1420587), + (0x9850010b), + (0x1bf2a2c0), + (0xcab0a747), + (0x4912048c), + (0x0000aaa5), + (0x83a2096e), + (0x52e00ce9), + (0xd142af22), + (0x9850abae), + (0x1bf20865), + (0xcab00de2), + (0x4912ae29)}, + {(0x00000000), + (0xe9100000), + (0x94d00000), + (0x7dc00000), + (0xdbcc0000), + (0x32dc0000), + (0x4f1c0000), + (0xa60c0000), + (0x09d01e00), + (0xe0c01e00), + (0x9d001e00), + (0x74101e00), + (0xd21c1e00), + (0x3b0c1e00), + (0x46cc1e00), + (0xafdc1e00)}, + {(0x3f800000), + (0x3ff48800), + (0x3fca6800), + (0x3fbee000), + (0x3fede600), + (0x3f996e00), + (0x3fa78e00), + (0x3fd30600), + (0x3f84e80f), + (0x3ff0600f), + (0x3fce800f), + (0x3fba080f), + (0x3fe90e0f), + (0x3f9d860f), + (0x3fa3660f), + (0x3fd7ee0f)}, + (0xfff80000), + {0xa6,0xc6,0x12,0x64,0xaf,0x79,0x40,0x50,0x7b,0xb9, + 0xa9,0xfa,0x9a,0xc0,0x7a,0xaf,0x63,0x83,0x39,0x6c,0x00} + }, + { + /* No.17 delta:5329 weight:467 */ + 11213, + 55, + 1, + 16, + {(0x00000000), + (0x2ce39cc8), + (0x6312ea87), + (0x4ff1764f), + (0x9ef00113), + (0xb2139ddb), + (0xfde2eb94), + (0xd101775c), + (0x00007ddc), + (0x2ce3e114), + (0x6312975b), + (0x4ff10b93), + (0x9ef07ccf), + (0xb213e007), + (0xfde29648), + (0xd1010a80)}, + {(0x00000000), + (0x0c021000), + (0xe3400000), + (0xef421000), + (0x02000000), + (0x0e021000), + (0xe1400000), + (0xed421000), + (0x50a01e00), + (0x5ca20e00), + (0xb3e01e00), + (0xbfe20e00), + (0x52a01e00), + (0x5ea20e00), + (0xb1e01e00), + (0xbde20e00)}, + {(0x3f800000), + (0x3f860108), + (0x3ff1a000), + (0x3ff7a108), + (0x3f810000), + (0x3f870108), + (0x3ff0a000), + (0x3ff6a108), + (0x3fa8500f), + (0x3fae5107), + (0x3fd9f00f), + (0x3fdff107), + (0x3fa9500f), + (0x3faf5107), + (0x3fd8f00f), + (0x3fdef107)}, + (0xfff80000), + {0xe4,0xb8,0x1d,0x0f,0x15,0xe2,0xd6,0xd2,0x30,0x67, + 0x18,0x06,0x38,0xd0,0x63,0x09,0x4d,0xc1,0xaa,0x48,0x00} + }, + { + /* No.18 delta:3046 weight:699 */ + 11213, + 9, + 9, + 15, + {(0x00000000), + (0x228294e5), + (0xc1861e7b), + (0xe3048a9e), + (0x6250012a), + (0x40d295cf), + (0xa3d61f51), + (0x81548bb4), + (0x00005800), + (0x2282cce5), + (0xc186467b), + (0xe304d29e), + (0x6250592a), + (0x40d2cdcf), + (0xa3d64751), + (0x8154d3b4)}, + {(0x00000000), + (0x57910c00), + (0xd07cc400), + (0x87edc800), + (0xa8036800), + (0xff926400), + (0x787fac00), + (0x2feea000), + (0x00521e00), + (0x57c31200), + (0xd02eda00), + (0x87bfd600), + (0xa8517600), + (0xffc07a00), + (0x782db200), + (0x2fbcbe00)}, + {(0x3f800000), + (0x3fabc886), + (0x3fe83e62), + (0x3fc3f6e4), + (0x3fd401b4), + (0x3fffc932), + (0x3fbc3fd6), + (0x3f97f750), + (0x3f80290f), + (0x3fabe189), + (0x3fe8176d), + (0x3fc3dfeb), + (0x3fd428bb), + (0x3fffe03d), + (0x3fbc16d9), + (0x3f97de5f)}, + (0xfff80000), + {0x3d,0xb7,0x41,0x11,0xf8,0x6e,0xe6,0x89,0x71,0x95, + 0x3b,0x7c,0x3a,0x38,0x60,0x12,0x4c,0xec,0xaa,0x83,0x00} + }, + { + /* No.19 delta:786 weight:1431 */ + 11213, + 75, + 17, + 6, + {(0x00000000), + (0x819ee5dc), + (0x4ffaa079), + (0xce6445a5), + (0xe6300137), + (0x67aee4eb), + (0xa9caa14e), + (0x28544492), + (0x00008a74), + (0x819e6fa8), + (0x4ffa2a0d), + (0xce64cfd1), + (0xe6308b43), + (0x67ae6e9f), + (0xa9ca2b3a), + (0x2854cee6)}, + {(0x00000000), + (0x98018000), + (0x20039800), + (0xb8021800), + (0x40104000), + (0xd811c000), + (0x6013d800), + (0xf8125800), + (0x00033e00), + (0x9802be00), + (0x2000a600), + (0xb8012600), + (0x40137e00), + (0xd812fe00), + (0x6010e600), + (0xf8116600)}, + {(0x3f800000), + (0x3fcc00c0), + (0x3f9001cc), + (0x3fdc010c), + (0x3fa00820), + (0x3fec08e0), + (0x3fb009ec), + (0x3ffc092c), + (0x3f80019f), + (0x3fcc015f), + (0x3f900053), + (0x3fdc0093), + (0x3fa009bf), + (0x3fec097f), + (0x3fb00873), + (0x3ffc08b3)}, + (0xfff80000), + {0x90,0xc1,0xc9,0xe7,0xea,0xaf,0xd9,0x5b,0x1f,0x93, + 0x8d,0xcd,0x9b,0xf4,0xbb,0x91,0x58,0xb2,0x03,0x70,0x00} + }, + { + /* No.20 delta:846 weight:909 */ + 11213, + 70, + 15, + 6, + {(0x00000000), + (0xc56d80c5), + (0x4bb862e9), + (0x8ed5e22c), + (0x92e00143), + (0x578d8186), + (0xd95863aa), + (0x1c35e36f), + (0x000095b5), + (0xc56d1570), + (0x4bb8f75c), + (0x8ed57799), + (0x92e094f6), + (0x578d1433), + (0xd958f61f), + (0x1c3576da)}, + {(0x00000000), + (0x20642000), + (0x2530d800), + (0x0554f800), + (0x01a05200), + (0x21c47200), + (0x24908a00), + (0x04f4aa00), + (0x00521e00), + (0x20363e00), + (0x2562c600), + (0x0506e600), + (0x01f24c00), + (0x21966c00), + (0x24c29400), + (0x04a6b400)}, + {(0x3f800000), + (0x3f903210), + (0x3f92986c), + (0x3f82aa7c), + (0x3f80d029), + (0x3f90e239), + (0x3f924845), + (0x3f827a55), + (0x3f80290f), + (0x3f901b1f), + (0x3f92b163), + (0x3f828373), + (0x3f80f926), + (0x3f90cb36), + (0x3f92614a), + (0x3f82535a)}, + (0xfff80000), + {0xd6,0xb1,0xe1,0x27,0x40,0x54,0x48,0x67,0x71,0xe5, + 0x2a,0x38,0xbf,0xa7,0x93,0x82,0x17,0xcd,0x71,0x33,0x00} + }, + { + /* No.21 delta:1909 weight:729 */ + 11213, + 63, + 15, + 17, + {(0x00000000), + (0x3c495454), + (0xf3a1ddf0), + (0xcfe889a4), + (0x1b200159), + (0x2769550d), + (0xe881dca9), + (0xd4c888fd), + (0x0000cd3b), + (0x3c49996f), + (0xf3a110cb), + (0xcfe8449f), + (0x1b20cc62), + (0x27699836), + (0xe8811192), + (0xd4c845c6)}, + {(0x00000000), + (0x08027000), + (0x9651d400), + (0x9e53a400), + (0x0040a400), + (0x0842d400), + (0x96117000), + (0x9e130000), + (0x006e9e00), + (0x086cee00), + (0x963f4a00), + (0x9e3d3a00), + (0x002e3a00), + (0x082c4a00), + (0x967fee00), + (0x9e7d9e00)}, + {(0x3f800000), + (0x3f840138), + (0x3fcb28ea), + (0x3fcf29d2), + (0x3f802052), + (0x3f84216a), + (0x3fcb08b8), + (0x3fcf0980), + (0x3f80374f), + (0x3f843677), + (0x3fcb1fa5), + (0x3fcf1e9d), + (0x3f80171d), + (0x3f841625), + (0x3fcb3ff7), + (0x3fcf3ecf)}, + (0xfff80000), + {0xc8,0xdc,0x70,0x0a,0x23,0xa5,0x20,0x35,0xa2,0xd7, + 0xd1,0x53,0xfc,0xe0,0xc1,0xde,0xc0,0x2b,0x65,0x4d,0x00} + }, + { + /* No.22 delta:2420 weight:985 */ + 11213, + 32, + 7, + 15, + {(0x00000000), + (0xd25d9ecf), + (0xb1288d77), + (0x637513b8), + (0xc3700160), + (0x112d9faf), + (0x72588c17), + (0xa00512d8), + (0x000093d5), + (0xd25d0d1a), + (0xb1281ea2), + (0x6375806d), + (0xc37092b5), + (0x112d0c7a), + (0x72581fc2), + (0xa005810d)}, + {(0x00000000), + (0x10134200), + (0x028b0000), + (0x12984200), + (0x50480000), + (0x405b4200), + (0x52c30000), + (0x42d04200), + (0x10ee5e00), + (0x00fd1c00), + (0x12655e00), + (0x02761c00), + (0x40a65e00), + (0x50b51c00), + (0x422d5e00), + (0x523e1c00)}, + {(0x3f800000), + (0x3f8809a1), + (0x3f814580), + (0x3f894c21), + (0x3fa82400), + (0x3fa02da1), + (0x3fa96180), + (0x3fa16821), + (0x3f88772f), + (0x3f807e8e), + (0x3f8932af), + (0x3f813b0e), + (0x3fa0532f), + (0x3fa85a8e), + (0x3fa116af), + (0x3fa91f0e)}, + (0xfff80000), + {0xd0,0xc2,0xd1,0x3e,0x09,0x41,0xc7,0x9c,0x09,0x33, + 0x25,0x5f,0x84,0x21,0xc4,0xcc,0xc5,0x43,0x2a,0x14,0x00} + }, + { + /* No.23 delta:985 weight:863 */ + 11213, + 70, + 12, + 10, + {(0x00000000), + (0x6e6163b2), + (0xa3cecdea), + (0xcdafae58), + (0xb670017d), + (0xd81162cf), + (0x15becc97), + (0x7bdfaf25), + (0x0000d554), + (0x6e61b6e6), + (0xa3ce18be), + (0xcdaf7b0c), + (0xb670d429), + (0xd811b79b), + (0x15be19c3), + (0x7bdf7a71)}, + {(0x00000000), + (0x0338d800), + (0x00545800), + (0x036c8000), + (0x01521000), + (0x026ac800), + (0x01064800), + (0x023e9000), + (0x0020de00), + (0x03180600), + (0x00748600), + (0x034c5e00), + (0x0172ce00), + (0x024a1600), + (0x01269600), + (0x021e4e00)}, + {(0x3f800000), + (0x3f819c6c), + (0x3f802a2c), + (0x3f81b640), + (0x3f80a908), + (0x3f813564), + (0x3f808324), + (0x3f811f48), + (0x3f80106f), + (0x3f818c03), + (0x3f803a43), + (0x3f81a62f), + (0x3f80b967), + (0x3f81250b), + (0x3f80934b), + (0x3f810f27)}, + (0xfff80000), + {0x57,0xda,0x1e,0x1e,0x0f,0xc1,0x5c,0xac,0x32,0x8f, + 0xe4,0x94,0x24,0xf0,0x86,0x24,0x1b,0xde,0x44,0x16,0x00} + }, + { + /* No.24 delta:1573 weight:1043 */ + 11213, + 58, + 21, + 2, + {(0x00000000), + (0xa6c80c3d), + (0x3502d818), + (0x93cad425), + (0xda700189), + (0x7cb80db4), + (0xef72d991), + (0x49bad5ac), + (0x0000cb8c), + (0xa6c8c7b1), + (0x35021394), + (0x93ca1fa9), + (0xda70ca05), + (0x7cb8c638), + (0xef72121d), + (0x49ba1e20)}, + {(0x00000000), + (0xd66f0400), + (0x014ca600), + (0xd723a200), + (0x00442a00), + (0xd62b2e00), + (0x01088c00), + (0xd7678800), + (0x0c835e00), + (0xdaec5a00), + (0x0dcff800), + (0xdba0fc00), + (0x0cc77400), + (0xdaa87000), + (0x0d8bd200), + (0xdbe4d600)}, + {(0x3f800000), + (0x3feb3782), + (0x3f80a653), + (0x3feb91d1), + (0x3f802215), + (0x3feb1597), + (0x3f808446), + (0x3febb3c4), + (0x3f8641af), + (0x3fed762d), + (0x3f86e7fc), + (0x3fedd07e), + (0x3f8663ba), + (0x3fed5438), + (0x3f86c5e9), + (0x3fedf26b)}, + (0xfff80000), + {0xd3,0x5b,0x43,0x3f,0x00,0x55,0xf8,0x40,0xfe,0x8f, + 0xd0,0xe0,0xac,0x48,0x50,0xf2,0x50,0x2a,0xb7,0xcf,0x00} + }, + { + /* No.25 delta:1860 weight:1169 */ + 11213, + 33, + 7, + 10, + {(0x00000000), + (0x3f9ccf17), + (0xcdd7a2a1), + (0xf24b6db6), + (0xf9c00195), + (0xc65cce82), + (0x3417a334), + (0x0b8b6c23), + (0x00006c32), + (0x3f9ca325), + (0xcdd7ce93), + (0xf24b0184), + (0xf9c06da7), + (0xc65ca2b0), + (0x3417cf06), + (0x0b8b0011)}, + {(0x00000000), + (0x043a0400), + (0x00714000), + (0x044b4400), + (0x10408400), + (0x147a8000), + (0x1031c400), + (0x140bc000), + (0x70049e00), + (0x743e9a00), + (0x7075de00), + (0x744fda00), + (0x60441a00), + (0x647e1e00), + (0x60355a00), + (0x640f5e00)}, + {(0x3f800000), + (0x3f821d02), + (0x3f8038a0), + (0x3f8225a2), + (0x3f882042), + (0x3f8a3d40), + (0x3f8818e2), + (0x3f8a05e0), + (0x3fb8024f), + (0x3fba1f4d), + (0x3fb83aef), + (0x3fba27ed), + (0x3fb0220d), + (0x3fb23f0f), + (0x3fb01aad), + (0x3fb207af)}, + (0xfff80000), + {0x6f,0x6a,0x15,0x14,0x9e,0x4e,0xca,0xcd,0xe1,0xfb, + 0x26,0x23,0xa0,0xa9,0x21,0x22,0xca,0x8c,0x68,0x8f,0x00} + }, + { + /* No.26 delta:2274 weight:1019 */ + 11213, + 18, + 7, + 13, + {(0x00000000), + (0x83f4f835), + (0x34e8f3fa), + (0xb71c0bcf), + (0xf21001a3), + (0x71e4f996), + (0xc6f8f259), + (0x450c0a6c), + (0x00009d49), + (0x83f4657c), + (0x34e86eb3), + (0xb71c9686), + (0xf2109cea), + (0x71e464df), + (0xc6f86f10), + (0x450c9725)}, + {(0x00000000), + (0x69050000), + (0x0b0a1800), + (0x620f1800), + (0x41a06000), + (0x28a56000), + (0x4aaa7800), + (0x23af7800), + (0x046b1e00), + (0x6d6e1e00), + (0x0f610600), + (0x66640600), + (0x45cb7e00), + (0x2cce7e00), + (0x4ec16600), + (0x27c46600)}, + {(0x3f800000), + (0x3fb48280), + (0x3f85850c), + (0x3fb1078c), + (0x3fa0d030), + (0x3f9452b0), + (0x3fa5553c), + (0x3f91d7bc), + (0x3f82358f), + (0x3fb6b70f), + (0x3f87b083), + (0x3fb33203), + (0x3fa2e5bf), + (0x3f96673f), + (0x3fa760b3), + (0x3f93e233)}, + (0xfff80000), + {0x6c,0xda,0xe3,0x3d,0xac,0x72,0x40,0x41,0xca,0xa3, + 0xf7,0xdf,0xff,0x2d,0x57,0xea,0x1f,0x8d,0x6c,0x04,0x00} + }, + { + /* No.27 delta:2503 weight:711 */ + 11213, + 9, + 12, + 13, + {(0x00000000), + (0xc54f7f87), + (0x6904a950), + (0xac4bd6d7), + (0x85c001bc), + (0x408f7e3b), + (0xecc4a8ec), + (0x298bd76b), + (0x00007b77), + (0xc54f04f0), + (0x6904d227), + (0xac4bada0), + (0x85c07acb), + (0x408f054c), + (0xecc4d39b), + (0x298bac1c)}, + {(0x00000000), + (0xc7002c00), + (0x5a61c800), + (0x9d61e400), + (0x12013800), + (0xd5011400), + (0x4860f000), + (0x8f60dc00), + (0xc8c01e00), + (0x0fc03200), + (0x92a1d600), + (0x55a1fa00), + (0xdac12600), + (0x1dc10a00), + (0x80a0ee00), + (0x47a0c200)}, + {(0x3f800000), + (0x3fe38016), + (0x3fad30e4), + (0x3fceb0f2), + (0x3f89009c), + (0x3fea808a), + (0x3fa43078), + (0x3fc7b06e), + (0x3fe4600f), + (0x3f87e019), + (0x3fc950eb), + (0x3faad0fd), + (0x3fed6093), + (0x3f8ee085), + (0x3fc05077), + (0x3fa3d061)}, + (0xfff80000), + {0xd6,0xd3,0xee,0x8e,0x9a,0x94,0x64,0x4c,0x3a,0x7b, + 0x1d,0x2f,0x64,0xef,0x67,0x33,0x0d,0x49,0x2e,0x20,0x00} + }, + { + /* No.28 delta:1642 weight:1597 */ + 11213, + 14, + 16, + 3, + {(0x00000000), + (0x8147d21a), + (0x627aba0f), + (0xe33d6815), + (0x279001c1), + (0xa6d7d3db), + (0x45eabbce), + (0xc4ad69d4), + (0x0000f4d1), + (0x814726cb), + (0x627a4ede), + (0xe33d9cc4), + (0x2790f510), + (0xa6d7270a), + (0x45ea4f1f), + (0xc4ad9d05)}, + {(0x00000000), + (0x210c6a00), + (0x0071b800), + (0x217dd200), + (0xcc021a00), + (0xed0e7000), + (0xcc73a200), + (0xed7fc800), + (0x41b2de00), + (0x60beb400), + (0x41c36600), + (0x60cf0c00), + (0x8db0c400), + (0xacbcae00), + (0x8dc17c00), + (0xaccd1600)}, + {(0x3f800000), + (0x3f908635), + (0x3f8038dc), + (0x3f90bee9), + (0x3fe6010d), + (0x3ff68738), + (0x3fe639d1), + (0x3ff6bfe4), + (0x3fa0d96f), + (0x3fb05f5a), + (0x3fa0e1b3), + (0x3fb06786), + (0x3fc6d862), + (0x3fd65e57), + (0x3fc6e0be), + (0x3fd6668b)}, + (0xfff80000), + {0x58,0xce,0x35,0x39,0xc0,0x04,0xad,0xd6,0xdd,0xb7, + 0x5d,0xf1,0xac,0xf9,0x85,0xea,0x3f,0x74,0x52,0x6d,0x00} + }, + { + /* No.29 delta:1888 weight:1763 */ + 11213, + 91, + 4, + 2, + {(0x00000000), + (0xa620066e), + (0x498ca8fb), + (0xefacae95), + (0xc3f001d3), + (0x65d007bd), + (0x8a7ca928), + (0x2c5caf46), + (0x0000927c), + (0xa6209412), + (0x498c3a87), + (0xefac3ce9), + (0xc3f093af), + (0x65d095c1), + (0x8a7c3b54), + (0x2c5c3d3a)}, + {(0x00000000), + (0x29909200), + (0x0074c600), + (0x29e45400), + (0x400e7000), + (0x699ee200), + (0x407ab600), + (0x69ea2400), + (0x44029e00), + (0x6d920c00), + (0x44765800), + (0x6de6ca00), + (0x040cee00), + (0x2d9c7c00), + (0x04782800), + (0x2de8ba00)}, + {(0x3f800000), + (0x3f94c849), + (0x3f803a63), + (0x3f94f22a), + (0x3fa00738), + (0x3fb4cf71), + (0x3fa03d5b), + (0x3fb4f512), + (0x3fa2014f), + (0x3fb6c906), + (0x3fa23b2c), + (0x3fb6f365), + (0x3f820677), + (0x3f96ce3e), + (0x3f823c14), + (0x3f96f45d)}, + (0xfff80000), + {0xbf,0x14,0xa8,0x90,0x29,0x75,0x15,0xde,0x68,0x12, + 0x39,0xb3,0x6e,0x2f,0xcb,0x19,0x1f,0xe6,0x2c,0x9b,0x00} + }, + { + /* No.30 delta:1194 weight:873 */ + 11213, + 90, + 10, + 14, + {(0x00000000), + (0xdd216696), + (0x738a5c01), + (0xaeab3a97), + (0x402001ec), + (0x9d01677a), + (0x33aa5ded), + (0xee8b3b7b), + (0x0000c5c9), + (0xdd21a35f), + (0x738a99c8), + (0xaeabff5e), + (0x4020c425), + (0x9d01a2b3), + (0x33aa9824), + (0xee8bfeb2)}, + {(0x00000000), + (0x193a0000), + (0x07a49000), + (0x1e9e9000), + (0x00658800), + (0x195f8800), + (0x07c11800), + (0x1efb1800), + (0x4456fe00), + (0x5d6cfe00), + (0x43f26e00), + (0x5ac86e00), + (0x44337600), + (0x5d097600), + (0x4397e600), + (0x5aade600)}, + {(0x3f800000), + (0x3f8c9d00), + (0x3f83d248), + (0x3f8f4f48), + (0x3f8032c4), + (0x3f8cafc4), + (0x3f83e08c), + (0x3f8f7d8c), + (0x3fa22b7f), + (0x3faeb67f), + (0x3fa1f937), + (0x3fad6437), + (0x3fa219bb), + (0x3fae84bb), + (0x3fa1cbf3), + (0x3fad56f3)}, + (0xfff80000), + {0x45,0xbe,0xc0,0x65,0xca,0x28,0x44,0x0e,0x06,0x4e, + 0xa0,0xbf,0x48,0xa8,0x8e,0x39,0x64,0x68,0xe1,0x30,0x00} + }, + { + /* No.31 delta:1509 weight:1313 */ + 11213, + 86, + 6, + 7, + {(0x00000000), + (0x41d73f34), + (0x0930d7f4), + (0x48e7e8c0), + (0x65b001f9), + (0x24673ecd), + (0x6c80d60d), + (0x2d57e939), + (0x00008ad2), + (0x41d7b5e6), + (0x09305d26), + (0x48e76212), + (0x65b08b2b), + (0x2467b41f), + (0x6c805cdf), + (0x2d5763eb)}, + {(0x00000000), + (0x02010000), + (0x10332000), + (0x12322000), + (0x10030000), + (0x12020000), + (0x00302000), + (0x02312000), + (0x403a9e00), + (0x423b9e00), + (0x5009be00), + (0x5208be00), + (0x50399e00), + (0x52389e00), + (0x400abe00), + (0x420bbe00)}, + {(0x3f800000), + (0x3f810080), + (0x3f881990), + (0x3f891910), + (0x3f880180), + (0x3f890100), + (0x3f801810), + (0x3f811890), + (0x3fa01d4f), + (0x3fa11dcf), + (0x3fa804df), + (0x3fa9045f), + (0x3fa81ccf), + (0x3fa91c4f), + (0x3fa0055f), + (0x3fa105df)}, + (0xfff80000), + {0x9f,0xb2,0x3a,0xbb,0xab,0xbd,0xc1,0x43,0x82,0x94, + 0x1f,0x8e,0xdf,0x89,0xbb,0xf6,0xee,0x6a,0x10,0x54,0x00} + }, + { + /* No.32 delta:3454 weight:869 */ + 11213, + 36, + 3, + 15, + {(0x00000000), + (0x1709ea04), + (0x8e9b8c43), + (0x99926647), + (0xdd100203), + (0xca19e807), + (0x538b8e40), + (0x44826444), + (0x0000f3b3), + (0x170919b7), + (0x8e9b7ff0), + (0x999295f4), + (0xdd10f1b0), + (0xca191bb4), + (0x538b7df3), + (0x448297f7)}, + {(0x00000000), + (0x28228000), + (0x1fc10000), + (0x37e38000), + (0x00400000), + (0x28628000), + (0x1f810000), + (0x37a38000), + (0x12b01e00), + (0x3a929e00), + (0x0d711e00), + (0x25539e00), + (0x12f01e00), + (0x3ad29e00), + (0x0d311e00), + (0x25139e00)}, + {(0x3f800000), + (0x3f941140), + (0x3f8fe080), + (0x3f9bf1c0), + (0x3f802000), + (0x3f943140), + (0x3f8fc080), + (0x3f9bd1c0), + (0x3f89580f), + (0x3f9d494f), + (0x3f86b88f), + (0x3f92a9cf), + (0x3f89780f), + (0x3f9d694f), + (0x3f86988f), + (0x3f9289cf)}, + (0xfff80000), + {0xbd,0x88,0xcf,0x70,0x9b,0x4f,0x1b,0xe7,0xe6,0xab, + 0x62,0x27,0x66,0xaf,0x36,0xbb,0x10,0x8b,0x27,0xd7,0x00} + }, + { + /* No.33 delta:1105 weight:1263 */ + 11213, + 40, + 9, + 3, + {(0x00000000), + (0x4406f6da), + (0xf592d5cb), + (0xb1942311), + (0xe0900211), + (0xa496f4cb), + (0x1502d7da), + (0x51042100), + (0x0000075b), + (0x4406f181), + (0xf592d290), + (0xb194244a), + (0xe090054a), + (0xa496f390), + (0x1502d081), + (0x5104265b)}, + {(0x00000000), + (0x10151000), + (0x10640000), + (0x00711000), + (0x20081800), + (0x301d0800), + (0x306c1800), + (0x20790800), + (0x00025e00), + (0x10174e00), + (0x10665e00), + (0x00734e00), + (0x200a4600), + (0x301f5600), + (0x306e4600), + (0x207b5600)}, + {(0x3f800000), + (0x3f880a88), + (0x3f883200), + (0x3f803888), + (0x3f90040c), + (0x3f980e84), + (0x3f98360c), + (0x3f903c84), + (0x3f80012f), + (0x3f880ba7), + (0x3f88332f), + (0x3f8039a7), + (0x3f900523), + (0x3f980fab), + (0x3f983723), + (0x3f903dab)}, + (0xfff80000), + {0x13,0x48,0x32,0x45,0xca,0x30,0xd6,0xa0,0xae,0xd3, + 0x68,0x38,0x03,0x61,0x73,0x81,0x24,0xd8,0x43,0xf3,0x00} + }, + { + /* No.34 delta:7663 weight:713 */ + 11213, + 62, + 2, + 15, + {(0x00000000), + (0x9fe7bf95), + (0x7e1ef3d4), + (0xe1f94c41), + (0x32e00221), + (0xad07bdb4), + (0x4cfef1f5), + (0xd3194e60), + (0x00005fc6), + (0x9fe7e053), + (0x7e1eac12), + (0xe1f91387), + (0x32e05de7), + (0xad07e272), + (0x4cfeae33), + (0xd31911a6)}, + {(0x00000000), + (0x00000000), + (0x00000000), + (0x00000000), + (0x20000000), + (0x20000000), + (0x20000000), + (0x20000000), + (0x50001e00), + (0x50001e00), + (0x50001e00), + (0x50001e00), + (0x70001e00), + (0x70001e00), + (0x70001e00), + (0x70001e00)}, + {(0x3f800000), + (0x3f800000), + (0x3f800000), + (0x3f800000), + (0x3f900000), + (0x3f900000), + (0x3f900000), + (0x3f900000), + (0x3fa8000f), + (0x3fa8000f), + (0x3fa8000f), + (0x3fa8000f), + (0x3fb8000f), + (0x3fb8000f), + (0x3fb8000f), + (0x3fb8000f)}, + (0xfff80000), + {0x05,0x3c,0xe6,0xed,0x20,0xd0,0x5e,0x82,0xc3,0x47, + 0x89,0x62,0x9a,0x00,0x4f,0xdf,0x8a,0xe2,0x89,0xe4,0x00} + }, + { + /* No.35 delta:1045 weight:1387 */ + 11213, + 66, + 18, + 8, + {(0x00000000), + (0xcc054daa), + (0x64ce00f1), + (0xa8cb4d5b), + (0xc6200238), + (0x0a254f92), + (0xa2ee02c9), + (0x6eeb4f63), + (0x00006fce), + (0xcc052264), + (0x64ce6f3f), + (0xa8cb2295), + (0xc6206df6), + (0x0a25205c), + (0xa2ee6d07), + (0x6eeb20ad)}, + {(0x00000000), + (0xd07d1a00), + (0x08927800), + (0xd8ef6200), + (0x00a4c000), + (0xd0d9da00), + (0x0836b800), + (0xd84ba200), + (0x00025e00), + (0xd07f4400), + (0x08902600), + (0xd8ed3c00), + (0x00a69e00), + (0xd0db8400), + (0x0834e600), + (0xd849fc00)}, + {(0x3f800000), + (0x3fe83e8d), + (0x3f84493c), + (0x3fec77b1), + (0x3f805260), + (0x3fe86ced), + (0x3f841b5c), + (0x3fec25d1), + (0x3f80012f), + (0x3fe83fa2), + (0x3f844813), + (0x3fec769e), + (0x3f80534f), + (0x3fe86dc2), + (0x3f841a73), + (0x3fec24fe)}, + (0xfff80000), + {0x53,0xdb,0x48,0x5e,0x80,0xb8,0xf7,0x7d,0xd4,0x43, + 0xc8,0x11,0x1f,0x88,0x87,0x4f,0x05,0x24,0x64,0x44,0x00} + }, + { + /* No.36 delta:2076 weight:1703 */ + 11213, + 75, + 9, + 2, + {(0x00000000), + (0xc42d5e09), + (0x3ecbb703), + (0xfae6e90a), + (0xe9b00243), + (0x2d9d5c4a), + (0xd77bb540), + (0x1356eb49), + (0x00003832), + (0xc42d663b), + (0x3ecb8f31), + (0xfae6d138), + (0xe9b03a71), + (0x2d9d6478), + (0xd77b8d72), + (0x1356d37b)}, + {(0x00000000), + (0x003c8000), + (0x00700000), + (0x004c8000), + (0x00080000), + (0x00348000), + (0x00780000), + (0x00448000), + (0x00021e00), + (0x003e9e00), + (0x00721e00), + (0x004e9e00), + (0x000a1e00), + (0x00369e00), + (0x007a1e00), + (0x00469e00)}, + {(0x3f800000), + (0x3f801e40), + (0x3f803800), + (0x3f802640), + (0x3f800400), + (0x3f801a40), + (0x3f803c00), + (0x3f802240), + (0x3f80010f), + (0x3f801f4f), + (0x3f80390f), + (0x3f80274f), + (0x3f80050f), + (0x3f801b4f), + (0x3f803d0f), + (0x3f80234f)}, + (0xfff80000), + {0x83,0xeb,0x26,0xe2,0x25,0xfd,0x8b,0x40,0xfc,0xd8, + 0x09,0x63,0xa1,0xb0,0x60,0x56,0xec,0x05,0xc2,0x27,0x00} + }, + { + /* No.37 delta:2017 weight:1375 */ + 11213, + 20, + 23, + 4, + {(0x00000000), + (0xf3dee608), + (0x43968c18), + (0xb0486a10), + (0x82100252), + (0x71cee45a), + (0xc1868e4a), + (0x32586842), + (0x0000b8e9), + (0xf3de5ee1), + (0x439634f1), + (0xb048d2f9), + (0x8210babb), + (0x71ce5cb3), + (0xc18636a3), + (0x3258d0ab)}, + {(0x00000000), + (0x0f350000), + (0x08b40000), + (0x07810000), + (0x20c1a000), + (0x2ff4a000), + (0x2875a000), + (0x2740a000), + (0x201c1e00), + (0x2f291e00), + (0x28a81e00), + (0x279d1e00), + (0x00ddbe00), + (0x0fe8be00), + (0x0869be00), + (0x075cbe00)}, + {(0x3f800000), + (0x3f879a80), + (0x3f845a00), + (0x3f83c080), + (0x3f9060d0), + (0x3f97fa50), + (0x3f943ad0), + (0x3f93a050), + (0x3f900e0f), + (0x3f97948f), + (0x3f94540f), + (0x3f93ce8f), + (0x3f806edf), + (0x3f87f45f), + (0x3f8434df), + (0x3f83ae5f)}, + (0xfff80000), + {0x64,0x1e,0x04,0xb6,0x86,0x5e,0xd5,0x07,0x5c,0xb3, + 0xbe,0x3a,0x1b,0xc8,0xe4,0x45,0x9e,0xc4,0xcf,0x11,0x00} + }, + { + /* No.38 delta:2221 weight:1197 */ + 11213, + 37, + 24, + 7, + {(0x00000000), + (0x4fb7bfce), + (0x968c3f7b), + (0xd93b80b5), + (0x11300267), + (0x5e87bda9), + (0x87bc3d1c), + (0xc80b82d2), + (0x000002b3), + (0x4fb7bd7d), + (0x968c3dc8), + (0xd93b8206), + (0x113000d4), + (0x5e87bf1a), + (0x87bc3faf), + (0xc80b8061)}, + {(0x00000000), + (0x207f2400), + (0x0138c000), + (0x2147e400), + (0x00160000), + (0x20692400), + (0x012ec000), + (0x2151e400), + (0x30127e00), + (0x106d5a00), + (0x312abe00), + (0x11559a00), + (0x30047e00), + (0x107b5a00), + (0x313cbe00), + (0x11439a00)}, + {(0x3f800000), + (0x3f903f92), + (0x3f809c60), + (0x3f90a3f2), + (0x3f800b00), + (0x3f903492), + (0x3f809760), + (0x3f90a8f2), + (0x3f98093f), + (0x3f8836ad), + (0x3f98955f), + (0x3f88aacd), + (0x3f98023f), + (0x3f883dad), + (0x3f989e5f), + (0x3f88a1cd)}, + (0xfff80000), + {0x56,0x6e,0x0e,0xb6,0x39,0x79,0xe8,0x2f,0xdb,0x3a, + 0xb8,0xa6,0xb7,0x15,0xb4,0x26,0x23,0x62,0x6c,0x7b,0x00} + }, + { + /* No.39 delta:3255 weight:871 */ + 11213, + 59, + 27, + 3, + {(0x00000000), + (0xd9be1e48), + (0x75016ef8), + (0xacbf70b0), + (0x0e00027a), + (0xd7be1c32), + (0x7b016c82), + (0xa2bf72ca), + (0x00004209), + (0xd9be5c41), + (0x75012cf1), + (0xacbf32b9), + (0x0e004073), + (0xd7be5e3b), + (0x7b012e8b), + (0xa2bf30c3)}, + {(0x00000000), + (0x14ad8000), + (0x05013000), + (0x11acb000), + (0x092e2000), + (0x1d83a000), + (0x0c2f1000), + (0x18829000), + (0x07501e00), + (0x13fd9e00), + (0x02512e00), + (0x16fcae00), + (0x0e7e3e00), + (0x1ad3be00), + (0x0b7f0e00), + (0x1fd28e00)}, + {(0x3f800000), + (0x3f8a56c0), + (0x3f828098), + (0x3f88d658), + (0x3f849710), + (0x3f8ec1d0), + (0x3f861788), + (0x3f8c4148), + (0x3f83a80f), + (0x3f89fecf), + (0x3f812897), + (0x3f8b7e57), + (0x3f873f1f), + (0x3f8d69df), + (0x3f85bf87), + (0x3f8fe947)}, + (0xfff80000), + {0xde,0x46,0xf8,0xe9,0xab,0x16,0xb9,0x71,0xfd,0x07, + 0x49,0x31,0xbb,0x29,0xb9,0xce,0xd3,0x1e,0x43,0x2e,0x00} + }, + { + /* No.40 delta:3532 weight:1325 */ + 11213, + 8, + 11, + 4, + {(0x00000000), + (0xe314ffbd), + (0x98f9b31f), + (0x7bed4ca2), + (0x71b0028c), + (0x92a4fd31), + (0xe949b193), + (0x0a5d4e2e), + (0x0000e823), + (0xe314179e), + (0x98f95b3c), + (0x7beda481), + (0x71b0eaaf), + (0x92a41512), + (0xe94959b0), + (0x0a5da60d)}, + {(0x00000000), + (0x0c000000), + (0x0a800000), + (0x06800000), + (0x16100000), + (0x1a100000), + (0x1c900000), + (0x10900000), + (0x95801e00), + (0x99801e00), + (0x9f001e00), + (0x93001e00), + (0x83901e00), + (0x8f901e00), + (0x89101e00), + (0x85101e00)}, + {(0x3f800000), + (0x3f860000), + (0x3f854000), + (0x3f834000), + (0x3f8b0800), + (0x3f8d0800), + (0x3f8e4800), + (0x3f884800), + (0x3fcac00f), + (0x3fccc00f), + (0x3fcf800f), + (0x3fc9800f), + (0x3fc1c80f), + (0x3fc7c80f), + (0x3fc4880f), + (0x3fc2880f)}, + (0xfff80000), + {0xc3,0xa5,0xf2,0x8c,0xb3,0x3e,0xd2,0x53,0x92,0x0c, + 0x01,0x4a,0x5c,0x0a,0x47,0xe9,0x85,0xa2,0xf5,0x7f,0x00} + }, + { + /* No.41 delta:5222 weight:1281 */ + 11213, + 90, + 27, + 2, + {(0x00000000), + (0xf1807db4), + (0x9f84df41), + (0x6e04a2f5), + (0x04200296), + (0xf5a07f22), + (0x9ba4ddd7), + (0x6a24a063), + (0x00005700), + (0xf1802ab4), + (0x9f848841), + (0x6e04f5f5), + (0x04205596), + (0xf5a02822), + (0x9ba48ad7), + (0x6a24f763)}, + {(0x00000000), + (0xe9519000), + (0x1a06a800), + (0xf3573800), + (0x0d032000), + (0xe452b000), + (0x17058800), + (0xfe541800), + (0x036ade00), + (0xea3b4e00), + (0x196c7600), + (0xf03de600), + (0x0e69fe00), + (0xe7386e00), + (0x146f5600), + (0xfd3ec600)}, + {(0x3f800000), + (0x3ff4a8c8), + (0x3f8d0354), + (0x3ff9ab9c), + (0x3f868190), + (0x3ff22958), + (0x3f8b82c4), + (0x3fff2a0c), + (0x3f81b56f), + (0x3ff51da7), + (0x3f8cb63b), + (0x3ff81ef3), + (0x3f8734ff), + (0x3ff39c37), + (0x3f8a37ab), + (0x3ffe9f63)}, + (0xfff80000), + {0x08,0x0d,0xba,0x61,0x69,0x6b,0x70,0x44,0xbf,0x27, + 0x4a,0xe9,0xcb,0x98,0x26,0xb9,0xb3,0x5d,0x82,0x3d,0x00} + }, + { + /* No.42 delta:1107 weight:1153 */ + 11213, + 48, + 16, + 10, + {(0x00000000), + (0x6adad7b8), + (0x649ee9f9), + (0x0e443e41), + (0x1b2002a0), + (0x71fad518), + (0x7fbeeb59), + (0x15643ce1), + (0x0000f400), + (0x6ada23b8), + (0x649e1df9), + (0x0e44ca41), + (0x1b20f6a0), + (0x71fa2118), + (0x7fbe1f59), + (0x1564c8e1)}, + {(0x00000000), + (0x09409c00), + (0x0060c000), + (0x09205c00), + (0x04104a00), + (0x0d50d600), + (0x04708a00), + (0x0d301600), + (0x00087e00), + (0x0948e200), + (0x0068be00), + (0x09282200), + (0x04183400), + (0x0d58a800), + (0x0478f400), + (0x0d386800)}, + {(0x3f800000), + (0x3f84a04e), + (0x3f803060), + (0x3f84902e), + (0x3f820825), + (0x3f86a86b), + (0x3f823845), + (0x3f86980b), + (0x3f80043f), + (0x3f84a471), + (0x3f80345f), + (0x3f849411), + (0x3f820c1a), + (0x3f86ac54), + (0x3f823c7a), + (0x3f869c34)}, + (0xfff80000), + {0xb4,0xff,0xa8,0x22,0xa3,0x34,0x7b,0xfd,0xd4,0xca, + 0xef,0x82,0x97,0x4e,0x9d,0x89,0xeb,0xb2,0x55,0x2c,0x00} + }, + { + /* No.43 delta:3289 weight:739 */ + 11213, + 90, + 3, + 15, + {(0x00000000), + (0x12510afd), + (0xc2094a89), + (0xd0584074), + (0x5ce002b7), + (0x4eb1084a), + (0x9ee9483e), + (0x8cb842c3), + (0x00009dee), + (0x12519713), + (0xc209d767), + (0xd058dd9a), + (0x5ce09f59), + (0x4eb195a4), + (0x9ee9d5d0), + (0x8cb8df2d)}, + {(0x00000000), + (0x0c230400), + (0x033c0000), + (0x0f1f0400), + (0x03b08000), + (0x0f938400), + (0x008c8000), + (0x0caf8400), + (0x08705e00), + (0x04535a00), + (0x0b4c5e00), + (0x076f5a00), + (0x0bc0de00), + (0x07e3da00), + (0x08fcde00), + (0x04dfda00)}, + {(0x3f800000), + (0x3f861182), + (0x3f819e00), + (0x3f878f82), + (0x3f81d840), + (0x3f87c9c2), + (0x3f804640), + (0x3f8657c2), + (0x3f84382f), + (0x3f8229ad), + (0x3f85a62f), + (0x3f83b7ad), + (0x3f85e06f), + (0x3f83f1ed), + (0x3f847e6f), + (0x3f826fed)}, + (0xfff80000), + {0x47,0xd8,0xbd,0x66,0xb2,0xe8,0x3c,0x2c,0x45,0x90, + 0x88,0x27,0x9c,0x8f,0x27,0x40,0xc8,0xd9,0x0e,0xd6,0x00} + }, + { + /* No.44 delta:1477 weight:1191 */ + 11213, + 33, + 20, + 2, + {(0x00000000), + (0x3f4d49c2), + (0xdca457bf), + (0xe3e91e7d), + (0x5d5002cf), + (0x621d4b0d), + (0x81f45570), + (0xbeb91cb2), + (0x0000c277), + (0x3f4d8bb5), + (0xdca495c8), + (0xe3e9dc0a), + (0x5d50c0b8), + (0x621d897a), + (0x81f49707), + (0xbeb9dec5)}, + {(0x00000000), + (0x0275b800), + (0x7149c400), + (0x733c7c00), + (0x1058c000), + (0x122d7800), + (0x61110400), + (0x6364bc00), + (0x006f3e00), + (0x021a8600), + (0x7126fa00), + (0x73534200), + (0x1037fe00), + (0x12424600), + (0x617e3a00), + (0x630b8200)}, + {(0x3f800000), + (0x3f813adc), + (0x3fb8a4e2), + (0x3fb99e3e), + (0x3f882c60), + (0x3f8916bc), + (0x3fb08882), + (0x3fb1b25e), + (0x3f80379f), + (0x3f810d43), + (0x3fb8937d), + (0x3fb9a9a1), + (0x3f881bff), + (0x3f892123), + (0x3fb0bf1d), + (0x3fb185c1)}, + (0xfff80000), + {0x43,0xbd,0xc4,0xf1,0xb1,0xd7,0x24,0x47,0xc5,0xd0, + 0xa4,0xbc,0xc9,0x66,0xb3,0x4b,0x26,0xd1,0x26,0x85,0x00} + }, + { + /* No.45 delta:1261 weight:1353 */ + 11213, + 24, + 18, + 5, + {(0x00000000), + (0xabac4677), + (0x903dfbe7), + (0x3b91bd90), + (0xf83002d0), + (0x539c44a7), + (0x680df937), + (0xc3a1bf40), + (0x00004840), + (0xabac0e37), + (0x903db3a7), + (0x3b91f5d0), + (0xf8304a90), + (0x539c0ce7), + (0x680db177), + (0xc3a1f700)}, + {(0x00000000), + (0x00762800), + (0x200acc00), + (0x207ce400), + (0x6ea81000), + (0x6ede3800), + (0x4ea2dc00), + (0x4ed4f400), + (0x004e1e00), + (0x00383600), + (0x2044d200), + (0x2032fa00), + (0x6ee60e00), + (0x6e902600), + (0x4eecc200), + (0x4e9aea00)}, + {(0x3f800000), + (0x3f803b14), + (0x3f900566), + (0x3f903e72), + (0x3fb75408), + (0x3fb76f1c), + (0x3fa7516e), + (0x3fa76a7a), + (0x3f80270f), + (0x3f801c1b), + (0x3f902269), + (0x3f90197d), + (0x3fb77307), + (0x3fb74813), + (0x3fa77661), + (0x3fa74d75)}, + (0xfff80000), + {0x1c,0x79,0xc4,0xaf,0x4a,0xca,0x6f,0x97,0x73,0x87, + 0xe2,0xfa,0x1b,0x02,0x4e,0xfc,0xc2,0xc5,0x85,0xa8,0x00} + }, + { + /* No.46 delta:2871 weight:1351 */ + 11213, + 24, + 4, + 11, + {(0x00000000), + (0x5f7bd2a5), + (0x9b479801), + (0xc43c4aa4), + (0x793002ea), + (0x264bd04f), + (0xe2779aeb), + (0xbd0c484e), + (0x0000737e), + (0x5f7ba1db), + (0x9b47eb7f), + (0xc43c39da), + (0x79307194), + (0x264ba331), + (0xe277e995), + (0xbd0c3b30)}, + {(0x00000000), + (0x0a8c0000), + (0x10810000), + (0x1a0d0000), + (0x00600800), + (0x0aec0800), + (0x10e10800), + (0x1a6d0800), + (0x40101e00), + (0x4a9c1e00), + (0x50911e00), + (0x5a1d1e00), + (0x40701600), + (0x4afc1600), + (0x50f11600), + (0x5a7d1600)}, + {(0x3f800000), + (0x3f854600), + (0x3f884080), + (0x3f8d0680), + (0x3f803004), + (0x3f857604), + (0x3f887084), + (0x3f8d3684), + (0x3fa0080f), + (0x3fa54e0f), + (0x3fa8488f), + (0x3fad0e8f), + (0x3fa0380b), + (0x3fa57e0b), + (0x3fa8788b), + (0x3fad3e8b)}, + (0xfff80000), + {0x23,0xc7,0xec,0x47,0xae,0x9d,0xf4,0x29,0xa3,0xce, + 0x13,0x6c,0x06,0x67,0x5b,0x3a,0xb2,0xac,0x33,0xdb,0x00} + }, + { + /* No.47 delta:4370 weight:1245 */ + 11213, + 26, + 30, + 4, + {(0x00000000), + (0x1af999ae), + (0x1bfe6053), + (0x0107f9fd), + (0xb1f002f1), + (0xab099b5f), + (0xaa0e62a2), + (0xb0f7fb0c), + (0x0000281b), + (0x1af9b1b5), + (0x1bfe4848), + (0x0107d1e6), + (0xb1f02aea), + (0xab09b344), + (0xaa0e4ab9), + (0xb0f7d317)}, + {(0x00000000), + (0x0c201000), + (0x03140000), + (0x0f341000), + (0xe4200800), + (0xe8001800), + (0xe7340800), + (0xeb141800), + (0x08001e00), + (0x04200e00), + (0x0b141e00), + (0x07340e00), + (0xec201600), + (0xe0000600), + (0xef341600), + (0xe3140600)}, + {(0x3f800000), + (0x3f861008), + (0x3f818a00), + (0x3f879a08), + (0x3ff21004), + (0x3ff4000c), + (0x3ff39a04), + (0x3ff58a0c), + (0x3f84000f), + (0x3f821007), + (0x3f858a0f), + (0x3f839a07), + (0x3ff6100b), + (0x3ff00003), + (0x3ff79a0b), + (0x3ff18a03)}, + (0xfff80000), + {0x98,0x58,0x06,0x9e,0x81,0x14,0x32,0xd7,0x93,0x32, + 0x65,0xc8,0x13,0x43,0x02,0x53,0x1e,0xd3,0xaf,0x94,0x00} + }, + { + /* No.48 delta:1177 weight:859 */ + 11213, + 75, + 13, + 16, + {(0x00000000), + (0x8e9ecf83), + (0xb438b3ee), + (0x3aa67c6d), + (0xbd800305), + (0x331ecc86), + (0x09b8b0eb), + (0x87267f68), + (0x0000d641), + (0x8e9e19c2), + (0xb43865af), + (0x3aa6aa2c), + (0xbd80d544), + (0x331e1ac7), + (0x09b866aa), + (0x8726a929)}, + {(0x00000000), + (0x0f7d1c00), + (0x76262000), + (0x795b3c00), + (0x41532000), + (0x4e2e3c00), + (0x37750000), + (0x38081c00), + (0x00429e00), + (0x0f3f8200), + (0x7664be00), + (0x7919a200), + (0x4111be00), + (0x4e6ca200), + (0x37379e00), + (0x384a8200)}, + {(0x3f800000), + (0x3f87be8e), + (0x3fbb1310), + (0x3fbcad9e), + (0x3fa0a990), + (0x3fa7171e), + (0x3f9bba80), + (0x3f9c040e), + (0x3f80214f), + (0x3f879fc1), + (0x3fbb325f), + (0x3fbc8cd1), + (0x3fa088df), + (0x3fa73651), + (0x3f9b9bcf), + (0x3f9c2541)}, + (0xfff80000), + {0xc9,0xe0,0x77,0x04,0x4f,0x92,0x96,0xd4,0x05,0xdc, + 0x3e,0x3c,0xa6,0xf3,0x8e,0x2d,0xdb,0xf2,0x8c,0xe4,0x00} + }, + { + /* No.49 delta:3224 weight:947 */ + 11213, + 65, + 7, + 13, + {(0x00000000), + (0x9221eadf), + (0x5003b0d0), + (0xc2225a0f), + (0x0d800317), + (0x9fa1e9c8), + (0x5d83b3c7), + (0xcfa25918), + (0x00005031), + (0x9221baee), + (0x5003e0e1), + (0xc2220a3e), + (0x0d805326), + (0x9fa1b9f9), + (0x5d83e3f6), + (0xcfa20929)}, + {(0x00000000), + (0x00400800), + (0x60600000), + (0x60200800), + (0x00000000), + (0x00400800), + (0x60600000), + (0x60200800), + (0x30101e00), + (0x30501600), + (0x50701e00), + (0x50301600), + (0x30101e00), + (0x30501600), + (0x50701e00), + (0x50301600)}, + {(0x3f800000), + (0x3f802004), + (0x3fb03000), + (0x3fb01004), + (0x3f800000), + (0x3f802004), + (0x3fb03000), + (0x3fb01004), + (0x3f98080f), + (0x3f98280b), + (0x3fa8380f), + (0x3fa8180b), + (0x3f98080f), + (0x3f98280b), + (0x3fa8380f), + (0x3fa8180b)}, + (0xfff80000), + {0xc1,0x70,0x72,0x7f,0xb1,0x1e,0x6e,0xc5,0xec,0xcc, + 0x69,0xd8,0x0b,0xba,0x4e,0x2c,0x73,0x46,0x81,0x52,0x00} + }, + { + /* No.50 delta:6665 weight:1221 */ + 11213, + 84, + 1, + 9, + {(0x00000000), + (0xbdb9b41e), + (0x9876c465), + (0x25cf707b), + (0x25c0032f), + (0x9879b731), + (0xbdb6c74a), + (0x000f7354), + (0x00003009), + (0xbdb98417), + (0x9876f46c), + (0x25cf4072), + (0x25c03326), + (0x98798738), + (0xbdb6f743), + (0x000f435d)}, + {(0x00000000), + (0x51000000), + (0x20000000), + (0x71000000), + (0x04200000), + (0x55200000), + (0x24200000), + (0x75200000), + (0x17201e00), + (0x46201e00), + (0x37201e00), + (0x66201e00), + (0x13001e00), + (0x42001e00), + (0x33001e00), + (0x62001e00)}, + {(0x3f800000), + (0x3fa88000), + (0x3f900000), + (0x3fb88000), + (0x3f821000), + (0x3faa9000), + (0x3f921000), + (0x3fba9000), + (0x3f8b900f), + (0x3fa3100f), + (0x3f9b900f), + (0x3fb3100f), + (0x3f89800f), + (0x3fa1000f), + (0x3f99800f), + (0x3fb1000f)}, + (0xfff80000), + {0xdf,0xd6,0xd2,0xb4,0x0a,0xa4,0x35,0xbe,0x0f,0xa6, + 0x48,0x42,0xfe,0x0c,0x0f,0xa3,0xa9,0x64,0x1b,0x93,0x00} + }, + { + /* No.51 delta:6604 weight:1075 */ + 11213, + 61, + 3, + 13, + {(0x00000000), + (0xe7ec9698), + (0xdc943f6e), + (0x3b78a9f6), + (0xdf600330), + (0x388c95a8), + (0x03f43c5e), + (0xe418aac6), + (0x000058c3), + (0xe7ecce5b), + (0xdc9467ad), + (0x3b78f135), + (0xdf605bf3), + (0x388ccd6b), + (0x03f4649d), + (0xe418f205)}, + {(0x00000000), + (0x80000000), + (0x50000000), + (0xd0000000), + (0x20000000), + (0xa0000000), + (0x70000000), + (0xf0000000), + (0x00001e00), + (0x80001e00), + (0x50001e00), + (0xd0001e00), + (0x20001e00), + (0xa0001e00), + (0x70001e00), + (0xf0001e00)}, + {(0x3f800000), + (0x3fc00000), + (0x3fa80000), + (0x3fe80000), + (0x3f900000), + (0x3fd00000), + (0x3fb80000), + (0x3ff80000), + (0x3f80000f), + (0x3fc0000f), + (0x3fa8000f), + (0x3fe8000f), + (0x3f90000f), + (0x3fd0000f), + (0x3fb8000f), + (0x3ff8000f)}, + (0xfff80000), + {0xf2,0x95,0xcc,0x96,0x13,0xa0,0x75,0xc2,0xea,0x1a, + 0x5c,0x2d,0xcc,0x41,0x22,0xf8,0x87,0x8d,0x52,0xc0,0x00} + }, + { + /* No.52 delta:980 weight:1115 */ + 11213, + 75, + 17, + 12, + {(0x00000000), + (0x619af787), + (0x463e8326), + (0x27a474a1), + (0xc5c00348), + (0xa45af4cf), + (0x83fe806e), + (0xe26477e9), + (0x00008ae3), + (0x619a7d64), + (0x463e09c5), + (0x27a4fe42), + (0xc5c089ab), + (0xa45a7e2c), + (0x83fe0a8d), + (0xe264fd0a)}, + {(0x00000000), + (0x107c1400), + (0x81204400), + (0x915c5000), + (0x00113400), + (0x106d2000), + (0x81317000), + (0x914d6400), + (0x000ede00), + (0x1072ca00), + (0x812e9a00), + (0x91528e00), + (0x001fea00), + (0x1063fe00), + (0x813fae00), + (0x9143ba00)}, + {(0x3f800000), + (0x3f883e0a), + (0x3fc09022), + (0x3fc8ae28), + (0x3f80089a), + (0x3f883690), + (0x3fc098b8), + (0x3fc8a6b2), + (0x3f80076f), + (0x3f883965), + (0x3fc0974d), + (0x3fc8a947), + (0x3f800ff5), + (0x3f8831ff), + (0x3fc09fd7), + (0x3fc8a1dd)}, + (0xfff80000), + {0x31,0x3b,0x59,0xba,0x4b,0xfa,0x15,0x6d,0x68,0x38, + 0xd0,0x59,0x4b,0xc5,0xee,0xd6,0xd1,0x72,0x77,0x56,0x00} + }, + { + /* No.53 delta:2128 weight:1031 */ + 11213, + 90, + 18, + 10, + {(0x00000000), + (0x54ddf61b), + (0x3289e26b), + (0x66541470), + (0x8c500359), + (0xd88df542), + (0xbed9e132), + (0xea041729), + (0x0000fb30), + (0x54dd0d2b), + (0x3289195b), + (0x6654ef40), + (0x8c50f869), + (0xd88d0e72), + (0xbed91a02), + (0xea04ec19)}, + {(0x00000000), + (0x80710000), + (0x704e0000), + (0xf03f0000), + (0x40450000), + (0xc0340000), + (0x300b0000), + (0xb07a0000), + (0x000c1e00), + (0x807d1e00), + (0x70421e00), + (0xf0331e00), + (0x40491e00), + (0xc0381e00), + (0x30071e00), + (0xb0761e00)}, + {(0x3f800000), + (0x3fc03880), + (0x3fb82700), + (0x3ff81f80), + (0x3fa02280), + (0x3fe01a00), + (0x3f980580), + (0x3fd83d00), + (0x3f80060f), + (0x3fc03e8f), + (0x3fb8210f), + (0x3ff8198f), + (0x3fa0248f), + (0x3fe01c0f), + (0x3f98038f), + (0x3fd83b0f)}, + (0xfff80000), + {0x2c,0x15,0xc7,0x91,0x8f,0xe7,0xba,0x43,0x56,0x9b, + 0xf8,0xd4,0x59,0xf2,0x0c,0x4e,0xf2,0x42,0x9a,0xfe,0x00} + }, + { + /* No.54 delta:2047 weight:935 */ + 11213, + 73, + 6, + 15, + {(0x00000000), + (0x1b3e4d84), + (0x40583cec), + (0x5b667168), + (0x82600363), + (0x995e4ee7), + (0xc2383f8f), + (0xd906720b), + (0x000025e9), + (0x1b3e686d), + (0x40581905), + (0x5b665481), + (0x8260268a), + (0x995e6b0e), + (0xc2381a66), + (0xd90657e2)}, + {(0x00000000), + (0x00524000), + (0x52804000), + (0x52d20000), + (0x00232000), + (0x00716000), + (0x52a36000), + (0x52f12000), + (0x21c51e00), + (0x21975e00), + (0x73455e00), + (0x73171e00), + (0x21e63e00), + (0x21b47e00), + (0x73667e00), + (0x73343e00)}, + {(0x3f800000), + (0x3f802920), + (0x3fa94020), + (0x3fa96900), + (0x3f801190), + (0x3f8038b0), + (0x3fa951b0), + (0x3fa97890), + (0x3f90e28f), + (0x3f90cbaf), + (0x3fb9a2af), + (0x3fb98b8f), + (0x3f90f31f), + (0x3f90da3f), + (0x3fb9b33f), + (0x3fb99a1f)}, + (0xfff80000), + {0x67,0xd5,0xbe,0x19,0x7f,0x4e,0x37,0xca,0xeb,0x0b, + 0x09,0x52,0xc2,0x91,0x23,0x02,0xb9,0xa6,0xdd,0x1e,0x00} + }, + { + /* No.55 delta:1367 weight:1089 */ + 11213, + 30, + 14, + 10, + {(0x00000000), + (0x3d4e7360), + (0xd47d559c), + (0xe93326fc), + (0x10e00371), + (0x2dae7011), + (0xc49d56ed), + (0xf9d3258d), + (0x0000f71b), + (0x3d4e847b), + (0xd47da287), + (0xe933d1e7), + (0x10e0f46a), + (0x2dae870a), + (0xc49da1f6), + (0xf9d3d296)}, + {(0x00000000), + (0x6b729000), + (0x206f1800), + (0x4b1d8800), + (0x00501a00), + (0x6b228a00), + (0x203f0200), + (0x4b4d9200), + (0x20103e00), + (0x4b62ae00), + (0x007f2600), + (0x6b0db600), + (0x20402400), + (0x4b32b400), + (0x002f3c00), + (0x6b5dac00)}, + {(0x3f800000), + (0x3fb5b948), + (0x3f90378c), + (0x3fa58ec4), + (0x3f80280d), + (0x3fb59145), + (0x3f901f81), + (0x3fa5a6c9), + (0x3f90081f), + (0x3fa5b157), + (0x3f803f93), + (0x3fb586db), + (0x3f902012), + (0x3fa5995a), + (0x3f80179e), + (0x3fb5aed6)}, + (0xfff80000), + {0x74,0x06,0xc4,0x94,0x50,0xc8,0x89,0xd9,0x6c,0x24, + 0x1b,0x4e,0x7f,0x96,0xbe,0x0a,0xb0,0xbb,0xa9,0x75,0x00} + }, + { + /* No.56 delta:1232 weight:1251 */ + 11213, + 56, + 20, + 8, + {(0x00000000), + (0x303bfd65), + (0x96ea74b0), + (0xa6d189d5), + (0x1d200385), + (0x2d1bfee0), + (0x8bca7735), + (0xbbf18a50), + (0x0000e0a3), + (0x303b1dc6), + (0x96ea9413), + (0xa6d16976), + (0x1d20e326), + (0x2d1b1e43), + (0x8bca9796), + (0xbbf16af3)}, + {(0x00000000), + (0x0e9c1400), + (0x00661e00), + (0x0efa0a00), + (0x20125000), + (0x2e8e4400), + (0x20744e00), + (0x2ee85a00), + (0x001abe00), + (0x0e86aa00), + (0x007ca000), + (0x0ee0b400), + (0x2008ee00), + (0x2e94fa00), + (0x206ef000), + (0x2ef2e400)}, + {(0x3f800000), + (0x3f874e0a), + (0x3f80330f), + (0x3f877d05), + (0x3f900928), + (0x3f974722), + (0x3f903a27), + (0x3f97742d), + (0x3f800d5f), + (0x3f874355), + (0x3f803e50), + (0x3f87705a), + (0x3f900477), + (0x3f974a7d), + (0x3f903778), + (0x3f977972)}, + (0xfff80000), + {0x9f,0xb8,0x5c,0x52,0x53,0x38,0x40,0xed,0x9b,0x43, + 0xe8,0x89,0x8c,0xd0,0x44,0x25,0x4b,0xbf,0xca,0xd0,0x00} + }, + { + /* No.57 delta:1379 weight:873 */ + 11213, + 89, + 13, + 1, + {(0x00000000), + (0xfacfdd0b), + (0x22ecafbf), + (0xd82372b4), + (0x85500390), + (0x7f9fde9b), + (0xa7bcac2f), + (0x5d737124), + (0x0000d423), + (0xfacf0928), + (0x22ec7b9c), + (0xd823a697), + (0x8550d7b3), + (0x7f9f0ab8), + (0xa7bc780c), + (0x5d73a507)}, + {(0x00000000), + (0x2c081000), + (0x05201800), + (0x29280800), + (0x20e00400), + (0x0ce81400), + (0x25c01c00), + (0x09c80c00), + (0x11481e00), + (0x3d400e00), + (0x14680600), + (0x38601600), + (0x31a81a00), + (0x1da00a00), + (0x34880200), + (0x18801200)}, + {(0x3f800000), + (0x3f960408), + (0x3f82900c), + (0x3f949404), + (0x3f907002), + (0x3f86740a), + (0x3f92e00e), + (0x3f84e406), + (0x3f88a40f), + (0x3f9ea007), + (0x3f8a3403), + (0x3f9c300b), + (0x3f98d40d), + (0x3f8ed005), + (0x3f9a4401), + (0x3f8c4009)}, + (0xfff80000), + {0x08,0x0f,0x24,0x9d,0x3a,0xba,0x6d,0xb4,0xb0,0x1a, + 0x1c,0x4b,0x44,0xe7,0x44,0xf7,0xc9,0x4a,0x5f,0x97,0x00} + }, + { + /* No.58 delta:904 weight:1097 */ + 11213, + 60, + 16, + 2, + {(0x00000000), + (0xda86476d), + (0x6c05798d), + (0xb6833ee0), + (0xb72003ae), + (0x6da644c3), + (0xdb257a23), + (0x01a33d4e), + (0x00001489), + (0xda8653e4), + (0x6c056d04), + (0xb6832a69), + (0xb7201727), + (0x6da6504a), + (0xdb256eaa), + (0x01a329c7)}, + {(0x00000000), + (0x0c74f000), + (0x0059a800), + (0x0c2d5800), + (0x02445000), + (0x0e30a000), + (0x021df800), + (0x0e690800), + (0x0902de00), + (0x05762e00), + (0x095b7600), + (0x052f8600), + (0x0b468e00), + (0x07327e00), + (0x0b1f2600), + (0x076bd600)}, + {(0x3f800000), + (0x3f863a78), + (0x3f802cd4), + (0x3f8616ac), + (0x3f812228), + (0x3f871850), + (0x3f810efc), + (0x3f873484), + (0x3f84816f), + (0x3f82bb17), + (0x3f84adbb), + (0x3f8297c3), + (0x3f85a347), + (0x3f83993f), + (0x3f858f93), + (0x3f83b5eb)}, + (0xfff80000), + {0xb8,0xe0,0xa0,0x3b,0x2e,0x11,0x17,0x83,0x7b,0x75, + 0x85,0x89,0xfa,0x1e,0x49,0xb4,0x5c,0xe6,0xb8,0xc1,0x00} + }, + { + /* No.59 delta:7724 weight:1539 */ + 11213, + 42, + 28, + 4, + {(0x00000000), + (0xdfefef22), + (0x804185a4), + (0x5fae6a86), + (0x54b003b3), + (0x8b5fec91), + (0xd4f18617), + (0x0b1e6935), + (0x00009211), + (0xdfef7d33), + (0x804117b5), + (0x5faef897), + (0x54b091a2), + (0x8b5f7e80), + (0xd4f11406), + (0x0b1efb24)}, + {(0x00000000), + (0x38020000), + (0x08014000), + (0x30034000), + (0x04000800), + (0x3c020800), + (0x0c014800), + (0x34034800), + (0x08001e00), + (0x30021e00), + (0x00015e00), + (0x38035e00), + (0x0c001600), + (0x34021600), + (0x04015600), + (0x3c035600)}, + {(0x3f800000), + (0x3f9c0100), + (0x3f8400a0), + (0x3f9801a0), + (0x3f820004), + (0x3f9e0104), + (0x3f8600a4), + (0x3f9a01a4), + (0x3f84000f), + (0x3f98010f), + (0x3f8000af), + (0x3f9c01af), + (0x3f86000b), + (0x3f9a010b), + (0x3f8200ab), + (0x3f9e01ab)}, + (0xfff80000), + {0x91,0xba,0x8c,0xac,0x44,0xa7,0x81,0xa7,0xed,0x37, + 0x7e,0x8d,0xaf,0xe5,0x08,0xe6,0xc7,0x1d,0xfd,0xe5,0x00} + }, + { + /* No.60 delta:2411 weight:1317 */ + 11213, + 13, + 24, + 5, + {(0x00000000), + (0x9dd3ce8f), + (0x90da0878), + (0x0d09c6f7), + (0xad8003cf), + (0x3053cd40), + (0x3d5a0bb7), + (0xa089c538), + (0x0000bcb0), + (0x9dd3723f), + (0x90dab4c8), + (0x0d097a47), + (0xad80bf7f), + (0x305371f0), + (0x3d5ab707), + (0xa0897988)}, + {(0x00000000), + (0x4c0b9800), + (0x0fa54000), + (0x43aed800), + (0x0067c000), + (0x4c6c5800), + (0x0fc28000), + (0x43c91800), + (0x0a105e00), + (0x461bc600), + (0x05b51e00), + (0x49be8600), + (0x0a779e00), + (0x467c0600), + (0x05d2de00), + (0x49d94600)}, + {(0x3f800000), + (0x3fa605cc), + (0x3f87d2a0), + (0x3fa1d76c), + (0x3f8033e0), + (0x3fa6362c), + (0x3f87e140), + (0x3fa1e48c), + (0x3f85082f), + (0x3fa30de3), + (0x3f82da8f), + (0x3fa4df43), + (0x3f853bcf), + (0x3fa33e03), + (0x3f82e96f), + (0x3fa4eca3)}, + (0xfff80000), + {0xac,0x0b,0xb8,0x4d,0x6f,0xbd,0x47,0x8b,0x3f,0x9c, + 0x92,0xd0,0x32,0xf9,0x89,0x38,0xda,0x67,0xea,0xbe,0x00} + }, + { + /* No.61 delta:1265 weight:827 */ + 11213, + 52, + 17, + 15, + {(0x00000000), + (0xa4b47608), + (0x36bc0fca), + (0x920879c2), + (0xdeb003d6), + (0x7a0475de), + (0xe80c0c1c), + (0x4cb87a14), + (0x0000fbcf), + (0xa4b48dc7), + (0x36bcf405), + (0x9208820d), + (0xdeb0f819), + (0x7a048e11), + (0xe80cf7d3), + (0x4cb881db)}, + {(0x00000000), + (0x0813ae00), + (0x20151000), + (0x2806be00), + (0x4029c000), + (0x483a6e00), + (0x603cd000), + (0x682f7e00), + (0x52035e00), + (0x5a10f000), + (0x72164e00), + (0x7a05e000), + (0x122a9e00), + (0x1a393000), + (0x323f8e00), + (0x3a2c2000)}, + {(0x3f800000), + (0x3f8409d7), + (0x3f900a88), + (0x3f94035f), + (0x3fa014e0), + (0x3fa41d37), + (0x3fb01e68), + (0x3fb417bf), + (0x3fa901af), + (0x3fad0878), + (0x3fb90b27), + (0x3fbd02f0), + (0x3f89154f), + (0x3f8d1c98), + (0x3f991fc7), + (0x3f9d1610)}, + (0xfff80000), + {0xb2,0x25,0x08,0xf6,0xcd,0xda,0xfa,0xdb,0x2f,0xe7, + 0x81,0x83,0x7f,0xb8,0x75,0x05,0xff,0x2c,0x1a,0x80,0x00} + }, + { + /* No.62 delta:3397 weight:1223 */ + 11213, + 44, + 3, + 7, + {(0x00000000), + (0x89ffcb3c), + (0xafe67560), + (0x2619be5c), + (0xf79003e8), + (0x7e6fc8d4), + (0x58767688), + (0xd189bdb4), + (0x0000dcdc), + (0x89ff17e0), + (0xafe6a9bc), + (0x26196280), + (0xf790df34), + (0x7e6f1408), + (0x5876aa54), + (0xd1896168)}, + {(0x00000000), + (0x00710000), + (0xb00e0800), + (0xb07f0800), + (0x90120000), + (0x90630000), + (0x201c0800), + (0x206d0800), + (0x40091e00), + (0x40781e00), + (0xf0071600), + (0xf0761600), + (0xd01b1e00), + (0xd06a1e00), + (0x60151600), + (0x60641600)}, + {(0x3f800000), + (0x3f803880), + (0x3fd80704), + (0x3fd83f84), + (0x3fc80900), + (0x3fc83180), + (0x3f900e04), + (0x3f903684), + (0x3fa0048f), + (0x3fa03c0f), + (0x3ff8038b), + (0x3ff83b0b), + (0x3fe80d8f), + (0x3fe8350f), + (0x3fb00a8b), + (0x3fb0320b)}, + (0xfff80000), + {0x65,0x92,0xc9,0x30,0xd4,0x39,0xe2,0xf8,0x3a,0x06, + 0x72,0x5a,0xf0,0xe9,0x6f,0x1d,0x41,0xb8,0x38,0xcb,0x00} + }, + { + /* No.63 delta:1253 weight:1063 */ + 11213, + 40, + 15, + 8, + {(0x00000000), + (0xf0f1fa2b), + (0xc095cbf9), + (0x306431d2), + (0x84c003f6), + (0x7431f9dd), + (0x4455c80f), + (0xb4a43224), + (0x000041b7), + (0xf0f1bb9c), + (0xc0958a4e), + (0x30647065), + (0x84c04241), + (0x7431b86a), + (0x445589b8), + (0xb4a47393)}, + {(0x00000000), + (0x000f4800), + (0x00c47000), + (0x00cb3800), + (0x001ec000), + (0x00118800), + (0x00dab000), + (0x00d5f800), + (0xc01d9e00), + (0xc012d600), + (0xc0d9ee00), + (0xc0d6a600), + (0xc0035e00), + (0xc00c1600), + (0xc0c72e00), + (0xc0c86600)}, + {(0x3f800000), + (0x3f8007a4), + (0x3f806238), + (0x3f80659c), + (0x3f800f60), + (0x3f8008c4), + (0x3f806d58), + (0x3f806afc), + (0x3fe00ecf), + (0x3fe0096b), + (0x3fe06cf7), + (0x3fe06b53), + (0x3fe001af), + (0x3fe0060b), + (0x3fe06397), + (0x3fe06433)}, + (0xfff80000), + {0x6a,0x42,0x24,0x72,0x49,0x2e,0x6c,0xc6,0x39,0xde, + 0x29,0x45,0x5e,0xba,0x3b,0xda,0xc6,0xb7,0x79,0xd2,0x00} + }, + { + /* No.64 delta:5028 weight:833 */ + 11213, + 40, + 3, + 16, + {(0x00000000), + (0x0fda9709), + (0xdb5d90d9), + (0xd48707d0), + (0x78500401), + (0x778a9308), + (0xa30d94d8), + (0xacd703d1), + (0x00000aa4), + (0x0fda9dad), + (0xdb5d9a7d), + (0xd4870d74), + (0x78500ea5), + (0x778a99ac), + (0xa30d9e7c), + (0xacd70975)}, + {(0x00000000), + (0x19200000), + (0x83a00000), + (0x9a800000), + (0x00800000), + (0x19a00000), + (0x83200000), + (0x9a000000), + (0x41001e00), + (0x58201e00), + (0xc2a01e00), + (0xdb801e00), + (0x41801e00), + (0x58a01e00), + (0xc2201e00), + (0xdb001e00)}, + {(0x3f800000), + (0x3f8c9000), + (0x3fc1d000), + (0x3fcd4000), + (0x3f804000), + (0x3f8cd000), + (0x3fc19000), + (0x3fcd0000), + (0x3fa0800f), + (0x3fac100f), + (0x3fe1500f), + (0x3fedc00f), + (0x3fa0c00f), + (0x3fac500f), + (0x3fe1100f), + (0x3fed800f)}, + (0xfff80000), + {0x7f,0xa7,0x79,0xc1,0x02,0x5a,0xb9,0x48,0xd7,0xc2, + 0x1b,0xde,0x64,0x28,0xca,0x0c,0xa1,0xb8,0xbd,0x71,0x00} + }, + { + /* No.65 delta:1199 weight:1181 */ + 11213, + 35, + 20, + 9, + {(0x00000000), + (0xf97f5fb7), + (0x820665df), + (0x7b793a68), + (0xeda00417), + (0x14df5ba0), + (0x6fa661c8), + (0x96d93e7f), + (0x0000be8a), + (0xf97fe13d), + (0x8206db55), + (0x7b7984e2), + (0xeda0ba9d), + (0x14dfe52a), + (0x6fa6df42), + (0x96d980f5)}, + {(0x00000000), + (0x0c163000), + (0x000c1000), + (0x0c1a2000), + (0xc0028000), + (0xcc14b000), + (0xc00e9000), + (0xcc18a000), + (0x7101de00), + (0x7d17ee00), + (0x710dce00), + (0x7d1bfe00), + (0xb1035e00), + (0xbd156e00), + (0xb10f4e00), + (0xbd197e00)}, + {(0x3f800000), + (0x3f860b18), + (0x3f800608), + (0x3f860d10), + (0x3fe00140), + (0x3fe60a58), + (0x3fe00748), + (0x3fe60c50), + (0x3fb880ef), + (0x3fbe8bf7), + (0x3fb886e7), + (0x3fbe8dff), + (0x3fd881af), + (0x3fde8ab7), + (0x3fd887a7), + (0x3fde8cbf)}, + (0xfff80000), + {0x44,0x09,0x7e,0x16,0x6a,0x0b,0xbf,0xd6,0xf6,0x83, + 0xc1,0x33,0x24,0x8d,0x24,0x40,0xc5,0xee,0xb0,0xd2,0x00} + }, + { + /* No.66 delta:1553 weight:539 */ + 11213, + 26, + 13, + 19, + {(0x00000000), + (0xc75eb6dc), + (0xfa4bc661), + (0x3d1570bd), + (0x6f600428), + (0xa83eb2f4), + (0x952bc249), + (0x52757495), + (0x0000df90), + (0xc75e694c), + (0xfa4b19f1), + (0x3d15af2d), + (0x6f60dbb8), + (0xa83e6d64), + (0x952b1dd9), + (0x5275ab05)}, + {(0x00000000), + (0x00521800), + (0x20647400), + (0x20366c00), + (0x60dc1800), + (0x608e0000), + (0x40b86c00), + (0x40ea7400), + (0x10341e00), + (0x10660600), + (0x30506a00), + (0x30027200), + (0x70e80600), + (0x70ba1e00), + (0x508c7200), + (0x50de6a00)}, + {(0x3f800000), + (0x3f80290c), + (0x3f90323a), + (0x3f901b36), + (0x3fb06e0c), + (0x3fb04700), + (0x3fa05c36), + (0x3fa0753a), + (0x3f881a0f), + (0x3f883303), + (0x3f982835), + (0x3f980139), + (0x3fb87403), + (0x3fb85d0f), + (0x3fa84639), + (0x3fa86f35)}, + (0xfff80000), + {0xe3,0x81,0xfe,0x0e,0xae,0xa6,0x17,0x99,0xb5,0xdc, + 0x36,0xa3,0xa9,0x84,0x5e,0xac,0xaf,0x0b,0xa6,0x5e,0x00} + }, + { + /* No.67 delta:1370 weight:1349 */ + 11213, + 50, + 8, + 4, + {(0x00000000), + (0xf2eee92e), + (0x184a48a6), + (0xeaa4a188), + (0x3cb00439), + (0xce5eed17), + (0x24fa4c9f), + (0xd614a5b1), + (0x0000c236), + (0xf2ee2b18), + (0x184a8a90), + (0xeaa463be), + (0x3cb0c60f), + (0xce5e2f21), + (0x24fa8ea9), + (0xd6146787)}, + {(0x00000000), + (0x40028000), + (0x70014000), + (0x3003c000), + (0x20002000), + (0x6002a000), + (0x50016000), + (0x1003e000), + (0x10001e00), + (0x50029e00), + (0x60015e00), + (0x2003de00), + (0x30003e00), + (0x7002be00), + (0x40017e00), + (0x0003fe00)}, + {(0x3f800000), + (0x3fa00140), + (0x3fb800a0), + (0x3f9801e0), + (0x3f900010), + (0x3fb00150), + (0x3fa800b0), + (0x3f8801f0), + (0x3f88000f), + (0x3fa8014f), + (0x3fb000af), + (0x3f9001ef), + (0x3f98001f), + (0x3fb8015f), + (0x3fa000bf), + (0x3f8001ff)}, + (0xfff80000), + {0xce,0xab,0xcf,0x53,0x4e,0xc1,0xc1,0xd0,0x64,0x84, + 0xd7,0xc3,0xad,0x13,0xad,0xf4,0xf7,0x14,0xe1,0xd6,0x00} + }, + { + /* No.68 delta:1769 weight:1053 */ + 11213, + 44, + 23, + 7, + {(0x00000000), + (0x1c10f784), + (0xb81f8711), + (0xa40f7095), + (0xd0d00449), + (0xccc0f3cd), + (0x68cf8358), + (0x74df74dc), + (0x00006582), + (0x1c109206), + (0xb81fe293), + (0xa40f1517), + (0xd0d061cb), + (0xccc0964f), + (0x68cfe6da), + (0x74df115e)}, + {(0x00000000), + (0x009da000), + (0x40746000), + (0x40e9c000), + (0x00028400), + (0x009f2400), + (0x4076e400), + (0x40eb4400), + (0x700bbe00), + (0x70961e00), + (0x307fde00), + (0x30e27e00), + (0x70093a00), + (0x70949a00), + (0x307d5a00), + (0x30e0fa00)}, + {(0x3f800000), + (0x3f804ed0), + (0x3fa03a30), + (0x3fa074e0), + (0x3f800142), + (0x3f804f92), + (0x3fa03b72), + (0x3fa075a2), + (0x3fb805df), + (0x3fb84b0f), + (0x3f983fef), + (0x3f98713f), + (0x3fb8049d), + (0x3fb84a4d), + (0x3f983ead), + (0x3f98707d)}, + (0xfff80000), + {0x25,0xc5,0x2b,0x7e,0x94,0x70,0x50,0xab,0x68,0x79, + 0xe0,0x34,0x49,0x1e,0xd3,0x2a,0xe2,0x9f,0xef,0x26,0x00} + }, + { + /* No.69 delta:1887 weight:1253 */ + 11213, + 64, + 9, + 8, + {(0x00000000), + (0x4cbf4fb8), + (0xcc209ffc), + (0x809fd044), + (0x7e700455), + (0x32cf4bed), + (0xb2509ba9), + (0xfeefd411), + (0x0000612d), + (0x4cbf2e95), + (0xcc20fed1), + (0x809fb169), + (0x7e706578), + (0x32cf2ac0), + (0xb250fa84), + (0xfeefb53c)}, + {(0x00000000), + (0x50090000), + (0x00035000), + (0x500a5000), + (0x04019000), + (0x54089000), + (0x0402c000), + (0x540bc000), + (0x05027e00), + (0x550b7e00), + (0x05012e00), + (0x55082e00), + (0x0103ee00), + (0x510aee00), + (0x0100be00), + (0x5109be00)}, + {(0x3f800000), + (0x3fa80480), + (0x3f8001a8), + (0x3fa80528), + (0x3f8200c8), + (0x3faa0448), + (0x3f820160), + (0x3faa05e0), + (0x3f82813f), + (0x3faa85bf), + (0x3f828097), + (0x3faa8417), + (0x3f8081f7), + (0x3fa88577), + (0x3f80805f), + (0x3fa884df)}, + (0xfff80000), + {0x1f,0x11,0x3a,0x53,0x30,0xf5,0x3a,0x92,0x69,0x8f, + 0x5e,0x40,0x86,0x58,0x16,0xa4,0x7f,0x33,0x04,0xc6,0x00} + }, + { + /* No.70 delta:1651 weight:1401 */ + 11213, + 35, + 9, + 8, + {(0x00000000), + (0xcaa73bcd), + (0x48ffa480), + (0x82589f4d), + (0x0b600460), + (0xc1c73fad), + (0x439fa0e0), + (0x89389b2d), + (0x0000d8fb), + (0xcaa7e336), + (0x48ff7c7b), + (0x825847b6), + (0x0b60dc9b), + (0xc1c7e756), + (0x439f781b), + (0x893843d6)}, + {(0x00000000), + (0x90604200), + (0x20222000), + (0xb0426200), + (0x5023a800), + (0xc043ea00), + (0x70018800), + (0xe061ca00), + (0x16031e00), + (0x86635c00), + (0x36213e00), + (0xa6417c00), + (0x4620b600), + (0xd640f400), + (0x66029600), + (0xf662d400)}, + {(0x3f800000), + (0x3fc83021), + (0x3f901110), + (0x3fd82131), + (0x3fa811d4), + (0x3fe021f5), + (0x3fb800c4), + (0x3ff030e5), + (0x3f8b018f), + (0x3fc331ae), + (0x3f9b109f), + (0x3fd320be), + (0x3fa3105b), + (0x3feb207a), + (0x3fb3014b), + (0x3ffb316a)}, + (0xfff80000), + {0xf7,0xac,0x3b,0x82,0x60,0x2e,0xa2,0x38,0xd5,0xbd, + 0x9e,0x07,0x19,0x05,0x37,0x68,0xa8,0x2b,0xcc,0x5b,0x00} + }, + { + /* No.71 delta:805 weight:1559 */ + 11213, + 85, + 17, + 2, + {(0x00000000), + (0x4ea39f4b), + (0xeedcca5e), + (0xa07f5515), + (0x1a80047d), + (0x54239b36), + (0xf45cce23), + (0xbaff5168), + (0x000051a3), + (0x4ea3cee8), + (0xeedc9bfd), + (0xa07f04b6), + (0x1a8055de), + (0x5423ca95), + (0xf45c9f80), + (0xbaff00cb)}, + {(0x00000000), + (0x0879e800), + (0x10141400), + (0x186dfc00), + (0x006c0800), + (0x0815e000), + (0x10781c00), + (0x1801f400), + (0x40237e00), + (0x485a9600), + (0x50376a00), + (0x584e8200), + (0x404f7600), + (0x48369e00), + (0x505b6200), + (0x58228a00)}, + {(0x3f800000), + (0x3f843cf4), + (0x3f880a0a), + (0x3f8c36fe), + (0x3f803604), + (0x3f840af0), + (0x3f883c0e), + (0x3f8c00fa), + (0x3fa011bf), + (0x3fa42d4b), + (0x3fa81bb5), + (0x3fac2741), + (0x3fa027bb), + (0x3fa41b4f), + (0x3fa82db1), + (0x3fac1145)}, + (0xfff80000), + {0x81,0x81,0xe0,0x37,0x51,0x1b,0x87,0x01,0xa3,0x40, + 0x70,0xd0,0xb9,0x63,0xbb,0xc0,0xe9,0x49,0x0b,0x62,0x00} + }, + { + /* No.72 delta:1929 weight:1383 */ + 11213, + 77, + 8, + 10, + {(0x00000000), + (0x9625646a), + (0xa06390e5), + (0x3646f48f), + (0x6c400487), + (0xfa6560ed), + (0xcc239462), + (0x5a06f008), + (0x00006232), + (0x96250658), + (0xa063f2d7), + (0x364696bd), + (0x6c4066b5), + (0xfa6502df), + (0xcc23f650), + (0x5a06923a)}, + {(0x00000000), + (0x60350000), + (0x08a08000), + (0x68958000), + (0x00120000), + (0x60270000), + (0x08b28000), + (0x68878000), + (0x60021e00), + (0x00371e00), + (0x68a29e00), + (0x08979e00), + (0x60101e00), + (0x00251e00), + (0x68b09e00), + (0x08859e00)}, + {(0x3f800000), + (0x3fb01a80), + (0x3f845040), + (0x3fb44ac0), + (0x3f800900), + (0x3fb01380), + (0x3f845940), + (0x3fb443c0), + (0x3fb0010f), + (0x3f801b8f), + (0x3fb4514f), + (0x3f844bcf), + (0x3fb0080f), + (0x3f80128f), + (0x3fb4584f), + (0x3f8442cf)}, + (0xfff80000), + {0xec,0xe8,0xd6,0x3f,0xf0,0x4f,0x6e,0xc9,0x92,0xb9, + 0x0b,0xf3,0x46,0x01,0x83,0x06,0xba,0xbb,0xfc,0x3c,0x00} + }, + { + /* No.73 delta:1312 weight:1037 */ + 11213, + 79, + 14, + 13, + {(0x00000000), + (0x3c3b4194), + (0x3b4a522a), + (0x077113be), + (0x70e00495), + (0x4cdb4501), + (0x4baa56bf), + (0x7791172b), + (0x00001842), + (0x3c3b59d6), + (0x3b4a4a68), + (0x07710bfc), + (0x70e01cd7), + (0x4cdb5d43), + (0x4baa4efd), + (0x77910f69)}, + {(0x00000000), + (0x5e1d3000), + (0x08002800), + (0x561d1800), + (0x00404000), + (0x5e5d7000), + (0x08406800), + (0x565d5800), + (0xa7841e00), + (0xf9992e00), + (0xaf843600), + (0xf1990600), + (0xa7c45e00), + (0xf9d96e00), + (0xafc47600), + (0xf1d94600)}, + {(0x3f800000), + (0x3faf0e98), + (0x3f840014), + (0x3fab0e8c), + (0x3f802020), + (0x3faf2eb8), + (0x3f842034), + (0x3fab2eac), + (0x3fd3c20f), + (0x3ffccc97), + (0x3fd7c21b), + (0x3ff8cc83), + (0x3fd3e22f), + (0x3ffcecb7), + (0x3fd7e23b), + (0x3ff8eca3)}, + (0xfff80000), + {0xe5,0x84,0x28,0x6a,0xc7,0xb8,0xff,0x35,0x7e,0x4a, + 0xd0,0x29,0x99,0x65,0xc9,0xf9,0x00,0xb5,0xa5,0x73,0x00} + }, + { + /* No.74 delta:1274 weight:753 */ + 11213, + 83, + 10, + 18, + {(0x00000000), + (0xdb6fd096), + (0x7bead936), + (0xa08509a0), + (0x059004a2), + (0xdeffd434), + (0x7e7add94), + (0xa5150d02), + (0x00003dd4), + (0xdb6fed42), + (0x7beae4e2), + (0xa0853474), + (0x05903976), + (0xdeffe9e0), + (0x7e7ae040), + (0xa51530d6)}, + {(0x00000000), + (0x0862a000), + (0x20176000), + (0x2875c000), + (0x21182000), + (0x297a8000), + (0x010f4000), + (0x096de000), + (0x100c1e00), + (0x186ebe00), + (0x301b7e00), + (0x3879de00), + (0x31143e00), + (0x39769e00), + (0x11035e00), + (0x1961fe00)}, + {(0x3f800000), + (0x3f843150), + (0x3f900bb0), + (0x3f943ae0), + (0x3f908c10), + (0x3f94bd40), + (0x3f8087a0), + (0x3f84b6f0), + (0x3f88060f), + (0x3f8c375f), + (0x3f980dbf), + (0x3f9c3cef), + (0x3f988a1f), + (0x3f9cbb4f), + (0x3f8881af), + (0x3f8cb0ff)}, + (0xfff80000), + {0x94,0x6b,0xe1,0x97,0xcf,0xd7,0x1d,0x69,0x3d,0xf1, + 0xd3,0x31,0x9b,0x3f,0x74,0x40,0xe4,0x78,0x37,0x93,0x00} + }, + { + /* No.75 delta:3240 weight:999 */ + 11213, + 25, + 3, + 14, + {(0x00000000), + (0x5231ede5), + (0x75f41157), + (0x27c5fcb2), + (0x231004bc), + (0x7121e959), + (0x56e415eb), + (0x04d5f80e), + (0x000014a2), + (0x5231f947), + (0x75f405f5), + (0x27c5e810), + (0x2310101e), + (0x7121fdfb), + (0x56e40149), + (0x04d5ecac)}, + {(0x00000000), + (0x09c10000), + (0x50f28000), + (0x59338000), + (0x12424000), + (0x1b834000), + (0x42b0c000), + (0x4b71c000), + (0x02361e00), + (0x0bf71e00), + (0x52c49e00), + (0x5b059e00), + (0x10745e00), + (0x19b55e00), + (0x4086de00), + (0x4947de00)}, + {(0x3f800000), + (0x3f84e080), + (0x3fa87940), + (0x3fac99c0), + (0x3f892120), + (0x3f8dc1a0), + (0x3fa15860), + (0x3fa5b8e0), + (0x3f811b0f), + (0x3f85fb8f), + (0x3fa9624f), + (0x3fad82cf), + (0x3f883a2f), + (0x3f8cdaaf), + (0x3fa0436f), + (0x3fa4a3ef)}, + (0xfff80000), + {0x22,0xa1,0x8f,0x2e,0x7e,0xb0,0x8f,0x95,0xab,0x7b, + 0xe4,0x15,0x6f,0x5a,0x78,0x2a,0xeb,0x47,0xfe,0xa6,0x00} + }, + { + /* No.76 delta:1884 weight:1457 */ + 11213, + 11, + 13, + 3, + {(0x00000000), + (0xb165bd1d), + (0x1f5b5cd1), + (0xae3ee1cc), + (0x07b004ca), + (0xb6d5b9d7), + (0x18eb581b), + (0xa98ee506), + (0x00000ebc), + (0xb165b3a1), + (0x1f5b526d), + (0xae3eef70), + (0x07b00a76), + (0xb6d5b76b), + (0x18eb56a7), + (0xa98eebba)}, + {(0x00000000), + (0x2a1ef400), + (0x43091000), + (0x6917e400), + (0x05182000), + (0x2f06d400), + (0x46113000), + (0x6c0fc400), + (0x20c41e00), + (0x0adaea00), + (0x63cd0e00), + (0x49d3fa00), + (0x25dc3e00), + (0x0fc2ca00), + (0x66d52e00), + (0x4ccbda00)}, + {(0x3f800000), + (0x3f950f7a), + (0x3fa18488), + (0x3fb48bf2), + (0x3f828c10), + (0x3f97836a), + (0x3fa30898), + (0x3fb607e2), + (0x3f90620f), + (0x3f856d75), + (0x3fb1e687), + (0x3fa4e9fd), + (0x3f92ee1f), + (0x3f87e165), + (0x3fb36a97), + (0x3fa665ed)}, + (0xfff80000), + {0x5f,0x66,0x78,0x0e,0x66,0x3f,0x37,0x9d,0x75,0xa2, + 0x49,0x78,0xb7,0x8c,0xf1,0x7c,0x84,0xf3,0xab,0x84,0x00} + }, + { + /* No.77 delta:1037 weight:1439 */ + 11213, + 43, + 15, + 7, + {(0x00000000), + (0x3b7738f7), + (0x2ee7f42b), + (0x1590ccdc), + (0x8c3004de), + (0xb7473c29), + (0xa2d7f0f5), + (0x99a0c802), + (0x0000b3f9), + (0x3b778b0e), + (0x2ee747d2), + (0x15907f25), + (0x8c30b727), + (0xb7478fd0), + (0xa2d7430c), + (0x99a07bfb)}, + {(0x00000000), + (0x20009400), + (0x70030800), + (0x50039c00), + (0x90011600), + (0xb0018200), + (0xe0021e00), + (0xc0028a00), + (0x40005e00), + (0x6000ca00), + (0x30035600), + (0x1003c200), + (0xd0014800), + (0xf001dc00), + (0xa0024000), + (0x8002d400)}, + {(0x3f800000), + (0x3f90004a), + (0x3fb80184), + (0x3fa801ce), + (0x3fc8008b), + (0x3fd800c1), + (0x3ff0010f), + (0x3fe00145), + (0x3fa0002f), + (0x3fb00065), + (0x3f9801ab), + (0x3f8801e1), + (0x3fe800a4), + (0x3ff800ee), + (0x3fd00120), + (0x3fc0016a)}, + (0xfff80000), + {0x4d,0xd9,0x1c,0xbc,0x61,0x94,0x41,0xb3,0x64,0x5a, + 0xe0,0x27,0x21,0x33,0x58,0x8a,0x3a,0x27,0xe7,0x61,0x00} + }, + { + /* No.78 delta:3771 weight:1149 */ + 11213, + 67, + 6, + 13, + {(0x00000000), + (0xeb935e7e), + (0x12dd9004), + (0xf94ece7a), + (0x518004ec), + (0xba135a92), + (0x435d94e8), + (0xa8ceca96), + (0x00002915), + (0xeb93776b), + (0x12ddb911), + (0xf94ee76f), + (0x51802df9), + (0xba137387), + (0x435dbdfd), + (0xa8cee383)}, + {(0x00000000), + (0x00600000), + (0x005c0000), + (0x003c0000), + (0xa7000000), + (0xa7600000), + (0xa75c0000), + (0xa73c0000), + (0x00381e00), + (0x00581e00), + (0x00641e00), + (0x00041e00), + (0xa7381e00), + (0xa7581e00), + (0xa7641e00), + (0xa7041e00)}, + {(0x3f800000), + (0x3f803000), + (0x3f802e00), + (0x3f801e00), + (0x3fd38000), + (0x3fd3b000), + (0x3fd3ae00), + (0x3fd39e00), + (0x3f801c0f), + (0x3f802c0f), + (0x3f80320f), + (0x3f80020f), + (0x3fd39c0f), + (0x3fd3ac0f), + (0x3fd3b20f), + (0x3fd3820f)}, + (0xfff80000), + {0x61,0xb9,0x79,0x4a,0xf6,0x0b,0x90,0x19,0x41,0xed, + 0xc7,0x02,0x30,0x6e,0x66,0x3a,0xa0,0x21,0x38,0x4d,0x00} + }, + { + /* No.79 delta:8905 weight:995 */ + 11213, + 37, + 2, + 14, + {(0x00000000), + (0xc386d224), + (0xa19cefca), + (0x621a3dee), + (0x73c004f0), + (0xb046d6d4), + (0xd25ceb3a), + (0x11da391e), + (0x00006023), + (0xc386b207), + (0xa19c8fe9), + (0x621a5dcd), + (0x73c064d3), + (0xb046b6f7), + (0xd25c8b19), + (0x11da593d)}, + {(0x00000000), + (0x50000000), + (0x60000000), + (0x30000000), + (0x00000000), + (0x50000000), + (0x60000000), + (0x30000000), + (0x10001e00), + (0x40001e00), + (0x70001e00), + (0x20001e00), + (0x10001e00), + (0x40001e00), + (0x70001e00), + (0x20001e00)}, + {(0x3f800000), + (0x3fa80000), + (0x3fb00000), + (0x3f980000), + (0x3f800000), + (0x3fa80000), + (0x3fb00000), + (0x3f980000), + (0x3f88000f), + (0x3fa0000f), + (0x3fb8000f), + (0x3f90000f), + (0x3f88000f), + (0x3fa0000f), + (0x3fb8000f), + (0x3f90000f)}, + (0xfff80000), + {0xcd,0x77,0xa6,0x4e,0x16,0x97,0x82,0x51,0x40,0x8c, + 0x23,0x3d,0x69,0x41,0x55,0xf4,0x6d,0xb5,0x97,0xc4,0x00} + }, + { + /* No.80 delta:1084 weight:1327 */ + 11213, + 41, + 20, + 7, + {(0x00000000), + (0x03b0124c), + (0x2709d148), + (0x24b9c304), + (0xd150050f), + (0xd2e01743), + (0xf659d447), + (0xf5e9c60b), + (0x0000e5a0), + (0x03b0f7ec), + (0x270934e8), + (0x24b926a4), + (0xd150e0af), + (0xd2e0f2e3), + (0xf65931e7), + (0xf5e923ab)}, + {(0x00000000), + (0x58fc3200), + (0x70059800), + (0x28f9aa00), + (0x00443a00), + (0x58b80800), + (0x7041a200), + (0x28bd9000), + (0x60225e00), + (0x38de6c00), + (0x1027c600), + (0x48dbf400), + (0x60666400), + (0x389a5600), + (0x1063fc00), + (0x489fce00)}, + {(0x3f800000), + (0x3fac7e19), + (0x3fb802cc), + (0x3f947cd5), + (0x3f80221d), + (0x3fac5c04), + (0x3fb820d1), + (0x3f945ec8), + (0x3fb0112f), + (0x3f9c6f36), + (0x3f8813e3), + (0x3fa46dfa), + (0x3fb03332), + (0x3f9c4d2b), + (0x3f8831fe), + (0x3fa44fe7)}, + (0xfff80000), + {0x17,0x06,0xb5,0x56,0x08,0x24,0x02,0x45,0x7d,0xec, + 0xaa,0x6e,0xee,0x42,0x3d,0x61,0xec,0x7b,0x95,0xda,0x00} + }, + { + /* No.81 delta:2107 weight:929 */ + 11213, + 68, + 7, + 13, + {(0x00000000), + (0xa2680084), + (0x72c07011), + (0xd0a87095), + (0xe9c00518), + (0x4ba8059c), + (0x9b007509), + (0x3968758d), + (0x000019d6), + (0xa2681952), + (0x72c069c7), + (0xd0a86943), + (0xe9c01cce), + (0x4ba81c4a), + (0x9b006cdf), + (0x39686c5b)}, + {(0x00000000), + (0x06214000), + (0x50182000), + (0x56396000), + (0x004c0000), + (0x066d4000), + (0x50542000), + (0x56756000), + (0x003abe00), + (0x061bfe00), + (0x50229e00), + (0x5603de00), + (0x0076be00), + (0x0657fe00), + (0x506e9e00), + (0x564fde00)}, + {(0x3f800000), + (0x3f8310a0), + (0x3fa80c10), + (0x3fab1cb0), + (0x3f802600), + (0x3f8336a0), + (0x3fa82a10), + (0x3fab3ab0), + (0x3f801d5f), + (0x3f830dff), + (0x3fa8114f), + (0x3fab01ef), + (0x3f803b5f), + (0x3f832bff), + (0x3fa8374f), + (0x3fab27ef)}, + (0xfff80000), + {0x06,0xc1,0x16,0x3a,0x4b,0xf5,0xcc,0xe4,0x06,0xc5, + 0x47,0x64,0xd8,0x26,0x6e,0xa3,0xd2,0xe3,0xfc,0x67,0x00} + }, + { + /* No.82 delta:1653 weight:993 */ + 11213, + 67, + 15, + 1, + {(0x00000000), + (0x205bddc2), + (0x51a5fb05), + (0x71fe26c7), + (0xbc800525), + (0x9cdbd8e7), + (0xed25fe20), + (0xcd7e23e2), + (0x0000ae60), + (0x205b73a2), + (0x51a55565), + (0x71fe88a7), + (0xbc80ab45), + (0x9cdb7687), + (0xed255040), + (0xcd7e8d82)}, + {(0x00000000), + (0x200d8e00), + (0x01004000), + (0x210dce00), + (0x1710c000), + (0x371d4e00), + (0x16108000), + (0x361d0e00), + (0x00409e00), + (0x204d1000), + (0x0140de00), + (0x214d5000), + (0x17505e00), + (0x375dd000), + (0x16501e00), + (0x365d9000)}, + {(0x3f800000), + (0x3f9006c7), + (0x3f808020), + (0x3f9086e7), + (0x3f8b8860), + (0x3f9b8ea7), + (0x3f8b0840), + (0x3f9b0e87), + (0x3f80204f), + (0x3f902688), + (0x3f80a06f), + (0x3f90a6a8), + (0x3f8ba82f), + (0x3f9baee8), + (0x3f8b280f), + (0x3f9b2ec8)}, + (0xfff80000), + {0x31,0x5a,0x14,0x56,0x22,0x69,0x71,0xb4,0xed,0xe9, + 0x57,0x3c,0xb3,0xa3,0xc2,0xd8,0x5c,0x3b,0xf9,0x7a,0x00} + }, + { + /* No.83 delta:2591 weight:1355 */ + 11213, + 78, + 3, + 3, + {(0x00000000), + (0x3fa6f3ae), + (0x11561526), + (0x2ef0e688), + (0x3f40053d), + (0x00e6f693), + (0x2e16101b), + (0x11b0e3b5), + (0x000038dd), + (0x3fa6cb73), + (0x11562dfb), + (0x2ef0de55), + (0x3f403de0), + (0x00e6ce4e), + (0x2e1628c6), + (0x11b0db68)}, + {(0x00000000), + (0x88264000), + (0x60420000), + (0xe8644000), + (0x20102000), + (0xa8366000), + (0x40522000), + (0xc8746000), + (0x00791e00), + (0x885f5e00), + (0x603b1e00), + (0xe81d5e00), + (0x20693e00), + (0xa84f7e00), + (0x402b3e00), + (0xc80d7e00)}, + {(0x3f800000), + (0x3fc41320), + (0x3fb02100), + (0x3ff43220), + (0x3f900810), + (0x3fd41b30), + (0x3fa02910), + (0x3fe43a30), + (0x3f803c8f), + (0x3fc42faf), + (0x3fb01d8f), + (0x3ff40eaf), + (0x3f90349f), + (0x3fd427bf), + (0x3fa0159f), + (0x3fe406bf)}, + (0xfff80000), + {0x95,0xde,0xea,0xd2,0x91,0x96,0x3a,0x31,0x18,0xb4, + 0x29,0x3c,0x05,0x83,0x13,0x20,0xa6,0xbb,0xfa,0x90,0x00} + }, + { + /* No.84 delta:1724 weight:1387 */ + 11213, + 31, + 24, + 7, + {(0x00000000), + (0x6f77a064), + (0x9d4e3ea4), + (0xf2399ec0), + (0xdab00543), + (0xb5c7a527), + (0x47fe3be7), + (0x28899b83), + (0x0000ba57), + (0x6f771a33), + (0x9d4e84f3), + (0xf2392497), + (0xdab0bf14), + (0xb5c71f70), + (0x47fe81b0), + (0x288921d4)}, + {(0x00000000), + (0x4052c800), + (0x403d7000), + (0x006fb800), + (0x01748400), + (0x41264c00), + (0x4149f400), + (0x011b3c00), + (0x30183e00), + (0x704af600), + (0x70254e00), + (0x30778600), + (0x316cba00), + (0x713e7200), + (0x7151ca00), + (0x31030200)}, + {(0x3f800000), + (0x3fa02964), + (0x3fa01eb8), + (0x3f8037dc), + (0x3f80ba42), + (0x3fa09326), + (0x3fa0a4fa), + (0x3f808d9e), + (0x3f980c1f), + (0x3fb8257b), + (0x3fb812a7), + (0x3f983bc3), + (0x3f98b65d), + (0x3fb89f39), + (0x3fb8a8e5), + (0x3f988181)}, + (0xfff80000), + {0x24,0x42,0xb5,0x8a,0x26,0x25,0x0b,0x43,0xb5,0xa1, + 0xfd,0xf3,0xef,0xe4,0x58,0x1d,0x2f,0x82,0x54,0xe1,0x00} + }, + { + /* No.85 delta:1315 weight:1167 */ + 11213, + 28, + 18, + 8, + {(0x00000000), + (0x7039a7b2), + (0x655a69d6), + (0x1563ce64), + (0x55800552), + (0x25b9a2e0), + (0x30da6c84), + (0x40e3cb36), + (0x0000db22), + (0x70397c90), + (0x655ab2f4), + (0x15631546), + (0x5580de70), + (0x25b979c2), + (0x30dab7a6), + (0x40e31014)}, + {(0x00000000), + (0x091ae000), + (0xc01fd200), + (0xc9053200), + (0x60072600), + (0x691dc600), + (0xa018f400), + (0xa9021400), + (0x40083e00), + (0x4912de00), + (0x8017ec00), + (0x890d0c00), + (0x200f1800), + (0x2915f800), + (0xe010ca00), + (0xe90a2a00)}, + {(0x3f800000), + (0x3f848d70), + (0x3fe00fe9), + (0x3fe48299), + (0x3fb00393), + (0x3fb48ee3), + (0x3fd00c7a), + (0x3fd4810a), + (0x3fa0041f), + (0x3fa4896f), + (0x3fc00bf6), + (0x3fc48686), + (0x3f90078c), + (0x3f948afc), + (0x3ff00865), + (0x3ff48515)}, + (0xfff80000), + {0x54,0x00,0xe5,0x09,0x83,0x8a,0xa3,0xac,0xe2,0x03, + 0xe4,0x5f,0x87,0xaa,0x93,0x3c,0x49,0xef,0xf1,0x12,0x00} + }, + { + /* No.86 delta:1805 weight:1023 */ + 11213, + 40, + 17, + 1, + {(0x00000000), + (0xd727963d), + (0x760f18b0), + (0xa1288e8d), + (0xe2d00563), + (0x35f7935e), + (0x94df1dd3), + (0x43f88bee), + (0x0000c942), + (0xd7275f7f), + (0x760fd1f2), + (0xa12847cf), + (0xe2d0cc21), + (0x35f75a1c), + (0x94dfd491), + (0x43f842ac)}, + {(0x00000000), + (0x207c0400), + (0x56934000), + (0x76ef4400), + (0x00009e00), + (0x207c9a00), + (0x5693de00), + (0x76efda00), + (0x20009e00), + (0x007c9a00), + (0x7693de00), + (0x56efda00), + (0x20000000), + (0x007c0400), + (0x76934000), + (0x56ef4400)}, + {(0x3f800000), + (0x3f903e02), + (0x3fab49a0), + (0x3fbb77a2), + (0x3f80004f), + (0x3f903e4d), + (0x3fab49ef), + (0x3fbb77ed), + (0x3f90004f), + (0x3f803e4d), + (0x3fbb49ef), + (0x3fab77ed), + (0x3f900000), + (0x3f803e02), + (0x3fbb49a0), + (0x3fab77a2)}, + (0xfff80000), + {0xc8,0x53,0x9a,0xab,0x96,0xd8,0xe7,0x02,0xe6,0xf1, + 0x74,0x36,0x00,0x32,0x32,0x6e,0x36,0xe4,0x78,0x88,0x00} + }, + { + /* No.87 delta:2165 weight:1423 */ + 11213, + 29, + 6, + 7, + {(0x00000000), + (0xb0a4f75d), + (0xd99a0020), + (0x693ef77d), + (0x0010057f), + (0xb0b4f222), + (0xd98a055f), + (0x692ef202), + (0x00002860), + (0xb0a4df3d), + (0xd99a2840), + (0x693edf1d), + (0x00102d1f), + (0xb0b4da42), + (0xd98a2d3f), + (0x692eda62)}, + {(0x00000000), + (0x00c02000), + (0x10102000), + (0x10d00000), + (0x700c0000), + (0x70cc2000), + (0x601c2000), + (0x60dc0000), + (0x00701e00), + (0x00b03e00), + (0x10603e00), + (0x10a01e00), + (0x707c1e00), + (0x70bc3e00), + (0x606c3e00), + (0x60ac1e00)}, + {(0x3f800000), + (0x3f806010), + (0x3f880810), + (0x3f886800), + (0x3fb80600), + (0x3fb86610), + (0x3fb00e10), + (0x3fb06e00), + (0x3f80380f), + (0x3f80581f), + (0x3f88301f), + (0x3f88500f), + (0x3fb83e0f), + (0x3fb85e1f), + (0x3fb0361f), + (0x3fb0560f)}, + (0xfff80000), + {0xc8,0x26,0xe1,0xb8,0xbd,0xd2,0x06,0x99,0x21,0x8b, + 0xa2,0x82,0x21,0x08,0x66,0x43,0x39,0x7d,0x22,0x3f,0x00} + }, + { + /* No.88 delta:2728 weight:929 */ + 11213, + 9, + 5, + 12, + {(0x00000000), + (0xba91b8b7), + (0x1f94657f), + (0xa505ddc8), + (0xc8900581), + (0x7201bd36), + (0xd70460fe), + (0x6d95d849), + (0x00009507), + (0xba912db0), + (0x1f94f078), + (0xa50548cf), + (0xc8909086), + (0x72012831), + (0xd704f5f9), + (0x6d954d4e)}, + {(0x00000000), + (0x74d60000), + (0x48810000), + (0x3c570000), + (0x07840000), + (0x73520000), + (0x4f050000), + (0x3bd30000), + (0xa0019e00), + (0xd4d79e00), + (0xe8809e00), + (0x9c569e00), + (0xa7859e00), + (0xd3539e00), + (0xef049e00), + (0x9bd29e00)}, + {(0x3f800000), + (0x3fba6b00), + (0x3fa44080), + (0x3f9e2b80), + (0x3f83c200), + (0x3fb9a900), + (0x3fa78280), + (0x3f9de980), + (0x3fd000cf), + (0x3fea6bcf), + (0x3ff4404f), + (0x3fce2b4f), + (0x3fd3c2cf), + (0x3fe9a9cf), + (0x3ff7824f), + (0x3fcde94f)}, + (0xfff80000), + {0xef,0x82,0x25,0x92,0x4d,0x84,0x32,0xcc,0x51,0x79, + 0xa6,0xf1,0xa8,0xb8,0xd3,0xc8,0xf4,0x1f,0x61,0x14,0x00} + }, + { + /* No.89 delta:1302 weight:829 */ + 11213, + 52, + 17, + 15, + {(0x00000000), + (0xff9c667b), + (0x076e42cb), + (0xf8f224b0), + (0x5a200593), + (0xa5bc63e8), + (0x5d4e4758), + (0xa2d22123), + (0x0000fbe9), + (0xff9c9d92), + (0x076eb922), + (0xf8f2df59), + (0x5a20fe7a), + (0xa5bc9801), + (0x5d4ebcb1), + (0xa2d2daca)}, + {(0x00000000), + (0x168c2000), + (0x08819000), + (0x1e0db000), + (0x8400d800), + (0x928cf800), + (0x8c814800), + (0x9a0d6800), + (0x0a023e00), + (0x1c8e1e00), + (0x0283ae00), + (0x140f8e00), + (0x8e02e600), + (0x988ec600), + (0x86837600), + (0x900f5600)}, + {(0x3f800000), + (0x3f8b4610), + (0x3f8440c8), + (0x3f8f06d8), + (0x3fc2006c), + (0x3fc9467c), + (0x3fc640a4), + (0x3fcd06b4), + (0x3f85011f), + (0x3f8e470f), + (0x3f8141d7), + (0x3f8a07c7), + (0x3fc70173), + (0x3fcc4763), + (0x3fc341bb), + (0x3fc807ab)}, + (0xfff80000), + {0x44,0x22,0x55,0x0c,0x46,0x02,0x05,0x6b,0x49,0xa7, + 0x79,0xcc,0xa0,0x5b,0x5c,0xeb,0x82,0xb3,0x48,0x1e,0x00} + }, + { + /* No.90 delta:1794 weight:683 */ + 11213, + 71, + 7, + 3, + {(0x00000000), + (0x28fcb37c), + (0x3de27e63), + (0x151ecd1f), + (0x99d005af), + (0xb12cb6d3), + (0xa4327bcc), + (0x8ccec8b0), + (0x0000473d), + (0x28fcf441), + (0x3de2395e), + (0x151e8a22), + (0x99d04292), + (0xb12cf1ee), + (0xa4323cf1), + (0x8cce8f8d)}, + {(0x00000000), + (0x00170000), + (0x00059200), + (0x00129200), + (0x61088000), + (0x611f8000), + (0x610d1200), + (0x611a1200), + (0x22825e00), + (0x22955e00), + (0x2287cc00), + (0x2290cc00), + (0x438ade00), + (0x439dde00), + (0x438f4c00), + (0x43984c00)}, + {(0x3f800000), + (0x3f800b80), + (0x3f8002c9), + (0x3f800949), + (0x3fb08440), + (0x3fb08fc0), + (0x3fb08689), + (0x3fb08d09), + (0x3f91412f), + (0x3f914aaf), + (0x3f9143e6), + (0x3f914866), + (0x3fa1c56f), + (0x3fa1ceef), + (0x3fa1c7a6), + (0x3fa1cc26)}, + (0xfff80000), + {0x63,0x96,0x53,0x66,0x89,0x8f,0x5a,0x0f,0x8c,0x80, + 0x0a,0x9a,0x17,0xd9,0x66,0x91,0xf8,0x92,0x97,0x62,0x00} + }, + { + /* No.91 delta:10527 weight:393 */ + 11213, + 5, + 2, + 19, + {(0x00000000), + (0x9ea45304), + (0x56ae02a1), + (0xc80a51a5), + (0x9ad005b9), + (0x047456bd), + (0xcc7e0718), + (0x52da541c), + (0x0000c554), + (0x9ea49650), + (0x56aec7f5), + (0xc80a94f1), + (0x9ad0c0ed), + (0x047493e9), + (0xcc7ec24c), + (0x52da9148)}, + {(0x00000000), + (0x64000000), + (0x0f800000), + (0x6b800000), + (0x00000000), + (0x64000000), + (0x0f800000), + (0x6b800000), + (0x00001e00), + (0x64001e00), + (0x0f801e00), + (0x6b801e00), + (0x00001e00), + (0x64001e00), + (0x0f801e00), + (0x6b801e00)}, + {(0x3f800000), + (0x3fb20000), + (0x3f87c000), + (0x3fb5c000), + (0x3f800000), + (0x3fb20000), + (0x3f87c000), + (0x3fb5c000), + (0x3f80000f), + (0x3fb2000f), + (0x3f87c00f), + (0x3fb5c00f), + (0x3f80000f), + (0x3fb2000f), + (0x3f87c00f), + (0x3fb5c00f)}, + (0xfff80000), + {0xd2,0x73,0xa3,0x8b,0x1a,0x90,0xef,0x94,0xe3,0x4a, + 0x16,0x2f,0x38,0x48,0xd9,0x68,0xf2,0xdf,0xe5,0xab,0x00} + }, + { + /* No.92 delta:2494 weight:1233 */ + 11213, + 7, + 21, + 4, + {(0x00000000), + (0x67c6fdcf), + (0x39165a15), + (0x5ed0a7da), + (0xa11005c0), + (0xc6d6f80f), + (0x98065fd5), + (0xffc0a21a), + (0x0000cdee), + (0x67c63021), + (0x391697fb), + (0x5ed06a34), + (0xa110c82e), + (0xc6d635e1), + (0x9806923b), + (0xffc06ff4)}, + {(0x00000000), + (0xc64d0800), + (0x67f58000), + (0xa1b88800), + (0x11ca8200), + (0xd7878a00), + (0x763f0200), + (0xb0720a00), + (0x4eb51e00), + (0x88f81600), + (0x29409e00), + (0xef0d9600), + (0x5f7f9c00), + (0x99329400), + (0x388a1c00), + (0xfec71400)}, + {(0x3f800000), + (0x3fe32684), + (0x3fb3fac0), + (0x3fd0dc44), + (0x3f88e541), + (0x3febc3c5), + (0x3fbb1f81), + (0x3fd83905), + (0x3fa75a8f), + (0x3fc47c0b), + (0x3f94a04f), + (0x3ff786cb), + (0x3fafbfce), + (0x3fcc994a), + (0x3f9c450e), + (0x3fff638a)}, + (0xfff80000), + {0x9e,0xa5,0x58,0x0a,0xe1,0x2c,0x68,0x94,0x2b,0x3f, + 0x4b,0xcd,0xe6,0xee,0x21,0x60,0xf3,0xf9,0x28,0xef,0x00} + }, + { + /* No.93 delta:2858 weight:713 */ + 11213, + 6, + 11, + 15, + {(0x00000000), + (0xce341fc2), + (0x74808815), + (0xbab497d7), + (0x396005de), + (0xf7541a1c), + (0x4de08dcb), + (0x83d49209), + (0x0000dee4), + (0xce34c126), + (0x748056f1), + (0xbab44933), + (0x3960db3a), + (0xf754c4f8), + (0x4de0532f), + (0x83d44ced)}, + {(0x00000000), + (0x0af25000), + (0x0c419c00), + (0x06b3cc00), + (0x82144400), + (0x88e61400), + (0x8e55d800), + (0x84a78800), + (0xe0053e00), + (0xeaf76e00), + (0xec44a200), + (0xe6b6f200), + (0x62117a00), + (0x68e32a00), + (0x6e50e600), + (0x64a2b600)}, + {(0x3f800000), + (0x3f857928), + (0x3f8620ce), + (0x3f8359e6), + (0x3fc10a22), + (0x3fc4730a), + (0x3fc72aec), + (0x3fc253c4), + (0x3ff0029f), + (0x3ff57bb7), + (0x3ff62251), + (0x3ff35b79), + (0x3fb108bd), + (0x3fb47195), + (0x3fb72873), + (0x3fb2515b)}, + (0xfff80000), + {0x67,0xfb,0x7b,0xdf,0x91,0xd7,0xa6,0xcb,0xfa,0x0c, + 0x9c,0xcf,0x32,0x59,0xd4,0x14,0x88,0x02,0x20,0xbd,0x00} + }, + { + /* No.94 delta:1428 weight:871 */ + 11213, + 51, + 24, + 3, + {(0x00000000), + (0x4055c0f5), + (0x3f9446d5), + (0x7fc18620), + (0xbd5005e5), + (0xfd05c510), + (0x82c44330), + (0xc29183c5), + (0x0000a8c2), + (0x40556837), + (0x3f94ee17), + (0x7fc12ee2), + (0xbd50ad27), + (0xfd056dd2), + (0x82c4ebf2), + (0xc2912b07)}, + {(0x00000000), + (0x6064a000), + (0x4ef89000), + (0x2e9c3000), + (0x08a1d000), + (0x68c57000), + (0x46594000), + (0x263de000), + (0x0c127e00), + (0x6c76de00), + (0x42eaee00), + (0x228e4e00), + (0x04b3ae00), + (0x64d70e00), + (0x4a4b3e00), + (0x2a2f9e00)}, + {(0x3f800000), + (0x3fb03250), + (0x3fa77c48), + (0x3f974e18), + (0x3f8450e8), + (0x3fb462b8), + (0x3fa32ca0), + (0x3f931ef0), + (0x3f86093f), + (0x3fb63b6f), + (0x3fa17577), + (0x3f914727), + (0x3f8259d7), + (0x3fb26b87), + (0x3fa5259f), + (0x3f9517cf)}, + (0xfff80000), + {0xfc,0xe1,0x89,0x6f,0x64,0xe4,0x4b,0x42,0xe3,0x27, + 0xa3,0x38,0x46,0x33,0x4f,0xf6,0x63,0x31,0xbb,0x80,0x00} + }, + { + /* No.95 delta:1914 weight:999 */ + 11213, + 43, + 8, + 13, + {(0x00000000), + (0x9c0723c5), + (0xc882db89), + (0x5485f84c), + (0x994005f3), + (0x05472636), + (0x51c2de7a), + (0xcdc5fdbf), + (0x000019bd), + (0x9c073a78), + (0xc882c234), + (0x5485e1f1), + (0x99401c4e), + (0x05473f8b), + (0x51c2c7c7), + (0xcdc5e402)}, + {(0x00000000), + (0x5061f000), + (0x105bc000), + (0x403a3000), + (0x00740400), + (0x5015f400), + (0x102fc400), + (0x404e3400), + (0x041c1e00), + (0x547dee00), + (0x1447de00), + (0x44262e00), + (0x04681a00), + (0x5409ea00), + (0x1433da00), + (0x44522a00)}, + {(0x3f800000), + (0x3fa830f8), + (0x3f882de0), + (0x3fa01d18), + (0x3f803a02), + (0x3fa80afa), + (0x3f8817e2), + (0x3fa0271a), + (0x3f820e0f), + (0x3faa3ef7), + (0x3f8a23ef), + (0x3fa21317), + (0x3f82340d), + (0x3faa04f5), + (0x3f8a19ed), + (0x3fa22915)}, + (0xfff80000), + {0xbf,0x5e,0xb4,0x48,0x47,0x8e,0xcb,0x36,0x4b,0x6a, + 0xc7,0x2c,0x1c,0xc9,0xdc,0x0d,0x4b,0x46,0x15,0xdf,0x00} + }, + { + /* No.96 delta:1078 weight:1383 */ + 11213, + 93, + 22, + 5, + {(0x00000000), + (0x4598c5d2), + (0x2a3c70f7), + (0x6fa4b525), + (0xf4e0060f), + (0xb178c3dd), + (0xdedc76f8), + (0x9b44b32a), + (0x0000ee71), + (0x45982ba3), + (0x2a3c9e86), + (0x6fa45b54), + (0xf4e0e87e), + (0xb1782dac), + (0xdedc9889), + (0x9b445d5b)}, + {(0x00000000), + (0x40220000), + (0x20738000), + (0x60518000), + (0x007e2000), + (0x405c2000), + (0x200da000), + (0x602fa000), + (0x80035e00), + (0xc0215e00), + (0xa070de00), + (0xe052de00), + (0x807d7e00), + (0xc05f7e00), + (0xa00efe00), + (0xe02cfe00)}, + {(0x3f800000), + (0x3fa01100), + (0x3f9039c0), + (0x3fb028c0), + (0x3f803f10), + (0x3fa02e10), + (0x3f9006d0), + (0x3fb017d0), + (0x3fc001af), + (0x3fe010af), + (0x3fd0386f), + (0x3ff0296f), + (0x3fc03ebf), + (0x3fe02fbf), + (0x3fd0077f), + (0x3ff0167f)}, + (0xfff80000), + {0xf7,0x01,0xdc,0x94,0xdb,0xfe,0x75,0xe3,0x41,0x0d, + 0xa7,0xcf,0xdb,0xc4,0xf8,0x63,0x39,0xf1,0x73,0x83,0x00} + }, + { + /* No.97 delta:1680 weight:855 */ + 11213, + 56, + 11, + 18, + {(0x00000000), + (0xed377fcb), + (0x935b7bcf), + (0x7e6c0404), + (0xb1b0061d), + (0x5c8779d6), + (0x22eb7dd2), + (0xcfdc0219), + (0x0000dc19), + (0xed37a3d2), + (0x935ba7d6), + (0x7e6cd81d), + (0xb1b0da04), + (0x5c87a5cf), + (0x22eba1cb), + (0xcfdcde00)}, + {(0x00000000), + (0x10100000), + (0x201c0000), + (0x300c0000), + (0x30000000), + (0x20100000), + (0x101c0000), + (0x000c0000), + (0x40051e00), + (0x50151e00), + (0x60191e00), + (0x70091e00), + (0x70051e00), + (0x60151e00), + (0x50191e00), + (0x40091e00)}, + {(0x3f800000), + (0x3f880800), + (0x3f900e00), + (0x3f980600), + (0x3f980000), + (0x3f900800), + (0x3f880e00), + (0x3f800600), + (0x3fa0028f), + (0x3fa80a8f), + (0x3fb00c8f), + (0x3fb8048f), + (0x3fb8028f), + (0x3fb00a8f), + (0x3fa80c8f), + (0x3fa0048f)}, + (0xfff80000), + {0xa7,0x90,0x32,0xf0,0xe5,0x54,0x81,0x86,0xda,0xa2, + 0x04,0x5e,0xda,0xe5,0xcd,0x25,0x97,0x20,0x5f,0xd8,0x00} + }, + { + /* No.98 delta:4818 weight:1887 */ + 11213, + 73, + 1, + 4, + {(0x00000000), + (0xf3234424), + (0xe4236cf9), + (0x170028dd), + (0x62d00623), + (0x91f34207), + (0x86f36ada), + (0x75d02efe), + (0x00003707), + (0xf3237323), + (0xe4235bfe), + (0x17001fda), + (0x62d03124), + (0x91f37500), + (0x86f35ddd), + (0x75d019f9)}, + {(0x00000000), + (0x40550000), + (0x40300000), + (0x00650000), + (0x7a81c000), + (0x3ad4c000), + (0x3ab1c000), + (0x7ae4c000), + (0x54351e00), + (0x14601e00), + (0x14051e00), + (0x54501e00), + (0x2eb4de00), + (0x6ee1de00), + (0x6e84de00), + (0x2ed1de00)}, + {(0x3f800000), + (0x3fa02a80), + (0x3fa01800), + (0x3f803280), + (0x3fbd40e0), + (0x3f9d6a60), + (0x3f9d58e0), + (0x3fbd7260), + (0x3faa1a8f), + (0x3f8a300f), + (0x3f8a028f), + (0x3faa280f), + (0x3f975a6f), + (0x3fb770ef), + (0x3fb7426f), + (0x3f9768ef)}, + (0xfff80000), + {0x78,0x4c,0x48,0x62,0xcb,0x43,0x6e,0xae,0x79,0x3f, + 0xa2,0x90,0xc7,0xd5,0xf6,0x2c,0x3a,0x94,0xf6,0x88,0x00} + }, + { + /* No.99 delta:4941 weight:807 */ + 11213, + 35, + 6, + 17, + {(0x00000000), + (0xceb13d37), + (0x6cab25b0), + (0xa21a1887), + (0x2d100639), + (0xe3a13b0e), + (0x41bb2389), + (0x8f0a1ebe), + (0x00002bd0), + (0xceb116e7), + (0x6cab0e60), + (0xa21a3357), + (0x2d102de9), + (0xe3a110de), + (0x41bb0859), + (0x8f0a356e)}, + {(0x00000000), + (0x07201000), + (0x42300200), + (0x45101200), + (0x40000000), + (0x47201000), + (0x02300200), + (0x05101200), + (0x70001e00), + (0x77200e00), + (0x32301c00), + (0x35100c00), + (0x30001e00), + (0x37200e00), + (0x72301c00), + (0x75100c00)}, + {(0x3f800000), + (0x3f839008), + (0x3fa11801), + (0x3fa28809), + (0x3fa00000), + (0x3fa39008), + (0x3f811801), + (0x3f828809), + (0x3fb8000f), + (0x3fbb9007), + (0x3f99180e), + (0x3f9a8806), + (0x3f98000f), + (0x3f9b9007), + (0x3fb9180e), + (0x3fba8806)}, + (0xfff80000), + {0x47,0x35,0x44,0x50,0x63,0x4a,0x6a,0xcd,0x53,0x03, + 0xdd,0x48,0x13,0x12,0x80,0xdf,0x0e,0x77,0xfa,0xf3,0x00} + }, + { + /* No.100 delta:1308 weight:863 */ + 11213, + 86, + 13, + 14, + {(0x00000000), + (0xc5ba19cb), + (0x67d04c0f), + (0xa26a55c4), + (0x36300642), + (0xf38a1f89), + (0x51e04a4d), + (0x945a5386), + (0x0000f011), + (0xc5bae9da), + (0x67d0bc1e), + (0xa26aa5d5), + (0x3630f653), + (0xf38aef98), + (0x51e0ba5c), + (0x945aa397)}, + {(0x00000000), + (0x09233a00), + (0x40645e00), + (0x49476400), + (0x1030a000), + (0x19139a00), + (0x5054fe00), + (0x5977c400), + (0x30c05e00), + (0x39e36400), + (0x70a40000), + (0x79873a00), + (0x20f0fe00), + (0x29d3c400), + (0x6094a000), + (0x69b79a00)}, + {(0x3f800000), + (0x3f84919d), + (0x3fa0322f), + (0x3fa4a3b2), + (0x3f881850), + (0x3f8c89cd), + (0x3fa82a7f), + (0x3facbbe2), + (0x3f98602f), + (0x3f9cf1b2), + (0x3fb85200), + (0x3fbcc39d), + (0x3f90787f), + (0x3f94e9e2), + (0x3fb04a50), + (0x3fb4dbcd)}, + (0xfff80000), + {0xbe,0xe1,0xe6,0x46,0x8d,0x04,0x11,0x44,0x1a,0x37, + 0x82,0xd9,0x6f,0xd6,0x9e,0xd5,0x25,0x58,0x1e,0xae,0x00} + }, + { + /* No.101 delta:3747 weight:693 */ + 11213, + 93, + 7, + 18, + {(0x00000000), + (0x34b395ad), + (0x437cf2d0), + (0x77cf677d), + (0xa770065c), + (0x93c393f1), + (0xe40cf48c), + (0xd0bf6121), + (0x0000f47f), + (0x34b361d2), + (0x437c06af), + (0x77cf9302), + (0xa770f223), + (0x93c3678e), + (0xe40c00f3), + (0xd0bf955e)}, + {(0x00000000), + (0x40700000), + (0x00580000), + (0x40280000), + (0x40680000), + (0x00180000), + (0x40300000), + (0x00400000), + (0x21601e00), + (0x61101e00), + (0x21381e00), + (0x61481e00), + (0x61081e00), + (0x21781e00), + (0x61501e00), + (0x21201e00)}, + {(0x3f800000), + (0x3fa03800), + (0x3f802c00), + (0x3fa01400), + (0x3fa03400), + (0x3f800c00), + (0x3fa01800), + (0x3f802000), + (0x3f90b00f), + (0x3fb0880f), + (0x3f909c0f), + (0x3fb0a40f), + (0x3fb0840f), + (0x3f90bc0f), + (0x3fb0a80f), + (0x3f90900f)}, + (0xfff80000), + {0xe2,0xf1,0x5a,0xc6,0xba,0x8b,0xae,0x08,0x43,0xcc, + 0x54,0xa6,0xe9,0x8f,0x81,0x0a,0x85,0xe3,0x5e,0xef,0x00} + }, + { + /* No.102 delta:3462 weight:1273 */ + 11213, + 55, + 23, + 8, + {(0x00000000), + (0xc3cc98c8), + (0xca3b10a5), + (0x09f7886d), + (0x18300660), + (0xdbfc9ea8), + (0xd20b16c5), + (0x11c78e0d), + (0x000030c4), + (0xc3cca80c), + (0xca3b2061), + (0x09f7b8a9), + (0x183036a4), + (0xdbfcae6c), + (0xd20b2601), + (0x11c7bec9)}, + {(0x00000000), + (0x08000000), + (0x00800000), + (0x08800000), + (0x88200000), + (0x80200000), + (0x88a00000), + (0x80a00000), + (0x03201e00), + (0x0b201e00), + (0x03a01e00), + (0x0ba01e00), + (0x8b001e00), + (0x83001e00), + (0x8b801e00), + (0x83801e00)}, + {(0x3f800000), + (0x3f840000), + (0x3f804000), + (0x3f844000), + (0x3fc41000), + (0x3fc01000), + (0x3fc45000), + (0x3fc05000), + (0x3f81900f), + (0x3f85900f), + (0x3f81d00f), + (0x3f85d00f), + (0x3fc5800f), + (0x3fc1800f), + (0x3fc5c00f), + (0x3fc1c00f)}, + (0xfff80000), + {0x43,0x1f,0x6f,0x01,0x80,0xf4,0x2e,0x31,0xcd,0xc1, + 0xb9,0x2f,0x6b,0x5c,0x0e,0x0b,0x35,0xa5,0x70,0x7e,0x00} + }, + { + /* No.103 delta:5054 weight:1635 */ + 11213, + 64, + 1, + 2, + {(0x00000000), + (0x4f30581d), + (0x5542c11f), + (0x1a729902), + (0x9da00670), + (0xd2905e6d), + (0xc8e2c76f), + (0x87d29f72), + (0x00007e47), + (0x4f30265a), + (0x5542bf58), + (0x1a72e745), + (0x9da07837), + (0xd290202a), + (0xc8e2b928), + (0x87d2e135)}, + {(0x00000000), + (0x0be21000), + (0x55018000), + (0x5ee39000), + (0x83944800), + (0x88765800), + (0xd695c800), + (0xdd77d800), + (0x00669e00), + (0x0b848e00), + (0x55671e00), + (0x5e850e00), + (0x83f2d600), + (0x8810c600), + (0xd6f35600), + (0xdd114600)}, + {(0x3f800000), + (0x3f85f108), + (0x3faa80c0), + (0x3faf71c8), + (0x3fc1ca24), + (0x3fc43b2c), + (0x3feb4ae4), + (0x3feebbec), + (0x3f80334f), + (0x3f85c247), + (0x3faab38f), + (0x3faf4287), + (0x3fc1f96b), + (0x3fc40863), + (0x3feb79ab), + (0x3fee88a3)}, + (0xfff80000), + {0x44,0x10,0x9f,0x8c,0xd9,0xbc,0x8e,0xb6,0xd5,0x14, + 0x72,0x32,0xdd,0xf2,0x3c,0xea,0xb3,0x38,0xb9,0x31,0x00} + }, + { + /* No.104 delta:2496 weight:907 */ + 11213, + 79, + 15, + 14, + {(0x00000000), + (0x5c0202d2), + (0x1c3f4858), + (0x403d4a8a), + (0xd2f0068f), + (0x8ef2045d), + (0xcecf4ed7), + (0x92cd4c05), + (0x0000d76d), + (0x5c02d5bf), + (0x1c3f9f35), + (0x403d9de7), + (0xd2f0d1e2), + (0x8ef2d330), + (0xcecf99ba), + (0x92cd9b68)}, + {(0x00000000), + (0x6b8d0400), + (0x1053a000), + (0x7bdea400), + (0x19807000), + (0x720d7400), + (0x09d3d000), + (0x625ed400), + (0x08441e00), + (0x63c91a00), + (0x1817be00), + (0x739aba00), + (0x11c46e00), + (0x7a496a00), + (0x0197ce00), + (0x6a1aca00)}, + {(0x3f800000), + (0x3fb5c682), + (0x3f8829d0), + (0x3fbdef52), + (0x3f8cc038), + (0x3fb906ba), + (0x3f84e9e8), + (0x3fb12f6a), + (0x3f84220f), + (0x3fb1e48d), + (0x3f8c0bdf), + (0x3fb9cd5d), + (0x3f88e237), + (0x3fbd24b5), + (0x3f80cbe7), + (0x3fb50d65)}, + (0xfff80000), + {0xb7,0xe4,0x3c,0x74,0x28,0xb1,0x2f,0xa4,0x5c,0x37, + 0xb1,0x69,0xd9,0x95,0x83,0xd9,0xa6,0x36,0x5b,0x12,0x00} + }, + { + /* No.105 delta:1174 weight:1019 */ + 11213, + 91, + 17, + 14, + {(0x00000000), + (0xa83f2177), + (0xa0b43c75), + (0x088b1d02), + (0x43300696), + (0xeb0f27e1), + (0xe3843ae3), + (0x4bbb1b94), + (0x00007f34), + (0xa83f5e43), + (0xa0b44341), + (0x088b6236), + (0x433079a2), + (0xeb0f58d5), + (0xe38445d7), + (0x4bbb64a0)}, + {(0x00000000), + (0x0115c000), + (0x90090000), + (0x911cc000), + (0x10422000), + (0x1157e000), + (0x804b2000), + (0x815ee000), + (0x10393e00), + (0x112cfe00), + (0x80303e00), + (0x8125fe00), + (0x007b1e00), + (0x016ede00), + (0x90721e00), + (0x9167de00)}, + {(0x3f800000), + (0x3f808ae0), + (0x3fc80480), + (0x3fc88e60), + (0x3f882110), + (0x3f88abf0), + (0x3fc02590), + (0x3fc0af70), + (0x3f881c9f), + (0x3f88967f), + (0x3fc0181f), + (0x3fc092ff), + (0x3f803d8f), + (0x3f80b76f), + (0x3fc8390f), + (0x3fc8b3ef)}, + (0xfff80000), + {0xe2,0x4f,0x2f,0xcb,0x05,0x76,0xce,0x0b,0xc7,0x7b, + 0xcc,0x65,0x06,0xce,0x2c,0x0c,0x3c,0xb6,0x2c,0x79,0x00} + }, + { + /* No.106 delta:1564 weight:925 */ + 11213, + 40, + 9, + 1, + {(0x00000000), + (0xd288f412), + (0x0b33c7cb), + (0xd9bb33d9), + (0xe0d006a8), + (0x3258f2ba), + (0xebe3c163), + (0x396b3571), + (0x00004470), + (0xd288b062), + (0x0b3383bb), + (0xd9bb77a9), + (0xe0d042d8), + (0x3258b6ca), + (0xebe38513), + (0x396b7101)}, + {(0x00000000), + (0x46794000), + (0x004d0000), + (0x46344000), + (0x007f0200), + (0x46064200), + (0x00320200), + (0x464b4200), + (0x00235e00), + (0x465a1e00), + (0x006e5e00), + (0x46171e00), + (0x005c5c00), + (0x46251c00), + (0x00115c00), + (0x46681c00)}, + {(0x3f800000), + (0x3fa33ca0), + (0x3f802680), + (0x3fa31a20), + (0x3f803f81), + (0x3fa30321), + (0x3f801901), + (0x3fa325a1), + (0x3f8011af), + (0x3fa32d0f), + (0x3f80372f), + (0x3fa30b8f), + (0x3f802e2e), + (0x3fa3128e), + (0x3f8008ae), + (0x3fa3340e)}, + (0xfff80000), + {0xc1,0x6e,0x8a,0x33,0x35,0x9f,0x07,0x03,0x76,0x11, + 0xe5,0x21,0xc3,0xdb,0x18,0x40,0x05,0xa0,0xd6,0x4c,0x00} + }, + { + /* No.107 delta:3386 weight:1851 */ + 11213, + 48, + 2, + 6, + {(0x00000000), + (0x5199ee9c), + (0x0606c085), + (0x579f2e19), + (0xe08006b0), + (0xb119e82c), + (0xe686c635), + (0xb71f28a9), + (0x000086be), + (0x51996822), + (0x0606463b), + (0x579fa8a7), + (0xe080800e), + (0xb1196e92), + (0xe686408b), + (0xb71fae17)}, + {(0x00000000), + (0x08250000), + (0x0a400800), + (0x02650800), + (0x10040000), + (0x18210000), + (0x1a440800), + (0x12610800), + (0x01081e00), + (0x092d1e00), + (0x0b481600), + (0x036d1600), + (0x110c1e00), + (0x19291e00), + (0x1b4c1600), + (0x13691600)}, + {(0x3f800000), + (0x3f841280), + (0x3f852004), + (0x3f813284), + (0x3f880200), + (0x3f8c1080), + (0x3f8d2204), + (0x3f893084), + (0x3f80840f), + (0x3f84968f), + (0x3f85a40b), + (0x3f81b68b), + (0x3f88860f), + (0x3f8c948f), + (0x3f8da60b), + (0x3f89b48b)}, + (0xfff80000), + {0x29,0x35,0xcb,0x9b,0x48,0x71,0x31,0x12,0x0b,0x2e, + 0xd3,0x98,0x06,0x50,0x05,0x3b,0xac,0x89,0x1a,0xaf,0x00} + }, + { + /* No.108 delta:2469 weight:1251 */ + 11213, + 31, + 7, + 1, + {(0x00000000), + (0x4efca9a0), + (0x3a920750), + (0x746eaef0), + (0x958006ce), + (0xdb7caf6e), + (0xaf12019e), + (0xe1eea83e), + (0x0000ee3c), + (0x4efc479c), + (0x3a92e96c), + (0x746e40cc), + (0x9580e8f2), + (0xdb7c4152), + (0xaf12efa2), + (0xe1ee4602)}, + {(0x00000000), + (0x405c0000), + (0x004ba200), + (0x4017a200), + (0x00600000), + (0x403c0000), + (0x002ba200), + (0x4077a200), + (0x80481e00), + (0xc0141e00), + (0x8003bc00), + (0xc05fbc00), + (0x80281e00), + (0xc0741e00), + (0x8063bc00), + (0xc03fbc00)}, + {(0x3f800000), + (0x3fa02e00), + (0x3f8025d1), + (0x3fa00bd1), + (0x3f803000), + (0x3fa01e00), + (0x3f8015d1), + (0x3fa03bd1), + (0x3fc0240f), + (0x3fe00a0f), + (0x3fc001de), + (0x3fe02fde), + (0x3fc0140f), + (0x3fe03a0f), + (0x3fc031de), + (0x3fe01fde)}, + (0xfff80000), + {0x05,0x56,0x79,0x8d,0xa1,0x79,0x94,0x9b,0xfd,0xfa, + 0xd1,0xd9,0x42,0x04,0x4f,0x21,0x8e,0xdb,0xe7,0xa3,0x00} + }, + { + /* No.109 delta:997 weight:681 */ + 11213, + 71, + 19, + 5, + {(0x00000000), + (0x21e405bb), + (0x4f97981d), + (0x6e739da6), + (0x01d006d7), + (0x2034036c), + (0x4e479eca), + (0x6fa39b71), + (0x0000e6b0), + (0x21e4e30b), + (0x4f977ead), + (0x6e737b16), + (0x01d0e067), + (0x2034e5dc), + (0x4e47787a), + (0x6fa37dc1)}, + {(0x00000000), + (0x40267000), + (0x0682d000), + (0x46a4a000), + (0x11832000), + (0x51a55000), + (0x1701f000), + (0x57278000), + (0x40581e00), + (0x007e6e00), + (0x46dace00), + (0x06fcbe00), + (0x51db3e00), + (0x11fd4e00), + (0x5759ee00), + (0x177f9e00)}, + {(0x3f800000), + (0x3fa01338), + (0x3f834168), + (0x3fa35250), + (0x3f88c190), + (0x3fa8d2a8), + (0x3f8b80f8), + (0x3fab93c0), + (0x3fa02c0f), + (0x3f803f37), + (0x3fa36d67), + (0x3f837e5f), + (0x3fa8ed9f), + (0x3f88fea7), + (0x3fabacf7), + (0x3f8bbfcf)}, + (0xfff80000), + {0x33,0x76,0x14,0x81,0x56,0x54,0xf0,0x4f,0x12,0x90, + 0xf4,0x03,0x95,0x9c,0x1a,0x38,0x51,0x80,0x32,0xaa,0x00} + }, + { + /* No.110 delta:2599 weight:829 */ + 11213, + 8, + 11, + 14, + {(0x00000000), + (0x4654c25e), + (0xa8eaa1d6), + (0xeebe6388), + (0x52a006e9), + (0x14f4c4b7), + (0xfa4aa73f), + (0xbc1e6561), + (0x000019ff), + (0x4654dba1), + (0xa8eab829), + (0xeebe7a77), + (0x52a01f16), + (0x14f4dd48), + (0xfa4abec0), + (0xbc1e7c9e)}, + {(0x00000000), + (0xfe272000), + (0x8207f000), + (0x7c20d000), + (0x4e344800), + (0xb0136800), + (0xcc33b800), + (0x32149800), + (0x01611e00), + (0xff463e00), + (0x8366ee00), + (0x7d41ce00), + (0x4f555600), + (0xb1727600), + (0xcd52a600), + (0x33758600)}, + {(0x3f800000), + (0x3fff1390), + (0x3fc103f8), + (0x3fbe1068), + (0x3fa71a24), + (0x3fd809b4), + (0x3fe619dc), + (0x3f990a4c), + (0x3f80b08f), + (0x3fffa31f), + (0x3fc1b377), + (0x3fbea0e7), + (0x3fa7aaab), + (0x3fd8b93b), + (0x3fe6a953), + (0x3f99bac3)}, + (0xfff80000), + {0xe0,0x6d,0x93,0xcf,0x6d,0x0f,0xa4,0xf7,0x93,0x3e, + 0x67,0xb4,0x20,0xb8,0x51,0x3a,0xe3,0xcd,0xf5,0xf9,0x00} + }, + { + /* No.111 delta:2048 weight:1649 */ + 11213, + 12, + 8, + 4, + {(0x00000000), + (0xbf40afc5), + (0xdef9c9b1), + (0x61b96674), + (0xfee006f8), + (0x41a0a93d), + (0x2019cf49), + (0x9f59608c), + (0x000056c5), + (0xbf40f900), + (0xdef99f74), + (0x61b930b1), + (0xfee0503d), + (0x41a0fff8), + (0x2019998c), + (0x9f593649)}, + {(0x00000000), + (0x2fa10c00), + (0x020b0000), + (0x2daa0c00), + (0x020ae000), + (0x2dabec00), + (0x0001e000), + (0x2fa0ec00), + (0x28021e00), + (0x07a31200), + (0x2a091e00), + (0x05a81200), + (0x2a08fe00), + (0x05a9f200), + (0x2803fe00), + (0x07a2f200)}, + {(0x3f800000), + (0x3f97d086), + (0x3f810580), + (0x3f96d506), + (0x3f810570), + (0x3f96d5f6), + (0x3f8000f0), + (0x3f97d076), + (0x3f94010f), + (0x3f83d189), + (0x3f95048f), + (0x3f82d409), + (0x3f95047f), + (0x3f82d4f9), + (0x3f9401ff), + (0x3f83d179)}, + (0xfff80000), + {0x4a,0x15,0xe8,0xf1,0x59,0x83,0x8e,0x52,0x8a,0x24, + 0xa4,0xb5,0x5d,0xfb,0x87,0xe0,0x22,0xe3,0x18,0x37,0x00} + }, + { + /* No.112 delta:2152 weight:1369 */ + 11213, + 81, + 6, + 10, + {(0x00000000), + (0xfbea0aeb), + (0xba6ad14d), + (0x4180dba6), + (0x21e00705), + (0xda0a0dee), + (0x9b8ad648), + (0x6060dca3), + (0x00003510), + (0xfbea3ffb), + (0xba6ae45d), + (0x4180eeb6), + (0x21e03215), + (0xda0a38fe), + (0x9b8ae358), + (0x6060e9b3)}, + {(0x00000000), + (0x01428000), + (0x04604000), + (0x0522c000), + (0x00081000), + (0x014a9000), + (0x04685000), + (0x052ad000), + (0x20261e00), + (0x21649e00), + (0x24465e00), + (0x2504de00), + (0x202e0e00), + (0x216c8e00), + (0x244e4e00), + (0x250cce00)}, + {(0x3f800000), + (0x3f80a140), + (0x3f823020), + (0x3f829160), + (0x3f800408), + (0x3f80a548), + (0x3f823428), + (0x3f829568), + (0x3f90130f), + (0x3f90b24f), + (0x3f92232f), + (0x3f92826f), + (0x3f901707), + (0x3f90b647), + (0x3f922727), + (0x3f928667)}, + (0xfff80000), + {0xfd,0x72,0xaa,0xc7,0x20,0x44,0x28,0xe5,0x03,0x3e, + 0xf9,0x6d,0xad,0x9f,0x51,0x0c,0x87,0xf6,0x43,0x0f,0x00} + }, + { + /* No.113 delta:1871 weight:1215 */ + 11213, + 61, + 14, + 10, + {(0x00000000), + (0x11856d8d), + (0xaac84415), + (0xbb4d2998), + (0xae00071a), + (0xbf856a97), + (0x04c8430f), + (0x154d2e82), + (0x0000cc65), + (0x1185a1e8), + (0xaac88870), + (0xbb4de5fd), + (0xae00cb7f), + (0xbf85a6f2), + (0x04c88f6a), + (0x154de2e7)}, + {(0x00000000), + (0x006d0000), + (0x00b10000), + (0x00dc0000), + (0x04490000), + (0x04240000), + (0x04f80000), + (0x04950000), + (0x00421e00), + (0x002f1e00), + (0x00f31e00), + (0x009e1e00), + (0x040b1e00), + (0x04661e00), + (0x04ba1e00), + (0x04d71e00)}, + {(0x3f800000), + (0x3f803680), + (0x3f805880), + (0x3f806e00), + (0x3f822480), + (0x3f821200), + (0x3f827c00), + (0x3f824a80), + (0x3f80210f), + (0x3f80178f), + (0x3f80798f), + (0x3f804f0f), + (0x3f82058f), + (0x3f82330f), + (0x3f825d0f), + (0x3f826b8f)}, + (0xfff80000), + {0x98,0xdb,0x7c,0xec,0x90,0x27,0x75,0x69,0x6c,0x3d, + 0x4c,0xec,0xa2,0x8e,0xab,0xef,0xd1,0x0c,0xbd,0x8c,0x00} + }, + { + /* No.114 delta:1950 weight:1011 */ + 11213, + 20, + 16, + 13, + {(0x00000000), + (0xbdc99be3), + (0xaafee229), + (0x173779ca), + (0x7300072e), + (0xcec99ccd), + (0xd9fee507), + (0x64377ee4), + (0x0000b504), + (0xbdc92ee7), + (0xaafe572d), + (0x1737ccce), + (0x7300b22a), + (0xcec929c9), + (0xd9fe5003), + (0x6437cbe0)}, + {(0x00000000), + (0x016ec000), + (0x8ce40000), + (0x8d8ac000), + (0x1c548000), + (0x1d3a4000), + (0x90b08000), + (0x91de4000), + (0x00869e00), + (0x01e85e00), + (0x8c629e00), + (0x8d0c5e00), + (0x1cd21e00), + (0x1dbcde00), + (0x90361e00), + (0x9158de00)}, + {(0x3f800000), + (0x3f80b760), + (0x3fc67200), + (0x3fc6c560), + (0x3f8e2a40), + (0x3f8e9d20), + (0x3fc85840), + (0x3fc8ef20), + (0x3f80434f), + (0x3f80f42f), + (0x3fc6314f), + (0x3fc6862f), + (0x3f8e690f), + (0x3f8ede6f), + (0x3fc81b0f), + (0x3fc8ac6f)}, + (0xfff80000), + {0xa7,0x22,0x09,0x2a,0x46,0xe2,0xa3,0x13,0x26,0x8f, + 0xa5,0xc6,0x28,0x12,0x57,0xb4,0x27,0x86,0xf1,0x1d,0x00} + }, + { + /* No.115 delta:1732 weight:1445 */ + 11213, + 29, + 17, + 7, + {(0x00000000), + (0xdb25076c), + (0x9bf7e9d5), + (0x40d2eeb9), + (0x95f00737), + (0x4ed5005b), + (0x0e07eee2), + (0xd522e98e), + (0x0000f5f0), + (0xdb25f29c), + (0x9bf71c25), + (0x40d21b49), + (0x95f0f2c7), + (0x4ed5f5ab), + (0x0e071b12), + (0xd5221c7e)}, + {(0x00000000), + (0x481e0000), + (0x80040000), + (0xc81a0000), + (0x007d0000), + (0x48630000), + (0x80790000), + (0xc8670000), + (0x40121e00), + (0x080c1e00), + (0xc0161e00), + (0x88081e00), + (0x406f1e00), + (0x08711e00), + (0xc06b1e00), + (0x88751e00)}, + {(0x3f800000), + (0x3fa40f00), + (0x3fc00200), + (0x3fe40d00), + (0x3f803e80), + (0x3fa43180), + (0x3fc03c80), + (0x3fe43380), + (0x3fa0090f), + (0x3f84060f), + (0x3fe00b0f), + (0x3fc4040f), + (0x3fa0378f), + (0x3f84388f), + (0x3fe0358f), + (0x3fc43a8f)}, + (0xfff80000), + {0xc2,0xbe,0xe6,0x5f,0xf5,0x28,0x34,0x1c,0x5e,0x2d, + 0xdb,0x99,0x36,0x5d,0x04,0x52,0x9e,0x76,0x9e,0xd5,0x00} + }, + { + /* No.116 delta:1707 weight:1245 */ + 11213, + 30, + 22, + 3, + {(0x00000000), + (0x0a5f3de8), + (0xcb7a16d6), + (0xc1252b3e), + (0xfcd0074b), + (0xf68f3aa3), + (0x37aa119d), + (0x3df52c75), + (0x00003bff), + (0x0a5f0617), + (0xcb7a2d29), + (0xc12510c1), + (0xfcd03cb4), + (0xf68f015c), + (0x37aa2a62), + (0x3df5178a)}, + {(0x00000000), + (0x402e8e00), + (0x0073d000), + (0x405d5e00), + (0x206d4000), + (0x6043ce00), + (0x201e9000), + (0x60301e00), + (0xd21dfe00), + (0x92337000), + (0xd26e2e00), + (0x9240a000), + (0xf270be00), + (0xb25e3000), + (0xf2036e00), + (0xb22de000)}, + {(0x3f800000), + (0x3fa01747), + (0x3f8039e8), + (0x3fa02eaf), + (0x3f9036a0), + (0x3fb021e7), + (0x3f900f48), + (0x3fb0180f), + (0x3fe90eff), + (0x3fc919b8), + (0x3fe93717), + (0x3fc92050), + (0x3ff9385f), + (0x3fd92f18), + (0x3ff901b7), + (0x3fd916f0)}, + (0xfff80000), + {0x30,0x04,0x85,0xba,0x89,0x2d,0x19,0x39,0x57,0x1c, + 0x54,0xa8,0xb5,0x0a,0x05,0x27,0x14,0x6a,0xed,0xe0,0x00} + }, + { + /* No.117 delta:2917 weight:1743 */ + 11213, + 37, + 3, + 6, + {(0x00000000), + (0x501b23d2), + (0x2770f82a), + (0x776bdbf8), + (0x67300751), + (0x372b2483), + (0x4040ff7b), + (0x105bdca9), + (0x000038d9), + (0x501b1b0b), + (0x2770c0f3), + (0x776be321), + (0x67303f88), + (0x372b1c5a), + (0x4040c7a2), + (0x105be470)}, + {(0x00000000), + (0x20542200), + (0x40387800), + (0x606c5a00), + (0x14402000), + (0x34140200), + (0x54785800), + (0x742c7a00), + (0x1840de00), + (0x3814fc00), + (0x5878a600), + (0x782c8400), + (0x0c00fe00), + (0x2c54dc00), + (0x4c388600), + (0x6c6ca400)}, + {(0x3f800000), + (0x3f902a11), + (0x3fa01c3c), + (0x3fb0362d), + (0x3f8a2010), + (0x3f9a0a01), + (0x3faa3c2c), + (0x3fba163d), + (0x3f8c206f), + (0x3f9c0a7e), + (0x3fac3c53), + (0x3fbc1642), + (0x3f86007f), + (0x3f962a6e), + (0x3fa61c43), + (0x3fb63652)}, + (0xfff80000), + {0x86,0x60,0xf6,0x24,0x0e,0xff,0xd7,0xe9,0x32,0x8f, + 0xa0,0x96,0x77,0x67,0x0e,0xec,0x2e,0x00,0x3b,0x13,0x00} + }, + { + /* No.118 delta:983 weight:1587 */ + 11213, + 62, + 19, + 4, + {(0x00000000), + (0x08eb784a), + (0x736759ff), + (0x7b8c21b5), + (0x0ca0076b), + (0x044b7f21), + (0x7fc75e94), + (0x772c26de), + (0x0000d939), + (0x08eba173), + (0x736780c6), + (0x7b8cf88c), + (0x0ca0de52), + (0x044ba618), + (0x7fc787ad), + (0x772cffe7)}, + {(0x00000000), + (0x041eba00), + (0x20637000), + (0x247dca00), + (0x20110000), + (0x240fba00), + (0x00727000), + (0x046cca00), + (0x10001e00), + (0x141ea400), + (0x30636e00), + (0x347dd400), + (0x30111e00), + (0x340fa400), + (0x10726e00), + (0x146cd400)}, + {(0x3f800000), + (0x3f820f5d), + (0x3f9031b8), + (0x3f923ee5), + (0x3f900880), + (0x3f9207dd), + (0x3f803938), + (0x3f823665), + (0x3f88000f), + (0x3f8a0f52), + (0x3f9831b7), + (0x3f9a3eea), + (0x3f98088f), + (0x3f9a07d2), + (0x3f883937), + (0x3f8a366a)}, + (0xfff80000), + {0x70,0x7f,0x78,0xb3,0x65,0x02,0xe0,0xb9,0x55,0x49, + 0xd9,0x60,0xa8,0xa5,0xd3,0x10,0x3b,0x08,0x55,0xfd,0x00} + }, + { + /* No.119 delta:1397 weight:1065 */ + 11213, + 57, + 14, + 11, + {(0x00000000), + (0x5e421ddc), + (0x638787c4), + (0x3dc59a18), + (0x8e00077d), + (0xd0421aa1), + (0xed8780b9), + (0xb3c59d65), + (0x0000840f), + (0x5e4299d3), + (0x638703cb), + (0x3dc51e17), + (0x8e008372), + (0xd0429eae), + (0xed8704b6), + (0xb3c5196a)}, + {(0x00000000), + (0x08e5ec00), + (0x245ea400), + (0x2cbb4800), + (0x00688000), + (0x088d6c00), + (0x24362400), + (0x2cd3c800), + (0x00111e00), + (0x08f4f200), + (0x244fba00), + (0x2caa5600), + (0x00799e00), + (0x089c7200), + (0x24273a00), + (0x2cc2d600)}, + {(0x3f800000), + (0x3f8472f6), + (0x3f922f52), + (0x3f965da4), + (0x3f803440), + (0x3f8446b6), + (0x3f921b12), + (0x3f9669e4), + (0x3f80088f), + (0x3f847a79), + (0x3f9227dd), + (0x3f96552b), + (0x3f803ccf), + (0x3f844e39), + (0x3f92139d), + (0x3f96616b)}, + (0xfff80000), + {0x72,0xeb,0x0e,0x84,0xe7,0xef,0x0c,0xb3,0x72,0xaf, + 0x80,0x06,0xbc,0xf9,0x33,0xf7,0x21,0x72,0x27,0x28,0x00} + }, + { + /* No.120 delta:1392 weight:827 */ + 11213, + 46, + 15, + 17, + {(0x00000000), + (0xa557bf77), + (0x097f4c89), + (0xac28f3fe), + (0xffa0078b), + (0x5af7b8fc), + (0xf6df4b02), + (0x5388f475), + (0x00006249), + (0xa557dd3e), + (0x097f2ec0), + (0xac2891b7), + (0xffa065c2), + (0x5af7dab5), + (0xf6df294b), + (0x5388963c)}, + {(0x00000000), + (0x68748400), + (0x4200ae00), + (0x2a742a00), + (0x1c086000), + (0x747ce400), + (0x5e08ce00), + (0x367c4a00), + (0x0046fe00), + (0x68327a00), + (0x42465000), + (0x2a32d400), + (0x1c4e9e00), + (0x743a1a00), + (0x5e4e3000), + (0x363ab400)}, + {(0x3f800000), + (0x3fb43a42), + (0x3fa10057), + (0x3f953a15), + (0x3f8e0430), + (0x3fba3e72), + (0x3faf0467), + (0x3f9b3e25), + (0x3f80237f), + (0x3fb4193d), + (0x3fa12328), + (0x3f95196a), + (0x3f8e274f), + (0x3fba1d0d), + (0x3faf2718), + (0x3f9b1d5a)}, + (0xfff80000), + {0x7c,0xb2,0x6a,0xff,0x78,0xfa,0xd6,0x78,0xf9,0xba, + 0x77,0x1d,0x84,0xb3,0xbb,0xcb,0xac,0xdf,0x51,0x54,0x00} + }, + { + /* No.121 delta:1663 weight:775 */ + 11213, + 82, + 9, + 17, + {(0x00000000), + (0x1fe0e7a6), + (0x67406a7f), + (0x78a08dd9), + (0xda30079d), + (0xc5d0e03b), + (0xbd706de2), + (0xa2908a44), + (0x000076e4), + (0x1fe09142), + (0x67401c9b), + (0x78a0fb3d), + (0xda307179), + (0xc5d096df), + (0xbd701b06), + (0xa290fca0)}, + {(0x00000000), + (0x100e1000), + (0x20734000), + (0x307d5000), + (0x5008e200), + (0x4006f200), + (0x707ba200), + (0x6075b200), + (0x3242de00), + (0x224cce00), + (0x12319e00), + (0x023f8e00), + (0x624a3c00), + (0x72442c00), + (0x42397c00), + (0x52376c00)}, + {(0x3f800000), + (0x3f880708), + (0x3f9039a0), + (0x3f983ea8), + (0x3fa80471), + (0x3fa00379), + (0x3fb83dd1), + (0x3fb03ad9), + (0x3f99216f), + (0x3f912667), + (0x3f8918cf), + (0x3f811fc7), + (0x3fb1251e), + (0x3fb92216), + (0x3fa11cbe), + (0x3fa91bb6)}, + (0xfff80000), + {0xa3,0xd8,0x55,0xcd,0x98,0xdc,0x68,0x95,0x68,0xdf, + 0xcf,0x56,0x03,0x2a,0x94,0x75,0x10,0xec,0x0a,0x47,0x00} + }, + { + /* No.122 delta:1328 weight:751 */ + 11213, + 67, + 14, + 18, + {(0x00000000), + (0x76bc3aa8), + (0xc37bdc20), + (0xb5c7e688), + (0x38b007ab), + (0x4e0c3d03), + (0xfbcbdb8b), + (0x8d77e123), + (0x0000bd02), + (0x76bc87aa), + (0xc37b6122), + (0xb5c75b8a), + (0x38b0baa9), + (0x4e0c8001), + (0xfbcb6689), + (0x8d775c21)}, + {(0x00000000), + (0x1112c200), + (0x18038000), + (0x09114200), + (0x00065000), + (0x11149200), + (0x1805d000), + (0x09171200), + (0x6001de00), + (0x71131c00), + (0x78025e00), + (0x69109c00), + (0x60078e00), + (0x71154c00), + (0x78040e00), + (0x6916cc00)}, + {(0x3f800000), + (0x3f888961), + (0x3f8c01c0), + (0x3f8488a1), + (0x3f800328), + (0x3f888a49), + (0x3f8c02e8), + (0x3f848b89), + (0x3fb000ef), + (0x3fb8898e), + (0x3fbc012f), + (0x3fb4884e), + (0x3fb003c7), + (0x3fb88aa6), + (0x3fbc0207), + (0x3fb48b66)}, + (0xfff80000), + {0x18,0x30,0x32,0x35,0xe2,0xb4,0xcd,0x94,0x5e,0x6b, + 0xe6,0x78,0x0b,0x92,0x24,0xbf,0x7c,0xc5,0xbd,0xe2,0x00} + }, + { + /* No.123 delta:1657 weight:573 */ + 11213, + 70, + 8, + 19, + {(0x00000000), + (0xfd59bd60), + (0xe0041fb5), + (0x1d5da2d5), + (0x836007b6), + (0x7e39bad6), + (0x63641803), + (0x9e3da563), + (0x0000b1f6), + (0xfd590c96), + (0xe004ae43), + (0x1d5d1323), + (0x8360b640), + (0x7e390b20), + (0x6364a9f5), + (0x9e3d1495)}, + {(0x00000000), + (0x57b14800), + (0x5868a400), + (0x0fd9ec00), + (0x084c7000), + (0x5ffd3800), + (0x5024d400), + (0x07959c00), + (0x10121e00), + (0x47a35600), + (0x487aba00), + (0x1fcbf200), + (0x185e6e00), + (0x4fef2600), + (0x4036ca00), + (0x17878200)}, + {(0x3f800000), + (0x3fabd8a4), + (0x3fac3452), + (0x3f87ecf6), + (0x3f842638), + (0x3faffe9c), + (0x3fa8126a), + (0x3f83cace), + (0x3f88090f), + (0x3fa3d1ab), + (0x3fa43d5d), + (0x3f8fe5f9), + (0x3f8c2f37), + (0x3fa7f793), + (0x3fa01b65), + (0x3f8bc3c1)}, + (0xfff80000), + {0x0b,0xcb,0xeb,0x33,0x75,0x01,0x5e,0xeb,0x92,0xfb, + 0x37,0xae,0xe0,0x31,0x80,0xa9,0x06,0x42,0x2b,0xd5,0x00} + }, + { + /* No.124 delta:1016 weight:1635 */ + 11213, + 80, + 18, + 2, + {(0x00000000), + (0x65b814ab), + (0x0b7c8e4e), + (0x6ec49ae5), + (0xe3e007c1), + (0x8658136a), + (0xe89c898f), + (0x8d249d24), + (0x00008bf0), + (0x65b89f5b), + (0x0b7c05be), + (0x6ec41115), + (0xe3e08c31), + (0x8658989a), + (0xe89c027f), + (0x8d2416d4)}, + {(0x00000000), + (0x110f9000), + (0x08401000), + (0x194f8000), + (0x20040000), + (0x310b9000), + (0x28441000), + (0x394b8000), + (0x00025e00), + (0x110dce00), + (0x08424e00), + (0x194dde00), + (0x20065e00), + (0x3109ce00), + (0x28464e00), + (0x3949de00)}, + {(0x3f800000), + (0x3f8887c8), + (0x3f842008), + (0x3f8ca7c0), + (0x3f900200), + (0x3f9885c8), + (0x3f942208), + (0x3f9ca5c0), + (0x3f80012f), + (0x3f8886e7), + (0x3f842127), + (0x3f8ca6ef), + (0x3f90032f), + (0x3f9884e7), + (0x3f942327), + (0x3f9ca4ef)}, + (0xfff80000), + {0xe8,0x1c,0x9d,0xcc,0x4a,0x97,0xc0,0xae,0x9d,0xce, + 0x1a,0xa4,0x45,0x9f,0x41,0xc4,0x83,0xd9,0x62,0x72,0x00} + }, + { + /* No.125 delta:1214 weight:1175 */ + 11213, + 28, + 16, + 7, + {(0x00000000), + (0x7b11b46d), + (0x3e529f7c), + (0x45432b11), + (0x05a007d2), + (0x7eb1b3bf), + (0x3bf298ae), + (0x40e32cc3), + (0x00001cdb), + (0x7b11a8b6), + (0x3e5283a7), + (0x454337ca), + (0x05a01b09), + (0x7eb1af64), + (0x3bf28475), + (0x40e33018)}, + {(0x00000000), + (0x4460cc00), + (0x50de6c00), + (0x14bea000), + (0x43011e00), + (0x0761d200), + (0x13df7200), + (0x57bfbe00), + (0x41807e00), + (0x05e0b200), + (0x115e1200), + (0x553ede00), + (0x02816000), + (0x46e1ac00), + (0x525f0c00), + (0x163fc000)}, + {(0x3f800000), + (0x3fa23066), + (0x3fa86f36), + (0x3f8a5f50), + (0x3fa1808f), + (0x3f83b0e9), + (0x3f89efb9), + (0x3fabdfdf), + (0x3fa0c03f), + (0x3f82f059), + (0x3f88af09), + (0x3faa9f6f), + (0x3f8140b0), + (0x3fa370d6), + (0x3fa92f86), + (0x3f8b1fe0)}, + (0xfff80000), + {0x5c,0x4c,0x7f,0xad,0xc2,0x0a,0xe3,0x36,0x3a,0x3f, + 0x3e,0x28,0x97,0x26,0xce,0xab,0xdb,0x12,0x07,0x20,0x00} + }, + { + /* No.126 delta:962 weight:1245 */ + 11213, + 78, + 18, + 5, + {(0x00000000), + (0xee0a807e), + (0xe937683b), + (0x073de845), + (0x14f007e9), + (0xfafa8797), + (0xfdc76fd2), + (0x13cdefac), + (0x0000f676), + (0xee0a7608), + (0xe9379e4d), + (0x073d1e33), + (0x14f0f19f), + (0xfafa71e1), + (0xfdc799a4), + (0x13cd19da)}, + {(0x00000000), + (0xb028bc00), + (0x08652400), + (0xb84d9800), + (0x14028600), + (0xa42a3a00), + (0x1c67a200), + (0xac4f1e00), + (0x00023e00), + (0xb02a8200), + (0x08671a00), + (0xb84fa600), + (0x1400b800), + (0xa4280400), + (0x1c659c00), + (0xac4d2000)}, + {(0x3f800000), + (0x3fd8145e), + (0x3f843292), + (0x3fdc26cc), + (0x3f8a0143), + (0x3fd2151d), + (0x3f8e33d1), + (0x3fd6278f), + (0x3f80011f), + (0x3fd81541), + (0x3f84338d), + (0x3fdc27d3), + (0x3f8a005c), + (0x3fd21402), + (0x3f8e32ce), + (0x3fd62690)}, + (0xfff80000), + {0x1f,0xae,0x0b,0x7d,0x23,0x0c,0x6e,0xd6,0x26,0xa9, + 0x92,0xbc,0x8f,0x01,0x36,0x36,0x07,0xe9,0x2c,0x7c,0x00} + }, + { + /* No.127 delta:4656 weight:1185 */ + 11213, + 57, + 4, + 13, + {(0x00000000), + (0x7d46d3c2), + (0x107426fc), + (0x6d32f53e), + (0x832007fe), + (0xfe66d43c), + (0x93542102), + (0xee12f2c0), + (0x00009ac7), + (0x7d464905), + (0x1074bc3b), + (0x6d326ff9), + (0x83209d39), + (0xfe664efb), + (0x9354bbc5), + (0xee126807)}, + {(0x00000000), + (0x18401000), + (0x14000000), + (0x0c401000), + (0x00000000), + (0x18401000), + (0x14000000), + (0x0c401000), + (0x10001e00), + (0x08400e00), + (0x04001e00), + (0x1c400e00), + (0x10001e00), + (0x08400e00), + (0x04001e00), + (0x1c400e00)}, + {(0x3f800000), + (0x3f8c2008), + (0x3f8a0000), + (0x3f862008), + (0x3f800000), + (0x3f8c2008), + (0x3f8a0000), + (0x3f862008), + (0x3f88000f), + (0x3f842007), + (0x3f82000f), + (0x3f8e2007), + (0x3f88000f), + (0x3f842007), + (0x3f82000f), + (0x3f8e2007)}, + (0xfff80000), + {0x2b,0xf5,0xba,0x2c,0x06,0x65,0xd9,0xae,0x19,0x02, + 0xa4,0xb4,0xe6,0x92,0x03,0x77,0xb7,0xb8,0x8c,0x23,0x00} + }, + { + /* No.128 delta:2214 weight:1371 */ + 11213, + 43, + 23, + 2, + {(0x00000000), + (0xe454d1ab), + (0x80c8a6d9), + (0x649c7772), + (0xb0f00808), + (0x54a4d9a3), + (0x3038aed1), + (0xd46c7f7a), + (0x00004f07), + (0xe4549eac), + (0x80c8e9de), + (0x649c3875), + (0xb0f0470f), + (0x54a496a4), + (0x3038e1d6), + (0xd46c307d)}, + {(0x00000000), + (0xca494000), + (0x00538000), + (0xca1ac000), + (0x10bd2000), + (0xdaf46000), + (0x10eea000), + (0xdaa7e000), + (0x18905e00), + (0xd2d91e00), + (0x18c3de00), + (0xd28a9e00), + (0x082d7e00), + (0xc2643e00), + (0x087efe00), + (0xc237be00)}, + {(0x3f800000), + (0x3fe524a0), + (0x3f8029c0), + (0x3fe50d60), + (0x3f885e90), + (0x3fed7a30), + (0x3f887750), + (0x3fed53f0), + (0x3f8c482f), + (0x3fe96c8f), + (0x3f8c61ef), + (0x3fe9454f), + (0x3f8416bf), + (0x3fe1321f), + (0x3f843f7f), + (0x3fe11bdf)}, + (0xfff80000), + {0xf5,0xb9,0x08,0x2c,0x6d,0x40,0xb0,0x38,0xb5,0x70, + 0x83,0x86,0xbb,0x54,0xe7,0x5e,0x64,0xf3,0x40,0x61,0x00} + }, + { + /* No.129 delta:886 weight:915 */ + 11213, + 70, + 12, + 5, + {(0x00000000), + (0x242c5090), + (0x10199a60), + (0x3435caf0), + (0xe9d00810), + (0xcdfc5880), + (0xf9c99270), + (0xdde5c2e0), + (0x00003567), + (0x242c65f7), + (0x1019af07), + (0x3435ff97), + (0xe9d03d77), + (0xcdfc6de7), + (0xf9c9a717), + (0xdde5f787)}, + {(0x00000000), + (0x004e4000), + (0x1009c000), + (0x10478000), + (0x0e025000), + (0x0e4c1000), + (0x1e0b9000), + (0x1e45d000), + (0x10345e00), + (0x107a1e00), + (0x003d9e00), + (0x0073de00), + (0x1e360e00), + (0x1e784e00), + (0x0e3fce00), + (0x0e718e00)}, + {(0x3f800000), + (0x3f802720), + (0x3f8804e0), + (0x3f8823c0), + (0x3f870128), + (0x3f872608), + (0x3f8f05c8), + (0x3f8f22e8), + (0x3f881a2f), + (0x3f883d0f), + (0x3f801ecf), + (0x3f8039ef), + (0x3f8f1b07), + (0x3f8f3c27), + (0x3f871fe7), + (0x3f8738c7)}, + (0xfff80000), + {0xae,0x65,0xce,0x51,0xe8,0x63,0xb5,0x45,0x7a,0xb5, + 0x06,0x3b,0x06,0x88,0x6c,0x62,0x83,0x37,0xc8,0xb9,0x00} + }, + { + /* No.130 delta:2602 weight:1519 */ + 11213, + 18, + 4, + 6, + {(0x00000000), + (0x4fa484d0), + (0x546a6e84), + (0x1bceea54), + (0x4a400828), + (0x05e48cf8), + (0x1e2a66ac), + (0x518ee27c), + (0x0000bda0), + (0x4fa43970), + (0x546ad324), + (0x1bce57f4), + (0x4a40b588), + (0x05e43158), + (0x1e2adb0c), + (0x518e5fdc)}, + {(0x00000000), + (0x13081400), + (0x928e3000), + (0x81862400), + (0x010e0000), + (0x12061400), + (0x93803000), + (0x80882400), + (0x10581e00), + (0x03500a00), + (0x82d62e00), + (0x91de3a00), + (0x11561e00), + (0x025e0a00), + (0x83d82e00), + (0x90d03a00)}, + {(0x3f800000), + (0x3f89840a), + (0x3fc94718), + (0x3fc0c312), + (0x3f808700), + (0x3f89030a), + (0x3fc9c018), + (0x3fc04412), + (0x3f882c0f), + (0x3f81a805), + (0x3fc16b17), + (0x3fc8ef1d), + (0x3f88ab0f), + (0x3f812f05), + (0x3fc1ec17), + (0x3fc8681d)}, + (0xfff80000), + {0x13,0xcb,0x05,0x11,0x83,0xac,0xeb,0x2f,0xe5,0x15, + 0x1a,0x0e,0x87,0xa3,0x4d,0xac,0x2b,0xc0,0xb1,0xf3,0x00} + }, + { + /* No.131 delta:1006 weight:1303 */ + 11213, + 69, + 16, + 7, + {(0x00000000), + (0xeb61a85a), + (0x9e89b6f4), + (0x75e81eae), + (0x4cc00837), + (0xa7a1a06d), + (0xd249bec3), + (0x39281699), + (0x00006d8a), + (0xeb61c5d0), + (0x9e89db7e), + (0x75e87324), + (0x4cc065bd), + (0xa7a1cde7), + (0xd249d349), + (0x39287b13)}, + {(0x00000000), + (0x20bcb000), + (0x51807000), + (0x713cc000), + (0x02a2a000), + (0x221e1000), + (0x5322d000), + (0x739e6000), + (0x00067e00), + (0x20bace00), + (0x51860e00), + (0x713abe00), + (0x02a4de00), + (0x22186e00), + (0x5324ae00), + (0x73981e00)}, + {(0x3f800000), + (0x3f905e58), + (0x3fa8c038), + (0x3fb89e60), + (0x3f815150), + (0x3f910f08), + (0x3fa99168), + (0x3fb9cf30), + (0x3f80033f), + (0x3f905d67), + (0x3fa8c307), + (0x3fb89d5f), + (0x3f81526f), + (0x3f910c37), + (0x3fa99257), + (0x3fb9cc0f)}, + (0xfff80000), + {0xbc,0xf3,0x6a,0x80,0xa6,0xee,0x61,0x78,0xa8,0x3d, + 0x8c,0xee,0x29,0x1b,0x5e,0xfd,0x0b,0xf8,0x0f,0x41,0x00} + }, + { + /* No.132 delta:2899 weight:1651 */ + 11213, + 57, + 3, + 7, + {(0x00000000), + (0x7a913b6d), + (0xeed573ba), + (0x944448d7), + (0xfbd00846), + (0x8141332b), + (0x15057bfc), + (0x6f944091), + (0x00003675), + (0x7a910d18), + (0xeed545cf), + (0x94447ea2), + (0xfbd03e33), + (0x8141055e), + (0x15054d89), + (0x6f9476e4)}, + {(0x00000000), + (0x28410000), + (0x92350000), + (0xba740000), + (0x00601000), + (0x28211000), + (0x92551000), + (0xba141000), + (0x20161e00), + (0x08571e00), + (0xb2231e00), + (0x9a621e00), + (0x20760e00), + (0x08370e00), + (0xb2430e00), + (0x9a020e00)}, + {(0x3f800000), + (0x3f942080), + (0x3fc91a80), + (0x3fdd3a00), + (0x3f803008), + (0x3f941088), + (0x3fc92a88), + (0x3fdd0a08), + (0x3f900b0f), + (0x3f842b8f), + (0x3fd9118f), + (0x3fcd310f), + (0x3f903b07), + (0x3f841b87), + (0x3fd92187), + (0x3fcd0107)}, + (0xfff80000), + {0xa3,0x9f,0x64,0xc5,0x74,0x6d,0x2d,0x17,0xe7,0x4d, + 0x9a,0xaf,0xeb,0xb2,0x24,0x54,0x22,0x7a,0x93,0x8c,0x00} + }, + { + /* No.133 delta:1681 weight:1015 */ + 11213, + 83, + 12, + 13, + {(0x00000000), + (0x9193fd4c), + (0x375d8e7c), + (0xa6ce7330), + (0xbf90085d), + (0x2e03f511), + (0x88cd8621), + (0x195e7b6d), + (0x0000af07), + (0x9193524b), + (0x375d217b), + (0xa6cedc37), + (0xbf90a75a), + (0x2e035a16), + (0x88cd2926), + (0x195ed46a)}, + {(0x00000000), + (0x10740800), + (0x200dc000), + (0x3079c800), + (0x2056f800), + (0x3022f000), + (0x005b3800), + (0x102f3000), + (0x20031e00), + (0x30771600), + (0x000ede00), + (0x107ad600), + (0x0055e600), + (0x1021ee00), + (0x20582600), + (0x302c2e00)}, + {(0x3f800000), + (0x3f883a04), + (0x3f9006e0), + (0x3f983ce4), + (0x3f902b7c), + (0x3f981178), + (0x3f802d9c), + (0x3f881798), + (0x3f90018f), + (0x3f983b8b), + (0x3f80076f), + (0x3f883d6b), + (0x3f802af3), + (0x3f8810f7), + (0x3f902c13), + (0x3f981617)}, + (0xfff80000), + {0x5d,0xf8,0x9e,0x34,0xb8,0x35,0x07,0x7f,0xd2,0xe0, + 0x4f,0x6e,0x48,0xe9,0xdf,0x81,0x9d,0xf1,0x95,0x7a,0x00} + }, + { + /* No.134 delta:2863 weight:755 */ + 11213, + 84, + 6, + 17, + {(0x00000000), + (0x61047d07), + (0x957fb46d), + (0xf47bc96a), + (0x58f00860), + (0x39f47567), + (0xcd8fbc0d), + (0xac8bc10a), + (0x0000e9c0), + (0x610494c7), + (0x957f5dad), + (0xf47b20aa), + (0x58f0e1a0), + (0x39f49ca7), + (0xcd8f55cd), + (0xac8b28ca)}, + {(0x00000000), + (0x007c0000), + (0x13020000), + (0x137e0000), + (0x00020000), + (0x007e0000), + (0x13000000), + (0x137c0000), + (0x20401e00), + (0x203c1e00), + (0x33421e00), + (0x333e1e00), + (0x20421e00), + (0x203e1e00), + (0x33401e00), + (0x333c1e00)}, + {(0x3f800000), + (0x3f803e00), + (0x3f898100), + (0x3f89bf00), + (0x3f800100), + (0x3f803f00), + (0x3f898000), + (0x3f89be00), + (0x3f90200f), + (0x3f901e0f), + (0x3f99a10f), + (0x3f999f0f), + (0x3f90210f), + (0x3f901f0f), + (0x3f99a00f), + (0x3f999e0f)}, + (0xfff80000), + {0xcf,0x5c,0xa5,0xf4,0x7e,0x51,0x25,0xe8,0xf1,0x2b, + 0x6a,0x13,0xd4,0x31,0xca,0x76,0x97,0x3d,0x44,0x1a,0x00} + }, + { + /* No.135 delta:1967 weight:665 */ + 11213, + 19, + 12, + 19, + {(0x00000000), + (0xabbc4cf0), + (0xdf51c626), + (0x74ed8ad6), + (0x74a00878), + (0xdf1c4488), + (0xabf1ce5e), + (0x004d82ae), + (0x0000858b), + (0xabbcc97b), + (0xdf5143ad), + (0x74ed0f5d), + (0x74a08df3), + (0xdf1cc103), + (0xabf14bd5), + (0x004d0725)}, + {(0x00000000), + (0x41001800), + (0x004bc000), + (0x414bd800), + (0x8b86e200), + (0xca86fa00), + (0x8bcd2200), + (0xcacd3a00), + (0x70061e00), + (0x31060600), + (0x704dde00), + (0x314dc600), + (0xfb80fc00), + (0xba80e400), + (0xfbcb3c00), + (0xbacb2400)}, + {(0x3f800000), + (0x3fa0800c), + (0x3f8025e0), + (0x3fa0a5ec), + (0x3fc5c371), + (0x3fe5437d), + (0x3fc5e691), + (0x3fe5669d), + (0x3fb8030f), + (0x3f988303), + (0x3fb826ef), + (0x3f98a6e3), + (0x3ffdc07e), + (0x3fdd4072), + (0x3ffde59e), + (0x3fdd6592)}, + (0xfff80000), + {0xa2,0xe2,0xa5,0xe0,0x11,0x34,0xcb,0xf8,0xfc,0xa2, + 0x71,0xc6,0xbf,0xe2,0xc1,0x23,0x58,0x95,0xf4,0x86,0x00} + }, + { + /* No.136 delta:918 weight:1551 */ + 11213, + 47, + 18, + 4, + {(0x00000000), + (0x09adadc4), + (0xf017020b), + (0xf9baafcf), + (0x03300880), + (0x0a9da544), + (0xf3270a8b), + (0xfa8aa74f), + (0x0000cfe7), + (0x09ad6223), + (0xf017cdec), + (0xf9ba6028), + (0x0330c767), + (0x0a9d6aa3), + (0xf327c56c), + (0xfa8a68a8)}, + {(0x00000000), + (0x18747400), + (0x204c5200), + (0x38382600), + (0x10026c00), + (0x08761800), + (0x304e3e00), + (0x283a4a00), + (0x10011e00), + (0x08756a00), + (0x304d4c00), + (0x28393800), + (0x00037200), + (0x18770600), + (0x204f2000), + (0x383b5400)}, + {(0x3f800000), + (0x3f8c3a3a), + (0x3f902629), + (0x3f9c1c13), + (0x3f880136), + (0x3f843b0c), + (0x3f98271f), + (0x3f941d25), + (0x3f88008f), + (0x3f843ab5), + (0x3f9826a6), + (0x3f941c9c), + (0x3f8001b9), + (0x3f8c3b83), + (0x3f902790), + (0x3f9c1daa)}, + (0xfff80000), + {0xfd,0x25,0x81,0xf4,0x6f,0xd2,0x73,0x0c,0x1d,0xf8, + 0x3c,0x0b,0xd2,0x33,0xf7,0x54,0x12,0xcd,0x88,0xa9,0x00} + }, + { + /* No.137 delta:4265 weight:777 */ + 11213, + 70, + 4, + 16, + {(0x00000000), + (0xab4eac1a), + (0x41078fcd), + (0xea4923d7), + (0x9d20089e), + (0x366ea484), + (0xdc278753), + (0x77692b49), + (0x0000022a), + (0xab4eae30), + (0x41078de7), + (0xea4921fd), + (0x9d200ab4), + (0x366ea6ae), + (0xdc278579), + (0x77692963)}, + {(0x00000000), + (0x39400800), + (0x00500000), + (0x39100800), + (0x002c0000), + (0x396c0800), + (0x007c0000), + (0x393c0800), + (0x5e881e00), + (0x67c81600), + (0x5ed81e00), + (0x67981600), + (0x5ea41e00), + (0x67e41600), + (0x5ef41e00), + (0x67b41600)}, + {(0x3f800000), + (0x3f9ca004), + (0x3f802800), + (0x3f9c8804), + (0x3f801600), + (0x3f9cb604), + (0x3f803e00), + (0x3f9c9e04), + (0x3faf440f), + (0x3fb3e40b), + (0x3faf6c0f), + (0x3fb3cc0b), + (0x3faf520f), + (0x3fb3f20b), + (0x3faf7a0f), + (0x3fb3da0b)}, + (0xfff80000), + {0x67,0x39,0x69,0x46,0xb6,0xab,0xda,0x03,0x1a,0xb9, + 0x33,0x5c,0x43,0x1d,0xc4,0x88,0x65,0xf4,0x6e,0x7c,0x00} + }, + { + /* No.138 delta:2916 weight:1245 */ + 11213, + 12, + 4, + 11, + {(0x00000000), + (0x8bd9bb70), + (0x6536d8cf), + (0xeeef63bf), + (0x83c008a3), + (0x0819b3d3), + (0xe6f6d06c), + (0x6d2f6b1c), + (0x00006357), + (0x8bd9d827), + (0x6536bb98), + (0xeeef00e8), + (0x83c06bf4), + (0x0819d084), + (0xe6f6b33b), + (0x6d2f084b)}, + {(0x00000000), + (0x10b20000), + (0x0c210800), + (0x1c930800), + (0x29540000), + (0x39e60000), + (0x25750800), + (0x35c70800), + (0x02001e00), + (0x12b21e00), + (0x0e211600), + (0x1e931600), + (0x2b541e00), + (0x3be61e00), + (0x27751600), + (0x37c71600)}, + {(0x3f800000), + (0x3f885900), + (0x3f861084), + (0x3f8e4984), + (0x3f94aa00), + (0x3f9cf300), + (0x3f92ba84), + (0x3f9ae384), + (0x3f81000f), + (0x3f89590f), + (0x3f87108b), + (0x3f8f498b), + (0x3f95aa0f), + (0x3f9df30f), + (0x3f93ba8b), + (0x3f9be38b)}, + (0xfff80000), + {0xf3,0xfa,0x1e,0x93,0x8b,0xfb,0x73,0xc0,0xf1,0x10, + 0x33,0xac,0x5f,0x6b,0x3c,0x07,0xa2,0x98,0x75,0xed,0x00} + }, + { + /* No.139 delta:2344 weight:1631 */ + 11213, + 19, + 8, + 7, + {(0x00000000), + (0xfee0d62f), + (0x304aad76), + (0xceaa7b59), + (0x871008b7), + (0x79f0de98), + (0xb75aa5c1), + (0x49ba73ee), + (0x00003b80), + (0xfee0edaf), + (0x304a96f6), + (0xceaa40d9), + (0x87103337), + (0x79f0e518), + (0xb75a9e41), + (0x49ba486e)}, + {(0x00000000), + (0x05204400), + (0x00640000), + (0x05444400), + (0x00510400), + (0x05714000), + (0x00350400), + (0x05154000), + (0x32861e00), + (0x37a65a00), + (0x32e21e00), + (0x37c25a00), + (0x32d71a00), + (0x37f75e00), + (0x32b31a00), + (0x37935e00)}, + {(0x3f800000), + (0x3f829022), + (0x3f803200), + (0x3f82a222), + (0x3f802882), + (0x3f82b8a0), + (0x3f801a82), + (0x3f828aa0), + (0x3f99430f), + (0x3f9bd32d), + (0x3f99710f), + (0x3f9be12d), + (0x3f996b8d), + (0x3f9bfbaf), + (0x3f99598d), + (0x3f9bc9af)}, + (0xfff80000), + {0xaf,0x4b,0x20,0xda,0xcd,0xb1,0xdf,0x23,0x89,0x9b, + 0x9d,0xaf,0x0b,0x97,0x1e,0x9f,0x61,0xe7,0xfc,0x34,0x00} + }, + { + /* No.140 delta:8901 weight:1275 */ + 11213, + 67, + 29, + 1, + {(0x00000000), + (0x10b888fe), + (0xd0c6c2fc), + (0xc07e4a02), + (0x93a008cd), + (0x83188033), + (0x4366ca31), + (0x53de42cf), + (0x00009412), + (0x10b81cec), + (0xd0c656ee), + (0xc07ede10), + (0x93a09cdf), + (0x83181421), + (0x43665e23), + (0x53ded6dd)}, + {(0x00000000), + (0xd4620000), + (0x7a000000), + (0xae620000), + (0x01000000), + (0xd5620000), + (0x7b000000), + (0xaf620000), + (0x20a01e00), + (0xf4c21e00), + (0x5aa01e00), + (0x8ec21e00), + (0x21a01e00), + (0xf5c21e00), + (0x5ba01e00), + (0x8fc21e00)}, + {(0x3f800000), + (0x3fea3100), + (0x3fbd0000), + (0x3fd73100), + (0x3f808000), + (0x3feab100), + (0x3fbd8000), + (0x3fd7b100), + (0x3f90500f), + (0x3ffa610f), + (0x3fad500f), + (0x3fc7610f), + (0x3f90d00f), + (0x3ffae10f), + (0x3fadd00f), + (0x3fc7e10f)}, + (0xfff80000), + {0x57,0x96,0xba,0x7d,0x3b,0x31,0xd7,0xac,0xb2,0xe9, + 0x75,0xcd,0xdb,0x72,0x76,0x05,0x30,0x7f,0xd3,0xa0,0x00} + }, + { + /* No.141 delta:3341 weight:741 */ + 11213, + 28, + 3, + 17, + {(0x00000000), + (0xac86815e), + (0xed762180), + (0x41f0a0de), + (0x81a008df), + (0x2d268981), + (0x6cd6295f), + (0xc050a801), + (0x00004e54), + (0xac86cf0a), + (0xed766fd4), + (0x41f0ee8a), + (0x81a0468b), + (0x2d26c7d5), + (0x6cd6670b), + (0xc050e655)}, + {(0x00000000), + (0x9a110000), + (0x0f440000), + (0x95550000), + (0x70020000), + (0xea130000), + (0x7f460000), + (0xe5570000), + (0x21561e00), + (0xbb471e00), + (0x2e121e00), + (0xb4031e00), + (0x51541e00), + (0xcb451e00), + (0x5e101e00), + (0xc4011e00)}, + {(0x3f800000), + (0x3fcd0880), + (0x3f87a200), + (0x3fcaaa80), + (0x3fb80100), + (0x3ff50980), + (0x3fbfa300), + (0x3ff2ab80), + (0x3f90ab0f), + (0x3fdda38f), + (0x3f97090f), + (0x3fda018f), + (0x3fa8aa0f), + (0x3fe5a28f), + (0x3faf080f), + (0x3fe2008f)}, + (0xfff80000), + {0xcc,0x1d,0x62,0xab,0x61,0x1e,0xfc,0xe5,0x74,0x60, + 0xa2,0x5f,0xd0,0xfe,0xff,0x0e,0xfb,0x75,0x83,0x88,0x00} + }, + { + /* No.142 delta:5114 weight:1233 */ + 11213, + 35, + 30, + 3, + {(0x00000000), + (0xb9cd2997), + (0xab1ac509), + (0x12d7ec9e), + (0x5b2008ea), + (0xe2ed217d), + (0xf03acde3), + (0x49f7e474), + (0x0000ef9a), + (0xb9cdc60d), + (0xab1a2a93), + (0x12d70304), + (0x5b20e770), + (0xe2edcee7), + (0xf03a2279), + (0x49f70bee)}, + {(0x00000000), + (0xaef05000), + (0x2d801000), + (0x83704000), + (0x2390a000), + (0x8d60f000), + (0x0e10b000), + (0xa0e0e000), + (0x01001e00), + (0xaff04e00), + (0x2c800e00), + (0x82705e00), + (0x2290be00), + (0x8c60ee00), + (0x0f10ae00), + (0xa1e0fe00)}, + {(0x3f800000), + (0x3fd77828), + (0x3f96c008), + (0x3fc1b820), + (0x3f91c850), + (0x3fc6b078), + (0x3f870858), + (0x3fd07070), + (0x3f80800f), + (0x3fd7f827), + (0x3f964007), + (0x3fc1382f), + (0x3f91485f), + (0x3fc63077), + (0x3f878857), + (0x3fd0f07f)}, + (0xfff80000), + {0xce,0x51,0x4c,0x65,0x7a,0xae,0xbf,0x6f,0xd6,0x0b, + 0x0c,0x85,0x1c,0x15,0xe3,0xbf,0x9f,0x2b,0xa1,0x5d,0x00} + }, + { + /* No.143 delta:2115 weight:1465 */ + 11213, + 11, + 20, + 4, + {(0x00000000), + (0x34795048), + (0x0b9d244e), + (0x3fe47406), + (0xc90008f2), + (0xfd7958ba), + (0xc29d2cbc), + (0xf6e47cf4), + (0x00008680), + (0x3479d6c8), + (0x0b9da2ce), + (0x3fe4f286), + (0xc9008e72), + (0xfd79de3a), + (0xc29daa3c), + (0xf6e4fa74)}, + {(0x00000000), + (0xc1592000), + (0x16984000), + (0xd7c16000), + (0x21226800), + (0xe07b4800), + (0x37ba2800), + (0xf6e30800), + (0x08345e00), + (0xc96d7e00), + (0x1eac1e00), + (0xdff53e00), + (0x29163600), + (0xe84f1600), + (0x3f8e7600), + (0xfed75600)}, + {(0x3f800000), + (0x3fe0ac90), + (0x3f8b4c20), + (0x3febe0b0), + (0x3f909134), + (0x3ff03da4), + (0x3f9bdd14), + (0x3ffb7184), + (0x3f841a2f), + (0x3fe4b6bf), + (0x3f8f560f), + (0x3feffa9f), + (0x3f948b1b), + (0x3ff4278b), + (0x3f9fc73b), + (0x3fff6bab)}, + (0xfff80000), + {0x5f,0xfb,0xd7,0xc9,0x75,0x94,0x0e,0x84,0xfd,0x2b, + 0xc3,0xaf,0xdd,0x54,0xe4,0x81,0x96,0x14,0x65,0x90,0x00} + }, + { + /* No.144 delta:1074 weight:843 */ + 11213, + 50, + 20, + 11, + {(0x00000000), + (0xa8afcf6f), + (0x497c3b6e), + (0xe1d3f401), + (0xa0800909), + (0x082fc666), + (0xe9fc3267), + (0x4153fd08), + (0x0000ec80), + (0xa8af23ef), + (0x497cd7ee), + (0xe1d31881), + (0xa080e589), + (0x082f2ae6), + (0xe9fcdee7), + (0x41531188)}, + {(0x00000000), + (0x00081200), + (0xd0708400), + (0xd0789600), + (0x70302a00), + (0x70383800), + (0xa040ae00), + (0xa048bc00), + (0x1040fe00), + (0x1048ec00), + (0xc0307a00), + (0xc0386800), + (0x6070d400), + (0x6078c600), + (0xb0005000), + (0xb0084200)}, + {(0x3f800000), + (0x3f800409), + (0x3fe83842), + (0x3fe83c4b), + (0x3fb81815), + (0x3fb81c1c), + (0x3fd02057), + (0x3fd0245e), + (0x3f88207f), + (0x3f882476), + (0x3fe0183d), + (0x3fe01c34), + (0x3fb0386a), + (0x3fb03c63), + (0x3fd80028), + (0x3fd80421)}, + (0xfff80000), + {0x95,0xfe,0x49,0x06,0x5e,0xae,0xca,0x7d,0x0a,0xce, + 0xf9,0x80,0x70,0xc2,0x03,0xa9,0x1c,0xc3,0x16,0x85,0x00} + }, + { + /* No.145 delta:2918 weight:721 */ + 11213, + 86, + 4, + 18, + {(0x00000000), + (0x3bebda5d), + (0x18b70390), + (0x235cd9cd), + (0x2c60091c), + (0x178bd341), + (0x34d70a8c), + (0x0f3cd0d1), + (0x00004f75), + (0x3beb9528), + (0x18b74ce5), + (0x235c96b8), + (0x2c604669), + (0x178b9c34), + (0x34d745f9), + (0x0f3c9fa4)}, + {(0x00000000), + (0x1e710200), + (0x09800000), + (0x17f10200), + (0x00c00000), + (0x1eb10200), + (0x09400000), + (0x17310200), + (0x30431e00), + (0x2e321c00), + (0x39c31e00), + (0x27b21c00), + (0x30831e00), + (0x2ef21c00), + (0x39031e00), + (0x27721c00)}, + {(0x3f800000), + (0x3f8f3881), + (0x3f84c000), + (0x3f8bf881), + (0x3f806000), + (0x3f8f5881), + (0x3f84a000), + (0x3f8b9881), + (0x3f98218f), + (0x3f97190e), + (0x3f9ce18f), + (0x3f93d90e), + (0x3f98418f), + (0x3f97790e), + (0x3f9c818f), + (0x3f93b90e)}, + (0xfff80000), + {0x3c,0x75,0x1b,0x34,0x56,0x7d,0x5c,0xdd,0x5a,0x41, + 0xb9,0x82,0x6d,0x1d,0xc3,0x11,0x62,0x1e,0xea,0x73,0x00} + }, + { + /* No.146 delta:2588 weight:993 */ + 11213, + 77, + 8, + 11, + {(0x00000000), + (0x29b76eba), + (0xb5519d7b), + (0x9ce6f3c1), + (0xac000920), + (0x85b7679a), + (0x1951945b), + (0x30e6fae1), + (0x00002499), + (0x29b74a23), + (0xb551b9e2), + (0x9ce6d758), + (0xac002db9), + (0x85b74303), + (0x1951b0c2), + (0x30e6de78)}, + {(0x00000000), + (0x00350000), + (0x086a0000), + (0x085f0000), + (0x085c0000), + (0x08690000), + (0x00360000), + (0x00030000), + (0x00519e00), + (0x00649e00), + (0x083b9e00), + (0x080e9e00), + (0x080d9e00), + (0x08389e00), + (0x00679e00), + (0x00529e00)}, + {(0x3f800000), + (0x3f801a80), + (0x3f843500), + (0x3f842f80), + (0x3f842e00), + (0x3f843480), + (0x3f801b00), + (0x3f800180), + (0x3f8028cf), + (0x3f80324f), + (0x3f841dcf), + (0x3f84074f), + (0x3f8406cf), + (0x3f841c4f), + (0x3f8033cf), + (0x3f80294f)}, + (0xfff80000), + {0x78,0x89,0x90,0x85,0x2f,0x08,0xc7,0x62,0xed,0x99, + 0x04,0xfb,0xe5,0x26,0x8d,0x20,0x08,0xbc,0xe0,0x01,0x00} + }, + { + /* No.147 delta:1196 weight:1067 */ + 11213, + 65, + 15, + 11, + {(0x00000000), + (0xe3c8118c), + (0x346df077), + (0xd7a5e1fb), + (0xff500936), + (0x1c9818ba), + (0xcb3df941), + (0x28f5e8cd), + (0x000057eb), + (0xe3c84667), + (0x346da79c), + (0xd7a5b610), + (0xff505edd), + (0x1c984f51), + (0xcb3daeaa), + (0x28f5bf26)}, + {(0x00000000), + (0x00411800), + (0x0c060000), + (0x0c471800), + (0x260a4800), + (0x264b5000), + (0x2a0c4800), + (0x2a4d5000), + (0x0003de00), + (0x0042c600), + (0x0c05de00), + (0x0c44c600), + (0x26099600), + (0x26488e00), + (0x2a0f9600), + (0x2a4e8e00)}, + {(0x3f800000), + (0x3f80208c), + (0x3f860300), + (0x3f86238c), + (0x3f930524), + (0x3f9325a8), + (0x3f950624), + (0x3f9526a8), + (0x3f8001ef), + (0x3f802163), + (0x3f8602ef), + (0x3f862263), + (0x3f9304cb), + (0x3f932447), + (0x3f9507cb), + (0x3f952747)}, + (0xfff80000), + {0x1f,0x15,0xcd,0x92,0x4b,0xcd,0x46,0xa5,0x75,0xd5, + 0x6e,0xf4,0x6d,0x40,0x10,0x3c,0xa0,0xd0,0x56,0x85,0x00} + }, + { + /* No.148 delta:995 weight:1397 */ + 11213, + 48, + 20, + 6, + {(0x00000000), + (0x81afe9a5), + (0xc7e54dd3), + (0x464aa476), + (0x42100942), + (0xc3bfe0e7), + (0x85f54491), + (0x045aad34), + (0x0000d573), + (0x81af3cd6), + (0xc7e598a0), + (0x464a7105), + (0x4210dc31), + (0xc3bf3594), + (0x85f591e2), + (0x045a7847)}, + {(0x00000000), + (0x0c8d6800), + (0x00660a00), + (0x0ceb6200), + (0x0190c600), + (0x0d1dae00), + (0x01f6cc00), + (0x0d7ba400), + (0x00423e00), + (0x0ccf5600), + (0x00243400), + (0x0ca95c00), + (0x01d2f800), + (0x0d5f9000), + (0x01b4f200), + (0x0d399a00)}, + {(0x3f800000), + (0x3f8646b4), + (0x3f803305), + (0x3f8675b1), + (0x3f80c863), + (0x3f868ed7), + (0x3f80fb66), + (0x3f86bdd2), + (0x3f80211f), + (0x3f8667ab), + (0x3f80121a), + (0x3f8654ae), + (0x3f80e97c), + (0x3f86afc8), + (0x3f80da79), + (0x3f869ccd)}, + (0xfff80000), + {0x89,0x5d,0x4d,0xfa,0x78,0x98,0x8a,0x59,0x89,0x1d, + 0x43,0x6d,0x08,0x21,0x0f,0x15,0xef,0xea,0xed,0x4f,0x00} + }, + { + /* No.149 delta:1807 weight:1017 */ + 11213, + 25, + 17, + 13, + {(0x00000000), + (0x95fafe23), + (0x258e5d0f), + (0xb074a32c), + (0x5b000950), + (0xcefaf773), + (0x7e8e545f), + (0xeb74aa7c), + (0x00007b8f), + (0x95fa85ac), + (0x258e2680), + (0xb074d8a3), + (0x5b0072df), + (0xcefa8cfc), + (0x7e8e2fd0), + (0xeb74d1f3)}, + {(0x00000000), + (0x40690000), + (0x107c4000), + (0x50154000), + (0x0061b000), + (0x4008b000), + (0x101df000), + (0x5074f000), + (0x10221e00), + (0x504b1e00), + (0x005e5e00), + (0x40375e00), + (0x1043ae00), + (0x502aae00), + (0x003fee00), + (0x4056ee00)}, + {(0x3f800000), + (0x3fa03480), + (0x3f883e20), + (0x3fa80aa0), + (0x3f8030d8), + (0x3fa00458), + (0x3f880ef8), + (0x3fa83a78), + (0x3f88110f), + (0x3fa8258f), + (0x3f802f2f), + (0x3fa01baf), + (0x3f8821d7), + (0x3fa81557), + (0x3f801ff7), + (0x3fa02b77)}, + (0xfff80000), + {0x29,0x89,0x68,0x24,0x4a,0xc0,0x9c,0xf5,0x79,0x14, + 0xc1,0x26,0xaa,0x3d,0xbf,0x1f,0xc1,0xbc,0x78,0x97,0x00} + }, + { + /* No.150 delta:2642 weight:975 */ + 11213, + 44, + 4, + 15, + {(0x00000000), + (0x3cf7745b), + (0x8a251fd4), + (0xb6d26b8f), + (0xc580096c), + (0xf9777d37), + (0x4fa516b8), + (0x735262e3), + (0x00007ddf), + (0x3cf70984), + (0x8a25620b), + (0xb6d21650), + (0xc58074b3), + (0xf97700e8), + (0x4fa56b67), + (0x73521f3c)}, + {(0x00000000), + (0x52780000), + (0x13600000), + (0x41180000), + (0x08cc0000), + (0x5ab40000), + (0x1bac0000), + (0x49d40000), + (0x02401e00), + (0x50381e00), + (0x11201e00), + (0x43581e00), + (0x0a8c1e00), + (0x58f41e00), + (0x19ec1e00), + (0x4b941e00)}, + {(0x3f800000), + (0x3fa93c00), + (0x3f89b000), + (0x3fa08c00), + (0x3f846600), + (0x3fad5a00), + (0x3f8dd600), + (0x3fa4ea00), + (0x3f81200f), + (0x3fa81c0f), + (0x3f88900f), + (0x3fa1ac0f), + (0x3f85460f), + (0x3fac7a0f), + (0x3f8cf60f), + (0x3fa5ca0f)}, + (0xfff80000), + {0x1c,0x8b,0x81,0x2c,0x97,0xf0,0xd6,0x0f,0xeb,0x28, + 0x7e,0xbd,0x56,0xe1,0x95,0x03,0x72,0xd1,0x0a,0x96,0x00} + }, + { + /* No.151 delta:962 weight:1023 */ + 11213, + 78, + 12, + 10, + {(0x00000000), + (0x171b50e0), + (0x997dbf57), + (0x8e66efb7), + (0x22d00977), + (0x35cb5997), + (0xbbadb620), + (0xacb6e6c0), + (0x00001c87), + (0x171b4c67), + (0x997da3d0), + (0x8e66f330), + (0x22d015f0), + (0x35cb4510), + (0xbbadaaa7), + (0xacb6fa47)}, + {(0x00000000), + (0x21821c00), + (0x10102200), + (0x31923e00), + (0x60023000), + (0x41802c00), + (0x70121200), + (0x51900e00), + (0xc100de00), + (0xe082c200), + (0xd110fc00), + (0xf092e000), + (0xa102ee00), + (0x8080f200), + (0xb112cc00), + (0x9090d000)}, + {(0x3f800000), + (0x3f90c10e), + (0x3f880811), + (0x3f98c91f), + (0x3fb00118), + (0x3fa0c016), + (0x3fb80909), + (0x3fa8c807), + (0x3fe0806f), + (0x3ff04161), + (0x3fe8887e), + (0x3ff84970), + (0x3fd08177), + (0x3fc04079), + (0x3fd88966), + (0x3fc84868)}, + (0xfff80000), + {0xb1,0xe6,0xdf,0x01,0xdd,0xa2,0x07,0x31,0x50,0x37, + 0xbf,0x34,0x2a,0x6d,0xfe,0xe7,0x69,0x32,0x01,0x60,0x00} + }, + { + /* No.152 delta:1302 weight:1041 */ + 11213, + 55, + 10, + 13, + {(0x00000000), + (0xd0556a8d), + (0x5e4d31d5), + (0x8e185b58), + (0xe6600989), + (0x36356304), + (0xb82d385c), + (0x687852d1), + (0x000019bb), + (0xd0557336), + (0x5e4d286e), + (0x8e1842e3), + (0xe6601032), + (0x36357abf), + (0xb82d21e7), + (0x68784b6a)}, + {(0x00000000), + (0x627c4000), + (0x3034a000), + (0x5248e000), + (0x00038000), + (0x627fc000), + (0x30372000), + (0x524b6000), + (0x80519e00), + (0xe22dde00), + (0xb0653e00), + (0xd2197e00), + (0x80521e00), + (0xe22e5e00), + (0xb066be00), + (0xd21afe00)}, + {(0x3f800000), + (0x3fb13e20), + (0x3f981a50), + (0x3fa92470), + (0x3f8001c0), + (0x3fb13fe0), + (0x3f981b90), + (0x3fa925b0), + (0x3fc028cf), + (0x3ff116ef), + (0x3fd8329f), + (0x3fe90cbf), + (0x3fc0290f), + (0x3ff1172f), + (0x3fd8335f), + (0x3fe90d7f)}, + (0xfff80000), + {0x9e,0x26,0x73,0xd6,0xbe,0x9b,0x5f,0x7d,0x6b,0x71, + 0x07,0x55,0x14,0xdf,0x70,0x0c,0x4a,0x9a,0xdd,0x23,0x00} + }, + { + /* No.153 delta:1084 weight:1123 */ + 11213, + 86, + 22, + 10, + {(0x00000000), + (0xa2a5f5b9), + (0x2b421269), + (0x89e7e7d0), + (0x54300991), + (0xf695fc28), + (0x7f721bf8), + (0xddd7ee41), + (0x0000dc1c), + (0xa2a529a5), + (0x2b42ce75), + (0x89e73bcc), + (0x5430d58d), + (0xf6952034), + (0x7f72c7e4), + (0xddd7325d)}, + {(0x00000000), + (0x40cc0000), + (0x50668000), + (0x10aa8000), + (0x0069f000), + (0x40a5f000), + (0x500f7000), + (0x10c37000), + (0x00131e00), + (0x40df1e00), + (0x50759e00), + (0x10b99e00), + (0x007aee00), + (0x40b6ee00), + (0x501c6e00), + (0x10d06e00)}, + {(0x3f800000), + (0x3fa06600), + (0x3fa83340), + (0x3f885540), + (0x3f8034f8), + (0x3fa052f8), + (0x3fa807b8), + (0x3f8861b8), + (0x3f80098f), + (0x3fa06f8f), + (0x3fa83acf), + (0x3f885ccf), + (0x3f803d77), + (0x3fa05b77), + (0x3fa80e37), + (0x3f886837)}, + (0xfff80000), + {0x27,0x0a,0x3f,0xdb,0x36,0x65,0x8b,0x9c,0x6c,0x3d, + 0xb3,0x81,0x6b,0x82,0xdc,0xaf,0x77,0xa0,0x5a,0x41,0x00} + }, + { + /* No.154 delta:1218 weight:1125 */ + 11213, + 33, + 17, + 9, + {(0x00000000), + (0xbc510269), + (0x187fd997), + (0xa42edbfe), + (0xb2d009a5), + (0x0e810bcc), + (0xaaafd032), + (0x16fed25b), + (0x00008c92), + (0xbc518efb), + (0x187f5505), + (0xa42e576c), + (0xb2d08537), + (0x0e81875e), + (0xaaaf5ca0), + (0x16fe5ec9)}, + {(0x00000000), + (0x4674aa00), + (0x20885800), + (0x66fcf200), + (0x010e8000), + (0x477a2a00), + (0x2186d800), + (0x67f27200), + (0x02c2be00), + (0x44b61400), + (0x224ae600), + (0x643e4c00), + (0x03cc3e00), + (0x45b89400), + (0x23446600), + (0x6530cc00)}, + {(0x3f800000), + (0x3fa33a55), + (0x3f90442c), + (0x3fb37e79), + (0x3f808740), + (0x3fa3bd15), + (0x3f90c36c), + (0x3fb3f939), + (0x3f81615f), + (0x3fa25b0a), + (0x3f912573), + (0x3fb21f26), + (0x3f81e61f), + (0x3fa2dc4a), + (0x3f91a233), + (0x3fb29866)}, + (0xfff80000), + {0xcd,0xbe,0xfa,0xd2,0x8e,0x1c,0x9f,0x67,0x49,0xe4, + 0xe4,0x6c,0xb2,0xe3,0x01,0xb2,0x56,0x77,0x18,0x40,0x00} + }, + { + /* No.155 delta:2783 weight:955 */ + 11213, + 59, + 3, + 7, + {(0x00000000), + (0xac2382ba), + (0x6ff1673d), + (0xc3d2e587), + (0x37a009b6), + (0x9b838b0c), + (0x58516e8b), + (0xf472ec31), + (0x0000a5f6), + (0xac23274c), + (0x6ff1c2cb), + (0xc3d24071), + (0x37a0ac40), + (0x9b832efa), + (0x5851cb7d), + (0xf47249c7)}, + {(0x00000000), + (0x14228400), + (0x00948000), + (0x14b60400), + (0x206a8400), + (0x34480000), + (0x20fe0400), + (0x34dc8000), + (0x40481e00), + (0x546a9a00), + (0x40dc9e00), + (0x54fe1a00), + (0x60229a00), + (0x74001e00), + (0x60b61a00), + (0x74949e00)}, + {(0x3f800000), + (0x3f8a1142), + (0x3f804a40), + (0x3f8a5b02), + (0x3f903542), + (0x3f9a2400), + (0x3f907f02), + (0x3f9a6e40), + (0x3fa0240f), + (0x3faa354d), + (0x3fa06e4f), + (0x3faa7f0d), + (0x3fb0114d), + (0x3fba000f), + (0x3fb05b0d), + (0x3fba4a4f)}, + (0xfff80000), + {0x12,0x6b,0xe6,0x1a,0xef,0x03,0x6a,0x5a,0xeb,0x44, + 0xd4,0xe8,0x31,0x17,0x3d,0x9b,0xd7,0xd8,0xc8,0xd2,0x00} + }, + { + /* No.156 delta:2681 weight:1401 */ + 11213, + 11, + 22, + 2, + {(0x00000000), + (0xfcaff0c3), + (0xee10c3a9), + (0x12bf336a), + (0x1ea009c1), + (0xe20ff902), + (0xf0b0ca68), + (0x0c1f3aab), + (0x0000a3d9), + (0xfcaf531a), + (0xee106070), + (0x12bf90b3), + (0x1ea0aa18), + (0xe20f5adb), + (0xf0b069b1), + (0x0c1f9972)}, + {(0x00000000), + (0x8f318000), + (0x0c949000), + (0x83a51000), + (0x61378000), + (0xee060000), + (0x6da31000), + (0xe2929000), + (0x4044de00), + (0xcf755e00), + (0x4cd04e00), + (0xc3e1ce00), + (0x21735e00), + (0xae42de00), + (0x2de7ce00), + (0xa2d64e00)}, + {(0x3f800000), + (0x3fc798c0), + (0x3f864a48), + (0x3fc1d288), + (0x3fb09bc0), + (0x3ff70300), + (0x3fb6d188), + (0x3ff14948), + (0x3fa0226f), + (0x3fe7baaf), + (0x3fa66827), + (0x3fe1f0e7), + (0x3f90b9af), + (0x3fd7216f), + (0x3f96f3e7), + (0x3fd16b27)}, + (0xfff80000), + {0x83,0x73,0xde,0x94,0x03,0x6f,0x08,0x85,0xc8,0x3c, + 0xf2,0x9a,0xb2,0x9d,0x8f,0xfe,0x34,0x78,0xe6,0x25,0x00} + }, + { + /* No.157 delta:4633 weight:903 */ + 11213, + 70, + 1, + 8, + {(0x00000000), + (0x4732d8c0), + (0x2145def8), + (0x66770638), + (0x8ec009da), + (0xc9f2d11a), + (0xaf85d722), + (0xe8b70fe2), + (0x000031b0), + (0x4732e970), + (0x2145ef48), + (0x66773788), + (0x8ec0386a), + (0xc9f2e0aa), + (0xaf85e692), + (0xe8b73e52)}, + {(0x00000000), + (0x10400000), + (0x24640000), + (0x34240000), + (0x81100000), + (0x91500000), + (0xa5740000), + (0xb5340000), + (0x08431e00), + (0x18031e00), + (0x2c271e00), + (0x3c671e00), + (0x89531e00), + (0x99131e00), + (0xad371e00), + (0xbd771e00)}, + {(0x3f800000), + (0x3f882000), + (0x3f923200), + (0x3f9a1200), + (0x3fc08800), + (0x3fc8a800), + (0x3fd2ba00), + (0x3fda9a00), + (0x3f84218f), + (0x3f8c018f), + (0x3f96138f), + (0x3f9e338f), + (0x3fc4a98f), + (0x3fcc898f), + (0x3fd69b8f), + (0x3fdebb8f)}, + (0xfff80000), + {0xdd,0x87,0x76,0x32,0x84,0x88,0x7a,0x5f,0x52,0x09, + 0x1f,0x36,0xae,0xfa,0x7b,0x5d,0xb4,0x87,0x91,0x59,0x00} + }, + { + /* No.158 delta:1376 weight:811 */ + 11213, + 58, + 16, + 14, + {(0x00000000), + (0xdc5d3a0a), + (0x023cad01), + (0xde61970b), + (0x286009e2), + (0xf43d33e8), + (0x2a5ca4e3), + (0xf6019ee9), + (0x00009c42), + (0xdc5da648), + (0x023c3143), + (0xde610b49), + (0x286095a0), + (0xf43dafaa), + (0x2a5c38a1), + (0xf60102ab)}, + {(0x00000000), + (0x50081000), + (0x305e0000), + (0x60561000), + (0x10324000), + (0x403a5000), + (0x206c4000), + (0x70645000), + (0x20011e00), + (0x70090e00), + (0x105f1e00), + (0x40570e00), + (0x30335e00), + (0x603b4e00), + (0x006d5e00), + (0x50654e00)}, + {(0x3f800000), + (0x3fa80408), + (0x3f982f00), + (0x3fb02b08), + (0x3f881920), + (0x3fa01d28), + (0x3f903620), + (0x3fb83228), + (0x3f90008f), + (0x3fb80487), + (0x3f882f8f), + (0x3fa02b87), + (0x3f9819af), + (0x3fb01da7), + (0x3f8036af), + (0x3fa832a7)}, + (0xfff80000), + {0x96,0xe0,0xc6,0xef,0x7f,0x51,0x3c,0x13,0xd3,0x63, + 0x80,0x54,0xc8,0x09,0xcc,0x33,0x8e,0x9a,0x15,0x91,0x00} + }, + { + /* No.159 delta:1647 weight:1099 */ + 11213, + 91, + 19, + 1, + {(0x00000000), + (0xeffea95b), + (0x587a7fdf), + (0xb784d684), + (0xe5b009ff), + (0x0a4ea0a4), + (0xbdca7620), + (0x5234df7b), + (0x00008677), + (0xeffe2f2c), + (0x587af9a8), + (0xb78450f3), + (0xe5b08f88), + (0x0a4e26d3), + (0xbdcaf057), + (0x5234590c)}, + {(0x00000000), + (0xc3463c00), + (0x20814400), + (0xe3c77800), + (0x04036400), + (0xc7455800), + (0x24822000), + (0xe7c41c00), + (0x66201e00), + (0xa5662200), + (0x46a15a00), + (0x85e76600), + (0x62237a00), + (0xa1654600), + (0x42a23e00), + (0x81e40200)}, + {(0x3f800000), + (0x3fe1a31e), + (0x3f9040a2), + (0x3ff1e3bc), + (0x3f8201b2), + (0x3fe3a2ac), + (0x3f924110), + (0x3ff3e20e), + (0x3fb3100f), + (0x3fd2b311), + (0x3fa350ad), + (0x3fc2f3b3), + (0x3fb111bd), + (0x3fd0b2a3), + (0x3fa1511f), + (0x3fc0f201)}, + (0xfff80000), + {0x6f,0x70,0x62,0xec,0x14,0x82,0xd2,0xb9,0xc0,0x8d, + 0xdc,0xae,0x07,0x77,0xb8,0x94,0x3f,0xc9,0xfa,0xe1,0x00} + }, + { + /* No.160 delta:2967 weight:901 */ + 11213, + 53, + 18, + 1, + {(0x00000000), + (0xaa302b40), + (0x85ec337a), + (0x2fdc183a), + (0x3dd00a0a), + (0x97e0214a), + (0xb83c3970), + (0x120c1230), + (0x00008c9b), + (0xaa30a7db), + (0x85ecbfe1), + (0x2fdc94a1), + (0x3dd08691), + (0x97e0add1), + (0xb83cb5eb), + (0x120c9eab)}, + {(0x00000000), + (0x0e4c0c00), + (0x81a28000), + (0x8fee8c00), + (0x01009400), + (0x0f4c9800), + (0x80a21400), + (0x8eee1800), + (0x09031e00), + (0x074f1200), + (0x88a19e00), + (0x86ed9200), + (0x08038a00), + (0x064f8600), + (0x89a10a00), + (0x87ed0600)}, + {(0x3f800000), + (0x3f872606), + (0x3fc0d140), + (0x3fc7f746), + (0x3f80804a), + (0x3f87a64c), + (0x3fc0510a), + (0x3fc7770c), + (0x3f84818f), + (0x3f83a789), + (0x3fc450cf), + (0x3fc376c9), + (0x3f8401c5), + (0x3f8327c3), + (0x3fc4d085), + (0x3fc3f683)}, + (0xfff80000), + {0xa5,0x57,0xd6,0x41,0xd4,0x56,0x49,0x1c,0xe3,0x86, + 0x35,0xfc,0x5c,0xaf,0xd9,0xba,0x3e,0xfe,0x47,0xfa,0x00} + }, + { + /* No.161 delta:1285 weight:1009 */ + 11213, + 44, + 22, + 9, + {(0x00000000), + (0xbd887100), + (0x6d55a627), + (0xd0ddd727), + (0x18000a1d), + (0xa5887b1d), + (0x7555ac3a), + (0xc8dddd3a), + (0x0000acfa), + (0xbd88ddfa), + (0x6d550add), + (0xd0dd7bdd), + (0x1800a6e7), + (0xa588d7e7), + (0x755500c0), + (0xc8dd71c0)}, + {(0x00000000), + (0x0fe36000), + (0x0045f000), + (0x0fa69000), + (0x121a2000), + (0x1df94000), + (0x125fd000), + (0x1dbcb000), + (0x00371e00), + (0x0fd47e00), + (0x0072ee00), + (0x0f918e00), + (0x122d3e00), + (0x1dce5e00), + (0x1268ce00), + (0x1d8bae00)}, + {(0x3f800000), + (0x3f87f1b0), + (0x3f8022f8), + (0x3f87d348), + (0x3f890d10), + (0x3f8efca0), + (0x3f892fe8), + (0x3f8ede58), + (0x3f801b8f), + (0x3f87ea3f), + (0x3f803977), + (0x3f87c8c7), + (0x3f89169f), + (0x3f8ee72f), + (0x3f893467), + (0x3f8ec5d7)}, + (0xfff80000), + {0xb3,0x0a,0x52,0x2b,0xc3,0xf3,0x8a,0x0b,0x60,0xcf, + 0x50,0x81,0xc0,0x03,0x13,0x44,0x56,0xfd,0xe5,0x6c,0x00} + }, + { + /* No.162 delta:3653 weight:1321 */ + 11213, + 77, + 4, + 1, + {(0x00000000), + (0x09eb7b50), + (0x4a578b30), + (0x43bcf060), + (0xc4b00a20), + (0xcd5b7170), + (0x8ee78110), + (0x870cfa40), + (0x000030d1), + (0x09eb4b81), + (0x4a57bbe1), + (0x43bcc0b1), + (0xc4b03af1), + (0xcd5b41a1), + (0x8ee7b1c1), + (0x870cca91)}, + {(0x00000000), + (0x20630000), + (0x00492000), + (0x202a2000), + (0x400a0000), + (0x60690000), + (0x40432000), + (0x60202000), + (0xc0027e00), + (0xe0617e00), + (0xc04b5e00), + (0xe0285e00), + (0x80087e00), + (0xa06b7e00), + (0x80415e00), + (0xa0225e00)}, + {(0x3f800000), + (0x3f903180), + (0x3f802490), + (0x3f901510), + (0x3fa00500), + (0x3fb03480), + (0x3fa02190), + (0x3fb01010), + (0x3fe0013f), + (0x3ff030bf), + (0x3fe025af), + (0x3ff0142f), + (0x3fc0043f), + (0x3fd035bf), + (0x3fc020af), + (0x3fd0112f)}, + (0xfff80000), + {0xed,0x0f,0x9e,0x5d,0x4b,0x7d,0x2e,0x4f,0xf8,0xa4, + 0xba,0x23,0xdc,0x1a,0x0e,0x40,0xa9,0xff,0xbf,0xfa,0x00} + }, + { + /* No.163 delta:1515 weight:829 */ + 11213, + 59, + 16, + 13, + {(0x00000000), + (0xd192fecc), + (0x1c86d46e), + (0xcd142aa2), + (0xeb900a31), + (0x3a02f4fd), + (0xf716de5f), + (0x26842093), + (0x00009c7b), + (0xd19262b7), + (0x1c864815), + (0xcd14b6d9), + (0xeb90964a), + (0x3a026886), + (0xf7164224), + (0x2684bce8)}, + {(0x00000000), + (0xc9688000), + (0x08400200), + (0xc1288200), + (0x082d4800), + (0xc145c800), + (0x006d4a00), + (0xc905ca00), + (0x312c1e00), + (0xf8449e00), + (0x396c1c00), + (0xf0049c00), + (0x39015600), + (0xf069d600), + (0x31415400), + (0xf829d400)}, + {(0x3f800000), + (0x3fe4b440), + (0x3f842001), + (0x3fe09441), + (0x3f8416a4), + (0x3fe0a2e4), + (0x3f8036a5), + (0x3fe482e5), + (0x3f98960f), + (0x3ffc224f), + (0x3f9cb60e), + (0x3ff8024e), + (0x3f9c80ab), + (0x3ff834eb), + (0x3f98a0aa), + (0x3ffc14ea)}, + (0xfff80000), + {0xe7,0xaa,0x57,0x85,0x45,0x30,0x30,0xea,0x81,0x55, + 0x14,0xf3,0xe1,0x42,0x5a,0xfc,0x05,0x1e,0xd3,0xf0,0x00} + }, + { + /* No.164 delta:5942 weight:1403 */ + 11213, + 49, + 28, + 3, + {(0x00000000), + (0x96bbff16), + (0x0e2dd758), + (0x9896284e), + (0xb5700a46), + (0x23cbf550), + (0xbb5ddd1e), + (0x2de62208), + (0x0000f8d9), + (0x96bb07cf), + (0x0e2d2f81), + (0x9896d097), + (0xb570f29f), + (0x23cb0d89), + (0xbb5d25c7), + (0x2de6dad1)}, + {(0x00000000), + (0x44940000), + (0x03b80000), + (0x472c0000), + (0x48600000), + (0x0cf40000), + (0x4bd80000), + (0x0f4c0000), + (0x00801e00), + (0x44141e00), + (0x03381e00), + (0x47ac1e00), + (0x48e01e00), + (0x0c741e00), + (0x4b581e00), + (0x0fcc1e00)}, + {(0x3f800000), + (0x3fa24a00), + (0x3f81dc00), + (0x3fa39600), + (0x3fa43000), + (0x3f867a00), + (0x3fa5ec00), + (0x3f87a600), + (0x3f80400f), + (0x3fa20a0f), + (0x3f819c0f), + (0x3fa3d60f), + (0x3fa4700f), + (0x3f863a0f), + (0x3fa5ac0f), + (0x3f87e60f)}, + (0xfff80000), + {0x76,0xb3,0x89,0x96,0x29,0x62,0x6a,0x7b,0xe7,0x6f, + 0x4a,0x6c,0x1f,0xbf,0x96,0x66,0x8d,0x45,0x5d,0x5c,0x00} + }, + { + /* No.165 delta:1776 weight:1045 */ + 11213, + 74, + 10, + 13, + {(0x00000000), + (0x24c994e7), + (0x7e990c2c), + (0x5a5098cb), + (0xb9000a51), + (0x9dc99eb6), + (0xc799067d), + (0xe350929a), + (0x0000dbdf), + (0x24c94f38), + (0x7e99d7f3), + (0x5a504314), + (0xb900d18e), + (0x9dc94569), + (0xc799dda2), + (0xe3504945)}, + {(0x00000000), + (0x00764000), + (0x000d4000), + (0x007b0000), + (0x102e6000), + (0x10582000), + (0x10232000), + (0x10556000), + (0x10065e00), + (0x10701e00), + (0x100b1e00), + (0x107d5e00), + (0x00283e00), + (0x005e7e00), + (0x00257e00), + (0x00533e00)}, + {(0x3f800000), + (0x3f803b20), + (0x3f8006a0), + (0x3f803d80), + (0x3f881730), + (0x3f882c10), + (0x3f881190), + (0x3f882ab0), + (0x3f88032f), + (0x3f88380f), + (0x3f88058f), + (0x3f883eaf), + (0x3f80141f), + (0x3f802f3f), + (0x3f8012bf), + (0x3f80299f)}, + (0xfff80000), + {0xfb,0xa8,0xac,0x3b,0xfe,0x8d,0xcc,0xf9,0x64,0x79, + 0xa4,0xdb,0x6d,0x8f,0x8a,0x6e,0xb9,0x91,0x4e,0xb0,0x00} + }, + { + /* No.166 delta:1278 weight:1311 */ + 11213, + 38, + 18, + 10, + {(0x00000000), + (0x1aa51933), + (0x7654762b), + (0x6cf16f18), + (0x06100a69), + (0x1cb5135a), + (0x70447c42), + (0x6ae16571), + (0x0000bdcd), + (0x1aa5a4fe), + (0x7654cbe6), + (0x6cf1d2d5), + (0x0610b7a4), + (0x1cb5ae97), + (0x7044c18f), + (0x6ae1d8bc)}, + {(0x00000000), + (0x1c020c00), + (0x10065600), + (0x0c045a00), + (0xa4030000), + (0xb8010c00), + (0xb4055600), + (0xa8075a00), + (0x51205e00), + (0x4d225200), + (0x41260800), + (0x5d240400), + (0xf5235e00), + (0xe9215200), + (0xe5250800), + (0xf9270400)}, + {(0x3f800000), + (0x3f8e0106), + (0x3f88032b), + (0x3f86022d), + (0x3fd20180), + (0x3fdc0086), + (0x3fda02ab), + (0x3fd403ad), + (0x3fa8902f), + (0x3fa69129), + (0x3fa09304), + (0x3fae9202), + (0x3ffa91af), + (0x3ff490a9), + (0x3ff29284), + (0x3ffc9382)}, + (0xfff80000), + {0xe2,0x4b,0xe1,0x7f,0x94,0x30,0x00,0x2c,0x65,0x3e, + 0x59,0x45,0xfa,0x87,0x44,0x25,0xe1,0x2d,0xb7,0xdb,0x00} + }, + { + /* No.167 delta:1582 weight:743 */ + 11213, + 80, + 9, + 17, + {(0x00000000), + (0xf8f257fd), + (0x26c7fb3f), + (0xde35acc2), + (0xba900a7d), + (0x42625d80), + (0x9c57f142), + (0x64a5a6bf), + (0x00008157), + (0xf8f2d6aa), + (0x26c77a68), + (0xde352d95), + (0xba908b2a), + (0x4262dcd7), + (0x9c577015), + (0x64a527e8)}, + {(0x00000000), + (0x884f0000), + (0x11035000), + (0x994c5000), + (0x2a02a800), + (0xa24da800), + (0x3b01f800), + (0xb34ef800), + (0x10041e00), + (0x984b1e00), + (0x01074e00), + (0x89484e00), + (0x3a06b600), + (0xb249b600), + (0x2b05e600), + (0xa34ae600)}, + {(0x3f800000), + (0x3fc42780), + (0x3f8881a8), + (0x3fcca628), + (0x3f950154), + (0x3fd126d4), + (0x3f9d80fc), + (0x3fd9a77c), + (0x3f88020f), + (0x3fcc258f), + (0x3f8083a7), + (0x3fc4a427), + (0x3f9d035b), + (0x3fd924db), + (0x3f9582f3), + (0x3fd1a573)}, + (0xfff80000), + {0xad,0x7a,0xb9,0x26,0x28,0x43,0xfc,0x1a,0x71,0x9d, + 0xfe,0xb1,0x4c,0x75,0x45,0xcd,0x8d,0xf2,0x4d,0x01,0x00} + }, + { + /* No.168 delta:7619 weight:787 */ + 11213, + 59, + 26, + 1, + {(0x00000000), + (0x98e8b6d9), + (0x521f6a74), + (0xcaf7dcad), + (0x53d00a8d), + (0xcb38bc54), + (0x01cf60f9), + (0x9927d620), + (0x0000f72a), + (0x98e841f3), + (0x521f9d5e), + (0xcaf72b87), + (0x53d0fda7), + (0xcb384b7e), + (0x01cf97d3), + (0x9927210a)}, + {(0x00000000), + (0x4e200000), + (0x70542000), + (0x3e742000), + (0x13942000), + (0x5db42000), + (0x63c00000), + (0x2de00000), + (0x08001e00), + (0x46201e00), + (0x78543e00), + (0x36743e00), + (0x1b943e00), + (0x55b43e00), + (0x6bc01e00), + (0x25e01e00)}, + {(0x3f800000), + (0x3fa71000), + (0x3fb82a10), + (0x3f9f3a10), + (0x3f89ca10), + (0x3faeda10), + (0x3fb1e000), + (0x3f96f000), + (0x3f84000f), + (0x3fa3100f), + (0x3fbc2a1f), + (0x3f9b3a1f), + (0x3f8dca1f), + (0x3faada1f), + (0x3fb5e00f), + (0x3f92f00f)}, + (0xfff80000), + {0xc1,0xeb,0x15,0xa4,0x17,0x5a,0x94,0xa3,0xdd,0x5b, + 0x7e,0x69,0x12,0x88,0xd9,0x94,0x36,0x81,0x7c,0x98,0x00} + }, + { + /* No.169 delta:1710 weight:1097 */ + 11213, + 57, + 14, + 11, + {(0x00000000), + (0x5e421ddc), + (0x638787c4), + (0x3dc59a18), + (0x8e000a9d), + (0xd0421741), + (0xed878d59), + (0xb3c59085), + (0x0000840f), + (0x5e4299d3), + (0x638703cb), + (0x3dc51e17), + (0x8e008e92), + (0xd042934e), + (0xed870956), + (0xb3c5148a)}, + {(0x00000000), + (0x4a752000), + (0xd0784000), + (0x9a0d6000), + (0x004c4000), + (0x4a396000), + (0xd0340000), + (0x9a412000), + (0x00005e00), + (0x4a757e00), + (0xd0781e00), + (0x9a0d3e00), + (0x004c1e00), + (0x4a393e00), + (0xd0345e00), + (0x9a417e00)}, + {(0x3f800000), + (0x3fa53a90), + (0x3fe83c20), + (0x3fcd06b0), + (0x3f802620), + (0x3fa51cb0), + (0x3fe81a00), + (0x3fcd2090), + (0x3f80002f), + (0x3fa53abf), + (0x3fe83c0f), + (0x3fcd069f), + (0x3f80260f), + (0x3fa51c9f), + (0x3fe81a2f), + (0x3fcd20bf)}, + (0xfff80000), + {0x63,0xf7,0x0a,0xee,0x1d,0x41,0x31,0xa9,0xfd,0x48, + 0x35,0xb8,0x86,0xd8,0xf7,0x25,0x29,0x14,0xb0,0x12,0x00} + }, + { + /* No.170 delta:4372 weight:995 */ + 11213, + 28, + 7, + 15, + {(0x00000000), + (0x655fb5a5), + (0x87997101), + (0xe2c6c4a4), + (0x59f00aaa), + (0x3cafbf0f), + (0xde697bab), + (0xbb36ce0e), + (0x0000365d), + (0x655f83f8), + (0x8799475c), + (0xe2c6f2f9), + (0x59f03cf7), + (0x3caf8952), + (0xde694df6), + (0xbb36f853)}, + {(0x00000000), + (0x81898800), + (0xd202e000), + (0x538b6800), + (0x08d64000), + (0x895fc800), + (0xdad4a000), + (0x5b5d2800), + (0x004a5e00), + (0x81c3d600), + (0xd248be00), + (0x53c13600), + (0x089c1e00), + (0x89159600), + (0xda9efe00), + (0x5b177600)}, + {(0x3f800000), + (0x3fc0c4c4), + (0x3fe90170), + (0x3fa9c5b4), + (0x3f846b20), + (0x3fc4afe4), + (0x3fed6a50), + (0x3fadae94), + (0x3f80252f), + (0x3fc0e1eb), + (0x3fe9245f), + (0x3fa9e09b), + (0x3f844e0f), + (0x3fc48acb), + (0x3fed4f7f), + (0x3fad8bbb)}, + (0xfff80000), + {0x89,0xf5,0x02,0x8f,0x88,0xdf,0x79,0x2c,0xc5,0x67, + 0x1f,0x9e,0xd5,0x1b,0xd9,0x5a,0x79,0x7f,0xca,0x71,0x00} + }, + { + /* No.171 delta:3023 weight:1549 */ + 11213, + 32, + 3, + 5, + {(0x00000000), + (0x3b134609), + (0x5b97bf87), + (0x6084f98e), + (0xdbb00aba), + (0xe0a34cb3), + (0x8027b53d), + (0xbb34f334), + (0x00000ea9), + (0x3b1348a0), + (0x5b97b12e), + (0x6084f727), + (0xdbb00413), + (0xe0a3421a), + (0x8027bb94), + (0xbb34fd9d)}, + {(0x00000000), + (0x04030000), + (0x00c10000), + (0x04c20000), + (0x304a8000), + (0x34498000), + (0x308b8000), + (0x34888000), + (0x00679e00), + (0x04649e00), + (0x00a69e00), + (0x04a59e00), + (0x302d1e00), + (0x342e1e00), + (0x30ec1e00), + (0x34ef1e00)}, + {(0x3f800000), + (0x3f820180), + (0x3f806080), + (0x3f826100), + (0x3f982540), + (0x3f9a24c0), + (0x3f9845c0), + (0x3f9a4440), + (0x3f8033cf), + (0x3f82324f), + (0x3f80534f), + (0x3f8252cf), + (0x3f98168f), + (0x3f9a170f), + (0x3f98760f), + (0x3f9a778f)}, + (0xfff80000), + {0x6a,0x8d,0xed,0xda,0x5f,0x16,0x85,0xea,0xd9,0x4c, + 0x66,0x31,0xe2,0x9c,0xc6,0x66,0x6d,0x10,0xa0,0xf9,0x00} + }, + { + /* No.172 delta:892 weight:1461 */ + 11213, + 41, + 18, + 4, + {(0x00000000), + (0x51c43b00), + (0x7d71cf7d), + (0x2cb5f47d), + (0x03f00ac3), + (0x523431c3), + (0x7e81c5be), + (0x2f45febe), + (0x0000fa3d), + (0x51c4c13d), + (0x7d713540), + (0x2cb50e40), + (0x03f0f0fe), + (0x5234cbfe), + (0x7e813f83), + (0x2f450483)}, + {(0x00000000), + (0x40672000), + (0x00508c00), + (0x4037ac00), + (0x00402000), + (0x40270000), + (0x0010ac00), + (0x40778c00), + (0x0e881e00), + (0x4eef3e00), + (0x0ed89200), + (0x4ebfb200), + (0x0ec83e00), + (0x4eaf1e00), + (0x0e98b200), + (0x4eff9200)}, + {(0x3f800000), + (0x3fa03390), + (0x3f802846), + (0x3fa01bd6), + (0x3f802010), + (0x3fa01380), + (0x3f800856), + (0x3fa03bc6), + (0x3f87440f), + (0x3fa7779f), + (0x3f876c49), + (0x3fa75fd9), + (0x3f87641f), + (0x3fa7578f), + (0x3f874c59), + (0x3fa77fc9)}, + (0xfff80000), + {0xc5,0x69,0xaf,0xb6,0xea,0x60,0x78,0x16,0x94,0x3a, + 0x36,0x01,0x5a,0xe7,0x99,0xcd,0x09,0x6a,0xda,0xea,0x00} + }, + { + /* No.173 delta:1013 weight:1115 */ + 11213, + 91, + 19, + 8, + {(0x00000000), + (0xd6aede60), + (0xdfd2815a), + (0x097c5f3a), + (0xbc400ad0), + (0x6aeed4b0), + (0x63928b8a), + (0xb53c55ea), + (0x000003b3), + (0xd6aeddd3), + (0xdfd282e9), + (0x097c5c89), + (0xbc400963), + (0x6aeed703), + (0x63928839), + (0xb53c5659)}, + {(0x00000000), + (0x24590000), + (0x08c14000), + (0x2c984000), + (0x80083800), + (0xa4513800), + (0x88c97800), + (0xac907800), + (0x50c09e00), + (0x74999e00), + (0x5801de00), + (0x7c58de00), + (0xd0c8a600), + (0xf491a600), + (0xd809e600), + (0xfc50e600)}, + {(0x3f800000), + (0x3f922c80), + (0x3f8460a0), + (0x3f964c20), + (0x3fc0041c), + (0x3fd2289c), + (0x3fc464bc), + (0x3fd6483c), + (0x3fa8604f), + (0x3fba4ccf), + (0x3fac00ef), + (0x3fbe2c6f), + (0x3fe86453), + (0x3ffa48d3), + (0x3fec04f3), + (0x3ffe2873)}, + (0xfff80000), + {0x55,0x6c,0x5c,0x20,0xdd,0xbb,0xa3,0xad,0x56,0x67, + 0x8f,0xcf,0xc9,0xb4,0xc5,0x0f,0x66,0xf7,0xb5,0xcc,0x00} + }, + { + /* No.174 delta:2582 weight:887 */ + 11213, + 40, + 4, + 1, + {(0x00000000), + (0x70c0d1b0), + (0x83972550), + (0xf357f4e0), + (0xbbc00ae0), + (0xcb00db50), + (0x38572fb0), + (0x4897fe00), + (0x0000df80), + (0x70c00e30), + (0x8397fad0), + (0xf3572b60), + (0xbbc0d560), + (0xcb0004d0), + (0x3857f030), + (0x48972180)}, + {(0x00000000), + (0x00b20200), + (0x00430000), + (0x00f10200), + (0x40024000), + (0x40b04200), + (0x40414000), + (0x40f34200), + (0x6401de00), + (0x64b3dc00), + (0x6442de00), + (0x64f0dc00), + (0x24039e00), + (0x24b19c00), + (0x24409e00), + (0x24f29c00)}, + {(0x3f800000), + (0x3f805901), + (0x3f802180), + (0x3f807881), + (0x3fa00120), + (0x3fa05821), + (0x3fa020a0), + (0x3fa079a1), + (0x3fb200ef), + (0x3fb259ee), + (0x3fb2216f), + (0x3fb2786e), + (0x3f9201cf), + (0x3f9258ce), + (0x3f92204f), + (0x3f92794e)}, + (0xfff80000), + {0x4c,0x34,0x96,0xf1,0x70,0xe5,0x52,0xb1,0x4d,0x38, + 0xa6,0x34,0x26,0x09,0x5c,0x6c,0x92,0xe6,0x3e,0xcb,0x00} + }, + { + /* No.175 delta:1962 weight:1531 */ + 11213, + 11, + 19, + 4, + {(0x00000000), + (0x91291aaa), + (0xdc02bffd), + (0x4d2ba557), + (0x1fc00af5), + (0x8ee9105f), + (0xc3c2b508), + (0x52ebafa2), + (0x0000add4), + (0x9129b77e), + (0xdc021229), + (0x4d2b0883), + (0x1fc0a721), + (0x8ee9bd8b), + (0xc3c218dc), + (0x52eb0276)}, + {(0x00000000), + (0x09ff0c00), + (0x09141600), + (0x00eb1a00), + (0x7510e000), + (0x7cefec00), + (0x7c04f600), + (0x75fbfa00), + (0x05509e00), + (0x0caf9200), + (0x0c448800), + (0x05bb8400), + (0x70407e00), + (0x79bf7200), + (0x79546800), + (0x70ab6400)}, + {(0x3f800000), + (0x3f84ff86), + (0x3f848a0b), + (0x3f80758d), + (0x3fba8870), + (0x3fbe77f6), + (0x3fbe027b), + (0x3fbafdfd), + (0x3f82a84f), + (0x3f8657c9), + (0x3f862244), + (0x3f82ddc2), + (0x3fb8203f), + (0x3fbcdfb9), + (0x3fbcaa34), + (0x3fb855b2)}, + (0xfff80000), + {0x6f,0x40,0xbd,0xae,0x48,0xc1,0x7d,0x5b,0x99,0x1a, + 0x4e,0x57,0x61,0x39,0x1e,0x68,0xb1,0xf7,0xc0,0xaa,0x00} + }, + { + /* No.176 delta:2277 weight:543 */ + 11213, + 33, + 7, + 19, + {(0x00000000), + (0x8044010b), + (0x62414b11), + (0xe2054a1a), + (0xbb700b06), + (0x3b340a0d), + (0xd9314017), + (0x5975411c), + (0x000099a5), + (0x804498ae), + (0x6241d2b4), + (0xe205d3bf), + (0xbb7092a3), + (0x3b3493a8), + (0xd931d9b2), + (0x5975d8b9)}, + {(0x00000000), + (0x0c3e0800), + (0x80be4000), + (0x8c804800), + (0x00483000), + (0x0c763800), + (0x80f67000), + (0x8cc87800), + (0x00791e00), + (0x0c471600), + (0x80c75e00), + (0x8cf95600), + (0x00312e00), + (0x0c0f2600), + (0x808f6e00), + (0x8cb16600)}, + {(0x3f800000), + (0x3f861f04), + (0x3fc05f20), + (0x3fc64024), + (0x3f802418), + (0x3f863b1c), + (0x3fc07b38), + (0x3fc6643c), + (0x3f803c8f), + (0x3f86238b), + (0x3fc063af), + (0x3fc67cab), + (0x3f801897), + (0x3f860793), + (0x3fc047b7), + (0x3fc658b3)}, + (0xfff80000), + {0xfc,0x12,0x23,0x4e,0x03,0xa3,0xf6,0xfd,0x28,0xb5, + 0xf1,0x0e,0x0a,0x5d,0xed,0x4a,0xd6,0x0c,0xfa,0x9a,0x00} + }, + { + /* No.177 delta:1331 weight:1179 */ + 11213, + 60, + 21, + 4, + {(0x00000000), + (0x8e46be68), + (0x9cb3a5d7), + (0x12f51bbf), + (0x3e600b12), + (0xb026b57a), + (0xa2d3aec5), + (0x2c9510ad), + (0x0000942c), + (0x8e462a44), + (0x9cb331fb), + (0x12f58f93), + (0x3e609f3e), + (0xb0262156), + (0xa2d33ae9), + (0x2c958481)}, + {(0x00000000), + (0x0940a800), + (0x388c9000), + (0x31cc3800), + (0x00608000), + (0x09202800), + (0x38ec1000), + (0x31acb800), + (0x005c7e00), + (0x091cd600), + (0x38d0ee00), + (0x31904600), + (0x003cfe00), + (0x097c5600), + (0x38b06e00), + (0x31f0c600)}, + {(0x3f800000), + (0x3f84a054), + (0x3f9c4648), + (0x3f98e61c), + (0x3f803040), + (0x3f849014), + (0x3f9c7608), + (0x3f98d65c), + (0x3f802e3f), + (0x3f848e6b), + (0x3f9c6877), + (0x3f98c823), + (0x3f801e7f), + (0x3f84be2b), + (0x3f9c5837), + (0x3f98f863)}, + (0xfff80000), + {0x71,0x3a,0xb0,0x71,0xe1,0x95,0x3c,0xba,0x23,0x00, + 0x7a,0xc6,0x93,0x4a,0xb7,0xb8,0xeb,0x00,0x24,0x8e,0x00} + }, + { + /* No.178 delta:3213 weight:657 */ + 11213, + 46, + 22, + 1, + {(0x00000000), + (0x53fdf1b0), + (0x32502578), + (0x61add4c8), + (0x46c00b28), + (0x153dfa98), + (0x74902e50), + (0x276ddfe0), + (0x00006d70), + (0x53fd9cc0), + (0x32504808), + (0x61adb9b8), + (0x46c06658), + (0x153d97e8), + (0x74904320), + (0x276db290)}, + {(0x00000000), + (0x44633a00), + (0x44038600), + (0x0060bc00), + (0x1819c200), + (0x5c7af800), + (0x5c1a4400), + (0x18797e00), + (0x21eade00), + (0x6589e400), + (0x65e95800), + (0x218a6200), + (0x39f31c00), + (0x7d902600), + (0x7df09a00), + (0x3993a000)}, + {(0x3f800000), + (0x3fa2319d), + (0x3fa201c3), + (0x3f80305e), + (0x3f8c0ce1), + (0x3fae3d7c), + (0x3fae0d22), + (0x3f8c3cbf), + (0x3f90f56f), + (0x3fb2c4f2), + (0x3fb2f4ac), + (0x3f90c531), + (0x3f9cf98e), + (0x3fbec813), + (0x3fbef84d), + (0x3f9cc9d0)}, + (0xfff80000), + {0x92,0xb2,0x66,0x1e,0x08,0xb8,0x0b,0x02,0x41,0xdc, + 0x45,0x04,0x59,0x65,0x0b,0x55,0x82,0x05,0xeb,0x6d,0x00} + }, + { + /* No.179 delta:4972 weight:1077 */ + 11213, + 16, + 7, + 11, + {(0x00000000), + (0xcf8962a9), + (0xb6d797a1), + (0x795ef508), + (0xfbb00b36), + (0x3439699f), + (0x4d679c97), + (0x82eefe3e), + (0x0000d59e), + (0xcf89b737), + (0xb6d7423f), + (0x795e2096), + (0xfbb0dea8), + (0x3439bc01), + (0x4d674909), + (0x82ee2ba0)}, + {(0x00000000), + (0x01000000), + (0x08000000), + (0x09000000), + (0x41800000), + (0x40800000), + (0x49800000), + (0x48800000), + (0x06801e00), + (0x07801e00), + (0x0e801e00), + (0x0f801e00), + (0x47001e00), + (0x46001e00), + (0x4f001e00), + (0x4e001e00)}, + {(0x3f800000), + (0x3f808000), + (0x3f840000), + (0x3f848000), + (0x3fa0c000), + (0x3fa04000), + (0x3fa4c000), + (0x3fa44000), + (0x3f83400f), + (0x3f83c00f), + (0x3f87400f), + (0x3f87c00f), + (0x3fa3800f), + (0x3fa3000f), + (0x3fa7800f), + (0x3fa7000f)}, + (0xfff80000), + {0x55,0xe1,0xc9,0x26,0x74,0x2c,0xed,0x5c,0x7b,0x89, + 0xe7,0x1d,0x6f,0x5d,0x02,0xe5,0x4a,0x19,0x8c,0x04,0x00} + }, + { + /* No.180 delta:2285 weight:1529 */ + 11213, + 16, + 5, + 9, + {(0x00000000), + (0x5766ef3b), + (0xaca2499c), + (0xfbc4a6a7), + (0x63800b4f), + (0x34e6e474), + (0xcf2242d3), + (0x9844ade8), + (0x0000a19a), + (0x57664ea1), + (0xaca2e806), + (0xfbc4073d), + (0x6380aad5), + (0x34e645ee), + (0xcf22e349), + (0x98440c72)}, + {(0x00000000), + (0x1901c200), + (0x88118000), + (0x91104200), + (0x02ef8000), + (0x1bee4200), + (0x8afe0000), + (0x93ffc200), + (0x3087be00), + (0x29867c00), + (0xb8963e00), + (0xa197fc00), + (0x32683e00), + (0x2b69fc00), + (0xba79be00), + (0xa3787c00)}, + {(0x3f800000), + (0x3f8c80e1), + (0x3fc408c0), + (0x3fc88821), + (0x3f8177c0), + (0x3f8df721), + (0x3fc57f00), + (0x3fc9ffe1), + (0x3f9843df), + (0x3f94c33e), + (0x3fdc4b1f), + (0x3fd0cbfe), + (0x3f99341f), + (0x3f95b4fe), + (0x3fdd3cdf), + (0x3fd1bc3e)}, + (0xfff80000), + {0x4b,0xb0,0xb5,0xae,0x6b,0x5e,0xea,0x44,0x3b,0xd2, + 0xcf,0xf3,0x8a,0x8d,0xff,0x98,0xeb,0xce,0xa2,0x22,0x00} + }, + { + /* No.181 delta:1320 weight:1461 */ + 11213, + 52, + 21, + 2, + {(0x00000000), + (0x2f3716e3), + (0x0af6f7a8), + (0x25c1e14b), + (0x67900b5a), + (0x48a71db9), + (0x6d66fcf2), + (0x4251ea11), + (0x0000adb5), + (0x2f37bb56), + (0x0af65a1d), + (0x25c14cfe), + (0x6790a6ef), + (0x48a7b00c), + (0x6d665147), + (0x425147a4)}, + {(0x00000000), + (0xc0295e00), + (0x1040c000), + (0xd0699e00), + (0x20fc7200), + (0xe0d52c00), + (0x30bcb200), + (0xf095ec00), + (0x10a2fe00), + (0xd08ba000), + (0x00e23e00), + (0xc0cb6000), + (0x305e8c00), + (0xf077d200), + (0x201e4c00), + (0xe0371200)}, + {(0x3f800000), + (0x3fe014af), + (0x3f882060), + (0x3fe834cf), + (0x3f907e39), + (0x3ff06a96), + (0x3f985e59), + (0x3ff84af6), + (0x3f88517f), + (0x3fe845d0), + (0x3f80711f), + (0x3fe065b0), + (0x3f982f46), + (0x3ff83be9), + (0x3f900f26), + (0x3ff01b89)}, + (0xfff80000), + {0xf7,0x30,0xe4,0xa1,0xb6,0x2c,0xff,0x05,0x23,0x13, + 0xd1,0x56,0xd7,0x7a,0x22,0x24,0xae,0xf7,0x34,0x52,0x00} + }, + { + /* No.182 delta:789 weight:1509 */ + 11213, + 74, + 16, + 6, + {(0x00000000), + (0xe416060b), + (0xd6bfa624), + (0x32a9a02f), + (0x56500b61), + (0xb2460d6a), + (0x80efad45), + (0x64f9ab4e), + (0x0000ce80), + (0xe416c88b), + (0xd6bf68a4), + (0x32a96eaf), + (0x5650c5e1), + (0xb246c3ea), + (0x80ef63c5), + (0x64f965ce)}, + {(0x00000000), + (0x804c0800), + (0x107ad000), + (0x9036d800), + (0x0055c400), + (0x8019cc00), + (0x102f1400), + (0x90631c00), + (0x00033e00), + (0x804f3600), + (0x1079ee00), + (0x9035e600), + (0x0056fa00), + (0x801af200), + (0x102c2a00), + (0x90602200)}, + {(0x3f800000), + (0x3fc02604), + (0x3f883d68), + (0x3fc81b6c), + (0x3f802ae2), + (0x3fc00ce6), + (0x3f88178a), + (0x3fc8318e), + (0x3f80019f), + (0x3fc0279b), + (0x3f883cf7), + (0x3fc81af3), + (0x3f802b7d), + (0x3fc00d79), + (0x3f881615), + (0x3fc83011)}, + (0xfff80000), + {0xa2,0xea,0x48,0x1e,0xb3,0x8f,0x99,0x75,0xba,0x12, + 0x9c,0xbf,0xf3,0xa0,0xb8,0x5d,0xc8,0x38,0xc4,0x74,0x00} + }, + { + /* No.183 delta:1268 weight:1109 */ + 11213, + 42, + 13, + 11, + {(0x00000000), + (0xf7ba01fd), + (0xaa8773ac), + (0x5d3d7251), + (0xa5b00b7d), + (0x520a0a80), + (0x0f3778d1), + (0xf88d792c), + (0x0000aaa0), + (0xf7baab5d), + (0xaa87d90c), + (0x5d3dd8f1), + (0xa5b0a1dd), + (0x520aa020), + (0x0f37d271), + (0xf88dd38c)}, + {(0x00000000), + (0x92abc000), + (0x00443800), + (0x92eff800), + (0x00c12000), + (0x926ae000), + (0x00851800), + (0x922ed800), + (0x02a3be00), + (0x90087e00), + (0x02e78600), + (0x904c4600), + (0x02629e00), + (0x90c95e00), + (0x0226a600), + (0x908d6600)}, + {(0x3f800000), + (0x3fc955e0), + (0x3f80221c), + (0x3fc977fc), + (0x3f806090), + (0x3fc93570), + (0x3f80428c), + (0x3fc9176c), + (0x3f8151df), + (0x3fc8043f), + (0x3f8173c3), + (0x3fc82623), + (0x3f81314f), + (0x3fc864af), + (0x3f811353), + (0x3fc846b3)}, + (0xfff80000), + {0xb0,0x87,0xce,0x22,0xcb,0xa4,0x10,0xdc,0xdb,0x3e, + 0x3c,0x67,0xae,0x3f,0xc0,0x11,0xf3,0xec,0xe2,0x06,0x00} + }, + { + /* No.184 delta:1092 weight:1295 */ + 11213, + 91, + 17, + 8, + {(0x00000000), + (0x2fa2608e), + (0x8f680761), + (0xa0ca67ef), + (0x13a00b8a), + (0x3c026b04), + (0x9cc80ceb), + (0xb36a6c65), + (0x00007f70), + (0x2fa21ffe), + (0x8f687811), + (0xa0ca189f), + (0x13a074fa), + (0x3c021474), + (0x9cc8739b), + (0xb36a1315)}, + {(0x00000000), + (0x089d6000), + (0x1a00e200), + (0x129d8200), + (0x40df4000), + (0x48422000), + (0x5adfa200), + (0x5242c200), + (0x01a6de00), + (0x093bbe00), + (0x1ba63c00), + (0x133b5c00), + (0x41799e00), + (0x49e4fe00), + (0x5b797c00), + (0x53e41c00)}, + {(0x3f800000), + (0x3f844eb0), + (0x3f8d0071), + (0x3f894ec1), + (0x3fa06fa0), + (0x3fa42110), + (0x3fad6fd1), + (0x3fa92161), + (0x3f80d36f), + (0x3f849ddf), + (0x3f8dd31e), + (0x3f899dae), + (0x3fa0bccf), + (0x3fa4f27f), + (0x3fadbcbe), + (0x3fa9f20e)}, + (0xfff80000), + {0xbd,0xb1,0x02,0x3f,0x46,0x65,0xe7,0x62,0xbf,0x9e, + 0x12,0xaa,0x33,0xbe,0x0c,0x5d,0x89,0x02,0x2c,0x11,0x00} + }, + { + /* No.185 delta:8146 weight:1071 */ + 11213, + 66, + 28, + 1, + {(0x00000000), + (0xc3e3a60c), + (0x80c000cd), + (0x4323a6c1), + (0xda800b97), + (0x1963ad9b), + (0x5a400b5a), + (0x99a3ad56), + (0x000058ad), + (0xc3e3fea1), + (0x80c05860), + (0x4323fe6c), + (0xda80533a), + (0x1963f536), + (0x5a4053f7), + (0x99a3f5fb)}, + {(0x00000000), + (0x89d10a00), + (0x403c0200), + (0xc9ed0800), + (0x53520000), + (0xda830a00), + (0x136e0200), + (0x9abf0800), + (0x61609e00), + (0xe8b19400), + (0x215c9c00), + (0xa88d9600), + (0x32329e00), + (0xbbe39400), + (0x720e9c00), + (0xfbdf9600)}, + {(0x3f800000), + (0x3fc4e885), + (0x3fa01e01), + (0x3fe4f684), + (0x3fa9a900), + (0x3fed4185), + (0x3f89b701), + (0x3fcd5f84), + (0x3fb0b04f), + (0x3ff458ca), + (0x3f90ae4e), + (0x3fd446cb), + (0x3f99194f), + (0x3fddf1ca), + (0x3fb9074e), + (0x3ffdefcb)}, + (0xfff80000), + {0xf7,0x3c,0x9c,0x40,0x28,0xb5,0xbe,0xbf,0x2e,0x97, + 0xa1,0x61,0x3b,0x82,0x2a,0x82,0x3c,0xa0,0xf4,0x90,0x00} + }, + { + /* No.186 delta:2697 weight:1957 */ + 11213, + 43, + 3, + 3, + {(0x00000000), + (0x7a0a48fc), + (0x29a53edd), + (0x53af7621), + (0x08f00ba0), + (0x72fa435c), + (0x2155357d), + (0x5b5f7d81), + (0x0000132f), + (0x7a0a5bd3), + (0x29a52df2), + (0x53af650e), + (0x08f0188f), + (0x72fa5073), + (0x21552652), + (0x5b5f6eae)}, + {(0x00000000), + (0xa2021000), + (0x1c21a000), + (0xbe23b000), + (0x00408000), + (0xa2429000), + (0x1c612000), + (0xbe633000), + (0x40201e00), + (0xe2220e00), + (0x5c01be00), + (0xfe03ae00), + (0x40609e00), + (0xe2628e00), + (0x5c413e00), + (0xfe432e00)}, + {(0x3f800000), + (0x3fd10108), + (0x3f8e10d0), + (0x3fdf11d8), + (0x3f802040), + (0x3fd12148), + (0x3f8e3090), + (0x3fdf3198), + (0x3fa0100f), + (0x3ff11107), + (0x3fae00df), + (0x3fff01d7), + (0x3fa0304f), + (0x3ff13147), + (0x3fae209f), + (0x3fff2197)}, + (0xfff80000), + {0x1a,0x79,0x8f,0xb2,0xec,0xc2,0xee,0xfc,0x66,0xa6, + 0x37,0x12,0x4d,0x78,0x6e,0xa1,0xb0,0x60,0x86,0x37,0x00} + }, + { + /* No.187 delta:2420 weight:1355 */ + 11213, + 28, + 24, + 3, + {(0x00000000), + (0x9580742c), + (0xce45a063), + (0x5bc5d44f), + (0x33f00bbf), + (0xa6707f93), + (0xfdb5abdc), + (0x6835dff0), + (0x000009ba), + (0x95807d96), + (0xce45a9d9), + (0x5bc5ddf5), + (0x33f00205), + (0xa6707629), + (0xfdb5a266), + (0x6835d64a)}, + {(0x00000000), + (0x40bf0200), + (0x00440200), + (0x40fb0000), + (0x3411d000), + (0x74aed200), + (0x3455d200), + (0x74ead000), + (0x9082de00), + (0xd03ddc00), + (0x90c6dc00), + (0xd079de00), + (0xa4930e00), + (0xe42c0c00), + (0xa4d70c00), + (0xe4680e00)}, + {(0x3f800000), + (0x3fa05f81), + (0x3f802201), + (0x3fa07d80), + (0x3f9a08e8), + (0x3fba5769), + (0x3f9a2ae9), + (0x3fba7568), + (0x3fc8416f), + (0x3fe81eee), + (0x3fc8636e), + (0x3fe83cef), + (0x3fd24987), + (0x3ff21606), + (0x3fd26b86), + (0x3ff23407)}, + (0xfff80000), + {0x20,0xe4,0x7d,0x6c,0xc4,0xf9,0x2b,0x4a,0x56,0x18, + 0x64,0xa0,0x86,0x2c,0x45,0x4a,0x42,0x3a,0x22,0x49,0x00} + }, + { + /* No.188 delta:1841 weight:735 */ + 11213, + 62, + 10, + 18, + {(0x00000000), + (0x179a1ef2), + (0x535f148e), + (0x44c50a7c), + (0x33700bc3), + (0x24ea1531), + (0x602f1f4d), + (0x77b501bf), + (0x0000df3e), + (0x179ac1cc), + (0x535fcbb0), + (0x44c5d542), + (0x3370d4fd), + (0x24eaca0f), + (0x602fc073), + (0x77b5de81)}, + {(0x00000000), + (0x30b90000), + (0x083c0000), + (0x38850000), + (0x40070000), + (0x70be0000), + (0x483b0000), + (0x78820000), + (0x10651e00), + (0x20dc1e00), + (0x18591e00), + (0x28e01e00), + (0x50621e00), + (0x60db1e00), + (0x585e1e00), + (0x68e71e00)}, + {(0x3f800000), + (0x3f985c80), + (0x3f841e00), + (0x3f9c4280), + (0x3fa00380), + (0x3fb85f00), + (0x3fa41d80), + (0x3fbc4100), + (0x3f88328f), + (0x3f906e0f), + (0x3f8c2c8f), + (0x3f94700f), + (0x3fa8310f), + (0x3fb06d8f), + (0x3fac2f0f), + (0x3fb4738f)}, + (0xfff80000), + {0x09,0x19,0x78,0xe9,0x81,0xea,0xdf,0x95,0x46,0x6b, + 0x4f,0xa1,0xca,0x2b,0xbc,0x8a,0x0b,0xaa,0x44,0xb8,0x00} + }, + { + /* No.189 delta:3318 weight:1469 */ + 11213, + 81, + 3, + 7, + {(0x00000000), + (0xfe728280), + (0xcc048331), + (0x327601b1), + (0x42200bd8), + (0xbc528958), + (0x8e2488e9), + (0x70560a69), + (0x0000d1a0), + (0xfe725320), + (0xcc045291), + (0x3276d011), + (0x4220da78), + (0xbc5258f8), + (0x8e245949), + (0x7056dbc9)}, + {(0x00000000), + (0x12010000), + (0x53002000), + (0x41012000), + (0x20414000), + (0x32404000), + (0x73416000), + (0x61406000), + (0x20321e00), + (0x32331e00), + (0x73323e00), + (0x61333e00), + (0x00735e00), + (0x12725e00), + (0x53737e00), + (0x41727e00)}, + {(0x3f800000), + (0x3f890080), + (0x3fa98010), + (0x3fa08090), + (0x3f9020a0), + (0x3f992020), + (0x3fb9a0b0), + (0x3fb0a030), + (0x3f90190f), + (0x3f99198f), + (0x3fb9991f), + (0x3fb0999f), + (0x3f8039af), + (0x3f89392f), + (0x3fa9b9bf), + (0x3fa0b93f)}, + (0xfff80000), + {0x0f,0xe8,0x93,0xf4,0x0e,0x7e,0xaf,0xe0,0x5d,0x20, + 0x58,0x92,0x06,0x7d,0x5b,0x05,0x6b,0x8a,0x33,0xbb,0x00} + }, + { + /* No.190 delta:1194 weight:821 */ + 11213, + 72, + 11, + 16, + {(0x00000000), + (0x44a385c2), + (0xca99870f), + (0x8e3a02cd), + (0x06c00be8), + (0x42638e2a), + (0xcc598ce7), + (0x88fa0925), + (0x00007bbf), + (0x44a3fe7d), + (0xca99fcb0), + (0x8e3a7972), + (0x06c07057), + (0x4263f595), + (0xcc59f758), + (0x88fa729a)}, + {(0x00000000), + (0x00527800), + (0x302f0400), + (0x307d7c00), + (0x20017000), + (0x20530800), + (0x102e7400), + (0x107c0c00), + (0x10429e00), + (0x1010e600), + (0x206d9a00), + (0x203fe200), + (0x3043ee00), + (0x30119600), + (0x006cea00), + (0x003e9200)}, + {(0x3f800000), + (0x3f80293c), + (0x3f981782), + (0x3f983ebe), + (0x3f9000b8), + (0x3f902984), + (0x3f88173a), + (0x3f883e06), + (0x3f88214f), + (0x3f880873), + (0x3f9036cd), + (0x3f901ff1), + (0x3f9821f7), + (0x3f9808cb), + (0x3f803675), + (0x3f801f49)}, + (0xfff80000), + {0xba,0xb7,0xd5,0xc8,0xec,0x6d,0xc1,0x0c,0x19,0x38, + 0x0f,0x27,0x93,0x3b,0xd8,0x74,0xa1,0x4e,0x45,0x89,0x00} + }, + { + /* No.191 delta:1166 weight:1045 */ + 11213, + 40, + 11, + 9, + {(0x00000000), + (0x212f4af4), + (0xf0432caf), + (0xd16c665b), + (0x11d00bf5), + (0x30ff4101), + (0xe193275a), + (0xc0bc6dae), + (0x0000755f), + (0x212f3fab), + (0xf04359f0), + (0xd16c1304), + (0x11d07eaa), + (0x30ff345e), + (0xe1935205), + (0xc0bc18f1)}, + {(0x00000000), + (0x08528000), + (0x70084000), + (0x785ac000), + (0x00196000), + (0x084be000), + (0x70112000), + (0x7843a000), + (0x0024fe00), + (0x08767e00), + (0x702cbe00), + (0x787e3e00), + (0x003d9e00), + (0x086f1e00), + (0x7035de00), + (0x78675e00)}, + {(0x3f800000), + (0x3f842940), + (0x3fb80420), + (0x3fbc2d60), + (0x3f800cb0), + (0x3f8425f0), + (0x3fb80890), + (0x3fbc21d0), + (0x3f80127f), + (0x3f843b3f), + (0x3fb8165f), + (0x3fbc3f1f), + (0x3f801ecf), + (0x3f84378f), + (0x3fb81aef), + (0x3fbc33af)}, + (0xfff80000), + {0xbf,0xbb,0x3f,0x17,0x6e,0x1a,0x3b,0x45,0x9b,0x2a, + 0x22,0x6a,0xf9,0xf5,0xba,0x97,0x3b,0x8a,0xec,0xd6,0x00} + }, + { + /* No.192 delta:4742 weight:1471 */ + 11213, + 27, + 4, + 6, + {(0x00000000), + (0x7fe173b6), + (0x51169f27), + (0x2ef7ec91), + (0x0a300c00), + (0x75d17fb6), + (0x5b269327), + (0x24c7e091), + (0x00001d00), + (0x7fe16eb6), + (0x51168227), + (0x2ef7f191), + (0x0a301100), + (0x75d162b6), + (0x5b268e27), + (0x24c7fd91)}, + {(0x00000000), + (0x41420000), + (0x00010000), + (0x41430000), + (0x29040000), + (0x68460000), + (0x29050000), + (0x68470000), + (0x00009e00), + (0x41429e00), + (0x00019e00), + (0x41439e00), + (0x29049e00), + (0x68469e00), + (0x29059e00), + (0x68479e00)}, + {(0x3f800000), + (0x3fa0a100), + (0x3f800080), + (0x3fa0a180), + (0x3f948200), + (0x3fb42300), + (0x3f948280), + (0x3fb42380), + (0x3f80004f), + (0x3fa0a14f), + (0x3f8000cf), + (0x3fa0a1cf), + (0x3f94824f), + (0x3fb4234f), + (0x3f9482cf), + (0x3fb423cf)}, + (0xfff80000), + {0xb4,0x7f,0x09,0x23,0xa8,0x3f,0x5e,0x9d,0x3e,0x97, + 0x19,0x94,0x35,0x0d,0xdb,0x3e,0xb7,0x43,0x15,0xd0,0x00} + }, + { + /* No.193 delta:3962 weight:1171 */ + 11213, + 92, + 2, + 13, + {(0x00000000), + (0x76b1ced9), + (0x928504d8), + (0xe434ca01), + (0x7b300c1a), + (0x0d81c2c3), + (0xe9b508c2), + (0x9f04c61b), + (0x0000b2d9), + (0x76b17c00), + (0x9285b601), + (0xe43478d8), + (0x7b30bec3), + (0x0d81701a), + (0xe9b5ba1b), + (0x9f0474c2)}, + {(0x00000000), + (0x08400000), + (0x06400000), + (0x0e000000), + (0x01200000), + (0x09600000), + (0x07600000), + (0x0f200000), + (0x04c01e00), + (0x0c801e00), + (0x02801e00), + (0x0ac01e00), + (0x05e01e00), + (0x0da01e00), + (0x03a01e00), + (0x0be01e00)}, + {(0x3f800000), + (0x3f842000), + (0x3f832000), + (0x3f870000), + (0x3f809000), + (0x3f84b000), + (0x3f83b000), + (0x3f879000), + (0x3f82600f), + (0x3f86400f), + (0x3f81400f), + (0x3f85600f), + (0x3f82f00f), + (0x3f86d00f), + (0x3f81d00f), + (0x3f85f00f)}, + (0xfff80000), + {0xdf,0x8e,0xab,0x00,0xdb,0xdc,0xe0,0x7a,0xb0,0x4c, + 0x05,0x23,0x25,0x58,0x15,0xac,0x74,0x97,0x22,0x21,0x00} + }, + { + /* No.194 delta:2215 weight:1499 */ + 11213, + 63, + 26, + 4, + {(0x00000000), + (0xad5d413b), + (0x166ef61d), + (0xbb33b726), + (0x9e000c20), + (0x335d4d1b), + (0x886efa3d), + (0x2533bb06), + (0x000077be), + (0xad5d3685), + (0x166e81a3), + (0xbb33c098), + (0x9e007b9e), + (0x335d3aa5), + (0x886e8d83), + (0x2533ccb8)}, + {(0x00000000), + (0x10720800), + (0x60810000), + (0x70f30800), + (0x300c0000), + (0x207e0800), + (0x508d0000), + (0x40ff0800), + (0x20023e00), + (0x30703600), + (0x40833e00), + (0x50f13600), + (0x100e3e00), + (0x007c3600), + (0x708f3e00), + (0x60fd3600)}, + {(0x3f800000), + (0x3f883904), + (0x3fb04080), + (0x3fb87984), + (0x3f980600), + (0x3f903f04), + (0x3fa84680), + (0x3fa07f84), + (0x3f90011f), + (0x3f98381b), + (0x3fa0419f), + (0x3fa8789b), + (0x3f88071f), + (0x3f803e1b), + (0x3fb8479f), + (0x3fb07e9b)}, + (0xfff80000), + {0x31,0xb8,0x64,0x9a,0xae,0xad,0xc8,0xf8,0x53,0x9b, + 0x64,0x2d,0x8c,0xb0,0xd2,0xa7,0x8e,0x2e,0xb2,0xc8,0x00} + }, + { + /* No.195 delta:1215 weight:463 */ + 11213, + 60, + 13, + 19, + {(0x00000000), + (0x60520e47), + (0xae8c1b90), + (0xcede15d7), + (0xc1c00c35), + (0xa1920272), + (0x6f4c17a5), + (0x0f1e19e2), + (0x0000fd60), + (0x6052f327), + (0xae8ce6f0), + (0xcedee8b7), + (0xc1c0f155), + (0xa192ff12), + (0x6f4ceac5), + (0x0f1ee482)}, + {(0x00000000), + (0x02e00000), + (0x10cd1200), + (0x122d1200), + (0x14101800), + (0x16f01800), + (0x04dd0a00), + (0x063d0a00), + (0x0057be00), + (0x02b7be00), + (0x109aac00), + (0x127aac00), + (0x1447a600), + (0x16a7a600), + (0x048ab400), + (0x066ab400)}, + {(0x3f800000), + (0x3f817000), + (0x3f886689), + (0x3f891689), + (0x3f8a080c), + (0x3f8b780c), + (0x3f826e85), + (0x3f831e85), + (0x3f802bdf), + (0x3f815bdf), + (0x3f884d56), + (0x3f893d56), + (0x3f8a23d3), + (0x3f8b53d3), + (0x3f82455a), + (0x3f83355a)}, + (0xfff80000), + {0x67,0xca,0xf4,0x9a,0x13,0x78,0x64,0xbc,0x60,0x6d, + 0x5b,0x5f,0x48,0x61,0x94,0x6f,0xdf,0x81,0x2c,0xe1,0x00} + }, + { + /* No.196 delta:939 weight:857 */ + 11213, + 51, + 11, + 2, + {(0x00000000), + (0xa61e8990), + (0x67d50999), + (0xc1cb8009), + (0xa3f00c49), + (0x05ee85d9), + (0xc42505d0), + (0x623b8c40), + (0x00000381), + (0xa61e8a11), + (0x67d50a18), + (0xc1cb8388), + (0xa3f00fc8), + (0x05ee8658), + (0xc4250651), + (0x623b8fc1)}, + {(0x00000000), + (0x08105000), + (0x0002b000), + (0x0812e000), + (0x90084c00), + (0x98181c00), + (0x900afc00), + (0x981aac00), + (0x01007e00), + (0x09102e00), + (0x0102ce00), + (0x09129e00), + (0x91083200), + (0x99186200), + (0x910a8200), + (0x991ad200)}, + {(0x3f800000), + (0x3f840828), + (0x3f800158), + (0x3f840970), + (0x3fc80426), + (0x3fcc0c0e), + (0x3fc8057e), + (0x3fcc0d56), + (0x3f80803f), + (0x3f848817), + (0x3f808167), + (0x3f84894f), + (0x3fc88419), + (0x3fcc8c31), + (0x3fc88541), + (0x3fcc8d69)}, + (0xfff80000), + {0x2c,0x79,0x20,0x40,0xe3,0x10,0xb7,0x11,0xcb,0xf4, + 0xba,0x4e,0xee,0x8b,0x5f,0x86,0xa9,0xdb,0x06,0x27,0x00} + }, + { + /* No.197 delta:1583 weight:1233 */ + 11213, + 26, + 20, + 8, + {(0x00000000), + (0x33fe7f24), + (0x88809fc9), + (0xbb7ee0ed), + (0x68600c55), + (0x5b9e7371), + (0xe0e0939c), + (0xd31eecb8), + (0x0000a12e), + (0x33fede0a), + (0x88803ee7), + (0xbb7e41c3), + (0x6860ad7b), + (0x5b9ed25f), + (0xe0e032b2), + (0xd31e4d96)}, + {(0x00000000), + (0x08750800), + (0x82099800), + (0x8a7c9000), + (0x40e2b000), + (0x4897b800), + (0xc2eb2800), + (0xca9e2000), + (0x004a5e00), + (0x083f5600), + (0x8243c600), + (0x8a36ce00), + (0x40a8ee00), + (0x48dde600), + (0xc2a17600), + (0xcad47e00)}, + {(0x3f800000), + (0x3f843a84), + (0x3fc104cc), + (0x3fc53e48), + (0x3fa07158), + (0x3fa44bdc), + (0x3fe17594), + (0x3fe54f10), + (0x3f80252f), + (0x3f841fab), + (0x3fc121e3), + (0x3fc51b67), + (0x3fa05477), + (0x3fa46ef3), + (0x3fe150bb), + (0x3fe56a3f)}, + (0xfff80000), + {0xb0,0x71,0x91,0x64,0xda,0x74,0xb8,0xc6,0x16,0x8c, + 0x5a,0x7e,0x26,0xea,0x75,0x3a,0x0b,0xa4,0xd9,0x97,0x00} + }, + { + /* No.198 delta:1565 weight:813 */ + 11213, + 89, + 7, + 10, + {(0x00000000), + (0x98a83f1e), + (0xcb779281), + (0x53dfad9f), + (0x20400c6a), + (0xb8e83374), + (0xeb379eeb), + (0x739fa1f5), + (0x000092fc), + (0x98a8ade2), + (0xcb77007d), + (0x53df3f63), + (0x20409e96), + (0xb8e8a188), + (0xeb370c17), + (0x739f3309)}, + {(0x00000000), + (0x467a0c00), + (0x04059800), + (0x427f9400), + (0x01093800), + (0x47733400), + (0x050ca000), + (0x4376ac00), + (0xc0e0fe00), + (0x869af200), + (0xc4e56600), + (0x829f6a00), + (0xc1e9c600), + (0x8793ca00), + (0xc5ec5e00), + (0x83965200)}, + {(0x3f800000), + (0x3fa33d06), + (0x3f8202cc), + (0x3fa13fca), + (0x3f80849c), + (0x3fa3b99a), + (0x3f828650), + (0x3fa1bb56), + (0x3fe0707f), + (0x3fc34d79), + (0x3fe272b3), + (0x3fc14fb5), + (0x3fe0f4e3), + (0x3fc3c9e5), + (0x3fe2f62f), + (0x3fc1cb29)}, + (0xfff80000), + {0x32,0x19,0xd6,0x71,0xe2,0x9d,0xf7,0x99,0x34,0xa0, + 0x5f,0x9a,0xcd,0x9f,0x42,0x5a,0x43,0x47,0xee,0xb2,0x00} + }, + { + /* No.199 delta:3921 weight:921 */ + 11213, + 49, + 3, + 15, + {(0x00000000), + (0xbb75ffa8), + (0xa0b33e2a), + (0x1bc6c182), + (0x9a200c78), + (0x2155f3d0), + (0x3a933252), + (0x81e6cdfa), + (0x000015a3), + (0xbb75ea0b), + (0xa0b32b89), + (0x1bc6d421), + (0x9a2019db), + (0x2155e673), + (0x3a9327f1), + (0x81e6d859)}, + {(0x00000000), + (0x45540800), + (0x07840400), + (0x42d00c00), + (0x08200000), + (0x4d740800), + (0x0fa40400), + (0x4af00c00), + (0x02201e00), + (0x47741600), + (0x05a41a00), + (0x40f01200), + (0x0a001e00), + (0x4f541600), + (0x0d841a00), + (0x48d01200)}, + {(0x3f800000), + (0x3fa2aa04), + (0x3f83c202), + (0x3fa16806), + (0x3f841000), + (0x3fa6ba04), + (0x3f87d202), + (0x3fa57806), + (0x3f81100f), + (0x3fa3ba0b), + (0x3f82d20d), + (0x3fa07809), + (0x3f85000f), + (0x3fa7aa0b), + (0x3f86c20d), + (0x3fa46809)}, + (0xfff80000), + {0x86,0x1e,0x5b,0xa8,0x8e,0x65,0x6f,0xc0,0xbc,0x92, + 0x81,0x1c,0x6d,0xbd,0x0f,0xd4,0x7e,0x57,0x5f,0x75,0x00} + } +}; + +#endif + + diff --git a/shared/package-files/f1/f12800813b5cd1ce351d0faed45064cc3d20a73436ea51a0562fbd35a136836e/conv_relu.py b/shared/package-files/f1/f12800813b5cd1ce351d0faed45064cc3d20a73436ea51a0562fbd35a136836e/conv_relu.py new file mode 100644 index 0000000000000000000000000000000000000000..25d695859180fc5ccb9b2f53b107e438c547de4a --- /dev/null +++ b/shared/package-files/f1/f12800813b5cd1ce351d0faed45064cc3d20a73436ea51a0562fbd35a136836e/conv_relu.py @@ -0,0 +1,263 @@ +# mypy: allow-untyped-defs + +import torch +import torch.ao.nn.intrinsic +import torch.ao.nn.intrinsic.qat +import torch.ao.nn.quantized as nnq +import torch.nn.functional as F +from torch.nn.utils import fuse_conv_bn_weights + + +__all__ = [ + "ConvReLU1d", + "ConvReLU2d", + "ConvReLU3d", +] + +_reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding + + +# TODO: factor out the common parts to ConvNd +class ConvReLU1d(nnq.Conv1d): + r""" + A ConvReLU1d module is a fused module of Conv1d and ReLU + + We adopt the same interface as :class:`torch.ao.nn.quantized.Conv1d`. + + Attributes: + Same as torch.ao.nn.quantized.Conv1d + + """ + _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU1d # type: ignore[assignment] + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + super().__init__( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + bias=bias, + padding_mode=padding_mode, + device=device, + dtype=dtype, + ) + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + if self.padding_mode != "zeros": + # Padding in Conv1d is stored as (p, p), need to get (p,) + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1]) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return torch.ops.quantized.conv1d_relu( + input, self._packed_params, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedConvReLU1d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU1d: + assert mod.bn.running_var is not None and mod.bn.running_mean is not None + mod.weight, mod.bias = fuse_conv_bn_weights( + mod.weight, + mod.bias, + mod.bn.running_mean, + mod.bn.running_var, + mod.bn.eps, + mod.bn.weight, + mod.bn.bias, + ) + return super().from_float(mod, use_precomputed_fake_quant) + + @classmethod + def from_reference(cls, ref_qconv, output_scale, output_zero_point): + assert ( + type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU1d + ), "BatchNorm1d should be fused into Conv1d before converting to reference module" + return super().from_reference(ref_qconv[0], output_scale, output_zero_point) + + +class ConvReLU2d(nnq.Conv2d): + r""" + A ConvReLU2d module is a fused module of Conv2d and ReLU + + We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`. + + Attributes: + Same as torch.ao.nn.quantized.Conv2d + + """ + _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU2d # type: ignore[assignment] + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + super().__init__( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + bias=bias, + padding_mode=padding_mode, + device=device, + dtype=dtype, + ) + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + if self.padding_mode != "zeros": + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return torch.ops.quantized.conv2d_relu( + input, self._packed_params, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedConvReLU2d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU2d: + assert mod.bn.running_var is not None and mod.bn.running_mean is not None + mod.weight, mod.bias = fuse_conv_bn_weights( + mod.weight, + mod.bias, + mod.bn.running_mean, + mod.bn.running_var, + mod.bn.eps, + mod.bn.weight, + mod.bn.bias, + ) + return super().from_float( + mod, use_precomputed_fake_quant=use_precomputed_fake_quant + ) + + @classmethod + def from_reference(cls, ref_qconv, output_scale, output_zero_point): + assert ( + type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU2d + ), "BatchNorm2d should be fused into Conv2d before converting to reference module" + return super().from_reference(ref_qconv[0], output_scale, output_zero_point) + + +class ConvReLU3d(nnq.Conv3d): + r""" + A ConvReLU3d module is a fused module of Conv3d and ReLU + + We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`. + + Attributes: Same as torch.ao.nn.quantized.Conv3d + + """ + _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d # type: ignore[assignment] + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + padding_mode="zeros", + device=None, + dtype=None, + ): + assert padding_mode != "reflect", "Conv3d does not support reflection padding" + super().__init__( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + bias=bias, + padding_mode=padding_mode, + device=device, + dtype=dtype, + ) + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, D, H, W)`!") + if self.padding_mode != "zeros": + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad( + input, _reversed_padding_repeated_twice, mode=self.padding_mode + ) + return torch.ops.quantized.conv3d_relu( + input, self._packed_params, self.scale, self.zero_point + ) + + def _get_name(self): + return "QuantizedConvReLU3d" + + @classmethod + def from_float(cls, mod, use_precomputed_fake_quant=False): + if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU3d: + assert mod.bn.running_var is not None and mod.bn.running_mean is not None + mod.weight, mod.bias = fuse_conv_bn_weights( + mod.weight, + mod.bias, + mod.bn.running_mean, + mod.bn.running_var, + mod.bn.eps, + mod.bn.weight, + mod.bn.bias, + ) + return super().from_float( + mod, use_precomputed_fake_quant=use_precomputed_fake_quant + ) + + @classmethod + def from_reference(cls, ref_qconv, output_scale, output_zero_point): + assert ( + type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU3d + ), "BatchNorm3d should be fused into Conv3d before converting to reference module" + return super().from_reference(ref_qconv[0], output_scale, output_zero_point) diff --git a/shared/package-files/f1/f1296df407b5da0b1d81076ead3f63eb4553052d8b53bf147e51d39fbb8924fb/mm.cpython-311.pyc b/shared/package-files/f1/f1296df407b5da0b1d81076ead3f63eb4553052d8b53bf147e51d39fbb8924fb/mm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5d8d07248d914de6e9990abe8db29f238047a77 Binary files /dev/null and b/shared/package-files/f1/f1296df407b5da0b1d81076ead3f63eb4553052d8b53bf147e51d39fbb8924fb/mm.cpython-311.pyc differ diff --git a/shared/package-files/f1/f136c372f98b81f9657c6a264d14ad4a94f95884224c72edfab4b71b224422d5/test_digraph_historical.py b/shared/package-files/f1/f136c372f98b81f9657c6a264d14ad4a94f95884224c72edfab4b71b224422d5/test_digraph_historical.py new file mode 100644 index 0000000000000000000000000000000000000000..ff9f9e9cc4e698a70a6123452fde20069a09f0a4 --- /dev/null +++ b/shared/package-files/f1/f136c372f98b81f9657c6a264d14ad4a94f95884224c72edfab4b71b224422d5/test_digraph_historical.py @@ -0,0 +1,110 @@ +"""Original NetworkX graph tests""" + +import pytest + +import networkx as nx + +from .historical_tests import HistoricalTests + + +class TestDiGraphHistorical(HistoricalTests): + @classmethod + def setup_class(cls): + HistoricalTests.setup_class() + cls.G = nx.DiGraph + + def test_in_degree(self): + G = self.G() + G.add_nodes_from("GJK") + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) + + assert sorted(d for n, d in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2] + assert dict(G.in_degree()) == { + "A": 0, + "C": 2, + "B": 1, + "D": 2, + "G": 0, + "K": 0, + "J": 0, + } + + def test_out_degree(self): + G = self.G() + G.add_nodes_from("GJK") + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) + assert sorted(v for k, v in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2] + assert dict(G.out_degree()) == { + "A": 2, + "C": 1, + "B": 2, + "D": 0, + "G": 0, + "K": 0, + "J": 0, + } + + def test_degree_digraph(self): + H = nx.DiGraph() + H.add_edges_from([(1, 24), (1, 2)]) + assert sorted(d for n, d in H.in_degree([1, 24])) == [0, 1] + assert sorted(d for n, d in H.out_degree([1, 24])) == [0, 2] + assert sorted(d for n, d in H.degree([1, 24])) == [1, 2] + + def test_neighbors(self): + G = self.G() + G.add_nodes_from("GJK") + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) + + assert sorted(G.neighbors("C")) == ["D"] + assert sorted(G["C"]) == ["D"] + assert sorted(G.neighbors("A")) == ["B", "C"] + pytest.raises(nx.NetworkXError, G.neighbors, "j") + pytest.raises(nx.NetworkXError, G.neighbors, "j") + + def test_successors(self): + G = self.G() + G.add_nodes_from("GJK") + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) + assert sorted(G.successors("A")) == ["B", "C"] + assert sorted(G.successors("A")) == ["B", "C"] + assert sorted(G.successors("G")) == [] + assert sorted(G.successors("D")) == [] + assert sorted(G.successors("G")) == [] + pytest.raises(nx.NetworkXError, G.successors, "j") + pytest.raises(nx.NetworkXError, G.successors, "j") + + def test_predecessors(self): + G = self.G() + G.add_nodes_from("GJK") + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) + assert sorted(G.predecessors("C")) == ["A", "B"] + assert sorted(G.predecessors("C")) == ["A", "B"] + assert sorted(G.predecessors("G")) == [] + assert sorted(G.predecessors("A")) == [] + assert sorted(G.predecessors("G")) == [] + assert sorted(G.predecessors("A")) == [] + assert sorted(G.successors("D")) == [] + + pytest.raises(nx.NetworkXError, G.predecessors, "j") + pytest.raises(nx.NetworkXError, G.predecessors, "j") + + def test_reverse(self): + G = nx.complete_graph(10) + H = G.to_directed() + HR = H.reverse() + assert nx.is_isomorphic(H, HR) + assert sorted(H.edges()) == sorted(HR.edges()) + + def test_reverse2(self): + H = nx.DiGraph() + foo = [H.add_edge(u, u + 1) for u in range(5)] + HR = H.reverse() + for u in range(5): + assert HR.has_edge(u + 1, u) + + def test_reverse3(self): + H = nx.DiGraph() + H.add_nodes_from([1, 2, 3, 4]) + HR = H.reverse() + assert sorted(HR.nodes()) == [1, 2, 3, 4] diff --git a/shared/package-files/f1/f149184fae160ae46683b502141ad950ccfc28cc2076fc77ee43fef99cfa8588/beta.cpython-311.pyc b/shared/package-files/f1/f149184fae160ae46683b502141ad950ccfc28cc2076fc77ee43fef99cfa8588/beta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63d493c37dd83475549fd3565734e1dc5d5a8a27 Binary files /dev/null and b/shared/package-files/f1/f149184fae160ae46683b502141ad950ccfc28cc2076fc77ee43fef99cfa8588/beta.cpython-311.pyc differ diff --git a/shared/package-files/f1/f1524d7fbc2d860bb722a268e4d5138259d3191671ea6e49f4f3a71d8f4ef13d/compound_rv.cpython-311.pyc b/shared/package-files/f1/f1524d7fbc2d860bb722a268e4d5138259d3191671ea6e49f4f3a71d8f4ef13d/compound_rv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59b2257f30397351862d4a665d5665ed8abb60fb Binary files /dev/null and b/shared/package-files/f1/f1524d7fbc2d860bb722a268e4d5138259d3191671ea6e49f4f3a71d8f4ef13d/compound_rv.cpython-311.pyc differ diff --git a/shared/package-files/f1/f165f3d3b8b1f3932509242fc3fa0e9c5008f48381bc0c03177e9655230cb3bc/operator.h b/shared/package-files/f1/f165f3d3b8b1f3932509242fc3fa0e9c5008f48381bc0c03177e9655230cb3bc/operator.h new file mode 100644 index 0000000000000000000000000000000000000000..2e609f18ecc07489863ba59518bb4af558f9c7b7 --- /dev/null +++ b/shared/package-files/f1/f165f3d3b8b1f3932509242fc3fa0e9c5008f48381bc0c03177e9655230cb3bc/operator.h @@ -0,0 +1,345 @@ +// in memory description of all ATen Ops similar to Caffe2 schema +// once C10 exists this can be removed, or stubbed out, but we need +// it now to implement correct semantic checking for script +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct Node; +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::Symbol; + +using OperationCreator = Operation (*)(const Node*); + +namespace { +const std::array kJitOnlyOperatorTags = { + at::Tag::pt2_compliant_tag}; +} + +/* + * Note: JIT relies on Operator instances having static lifetime, because + * it for example stores a non-owning FunctionSchema* pointer in the Node class, + * which points to the function schema stored in the Operator instance. + * Also, jit::Operator is meant to store more operator related information like + * symbolic derivatives, which also requires them to have static lifetime + * so that changes to symbolic derivatives are remembered. + * + * Currently, the JIT operator library contains a jit::Operator instance + * with a wrapper for each c10 operator. The c10 operator library registers + * those wrappers using listeners in register_c10_ops.cpp. + * TODO Instead of doing it this way, we should only have pure-jit ops in + * the jit library but have the JIT operator lookup look into the c10 library + * too. + */ + +// An Operator is a thin wrapper around either a pure JIT operator (e.g. prim +// ops) or a c10 operator, allowing some common operations and abstracting away +// the concrete operator nature. +struct TORCH_API Operator { + private: + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + struct C10Operator final { + c10::OperatorHandle handle_; + Operation op_; + }; + struct UnparsedFunctionSchema final { + std::string schema_string_; + mutable std::optional alias_analysis_; + }; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + struct JitOnlyOperator final { + // The only valid transition for schema_ is from right->left, i.e. + // when the schema gets parsed. + mutable std::variant schema_; + + std::variant op_; + }; + + public: + Operator(c10::OperatorHandle opHandle, Operation operation) + : op_(C10Operator{std::move(opHandle), std::move(operation)}) {} + + Operator( + std::string schema, + Operation op, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + UnparsedFunctionSchema{std::move(schema), alias_analysis}, + Operation(std::move(op))}) {} + + Operator( + std::string name, + std::string overload_name, + std::vector arguments, + std::vector returns, + Operation op, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + FunctionSchema(varArgSchemaWithName( + std::move(name), + std::move(overload_name), + std::move(arguments), + std::move(returns), + alias_analysis)), + std::move(op)}) {} + + Operator( + std::string schema, + OperationCreator op_creator, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + UnparsedFunctionSchema{std::move(schema), alias_analysis}, + op_creator}) {} + + // Helper constructor to register `op` to run + // run for _every_ IR Node where n.kind() == name, regardless of arguments. + // This is accomplished by marking the schema varargs and having no required + // arguments. + Operator( + Symbol name, + OperationCreator op_creator, + c10::AliasAnalysisKind alias_analysis) + : op_(JitOnlyOperator{ + FunctionSchema(varArgSchemaWithName(name, alias_analysis)), + op_creator}) {} + + Operation getOperation(const Node* node = nullptr) const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) { return op.op_; }, + [node](const JitOnlyOperator& op) { + return std::visit( + c10::overloaded( + [](const Operation& op) { return op; }, + [node](const OperationCreator& op_creator) { + return op_creator(node); + }), + op.op_); + }), + op_); + } + + Operation getOperationForDispatchKey(c10::DispatchKey dk) const { + // TODO: some sort of caching mechanism? + return std::visit( + c10::overloaded( + [dk](const C10Operator& op) { + return Operation([op, dk](Stack& stack) { + op.handle_.callBoxedForDispatchKey(dk, stack); + }); + }, + [](const JitOnlyOperator& op) { + TORCH_CHECK( + false, + "calling a JIT operator for dispatch key is not supported"); + return Operation(nullptr); + }), + op_); + } + + const FunctionSchema& schema() const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) -> const FunctionSchema& { + return op.handle_.schema(); + }, + [](const JitOnlyOperator& op) -> const FunctionSchema& { + // we lazily parse schema initialized from strings so that + // we do less work during static operator registration + if (op.schema_.index() == 1) { + auto& unmaterializedSchema = + std::get(op.schema_); + FunctionSchema schema = + parseSchema(unmaterializedSchema.schema_string_); + if (unmaterializedSchema.alias_analysis_.has_value()) { + // TODO What if it gets set later? + schema.setAliasAnalysis( + *unmaterializedSchema.alias_analysis_); + } + op.schema_ = std::move(schema); + } + return std::get(op.schema_); + }), + op_); + } + + c10::ArrayRef getTags() const { + return std::visit( + c10::overloaded( + [](const C10Operator& op) { return op.handle_.getTags(); }, + [](const JitOnlyOperator& op) { + // JitOnlyOperators don't have an c10::OperatorHandle or a way to + // specify tags. We're grandfathering them all into + // pt2_compliant_tag, but for anything else, please just stop + // using JitOnlyOperator. + return c10::ArrayRef(kJitOnlyOperatorTags); + }), + op_); + } + + bool isC10Op() const { + return op_.index() == 0; + } + + c10::AliasAnalysisKind aliasAnalysisKind() const { + const FunctionSchema& schemaRef = schema(); + c10::AliasAnalysisKind alias_analysis = schemaRef.aliasAnalysis(); + + TORCH_CHECK( + alias_analysis == AliasAnalysisKind::FROM_SCHEMA || + !schemaRef.hasAnyAliasInfo(), + "In operator registration: Tried to register operator ", + schemaRef, + " with aliasing information in the schema but without AliasAnalysisKind::FROM_SCHEMA."); + return alias_analysis; + } + + bool hasOperation() const { + return std::visit( + c10::overloaded( + [](const C10Operator&) { return true; }, + [](const JitOnlyOperator& op) { return op.op_.index() == 0; }), + op_); + } + + private: + static FunctionSchema varArgSchemaWithName( + Symbol name, + AliasAnalysisKind alias_analysis) { + auto result = FunctionSchema( + name, + "", + {}, + {}, + /*is_vararg*/ true, + /*is_varret*/ true); + result.setAliasAnalysis(alias_analysis); + return result; + } + + static FunctionSchema varArgSchemaWithName( + std::string name, + std::string overload_name, + std::vector arguments, + std::vector returns, + AliasAnalysisKind alias_analysis) { + auto result = FunctionSchema( + std::move(name), + std::move(overload_name), + std::move(arguments), + std::move(returns), + /*is_vararg*/ false, + /*is_varret*/ false); + result.setAliasAnalysis(alias_analysis); + return result; + } + + std::variant op_; +}; + +TORCH_API std::string canonicalSchemaString(const FunctionSchema& schema); + +TORCH_API const std::vector> getAllOperators(); +TORCH_API const std::vector>& getAllOperatorsFor( + Symbol name); +// Returns operators in the order which OpOverloadPacket resolves them. +TORCH_API std::vector> getAllSortedOperatorsFor( + Symbol name); + +// given a operator with an overload name, find the specific operator related to +// it, may return nullptr if no operator exists. +TORCH_API std::shared_ptr findOperatorFor( + const c10::OperatorName& full_name); + +TORCH_API std::vector findSimilarOperators(Symbol input_op); + +TORCH_API void registerOperator(Operator&& op); +TORCH_API void deregisterOperator(const FunctionSchema& schema); + +// XXX: this function is meant to be used with string literals only! +TORCH_API std::shared_ptr getOperatorForLiteral( + const char* signature); + +// Ensure the thing that registers c10 ops is defined. +// Otherwise, our registry will not have c10 ops. You can run into this +// scenario if you're querying registered ops during static init. +// +// This fn is defined in register_c10_ops.cpp +TORCH_API void ensure_c10_registerer_defined(); + +// Used to assert that unschematized operators have an analysis method written +TORCH_API bool aliasAnalysisHasSpecialCaseFor(c10::Symbol sym); + +// A factory function to generate an optional operator. It has two +// instantiations depending on the template bool arg value. The arg can be a +// compile-time function for the selective op registration based on schema +// string. +template +std::optional OperatorGenerator( + const char* schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::optional(Operator( + std::string(schema_str), std::forward(op), alias_analysis)); +} + +template +std::optional OperatorGenerator( + torch::detail::SelectiveStr schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return OperatorGenerator( + static_cast(schema_str), + std::forward(op), + alias_analysis); +} + +template +std::optional OperatorGenerator( + torch::detail::SelectiveStr schema_str, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::nullopt; +} + +template +std::optional OperatorGenerator( + const std::string name, + const std::string overload_name, + const std::vector arguments, + const std::vector returns, + Func&& op, + AliasAnalysisKind alias_analysis) { + return std::optional(Operator( + name, + overload_name, + arguments, + returns, + std::forward(op), + alias_analysis)); +} + +} // namespace torch::jit diff --git a/shared/package-files/f1/f172a4be81b0d876941e84cb6215b2d9c4bcada2c57abda2bee2a0eef8926ef7/function_schema.h b/shared/package-files/f1/f172a4be81b0d876941e84cb6215b2d9c4bcada2c57abda2bee2a0eef8926ef7/function_schema.h new file mode 100644 index 0000000000000000000000000000000000000000..c3e1520dc9868a7d7849169b895fc786a1f7d55b --- /dev/null +++ b/shared/package-files/f1/f172a4be81b0d876941e84cb6215b2d9c4bcada2c57abda2bee2a0eef8926ef7/function_schema.h @@ -0,0 +1,690 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +// schema as used in the compiler for resolving function calls and reporting +// errors. These objects should be constructed from C10 schema once those +// are available. + +struct Argument; +struct FunctionSchema; + +using AliasTypeSet = std::vector; + +bool operator==(const Argument& lhs, const Argument& rhs); + +struct TORCH_API Argument { + Argument( + std::string name = "", + const TypePtr& type = nullptr, + std::optional N = std::nullopt, + std::optional default_value = std::nullopt, + bool kwarg_only = false, + std::optional alias_info = std::nullopt) + : Argument(std::move(name), type, type, N, std::move(default_value), kwarg_only, std::move(alias_info)) {} + + Argument( + std::string name, + TypePtr fake_type, + TypePtr real_type, + std::optional N = std::nullopt, + std::optional default_value = std::nullopt, + bool kwarg_only = false, + std::optional alias_info = std::nullopt) + : name_(std::move(name)), + type_(fake_type ? std::move(fake_type) : TensorType::get()), + real_type_(real_type ? std::move(real_type) : type_), + N_(N), + default_value_(std::move(default_value)), + alias_info_(alias_info ? std::make_unique(std::move(*alias_info)) : nullptr), + kwarg_only_(kwarg_only) { + // this is an softly-enforced invariant for out arguments. + bool is_alias = alias_info_ != nullptr && alias_info_->isWrite(); + is_out_ = kwarg_only_ && is_alias; + } + + Argument(Argument&& rhs) noexcept = default; + + Argument(const Argument& rhs) + : name_(rhs.name_), + type_(rhs.type_), + real_type_(rhs.real_type_), + N_(rhs.N_), + default_value_(rhs.default_value_), + alias_info_(rhs.alias_info_ ? std::make_unique(*rhs.alias_info_) : nullptr), + kwarg_only_(rhs.kwarg_only_), + is_out_(rhs.is_out_) {} + + Argument& operator=(Argument&& rhs) = default; + + Argument& operator=(const Argument& rhs) { + if (this != &rhs) { + name_ = rhs.name_; + type_ = rhs.type_; + real_type_ = rhs.real_type_; + N_ = rhs.N_; + default_value_ = rhs.default_value_; + alias_info_ = rhs.alias_info_ ? std::make_unique(*rhs.alias_info_) : nullptr; + kwarg_only_ = rhs.kwarg_only_; + is_out_ = rhs.is_out_; + } + return *this; + } + ~Argument() = default; + + const std::string& name() const { + return name_; + } + const TypePtr& type() const { + return type_; + } + // if type() is non-null, this is guaranteed to be non-null (if no real + // type was provided, this takes on type()'s value) + const TypePtr& real_type() const { + return real_type_; + } + const std::optional& N() const { + return N_; + } + const std::optional& default_value() const { + return default_value_; + } + bool kwarg_only() const { + return kwarg_only_; + } + + bool is_out() const { + return is_out_; + } + + [[nodiscard]] const AliasInfo* alias_info() const { + return alias_info_.get(); + } + + bool is_inferred_type() const { + bool is_inferred_type = false; + TORCH_INTERNAL_ASSERT(type_); + if (auto pt = type_->cast()) { + if (pt->isInferredType()) { + is_inferred_type = true; + } + } + return is_inferred_type; + } + + std::string formatTypeMismatchMsg(const std::string& actual_type) const { + std::string inferred_type_hint; + if (is_inferred_type()) { + inferred_type_hint = c10::str( + "Inferred '", + name(), + "' to be of type 'Tensor' ", + "because it was not annotated with an explicit type.\n"); + } + return c10::str( + "Expected a value of type '", + type()->repr_str(), + "' for argument '", + name(), + "' but instead found type '", + actual_type, + "'.\n", + inferred_type_hint); + } + + Argument cloneWithType(const TypePtr& new_type) const { + return Argument( + name_, + new_type, + N_, + default_value_, + kwarg_only_, + alias_info_ ? std::optional(*alias_info_) : std::nullopt); + } + + // this function checks whether this Argument is backward compatible with + // the old one. we consider the following cases are backward compatible: + // 1) two arguments are equal + // 2) this arg's type should be subtype of old + // 3) this arg must provide the same default value if old arg has one, + bool isBackwardCompatibleWith( + const Argument& old, + std::ostream* why_not=nullptr) const; + + // this function checks whether this Argument is forward compatible with + // the old one. we consider the following cases are forward compatible: + // 1) two arguments are equal + // 2) this arg's type should be subtype of old + // 3) this arg must provide the same default value if old arg has one, + bool isForwardCompatibleWith( + const Argument& old, + std::ostream* why_not = nullptr) const; + + private: + std::string name_; + TypePtr type_; + TypePtr real_type_; // this is ScalarType, not int, e.g. + // for list types, an optional statically known length for the list + // e.g. for int[3]: type = ListType::ofInts(), N = 3 + // If present, this will allow scalars to be broadcast to this length to + // become a list. + std::optional N_; + + std::optional default_value_; + // AliasInfo is huge, so let's only allocate memory for it if + // necessary (which it isn't during schema parsing on startup, to + // give a pertinent example). + std::unique_ptr alias_info_; + // is this only specifiable as a keyword argument? + bool kwarg_only_; + // marks if the argument is out variant of the schema + bool is_out_; +}; + +inline bool operator==(const Argument& lhs, const Argument& rhs) { + return lhs.name() == rhs.name() + && *lhs.type() == *rhs.type() + && lhs.N() == rhs.N() + && lhs.default_value() == rhs.default_value() + && lhs.kwarg_only() == rhs.kwarg_only() + && (lhs.alias_info() == rhs.alias_info() + || (lhs.alias_info() != nullptr && rhs.alias_info() != nullptr + && *lhs.alias_info() == *rhs.alias_info())); +} + +inline bool operator!=(const Argument& lhs, const Argument& rhs) { + return !(lhs == rhs); +} + +enum struct TORCH_API SchemaArgType { input, output }; + +/** + * struct SchemaArgument + * + * Structure used to represent arguments or returns for a schema. + */ +struct TORCH_API SchemaArgument { + SchemaArgType type; + size_t index; + SchemaArgument(SchemaArgType tpe, size_t idx) : type(tpe), index(idx) {} + bool operator==(const SchemaArgument& rhs) const { + return type == rhs.type && index == rhs.index; + } +}; + +bool operator==(const FunctionSchema& lhs, const FunctionSchema& rhs); + +struct TORCH_API FunctionSchema { + FunctionSchema( + std::string name, + std::string overload_name, + std::vector arguments, + std::vector returns, + bool is_vararg = false, + bool is_varret = false) + : name_({std::move(name), std::move(overload_name)}), + arguments_(std::move(arguments)), + returns_(std::move(returns)), + is_vararg_(is_vararg), + is_varret_(is_varret) { + checkSchema(); + } + + FunctionSchema( + Symbol name, + std::string overload_name, + std::vector arguments, + std::vector returns, + bool is_vararg = false, + bool is_varret = false) + : FunctionSchema( + name.toQualString(), + std::move(overload_name), + std::move(arguments), + std::move(returns), + is_vararg, + is_varret) { + checkSchema(); + } + + // Checks whether this schema is backward compatible with the old one. + // The following conditions must be true: + // [Function structure] The new schema's name, overload-name, varargs, and + // return arity are the same. + // [Output Narrowing] The new schema's output type must be the same class + // or inherit from the old schema's output type. + // [Argument count] The new schema must have at least as many arguments as + // the old schema (considering the list of positional and kwargs). + // [Arg Compatibility] Every argument in the old schema has a corresponding + // argument in the new schema that: + // * is at the same position. + // * has the same name. + // * is either positional, or kwarg and the old argument was kwarg. + // * has the same type, or the old argument's type inherits from the + // new argument's type. + // [Default Values] Every new argument must have a default value. + // E.g. + // OK f_new(a, b, c=1) => f_old(a, b) + // NOK f_new(a, c=1, *, b) => f_old(a, *, b) + // OK f_new(a, b, *, c) => f_old(a, *, b, c) + // NOK f_new(a, *, b, c) -> f_old(a, b, *, c) + // NOK f_new(a, *, c, b) => f_old(a, *, b, c) + // OK f_new(a, *, b, c, d=1) => f_old(a, *, b, c) + bool isBackwardCompatibleWith( + const FunctionSchema& old, + std::ostream* why_not = nullptr) const; + + // Checks whether this schema is forward compatible with the old one. + // The following conditions must be true: + // [Function structure] The new schema's name, overload-name, varargs, and + // return arity are the same. + // [Output Narrowing] The new schema's output type must be the same class + // or inherit from the old schema's output type. + // [Arg Compatibility] Every argument in the old schema has a corresponding + // argument in the new schema that: + // * is at the same position. + // * has the same name. + // * is either positional, or kwarg and the old argument was kwarg. + // * has the same type, or the old argument's type inherits from the + // new argument's type. + // [Default Values] Every new argument must have a default value. + // Each default value type should NOT be a container type. + // [Positioning] All defaults arguments MUST go after either old + // default arguments or the end of positional arguments + // and right BEFORE all out arguments + bool isForwardCompatibleWith( + const FunctionSchema& old, + std::ostringstream& why_not) const; + + private: + OperatorName name_; + std::vector arguments_; + std::vector returns_; + // if true then this schema takes an arbitrary number of additional arguments + // after the argument specified in arguments + // currently this is used primarily to represent 'primitive' operators whose + // arguments are not checked by schema + bool is_vararg_; + bool is_varret_; + + // if no alias information is directly specified, what kind of "default" + // alias information should we infer? + // NB: due to alias analysis kind merging, this may be nullopt. Eventually + // this should always be set no matter what + std::optional alias_kind_; + + template + void checkArg(const IValue& value, const Argument& argument, std::optional pos) const; + + void checkSchema() const { + bool seen_default_arg = false; + for (const auto& arg : arguments()) { + if (arg.default_value()) { + seen_default_arg = true; + } else { + // we have historically serialized broadcasting lists wo/default values, + // so to not break BC allow lists here + if (arg.type()->kind() == ListType::Kind) { + continue; + } + TORCH_INTERNAL_ASSERT( + !seen_default_arg || arg.kwarg_only(), + "Non-default positional argument follows default argument. Parameter ", + arg.name(), + " in ", + *this); + } + } + } + + public: + + void dump() const; + + const OperatorName& operator_name() const { + return name_; + } + const std::string& name() const { + return name_.name; + } + const std::string& overload_name() const { + return name_.overload_name; + } + const std::vector& arguments() const { + return arguments_; + } + const std::vector& returns() const { + return returns_; + } + bool is_vararg() const { + return is_vararg_; + } + bool is_varret() const { + return is_varret_; + } + bool is_aliasing(const c10::SchemaArgument &argument) const { + TORCH_INTERNAL_ASSERT( + argument.index < getCorrectList(argument.type).size(), + "Invalid index for schema."); + const AliasInfo* aliasInfo = getCorrectList(argument.type)[argument.index].alias_info(); + return aliasInfo; + } + bool is_mutable() const { + return std::any_of( + arguments_.cbegin(), arguments_.cend(), [](const Argument& arg) { + const AliasInfo* aliasInfo = arg.alias_info(); + return aliasInfo && aliasInfo->isWrite(); + }); + } + bool is_mutable(const c10::SchemaArgument &argument) const { + TORCH_INTERNAL_ASSERT( + argument.index < getCorrectList(argument.type).size(), + "Invalid index for schema."); + const AliasInfo* aliasInfo = getCorrectList(argument.type)[argument.index].alias_info(); + return aliasInfo && aliasInfo->isWrite(); + } + bool is_mutable(std::string_view name) const { + std::optional index = argumentIndexWithName(name); + TORCH_INTERNAL_ASSERT( + index.has_value(), "Schema has no argument named ", name); + + return is_mutable({c10::SchemaArgType::input, static_cast(*index)}); + } + + // Returns whether lhs and rhs may alias directly. + // This does not account for cases where lhs or rhs are a container that + // may contain elements that alias the other argument. + // FunctionSchema::may_contain_alias will include that functionality. + bool may_alias(const SchemaArgument& lhs, const SchemaArgument& rhs) const; + + // Returns whether lhs and rhs may alias directly or whether lhs/rhs are a container + // that may contain elements that alias the other argument. + // bidirectional = false only returns whether lhs may contain an alias of rhs + // while bidirectional = true returns both directions. + bool may_contain_alias(const SchemaArgument& lhs, const SchemaArgument& rhs, bool bidirectional = true) const; + + // Returns whether the two AliasTypeSets contain any similarities + // ie: whether the two type sets can alias. + bool canAliasTypeSetsAlias(const std::optional &lhs, const std::optional &rhs) const; + + // Recursively Finds all contained types within the AliasTypeSet. + std::optional getAliasTypeSetContainedTypes(const std::optional &aliasTypeSet) const; + + // Similar to mapTypeToAliasTypeSet defined in alias_analysis.cpp. + // Used to map types to a type such that all types that can alias will be mapped to the same type. + // For example, calling this method on 'Optional[List[int]]' is the same as calling this method + // on 'List[int]'. + std::optional mapTypeToAliasTypeSet(const TypePtr& type) const; + + // Returns either arguments() or returns() depending on the SchemaArgType + // output => returns(), input => arguments() + const std::vector& getCorrectList(SchemaArgType type) const; + + std::optional argumentIndexWithName(std::string_view name) const { + for (const auto i : c10::irange(arguments().size())) { + if(name == arguments()[i].name()) + return i; + } + return std::nullopt; + } + FunctionSchema cloneWithName(std::string name, std::string overload_name) const { + return FunctionSchema( + std::move(name), + std::move(overload_name), + arguments(), + returns(), + is_vararg(), + is_varret() + ); + } + FunctionSchema cloneWithArguments(std::vector new_arguments) const { + return FunctionSchema( + name(), + overload_name(), + std::move(new_arguments), + returns(), + is_vararg(), + is_varret()); + } + FunctionSchema cloneWithReturns(std::vector new_returns) const { + return FunctionSchema( + name(), + overload_name(), + arguments(), + std::move(new_returns), + is_vararg(), + is_varret()); + } + + std::string formatTypeMismatchMsg( + const Argument& expected, + const std::string& actual_type, + std::optional position = std::nullopt, + std::optional value = std::nullopt) const; + + FunctionSchema cloneWithRemappedTypes( + const std::function type_map) const; + + FunctionSchema cloneWithRealTypes(bool with_symint=true) const; + + // Check that inputs have the correct types and appends any missing default + // values. + template + void checkAndNormalizeInputs( + std::vector& inputs, + const std::unordered_map& kwargs = + std::unordered_map{}) const; + + std::string findErrorInKwargs(const std::vector& kwargs) const; + + bool hasAnyAliasInfo() const { + for (const auto& arg : arguments_) { + if (arg.alias_info() != nullptr) { + return true; + } + } + for (const auto& ret : returns_) { + if (ret.alias_info() != nullptr) { + return true; + } + } + return false; + } + + + // TODO remove the mutation here + bool isDefaultAliasAnalysisKind() const { + return !alias_kind_; + } + AliasAnalysisKind aliasAnalysis() const { + return alias_kind_.value_or(AliasAnalysisKind::CONSERVATIVE); + } + void setAliasAnalysis(AliasAnalysisKind v) { + alias_kind_ = v; + } + + std::optional getNamespace() const { + return name_.getNamespace(); + } + + // Returns true if we successfully set the namespace (as there + // was none set, and false otherwise) + bool setNamespaceIfNotSet(const char* ns) { + return name_.setNamespaceIfNotSet(ns); + } + + // can a function with this schema be substituted for a function of rhs's + // schema and have the program typecheck? + // as_method - if true, treat this schema as a method and ignore + // the first argument, which will be the object in both cases + bool isSubtypeOf(const FunctionSchema& rhs, bool as_method, std::ostream* why_not=nullptr) const; +}; + +inline bool operator==(const FunctionSchema& lhs, const FunctionSchema& rhs) { + return lhs.name() == rhs.name() + && lhs.overload_name() == rhs.overload_name() + && lhs.arguments() == rhs.arguments() + && lhs.returns() == rhs.returns() + && lhs.is_vararg() == rhs.is_vararg() + && lhs.is_varret() == rhs.is_varret(); +} + +inline bool operator!=(const FunctionSchema& lhs, const FunctionSchema& rhs) { + return !(lhs == rhs); +} + +// print out Argument, which is compatible with FunctionSchema parser +// full format: Type(alias)? name=default_value +inline std::ostream& operator<<(std::ostream& out, const Argument& arg) { + + // for adjusting the ? position. + // in schema, we have Tensor?(a!) input, and t(a!)?. + // however, t?(a!) doesn't work with schema parser. + // so we always use Type(alias)? format + // real_type versus fake_type: in order to be compatible with FunctionSchema + // parser, printing an argument with either MemoryFormat or Layout type should + // give us the original schema string, hence printing out real_type. + auto type = arg.real_type(); + bool is_opt = type->kind() == OptionalType::Kind; + auto unopt_type = is_opt ? type->castRaw()->getElementType() : type; + + if (unopt_type->kind() == ListType::Kind) { + // sized lists get size N from arg, not type + auto list = unopt_type->cast(); + out << list->getElementType()->str(); + if (arg.alias_info() && !arg.alias_info()->containedTypes().empty()){ + out << arg.alias_info()->containedTypes()[0]; + } + std::string N; + if (arg.N()) { + N = std::to_string(*arg.N()); + } + out << "[" << N << "]"; + } else { + out << unopt_type->str(); + } + + // print alias info if it has beforeSets. + if (arg.alias_info() && !arg.alias_info()->beforeSets().empty()) { + out << *arg.alias_info(); + } + + if (is_opt) { + out << "?"; + } + + if (!arg.name().empty()) { + out << " " << arg.name(); + } + + if (arg.default_value()) { + out << "="; + if ((type->kind() == c10::TypeKind::StringType || + unopt_type->kind() == c10::TypeKind::StringType) && + arg.default_value().value().isString()) { + printQuotedString(out, arg.default_value().value().toStringRef()); + } else if (type->kind() == TypeKind::ListType && type->castRaw()->getElementType()->kind() == c10::TypeKind::IntType) { + // We want to faithfully replicate JIT schema. + // in native_functions.yaml defaults for int arrays with a single value always look like + // int[2] stride=1 + // instead of + // int[2] stride=[1, 1] + auto default_val = arg.default_value().value().toIntList(); + if (default_val.size() > 1) { + auto all_defaults_the_same = true; + for (const auto i : c10::irange(1, default_val.size())) { + if (default_val[0] != default_val[i]) all_defaults_the_same = false; + } + if (all_defaults_the_same) { + out << default_val[0]; + } else { + out << arg.default_value().value(); + } + } else { + out << arg.default_value().value(); + } + } else { + out << arg.default_value().value(); + } + } + + return out; +} + +TORCH_API std::ostream& operator<<(std::ostream& out, const FunctionSchema& schema); + +inline std::string toString(const FunctionSchema& schema) { + std::ostringstream str; + str << schema; + return str.str(); +} + +} // namespace c10 + +namespace std { +template<> + struct hash { + size_t operator()(const c10::SchemaArgument& arg) const + { + return c10::hash_combine(std::hash()(arg.index), std::hash()(static_cast(arg.type))); + } + }; +template<> + struct hash { + size_t operator()(const c10::Argument& arg) const + { + auto hash = std::hash{}(arg.name()); + auto type_hash = std::hash{}(arg.type()); + auto kwarg_only_hash = std::hash{}(arg.kwarg_only()); + hash = c10::hash_combine(hash, type_hash); + hash = c10::hash_combine(hash, kwarg_only_hash); + // hashing optional fields if they exist + if (arg.default_value().has_value()) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto default_value_hash = c10::hash{}(*arg.default_value()); + hash = c10::hash_combine(hash, default_value_hash); + } + if (arg.N().has_value()) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto N_hash = std::hash{}(*arg.N()); + hash = c10::hash_combine(hash, N_hash); + } + if (arg.alias_info()) { + auto alias_info_hash = std::hash{}(*arg.alias_info()); + hash = c10::hash_combine(hash, alias_info_hash); + } + return hash; + } + }; +template<> + struct hash { + size_t operator()(const c10::FunctionSchema& schema) const + { + auto hash = std::hash{}(schema.operator_name()); + auto args_hash = c10::hash>{}(schema.arguments()); + auto returns_hash = c10::hash>{}(schema.returns()); + auto is_vararg_hash = std::hash{}(schema.is_vararg()); + auto is_varret_hash = std::hash{}(schema.is_varret()); + hash = c10::hash_combine(hash, args_hash); + hash = c10::hash_combine(hash, returns_hash); + hash = c10::hash_combine(hash, is_vararg_hash); + hash = c10::hash_combine(hash, is_varret_hash); + return hash; + } + }; +} // namespace std + + +#include // IWYU pragma: keep diff --git a/shared/package-files/f1/f17b91f78cb1ec19eec7937ebec69488e32ec09ebdc1f286ce39ae9482f0cc64/common_dist_composable.cpython-311.pyc b/shared/package-files/f1/f17b91f78cb1ec19eec7937ebec69488e32ec09ebdc1f286ce39ae9482f0cc64/common_dist_composable.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcad93193ef926ec7dc69c2ddbfc5d64c41bcec1 Binary files /dev/null and b/shared/package-files/f1/f17b91f78cb1ec19eec7937ebec69488e32ec09ebdc1f286ce39ae9482f0cc64/common_dist_composable.cpython-311.pyc differ diff --git a/shared/package-files/f1/f18fb19cd822f7991e55883c161cd0a562a9b2577626ed35ec7f214d44783a3d/__init__.cpython-311.pyc b/shared/package-files/f1/f18fb19cd822f7991e55883c161cd0a562a9b2577626ed35ec7f214d44783a3d/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..802f5aa94721a10d97717f7bf7abd515088beeea Binary files /dev/null and b/shared/package-files/f1/f18fb19cd822f7991e55883c161cd0a562a9b2577626ed35ec7f214d44783a3d/__init__.cpython-311.pyc differ diff --git a/shared/package-files/f1/f19ee056b18165cc6735efab0b4ca3508be9405b9646c38113316c15e8278a6f/dylib.py b/shared/package-files/f1/f19ee056b18165cc6735efab0b4ca3508be9405b9646c38113316c15e8278a6f/dylib.py new file mode 100644 index 0000000000000000000000000000000000000000..0ad4cba8da3521756942a18942bd11aaaad95a58 --- /dev/null +++ b/shared/package-files/f1/f19ee056b18165cc6735efab0b4ca3508be9405b9646c38113316c15e8278a6f/dylib.py @@ -0,0 +1,42 @@ +""" +Generic dylib path manipulation +""" + +import re + +__all__ = ['dylib_info'] + +DYLIB_RE = re.compile(r"""(?x) +(?P^.*)(?:^|/) +(?P + (?P\w+?) + (?:\.(?P[^._]+))? + (?:_(?P[^._]+))? + \.dylib$ +) +""") + +def dylib_info(filename): + """ + A dylib name can take one of the following four forms: + Location/Name.SomeVersion_Suffix.dylib + Location/Name.SomeVersion.dylib + Location/Name_Suffix.dylib + Location/Name.dylib + + returns None if not found or a mapping equivalent to: + dict( + location='Location', + name='Name.SomeVersion_Suffix.dylib', + shortname='Name', + version='SomeVersion', + suffix='Suffix', + ) + + Note that SomeVersion and Suffix are optional and may be None + if not present. + """ + is_dylib = DYLIB_RE.match(filename) + if not is_dylib: + return None + return is_dylib.groupdict() diff --git a/shared/package-files/f1/f1a02ab08eb430e0c6be32e83cf7036314cb6035c96e5d166f1ef286146fcf8b/infinitely_differentiable_gelu_backward_ops.h b/shared/package-files/f1/f1a02ab08eb430e0c6be32e83cf7036314cb6035c96e5d166f1ef286146fcf8b/infinitely_differentiable_gelu_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c3cc3313eaa21a31b79054c17b90f8753b4bb56e --- /dev/null +++ b/shared/package-files/f1/f1a02ab08eb430e0c6be32e83cf7036314cb6035c96e5d166f1ef286146fcf8b/infinitely_differentiable_gelu_backward_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API infinitely_differentiable_gelu_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::infinitely_differentiable_gelu_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "infinitely_differentiable_gelu_backward(Tensor grad, Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & grad, const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/f1/f1a3796647fca0cd6ecdbe2b3b5c770e5bf18558b5e2162160b17722eaaa1ac9/nll_loss_native.h b/shared/package-files/f1/f1a3796647fca0cd6ecdbe2b3b5c770e5bf18558b5e2162160b17722eaaa1ac9/nll_loss_native.h new file mode 100644 index 0000000000000000000000000000000000000000..3bd0e7dcefd0d211ffdd142765f649fe5c0dad1f --- /dev/null +++ b/shared/package-files/f1/f1a3796647fca0cd6ecdbe2b3b5c770e5bf18558b5e2162160b17722eaaa1ac9/nll_loss_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor nll_loss_symint(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100); +TORCH_API at::Tensor & nll_loss_out(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/f1/f1a925e584b3ace31b2e51f28148bcbaef4306774451227f36693469d46a0be0/__init__.cpython-311.pyc b/shared/package-files/f1/f1a925e584b3ace31b2e51f28148bcbaef4306774451227f36693469d46a0be0/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9afda27d8ca6b31931f5f7ed43eb4cbe5bbaba47 Binary files /dev/null and b/shared/package-files/f1/f1a925e584b3ace31b2e51f28148bcbaef4306774451227f36693469d46a0be0/__init__.cpython-311.pyc differ diff --git a/shared/package-files/f1/f1b827c46232f4325e5fd74887a8933eaae518342a780124996bdf84b7439cfe/__init__.py b/shared/package-files/f1/f1b827c46232f4325e5fd74887a8933eaae518342a780124996bdf84b7439cfe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de042277c7c8fd67084cdf70026c1779755a164e --- /dev/null +++ b/shared/package-files/f1/f1b827c46232f4325e5fd74887a8933eaae518342a780124996bdf84b7439cfe/__init__.py @@ -0,0 +1,5 @@ +from torch._C import FileCheck as FileCheck + +from . import _utils +from ._comparison import assert_allclose, assert_close as assert_close +from ._creation import make_tensor as make_tensor diff --git a/shared/package-files/f1/f1ca94e7c57b2a514970b679cb09532b10c23e71ffd4dc7a3b43262899e52721/ns_types.cpython-311.pyc b/shared/package-files/f1/f1ca94e7c57b2a514970b679cb09532b10c23e71ffd4dc7a3b43262899e52721/ns_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2127ea48e8cfcbc68ed6c92b871bd0fdaeaf4a1d Binary files /dev/null and b/shared/package-files/f1/f1ca94e7c57b2a514970b679cb09532b10c23e71ffd4dc7a3b43262899e52721/ns_types.cpython-311.pyc differ diff --git a/shared/package-files/f1/f1cb0f28143ecb1506dc5c5d88194d97e931c8f0804e6856884e6d4bd2f314ea/functional_adadelta.py b/shared/package-files/f1/f1cb0f28143ecb1506dc5c5d88194d97e931c8f0804e6856884e6d4bd2f314ea/functional_adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..9af7bba4680dc668dcee8a7330a0447511fcf209 --- /dev/null +++ b/shared/package-files/f1/f1cb0f28143ecb1506dc5c5d88194d97e931c8f0804e6856884e6d4bd2f314ea/functional_adadelta.py @@ -0,0 +1,111 @@ +# mypy: allow-untyped-defs +from typing import Optional + +import torch +import torch.optim._functional as F +from torch import Tensor +from torch.distributed.optim._deprecation_warning import ( + _scripted_functional_optimizer_deprecation_warning, +) + + +__all__: list[str] = [] + + +# Define a TorchScript compatible Functional Adadelta Optimizer +# where we use these optimizer in a functional way. +# Instead of using the `param.grad` when updating parameters, +# we explicitly allow the distributed optimizer pass gradients to +# the `step` function. In this way, we could separate the gradients +# and parameters and allow multithreaded trainer to update the +# parameters without data traces on accumulating to the same .grad. +# NOTE: This should be only used by distributed optimizer internals +# and not meant to expose to the user. +@torch.jit.script +class _FunctionalAdadelta: + def __init__( + self, + params: list[Tensor], + lr: float = 1.0, + rho: float = 0.9, + eps: float = 1e-6, + weight_decay: float = 0.0, + foreach: bool = False, + maximize: bool = False, + _allow_empty_param_list: bool = False, + ): + _scripted_functional_optimizer_deprecation_warning(stacklevel=2) + self.defaults = { + "lr": lr, + "rho": rho, + "eps": eps, + "weight_decay": weight_decay, + } + self.foreach = foreach + self.maximize = maximize + + if len(params) == 0 and not _allow_empty_param_list: + raise ValueError("optimizer got an empty parameter list") + + # NOTE: we only have one param_group and don't allow user to add additional + # param group as it's not a common use case. + self.param_group = {"params": params} + + self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {}) + + def step(self, gradients: list[Optional[Tensor]]): + params = self.param_group["params"] + params_with_grad = [] + grads = [] + square_avgs = [] + acc_deltas = [] + state_steps = [] + lr = self.defaults["lr"] + rho = self.defaults["rho"] + eps = self.defaults["eps"] + weight_decay = self.defaults["weight_decay"] + + if len(params) != len(gradients): + raise ValueError( + "the gradients passed in does not equal to the size of the parameters!" + + f"Params length: {len(params)}. " + + f"Gradients length: {len(gradients)}" + ) + has_complex = False + for param, gradient in zip(params, gradients): + if gradient is not None: + has_complex |= torch.is_complex(param) + params_with_grad.append(param) + grads.append(gradient) + # Lazy state initialization + if param not in self.state: + self.state[param] = {} + state = self.state[param] + state["step"] = torch.tensor(0.0) + state["square_avg"] = torch.zeros_like( + param, memory_format=torch.preserve_format + ) + state["acc_delta"] = torch.zeros_like( + param, memory_format=torch.preserve_format + ) + + state = self.state[param] + square_avgs.append(state["square_avg"]) + acc_deltas.append(state["acc_delta"]) + state_steps.append(state["step"]) + + with torch.no_grad(): + F.adadelta( + params_with_grad, + grads, + square_avgs, + acc_deltas, + state_steps, + lr=lr, + rho=rho, + eps=eps, + weight_decay=weight_decay, + foreach=self.foreach, + maximize=self.maximize, + has_complex=has_complex, + ) diff --git a/shared/package-files/f1/f1e8b3129f5abc31d57e8708fd818d888d2e1e90f6b6b4ebf879c6cd060f3f42/__init__.py b/shared/package-files/f1/f1e8b3129f5abc31d57e8708fd818d888d2e1e90f6b6b4ebf879c6cd060f3f42/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d00a731324c92d51f0c421dbd64328904dce6dac --- /dev/null +++ b/shared/package-files/f1/f1e8b3129f5abc31d57e8708fd818d888d2e1e90f6b6b4ebf879c6cd060f3f42/__init__.py @@ -0,0 +1,437 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# flake8: noqa + +""" +PyArrow is the python implementation of Apache Arrow. + +Apache Arrow is a cross-language development platform for in-memory data. +It specifies a standardized language-independent columnar memory format for +flat and hierarchical data, organized for efficient analytic operations on +modern hardware. It also provides computational libraries and zero-copy +streaming messaging and interprocess communication. + +For more information see the official page at https://arrow.apache.org +""" + +import gc as _gc +import importlib as _importlib +import os as _os +import platform as _platform +import sys as _sys +import warnings as _warnings + +try: + from ._generated_version import version as __version__ +except ImportError: + # Package is not installed, parse git tag at runtime + try: + import setuptools_scm + # Code duplicated from setup.py to avoid a dependency on each other + + def parse_git(root, **kwargs): + """ + Parse function for setuptools_scm that ignores tags for non-C++ + subprojects, e.g. apache-arrow-js-XXX tags. + """ + from setuptools_scm.git import parse + kwargs['describe_command'] = \ + "git describe --dirty --tags --long --match 'apache-arrow-[0-9]*.*'" + return parse(root, **kwargs) + __version__ = setuptools_scm.get_version('../', + parse=parse_git) + except ImportError: + __version__ = None + +# ARROW-8684: Disable GC while initializing Cython extension module, +# to workaround Cython bug in https://github.com/cython/cython/issues/3603 +_gc_enabled = _gc.isenabled() +_gc.disable() +import pyarrow.lib as _lib +if _gc_enabled: + _gc.enable() + +from pyarrow.lib import (BuildInfo, RuntimeInfo, set_timezone_db_path, + MonthDayNano, VersionInfo, cpp_build_info, + cpp_version, cpp_version_info, runtime_info, + cpu_count, set_cpu_count, enable_signal_handlers, + io_thread_count, set_io_thread_count) + + +def show_versions(): + """ + Print various version information, to help with error reporting. + """ + def print_entry(label, value): + print(f"{label: <26}: {value: <8}") + + print("pyarrow version info\n--------------------") + print_entry("Package kind", cpp_build_info.package_kind + if len(cpp_build_info.package_kind) > 0 + else "not indicated") + print_entry("Arrow C++ library version", cpp_build_info.version) + print_entry("Arrow C++ compiler", + f"{cpp_build_info.compiler_id} {cpp_build_info.compiler_version}") + print_entry("Arrow C++ compiler flags", cpp_build_info.compiler_flags) + print_entry("Arrow C++ git revision", cpp_build_info.git_id) + print_entry("Arrow C++ git description", cpp_build_info.git_description) + print_entry("Arrow C++ build type", cpp_build_info.build_type) + + +def _module_is_available(module): + try: + _importlib.import_module(f'pyarrow.{module}') + except ImportError: + return False + else: + return True + + +def _filesystem_is_available(fs): + try: + import pyarrow.fs + except ImportError: + return False + + try: + getattr(pyarrow.fs, fs) + except (ImportError, AttributeError): + return False + else: + return True + + +def show_info(): + """ + Print detailed version and platform information, for error reporting + """ + show_versions() + + def print_entry(label, value): + print(f" {label: <20}: {value: <8}") + + print("\nPlatform:") + print_entry("OS / Arch", f"{_platform.system()} {_platform.machine()}") + print_entry("SIMD Level", runtime_info().simd_level) + print_entry("Detected SIMD Level", runtime_info().detected_simd_level) + + pool = default_memory_pool() + print("\nMemory:") + print_entry("Default backend", pool.backend_name) + print_entry("Bytes allocated", f"{pool.bytes_allocated()} bytes") + print_entry("Max memory", f"{pool.max_memory()} bytes") + print_entry("Supported Backends", ', '.join(supported_memory_backends())) + + print("\nOptional modules:") + modules = ["csv", "cuda", "dataset", "feather", "flight", "fs", "gandiva", "json", + "orc", "parquet"] + for module in modules: + status = "Enabled" if _module_is_available(module) else "-" + print(f" {module: <20}: {status: <8}") + + print("\nFilesystems:") + filesystems = ["AzureFileSystem", "GcsFileSystem", + "HadoopFileSystem", "S3FileSystem"] + for fs in filesystems: + status = "Enabled" if _filesystem_is_available(fs) else "-" + print(f" {fs: <20}: {status: <8}") + + print("\nCompression Codecs:") + codecs = ["brotli", "bz2", "gzip", "lz4_frame", "lz4", "snappy", "zstd"] + for codec in codecs: + status = "Enabled" if Codec.is_available(codec) else "-" + print(f" {codec: <20}: {status: <8}") + + +from pyarrow.lib import (null, bool_, + int8, int16, int32, int64, + uint8, uint16, uint32, uint64, + time32, time64, timestamp, date32, date64, duration, + month_day_nano_interval, + float16, float32, float64, + binary, string, utf8, binary_view, string_view, + large_binary, large_string, large_utf8, + decimal32, decimal64, decimal128, decimal256, + list_, large_list, list_view, large_list_view, + map_, struct, + union, sparse_union, dense_union, + dictionary, + run_end_encoded, + bool8, fixed_shape_tensor, json_, opaque, uuid, + field, + type_for_alias, + DataType, DictionaryType, StructType, + ListType, LargeListType, FixedSizeListType, + ListViewType, LargeListViewType, + MapType, UnionType, SparseUnionType, DenseUnionType, + TimestampType, Time32Type, Time64Type, DurationType, + FixedSizeBinaryType, + Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, + BaseExtensionType, ExtensionType, + RunEndEncodedType, Bool8Type, FixedShapeTensorType, + JsonType, OpaqueType, UuidType, + PyExtensionType, UnknownExtensionType, + register_extension_type, unregister_extension_type, + DictionaryMemo, + KeyValueMetadata, + Field, + Schema, + schema, + unify_schemas, + Array, Tensor, + array, chunked_array, record_batch, nulls, repeat, + SparseCOOTensor, SparseCSRMatrix, SparseCSCMatrix, + SparseCSFTensor, + infer_type, from_numpy_dtype, + NullArray, + NumericArray, IntegerArray, FloatingPointArray, + BooleanArray, + Int8Array, UInt8Array, + Int16Array, UInt16Array, + Int32Array, UInt32Array, + Int64Array, UInt64Array, + HalfFloatArray, FloatArray, DoubleArray, + ListArray, LargeListArray, FixedSizeListArray, + ListViewArray, LargeListViewArray, + MapArray, UnionArray, + BinaryArray, StringArray, + LargeBinaryArray, LargeStringArray, + BinaryViewArray, StringViewArray, + FixedSizeBinaryArray, + DictionaryArray, + Date32Array, Date64Array, TimestampArray, + Time32Array, Time64Array, DurationArray, + MonthDayNanoIntervalArray, + Decimal32Array, Decimal64Array, Decimal128Array, Decimal256Array, + StructArray, ExtensionArray, + RunEndEncodedArray, Bool8Array, FixedShapeTensorArray, + JsonArray, OpaqueArray, UuidArray, + scalar, NA, _NULL as NULL, Scalar, + NullScalar, BooleanScalar, + Int8Scalar, Int16Scalar, Int32Scalar, Int64Scalar, + UInt8Scalar, UInt16Scalar, UInt32Scalar, UInt64Scalar, + HalfFloatScalar, FloatScalar, DoubleScalar, + Decimal32Scalar, Decimal64Scalar, Decimal128Scalar, Decimal256Scalar, + ListScalar, LargeListScalar, FixedSizeListScalar, + ListViewScalar, LargeListViewScalar, + Date32Scalar, Date64Scalar, + Time32Scalar, Time64Scalar, + TimestampScalar, DurationScalar, + MonthDayNanoIntervalScalar, + BinaryScalar, LargeBinaryScalar, BinaryViewScalar, + StringScalar, LargeStringScalar, StringViewScalar, + FixedSizeBinaryScalar, DictionaryScalar, + MapScalar, StructScalar, UnionScalar, + RunEndEncodedScalar, Bool8Scalar, ExtensionScalar, + FixedShapeTensorScalar, JsonScalar, OpaqueScalar, UuidScalar) + +# Buffers, allocation +from pyarrow.lib import (DeviceAllocationType, Device, MemoryManager, + default_cpu_memory_manager) + +from pyarrow.lib import (Buffer, ResizableBuffer, foreign_buffer, py_buffer, + Codec, compress, decompress, allocate_buffer) + +from pyarrow.lib import (MemoryPool, LoggingMemoryPool, ProxyMemoryPool, + total_allocated_bytes, set_memory_pool, + default_memory_pool, system_memory_pool, + jemalloc_memory_pool, mimalloc_memory_pool, + logging_memory_pool, proxy_memory_pool, + log_memory_allocations, jemalloc_set_decay_ms, + supported_memory_backends) + +# I/O +from pyarrow.lib import (NativeFile, PythonFile, + BufferedInputStream, BufferedOutputStream, CacheOptions, + CompressedInputStream, CompressedOutputStream, + TransformInputStream, transcoding_input_stream, + FixedSizeBufferWriter, + BufferReader, BufferOutputStream, + OSFile, MemoryMappedFile, memory_map, + create_memory_map, MockOutputStream, + input_stream, output_stream, + have_libhdfs) + +from pyarrow.lib import (ChunkedArray, RecordBatch, Table, table, + concat_arrays, concat_tables, TableGroupBy, + RecordBatchReader, concat_batches) + +# Exceptions +from pyarrow.lib import (ArrowCancelled, + ArrowCapacityError, + ArrowException, + ArrowKeyError, + ArrowIndexError, + ArrowInvalid, + ArrowIOError, + ArrowMemoryError, + ArrowNotImplementedError, + ArrowTypeError, + ArrowSerializationError) + +from pyarrow.ipc import serialize_pandas, deserialize_pandas +import pyarrow.ipc as ipc + +import pyarrow.types as types + + +# ---------------------------------------------------------------------- +# Deprecations + +from pyarrow.util import _deprecate_api, _deprecate_class + + +# TODO: Deprecate these somehow in the pyarrow namespace +from pyarrow.ipc import (Message, MessageReader, MetadataVersion, + RecordBatchFileReader, RecordBatchFileWriter, + RecordBatchStreamReader, RecordBatchStreamWriter) + +# ---------------------------------------------------------------------- +# Returning absolute path to the pyarrow include directory (if bundled, e.g. in +# wheels) + + +def get_include(): + """ + Return absolute path to directory containing Arrow C++ include + headers. Similar to numpy.get_include + """ + return _os.path.join(_os.path.dirname(__file__), 'include') + + +def _get_pkg_config_executable(): + return _os.environ.get('PKG_CONFIG', 'pkg-config') + + +def _has_pkg_config(pkgname): + import subprocess + try: + return subprocess.call([_get_pkg_config_executable(), + '--exists', pkgname]) == 0 + except FileNotFoundError: + return False + + +def _read_pkg_config_variable(pkgname, cli_args): + import subprocess + cmd = [_get_pkg_config_executable(), pkgname] + cli_args + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + out, err = proc.communicate() + if proc.returncode != 0: + raise RuntimeError("pkg-config failed: " + err.decode('utf8')) + return out.rstrip().decode('utf8') + + +def get_libraries(): + """ + Return list of library names to include in the `libraries` argument for C + or Cython extensions using pyarrow + """ + return ['arrow_python', 'arrow'] + + +def create_library_symlinks(): + """ + With Linux and macOS wheels, the bundled shared libraries have an embedded + ABI version like libarrow.so.17 or libarrow.17.dylib and so linking to them + with -larrow won't work unless we create symlinks at locations like + site-packages/pyarrow/libarrow.so. This unfortunate workaround addresses + prior problems we had with shipping two copies of the shared libraries to + permit third party projects like turbodbc to build their C++ extensions + against the pyarrow wheels. + + This function must only be invoked once and only when the shared libraries + are bundled with the Python package, which should only apply to wheel-based + installs. It requires write access to the site-packages/pyarrow directory + and so depending on your system may need to be run with root. + """ + import glob + if _sys.platform == 'win32': + return + package_cwd = _os.path.dirname(__file__) + + if _sys.platform == 'linux': + bundled_libs = glob.glob(_os.path.join(package_cwd, '*.so.*')) + + def get_symlink_path(hard_path): + return hard_path.rsplit('.', 1)[0] + else: + bundled_libs = glob.glob(_os.path.join(package_cwd, '*.*.dylib')) + + def get_symlink_path(hard_path): + return '.'.join((hard_path.rsplit('.', 2)[0], 'dylib')) + + for lib_hard_path in bundled_libs: + symlink_path = get_symlink_path(lib_hard_path) + if _os.path.exists(symlink_path): + continue + try: + _os.symlink(lib_hard_path, symlink_path) + except PermissionError: + print("Tried creating symlink {}. If you need to link to " + "bundled shared libraries, run " + "pyarrow.create_library_symlinks() as root") + + +def get_library_dirs(): + """ + Return lists of directories likely to contain Arrow C++ libraries for + linking C or Cython extensions using pyarrow + """ + package_cwd = _os.path.dirname(__file__) + library_dirs = [package_cwd] + + def append_library_dir(library_dir): + if library_dir not in library_dirs: + library_dirs.append(library_dir) + + # Search library paths via pkg-config. This is necessary if the user + # installed libarrow and the other shared libraries manually and they + # are not shipped inside the pyarrow package (see also ARROW-2976). + pkg_config_executable = _os.environ.get('PKG_CONFIG') or 'pkg-config' + for pkgname in ["arrow", "arrow_python"]: + if _has_pkg_config(pkgname): + library_dir = _read_pkg_config_variable(pkgname, + ["--libs-only-L"]) + # pkg-config output could be empty if Arrow is installed + # as a system package. + if library_dir: + if not library_dir.startswith("-L"): + raise ValueError( + "pkg-config --libs-only-L returned unexpected " + "value {!r}".format(library_dir)) + append_library_dir(library_dir[2:]) + + if _sys.platform == 'win32': + # TODO(wesm): Is this necessary, or does setuptools within a conda + # installation add Library\lib to the linker path for MSVC? + python_base_install = _os.path.dirname(_sys.executable) + library_dir = _os.path.join(python_base_install, 'Library', 'lib') + + if _os.path.exists(_os.path.join(library_dir, 'arrow.lib')): + append_library_dir(library_dir) + + # ARROW-4074: Allow for ARROW_HOME to be set to some other directory + if _os.environ.get('ARROW_HOME'): + append_library_dir(_os.path.join(_os.environ['ARROW_HOME'], 'lib')) + else: + # Python wheels bundle the Arrow libraries in the pyarrow directory. + append_library_dir(_os.path.dirname(_os.path.abspath(__file__))) + + return library_dirs diff --git a/shared/package-files/f1/f1f61bdec46ac8680d48c07f8883de315b01c1904dcbff405fc02a6e25c41850/linalg_multi_dot.h b/shared/package-files/f1/f1f61bdec46ac8680d48c07f8883de315b01c1904dcbff405fc02a6e25c41850/linalg_multi_dot.h new file mode 100644 index 0000000000000000000000000000000000000000..32d2145656b7001e4f1914f13b8abcade7ca48c0 --- /dev/null +++ b/shared/package-files/f1/f1f61bdec46ac8680d48c07f8883de315b01c1904dcbff405fc02a6e25c41850/linalg_multi_dot.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_multi_dot(Tensor[] tensors) -> Tensor +inline at::Tensor linalg_multi_dot(at::TensorList tensors) { + return at::_ops::linalg_multi_dot::call(tensors); +} + +// aten::linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_multi_dot_out(at::Tensor & out, at::TensorList tensors) { + return at::_ops::linalg_multi_dot_out::call(tensors, out); +} +// aten::linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_multi_dot_outf(at::TensorList tensors, at::Tensor & out) { + return at::_ops::linalg_multi_dot_out::call(tensors, out); +} + +}