1 from functools
import update_wrapper
2 from numbers
import Number
9 def _default_promotion(v):
13 def broadcast_all(*values):
15 Given a list of values (possibly containing numbers), returns a list where each 16 value is broadcasted based on the following rules: 17 - `torch.*Tensor` instances are broadcasted as per :ref:`_broadcasting-semantics`. 18 - numbers.Number instances (scalars) are upcast to tensors having 19 the same size and type as the first tensor passed to `values`. If all the 20 values are scalars, then they are upcasted to scalar Tensors. 23 values (list of `numbers.Number` or `torch.*Tensor`) 26 ValueError: if any of the values is not a `numbers.Number` or 27 `torch.*Tensor` instance 29 if not all(
torch.is_tensor(v)
or isinstance(v, Number)
for v
in values):
30 raise ValueError(
'Input arguments must all be instances of numbers.Number or torch.tensor.')
31 if not all(map(torch.is_tensor, values)):
32 new_tensor = _default_promotion
35 new_tensor = value.new_tensor
38 return torch.broadcast_tensors(*values)
41 def _standard_normal(shape, dtype, device):
42 if torch._C._get_tracing_state():
44 return torch.normal(torch.zeros(shape, dtype=dtype, device=device),
45 torch.ones(shape, dtype=dtype, device=device))
46 return torch.empty(shape, dtype=dtype, device=device).normal_()
49 def _sum_rightmost(value, dim):
51 Sum out ``dim`` many rightmost dimensions of a given tensor. 54 value (Tensor): A tensor of ``.dim()`` at least ``dim``. 55 dim (int): The number of rightmost dims to sum out. 59 required_shape = value.shape[:-dim] + (-1,)
60 return value.reshape(required_shape).sum(-1)
63 def logits_to_probs(logits, is_binary=False):
65 Converts a tensor of logits into probabilities. Note that for the 66 binary case, each value denotes log odds, whereas for the 67 multi-dimensional case, the values along the last dimension denote 68 the log probabilities (possibly unnormalized) of the events. 71 return torch.sigmoid(logits)
72 return F.softmax(logits, dim=-1)
75 def clamp_probs(probs):
76 eps = torch.finfo(probs.dtype).eps
77 return probs.clamp(min=eps, max=1 - eps)
80 def probs_to_logits(probs, is_binary=False):
82 Converts a tensor of probabilities into logits. For the binary case, 83 this denotes the probability of occurrence of the event indexed by `1`. 84 For the multi-dimensional case, the values along the last dimension 85 denote the probabilities of occurrence of each of the events. 87 ps_clamped = clamp_probs(probs)
89 return torch.log(ps_clamped) - torch.log1p(-ps_clamped)
90 return torch.log(ps_clamped)
95 Used as a decorator for lazy loading of class attributes. This uses a 96 non-data descriptor that calls the wrapped method to compute the property on 97 first call; thereafter replacing the wrapped method into an instance 100 def __init__(self, wrapped):
102 update_wrapper(self, wrapped)
104 def __get__(self, instance, obj_type=None):
107 with torch.enable_grad():
109 setattr(instance, self.wrapped.__name__, value)