Python torch.trunc() Examples

The following are 5 code examples of torch.trunc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module torch , or try the search function .
Example #1
Source File: distributed_sampler.py    From detectron2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, repeat_factors, *, shuffle=True, seed=None):
        """
        Args:
            repeat_factors (Tensor): a float vector, the repeat factor for each indice. When it's
                full of ones, it is equivalent to ``TrainingSampler(len(repeat_factors), ...)``.
            shuffle (bool): whether to shuffle the indices or not
            seed (int): the initial seed of the shuffle. Must be the same
                across all workers. If None, will use a random seed shared
                among workers (require synchronization among all workers).
        """
        self._shuffle = shuffle
        if seed is None:
            seed = comm.shared_random_seed()
        self._seed = int(seed)

        self._rank = comm.get_rank()
        self._world_size = comm.get_world_size()

        # Split into whole number (_int_part) and fractional (_frac_part) parts.
        self._int_part = torch.trunc(repeat_factors)
        self._frac_part = repeat_factors - self._int_part 
Example #2
Source File: distributed_sampler.py    From detectron2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, dataset_dicts, repeat_thresh, shuffle=True, seed=None):
        """
        Args:
            dataset_dicts (list[dict]): annotations in Detectron2 dataset format.
            repeat_thresh (float): frequency threshold below which data is repeated.
            shuffle (bool): whether to shuffle the indices or not
            seed (int): the initial seed of the shuffle. Must be the same
                across all workers. If None, will use a random seed shared
                among workers (require synchronization among all workers).
        """
        self._shuffle = shuffle
        if seed is None:
            seed = comm.shared_random_seed()
        self._seed = int(seed)

        self._rank = comm.get_rank()
        self._world_size = comm.get_world_size()

        # Get fractional repeat factors and split into whole number (_int_part)
        # and fractional (_frac_part) parts.
        rep_factors = self._get_repeat_factors(dataset_dicts, repeat_thresh)
        self._int_part = torch.trunc(rep_factors)
        self._frac_part = rep_factors - self._int_part 
Example #3
Source File: rounding.py    From heat with MIT License 5 votes vote down vote up
def trunc(x, out=None):
    """
    Return the trunc of the input, element-wise.

    The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the
    fractional part of the signed number x is discarded.

    Parameters
    ----------
    x : ht.DNDarray
        The value for which to compute the trunced values.
    out : ht.DNDarray or None, optional
        A location in which to store the results. If provided, it must have a broadcastable shape. If not provided
        or set to None, a fresh tensor is allocated.

    Returns
    -------
    trunced : ht.DNDarray
        A tensor of the same shape as x, containing the trunced valued of each element in this tensor. If out was
        provided, trunced is a reference to it.

    Examples
    --------
    >>> ht.trunc(ht.arange(-2.0, 2.0, 0.4))
    tensor([-2., -1., -1., -0., -0.,  0.,  0.,  0.,  1.,  1.])
    """
    return operations.__local_op(torch.trunc, x, out) 
Example #4
Source File: repeat_factor.py    From Parsing-R-CNN with MIT License 4 votes vote down vote up
def __init__(self, dataset, config, num_replicas=None, rank=None, shuffle=True):
        """
        Args:
            dataset: COCODataset.
            config:
                REPEAT_THRESHOLD (float): frequency used for control imgs per epoch
                MAX_REPEAT_TIMES (float) : max repeat times for single epoch
                MIN_REPEAT_TIMES (float) : min repeat times for single epoch
                POW(float): 0.5 for lvis paper sqrt ,1.0 for linear
            shuffle (bool): whether to shuffle the indices or not
        """
        self.shuffle = shuffle
        self.config = config
        if num_replicas is None:
            if not dist.is_available():
                raise RuntimeError("Requires distributed package to be available")
            num_replicas = dist.get_world_size()
        if rank is None:
            if not dist.is_available():
                raise RuntimeError("Requires distributed package to be available")
            rank = dist.get_rank()
        self.num_replicas = num_replicas
        self.rank = rank
        self.epoch = 0
        self.num_samples = int(math.ceil(len(dataset) * 1.0 / self.num_replicas))
        self.total_size = self.num_samples * self.num_replicas

        # Get per-image annotations list
        coco_json = dataset.coco
        img_bboxes = {}
        ids = dataset.ids  # or use dataset_dicts.id_to_img_map and get its value
        annotations = coco_json.anns
        for item_ in annotations:
            item = annotations[item_]
            img_bboxes.setdefault(item['image_id'], []).append(item)
        dataset_dict_img = []
        for img_id in ids:
            dataset_dict_img.append({"annotations": img_bboxes[img_id]})

        # Get fractional repeat factors and split into whole number (_int_part)
        # and fractional (_frac_part) parts.
        rep_factors = self._get_repeat_factors(dataset_dict_img)
        self._int_part = torch.trunc(rep_factors)
        self._frac_part = rep_factors - self._int_part 
Example #5
Source File: rounding.py    From heat with MIT License 4 votes vote down vote up
def modf(x, out=None):
    """
    Return the fractional and integral parts of a tensor, element-wise.
    The fractional and integral parts are negative if the given number is negative.

    Parameters
    ----------
    x : ht.DNDarray
        Input tensor
    out : tuple(ht.DNDarray, ht.DNDarray), optional
        A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to.
        If not provided or None, a freshly-allocated tensor is returned.

    Returns
    -------
    tuple(ht.DNDarray: fractionalParts, ht.DNDarray: integralParts)

    fractionalParts : ht.DNDdarray
        Fractional part of x. This is a scalar if x is a scalar.

    integralParts : ht.DNDdarray
        Integral part of x. This is a scalar if x is a scalar.

    Examples
    --------
    >>> ht.modf(ht.arange(-2.0, 2.0, 0.4))
        (tensor([-2., -1., -1., -0., -0.,  0.,  0.,  0.,  1.,  1.]),
        tensor([ 0.0000, -0.6000, -0.2000, -0.8000, -0.4000,  0.0000,  0.4000,  0.8000, 0.2000,  0.6000]))
    """
    if not isinstance(x, dndarray.DNDarray):
        raise TypeError("expected x to be a ht.DNDarray, but was {}".format(type(x)))

    integralParts = trunc(x)
    fractionalParts = x - integralParts

    if out is not None:
        if not isinstance(out, tuple):
            raise TypeError(
                "expected out to be None or a tuple of ht.DNDarray, but was {}".format(type(out))
            )
        if len(out) != 2:
            raise ValueError(
                "expected out to be a tuple of length 2, but was of length {}".format(len(out))
            )
        if (not isinstance(out[0], dndarray.DNDarray)) or (
            not isinstance(out[1], dndarray.DNDarray)
        ):
            raise TypeError(
                "expected out to be None or a tuple of ht.DNDarray, but was ({}, {})".format(
                    type(out[0]), type(out[1])
                )
            )
        out[0]._DNDarray__array = fractionalParts._DNDarray__array
        out[1]._DNDarray__array = integralParts._DNDarray__array
        return out

    return (fractionalParts, integralParts)