doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
tf.Variable View source on GitHub See the variable guide.
tf.Variable(
initial_value=None, trainable=None, validate_shape=True, caching_device=None,
name=None, variable_def=None, dtype=None, import_scope=None, constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None
)
A variable maintains shared, persistent state manipulated by a program. The Variable() constructor requires an initial value for the variable, which can be a Tensor of any type and shape. This initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods.
v = tf.Variable(1.)
v.assign(2.)
<tf.Variable ... shape=() dtype=float32, numpy=2.0>
v.assign_add(0.5)
<tf.Variable ... shape=() dtype=float32, numpy=2.5>
The shape argument to Variable's constructor allows you to construct a variable with a less defined shape than its initial_value:
v = tf.Variable(1., shape=tf.TensorShape(None))
v.assign([[1.]])
<tf.Variable ... shape=<unknown> dtype=float32, numpy=array([[1.]], ...)>
Just like any Tensor, variables created with Variable() can be used as inputs to operations. Additionally, all the operators overloaded for the Tensor class are carried over to variables.
w = tf.Variable([[1.], [2.]])
x = tf.constant([[3., 4.]])
tf.matmul(w, x)
<tf.Tensor:... shape=(2, 2), ... numpy=
array([[3., 4.],
[6., 8.]], dtype=float32)>
tf.sigmoid(w + x)
<tf.Tensor:... shape=(2, 2), ...>
When building a machine learning model it is often convenient to distinguish between variables holding trainable model parameters and other variables such as a step variable used to count training steps. To make this easier, the variable constructor supports a trainable=<bool> parameter. tf.GradientTape watches trainable variables by default:
with tf.GradientTape(persistent=True) as tape:
trainable = tf.Variable(1.)
non_trainable = tf.Variable(2., trainable=False)
x1 = trainable * 2.
x2 = non_trainable * 3.
tape.gradient(x1, trainable)
<tf.Tensor:... shape=(), dtype=float32, numpy=2.0>
assert tape.gradient(x2, non_trainable) is None # Unwatched
Variables are automatically tracked when assigned to attributes of types inheriting from tf.Module.
m = tf.Module()
m.v = tf.Variable([1.])
m.trainable_variables
(<tf.Variable ... shape=(1,) ... numpy=array([1.], dtype=float32)>,)
This tracking then allows saving variable values to training checkpoints, or to SavedModels which include serialized TensorFlow graphs. Variables are often captured and manipulated by tf.functions. This works the same way the un-decorated function would have:
v = tf.Variable(0.)
read_and_decrement = tf.function(lambda: v.assign_sub(0.1))
read_and_decrement()
<tf.Tensor: shape=(), dtype=float32, numpy=-0.1>
read_and_decrement()
<tf.Tensor: shape=(), dtype=float32, numpy=-0.2>
Variables created inside a tf.function must be owned outside the function and be created only once:
class M(tf.Module):
@tf.function
def __call__(self, x):
if not hasattr(self, "v"): # Or set self.v to None in __init__
self.v = tf.Variable(x)
return self.v * x
m = M()
m(2.)
<tf.Tensor: shape=(), dtype=float32, numpy=4.0>
m(3.)
<tf.Tensor: shape=(), dtype=float32, numpy=6.0>
m.v
<tf.Variable ... shape=() dtype=float32, numpy=2.0>
See the tf.function documentation for details.
Args
initial_value A Tensor, or Python object convertible to a Tensor, which is the initial value for the Variable. The initial value must have a shape specified unless validate_shape is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, dtype must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.)
trainable If True, GradientTapes automatically watch uses of this variable. Defaults to True, unless synchronization is set to ON_READ, in which case it defaults to False.
validate_shape If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known.
caching_device Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not None, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through Switch and other conditional statements.
name Optional name for the variable. Defaults to 'Variable' and gets uniquified automatically.
variable_def VariableDef protocol buffer. If not None, recreates the Variable object with its contents, referencing the variable's nodes in the graph, which must already exist. The graph is not changed. variable_def and the other arguments are mutually exclusive.
dtype If set, initial_value will be converted to the given type. If None, either the datatype will be kept (if initial_value is a Tensor), or convert_to_tensor will decide.
import_scope Optional string. Name scope to add to the Variable. Only used when initializing from protocol buffer.
constraint An optional projection function to be applied to the variable after being updated by an Optimizer (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training.
synchronization Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class tf.VariableSynchronization. By default the synchronization is set to AUTO and the current DistributionStrategy chooses when to synchronize.
aggregation Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class tf.VariableAggregation.
shape (optional) The shape of this variable. If None, the shape of initial_value will be used. When setting this argument to tf.TensorShape(None) (representing an unspecified shape), the variable can be assigned with values of different shapes.
Raises
ValueError If both variable_def and initial_value are specified.
ValueError If the initial value is not specified, or does not have a shape and validate_shape is True.
Attributes
aggregation
constraint Returns the constraint function associated with this variable.
device The device of this variable.
dtype The DType of this variable.
graph The Graph of this variable.
initial_value Returns the Tensor used as the initial value for the variable. Note that this is different from initialized_value() which runs the op that initializes the variable before returning its value. This method returns the tensor that is used by the op that initializes the variable.
initializer The initializer operation for this variable.
name The name of this variable.
op The Operation of this variable.
shape The TensorShape of this variable.
synchronization
trainable
Child Classes class SaveSliceInfo Methods assign View source
assign(
value, use_locking=False, name=None, read_value=True
)
Assigns a new value to the variable. This is essentially a shortcut for assign(self, value).
Args
value A Tensor. The new value for this variable.
use_locking If True, use locking during the assignment.
name The name of the operation to be created
read_value if True, will return something which evaluates to the new value of the variable; if False will return the assign op.
Returns The updated variable. If read_value is false, instead returns None in Eager mode and the assign op in graph mode.
assign_add View source
assign_add(
delta, use_locking=False, name=None, read_value=True
)
Adds a value to this variable. This is essentially a shortcut for assign_add(self, delta).
Args
delta A Tensor. The value to add to this variable.
use_locking If True, use locking during the operation.
name The name of the operation to be created
read_value if True, will return something which evaluates to the new value of the variable; if False will return the assign op.
Returns The updated variable. If read_value is false, instead returns None in Eager mode and the assign op in graph mode.
assign_sub View source
assign_sub(
delta, use_locking=False, name=None, read_value=True
)
Subtracts a value from this variable. This is essentially a shortcut for assign_sub(self, delta).
Args
delta A Tensor. The value to subtract from this variable.
use_locking If True, use locking during the operation.
name The name of the operation to be created
read_value if True, will return something which evaluates to the new value of the variable; if False will return the assign op.
Returns The updated variable. If read_value is false, instead returns None in Eager mode and the assign op in graph mode.
batch_scatter_update View source
batch_scatter_update(
sparse_delta, use_locking=False, name=None
)
Assigns tf.IndexedSlices to this variable batch-wise. Analogous to batch_gather. This assumes that this variable and the sparse_delta IndexedSlices have a series of leading dimensions that are the same for all of them, and the updates are performed on the last dimension of indices. In other words, the dimensions should be the following: num_prefix_dims = sparse_delta.indices.ndims - 1 batch_dim = num_prefix_dims + 1 sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[ batch_dim:] where sparse_delta.updates.shape[:num_prefix_dims] == sparse_delta.indices.shape[:num_prefix_dims] == var.shape[:num_prefix_dims] And the operation performed can be expressed as: var[i_1, ..., i_n, sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[ i_1, ..., i_n, j] When sparse_delta.indices is a 1D tensor, this operation is equivalent to scatter_update. To avoid this operation one can looping over the first ndims of the variable and using scatter_update on the subtensors that result of slicing the first dimension. This is a valid option for ndims = 1, but less efficient than this implementation.
Args
sparse_delta tf.IndexedSlices to be assigned to this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. count_up_to View source
count_up_to(
limit
)
Increments this variable until it reaches limit. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Prefer Dataset.range instead. When that Op is run it tries to increment the variable by 1. If incrementing the variable would bring it above limit then the Op raises the exception OutOfRangeError. If no error is raised, the Op outputs the value of the variable before the increment. This is essentially a shortcut for count_up_to(self, limit).
Args
limit value at which incrementing the variable raises an error.
Returns A Tensor that will hold the variable value before the increment. If no other Op modifies this variable, the values produced will all be distinct.
eval View source
eval(
session=None
)
In a session, computes and returns the value of this variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See tf.compat.v1.Session for more information on launching a graph and on sessions. v = tf.Variable([1, 2])
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
print(v.eval())
Args
session The session to use to evaluate this variable. If none, the default session is used.
Returns A numpy ndarray with a copy of the value of this variable.
experimental_ref View source
experimental_ref()
DEPRECATED FUNCTION Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use ref() instead. from_proto View source
@staticmethod
from_proto(
variable_def, import_scope=None
)
Returns a Variable object created from variable_def. gather_nd View source
gather_nd(
indices, name=None
)
Gather slices from params into a Tensor with shape specified by indices. See tf.gather_nd for details.
Args
indices A Tensor. Must be one of the following types: int32, int64. Index tensor.
name A name for the operation (optional).
Returns A Tensor. Has the same type as params.
get_shape View source
get_shape()
Alias of Variable.shape. initialized_value View source
initialized_value()
Returns the value of the initialized variable. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts. You should use this instead of the variable itself to initialize another variable with a value that depends on the value of this variable. # Initialize 'v' with a random tensor.
v = tf.Variable(tf.random.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
Returns A Tensor holding the value of this variable after its initializer has run.
load View source
load(
value, session=None
)
Load new value into this variable. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Prefer Variable.assign which has equivalent behavior in 2.X. Writes new value to variable's memory. Doesn't add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See tf.compat.v1.Session for more information on launching a graph and on sessions. v = tf.Variable([1, 2])
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
v.load([2, 3], sess)
print(v.eval(sess)) # prints [2 3]
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
v.load([3, 4], sess)
print(v.eval()) # prints [3 4]
Args
value New variable value
session The session to use to evaluate this variable. If none, the default session is used.
Raises
ValueError Session is not passed and no default session read_value View source
read_value()
Returns the value of this variable, read in the current context. Can be different from value() if it's on another device, with control dependencies, etc.
Returns A Tensor containing the value of the variable.
ref View source
ref()
Returns a hashable reference object to this Variable. The primary use case for this API is to put variables in a set/dictionary. We can't put variables in a set/dictionary as variable.__hash__() is no longer available starting Tensorflow 2.0. The following will raise an exception starting 2.0
x = tf.Variable(5)
y = tf.Variable(10)
z = tf.Variable(10)
variable_set = {x, y, z}
Traceback (most recent call last):
TypeError: Variable is unhashable. Instead, use tensor.ref() as the key.
variable_dict = {x: 'five', y: 'ten'}
Traceback (most recent call last):
TypeError: Variable is unhashable. Instead, use tensor.ref() as the key.
Instead, we can use variable.ref().
variable_set = {x.ref(), y.ref(), z.ref()}
x.ref() in variable_set
True
variable_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'}
variable_dict[y.ref()]
'ten'
Also, the reference object provides .deref() function that returns the original Variable.
x = tf.Variable(5)
x.ref().deref()
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>
scatter_add View source
scatter_add(
sparse_delta, use_locking=False, name=None
)
Adds tf.IndexedSlices to this variable.
Args
sparse_delta tf.IndexedSlices to be added to this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_div View source
scatter_div(
sparse_delta, use_locking=False, name=None
)
Divide this variable by tf.IndexedSlices.
Args
sparse_delta tf.IndexedSlices to divide this variable by.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_max View source
scatter_max(
sparse_delta, use_locking=False, name=None
)
Updates this variable with the max of tf.IndexedSlices and itself.
Args
sparse_delta tf.IndexedSlices to use as an argument of max with this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_min View source
scatter_min(
sparse_delta, use_locking=False, name=None
)
Updates this variable with the min of tf.IndexedSlices and itself.
Args
sparse_delta tf.IndexedSlices to use as an argument of min with this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_mul View source
scatter_mul(
sparse_delta, use_locking=False, name=None
)
Multiply this variable by tf.IndexedSlices.
Args
sparse_delta tf.IndexedSlices to multiply this variable by.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_nd_add View source
scatter_nd_add(
indices, updates, name=None
)
Applies sparse addition to individual values or slices in a Variable. The Variable has rank P and indices is a Tensor of rank Q. indices must be integer tensor, containing indices into self. It must be shape [d_0, ..., d_{Q-2}, K] where 0 < K <= P. The innermost dimension of indices (with length K) corresponds to indices into elements (if K = P) or slices (if K < P) along the Kth dimension of self. updates is Tensor of rank Q-1+P-K with shape: [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this: v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
add = v.scatter_nd_add(indices, updates)
with tf.compat.v1.Session() as sess:
print sess.run(add)
The resulting update to v would look like this: [1, 13, 3, 14, 14, 6, 7, 20]
See tf.scatter_nd for more details about how to make updates to slices.
Args
indices The indices to be used in the operation.
updates The values to be used in the operation.
name the name of the operation.
Returns The updated variable.
scatter_nd_sub View source
scatter_nd_sub(
indices, updates, name=None
)
Applies sparse subtraction to individual values or slices in a Variable. Assuming the variable has rank P and indices is a Tensor of rank Q. indices must be integer tensor, containing indices into self. It must be shape [d_0, ..., d_{Q-2}, K] where 0 < K <= P. The innermost dimension of indices (with length K) corresponds to indices into elements (if K = P) or slices (if K < P) along the Kth dimension of self. updates is Tensor of rank Q-1+P-K with shape: [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this: v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = v.scatter_nd_sub(indices, updates)
with tf.compat.v1.Session() as sess:
print sess.run(op)
The resulting update to v would look like this: [1, -9, 3, -6, -6, 6, 7, -4]
See tf.scatter_nd for more details about how to make updates to slices.
Args
indices The indices to be used in the operation.
updates The values to be used in the operation.
name the name of the operation.
Returns The updated variable.
scatter_nd_update View source
scatter_nd_update(
indices, updates, name=None
)
Applies sparse assignment to individual values or slices in a Variable. The Variable has rank P and indices is a Tensor of rank Q. indices must be integer tensor, containing indices into self. It must be shape [d_0, ..., d_{Q-2}, K] where 0 < K <= P. The innermost dimension of indices (with length K) corresponds to indices into elements (if K = P) or slices (if K < P) along the Kth dimension of self. updates is Tensor of rank Q-1+P-K with shape: [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this: v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = v.scatter_nd_assign(indices, updates)
with tf.compat.v1.Session() as sess:
print sess.run(op)
The resulting update to v would look like this: [1, 11, 3, 10, 9, 6, 7, 12]
See tf.scatter_nd for more details about how to make updates to slices.
Args
indices The indices to be used in the operation.
updates The values to be used in the operation.
name the name of the operation.
Returns The updated variable.
scatter_sub View source
scatter_sub(
sparse_delta, use_locking=False, name=None
)
Subtracts tf.IndexedSlices from this variable.
Args
sparse_delta tf.IndexedSlices to be subtracted from this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. scatter_update View source
scatter_update(
sparse_delta, use_locking=False, name=None
)
Assigns tf.IndexedSlices to this variable.
Args
sparse_delta tf.IndexedSlices to be assigned to this variable.
use_locking If True, use locking during the operation.
name the name of the operation.
Returns The updated variable.
Raises
TypeError if sparse_delta is not an IndexedSlices. set_shape View source
set_shape(
shape
)
Overrides the shape for this variable.
Args
shape the TensorShape representing the overridden shape. sparse_read View source
sparse_read(
indices, name=None
)
Gather slices from params axis axis according to indices. This function supports a subset of tf.gather, see tf.gather for details on usage.
Args
indices The index Tensor. Must be one of the following types: int32, int64. Must be in range [0, params.shape[axis]).
name A name for the operation (optional).
Returns A Tensor. Has the same type as params.
to_proto View source
to_proto(
export_scope=None
)
Converts a Variable to a VariableDef protocol buffer.
Args
export_scope Optional string. Name scope to remove.
Returns A VariableDef protocol buffer, or None if the Variable is not in the specified name scope.
value View source
value()
Returns the last snapshot of this variable. You usually do not need to call this method as all ops that need the value of the variable call it automatically through a convert_to_tensor() call. Returns a Tensor which holds the value of the variable. You can not assign a new value to this tensor as it is not a reference to the variable. To avoid copies, if the consumer of the returned value is on the same device as the variable, this actually returns the live value of the variable, not a copy. Updates to the variable are seen by the consumer. If the consumer is on a different device it will get a copy of the variable.
Returns A Tensor containing the value of the variable.
__abs__ View source
__abs__(
x, name=None
)
Computes the absolute value of a tensor. Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input. Given a tensor x of complex numbers, this operation returns a tensor of type float32 or float64 that is the absolute value of each element in x. For a complex number \(a + bj\), its absolute value is computed as \(\sqrt{a^2 + b^2}\). For example:
# real number
x = tf.constant([-2.25, 3.25])
tf.abs(x)
<tf.Tensor: shape=(2,), dtype=float32,
numpy=array([2.25, 3.25], dtype=float32)>
# complex number
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
tf.abs(x)
<tf.Tensor: shape=(2, 1), dtype=float64, numpy=
array([[5.25594901],
[6.60492241]])>
Args
x A Tensor or SparseTensor of type float16, float32, float64, int32, int64, complex64 or complex128.
name A name for the operation (optional).
Returns A Tensor or SparseTensor of the same size, type and sparsity as x, with absolute values. Note, for complex64 or complex128 input, the returned Tensor will be of type float32 or float64, respectively.
__add__ View source
__add__(
x, y
)
The operation invoked by the Tensor.add operator. Purpose in the API: This method is exposed in TensorFlow's API so that library developers
can register dispatching for <a href="../tf/Tensor#__add__"><code>Tensor.__add__</code></a> to allow it to handle
custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does
appear in TensorFlow's generated documentation.
Args
x The left-hand side of the + operator.
y The right-hand side of the + operator.
name an optional name for the operation.
Returns The result of the elementwise + operation.
__and__ View source
__and__(
x, y
)
__div__ View source
__div__(
x, y
)
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide.
Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics.
This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y returns the quotient of x and y.
__eq__ View source
__eq__(
other
)
Compares two variables element-wise for equality. __floordiv__ View source
__floordiv__(
x, y
)
Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y rounded down.
Raises
TypeError If the inputs are complex. __ge__
__ge__(
x, y, name=None
)
Returns the truth value of (x >= y) element-wise.
Note: math.greater_equal supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6, 7])
y = tf.constant([5, 2, 5, 10])
tf.math.greater_equal(x, y) ==> [True, True, True, False]
x = tf.constant([5, 4, 6, 7])
y = tf.constant([5])
tf.math.greater_equal(x, y) ==> [True, False, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__getitem__ View source
__getitem__(
var, slice_spec
)
Creates a slice helper object given a variable. This allows creating a sub-tensor from part of the current contents of a variable. See tf.Tensor.getitem for detailed examples of slicing. This function in addition also allows assignment to a sliced range. This is similar to __setitem__ functionality in Python. However, the syntax is different so that the user can capture the assignment operation for grouping or passing to sess.run(). For example, import tensorflow as tf
A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32)
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
print(sess.run(A[:2, :2])) # => [[1,2], [4,5]]
op = A[:2,:2].assign(22. * tf.ones((2, 2)))
print(sess.run(op)) # => [[22, 22, 3], [22, 22, 6], [7,8,9]]
Note that assignments currently do not support NumPy broadcasting semantics.
Args
var An ops.Variable object.
slice_spec The arguments to Tensor.getitem.
Returns The appropriate slice of "tensor", based on "slice_spec". As an operator. The operator also has a assign() method that can be used to generate an assignment operator.
Raises
ValueError If a slice range is negative size.
TypeError TypeError: If the slice indices aren't int, slice, ellipsis, tf.newaxis or int32/int64 tensors. __gt__
__gt__(
x, y, name=None
)
Returns the truth value of (x > y) element-wise.
Note: math.greater supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5, 2, 5])
tf.math.greater(x, y) ==> [False, True, True]
x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.greater(x, y) ==> [False, False, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__invert__ View source
__invert__(
x, name=None
)
__iter__ View source
__iter__()
Dummy method to prevent iteration. Do not call. NOTE(mrry): If we register getitem as an overloaded operator, Python will valiantly attempt to iterate over the variable's Tensor from 0 to infinity. Declaring this method prevents this unintended behavior.
Raises
TypeError when invoked. __le__
__le__(
x, y, name=None
)
Returns the truth value of (x <= y) element-wise.
Note: math.less_equal supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less_equal(x, y) ==> [True, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 6])
tf.math.less_equal(x, y) ==> [True, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__lt__
__lt__(
x, y, name=None
)
Returns the truth value of (x < y) element-wise.
Note: math.less supports broadcasting. More about broadcasting here
Example: x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less(x, y) ==> [False, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 7])
tf.math.less(x, y) ==> [False, True, True]
Args
x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor of type bool.
__matmul__ View source
__matmul__(
x, y
)
Multiplies matrix a by matrix b, producing a * b. The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication dimensions, and any further outer dimensions specify matching batch size. Both matrices must be of the same type. The supported types are: float16, float32, float64, int32, complex64, complex128. Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to True. These are False by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding a_is_sparse or b_is_sparse flag to True. These are False by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes bfloat16 or float32. A simple 2-D tensor matrix multiplication:
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
a # 2-D tensor
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
b # 2-D tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[ 7, 8],
[ 9, 10],
[11, 12]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 58, 64],
[139, 154]], dtype=int32)>
A batch matrix multiplication with batch shape [2]:
a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
a # 3-D tensor
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]], dtype=int32)>
b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2])
b # 3-D tensor
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[13, 14],
[15, 16],
[17, 18]],
[[19, 20],
[21, 22],
[23, 24]]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[ 94, 100],
[229, 244]],
[[508, 532],
[697, 730]]], dtype=int32)>
Since python >= 3.5 the @ operator is supported (see PEP 465). In TensorFlow, it simply calls the tf.matmul() function, so the following lines are equivalent:
d = a @ b @ [[10], [11]]
d = tf.matmul(tf.matmul(a, b), [[10], [11]])
Args
a tf.Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
b tf.Tensor with same type and rank as a.
transpose_a If True, a is transposed before multiplication.
transpose_b If True, b is transposed before multiplication.
adjoint_a If True, a is conjugated and transposed before multiplication.
adjoint_b If True, b is conjugated and transposed before multiplication.
a_is_sparse If True, a is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
b_is_sparse If True, b is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
name Name for the operation (optional).
Returns A tf.Tensor of the same type as a and b where each inner-most matrix is the product of the corresponding matrices in a and b, e.g. if all transpose or adjoint attributes are False: output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j]), for all indices i, j.
Note This is matrix product, not element-wise product.
Raises
ValueError If transpose_a and adjoint_a, or transpose_b and adjoint_b are both set to True. __mod__ View source
__mod__(
x, y
)
Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x.
Note: math.floormod supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x.
__mul__ View source
__mul__(
x, y
)
Dispatches cwise mul for "DenseDense" and "DenseSparse". __ne__ View source
__ne__(
other
)
Compares two variables element-wise for equality. __neg__
__neg__(
x, name=None
)
Computes numerical negative value element-wise. I.e., \(y = -x\).
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x.
__or__ View source
__or__(
x, y
)
__pow__ View source
__pow__(
x, y
)
Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
Args
x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
name A name for the operation (optional).
Returns A Tensor.
__radd__ View source
__radd__(
y, x
)
The operation invoked by the Tensor.add operator. Purpose in the API: This method is exposed in TensorFlow's API so that library developers
can register dispatching for <a href="../tf/Tensor#__add__"><code>Tensor.__add__</code></a> to allow it to handle
custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does
appear in TensorFlow's generated documentation.
Args
x The left-hand side of the + operator.
y The right-hand side of the + operator.
name an optional name for the operation.
Returns The result of the elementwise + operation.
__rand__ View source
__rand__(
y, x
)
__rdiv__ View source
__rdiv__(
y, x
)
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide.
Note: Prefer using the Tensor division operator or tf.divide which obey Python 3 division operator semantics.
This function divides x and y, forcing Python 2 semantics. That is, if x and y are both integers then the result will be an integer. This is in contrast to Python 3, where division with / is always a float while division with // is always an integer.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y returns the quotient of x and y.
__rfloordiv__ View source
__rfloordiv__(
y, x
)
Divides x / y elementwise, rounding toward the most negative integer. The same as tf.compat.v1.div(x,y) for integers, but uses tf.floor(tf.compat.v1.div(x,y)) for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by x // y floor division in Python 3 and in Python 2.7 with from __future__ import division. x and y must have the same type, and the result will have the same type as well.
Args
x Tensor numerator of real numeric type.
y Tensor denominator of real numeric type.
name A name for the operation (optional).
Returns x / y rounded down.
Raises
TypeError If the inputs are complex. __rmatmul__ View source
__rmatmul__(
y, x
)
Multiplies matrix a by matrix b, producing a * b. The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication dimensions, and any further outer dimensions specify matching batch size. Both matrices must be of the same type. The supported types are: float16, float32, float64, int32, complex64, complex128. Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to True. These are False by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding a_is_sparse or b_is_sparse flag to True. These are False by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes bfloat16 or float32. A simple 2-D tensor matrix multiplication:
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
a # 2-D tensor
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
b # 2-D tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[ 7, 8],
[ 9, 10],
[11, 12]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 58, 64],
[139, 154]], dtype=int32)>
A batch matrix multiplication with batch shape [2]:
a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
a # 3-D tensor
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]], dtype=int32)>
b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2])
b # 3-D tensor
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[13, 14],
[15, 16],
[17, 18]],
[[19, 20],
[21, 22],
[23, 24]]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[ 94, 100],
[229, 244]],
[[508, 532],
[697, 730]]], dtype=int32)>
Since python >= 3.5 the @ operator is supported (see PEP 465). In TensorFlow, it simply calls the tf.matmul() function, so the following lines are equivalent:
d = a @ b @ [[10], [11]]
d = tf.matmul(tf.matmul(a, b), [[10], [11]])
Args
a tf.Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
b tf.Tensor with same type and rank as a.
transpose_a If True, a is transposed before multiplication.
transpose_b If True, b is transposed before multiplication.
adjoint_a If True, a is conjugated and transposed before multiplication.
adjoint_b If True, b is conjugated and transposed before multiplication.
a_is_sparse If True, a is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
b_is_sparse If True, b is treated as a sparse matrix. Notice, this does not support tf.sparse.SparseTensor, it just makes optimizations that assume most values in a are zero. See tf.sparse.sparse_dense_matmul for some support for tf.sparse.SparseTensor multiplication.
name Name for the operation (optional).
Returns A tf.Tensor of the same type as a and b where each inner-most matrix is the product of the corresponding matrices in a and b, e.g. if all transpose or adjoint attributes are False: output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j]), for all indices i, j.
Note This is matrix product, not element-wise product.
Raises
ValueError If transpose_a and adjoint_a, or transpose_b and adjoint_b are both set to True. __rmod__ View source
__rmod__(
y, x
)
Returns element-wise remainder of division. When x < 0 xor y < 0 is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. floor(x / y) * y + mod(x, y) = x.
Note: math.floormod supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: int32, int64, uint64, bfloat16, half, float32, float64.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x.
__rmul__ View source
__rmul__(
y, x
)
Dispatches cwise mul for "DenseDense" and "DenseSparse". __ror__ View source
__ror__(
y, x
)
__rpow__ View source
__rpow__(
y, x
)
Computes the power of one value to another. Given a tensor x and a tensor y, this operation computes \(x^y\) for corresponding elements in x and y. For example: x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
Args
x A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
y A Tensor of type float16, float32, float64, int32, int64, complex64, or complex128.
name A name for the operation (optional).
Returns A Tensor.
__rsub__ View source
__rsub__(
y, x
)
Returns x - y element-wise.
Note: Subtract supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x.
__rtruediv__ View source
__rtruediv__(
y, x
)
Divides x / y elementwise (using Python 3 division operator semantics).
Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy).
Args
x Tensor numerator of numeric type.
y Tensor denominator of numeric type.
name A name for the operation (optional).
Returns x / y evaluated in floating point.
Raises
TypeError If x and y have different dtypes. __rxor__ View source
__rxor__(
y, x
)
__sub__ View source
__sub__(
x, y
)
Returns x - y element-wise.
Note: Subtract supports broadcasting. More about broadcasting here
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32.
y A Tensor. Must have the same type as x.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x.
__truediv__ View source
__truediv__(
x, y
)
Divides x / y elementwise (using Python 3 division operator semantics).
Note: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal x / y division in Python 3 and in Python 2.7 with from __future__ import division. If you want integer division that rounds down, use x // y or tf.math.floordiv. x and y must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to float32 for int8 and int16 and float64 for int32 and int64 (matching the behavior of Numpy).
Args
x Tensor numerator of numeric type.
y Tensor denominator of numeric type.
name A name for the operation (optional).
Returns x / y evaluated in floating point.
Raises
TypeError If x and y have different dtypes. __xor__ View source
__xor__(
x, y
) | tensorflow.variable |
tf.Variable.SaveSliceInfo View source on GitHub Information on how to save this Variable as a slice. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.Variable.SaveSliceInfo
tf.Variable.SaveSliceInfo(
full_name=None, full_shape=None, var_offset=None, var_shape=None,
save_slice_info_def=None, import_scope=None
)
Provides internal support for saving variables as slices of a larger variable. This API is not public and is subject to change. Available properties: full_name full_shape var_offset var_shape
Args
full_name Name of the full variable of which this Variable is a slice.
full_shape Shape of the full variable, as a list of int.
var_offset Offset of this Variable into the full variable, as a list of int.
var_shape Shape of this Variable, as a list of int.
save_slice_info_def SaveSliceInfoDef protocol buffer. If not None, recreates the SaveSliceInfo object its contents. save_slice_info_def and other arguments are mutually exclusive.
import_scope Optional string. Name scope to add. Only used when initializing from protocol buffer.
Attributes
spec Computes the spec string used for saving. Methods to_proto View source
to_proto(
export_scope=None
)
Returns a SaveSliceInfoDef() proto.
Args
export_scope Optional string. Name scope to remove.
Returns A SaveSliceInfoDef protocol buffer, or None if the Variable is not in the specified name scope. | tensorflow.variable.savesliceinfo |
tf.VariableAggregation View source on GitHub Indicates how a distributed variable will be aggregated. tf.distribute.Strategy distributes a model by making multiple copies (called "replicas") acting data-parallel on different elements of the input batch. When performing some variable-update operation, say var.assign_add(x), in a model, we need to resolve how to combine the different values for x computed in the different replicas.
NONE: This is the default, giving an error if you use a variable-update operation with multiple replicas.
SUM: Add the updates across replicas.
MEAN: Take the arithmetic mean ("average") of the updates across replicas.
ONLY_FIRST_REPLICA: This is for when every replica is performing the same update, but we only want to perform the update once. Used, e.g., for the global step counter.
Class Variables
MEAN tf.VariableAggregation
NONE tf.VariableAggregation
ONLY_FIRST_REPLICA tf.VariableAggregation
SUM tf.VariableAggregation | tensorflow.variableaggregation |
tf.VariableSynchronization View source on GitHub Indicates when a distributed variable will be synced. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.VariableSynchronization
AUTO: Indicates that the synchronization will be determined by the current DistributionStrategy (eg. With MirroredStrategy this would be ON_WRITE).
NONE: Indicates that there will only be one copy of the variable, so there is no need to sync.
ON_WRITE: Indicates that the variable will be updated across devices every time it is written.
ON_READ: Indicates that the variable will be aggregated across devices when it is read (eg. when checkpointing or when evaluating an op that uses the variable).
Class Variables
AUTO tf.VariableSynchronization
NONE tf.VariableSynchronization
ON_READ tf.VariableSynchronization
ON_WRITE tf.VariableSynchronization | tensorflow.variablesynchronization |
tf.variable_creator_scope View source on GitHub Scope which defines a variable creation function to be used by variable().
@tf_contextlib.contextmanager
tf.variable_creator_scope(
variable_creator
)
variable_creator is expected to be a function with the following signature: def variable_creator(next_creator, **kwargs)
The creator is supposed to eventually call the next_creator to create a variable if it does want to create a variable and not call Variable or ResourceVariable directly. This helps make creators composable. A creator may choose to create multiple variables, return already existing variables, or simply register that a variable was created and defer to the next creators in line. Creators can also modify the keyword arguments seen by the next creators. Custom getters in the variable scope will eventually resolve down to these custom creators when they do create variables. The valid keyword arguments in kwds are: initial_value: A Tensor, or Python object convertible to a Tensor, which is the initial value for the Variable. The initial value must have a shape specified unless validate_shape is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, dtype must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.) trainable: If True, the default, GradientTapes automatically watch uses of this Variable. validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. caching_device: Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not None, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through Switch and other conditional statements. name: Optional name for the variable. Defaults to 'Variable' and gets uniquified automatically. dtype: If set, initial_value will be converted to the given type. If None, either the datatype will be kept (if initial_value is a Tensor), or convert_to_tensor will decide. constraint: A constraint function to be applied to the variable after updates by some algorithms. synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class tf.VariableSynchronization. By default the synchronization is set to AUTO and the current DistributionStrategy chooses when to synchronize. aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class tf.VariableAggregation. This set may grow over time, so it's important the signature of creators is as mentioned above.
Args
variable_creator the passed creator
Yields A scope in which the creator is active | tensorflow.variable_creator_scope |
tf.vectorized_map View source on GitHub Parallel map on the list of tensors unpacked from elems on dimension 0. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.vectorized_map
tf.vectorized_map(
fn, elems, fallback_to_while_loop=True
)
This method works similar to tf.map_fn but is optimized to run much faster, possibly with a much larger memory footprint. The speedups are obtained by vectorization (see Auto-Vectorizing TensorFlow Graphs: Jacobians, Auto-Batching and Beyond). The idea behind vectorization is to semantically launch all the invocations of fn in parallel and fuse corresponding operations across all these invocations. This fusion is done statically at graph generation time and the generated code is often similar in performance to a manually fused version. Because tf.vectorized_map fully parallelizes the batch, this method will generally be significantly faster than using tf.map_fn, especially in eager mode. However this is an experimental feature and currently has a lot of limitations: There should be no data dependency between the different semantic invocations of fn, i.e. it should be safe to map the elements of the inputs in any order. Stateful kernels may mostly not be supported since these often imply a data dependency. We do support a limited set of such stateful kernels though (like RandomFoo, Variable operations like reads, etc).
fn has limited support for control flow operations.
fn should return nested structure of Tensors or Operations. However if an Operation is returned, it should have zero outputs. The shape and dtype of any intermediate or output tensors in the computation of fn should not depend on the input to fn. Examples: def outer_product(a):
return tf.tensordot(a, a, 0)
batch_size = 100
a = tf.ones((batch_size, 32, 32))
c = tf.vectorized_map(outer_product, a)
assert c.shape == (batch_size, 32, 32, 32, 32)
# Computing per-example gradients
batch_size = 10
num_features = 32
layer = tf.keras.layers.Dense(1)
def model_fn(arg):
with tf.GradientTape() as g:
inp, label = arg
inp = tf.expand_dims(inp, 0)
label = tf.expand_dims(label, 0)
prediction = layer(inp)
loss = tf.nn.l2_loss(label - prediction)
return g.gradient(loss, (layer.kernel, layer.bias))
inputs = tf.random.uniform([batch_size, num_features])
labels = tf.random.uniform([batch_size, 1])
per_example_gradients = tf.vectorized_map(model_fn, (inputs, labels))
assert per_example_gradients[0].shape == (batch_size, num_features, 1)
assert per_example_gradients[1].shape == (batch_size, 1)
Args
fn The callable to be performed. It accepts one argument, which will have the same (possibly nested) structure as elems, and returns a possibly nested structure of Tensors and Operations, which may be different than the structure of elems.
elems A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be mapped over by fn. The first dimensions of all elements must broadcast to a consistent value; equivalently, each element tensor must have first dimension of either B or 1, for some common batch size B >= 1.
fallback_to_while_loop If true, on failing to vectorize an operation, the unsupported op is wrapped in a tf.while_loop to execute the map iterations. Note that this fallback only happens for unsupported ops and other parts of fn are still vectorized. If false, on encountering an unsupported op, a ValueError is thrown. Note that the fallbacks can result in slowdowns since vectorization often yields speedup of one to two orders of magnitude.
Returns A tensor or (possibly nested) sequence of tensors. Each tensor packs the results of applying fn to tensors unpacked from elems along the first dimension, from first to last. Although they are less common as user-visible inputs and outputs, note that tensors of type tf.variant which represent tensor lists (for example from tf.raw_ops.TensorListFromTensor) are vectorized by stacking the list contents rather than the variant itself, and so the container tensor will have a scalar shape when returned rather than the usual stacked shape. This improves the performance of control flow gradient vectorization.
Raises
ValueError If vectorization fails and fallback_to_while_loop is False. | tensorflow.vectorized_map |
Module: tf.version Public API for tf.version namespace.
Other Members
COMPILER_VERSION '7.3.1 20180303'
GIT_VERSION 'v2.4.0-rc4-71-g582c8d236cb'
GRAPH_DEF_VERSION 561
GRAPH_DEF_VERSION_MIN_CONSUMER 0
GRAPH_DEF_VERSION_MIN_PRODUCER 0
VERSION '2.4.0' | tensorflow.version |
tf.where View source on GitHub Return the elements where condition is True (multiplexing x and y). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.where_v2
tf.where(
condition, x=None, y=None, name=None
)
This operator has two modes: in one mode both x and y are provided, in another mode neither are provided. condition is always expected to be a tf.Tensor of type bool. Retrieving indices of True elements If x and y are not provided (both are None): tf.where will return the indices of condition that are True, in the form of a 2-D tensor with shape (n, d). (Where n is the number of matching indices in condition, and d is the number of dimensions in condition). Indices are output in row-major order.
tf.where([True, False, False, True])
<tf.Tensor: shape=(2, 1), dtype=int64, numpy=
array([[0],
[3]])>
tf.where([[True, False], [False, True]])
<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[0, 0],
[1, 1]])>
tf.where([[[True, False], [False, True], [True, True]]])
<tf.Tensor: shape=(4, 3), dtype=int64, numpy=
array([[0, 0, 0],
[0, 1, 1],
[0, 2, 0],
[0, 2, 1]])>
Multiplexing between x and y
If x and y are provided (both have non-None values): tf.where will choose an output shape from the shapes of condition, x, and y that all three shapes are broadcastable to. The condition tensor acts as a mask that chooses whether the corresponding element / row in the output should be taken from x (if the element in condition is True) or y (if it is false).
tf.where([True, False, False, True], [1,2,3,4], [100,200,300,400])
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 200, 300, 4],
dtype=int32)>
tf.where([True, False, False, True], [1,2,3,4], [100])
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],
dtype=int32)>
tf.where([True, False, False, True], [1,2,3,4], 100)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],
dtype=int32)>
tf.where([True, False, False, True], 1, 100)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 1],
dtype=int32)>
tf.where(True, [1,2,3,4], 100)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4],
dtype=int32)>
tf.where(False, [1,2,3,4], 100)
<tf.Tensor: shape=(4,), dtype=int32, numpy=array([100, 100, 100, 100],
dtype=int32)>
Note that if the gradient of either branch of the tf.where generates a NaN, then the gradient of the entire tf.where will be NaN. A workaround is to use an inner tf.where to ensure the function has no asymptote, and to avoid computing a value whose gradient is NaN by replacing dangerous inputs with safe inputs. Instead of this,
y = tf.constant(-1, dtype=tf.float32)
tf.where(y > 0, tf.sqrt(y), y)
<tf.Tensor: shape=(), dtype=float32, numpy=-1.0>
Use this
tf.where(y > 0, tf.sqrt(tf.where(y > 0, y, 1)), y)
<tf.Tensor: shape=(), dtype=float32, numpy=-1.0>
Args
condition A tf.Tensor of type bool
x If provided, a Tensor which is of the same type as y, and has a shape broadcastable with condition and y.
y If provided, a Tensor which is of the same type as x, and has a shape broadcastable with condition and x.
name A name of the operation (optional).
Returns If x and y are provided: A Tensor with the same type as x and y, and shape that is broadcast from condition, x, and y. Otherwise, a Tensor with shape (num_true, dim_size(condition)).
Raises
ValueError When exactly one of x or y is non-None, or the shapes are not all broadcastable. | tensorflow.where |
tf.while_loop View source on GitHub Repeat body while the condition cond is true. (deprecated argument values)
tf.while_loop(
cond, body, loop_vars, shape_invariants=None, parallel_iterations=10,
back_prop=True, swap_memory=False, maximum_iterations=None, name=None
)
Warning: SOME ARGUMENT VALUES ARE DEPRECATED: (back_prop=False). They will be removed in a future version. Instructions for updating: back_prop=False is deprecated. Consider using tf.stop_gradient instead. Instead of: results = tf.while_loop(c, b, vars, back_prop=False) Use: results = tf.nest.map_structure(tf.stop_gradient, tf.while_loop(c, b, vars)) cond is a callable returning a boolean scalar tensor. body is a callable returning a (possibly nested) tuple, namedtuple or list of tensors of the same arity (length and structure) and types as loop_vars. loop_vars is a (possibly nested) tuple, namedtuple or list of tensors that is passed to both cond and body. cond and body both take as many arguments as there are loop_vars. In addition to regular Tensors or IndexedSlices, the body may accept and return TensorArray objects. The flows of the TensorArray objects will be appropriately forwarded between loops and during gradient calculations. Note that while_loop calls cond and body exactly once (inside the call to while_loop, and not at all during Session.run()). while_loop stitches together the graph fragments created during the cond and body calls with some additional graph nodes to create the graph flow that repeats body until cond returns false. For correctness, tf.while_loop() strictly enforces shape invariants for the loop variables. A shape invariant is a (possibly partial) shape that is unchanged across the iterations of the loop. An error will be raised if the shape of a loop variable after an iteration is determined to be more general than or incompatible with its shape invariant. For example, a shape of [11, None] is more general than a shape of [11, 17], and [11, 21] is not compatible with [11, 17]. By default (if the argument shape_invariants is not specified), it is assumed that the initial shape of each tensor in loop_vars is the same in every iteration. The shape_invariants argument allows the caller to specify a less specific shape invariant for each loop variable, which is needed if the shape varies between iterations. The tf.Tensor.set_shape function may also be used in the body function to indicate that the output loop variable has a particular shape. The shape invariant for SparseTensor and IndexedSlices are treated specially as follows: a) If a loop variable is a SparseTensor, the shape invariant must be TensorShape([r]) where r is the rank of the dense tensor represented by the sparse tensor. It means the shapes of the three tensors of the SparseTensor are ([None], [None, r], [r]). NOTE: The shape invariant here is the shape of the SparseTensor.dense_shape property. It must be the shape of a vector. b) If a loop variable is an IndexedSlices, the shape invariant must be a shape invariant of the values tensor of the IndexedSlices. It means the shapes of the three tensors of the IndexedSlices are (shape, [shape[0]], [shape.ndims]). while_loop implements non-strict semantics, enabling multiple iterations to run in parallel. The maximum number of parallel iterations can be controlled by parallel_iterations, which gives users some control over memory consumption and execution order. For correct programs, while_loop should return the same result for any parallel_iterations > 0. For training, TensorFlow stores the tensors that are produced in the forward inference and are needed in back propagation. These tensors are a main source of memory consumption and often cause OOM errors when training on GPUs. When the flag swap_memory is true, we swap out these tensors from GPU to CPU. This for example allows us to train RNN models with very long sequences and large batches.
Args
cond A callable that represents the termination condition of the loop.
body A callable that represents the loop body.
loop_vars A (possibly nested) tuple, namedtuple or list of numpy array, Tensor, and TensorArray objects.
shape_invariants The shape invariants for the loop variables.
parallel_iterations The number of iterations allowed to run in parallel. It must be a positive integer.
back_prop (optional) Deprecated. False disables support for back propagation. Prefer using tf.stop_gradient instead.
swap_memory Whether GPU-CPU memory swap is enabled for this loop.
maximum_iterations Optional maximum number of iterations of the while loop to run. If provided, the cond output is AND-ed with an additional condition ensuring the number of iterations executed is no greater than maximum_iterations.
name Optional name prefix for the returned tensors.
Returns The output tensors for the loop variables after the loop. The return value has the same structure as loop_vars.
Raises
TypeError if cond or body is not callable.
ValueError if loop_vars is empty. Example: i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: (tf.add(i, 1), )
r = tf.while_loop(c, b, [i])
Example with nesting and a namedtuple: import collections
Pair = collections.namedtuple('Pair', 'j, k')
ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2)))
c = lambda i, p: i < 10
b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k)))
ijk_final = tf.while_loop(c, b, ijk_0)
Example using shape_invariants: i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 10
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
tf.while_loop(
c, b, loop_vars=[i0, m0],
shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])
Example which demonstrates non-strict semantics: In the following example, the final value of the counter i does not depend on x. So the while_loop can increment the counter parallel to updates of x. However, because the loop counter at one loop iteration depends on the value at the previous iteration, the loop counter itself cannot be incremented in parallel. Hence if we just want the final value of the counter (which we print on the line print(sess.run(i))), then x will never be incremented, but the counter will be updated on a single thread. Conversely, if we want the value of the output (which we print on the line print(sess.run(out).shape)), then the counter may be incremented on its own thread, while x can be incremented in parallel on a separate thread. In the extreme case, it is conceivable that the thread incrementing the counter runs until completion before x is incremented even a single time. The only thing that can never happen is that the thread updating x can never get ahead of the counter thread because the thread incrementing x depends on the value of the counter. import tensorflow as tf
n = 10000
x = tf.constant(list(range(n)))
c = lambda i, x: i < n
b = lambda i, x: (tf.compat.v1.Print(i + 1, [i]), tf.compat.v1.Print(x + 1,
[i], "x:"))
i, out = tf.while_loop(c, b, (0, x))
with tf.compat.v1.Session() as sess:
print(sess.run(i)) # prints [0] ... [9999]
# The following line may increment the counter and x in parallel.
# The counter thread may get ahead of the other thread, but not the
# other way around. So you may see things like
# [9996] x:[9987]
# meaning that the counter thread is on iteration 9996,
# while the other thread is on iteration 9987
print(sess.run(out).shape) | tensorflow.while_loop |
Module: tf.xla Public API for tf.xla namespace. Modules experimental module: Public API for tf.xla.experimental namespace. | tensorflow.xla |
Module: tf.xla.experimental Public API for tf.xla.experimental namespace. Functions compile(...): Builds an operator that compiles and runs computation with XLA. (deprecated) jit_scope(...): Enable or disable JIT compilation of operators within the scope. | tensorflow.xla.experimental |
tf.xla.experimental.compile View source on GitHub Builds an operator that compiles and runs computation with XLA. (deprecated) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.xla.experimental.compile
tf.xla.experimental.compile(
computation, inputs=None
)
Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: xla.experimental.compile is deprecated. Consider using tf.function(experimental_compile=True)
Note: In eager mode, computation will have @tf.function semantics.
Args
computation A Python function that builds a computation to apply to the input. If the function takes n inputs, 'inputs' should be a list of n tensors. computation may return a list of operations and tensors. Tensors must come before operations in the returned list. The return value of compile is a list of tensors corresponding to the tensors from the output of computation. All Operations returned from computation will be executed when evaluating any of the returned output tensors.
inputs A list of inputs or None (equivalent to an empty list). Each input can be a nested structure containing values that are convertible to tensors. Note that passing an N-dimension list of compatible values will result in a N-dimension list of scalar tensors rather than a single Rank-N tensors. If you need different behavior, convert part of inputs to tensors with tf.convert_to_tensor.
Returns Same data structure as if computation(*inputs) is called directly with some exceptions for correctness. Exceptions include: 1) None output: a NoOp would be returned which control-depends on computation. 2) Single value output: A tuple containing the value would be returned. 3) Operation-only outputs: a NoOp would be returned which control-depends on computation.
Raises
RuntimeError if called when eager execution is enabled. Known issues: When a tf.random operation is built with XLA, the implementation doesn't pass the user provided seed to the XLA compiler. As such, the XLA compiler generates a random number and uses it as a seed when compiling the operation. This implementation causes a violation of the Tensorflow defined semantics in two aspects. First, changing the value of the user defined seed doesn't change the numbers generated by the operation. Second, when a seed is not specified, running the program multiple times will generate the same numbers. | tensorflow.xla.experimental.compile |
tf.xla.experimental.jit_scope View source on GitHub Enable or disable JIT compilation of operators within the scope. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.xla.experimental.jit_scope
@contextlib.contextmanager
tf.xla.experimental.jit_scope(
compile_ops=True, separate_compiled_gradients=False
)
Note: This is an experimental feature.
The compilation is a hint and only supported on a best-effort basis. Example usage: with tf.xla.experimental.jit_scope():
c = tf.matmul(a, b) # compiled
with tf.xla.experimental.jit_scope(compile_ops=False):
d = tf.matmul(a, c) # not compiled
with tf.xla.experimental.jit_scope(
compile_ops=lambda node_def: 'matmul' in node_def.op.lower()):
e = tf.matmul(a, b) + d # matmul is compiled, the addition is not.
Example of separate_compiled_gradients: # In the example below, the computations for f, g and h will all be compiled
# in separate scopes.
with tf.xla.experimental.jit_scope(
separate_compiled_gradients=True):
f = tf.matmul(a, b)
g = tf.gradients([f], [a, b], name='mygrads1')
h = tf.gradients([f], [a, b], name='mygrads2')
Ops that are not in the scope may be clustered and compiled with ops in the scope with compile_ops=True, while the ops in the scope with compile_ops=False will never be compiled. For example: # In the example below, x and loss may be clustered and compiled together,
# while y will not be compiled.
with tf.xla.experimental.jit_scope():
x = tf.matmul(a, b)
with tf.xla.experimental.jit_scope(compile_ops=False):
y = tf.matmul(c, d)
loss = x + y
If you want to only compile the ops in the scope with compile_ops=True, consider adding an outer jit_scope(compile_ops=False): # In the example below, only x will be compiled.
with tf.xla.experimental.jit_scope(compile_ops=False):
with tf.xla.experimental.jit_scope():
x = tf.matmul(a, b)
y = tf.matmul(c, d)
loss = x + y
Args
compile_ops Whether to enable or disable compilation in the scope. Either a Python bool, or a callable that accepts the parameter node_def and returns a python bool.
separate_compiled_gradients If true put each gradient subgraph into a separate compilation scope. This gives fine-grained control over which portions of the graph will be compiled as a single unit. Compiling gradients separately may yield better performance for some graphs. The scope is named based on the scope of the forward computation as well as the name of the gradients. As a result, the gradients will be compiled in a scope that is separate from both the forward computation, and from other gradients.
Raises
RuntimeError if called when eager execution is enabled.
Yields The current scope, enabling or disabling compilation. | tensorflow.xla.experimental.jit_scope |
tf.zeros View source on GitHub Creates a tensor with all elements set to zero. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.zeros
tf.zeros(
shape, dtype=tf.dtypes.float32, name=None
)
See also tf.zeros_like, tf.ones, tf.fill, tf.eye. This operation returns a tensor of type dtype with shape shape and all elements set to zero.
tf.zeros([3, 4], tf.int32)
<tf.Tensor: shape=(3, 4), dtype=int32, numpy=
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int32)>
Args
shape A list of integers, a tuple of integers, or a 1-D Tensor of type int32.
dtype The DType of an element in the resulting Tensor.
name Optional string. A name for the operation.
Returns A Tensor with all elements set to zero. | tensorflow.zeros |
tf.zeros_initializer View source on GitHub Initializer that generates tensors initialized to 0. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Examples:
def make_variables(k, initializer):
return (tf.Variable(initializer(shape=[k], dtype=tf.float32)),
tf.Variable(initializer(shape=[k, k], dtype=tf.float32)))
v1, v2 = make_variables(3, tf.zeros_initializer())
v1
<tf.Variable ... shape=(3,) ... numpy=array([0., 0., 0.], dtype=float32)>
v2
<tf.Variable ... shape=(3, 3) ... numpy=
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=float32)>
make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.))
(<tf.Variable...shape=(4,) dtype=float32...>, <tf.Variable...shape=(4, 4) ...
Methods from_config View source
@classmethod
from_config(
config
)
Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
Args
config A Python dictionary. It will typically be the output of get_config.
Returns An Initializer instance.
get_config View source
get_config()
Returns the configuration of the initializer as a JSON-serializable dict.
Returns A JSON-serializable Python dict.
__call__ View source
__call__(
shape, dtype=tf.dtypes.float32, **kwargs
)
Returns a tensor object initialized as specified by the initializer.
Args
shape Shape of the tensor.
dtype Optional dtype of the tensor. Only numeric or boolean dtypes are supported.
**kwargs Additional keyword arguments.
Raises
ValuesError If the dtype is not numeric or boolean. | tensorflow.zeros_initializer |
tf.zeros_like View source on GitHub Creates a tensor with all elements set to zero.
tf.zeros_like(
input, dtype=None, name=None
)
See also tf.zeros. Given a single tensor or array-like object (input), this operation returns a tensor of the same type and shape as input with all elements set to zero. Optionally, you can use dtype to specify a new type for the returned tensor. Examples:
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.zeros_like(tensor)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 0],
[0, 0, 0]], dtype=int32)>
tf.zeros_like(tensor, dtype=tf.float32)
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0., 0., 0.],
[0., 0., 0.]], dtype=float32)>
tf.zeros_like([[1, 2, 3], [4, 5, 6]])
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 0],
[0, 0, 0]], dtype=int32)>
Args
input A Tensor or array-like object.
dtype A type for the returned Tensor. Must be float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128, bool or string (optional).
name A name for the operation (optional).
Returns A Tensor with all elements set to zero. | tensorflow.zeros_like |
torch The torch package contains data structures for multi-dimensional tensors and defines mathematical operations over these tensors. Additionally, it provides many utilities for efficient serializing of Tensors and arbitrary types, and other useful utilities. It has a CUDA counterpart, that enables you to run your tensor computations on an NVIDIA GPU with compute capability >= 3.0 Tensors
is_tensor
Returns True if obj is a PyTorch tensor.
is_storage
Returns True if obj is a PyTorch storage object.
is_complex
Returns True if the data type of input is a complex data type i.e., one of torch.complex64, and torch.complex128.
is_floating_point
Returns True if the data type of input is a floating point data type i.e., one of torch.float64, torch.float32, torch.float16, and torch.bfloat16.
is_nonzero
Returns True if the input is a single element tensor which is not equal to zero after type conversions.
set_default_dtype
Sets the default floating point dtype to d.
get_default_dtype
Get the current default floating point torch.dtype.
set_default_tensor_type
Sets the default torch.Tensor type to floating point tensor type t.
numel
Returns the total number of elements in the input tensor.
set_printoptions
Set options for printing.
set_flush_denormal
Disables denormal floating numbers on CPU. Creation Ops Note Random sampling creation ops are listed under Random sampling and include: torch.rand() torch.rand_like() torch.randn() torch.randn_like() torch.randint() torch.randint_like() torch.randperm() You may also use torch.empty() with the In-place random sampling methods to create torch.Tensor s with values sampled from a broader range of distributions.
tensor
Constructs a tensor with data.
sparse_coo_tensor
Constructs a sparse tensor in COO(rdinate) format with specified values at the given indices.
as_tensor
Convert the data into a torch.Tensor.
as_strided
Create a view of an existing torch.Tensor input with specified size, stride and storage_offset.
from_numpy
Creates a Tensor from a numpy.ndarray.
zeros
Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.
zeros_like
Returns a tensor filled with the scalar value 0, with the same size as input.
ones
Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.
ones_like
Returns a tensor filled with the scalar value 1, with the same size as input.
arange
Returns a 1-D tensor of size ⌈end−startstep⌉\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil with values from the interval [start, end) taken with common difference step beginning from start.
range
Returns a 1-D tensor of size ⌊end−startstep⌋+1\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1 with values from start to end with step step.
linspace
Creates a one-dimensional tensor of size steps whose values are evenly spaced from start to end, inclusive.
logspace
Creates a one-dimensional tensor of size steps whose values are evenly spaced from basestart{{\text{{base}}}}^{{\text{{start}}}} to baseend{{\text{{base}}}}^{{\text{{end}}}} , inclusive, on a logarithmic scale with base base.
eye
Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
empty
Returns a tensor filled with uninitialized data.
empty_like
Returns an uninitialized tensor with the same size as input.
empty_strided
Returns a tensor filled with uninitialized data.
full
Creates a tensor of size size filled with fill_value.
full_like
Returns a tensor with the same size as input filled with fill_value.
quantize_per_tensor
Converts a float tensor to a quantized tensor with given scale and zero point.
quantize_per_channel
Converts a float tensor to a per-channel quantized tensor with given scales and zero points.
dequantize
Returns an fp32 Tensor by dequantizing a quantized Tensor
complex
Constructs a complex tensor with its real part equal to real and its imaginary part equal to imag.
polar
Constructs a complex tensor whose elements are Cartesian coordinates corresponding to the polar coordinates with absolute value abs and angle angle.
heaviside
Computes the Heaviside step function for each element in input. Indexing, Slicing, Joining, Mutating Ops
cat
Concatenates the given sequence of seq tensors in the given dimension.
chunk
Splits a tensor into a specific number of chunks.
column_stack
Creates a new tensor by horizontally stacking the tensors in tensors.
dstack
Stack tensors in sequence depthwise (along third axis).
gather
Gathers values along an axis specified by dim.
hstack
Stack tensors in sequence horizontally (column wise).
index_select
Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a LongTensor.
masked_select
Returns a new 1-D tensor which indexes the input tensor according to the boolean mask mask which is a BoolTensor.
movedim
Moves the dimension(s) of input at the position(s) in source to the position(s) in destination.
moveaxis
Alias for torch.movedim().
narrow
Returns a new tensor that is a narrowed version of input tensor.
nonzero
reshape
Returns a tensor with the same data and number of elements as input, but with the specified shape.
row_stack
Alias of torch.vstack().
scatter
Out-of-place version of torch.Tensor.scatter_()
scatter_add
Out-of-place version of torch.Tensor.scatter_add_()
split
Splits the tensor into chunks.
squeeze
Returns a tensor with all the dimensions of input of size 1 removed.
stack
Concatenates a sequence of tensors along a new dimension.
swapaxes
Alias for torch.transpose().
swapdims
Alias for torch.transpose().
t
Expects input to be <= 2-D tensor and transposes dimensions 0 and 1.
take
Returns a new tensor with the elements of input at the given indices.
tensor_split
Splits a tensor into multiple sub-tensors, all of which are views of input, along dimension dim according to the indices or number of sections specified by indices_or_sections.
tile
Constructs a tensor by repeating the elements of input.
transpose
Returns a tensor that is a transposed version of input.
unbind
Removes a tensor dimension.
unsqueeze
Returns a new tensor with a dimension of size one inserted at the specified position.
vstack
Stack tensors in sequence vertically (row wise).
where
Return a tensor of elements selected from either x or y, depending on condition. Generators
Generator
Creates and returns a generator object that manages the state of the algorithm which produces pseudo random numbers. Random sampling
seed
Sets the seed for generating random numbers to a non-deterministic random number.
manual_seed
Sets the seed for generating random numbers.
initial_seed
Returns the initial seed for generating random numbers as a Python long.
get_rng_state
Returns the random number generator state as a torch.ByteTensor.
set_rng_state
Sets the random number generator state.
torch.default_generator Returns the default CPU torch.Generator
bernoulli
Draws binary random numbers (0 or 1) from a Bernoulli distribution.
multinomial
Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution located in the corresponding row of tensor input.
normal
Returns a tensor of random numbers drawn from separate normal distributions whose mean and standard deviation are given.
poisson
Returns a tensor of the same size as input with each element sampled from a Poisson distribution with rate parameter given by the corresponding element in input i.e.,
rand
Returns a tensor filled with random numbers from a uniform distribution on the interval [0,1)[0, 1)
rand_like
Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [0,1)[0, 1) .
randint
Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive).
randint_like
Returns a tensor with the same shape as Tensor input filled with random integers generated uniformly between low (inclusive) and high (exclusive).
randn
Returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1 (also called the standard normal distribution).
randn_like
Returns a tensor with the same size as input that is filled with random numbers from a normal distribution with mean 0 and variance 1.
randperm
Returns a random permutation of integers from 0 to n - 1. In-place random sampling There are a few more in-place random sampling functions defined on Tensors as well. Click through to refer to their documentation:
torch.Tensor.bernoulli_() - in-place version of torch.bernoulli()
torch.Tensor.cauchy_() - numbers drawn from the Cauchy distribution
torch.Tensor.exponential_() - numbers drawn from the exponential distribution
torch.Tensor.geometric_() - elements drawn from the geometric distribution
torch.Tensor.log_normal_() - samples from the log-normal distribution
torch.Tensor.normal_() - in-place version of torch.normal()
torch.Tensor.random_() - numbers sampled from the discrete uniform distribution
torch.Tensor.uniform_() - numbers sampled from the continuous uniform distribution Quasi-random sampling
quasirandom.SobolEngine The torch.quasirandom.SobolEngine is an engine for generating (scrambled) Sobol sequences. Serialization
save
Saves an object to a disk file.
load
Loads an object saved with torch.save() from a file. Parallelism
get_num_threads
Returns the number of threads used for parallelizing CPU operations
set_num_threads
Sets the number of threads used for intraop parallelism on CPU.
get_num_interop_threads
Returns the number of threads used for inter-op parallelism on CPU (e.g.
set_num_interop_threads
Sets the number of threads used for interop parallelism (e.g. Locally disabling gradient computation The context managers torch.no_grad(), torch.enable_grad(), and torch.set_grad_enabled() are helpful for locally disabling and enabling gradient computation. See Locally disabling gradient computation for more details on their usage. These context managers are thread local, so they won’t work if you send work to another thread using the threading module, etc. Examples: >>> x = torch.zeros(1, requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
... y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True) # this can also be used as a function
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False
no_grad
Context-manager that disabled gradient calculation.
enable_grad
Context-manager that enables gradient calculation.
set_grad_enabled
Context-manager that sets gradient calculation to on or off. Math operations Pointwise Ops
abs
Computes the absolute value of each element in input.
absolute
Alias for torch.abs()
acos
Computes the inverse cosine of each element in input.
arccos
Alias for torch.acos().
acosh
Returns a new tensor with the inverse hyperbolic cosine of the elements of input.
arccosh
Alias for torch.acosh().
add
Adds the scalar other to each element of the input input and returns a new resulting tensor.
addcdiv
Performs the element-wise division of tensor1 by tensor2, multiply the result by the scalar value and add it to input.
addcmul
Performs the element-wise multiplication of tensor1 by tensor2, multiply the result by the scalar value and add it to input.
angle
Computes the element-wise angle (in radians) of the given input tensor.
asin
Returns a new tensor with the arcsine of the elements of input.
arcsin
Alias for torch.asin().
asinh
Returns a new tensor with the inverse hyperbolic sine of the elements of input.
arcsinh
Alias for torch.asinh().
atan
Returns a new tensor with the arctangent of the elements of input.
arctan
Alias for torch.atan().
atanh
Returns a new tensor with the inverse hyperbolic tangent of the elements of input.
arctanh
Alias for torch.atanh().
atan2
Element-wise arctangent of inputi/otheri\text{input}_{i} / \text{other}_{i} with consideration of the quadrant.
bitwise_not
Computes the bitwise NOT of the given input tensor.
bitwise_and
Computes the bitwise AND of input and other.
bitwise_or
Computes the bitwise OR of input and other.
bitwise_xor
Computes the bitwise XOR of input and other.
ceil
Returns a new tensor with the ceil of the elements of input, the smallest integer greater than or equal to each element.
clamp
Clamp all elements in input into the range [ min, max ].
clip
Alias for torch.clamp().
conj
Computes the element-wise conjugate of the given input tensor.
copysign
Create a new floating-point tensor with the magnitude of input and the sign of other, elementwise.
cos
Returns a new tensor with the cosine of the elements of input.
cosh
Returns a new tensor with the hyperbolic cosine of the elements of input.
deg2rad
Returns a new tensor with each of the elements of input converted from angles in degrees to radians.
div
Divides each element of the input input by the corresponding element of other.
divide
Alias for torch.div().
digamma
Computes the logarithmic derivative of the gamma function on input.
erf
Computes the error function of each element.
erfc
Computes the complementary error function of each element of input.
erfinv
Computes the inverse error function of each element of input.
exp
Returns a new tensor with the exponential of the elements of the input tensor input.
exp2
Computes the base two exponential function of input.
expm1
Returns a new tensor with the exponential of the elements minus 1 of input.
fake_quantize_per_channel_affine
Returns a new tensor with the data in input fake quantized per channel using scale, zero_point, quant_min and quant_max, across the channel specified by axis.
fake_quantize_per_tensor_affine
Returns a new tensor with the data in input fake quantized using scale, zero_point, quant_min and quant_max.
fix
Alias for torch.trunc()
float_power
Raises input to the power of exponent, elementwise, in double precision.
floor
Returns a new tensor with the floor of the elements of input, the largest integer less than or equal to each element.
floor_divide
fmod
Computes the element-wise remainder of division.
frac
Computes the fractional portion of each element in input.
imag
Returns a new tensor containing imaginary values of the self tensor.
ldexp
Multiplies input by 2**:attr:other.
lerp
Does a linear interpolation of two tensors start (given by input) and end based on a scalar or tensor weight and returns the resulting out tensor.
lgamma
Computes the logarithm of the gamma function on input.
log
Returns a new tensor with the natural logarithm of the elements of input.
log10
Returns a new tensor with the logarithm to the base 10 of the elements of input.
log1p
Returns a new tensor with the natural logarithm of (1 + input).
log2
Returns a new tensor with the logarithm to the base 2 of the elements of input.
logaddexp
Logarithm of the sum of exponentiations of the inputs.
logaddexp2
Logarithm of the sum of exponentiations of the inputs in base-2.
logical_and
Computes the element-wise logical AND of the given input tensors.
logical_not
Computes the element-wise logical NOT of the given input tensor.
logical_or
Computes the element-wise logical OR of the given input tensors.
logical_xor
Computes the element-wise logical XOR of the given input tensors.
logit
Returns a new tensor with the logit of the elements of input.
hypot
Given the legs of a right triangle, return its hypotenuse.
i0
Computes the zeroth order modified Bessel function of the first kind for each element of input.
igamma
Computes the regularized lower incomplete gamma function:
igammac
Computes the regularized upper incomplete gamma function:
mul
Multiplies each element of the input input with the scalar other and returns a new resulting tensor.
multiply
Alias for torch.mul().
mvlgamma
Computes the multivariate log-gamma function) with dimension pp element-wise, given by
nan_to_num
Replaces NaN, positive infinity, and negative infinity values in input with the values specified by nan, posinf, and neginf, respectively.
neg
Returns a new tensor with the negative of the elements of input.
negative
Alias for torch.neg()
nextafter
Return the next floating-point value after input towards other, elementwise.
polygamma
Computes the nthn^{th} derivative of the digamma function on input.
pow
Takes the power of each element in input with exponent and returns a tensor with the result.
rad2deg
Returns a new tensor with each of the elements of input converted from angles in radians to degrees.
real
Returns a new tensor containing real values of the self tensor.
reciprocal
Returns a new tensor with the reciprocal of the elements of input
remainder
Computes the element-wise remainder of division.
round
Returns a new tensor with each of the elements of input rounded to the closest integer.
rsqrt
Returns a new tensor with the reciprocal of the square-root of each of the elements of input.
sigmoid
Returns a new tensor with the sigmoid of the elements of input.
sign
Returns a new tensor with the signs of the elements of input.
sgn
For complex tensors, this function returns a new tensor whose elemants have the same angle as that of the elements of input and absolute value 1.
signbit
Tests if each element of input has its sign bit set (is less than zero) or not.
sin
Returns a new tensor with the sine of the elements of input.
sinc
Computes the normalized sinc of input.
sinh
Returns a new tensor with the hyperbolic sine of the elements of input.
sqrt
Returns a new tensor with the square-root of the elements of input.
square
Returns a new tensor with the square of the elements of input.
sub
Subtracts other, scaled by alpha, from input.
subtract
Alias for torch.sub().
tan
Returns a new tensor with the tangent of the elements of input.
tanh
Returns a new tensor with the hyperbolic tangent of the elements of input.
true_divide
Alias for torch.div() with rounding_mode=None.
trunc
Returns a new tensor with the truncated integer values of the elements of input.
xlogy
Computes input * log(other) with the following cases. Reduction Ops
argmax
Returns the indices of the maximum value of all elements in the input tensor.
argmin
Returns the indices of the minimum value(s) of the flattened tensor or along a dimension
amax
Returns the maximum value of each slice of the input tensor in the given dimension(s) dim.
amin
Returns the minimum value of each slice of the input tensor in the given dimension(s) dim.
all
Tests if all elements in input evaluate to True.
any
param input
the input tensor.
max
Returns the maximum value of all elements in the input tensor.
min
Returns the minimum value of all elements in the input tensor.
dist
Returns the p-norm of (input - other)
logsumexp
Returns the log of summed exponentials of each row of the input tensor in the given dimension dim.
mean
Returns the mean value of all elements in the input tensor.
median
Returns the median of the values in input.
nanmedian
Returns the median of the values in input, ignoring NaN values.
mode
Returns a namedtuple (values, indices) where values is the mode value of each row of the input tensor in the given dimension dim, i.e.
norm
Returns the matrix norm or vector norm of a given tensor.
nansum
Returns the sum of all elements, treating Not a Numbers (NaNs) as zero.
prod
Returns the product of all elements in the input tensor.
quantile
Returns the q-th quantiles of all elements in the input tensor, doing a linear interpolation when the q-th quantile lies between two data points.
nanquantile
This is a variant of torch.quantile() that “ignores” NaN values, computing the quantiles q as if NaN values in input did not exist.
std
Returns the standard-deviation of all elements in the input tensor.
std_mean
Returns the standard-deviation and mean of all elements in the input tensor.
sum
Returns the sum of all elements in the input tensor.
unique
Returns the unique elements of the input tensor.
unique_consecutive
Eliminates all but the first element from every consecutive group of equivalent elements.
var
Returns the variance of all elements in the input tensor.
var_mean
Returns the variance and mean of all elements in the input tensor.
count_nonzero
Counts the number of non-zero values in the tensor input along the given dim. Comparison Ops
allclose
This function checks if all input and other satisfy the condition:
argsort
Returns the indices that sort a tensor along a given dimension in ascending order by value.
eq
Computes element-wise equality
equal
True if two tensors have the same size and elements, False otherwise.
ge
Computes input≥other\text{input} \geq \text{other} element-wise.
greater_equal
Alias for torch.ge().
gt
Computes input>other\text{input} > \text{other} element-wise.
greater
Alias for torch.gt().
isclose
Returns a new tensor with boolean elements representing if each element of input is “close” to the corresponding element of other.
isfinite
Returns a new tensor with boolean elements representing if each element is finite or not.
isinf
Tests if each element of input is infinite (positive or negative infinity) or not.
isposinf
Tests if each element of input is positive infinity or not.
isneginf
Tests if each element of input is negative infinity or not.
isnan
Returns a new tensor with boolean elements representing if each element of input is NaN or not.
isreal
Returns a new tensor with boolean elements representing if each element of input is real-valued or not.
kthvalue
Returns a namedtuple (values, indices) where values is the k th smallest element of each row of the input tensor in the given dimension dim.
le
Computes input≤other\text{input} \leq \text{other} element-wise.
less_equal
Alias for torch.le().
lt
Computes input<other\text{input} < \text{other} element-wise.
less
Alias for torch.lt().
maximum
Computes the element-wise maximum of input and other.
minimum
Computes the element-wise minimum of input and other.
fmax
Computes the element-wise maximum of input and other.
fmin
Computes the element-wise minimum of input and other.
ne
Computes input≠other\text{input} \neq \text{other} element-wise.
not_equal
Alias for torch.ne().
sort
Sorts the elements of the input tensor along a given dimension in ascending order by value.
topk
Returns the k largest elements of the given input tensor along a given dimension.
msort
Sorts the elements of the input tensor along its first dimension in ascending order by value. Spectral Ops
stft
Short-time Fourier transform (STFT).
istft
Inverse short time Fourier Transform.
bartlett_window
Bartlett window function.
blackman_window
Blackman window function.
hamming_window
Hamming window function.
hann_window
Hann window function.
kaiser_window
Computes the Kaiser window with window length window_length and shape parameter beta. Other Operations
atleast_1d
Returns a 1-dimensional view of each input tensor with zero dimensions.
atleast_2d
Returns a 2-dimensional view of each input tensor with zero dimensions.
atleast_3d
Returns a 3-dimensional view of each input tensor with zero dimensions.
bincount
Count the frequency of each value in an array of non-negative ints.
block_diag
Create a block diagonal matrix from provided tensors.
broadcast_tensors
Broadcasts the given tensors according to Broadcasting semantics.
broadcast_to
Broadcasts input to the shape shape.
broadcast_shapes
Similar to broadcast_tensors() but for shapes.
bucketize
Returns the indices of the buckets to which each value in the input belongs, where the boundaries of the buckets are set by boundaries.
cartesian_prod
Do cartesian product of the given sequence of tensors.
cdist
Computes batched the p-norm distance between each pair of the two collections of row vectors.
clone
Returns a copy of input.
combinations
Compute combinations of length rr of the given tensor.
cross
Returns the cross product of vectors in dimension dim of input and other.
cummax
Returns a namedtuple (values, indices) where values is the cumulative maximum of elements of input in the dimension dim.
cummin
Returns a namedtuple (values, indices) where values is the cumulative minimum of elements of input in the dimension dim.
cumprod
Returns the cumulative product of elements of input in the dimension dim.
cumsum
Returns the cumulative sum of elements of input in the dimension dim.
diag
If input is a vector (1-D tensor), then returns a 2-D square tensor
diag_embed
Creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) are filled by input.
diagflat
If input is a vector (1-D tensor), then returns a 2-D square tensor
diagonal
Returns a partial view of input with the its diagonal elements with respect to dim1 and dim2 appended as a dimension at the end of the shape.
diff
Computes the n-th forward difference along the given dimension.
einsum
Sums the product of the elements of the input operands along dimensions specified using a notation based on the Einstein summation convention.
flatten
Flattens input by reshaping it into a one-dimensional tensor.
flip
Reverse the order of a n-D tensor along given axis in dims.
fliplr
Flip tensor in the left/right direction, returning a new tensor.
flipud
Flip tensor in the up/down direction, returning a new tensor.
kron
Computes the Kronecker product, denoted by ⊗\otimes , of input and other.
rot90
Rotate a n-D tensor by 90 degrees in the plane specified by dims axis.
gcd
Computes the element-wise greatest common divisor (GCD) of input and other.
histc
Computes the histogram of a tensor.
meshgrid
Take NN tensors, each of which can be either scalar or 1-dimensional vector, and create NN N-dimensional grids, where the ii th grid is defined by expanding the ii th input over dimensions defined by other inputs.
lcm
Computes the element-wise least common multiple (LCM) of input and other.
logcumsumexp
Returns the logarithm of the cumulative summation of the exponentiation of elements of input in the dimension dim.
ravel
Return a contiguous flattened tensor.
renorm
Returns a tensor where each sub-tensor of input along dimension dim is normalized such that the p-norm of the sub-tensor is lower than the value maxnorm
repeat_interleave
Repeat elements of a tensor.
roll
Roll the tensor along the given dimension(s).
searchsorted
Find the indices from the innermost dimension of sorted_sequence such that, if the corresponding values in values were inserted before the indices, the order of the corresponding innermost dimension within sorted_sequence would be preserved.
tensordot
Returns a contraction of a and b over multiple dimensions.
trace
Returns the sum of the elements of the diagonal of the input 2-D matrix.
tril
Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices input, the other elements of the result tensor out are set to 0.
tril_indices
Returns the indices of the lower triangular part of a row-by- col matrix in a 2-by-N Tensor, where the first row contains row coordinates of all indices and the second row contains column coordinates.
triu
Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices input, the other elements of the result tensor out are set to 0.
triu_indices
Returns the indices of the upper triangular part of a row by col matrix in a 2-by-N Tensor, where the first row contains row coordinates of all indices and the second row contains column coordinates.
vander
Generates a Vandermonde matrix.
view_as_real
Returns a view of input as a real tensor.
view_as_complex
Returns a view of input as a complex tensor. BLAS and LAPACK Operations
addbmm
Performs a batch matrix-matrix product of matrices stored in batch1 and batch2, with a reduced add step (all matrix multiplications get accumulated along the first dimension).
addmm
Performs a matrix multiplication of the matrices mat1 and mat2.
addmv
Performs a matrix-vector product of the matrix mat and the vector vec.
addr
Performs the outer-product of vectors vec1 and vec2 and adds it to the matrix input.
baddbmm
Performs a batch matrix-matrix product of matrices in batch1 and batch2.
bmm
Performs a batch matrix-matrix product of matrices stored in input and mat2.
chain_matmul
Returns the matrix product of the NN 2-D tensors.
cholesky
Computes the Cholesky decomposition of a symmetric positive-definite matrix AA or for batches of symmetric positive-definite matrices.
cholesky_inverse
Computes the inverse of a symmetric positive-definite matrix AA using its Cholesky factor uu : returns matrix inv.
cholesky_solve
Solves a linear system of equations with a positive semidefinite matrix to be inverted given its Cholesky factor matrix uu .
dot
Computes the dot product of two 1D tensors.
eig
Computes the eigenvalues and eigenvectors of a real square matrix.
geqrf
This is a low-level function for calling LAPACK directly.
ger
Alias of torch.outer().
inner
Computes the dot product for 1D tensors.
inverse
Takes the inverse of the square matrix input.
det
Calculates determinant of a square matrix or batches of square matrices.
logdet
Calculates log determinant of a square matrix or batches of square matrices.
slogdet
Calculates the sign and log absolute value of the determinant(s) of a square matrix or batches of square matrices.
lstsq
Computes the solution to the least squares and least norm problems for a full rank matrix AA of size (m×n)(m \times n) and a matrix BB of size (m×k)(m \times k) .
lu
Computes the LU factorization of a matrix or batches of matrices A.
lu_solve
Returns the LU solve of the linear system Ax=bAx = b using the partially pivoted LU factorization of A from torch.lu().
lu_unpack
Unpacks the data and pivots from a LU factorization of a tensor.
matmul
Matrix product of two tensors.
matrix_power
Returns the matrix raised to the power n for square matrices.
matrix_rank
Returns the numerical rank of a 2-D tensor.
matrix_exp
Returns the matrix exponential.
mm
Performs a matrix multiplication of the matrices input and mat2.
mv
Performs a matrix-vector product of the matrix input and the vector vec.
orgqr
Computes the orthogonal matrix Q of a QR factorization, from the (input, input2) tuple returned by torch.geqrf().
ormqr
Multiplies mat (given by input3) by the orthogonal Q matrix of the QR factorization formed by torch.geqrf() that is represented by (a, tau) (given by (input, input2)).
outer
Outer product of input and vec2.
pinverse
Calculates the pseudo-inverse (also known as the Moore-Penrose inverse) of a 2D tensor.
qr
Computes the QR decomposition of a matrix or a batch of matrices input, and returns a namedtuple (Q, R) of tensors such that input=QR\text{input} = Q R with QQ being an orthogonal matrix or batch of orthogonal matrices and RR being an upper triangular matrix or batch of upper triangular matrices.
solve
This function returns the solution to the system of linear equations represented by AX=BAX = B and the LU factorization of A, in order as a namedtuple solution, LU.
svd
Computes the singular value decomposition of either a matrix or batch of matrices input.
svd_lowrank
Return the singular value decomposition (U, S, V) of a matrix, batches of matrices, or a sparse matrix AA such that A≈Udiag(S)VTA \approx U diag(S) V^T .
pca_lowrank
Performs linear Principal Component Analysis (PCA) on a low-rank matrix, batches of such matrices, or sparse matrix.
symeig
This function returns eigenvalues and eigenvectors of a real symmetric matrix input or a batch of real symmetric matrices, represented by a namedtuple (eigenvalues, eigenvectors).
lobpcg
Find the k largest (or smallest) eigenvalues and the corresponding eigenvectors of a symmetric positive defined generalized eigenvalue problem using matrix-free LOBPCG methods.
trapz
Estimate ∫ydx\int y\,dx along dim, using the trapezoid rule.
triangular_solve
Solves a system of equations with a triangular coefficient matrix AA and multiple right-hand sides bb .
vdot
Computes the dot product of two 1D tensors. Utilities
compiled_with_cxx11_abi
Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1
result_type
Returns the torch.dtype that would result from performing an arithmetic operation on the provided input tensors.
can_cast
Determines if a type conversion is allowed under PyTorch casting rules described in the type promotion documentation.
promote_types
Returns the torch.dtype with the smallest size and scalar kind that is not smaller nor of lower kind than either type1 or type2.
use_deterministic_algorithms
Sets whether PyTorch operations must use “deterministic” algorithms.
are_deterministic_algorithms_enabled
Returns True if the global deterministic flag is turned on.
_assert
A wrapper around Python’s assert which is symbolically traceable. | torch |
torch.abs(input, *, out=None) → Tensor
Computes the absolute value of each element in input. outi=∣inputi∣\text{out}_{i} = |\text{input}_{i}|
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> torch.abs(torch.tensor([-1, -2, 3]))
tensor([ 1, 2, 3]) | torch.generated.torch.abs#torch.abs |
torch.absolute(input, *, out=None) → Tensor
Alias for torch.abs() | torch.generated.torch.absolute#torch.absolute |
torch.acos(input, *, out=None) → Tensor
Computes the inverse cosine of each element in input. outi=cos−1(inputi)\text{out}_{i} = \cos^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.3348, -0.5889, 0.2005, -0.1584])
>>> torch.acos(a)
tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) | torch.generated.torch.acos#torch.acos |
torch.acosh(input, *, out=None) → Tensor
Returns a new tensor with the inverse hyperbolic cosine of the elements of input. Note The domain of the inverse hyperbolic cosine is [1, inf) and values outside this range will be mapped to NaN, except for + INF for which the output is mapped to + INF. outi=cosh−1(inputi)\text{out}_{i} = \cosh^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4).uniform_(1, 2)
>>> a
tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ])
>>> torch.acosh(a)
tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) | torch.generated.torch.acosh#torch.acosh |
torch.add(input, other, *, out=None)
Adds the scalar other to each element of the input input and returns a new resulting tensor. out=input+other\text{out} = \text{input} + \text{other}
If input is of type FloatTensor or DoubleTensor, other must be a real number, otherwise it should be an integer. Parameters
input (Tensor) – the input tensor.
value (Number) – the number to be added to each element of input
Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.0202, 1.0985, 1.3506, -0.6056])
>>> torch.add(a, 20)
tensor([ 20.0202, 21.0985, 21.3506, 19.3944])
torch.add(input, other, *, alpha=1, out=None)
Each element of the tensor other is multiplied by the scalar alpha and added to each element of the tensor input. The resulting tensor is returned. The shapes of input and other must be broadcastable. out=input+alpha×other\text{out} = \text{input} + \text{alpha} \times \text{other}
If other is of type FloatTensor or DoubleTensor, alpha must be a real number, otherwise it should be an integer. Parameters
input (Tensor) – the first input tensor
other (Tensor) – the second input tensor Keyword Arguments
alpha (Number) – the scalar multiplier for other
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([-0.9732, -0.3497, 0.6245, 0.4022])
>>> b = torch.randn(4, 1)
>>> b
tensor([[ 0.3743],
[-1.7724],
[-0.5811],
[-0.8017]])
>>> torch.add(a, b, alpha=10)
tensor([[ 2.7695, 3.3930, 4.3672, 4.1450],
[-18.6971, -18.0736, -17.0994, -17.3216],
[ -6.7845, -6.1610, -5.1868, -5.4090],
[ -8.9902, -8.3667, -7.3925, -7.6147]]) | torch.generated.torch.add#torch.add |
torch.addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) → Tensor
Performs a batch matrix-matrix product of matrices stored in batch1 and batch2, with a reduced add step (all matrix multiplications get accumulated along the first dimension). input is added to the final result. batch1 and batch2 must be 3-D tensors each containing the same number of matrices. If batch1 is a (b×n×m)(b \times n \times m) tensor, batch2 is a (b×m×p)(b \times m \times p) tensor, input must be broadcastable with a (n×p)(n \times p) tensor and out will be a (n×p)(n \times p) tensor. out=β input+α(∑i=0b−1batch1i@batch2i)out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i)
If beta is 0, then input will be ignored, and nan and inf in it will not be propagated. For inputs of type FloatTensor or DoubleTensor, arguments beta and alpha must be real numbers, otherwise they should be integers. This operator supports TensorFloat32. Parameters
batch1 (Tensor) – the first batch of matrices to be multiplied
batch2 (Tensor) – the second batch of matrices to be multiplied Keyword Arguments
beta (Number, optional) – multiplier for input (β\beta )
input (Tensor) – matrix to be added
alpha (Number, optional) – multiplier for batch1 @ batch2 (α\alpha )
out (Tensor, optional) – the output tensor. Example: >>> M = torch.randn(3, 5)
>>> batch1 = torch.randn(10, 3, 4)
>>> batch2 = torch.randn(10, 4, 5)
>>> torch.addbmm(M, batch1, batch2)
tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653],
[ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743],
[ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) | torch.generated.torch.addbmm#torch.addbmm |
torch.addcdiv(input, tensor1, tensor2, *, value=1, out=None) → Tensor
Performs the element-wise division of tensor1 by tensor2, multiply the result by the scalar value and add it to input. Warning 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. outi=inputi+value×tensor1itensor2i\text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i}
The shapes of input, tensor1, and tensor2 must be broadcastable. For inputs of type FloatTensor or DoubleTensor, value must be a real number, otherwise an integer. Parameters
input (Tensor) – the tensor to be added
tensor1 (Tensor) – the numerator tensor
tensor2 (Tensor) – the denominator tensor Keyword Arguments
value (Number, optional) – multiplier for tensor1/tensor2\text{tensor1} / \text{tensor2}
out (Tensor, optional) – the output tensor. Example: >>> t = torch.randn(1, 3)
>>> t1 = torch.randn(3, 1)
>>> t2 = torch.randn(1, 3)
>>> torch.addcdiv(t, t1, t2, value=0.1)
tensor([[-0.2312, -3.6496, 0.1312],
[-1.0428, 3.4292, -0.1030],
[-0.5369, -0.9829, 0.0430]]) | torch.generated.torch.addcdiv#torch.addcdiv |
torch.addcmul(input, tensor1, tensor2, *, value=1, out=None) → Tensor
Performs the element-wise multiplication of tensor1 by tensor2, multiply the result by the scalar value and add it to input. outi=inputi+value×tensor1i×tensor2i\text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i
The shapes of tensor, tensor1, and tensor2 must be broadcastable. For inputs of type FloatTensor or DoubleTensor, value must be a real number, otherwise an integer. Parameters
input (Tensor) – the tensor to be added
tensor1 (Tensor) – the tensor to be multiplied
tensor2 (Tensor) – the tensor to be multiplied Keyword Arguments
value (Number, optional) – multiplier for tensor1.∗tensor2tensor1 .* tensor2
out (Tensor, optional) – the output tensor. Example: >>> t = torch.randn(1, 3)
>>> t1 = torch.randn(3, 1)
>>> t2 = torch.randn(1, 3)
>>> torch.addcmul(t, t1, t2, value=0.1)
tensor([[-0.8635, -0.6391, 1.6174],
[-0.7617, -0.5879, 1.7388],
[-0.8353, -0.6249, 1.6511]]) | torch.generated.torch.addcmul#torch.addcmul |
torch.addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) → Tensor
Performs a matrix multiplication of the matrices mat1 and mat2. The matrix input is added to the final result. If mat1 is a (n×m)(n \times m) tensor, mat2 is a (m×p)(m \times p) tensor, then input must be broadcastable with a (n×p)(n \times p) tensor and out will be a (n×p)(n \times p) tensor. alpha and beta are scaling factors on matrix-vector product between mat1 and mat2 and the added matrix input respectively. out=β input+α(mat1i@mat2i)\text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i)
If beta is 0, then input will be ignored, and nan and inf in it will not be propagated. For inputs of type FloatTensor or DoubleTensor, arguments beta and alpha must be real numbers, otherwise they should be integers. This operator supports TensorFloat32. Parameters
input (Tensor) – matrix to be added
mat1 (Tensor) – the first matrix to be matrix multiplied
mat2 (Tensor) – the second matrix to be matrix multiplied Keyword Arguments
beta (Number, optional) – multiplier for input (β\beta )
alpha (Number, optional) – multiplier for mat1@mat2mat1 @ mat2 (α\alpha )
out (Tensor, optional) – the output tensor. Example: >>> M = torch.randn(2, 3)
>>> mat1 = torch.randn(2, 3)
>>> mat2 = torch.randn(3, 3)
>>> torch.addmm(M, mat1, mat2)
tensor([[-4.8716, 1.4671, -1.3746],
[ 0.7573, -3.9555, -2.8681]]) | torch.generated.torch.addmm#torch.addmm |
torch.addmv(input, mat, vec, *, beta=1, alpha=1, out=None) → Tensor
Performs a matrix-vector product of the matrix mat and the vector vec. The vector input is added to the final result. If mat is a (n×m)(n \times m) tensor, vec is a 1-D tensor of size m, then input must be broadcastable with a 1-D tensor of size n and out will be 1-D tensor of size n. alpha and beta are scaling factors on matrix-vector product between mat and vec and the added tensor input respectively. out=β input+α(mat@vec)\text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec})
If beta is 0, then input will be ignored, and nan and inf in it will not be propagated. For inputs of type FloatTensor or DoubleTensor, arguments beta and alpha must be real numbers, otherwise they should be integers Parameters
input (Tensor) – vector to be added
mat (Tensor) – matrix to be matrix multiplied
vec (Tensor) – vector to be matrix multiplied Keyword Arguments
beta (Number, optional) – multiplier for input (β\beta )
alpha (Number, optional) – multiplier for mat@vecmat @ vec (α\alpha )
out (Tensor, optional) – the output tensor. Example: >>> M = torch.randn(2)
>>> mat = torch.randn(2, 3)
>>> vec = torch.randn(3)
>>> torch.addmv(M, mat, vec)
tensor([-0.3768, -5.5565]) | torch.generated.torch.addmv#torch.addmv |
torch.addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) → Tensor
Performs the outer-product of vectors vec1 and vec2 and adds it to the matrix input. Optional values beta and alpha are scaling factors on the outer product between vec1 and vec2 and the added matrix input respectively. out=β input+α(vec1⊗vec2)\text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2})
If beta is 0, then input will be ignored, and nan and inf in it will not be propagated. If vec1 is a vector of size n and vec2 is a vector of size m, then input must be broadcastable with a matrix of size (n×m)(n \times m) and out will be a matrix of size (n×m)(n \times m) . Parameters
input (Tensor) – matrix to be added
vec1 (Tensor) – the first vector of the outer product
vec2 (Tensor) – the second vector of the outer product Keyword Arguments
beta (Number, optional) – multiplier for input (β\beta )
alpha (Number, optional) – multiplier for vec1⊗vec2\text{vec1} \otimes \text{vec2} (α\alpha )
out (Tensor, optional) – the output tensor. Example: >>> vec1 = torch.arange(1., 4.)
>>> vec2 = torch.arange(1., 3.)
>>> M = torch.zeros(3, 2)
>>> torch.addr(M, vec1, vec2)
tensor([[ 1., 2.],
[ 2., 4.],
[ 3., 6.]]) | torch.generated.torch.addr#torch.addr |
torch.all(input) → Tensor
Tests if all elements in input evaluate to True. Note This function matches the behaviour of NumPy in returning output of dtype bool for all supported dtypes except uint8. For uint8 the dtype of output is uint8 itself. Example: >>> a = torch.rand(1, 2).bool()
>>> a
tensor([[False, True]], dtype=torch.bool)
>>> torch.all(a)
tensor(False, dtype=torch.bool)
>>> a = torch.arange(0, 3)
>>> a
tensor([0, 1, 2])
>>> torch.all(a)
tensor(False)
torch.all(input, dim, keepdim=False, *, out=None) → Tensor
For each row of input in the given dimension dim, returns True if all elements in the row evaluate to True and False otherwise. If keepdim is True, the output tensor is of the same size as input except in the dimension dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 fewer dimension than input. Parameters
input (Tensor) – the input tensor.
dim (int) – the dimension to reduce.
keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.rand(4, 2).bool()
>>> a
tensor([[True, True],
[True, False],
[True, True],
[True, True]], dtype=torch.bool)
>>> torch.all(a, dim=1)
tensor([ True, False, True, True], dtype=torch.bool)
>>> torch.all(a, dim=0)
tensor([ True, False], dtype=torch.bool) | torch.generated.torch.all#torch.all |
torch.allclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) → bool
This function checks if all input and other satisfy the condition: ∣input−other∣≤atol+rtol×∣other∣\lvert \text{input} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert
elementwise, for all elements of input and other. The behaviour of this function is analogous to numpy.allclose Parameters
input (Tensor) – first tensor to compare
other (Tensor) – second tensor to compare
atol (float, optional) – absolute tolerance. Default: 1e-08
rtol (float, optional) – relative tolerance. Default: 1e-05
equal_nan (bool, optional) – if True, then two NaN s will be considered equal. Default: False
Example: >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08]))
False
>>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09]))
True
>>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]))
False
>>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True)
True | torch.generated.torch.allclose#torch.allclose |
torch.amax(input, dim, keepdim=False, *, out=None) → Tensor
Returns the maximum value of each slice of the input tensor in the given dimension(s) dim. Note
The difference between max/min and amax/amin is:
amax/amin supports reducing on multiple dimensions,
amax/amin does not return indices,
amax/amin evenly distributes gradient between equal values, while max(dim)/min(dim) propagates gradient only to a single index in the source tensor. If keepdim is ``True`, the output tensors are of the same size as input except in the dimension(s) dim where they are of size 1. Otherwise, dim`s are squeezed (see :func:`torch.squeeze), resulting in the output tensors having fewer dimension than input. Parameters
input (Tensor) – the input tensor.
dim (int or tuple of python:ints) – the dimension or dimensions to reduce.
keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.8177, 1.4878, -0.2491, 0.9130],
[-0.7158, 1.1775, 2.0992, 0.4817],
[-0.0053, 0.0164, -1.3738, -0.0507],
[ 1.9700, 1.1106, -1.0318, -1.0816]])
>>> torch.amax(a, 1)
tensor([1.4878, 2.0992, 0.0164, 1.9700]) | torch.generated.torch.amax#torch.amax |
torch.amin(input, dim, keepdim=False, *, out=None) → Tensor
Returns the minimum value of each slice of the input tensor in the given dimension(s) dim. Note
The difference between max/min and amax/amin is:
amax/amin supports reducing on multiple dimensions,
amax/amin does not return indices,
amax/amin evenly distributes gradient between equal values, while max(dim)/min(dim) propagates gradient only to a single index in the source tensor. If keepdim is True, the output tensors are of the same size as input except in the dimension(s) dim where they are of size 1. Otherwise, dim`s are squeezed (see :func:`torch.squeeze), resulting in the output tensors having fewer dimensions than input. Parameters
input (Tensor) – the input tensor.
dim (int or tuple of python:ints) – the dimension or dimensions to reduce.
keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.6451, -0.4866, 0.2987, -1.3312],
[-0.5744, 1.2980, 1.8397, -0.2713],
[ 0.9128, 0.9214, -1.7268, -0.2995],
[ 0.9023, 0.4853, 0.9075, -1.6165]])
>>> torch.amin(a, 1)
tensor([-1.3312, -0.5744, -1.7268, -1.6165]) | torch.generated.torch.amin#torch.amin |
torch.angle(input, *, out=None) → Tensor
Computes the element-wise angle (in radians) of the given input tensor. outi=angle(inputi)\text{out}_{i} = angle(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Note Starting in PyTorch 1.8, angle returns pi for negative real numbers, zero for non-negative real numbers, and propagates NaNs. Previously the function would return zero for all real numbers and not propagate floating-point NaNs. Example: >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159
tensor([ 135., 135, -45]) | torch.generated.torch.angle#torch.angle |
torch.any(input) → Tensor
Parameters
input (Tensor) – the input tensor. Tests if any element in input evaluates to True. Note This function matches the behaviour of NumPy in returning output of dtype bool for all supported dtypes except uint8. For uint8 the dtype of output is uint8 itself. Example: >>> a = torch.rand(1, 2).bool()
>>> a
tensor([[False, True]], dtype=torch.bool)
>>> torch.any(a)
tensor(True, dtype=torch.bool)
>>> a = torch.arange(0, 3)
>>> a
tensor([0, 1, 2])
>>> torch.any(a)
tensor(True)
torch.any(input, dim, keepdim=False, *, out=None) → Tensor
For each row of input in the given dimension dim, returns True if any element in the row evaluate to True and False otherwise. If keepdim is True, the output tensor is of the same size as input except in the dimension dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 fewer dimension than input. Parameters
input (Tensor) – the input tensor.
dim (int) – the dimension to reduce.
keepdim (bool) – whether the output tensor has dim retained or not. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4, 2) < 0
>>> a
tensor([[ True, True],
[False, True],
[ True, True],
[False, False]])
>>> torch.any(a, 1)
tensor([ True, True, True, False])
>>> torch.any(a, 0)
tensor([True, True]) | torch.generated.torch.any#torch.any |
torch.arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
Returns a 1-D tensor of size ⌈end−startstep⌉\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil with values from the interval [start, end) taken with common difference step beginning from start. Note that non-integer step is subject to floating point rounding errors when comparing against end; to avoid inconsistency, we advise adding a small epsilon to end in such cases. outi+1=outi+step\text{out}_{{i+1}} = \text{out}_{i} + \text{step}
Parameters
start (Number) – the starting value for the set of points. Default: 0.
end (Number) – the ending value for the set of points
step (Number) – the gap between each pair of adjacent points. Default: 1. Keyword Arguments
out (Tensor, optional) – the output tensor.
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()). If dtype is not given, infer the data type from the other input arguments. If any of start, end, or stop are floating-point, the dtype is inferred to be the default dtype, see get_default_dtype(). Otherwise, the dtype is inferred to be torch.int64.
layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. Example: >>> torch.arange(5)
tensor([ 0, 1, 2, 3, 4])
>>> torch.arange(1, 4)
tensor([ 1, 2, 3])
>>> torch.arange(1, 2.5, 0.5)
tensor([ 1.0000, 1.5000, 2.0000]) | torch.generated.torch.arange#torch.arange |
torch.arccos(input, *, out=None) → Tensor
Alias for torch.acos(). | torch.generated.torch.arccos#torch.arccos |
torch.arccosh(input, *, out=None) → Tensor
Alias for torch.acosh(). | torch.generated.torch.arccosh#torch.arccosh |
torch.arcsin(input, *, out=None) → Tensor
Alias for torch.asin(). | torch.generated.torch.arcsin#torch.arcsin |
torch.arcsinh(input, *, out=None) → Tensor
Alias for torch.asinh(). | torch.generated.torch.arcsinh#torch.arcsinh |
torch.arctan(input, *, out=None) → Tensor
Alias for torch.atan(). | torch.generated.torch.arctan#torch.arctan |
torch.arctanh(input, *, out=None) → Tensor
Alias for torch.atanh(). | torch.generated.torch.arctanh#torch.arctanh |
torch.are_deterministic_algorithms_enabled() [source]
Returns True if the global deterministic flag is turned on. Refer to torch.use_deterministic_algorithms() documentation for more details. | torch.generated.torch.are_deterministic_algorithms_enabled#torch.are_deterministic_algorithms_enabled |
torch.argmax(input) → LongTensor
Returns the indices of the maximum value of all elements in the input tensor. This is the second value returned by torch.max(). See its documentation for the exact semantics of this method. Note If there are multiple minimal values then the indices of the first minimal value are returned. Parameters
input (Tensor) – the input tensor. Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
[-0.7401, -0.8805, -0.3402, -1.1936],
[ 0.4907, -1.3948, -1.0691, -0.3132],
[-1.6092, 0.5419, -0.2993, 0.3195]])
>>> torch.argmax(a)
tensor(0)
torch.argmax(input, dim, keepdim=False) → LongTensor
Returns the indices of the maximum values of a tensor across a dimension. This is the second value returned by torch.max(). See its documentation for the exact semantics of this method. Parameters
input (Tensor) – the input tensor.
dim (int) – the dimension to reduce. If None, the argmax of the flattened input is returned.
keepdim (bool) – whether the output tensor has dim retained or not. Ignored if dim=None. Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
[-0.7401, -0.8805, -0.3402, -1.1936],
[ 0.4907, -1.3948, -1.0691, -0.3132],
[-1.6092, 0.5419, -0.2993, 0.3195]])
>>> torch.argmax(a, dim=1)
tensor([ 0, 2, 0, 1]) | torch.generated.torch.argmax#torch.argmax |
torch.argmin(input, dim=None, keepdim=False) → LongTensor
Returns the indices of the minimum value(s) of the flattened tensor or along a dimension This is the second value returned by torch.min(). See its documentation for the exact semantics of this method. Note If there are multiple minimal values then the indices of the first minimal value are returned. Parameters
input (Tensor) – the input tensor.
dim (int) – the dimension to reduce. If None, the argmin of the flattened input is returned.
keepdim (bool) – whether the output tensor has dim retained or not. Ignored if dim=None. Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.1139, 0.2254, -0.1381, 0.3687],
[ 1.0100, -1.1975, -0.0102, -0.4732],
[-0.9240, 0.1207, -0.7506, -1.0213],
[ 1.7809, -1.2960, 0.9384, 0.1438]])
>>> torch.argmin(a)
tensor(13)
>>> torch.argmin(a, dim=1)
tensor([ 2, 1, 3, 1])
>>> torch.argmin(a, dim=1, keepdim=True)
tensor([[2],
[1],
[3],
[1]]) | torch.generated.torch.argmin#torch.argmin |
torch.argsort(input, dim=-1, descending=False) → LongTensor
Returns the indices that sort a tensor along a given dimension in ascending order by value. This is the second value returned by torch.sort(). See its documentation for the exact semantics of this method. Parameters
input (Tensor) – the input tensor.
dim (int, optional) – the dimension to sort along
descending (bool, optional) – controls the sorting order (ascending or descending) Example: >>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.0785, 1.5267, -0.8521, 0.4065],
[ 0.1598, 0.0788, -0.0745, -1.2700],
[ 1.2208, 1.0722, -0.7064, 1.2564],
[ 0.0669, -0.2318, -0.8229, -0.9280]])
>>> torch.argsort(a, dim=1)
tensor([[2, 0, 3, 1],
[3, 2, 1, 0],
[2, 1, 0, 3],
[3, 2, 1, 0]]) | torch.generated.torch.argsort#torch.argsort |
torch.asin(input, *, out=None) → Tensor
Returns a new tensor with the arcsine of the elements of input. outi=sin−1(inputi)\text{out}_{i} = \sin^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([-0.5962, 1.4985, -0.4396, 1.4525])
>>> torch.asin(a)
tensor([-0.6387, nan, -0.4552, nan]) | torch.generated.torch.asin#torch.asin |
torch.asinh(input, *, out=None) → Tensor
Returns a new tensor with the inverse hyperbolic sine of the elements of input. outi=sinh−1(inputi)\text{out}_{i} = \sinh^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ])
>>> torch.asinh(a)
tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) | torch.generated.torch.asinh#torch.asinh |
torch.as_strided(input, size, stride, storage_offset=0) → Tensor
Create a view of an existing torch.Tensor input with specified size, stride and storage_offset. Warning More than one element of a created tensor may refer to a single memory location. As a result, in-place operations (especially ones that are vectorized) may result in incorrect behavior. If you need to write to the tensors, please clone them first. Many PyTorch functions, which return a view of a tensor, are internally implemented with this function. Those functions, like torch.Tensor.expand(), are easier to read and are therefore more advisable to use. Parameters
input (Tensor) – the input tensor.
size (tuple or ints) – the shape of the output tensor
stride (tuple or ints) – the stride of the output tensor
storage_offset (int, optional) – the offset in the underlying storage of the output tensor Example: >>> x = torch.randn(3, 3)
>>> x
tensor([[ 0.9039, 0.6291, 1.0795],
[ 0.1586, 2.1939, -0.4900],
[-0.1909, -0.7503, 1.9355]])
>>> t = torch.as_strided(x, (2, 2), (1, 2))
>>> t
tensor([[0.9039, 1.0795],
[0.6291, 0.1586]])
>>> t = torch.as_strided(x, (2, 2), (1, 2), 1)
tensor([[0.6291, 0.1586],
[1.0795, 2.1939]]) | torch.generated.torch.as_strided#torch.as_strided |
torch.as_tensor(data, dtype=None, device=None) → Tensor
Convert the data into a torch.Tensor. If the data is already a Tensor with the same dtype and device, no copy will be performed, otherwise a new Tensor will be returned with computational graph retained if data Tensor has requires_grad=True. Similarly, if the data is an ndarray of the corresponding dtype and the device is the cpu, no copy will be performed. Parameters
data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. Example: >>> a = numpy.array([1, 2, 3])
>>> t = torch.as_tensor(a)
>>> t
tensor([ 1, 2, 3])
>>> t[0] = -1
>>> a
array([-1, 2, 3])
>>> a = numpy.array([1, 2, 3])
>>> t = torch.as_tensor(a, device=torch.device('cuda'))
>>> t
tensor([ 1, 2, 3])
>>> t[0] = -1
>>> a
array([1, 2, 3]) | torch.generated.torch.as_tensor#torch.as_tensor |
torch.atan(input, *, out=None) → Tensor
Returns a new tensor with the arctangent of the elements of input. outi=tan−1(inputi)\text{out}_{i} = \tan^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.2341, 0.2539, -0.6256, -0.6448])
>>> torch.atan(a)
tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) | torch.generated.torch.atan#torch.atan |
torch.atan2(input, other, *, out=None) → Tensor
Element-wise arctangent of inputi/otheri\text{input}_{i} / \text{other}_{i} with consideration of the quadrant. Returns a new tensor with the signed angles in radians between vector (otheri,inputi)(\text{other}_{i}, \text{input}_{i}) and vector (1,0)(1, 0) . (Note that otheri\text{other}_{i} , the second parameter, is the x-coordinate, while inputi\text{input}_{i} , the first parameter, is the y-coordinate.) The shapes of input and other must be broadcastable. Parameters
input (Tensor) – the first input tensor
other (Tensor) – the second input tensor Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4)
>>> a
tensor([ 0.9041, 0.0196, -0.3108, -2.4423])
>>> torch.atan2(a, torch.randn(4))
tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) | torch.generated.torch.atan2#torch.atan2 |
torch.atanh(input, *, out=None) → Tensor
Returns a new tensor with the inverse hyperbolic tangent of the elements of input. Note The domain of the inverse hyperbolic tangent is (-1, 1) and values outside this range will be mapped to NaN, except for the values 1 and -1 for which the output is mapped to +/-INF respectively. outi=tanh−1(inputi)\text{out}_{i} = \tanh^{-1}(\text{input}_{i})
Parameters
input (Tensor) – the input tensor. Keyword Arguments
out (Tensor, optional) – the output tensor. Example: >>> a = torch.randn(4).uniform_(-1, 1)
>>> a
tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ])
>>> torch.atanh(a)
tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) | torch.generated.torch.atanh#torch.atanh |
torch.atleast_1d(*tensors) [source]
Returns a 1-dimensional view of each input tensor with zero dimensions. Input tensors with one or more dimensions are returned as-is. Parameters
input (Tensor or list of Tensors) – Returns
output (Tensor or tuple of Tensors) Example::
>>> x = torch.randn(2)
>>> x
tensor([1.4584, 0.7583])
>>> torch.atleast_1d(x)
tensor([1.4584, 0.7583])
>>> x = torch.tensor(1.)
>>> x
tensor(1.)
>>> torch.atleast_1d(x)
tensor([1.])
>>> x = torch.tensor(0.5)
>>> y = torch.tensor(1.)
>>> torch.atleast_1d((x,y))
(tensor([0.5000]), tensor([1.])) | torch.generated.torch.atleast_1d#torch.atleast_1d |
torch.atleast_2d(*tensors) [source]
Returns a 2-dimensional view of each input tensor with zero dimensions. Input tensors with two or more dimensions are returned as-is. :param input: :type input: Tensor or list of Tensors Returns
output (Tensor or tuple of Tensors) Example::
>>> x = torch.tensor(1.)
>>> x
tensor(1.)
>>> torch.atleast_2d(x)
tensor([[1.]])
>>> x = torch.randn(2,2)
>>> x
tensor([[2.2086, 2.5165],
[0.1757, 0.5194]])
>>> torch.atleast_2d(x)
tensor([[2.2086, 2.5165],
[0.1757, 0.5194]])
>>> x = torch.tensor(0.5)
>>> y = torch.tensor(1.)
>>> torch.atleast_2d((x,y))
(tensor([[0.5000]]), tensor([[1.]])) | torch.generated.torch.atleast_2d#torch.atleast_2d |
torch.atleast_3d(*tensors) [source]
Returns a 3-dimensional view of each input tensor with zero dimensions. Input tensors with three or more dimensions are returned as-is. :param input: :type input: Tensor or list of Tensors Returns
output (Tensor or tuple of Tensors) Example >>> x = torch.tensor(0.5)
>>> x
tensor(0.5000)
>>> torch.atleast_3d(x)
tensor([[[0.5000]]])
>>> y = torch.randn(2,2)
>>> y
tensor([[-0.8079, 0.7460],
[-1.1647, 1.4734]])
>>> torch.atleast_3d(y)
tensor([[[-0.8079],
[ 0.7460]],
[[-1.1647],
[ 1.4734]]])
>>> x = torch.randn(1,1,1)
>>> x
tensor([[[-1.5689]]])
>>> torch.atleast_3d(x)
tensor([[[-1.5689]]])
>>> x = torch.tensor(0.5)
>>> y = torch.tensor(1.)
>>> torch.atleast_3d((x,y))
(tensor([[[0.5000]]]), tensor([[[1.]]])) | torch.generated.torch.atleast_3d#torch.atleast_3d |
Automatic differentiation package - torch.autograd torch.autograd provides classes and functions implementing automatic differentiation of arbitrary scalar valued functions. It requires minimal changes to the existing code - you only need to declare Tensor s for which gradients should be computed with the requires_grad=True keyword. As of now, we only support autograd for floating point Tensor types ( half, float, double and bfloat16) and complex Tensor types (cfloat, cdouble).
torch.autograd.backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False, grad_variables=None, inputs=None) [source]
Computes the sum of gradients of given tensors w.r.t. graph leaves. The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient, then the Jacobian-vector product would be computed, in this case the function additionally requires specifying grad_tensors. It should be a sequence of matching length, that contains the “vector” in the Jacobian-vector product, usually the gradient of the differentiated function w.r.t. corresponding tensors (None is an acceptable value for all tensors that don’t need gradient tensors). This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients. Note Using this method with create_graph=True will create a reference cycle between the parameter and its gradient which can cause a memory leak. We recommend using autograd.grad when creating the graph to avoid this. If you have to use this function, make sure to reset the .grad fields of your parameters to None after use to break the cycle and avoid the leak. Note If you run any forward ops, create grad_tensors, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes. Parameters
tensors (sequence of Tensor) – Tensors of which the derivative will be computed.
grad_tensors (sequence of (Tensor or None)) – The “vector” in the Jacobian-vector product, usually gradients w.r.t. each element of corresponding tensors. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable for all grad_tensors, then this argument is optional.
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.
inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be accumulated into .grad. All other Tensors will be ignored. If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors. All the provided inputs must be leaf Tensors.
torch.autograd.grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False, only_inputs=True, allow_unused=False) [source]
Computes and returns the sum of gradients of outputs w.r.t. the inputs. grad_outputs should be a sequence of length matching output containing the “vector” in Jacobian-vector product, usually the pre-computed gradients w.r.t. each of the outputs. If an output doesn’t require_grad, then the gradient can be None). If only_inputs is True, the function will only return a list of gradients w.r.t the specified inputs. If it’s False, then gradient w.r.t. all remaining leaves will still be computed, and will be accumulated into their .grad attribute. Note If you run any forward ops, create grad_outputs, and/or call grad in a user-specified CUDA stream context, see Stream semantics of backward passes. Parameters
outputs (sequence of Tensor) – outputs of the differentiated function.
inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be returned (and not accumulated into .grad).
grad_outputs (sequence of Tensor) – The “vector” in the Jacobian-vector product. Usually gradients w.r.t. each output. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable for all grad_tensors, then this argument is optional. Default: None.
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Default: False.
allow_unused (bool, optional) – If False, specifying inputs that were not used when computing outputs (and therefore their grad is always zero) is an error. Defaults to False.
Functional higher level API Warning This API is in beta. Even though the function signatures are very unlikely to change, major improvements to performances are planned before we consider this stable. This section contains the higher level API for the autograd that builds on the basic API above and allows you to compute jacobians, hessians, etc. This API works with user-provided functions that take only Tensors as input and return only Tensors. If your function takes other arguments that are not Tensors or Tensors that don’t have requires_grad set, you can use a lambda to capture them. For example, for a function f that takes three inputs, a Tensor for which we want the jacobian, another tensor that should be considered constant and a boolean flag as f(input, constant, flag=flag) you can use it as functional.jacobian(lambda x: f(x, constant, flag=flag), input).
torch.autograd.functional.jacobian(func, inputs, create_graph=False, strict=False, vectorize=False) [source]
Function that computes the Jacobian of a given function. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
create_graph (bool, optional) – If True, the Jacobian will be computed in a differentiable manner. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the jacobian for said inputs, which is the expected mathematical value. Defaults to False.
vectorize (bool, optional) – This feature is experimental, please use at your own risk. When computing the jacobian, usually we invoke autograd.grad once per row of the jacobian. If this flag is True, we use the vmap prototype feature as the backend to vectorize calls to autograd.grad so we only invoke it once instead of once per row. This should lead to performance improvements in many use cases, however, due to this feature being incomplete, there may be performance cliffs. Please use torch._C._debug_only_display_vmap_fallback_warnings(True) to show any performance warnings and file us issues if warnings exist for your use case. Defaults to False. Returns
if there is a single input and output, this will be a single Tensor containing the Jacobian for the linearized inputs and output. If one of the two is a tuple, then the Jacobian will be a tuple of Tensors. If both of them are tuples, then the Jacobian will be a tuple of tuple of Tensors where Jacobian[i][j] will contain the Jacobian of the ith output and jth input and will have as size the concatenation of the sizes of the corresponding output and the corresponding input and will have same dtype and device as the corresponding input. Return type
Jacobian (Tensor or nested tuple of Tensors) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(2, 2)
>>> jacobian(exp_reducer, inputs)
tensor([[[1.4917, 2.4352],
[0.0000, 0.0000]],
[[0.0000, 0.0000],
[2.4369, 2.3799]]])
>>> jacobian(exp_reducer, inputs, create_graph=True)
tensor([[[1.4917, 2.4352],
[0.0000, 0.0000]],
[[0.0000, 0.0000],
[2.4369, 2.3799]]], grad_fn=<ViewBackward>)
>>> def exp_adder(x, y):
... return 2 * x.exp() + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> jacobian(exp_adder, inputs)
(tensor([[2.8052, 0.0000],
[0.0000, 3.3963]]),
tensor([[3., 0.],
[0., 3.]]))
torch.autograd.functional.hessian(func, inputs, create_graph=False, strict=False, vectorize=False) [source]
Function that computes the Hessian of a given scalar function. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
create_graph (bool, optional) – If True, the Hessian will be computed in a differentiable manner. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the hessian for said inputs, which is the expected mathematical value. Defaults to False.
vectorize (bool, optional) – This feature is experimental, please use at your own risk. When computing the hessian, usually we invoke autograd.grad once per row of the hessian. If this flag is True, we use the vmap prototype feature as the backend to vectorize calls to autograd.grad so we only invoke it once instead of once per row. This should lead to performance improvements in many use cases, however, due to this feature being incomplete, there may be performance cliffs. Please use torch._C._debug_only_display_vmap_fallback_warnings(True) to show any performance warnings and file us issues if warnings exist for your use case. Defaults to False. Returns
if there is a single input, this will be a single Tensor containing the Hessian for the input. If it is a tuple, then the Hessian will be a tuple of tuples where Hessian[i][j] will contain the Hessian of the ith input and jth input with size the sum of the size of the ith input plus the size of the jth input. Hessian[i][j] will have the same dtype and device as the corresponding ith input. Return type
Hessian (Tensor or a tuple of tuple of Tensors) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> hessian(pow_reducer, inputs)
tensor([[[[5.2265, 0.0000],
[0.0000, 0.0000]],
[[0.0000, 4.8221],
[0.0000, 0.0000]]],
[[[0.0000, 0.0000],
[1.9456, 0.0000]],
[[0.0000, 0.0000],
[0.0000, 3.2550]]]])
>>> hessian(pow_reducer, inputs, create_graph=True)
tensor([[[[5.2265, 0.0000],
[0.0000, 0.0000]],
[[0.0000, 4.8221],
[0.0000, 0.0000]]],
[[[0.0000, 0.0000],
[1.9456, 0.0000]],
[[0.0000, 0.0000],
[0.0000, 3.2550]]]], grad_fn=<ViewBackward>)
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> hessian(pow_adder_reducer, inputs)
((tensor([[4., 0.],
[0., 4.]]),
tensor([[0., 0.],
[0., 0.]])),
(tensor([[0., 0.],
[0., 0.]]),
tensor([[6., 0.],
[0., 6.]])))
torch.autograd.functional.vjp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between a vector v and the Jacobian of the given function at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the vector Jacobian product is computed. Must be the same size as the output of func. This argument is optional when the output of func contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the vjp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) vjp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(4, 4)
>>> v = torch.ones(4)
>>> vjp(exp_reducer, inputs, v)
(tensor([5.7817, 7.2458, 5.7830, 6.7782]),
tensor([[1.4458, 1.3962, 1.3042, 1.6354],
[2.1288, 1.0652, 1.5483, 2.5035],
[2.2046, 1.1292, 1.1432, 1.3059],
[1.3225, 1.6652, 1.7753, 2.0152]]))
>>> vjp(exp_reducer, inputs, v, create_graph=True)
(tensor([5.7817, 7.2458, 5.7830, 6.7782], grad_fn=<SumBackward1>),
tensor([[1.4458, 1.3962, 1.3042, 1.6354],
[2.1288, 1.0652, 1.5483, 2.5035],
[2.2046, 1.1292, 1.1432, 1.3059],
[1.3225, 1.6652, 1.7753, 2.0152]], grad_fn=<MulBackward0>))
>>> def adder(x, y):
... return 2 * x + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = torch.ones(2)
>>> vjp(adder, inputs, v)
(tensor([2.4225, 2.3340]),
(tensor([2., 2.]), tensor([3., 3.])))
torch.autograd.functional.jvp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between the Jacobian of the given function at the point given by the inputs and a vector v. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the Jacobian vector product is computed. Must be the same size as the input of func. This argument is optional when the input to func contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the jvp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) jvp (tuple of Tensors or Tensor): result of the dot product with the same shape as the output. Return type
output (tuple) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(4, 4)
>>> v = torch.ones(4, 4)
>>> jvp(exp_reducer, inputs, v)
(tensor([6.3090, 4.6742, 7.9114, 8.2106]),
tensor([6.3090, 4.6742, 7.9114, 8.2106]))
>>> jvp(exp_reducer, inputs, v, create_graph=True)
(tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SumBackward1>),
tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SqueezeBackward1>))
>>> def adder(x, y):
... return 2 * x + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.ones(2), torch.ones(2))
>>> jvp(adder, inputs, v)
(tensor([2.2399, 2.5005]),
tensor([5., 5.]))
Note The jvp is currently computed by using the backward of the backward (sometimes called the double backwards trick) as we don’t have support for forward mode AD in PyTorch at the moment.
torch.autograd.functional.vhp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between a vector v and the Hessian of a given scalar function at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the vector Hessian product is computed. Must be the same size as the input of func. This argument is optional when func’s input contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the vhp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) vhp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> vhp(pow_reducer, inputs, v)
(tensor(0.5591),
tensor([[1.0689, 1.2431],
[3.0989, 4.4456]]))
>>> vhp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.5591, grad_fn=<SumBackward0>),
tensor([[1.0689, 1.2431],
[3.0989, 4.4456]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> vhp(pow_adder_reducer, inputs, v)
(tensor(4.8053),
(tensor([0., 0.]),
tensor([6., 6.])))
torch.autograd.functional.hvp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between the Hessian of a given scalar function and a vector v at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the Hessian vector product is computed. Must be the same size as the input of func. This argument is optional when func’s input contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the hvp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) hvp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> hvp(pow_reducer, inputs, v)
(tensor(0.1448),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]]))
>>> hvp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.1448, grad_fn=<SumBackward0>),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> hvp(pow_adder_reducer, inputs, v)
(tensor(2.3030),
(tensor([0., 0.]),
tensor([6., 6.])))
Note This function is significantly slower than vhp due to backward mode AD constraints. If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you know that your function satisfies this condition, you should use vhp instead that is much faster with the current implementation.
Locally disabling gradient computation
class torch.autograd.no_grad [source]
Context-manager that disabled gradient calculation. Disabling gradient calculation is useful for inference, when you are sure that you will not call Tensor.backward(). It will reduce memory consumption for computations that would otherwise have requires_grad=True. In this mode, the result of every computation will have requires_grad=False, even when the inputs have requires_grad=True. This context manager is thread local; it will not affect computation in other threads. Also functions as a decorator. (Make sure to instantiate with parenthesis.) Example: >>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
... return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False
class torch.autograd.enable_grad [source]
Context-manager that enables gradient calculation. Enables gradient calculation, if it has been disabled via no_grad or set_grad_enabled. This context manager is thread local; it will not affect computation in other threads. Also functions as a decorator. (Make sure to instantiate with parenthesis.) Example: >>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... with torch.enable_grad():
... y = x * 2
>>> y.requires_grad
True
>>> y.backward()
>>> x.grad
>>> @torch.enable_grad()
... def doubler(x):
... return x * 2
>>> with torch.no_grad():
... z = doubler(x)
>>> z.requires_grad
True
class torch.autograd.set_grad_enabled(mode) [source]
Context-manager that sets gradient calculation to on or off. set_grad_enabled will enable or disable grads based on its argument mode. It can be used as a context-manager or as a function. This context manager is thread local; it will not affect computation in other threads. Parameters
mode (bool) – Flag whether to enable grad (True), or disable (False). This can be used to conditionally enable gradients. Example: >>> x = torch.tensor([1], requires_grad=True)
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
... y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True)
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False
Default gradient layouts When a non-sparse param receives a non-sparse gradient during torch.autograd.backward() or torch.Tensor.backward() param.grad is accumulated as follows. If param.grad is initially None: If param’s memory is non-overlapping and dense, .grad is created with strides matching param (thus matching param’s layout). Otherwise, .grad is created with rowmajor-contiguous strides. If param already has a non-sparse .grad attribute: If create_graph=False, backward() accumulates into .grad in-place, which preserves its strides. If create_graph=True, backward() replaces .grad with a new tensor .grad + new grad, which attempts (but does not guarantee) matching the preexisting .grad’s strides. The default behavior (letting .grads be None before the first backward(), such that their layout is created according to 1 or 2, and retained over time according to 3 or 4) is recommended for best performance. Calls to model.zero_grad() or optimizer.zero_grad() will not affect .grad layouts. In fact, resetting all .grads to None before each accumulation phase, e.g.: for iterations...
...
for param in model.parameters():
param.grad = None
loss.backward()
such that they’re recreated according to 1 or 2 every time, is a valid alternative to model.zero_grad() or optimizer.zero_grad() that may improve performance for some networks. Manual gradient layouts If you need manual control over .grad’s strides, assign param.grad = a zeroed tensor with desired strides before the first backward(), and never reset it to None. 3 guarantees your layout is preserved as long as create_graph=False. 4 indicates your layout is likely preserved even if create_graph=True. In-place operations on Tensors Supporting in-place operations in autograd is a hard matter, and we discourage their use in most cases. Autograd’s aggressive buffer freeing and reuse makes it very efficient and there are very few occasions when in-place operations actually lower memory usage by any significant amount. Unless you’re operating under heavy memory pressure, you might never need to use them. In-place correctness checks All Tensor s keep track of in-place operations applied to them, and if the implementation detects that a tensor was saved for backward in one of the functions, but it was modified in-place afterwards, an error will be raised once backward pass is started. This ensures that if you’re using in-place functions and not seeing any errors, you can be sure that the computed gradients are correct. Variable (deprecated) Warning The Variable API has been deprecated: Variables are no longer necessary to use autograd with tensors. Autograd automatically supports Tensors with requires_grad set to True. Below please find a quick guide on what has changed:
Variable(tensor) and Variable(tensor, requires_grad) still work as expected, but they return Tensors instead of Variables.
var.data is the same thing as tensor.data. Methods such as var.backward(), var.detach(), var.register_hook() now work on tensors with the same method names. In addition, one can now create tensors with requires_grad=True using factory methods such as torch.randn(), torch.zeros(), torch.ones(), and others like the following: autograd_tensor = torch.randn((2, 3, 4), requires_grad=True) Tensor autograd functions
class torch.Tensor
grad
This attribute is None by default and becomes a Tensor the first time a call to backward() computes gradients for self. The attribute will then contain the gradients computed and future calls to backward() will accumulate (add) gradients into it.
requires_grad
Is True if gradients need to be computed for this Tensor, False otherwise. Note The fact that gradients need to be computed for a Tensor do not mean that the grad attribute will be populated, see is_leaf for more details.
is_leaf
All Tensors that have requires_grad which is False will be leaf Tensors by convention. For Tensors that have requires_grad which is True, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so grad_fn is None. Only leaf Tensors will have their grad populated during a call to backward(). To get grad populated for non-leaf Tensors, you can use retain_grad(). Example: >>> a = torch.rand(10, requires_grad=True)
>>> a.is_leaf
True
>>> b = torch.rand(10, requires_grad=True).cuda()
>>> b.is_leaf
False
# b was created by the operation that cast a cpu Tensor into a cuda Tensor
>>> c = torch.rand(10, requires_grad=True) + 2
>>> c.is_leaf
False
# c was created by the addition operation
>>> d = torch.rand(10).cuda()
>>> d.is_leaf
True
# d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
>>> e = torch.rand(10).cuda().requires_grad_()
>>> e.is_leaf
True
# e requires gradients and has no operations creating it
>>> f = torch.rand(10, requires_grad=True, device="cuda")
>>> f.is_leaf
True
# f requires grad, has no operation creating it
backward(gradient=None, retain_graph=None, create_graph=False, inputs=None) [source]
Computes the gradient of current tensor w.r.t. graph leaves. The graph is differentiated using the chain rule. If the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. It should be a tensor of matching type and location, that contains the gradient of the differentiated function w.r.t. self. This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients. Note If you run any forward ops, create gradient, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes. Parameters
gradient (Tensor or None) – Gradient w.r.t. the tensor. If it is a tensor, it will be automatically converted to a Tensor that does not require grad unless create_graph is True. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable then this argument is optional.
retain_graph (bool, optional) – If False, the graph used to compute the grads will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.
inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be accumulated into .grad. All other Tensors will be ignored. If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors. All the provided inputs must be leaf Tensors.
detach()
Returns a new Tensor, detached from the current graph. The result will never require gradient. Note Returned Tensor shares the same storage with the original one. In-place modifications on either of them will be seen, and may trigger errors in correctness checks. IMPORTANT NOTE: Previously, in-place size / stride / storage changes (such as resize_ / resize_as_ / set_ / transpose_) to the returned tensor also update the original tensor. Now, these in-place changes will not update the original tensor anymore, and will instead trigger an error. For sparse tensors: In-place indices / values changes (such as zero_ / copy_ / add_) to the returned tensor will not update the original tensor anymore, and will instead trigger an error.
detach_()
Detaches the Tensor from the graph that created it, making it a leaf. Views cannot be detached in-place.
register_hook(hook) [source]
Registers a backward hook. The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature: hook(grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of grad. This function returns a handle with a method handle.remove() that removes the hook from the module. Example: >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v.grad
2
4
6
[torch.FloatTensor of size (3,)]
>>> h.remove() # removes the hook
retain_grad() [source]
Enables .grad attribute for non-leaf Tensors.
Function
class torch.autograd.Function [source]
Records operation history and defines formulas for differentiating ops. See the Note on extending the autograd engine for more details on how to use this class: https://pytorch.org/docs/stable/notes/extending.html#extending-torch-autograd Every operation performed on Tensor s creates a new function object, that performs the computation, and records that it happened. The history is retained in the form of a DAG of functions, with edges denoting data dependencies (input <- output). Then, when backward is called, the graph is processed in the topological ordering, by calling backward() methods of each Function object, and passing returned gradients on to next Function s. Normally, the only way users interact with functions is by creating subclasses and defining new operations. This is a recommended way of extending torch.autograd. Examples: >>> class Exp(Function):
>>>
>>> @staticmethod
>>> def forward(ctx, i):
>>> result = i.exp()
>>> ctx.save_for_backward(result)
>>> return result
>>>
>>> @staticmethod
>>> def backward(ctx, grad_output):
>>> result, = ctx.saved_tensors
>>> return grad_output * result
>>>
>>> #Use it by calling the apply method:
>>> output = Exp.apply(input)
static backward(ctx, *grad_outputs) [source]
Defines a formula for differentiating the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by as many outputs did forward() return, and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computated w.r.t. the output.
static forward(ctx, *args, **kwargs) [source]
Performs the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types). The context can be used to store tensors that can be then retrieved during the backward pass.
Context method mixins When creating a new Function, the following methods are available to ctx.
class torch.autograd.function._ContextMethodMixin [source]
mark_dirty(*args) [source]
Marks given tensors as modified in an in-place operation. This should be called at most once, only from inside the forward() method, and all arguments should be inputs. Every tensor that’s been modified in-place in a call to forward() should be given to this function, to ensure correctness of our checks. It doesn’t matter whether the function is called before or after modification.
mark_non_differentiable(*args) [source]
Marks outputs as non-differentiable. This should be called at most once, only from inside the forward() method, and all arguments should be outputs. This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in backward(), but it’s always going to be a zero tensor with the same shape as the shape of a corresponding output. This is used e.g. for indices returned from a max Function.
save_for_backward(*tensors) [source]
Saves given tensors for a future call to backward(). This should be called at most once, and only from inside the forward() method. Later, saved tensors can be accessed through the saved_tensors attribute. Before returning them to the user, a check is made to ensure they weren’t used in any in-place operation that modified their content. Arguments can also be None.
set_materialize_grads(value) [source]
Sets whether to materialize output grad tensors. Default is true. This should be called only from inside the forward() method If true, undefined output grad tensors will be expanded to tensors full of zeros prior to calling the backward() method.
Numerical gradient checking
torch.autograd.gradcheck(func, inputs, eps=1e-06, atol=1e-05, rtol=0.001, raise_exception=True, check_sparse_nnz=False, nondet_tol=0.0, check_undefined_grad=True, check_grad_dtypes=False, check_batched_grad=False) [source]
Check gradients computed via small finite differences against analytical gradients w.r.t. tensors in inputs that are of floating point or complex type and with requires_grad=True. The check between numerical and analytical gradients uses allclose(). For complex functions, no notion of Jacobian exists. Gradcheck verifies if the numerical and analytical values of Wirtinger and Conjugate Wirtinger derivative are consistent. The gradient computation is done under the assumption that the overall function has a real valued output. For functions with complex output, gradcheck compares the numerical and analytical gradients for two values of grad_output: 1 and 1j. For more details, check out Autograd for Complex Numbers. Note The default values are designed for input of double precision. This check will likely fail if input is of less precision, e.g., FloatTensor. Warning If any checked tensor in input has overlapping memory, i.e., different indices pointing to the same memory address (e.g., from torch.expand()), this check will likely fail because the numerical gradients computed by point perturbation at such indices will change values at all other indices that share the same memory address. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor or a tuple of Tensors
inputs (tuple of Tensor or Tensor) – inputs to the function
eps (float, optional) – perturbation for finite differences
atol (float, optional) – absolute tolerance
rtol (float, optional) – relative tolerance
raise_exception (bool, optional) – indicating whether to raise an exception if the check fails. The exception gives more information about the exact nature of the failure. This is helpful when debugging gradchecks.
check_sparse_nnz (bool, optional) – if True, gradcheck allows for SparseTensor input, and for any SparseTensor at input, gradcheck will perform check at nnz positions only.
nondet_tol (float, optional) – tolerance for non-determinism. When running identical inputs through the differentiation, the results must either match exactly (default, 0.0) or be within this tolerance.
check_undefined_grad (bool, optional) – if True, check if undefined output grads are supported and treated as zeros, for Tensor outputs.
check_batched_grad (bool, optional) – if True, check if we can compute batched gradients using prototype vmap support. Defaults to False. Returns
True if all differences satisfy allclose condition
torch.autograd.gradgradcheck(func, inputs, grad_outputs=None, eps=1e-06, atol=1e-05, rtol=0.001, gen_non_contig_grad_outputs=False, raise_exception=True, nondet_tol=0.0, check_undefined_grad=True, check_grad_dtypes=False, check_batched_grad=False) [source]
Check gradients of gradients computed via small finite differences against analytical gradients w.r.t. tensors in inputs and grad_outputs that are of floating point or complex type and with requires_grad=True. This function checks that backpropagating through the gradients computed to the given grad_outputs are correct. The check between numerical and analytical gradients uses allclose(). Note The default values are designed for input and grad_outputs of double precision. This check will likely fail if they are of less precision, e.g., FloatTensor. Warning If any checked tensor in input and grad_outputs has overlapping memory, i.e., different indices pointing to the same memory address (e.g., from torch.expand()), this check will likely fail because the numerical gradients computed by point perturbation at such indices will change values at all other indices that share the same memory address. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor or a tuple of Tensors
inputs (tuple of Tensor or Tensor) – inputs to the function
grad_outputs (tuple of Tensor or Tensor, optional) – The gradients with respect to the function’s outputs.
eps (float, optional) – perturbation for finite differences
atol (float, optional) – absolute tolerance
rtol (float, optional) – relative tolerance
gen_non_contig_grad_outputs (bool, optional) – if grad_outputs is None and gen_non_contig_grad_outputs is True, the randomly generated gradient outputs are made to be noncontiguous
raise_exception (bool, optional) – indicating whether to raise an exception if the check fails. The exception gives more information about the exact nature of the failure. This is helpful when debugging gradchecks.
nondet_tol (float, optional) – tolerance for non-determinism. When running identical inputs through the differentiation, the results must either match exactly (default, 0.0) or be within this tolerance. Note that a small amount of nondeterminism in the gradient will lead to larger inaccuracies in the second derivative.
check_undefined_grad (bool, optional) – if True, check if undefined output grads are supported and treated as zeros
check_batched_grad (bool, optional) – if True, check if we can compute batched gradients using prototype vmap support. Defaults to False. Returns
True if all differences satisfy allclose condition
Profiler Autograd includes a profiler that lets you inspect the cost of different operators inside your model - both on the CPU and GPU. There are two modes implemented at the moment - CPU-only using profile. and nvprof based (registers both CPU and GPU activity) using emit_nvtx.
class torch.autograd.profiler.profile(enabled=True, *, use_cuda=False, record_shapes=False, with_flops=False, profile_memory=False, with_stack=False, use_kineto=False, use_cpu=True) [source]
Context manager that manages autograd profiler state and holds a summary of results. Under the hood it just records events of functions being executed in C++ and exposes those events to Python. You can wrap any code into it and it will only report runtime of PyTorch functions. Note: profiler is thread local and is automatically propagated into the async tasks Parameters
enabled (bool, optional) – Setting this to False makes this context manager a no-op.
use_cuda (bool, optional) – Enables timing of CUDA events as well using the cudaEvent API. Adds approximately 4us of overhead to each tensor operation.
record_shapes (bool, optional) – If shapes recording is set, information about input dimensions will be collected. This allows one to see which dimensions have been used under the hood and further group by them using prof.key_averages(group_by_input_shape=True). Please note that shape recording might skew your profiling data. It is recommended to use separate runs with and without shape recording to validate the timing. Most likely the skew will be negligible for bottom most events (in a case of nested function calls). But for higher level functions the total self cpu time might be artificially increased because of the shape collection.
with_flops (bool, optional) – If with_flops is set, the profiler will estimate the FLOPS (floating pointer operations per second) value using the operator’s input shape and total time. This allows one to estimate the hardware performance. Currently, this option only works for the matrix multiplication and 2D convolution operators.
profile_memory (bool, optional) – track tensor memory allocation/deallocation.
with_stack (bool, optional) – record source information (file and line number) for the ops.
use_kineto (bool, optional) – experimental, enable profiling with Kineto profiler.
use_cpu (bool, optional) – profile CPU events; setting to False requires use_kineto=True and can be used to lower the overhead for GPU-only profiling. Example >>> x = torch.randn((1, 1), requires_grad=True)
>>> with torch.autograd.profiler.profile() as prof:
>>> for _ in range(100): # any normal python code, really!
>>> y = x ** 2
>> y.backward()
>>> # NOTE: some columns were removed for brevity
>>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
----------------------------------- --------------- --------------- ---------------
Name Self CPU total CPU time avg Number of Calls
----------------------------------- --------------- --------------- ---------------
mul 32.048ms 32.048ms 200
pow 27.041ms 27.041ms 200
PowBackward0 9.727ms 55.483ms 100
torch::autograd::AccumulateGrad 9.148ms 9.148ms 100
torch::autograd::GraphRoot 691.816us 691.816us 100
----------------------------------- --------------- --------------- ---------------
export_chrome_trace(path) [source]
Exports an EventList as a Chrome tracing tools file. The checkpoint can be later loaded and inspected under chrome://tracing URL. Parameters
path (str) – Path where the trace will be written.
key_averages(group_by_input_shape=False, group_by_stack_n=0) [source]
Averages all function events over their keys. Parameters
group_by_input_shapes – group entries by
name, input shapes) rather than just event name. ((event) –
is useful to see which input shapes contribute to the runtime (This) –
most and may help with size-specific optimizations or (the) –
the best candidates for quantization (choosing) –
group_by_stack_n – group by top n stack trace entries Returns
An EventList containing FunctionEventAvg objects.
property self_cpu_time_total
Returns total time spent on CPU obtained as a sum of all self times across all the events.
table(sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False) [source]
Prints an EventList as a nicely formatted table. Parameters
sort_by (str, optional) – Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: cpu_time, cuda_time, cpu_time_total, cuda_time_total, cpu_memory_usage, cuda_memory_usage, self_cpu_memory_usage, self_cuda_memory_usage, count.
top_level_events_only (bool, optional) – Boolean flag to determine the selection of events to display. If true, the profiler will only display events at top level like top-level invocation of python lstm, python add or other functions, nested events like low-level cpu/cuda ops events are omitted for profiler result readability. Returns
A string containing the table.
total_average() [source]
Averages all events. Returns
A FunctionEventAvg object.
class torch.autograd.profiler.emit_nvtx(enabled=True, record_shapes=False) [source]
Context manager that makes every autograd operation emit an NVTX range. It is useful when running the program under nvprof: nvprof --profile-from-start off -o trace_name.prof -- <regular command here>
Unfortunately, there’s no way to force nvprof to flush the data it collected to disk, so for CUDA profiling one has to use this context manager to annotate nvprof traces and wait for the process to exit before inspecting them. Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or torch.autograd.profiler.load_nvprof() can load the results for inspection e.g. in Python REPL. Parameters
enabled (bool, optional, default=True) – Setting enabled=False makes this context manager a no-op. Default: True.
record_shapes (bool, optional, default=False) – If record_shapes=True, the nvtx range wrapping each autograd op will append information about the sizes of Tensor arguments received by that op, in the following format: [[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...] Non-tensor arguments will be represented by []. Arguments will be listed in the order they are received by the backend op. Please note that this order may not match the order in which those arguments were passed on the Python side. Also note that shape recording may increase the overhead of nvtx range creation. Example >>> with torch.cuda.profiler.profile():
... model(x) # Warmup CUDA memory allocator and profiler
... with torch.autograd.profiler.emit_nvtx():
... model(x)
Forward-backward correlation When viewing a profile created using emit_nvtx in the Nvidia Visual Profiler, correlating each backward-pass op with the corresponding forward-pass op can be difficult. To ease this task, emit_nvtx appends sequence number information to the ranges it generates. During the forward pass, each function range is decorated with seq=<N>. seq is a running counter, incremented each time a new backward Function object is created and stashed for backward. Thus, the seq=<N> annotation associated with each forward function range tells you that if a backward Function object is created by this forward function, the backward object will receive sequence number N. During the backward pass, the top-level range wrapping each C++ backward Function’s apply() call is decorated with stashed seq=<M>. M is the sequence number that the backward object was created with. By comparing stashed seq numbers in backward with seq numbers in forward, you can track down which forward op created each backward Function. Any functions executed during the backward pass are also decorated with seq=<N>. During default backward (with create_graph=False) this information is irrelevant, and in fact, N may simply be 0 for all such functions. Only the top-level ranges associated with backward Function objects’ apply() methods are useful, as a way to correlate these Function objects with the earlier forward pass. Double-backward If, on the other hand, a backward pass with create_graph=True is underway (in other words, if you are setting up for a double-backward), each function’s execution during backward is given a nonzero, useful seq=<N>. Those functions may themselves create Function objects to be executed later during double-backward, just as the original functions in the forward pass did. The relationship between backward and double-backward is conceptually the same as the relationship between forward and backward: The functions still emit current-sequence-number-tagged ranges, the Function objects they create still stash those sequence numbers, and during the eventual double-backward, the Function objects’ apply() ranges are still tagged with stashed seq numbers, which can be compared to seq numbers from the backward pass.
torch.autograd.profiler.load_nvprof(path) [source]
Opens an nvprof trace file and parses autograd annotations. Parameters
path (str) – path to nvprof trace
Anomaly detection
class torch.autograd.detect_anomaly [source]
Context-manager that enable anomaly detection for the autograd engine. This does two things: Running the forward pass with detection enabled will allow the backward pass to print the traceback of the forward operation that created the failing backward function. Any backward computation that generate “nan” value will raise an error. Warning This mode should be enabled only for debugging as the different tests will slow down your program execution. Example >>> import torch
>>> from torch import autograd
>>> class MyFunc(autograd.Function):
... @staticmethod
... def forward(ctx, inp):
... return inp.clone()
... @staticmethod
... def backward(ctx, gO):
... # Error during the backward pass
... raise RuntimeError("Some error in backward")
... return gO.clone()
>>> def run_fn(a):
... out = MyFunc.apply(a)
... return out.sum()
>>> inp = torch.rand(10, 10, requires_grad=True)
>>> out = run_fn(inp)
>>> out.backward()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/your/pytorch/install/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
return self._forward_cls.backward(self, *args)
File "<stdin>", line 8, in backward
RuntimeError: Some error in backward
>>> with autograd.detect_anomaly():
... inp = torch.rand(10, 10, requires_grad=True)
... out = run_fn(inp)
... out.backward()
Traceback of forward call that caused the error:
File "tmp.py", line 53, in <module>
out = run_fn(inp)
File "tmp.py", line 44, in run_fn
out = MyFunc.apply(a)
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/your/pytorch/install/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
return self._forward_cls.backward(self, *args)
File "<stdin>", line 8, in backward
RuntimeError: Some error in backward
class torch.autograd.set_detect_anomaly(mode) [source]
Context-manager that sets the anomaly detection for the autograd engine on or off. set_detect_anomaly will enable or disable the autograd anomaly detection based on its argument mode. It can be used as a context-manager or as a function. See detect_anomaly above for details of the anomaly detection behaviour. Parameters
mode (bool) – Flag whether to enable anomaly detection (True), or disable (False). | torch.autograd |
torch.autograd.backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False, grad_variables=None, inputs=None) [source]
Computes the sum of gradients of given tensors w.r.t. graph leaves. The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient, then the Jacobian-vector product would be computed, in this case the function additionally requires specifying grad_tensors. It should be a sequence of matching length, that contains the “vector” in the Jacobian-vector product, usually the gradient of the differentiated function w.r.t. corresponding tensors (None is an acceptable value for all tensors that don’t need gradient tensors). This function accumulates gradients in the leaves - you might need to zero .grad attributes or set them to None before calling it. See Default gradient layouts for details on the memory layout of accumulated gradients. Note Using this method with create_graph=True will create a reference cycle between the parameter and its gradient which can cause a memory leak. We recommend using autograd.grad when creating the graph to avoid this. If you have to use this function, make sure to reset the .grad fields of your parameters to None after use to break the cycle and avoid the leak. Note If you run any forward ops, create grad_tensors, and/or call backward in a user-specified CUDA stream context, see Stream semantics of backward passes. Parameters
tensors (sequence of Tensor) – Tensors of which the derivative will be computed.
grad_tensors (sequence of (Tensor or None)) – The “vector” in the Jacobian-vector product, usually gradients w.r.t. each element of corresponding tensors. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable for all grad_tensors, then this argument is optional.
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.
inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be accumulated into .grad. All other Tensors will be ignored. If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors. All the provided inputs must be leaf Tensors. | torch.autograd#torch.autograd.backward |
class torch.autograd.detect_anomaly [source]
Context-manager that enable anomaly detection for the autograd engine. This does two things: Running the forward pass with detection enabled will allow the backward pass to print the traceback of the forward operation that created the failing backward function. Any backward computation that generate “nan” value will raise an error. Warning This mode should be enabled only for debugging as the different tests will slow down your program execution. Example >>> import torch
>>> from torch import autograd
>>> class MyFunc(autograd.Function):
... @staticmethod
... def forward(ctx, inp):
... return inp.clone()
... @staticmethod
... def backward(ctx, gO):
... # Error during the backward pass
... raise RuntimeError("Some error in backward")
... return gO.clone()
>>> def run_fn(a):
... out = MyFunc.apply(a)
... return out.sum()
>>> inp = torch.rand(10, 10, requires_grad=True)
>>> out = run_fn(inp)
>>> out.backward()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/your/pytorch/install/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
return self._forward_cls.backward(self, *args)
File "<stdin>", line 8, in backward
RuntimeError: Some error in backward
>>> with autograd.detect_anomaly():
... inp = torch.rand(10, 10, requires_grad=True)
... out = run_fn(inp)
... out.backward()
Traceback of forward call that caused the error:
File "tmp.py", line 53, in <module>
out = run_fn(inp)
File "tmp.py", line 44, in run_fn
out = MyFunc.apply(a)
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/your/pytorch/install/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/your/pytorch/install/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
File "/your/pytorch/install/torch/autograd/function.py", line 76, in apply
return self._forward_cls.backward(self, *args)
File "<stdin>", line 8, in backward
RuntimeError: Some error in backward | torch.autograd#torch.autograd.detect_anomaly |
class torch.autograd.enable_grad [source]
Context-manager that enables gradient calculation. Enables gradient calculation, if it has been disabled via no_grad or set_grad_enabled. This context manager is thread local; it will not affect computation in other threads. Also functions as a decorator. (Make sure to instantiate with parenthesis.) Example: >>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... with torch.enable_grad():
... y = x * 2
>>> y.requires_grad
True
>>> y.backward()
>>> x.grad
>>> @torch.enable_grad()
... def doubler(x):
... return x * 2
>>> with torch.no_grad():
... z = doubler(x)
>>> z.requires_grad
True | torch.autograd#torch.autograd.enable_grad |
class torch.autograd.Function [source]
Records operation history and defines formulas for differentiating ops. See the Note on extending the autograd engine for more details on how to use this class: https://pytorch.org/docs/stable/notes/extending.html#extending-torch-autograd Every operation performed on Tensor s creates a new function object, that performs the computation, and records that it happened. The history is retained in the form of a DAG of functions, with edges denoting data dependencies (input <- output). Then, when backward is called, the graph is processed in the topological ordering, by calling backward() methods of each Function object, and passing returned gradients on to next Function s. Normally, the only way users interact with functions is by creating subclasses and defining new operations. This is a recommended way of extending torch.autograd. Examples: >>> class Exp(Function):
>>>
>>> @staticmethod
>>> def forward(ctx, i):
>>> result = i.exp()
>>> ctx.save_for_backward(result)
>>> return result
>>>
>>> @staticmethod
>>> def backward(ctx, grad_output):
>>> result, = ctx.saved_tensors
>>> return grad_output * result
>>>
>>> #Use it by calling the apply method:
>>> output = Exp.apply(input)
static backward(ctx, *grad_outputs) [source]
Defines a formula for differentiating the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by as many outputs did forward() return, and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computated w.r.t. the output.
static forward(ctx, *args, **kwargs) [source]
Performs the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types). The context can be used to store tensors that can be then retrieved during the backward pass. | torch.autograd#torch.autograd.Function |
static backward(ctx, *grad_outputs) [source]
Defines a formula for differentiating the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by as many outputs did forward() return, and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computated w.r.t. the output. | torch.autograd#torch.autograd.Function.backward |
static forward(ctx, *args, **kwargs) [source]
Performs the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types). The context can be used to store tensors that can be then retrieved during the backward pass. | torch.autograd#torch.autograd.Function.forward |
class torch.autograd.function._ContextMethodMixin [source]
mark_dirty(*args) [source]
Marks given tensors as modified in an in-place operation. This should be called at most once, only from inside the forward() method, and all arguments should be inputs. Every tensor that’s been modified in-place in a call to forward() should be given to this function, to ensure correctness of our checks. It doesn’t matter whether the function is called before or after modification.
mark_non_differentiable(*args) [source]
Marks outputs as non-differentiable. This should be called at most once, only from inside the forward() method, and all arguments should be outputs. This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in backward(), but it’s always going to be a zero tensor with the same shape as the shape of a corresponding output. This is used e.g. for indices returned from a max Function.
save_for_backward(*tensors) [source]
Saves given tensors for a future call to backward(). This should be called at most once, and only from inside the forward() method. Later, saved tensors can be accessed through the saved_tensors attribute. Before returning them to the user, a check is made to ensure they weren’t used in any in-place operation that modified their content. Arguments can also be None.
set_materialize_grads(value) [source]
Sets whether to materialize output grad tensors. Default is true. This should be called only from inside the forward() method If true, undefined output grad tensors will be expanded to tensors full of zeros prior to calling the backward() method. | torch.autograd#torch.autograd.function._ContextMethodMixin |
mark_dirty(*args) [source]
Marks given tensors as modified in an in-place operation. This should be called at most once, only from inside the forward() method, and all arguments should be inputs. Every tensor that’s been modified in-place in a call to forward() should be given to this function, to ensure correctness of our checks. It doesn’t matter whether the function is called before or after modification. | torch.autograd#torch.autograd.function._ContextMethodMixin.mark_dirty |
mark_non_differentiable(*args) [source]
Marks outputs as non-differentiable. This should be called at most once, only from inside the forward() method, and all arguments should be outputs. This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in backward(), but it’s always going to be a zero tensor with the same shape as the shape of a corresponding output. This is used e.g. for indices returned from a max Function. | torch.autograd#torch.autograd.function._ContextMethodMixin.mark_non_differentiable |
save_for_backward(*tensors) [source]
Saves given tensors for a future call to backward(). This should be called at most once, and only from inside the forward() method. Later, saved tensors can be accessed through the saved_tensors attribute. Before returning them to the user, a check is made to ensure they weren’t used in any in-place operation that modified their content. Arguments can also be None. | torch.autograd#torch.autograd.function._ContextMethodMixin.save_for_backward |
set_materialize_grads(value) [source]
Sets whether to materialize output grad tensors. Default is true. This should be called only from inside the forward() method If true, undefined output grad tensors will be expanded to tensors full of zeros prior to calling the backward() method. | torch.autograd#torch.autograd.function._ContextMethodMixin.set_materialize_grads |
torch.autograd.functional.hessian(func, inputs, create_graph=False, strict=False, vectorize=False) [source]
Function that computes the Hessian of a given scalar function. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
create_graph (bool, optional) – If True, the Hessian will be computed in a differentiable manner. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the hessian for said inputs, which is the expected mathematical value. Defaults to False.
vectorize (bool, optional) – This feature is experimental, please use at your own risk. When computing the hessian, usually we invoke autograd.grad once per row of the hessian. If this flag is True, we use the vmap prototype feature as the backend to vectorize calls to autograd.grad so we only invoke it once instead of once per row. This should lead to performance improvements in many use cases, however, due to this feature being incomplete, there may be performance cliffs. Please use torch._C._debug_only_display_vmap_fallback_warnings(True) to show any performance warnings and file us issues if warnings exist for your use case. Defaults to False. Returns
if there is a single input, this will be a single Tensor containing the Hessian for the input. If it is a tuple, then the Hessian will be a tuple of tuples where Hessian[i][j] will contain the Hessian of the ith input and jth input with size the sum of the size of the ith input plus the size of the jth input. Hessian[i][j] will have the same dtype and device as the corresponding ith input. Return type
Hessian (Tensor or a tuple of tuple of Tensors) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> hessian(pow_reducer, inputs)
tensor([[[[5.2265, 0.0000],
[0.0000, 0.0000]],
[[0.0000, 4.8221],
[0.0000, 0.0000]]],
[[[0.0000, 0.0000],
[1.9456, 0.0000]],
[[0.0000, 0.0000],
[0.0000, 3.2550]]]])
>>> hessian(pow_reducer, inputs, create_graph=True)
tensor([[[[5.2265, 0.0000],
[0.0000, 0.0000]],
[[0.0000, 4.8221],
[0.0000, 0.0000]]],
[[[0.0000, 0.0000],
[1.9456, 0.0000]],
[[0.0000, 0.0000],
[0.0000, 3.2550]]]], grad_fn=<ViewBackward>)
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> hessian(pow_adder_reducer, inputs)
((tensor([[4., 0.],
[0., 4.]]),
tensor([[0., 0.],
[0., 0.]])),
(tensor([[0., 0.],
[0., 0.]]),
tensor([[6., 0.],
[0., 6.]]))) | torch.autograd#torch.autograd.functional.hessian |
torch.autograd.functional.hvp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between the Hessian of a given scalar function and a vector v at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the Hessian vector product is computed. Must be the same size as the input of func. This argument is optional when func’s input contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the hvp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) hvp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> hvp(pow_reducer, inputs, v)
(tensor(0.1448),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]]))
>>> hvp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.1448, grad_fn=<SumBackward0>),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> hvp(pow_adder_reducer, inputs, v)
(tensor(2.3030),
(tensor([0., 0.]),
tensor([6., 6.])))
Note This function is significantly slower than vhp due to backward mode AD constraints. If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you know that your function satisfies this condition, you should use vhp instead that is much faster with the current implementation. | torch.autograd#torch.autograd.functional.hvp |
torch.autograd.functional.jacobian(func, inputs, create_graph=False, strict=False, vectorize=False) [source]
Function that computes the Jacobian of a given function. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
create_graph (bool, optional) – If True, the Jacobian will be computed in a differentiable manner. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the jacobian for said inputs, which is the expected mathematical value. Defaults to False.
vectorize (bool, optional) – This feature is experimental, please use at your own risk. When computing the jacobian, usually we invoke autograd.grad once per row of the jacobian. If this flag is True, we use the vmap prototype feature as the backend to vectorize calls to autograd.grad so we only invoke it once instead of once per row. This should lead to performance improvements in many use cases, however, due to this feature being incomplete, there may be performance cliffs. Please use torch._C._debug_only_display_vmap_fallback_warnings(True) to show any performance warnings and file us issues if warnings exist for your use case. Defaults to False. Returns
if there is a single input and output, this will be a single Tensor containing the Jacobian for the linearized inputs and output. If one of the two is a tuple, then the Jacobian will be a tuple of Tensors. If both of them are tuples, then the Jacobian will be a tuple of tuple of Tensors where Jacobian[i][j] will contain the Jacobian of the ith output and jth input and will have as size the concatenation of the sizes of the corresponding output and the corresponding input and will have same dtype and device as the corresponding input. Return type
Jacobian (Tensor or nested tuple of Tensors) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(2, 2)
>>> jacobian(exp_reducer, inputs)
tensor([[[1.4917, 2.4352],
[0.0000, 0.0000]],
[[0.0000, 0.0000],
[2.4369, 2.3799]]])
>>> jacobian(exp_reducer, inputs, create_graph=True)
tensor([[[1.4917, 2.4352],
[0.0000, 0.0000]],
[[0.0000, 0.0000],
[2.4369, 2.3799]]], grad_fn=<ViewBackward>)
>>> def exp_adder(x, y):
... return 2 * x.exp() + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> jacobian(exp_adder, inputs)
(tensor([[2.8052, 0.0000],
[0.0000, 3.3963]]),
tensor([[3., 0.],
[0., 3.]])) | torch.autograd#torch.autograd.functional.jacobian |
torch.autograd.functional.jvp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between the Jacobian of the given function at the point given by the inputs and a vector v. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the Jacobian vector product is computed. Must be the same size as the input of func. This argument is optional when the input to func contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the jvp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) jvp (tuple of Tensors or Tensor): result of the dot product with the same shape as the output. Return type
output (tuple) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(4, 4)
>>> v = torch.ones(4, 4)
>>> jvp(exp_reducer, inputs, v)
(tensor([6.3090, 4.6742, 7.9114, 8.2106]),
tensor([6.3090, 4.6742, 7.9114, 8.2106]))
>>> jvp(exp_reducer, inputs, v, create_graph=True)
(tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SumBackward1>),
tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SqueezeBackward1>))
>>> def adder(x, y):
... return 2 * x + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.ones(2), torch.ones(2))
>>> jvp(adder, inputs, v)
(tensor([2.2399, 2.5005]),
tensor([5., 5.]))
Note The jvp is currently computed by using the backward of the backward (sometimes called the double backwards trick) as we don’t have support for forward mode AD in PyTorch at the moment. | torch.autograd#torch.autograd.functional.jvp |
torch.autograd.functional.vhp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between a vector v and the Hessian of a given scalar function at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor with a single element.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the vector Hessian product is computed. Must be the same size as the input of func. This argument is optional when func’s input contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the vhp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) vhp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> vhp(pow_reducer, inputs, v)
(tensor(0.5591),
tensor([[1.0689, 1.2431],
[3.0989, 4.4456]]))
>>> vhp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.5591, grad_fn=<SumBackward0>),
tensor([[1.0689, 1.2431],
[3.0989, 4.4456]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> vhp(pow_adder_reducer, inputs, v)
(tensor(4.8053),
(tensor([0., 0.]),
tensor([6., 6.]))) | torch.autograd#torch.autograd.functional.vhp |
torch.autograd.functional.vjp(func, inputs, v=None, create_graph=False, strict=False) [source]
Function that computes the dot product between a vector v and the Jacobian of the given function at the point given by the inputs. Parameters
func (function) – a Python function that takes Tensor inputs and returns a tuple of Tensors or a Tensor.
inputs (tuple of Tensors or Tensor) – inputs to the function func.
v (tuple of Tensors or Tensor) – The vector for which the vector Jacobian product is computed. Must be the same size as the output of func. This argument is optional when the output of func contains a single element and (if it is not provided) will be set as a Tensor containing a single 1.
create_graph (bool, optional) – If True, both the output and result will be computed in a differentiable way. Note that when strict is False, the result can not require gradients or be disconnected from the inputs. Defaults to False.
strict (bool, optional) – If True, an error will be raised when we detect that there exists an input such that all the outputs are independent of it. If False, we return a Tensor of zeros as the vjp for said inputs, which is the expected mathematical value. Defaults to False. Returns
tuple with:
func_output (tuple of Tensors or Tensor): output of func(inputs) vjp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs. Return type
output (tuple) Example >>> def exp_reducer(x):
... return x.exp().sum(dim=1)
>>> inputs = torch.rand(4, 4)
>>> v = torch.ones(4)
>>> vjp(exp_reducer, inputs, v)
(tensor([5.7817, 7.2458, 5.7830, 6.7782]),
tensor([[1.4458, 1.3962, 1.3042, 1.6354],
[2.1288, 1.0652, 1.5483, 2.5035],
[2.2046, 1.1292, 1.1432, 1.3059],
[1.3225, 1.6652, 1.7753, 2.0152]]))
>>> vjp(exp_reducer, inputs, v, create_graph=True)
(tensor([5.7817, 7.2458, 5.7830, 6.7782], grad_fn=<SumBackward1>),
tensor([[1.4458, 1.3962, 1.3042, 1.6354],
[2.1288, 1.0652, 1.5483, 2.5035],
[2.2046, 1.1292, 1.1432, 1.3059],
[1.3225, 1.6652, 1.7753, 2.0152]], grad_fn=<MulBackward0>))
>>> def adder(x, y):
... return 2 * x + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = torch.ones(2)
>>> vjp(adder, inputs, v)
(tensor([2.4225, 2.3340]),
(tensor([2., 2.]), tensor([3., 3.]))) | torch.autograd#torch.autograd.functional.vjp |
torch.autograd.grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False, only_inputs=True, allow_unused=False) [source]
Computes and returns the sum of gradients of outputs w.r.t. the inputs. grad_outputs should be a sequence of length matching output containing the “vector” in Jacobian-vector product, usually the pre-computed gradients w.r.t. each of the outputs. If an output doesn’t require_grad, then the gradient can be None). If only_inputs is True, the function will only return a list of gradients w.r.t the specified inputs. If it’s False, then gradient w.r.t. all remaining leaves will still be computed, and will be accumulated into their .grad attribute. Note If you run any forward ops, create grad_outputs, and/or call grad in a user-specified CUDA stream context, see Stream semantics of backward passes. Parameters
outputs (sequence of Tensor) – outputs of the differentiated function.
inputs (sequence of Tensor) – Inputs w.r.t. which the gradient will be returned (and not accumulated into .grad).
grad_outputs (sequence of Tensor) – The “vector” in the Jacobian-vector product. Usually gradients w.r.t. each output. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable for all grad_tensors, then this argument is optional. Default: None.
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
create_graph (bool, optional) – If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Default: False.
allow_unused (bool, optional) – If False, specifying inputs that were not used when computing outputs (and therefore their grad is always zero) is an error. Defaults to False. | torch.autograd#torch.autograd.grad |
torch.autograd.gradcheck(func, inputs, eps=1e-06, atol=1e-05, rtol=0.001, raise_exception=True, check_sparse_nnz=False, nondet_tol=0.0, check_undefined_grad=True, check_grad_dtypes=False, check_batched_grad=False) [source]
Check gradients computed via small finite differences against analytical gradients w.r.t. tensors in inputs that are of floating point or complex type and with requires_grad=True. The check between numerical and analytical gradients uses allclose(). For complex functions, no notion of Jacobian exists. Gradcheck verifies if the numerical and analytical values of Wirtinger and Conjugate Wirtinger derivative are consistent. The gradient computation is done under the assumption that the overall function has a real valued output. For functions with complex output, gradcheck compares the numerical and analytical gradients for two values of grad_output: 1 and 1j. For more details, check out Autograd for Complex Numbers. Note The default values are designed for input of double precision. This check will likely fail if input is of less precision, e.g., FloatTensor. Warning If any checked tensor in input has overlapping memory, i.e., different indices pointing to the same memory address (e.g., from torch.expand()), this check will likely fail because the numerical gradients computed by point perturbation at such indices will change values at all other indices that share the same memory address. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor or a tuple of Tensors
inputs (tuple of Tensor or Tensor) – inputs to the function
eps (float, optional) – perturbation for finite differences
atol (float, optional) – absolute tolerance
rtol (float, optional) – relative tolerance
raise_exception (bool, optional) – indicating whether to raise an exception if the check fails. The exception gives more information about the exact nature of the failure. This is helpful when debugging gradchecks.
check_sparse_nnz (bool, optional) – if True, gradcheck allows for SparseTensor input, and for any SparseTensor at input, gradcheck will perform check at nnz positions only.
nondet_tol (float, optional) – tolerance for non-determinism. When running identical inputs through the differentiation, the results must either match exactly (default, 0.0) or be within this tolerance.
check_undefined_grad (bool, optional) – if True, check if undefined output grads are supported and treated as zeros, for Tensor outputs.
check_batched_grad (bool, optional) – if True, check if we can compute batched gradients using prototype vmap support. Defaults to False. Returns
True if all differences satisfy allclose condition | torch.autograd#torch.autograd.gradcheck |
torch.autograd.gradgradcheck(func, inputs, grad_outputs=None, eps=1e-06, atol=1e-05, rtol=0.001, gen_non_contig_grad_outputs=False, raise_exception=True, nondet_tol=0.0, check_undefined_grad=True, check_grad_dtypes=False, check_batched_grad=False) [source]
Check gradients of gradients computed via small finite differences against analytical gradients w.r.t. tensors in inputs and grad_outputs that are of floating point or complex type and with requires_grad=True. This function checks that backpropagating through the gradients computed to the given grad_outputs are correct. The check between numerical and analytical gradients uses allclose(). Note The default values are designed for input and grad_outputs of double precision. This check will likely fail if they are of less precision, e.g., FloatTensor. Warning If any checked tensor in input and grad_outputs has overlapping memory, i.e., different indices pointing to the same memory address (e.g., from torch.expand()), this check will likely fail because the numerical gradients computed by point perturbation at such indices will change values at all other indices that share the same memory address. Parameters
func (function) – a Python function that takes Tensor inputs and returns a Tensor or a tuple of Tensors
inputs (tuple of Tensor or Tensor) – inputs to the function
grad_outputs (tuple of Tensor or Tensor, optional) – The gradients with respect to the function’s outputs.
eps (float, optional) – perturbation for finite differences
atol (float, optional) – absolute tolerance
rtol (float, optional) – relative tolerance
gen_non_contig_grad_outputs (bool, optional) – if grad_outputs is None and gen_non_contig_grad_outputs is True, the randomly generated gradient outputs are made to be noncontiguous
raise_exception (bool, optional) – indicating whether to raise an exception if the check fails. The exception gives more information about the exact nature of the failure. This is helpful when debugging gradchecks.
nondet_tol (float, optional) – tolerance for non-determinism. When running identical inputs through the differentiation, the results must either match exactly (default, 0.0) or be within this tolerance. Note that a small amount of nondeterminism in the gradient will lead to larger inaccuracies in the second derivative.
check_undefined_grad (bool, optional) – if True, check if undefined output grads are supported and treated as zeros
check_batched_grad (bool, optional) – if True, check if we can compute batched gradients using prototype vmap support. Defaults to False. Returns
True if all differences satisfy allclose condition | torch.autograd#torch.autograd.gradgradcheck |
class torch.autograd.no_grad [source]
Context-manager that disabled gradient calculation. Disabling gradient calculation is useful for inference, when you are sure that you will not call Tensor.backward(). It will reduce memory consumption for computations that would otherwise have requires_grad=True. In this mode, the result of every computation will have requires_grad=False, even when the inputs have requires_grad=True. This context manager is thread local; it will not affect computation in other threads. Also functions as a decorator. (Make sure to instantiate with parenthesis.) Example: >>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
... return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False | torch.autograd#torch.autograd.no_grad |
class torch.autograd.profiler.emit_nvtx(enabled=True, record_shapes=False) [source]
Context manager that makes every autograd operation emit an NVTX range. It is useful when running the program under nvprof: nvprof --profile-from-start off -o trace_name.prof -- <regular command here>
Unfortunately, there’s no way to force nvprof to flush the data it collected to disk, so for CUDA profiling one has to use this context manager to annotate nvprof traces and wait for the process to exit before inspecting them. Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or torch.autograd.profiler.load_nvprof() can load the results for inspection e.g. in Python REPL. Parameters
enabled (bool, optional, default=True) – Setting enabled=False makes this context manager a no-op. Default: True.
record_shapes (bool, optional, default=False) – If record_shapes=True, the nvtx range wrapping each autograd op will append information about the sizes of Tensor arguments received by that op, in the following format: [[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...] Non-tensor arguments will be represented by []. Arguments will be listed in the order they are received by the backend op. Please note that this order may not match the order in which those arguments were passed on the Python side. Also note that shape recording may increase the overhead of nvtx range creation. Example >>> with torch.cuda.profiler.profile():
... model(x) # Warmup CUDA memory allocator and profiler
... with torch.autograd.profiler.emit_nvtx():
... model(x)
Forward-backward correlation When viewing a profile created using emit_nvtx in the Nvidia Visual Profiler, correlating each backward-pass op with the corresponding forward-pass op can be difficult. To ease this task, emit_nvtx appends sequence number information to the ranges it generates. During the forward pass, each function range is decorated with seq=<N>. seq is a running counter, incremented each time a new backward Function object is created and stashed for backward. Thus, the seq=<N> annotation associated with each forward function range tells you that if a backward Function object is created by this forward function, the backward object will receive sequence number N. During the backward pass, the top-level range wrapping each C++ backward Function’s apply() call is decorated with stashed seq=<M>. M is the sequence number that the backward object was created with. By comparing stashed seq numbers in backward with seq numbers in forward, you can track down which forward op created each backward Function. Any functions executed during the backward pass are also decorated with seq=<N>. During default backward (with create_graph=False) this information is irrelevant, and in fact, N may simply be 0 for all such functions. Only the top-level ranges associated with backward Function objects’ apply() methods are useful, as a way to correlate these Function objects with the earlier forward pass. Double-backward If, on the other hand, a backward pass with create_graph=True is underway (in other words, if you are setting up for a double-backward), each function’s execution during backward is given a nonzero, useful seq=<N>. Those functions may themselves create Function objects to be executed later during double-backward, just as the original functions in the forward pass did. The relationship between backward and double-backward is conceptually the same as the relationship between forward and backward: The functions still emit current-sequence-number-tagged ranges, the Function objects they create still stash those sequence numbers, and during the eventual double-backward, the Function objects’ apply() ranges are still tagged with stashed seq numbers, which can be compared to seq numbers from the backward pass. | torch.autograd#torch.autograd.profiler.emit_nvtx |
torch.autograd.profiler.load_nvprof(path) [source]
Opens an nvprof trace file and parses autograd annotations. Parameters
path (str) – path to nvprof trace | torch.autograd#torch.autograd.profiler.load_nvprof |
class torch.autograd.profiler.profile(enabled=True, *, use_cuda=False, record_shapes=False, with_flops=False, profile_memory=False, with_stack=False, use_kineto=False, use_cpu=True) [source]
Context manager that manages autograd profiler state and holds a summary of results. Under the hood it just records events of functions being executed in C++ and exposes those events to Python. You can wrap any code into it and it will only report runtime of PyTorch functions. Note: profiler is thread local and is automatically propagated into the async tasks Parameters
enabled (bool, optional) – Setting this to False makes this context manager a no-op.
use_cuda (bool, optional) – Enables timing of CUDA events as well using the cudaEvent API. Adds approximately 4us of overhead to each tensor operation.
record_shapes (bool, optional) – If shapes recording is set, information about input dimensions will be collected. This allows one to see which dimensions have been used under the hood and further group by them using prof.key_averages(group_by_input_shape=True). Please note that shape recording might skew your profiling data. It is recommended to use separate runs with and without shape recording to validate the timing. Most likely the skew will be negligible for bottom most events (in a case of nested function calls). But for higher level functions the total self cpu time might be artificially increased because of the shape collection.
with_flops (bool, optional) – If with_flops is set, the profiler will estimate the FLOPS (floating pointer operations per second) value using the operator’s input shape and total time. This allows one to estimate the hardware performance. Currently, this option only works for the matrix multiplication and 2D convolution operators.
profile_memory (bool, optional) – track tensor memory allocation/deallocation.
with_stack (bool, optional) – record source information (file and line number) for the ops.
use_kineto (bool, optional) – experimental, enable profiling with Kineto profiler.
use_cpu (bool, optional) – profile CPU events; setting to False requires use_kineto=True and can be used to lower the overhead for GPU-only profiling. Example >>> x = torch.randn((1, 1), requires_grad=True)
>>> with torch.autograd.profiler.profile() as prof:
>>> for _ in range(100): # any normal python code, really!
>>> y = x ** 2
>> y.backward()
>>> # NOTE: some columns were removed for brevity
>>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
----------------------------------- --------------- --------------- ---------------
Name Self CPU total CPU time avg Number of Calls
----------------------------------- --------------- --------------- ---------------
mul 32.048ms 32.048ms 200
pow 27.041ms 27.041ms 200
PowBackward0 9.727ms 55.483ms 100
torch::autograd::AccumulateGrad 9.148ms 9.148ms 100
torch::autograd::GraphRoot 691.816us 691.816us 100
----------------------------------- --------------- --------------- ---------------
export_chrome_trace(path) [source]
Exports an EventList as a Chrome tracing tools file. The checkpoint can be later loaded and inspected under chrome://tracing URL. Parameters
path (str) – Path where the trace will be written.
key_averages(group_by_input_shape=False, group_by_stack_n=0) [source]
Averages all function events over their keys. Parameters
group_by_input_shapes – group entries by
name, input shapes) rather than just event name. ((event) –
is useful to see which input shapes contribute to the runtime (This) –
most and may help with size-specific optimizations or (the) –
the best candidates for quantization (choosing) –
group_by_stack_n – group by top n stack trace entries Returns
An EventList containing FunctionEventAvg objects.
property self_cpu_time_total
Returns total time spent on CPU obtained as a sum of all self times across all the events.
table(sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False) [source]
Prints an EventList as a nicely formatted table. Parameters
sort_by (str, optional) – Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: cpu_time, cuda_time, cpu_time_total, cuda_time_total, cpu_memory_usage, cuda_memory_usage, self_cpu_memory_usage, self_cuda_memory_usage, count.
top_level_events_only (bool, optional) – Boolean flag to determine the selection of events to display. If true, the profiler will only display events at top level like top-level invocation of python lstm, python add or other functions, nested events like low-level cpu/cuda ops events are omitted for profiler result readability. Returns
A string containing the table.
total_average() [source]
Averages all events. Returns
A FunctionEventAvg object. | torch.autograd#torch.autograd.profiler.profile |
export_chrome_trace(path) [source]
Exports an EventList as a Chrome tracing tools file. The checkpoint can be later loaded and inspected under chrome://tracing URL. Parameters
path (str) – Path where the trace will be written. | torch.autograd#torch.autograd.profiler.profile.export_chrome_trace |
key_averages(group_by_input_shape=False, group_by_stack_n=0) [source]
Averages all function events over their keys. Parameters
group_by_input_shapes – group entries by
name, input shapes) rather than just event name. ((event) –
is useful to see which input shapes contribute to the runtime (This) –
most and may help with size-specific optimizations or (the) –
the best candidates for quantization (choosing) –
group_by_stack_n – group by top n stack trace entries Returns
An EventList containing FunctionEventAvg objects. | torch.autograd#torch.autograd.profiler.profile.key_averages |
property self_cpu_time_total
Returns total time spent on CPU obtained as a sum of all self times across all the events. | torch.autograd#torch.autograd.profiler.profile.self_cpu_time_total |
table(sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False) [source]
Prints an EventList as a nicely formatted table. Parameters
sort_by (str, optional) – Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: cpu_time, cuda_time, cpu_time_total, cuda_time_total, cpu_memory_usage, cuda_memory_usage, self_cpu_memory_usage, self_cuda_memory_usage, count.
top_level_events_only (bool, optional) – Boolean flag to determine the selection of events to display. If true, the profiler will only display events at top level like top-level invocation of python lstm, python add or other functions, nested events like low-level cpu/cuda ops events are omitted for profiler result readability. Returns
A string containing the table. | torch.autograd#torch.autograd.profiler.profile.table |
total_average() [source]
Averages all events. Returns
A FunctionEventAvg object. | torch.autograd#torch.autograd.profiler.profile.total_average |
class torch.autograd.set_detect_anomaly(mode) [source]
Context-manager that sets the anomaly detection for the autograd engine on or off. set_detect_anomaly will enable or disable the autograd anomaly detection based on its argument mode. It can be used as a context-manager or as a function. See detect_anomaly above for details of the anomaly detection behaviour. Parameters
mode (bool) – Flag whether to enable anomaly detection (True), or disable (False). | torch.autograd#torch.autograd.set_detect_anomaly |
class torch.autograd.set_grad_enabled(mode) [source]
Context-manager that sets gradient calculation to on or off. set_grad_enabled will enable or disable grads based on its argument mode. It can be used as a context-manager or as a function. This context manager is thread local; it will not affect computation in other threads. Parameters
mode (bool) – Flag whether to enable grad (True), or disable (False). This can be used to conditionally enable gradients. Example: >>> x = torch.tensor([1], requires_grad=True)
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
... y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True)
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False | torch.autograd#torch.autograd.set_grad_enabled |
torch.backends torch.backends controls the behavior of various backends that PyTorch supports. These backends include: torch.backends.cuda torch.backends.cudnn torch.backends.mkl torch.backends.mkldnn torch.backends.openmp torch.backends.cuda
torch.backends.cuda.is_built() [source]
Returns whether PyTorch is built with CUDA support. Note that this doesn’t necessarily mean CUDA is available; just that if this PyTorch binary were run a machine with working CUDA drivers and devices, we would be able to use it.
torch.backends.cuda.matmul.allow_tf32
A bool that controls whether TensorFloat-32 tensor cores may be used in matrix multiplications on Ampere or newer GPUs. See TensorFloat-32(TF32) on Ampere devices.
torch.backends.cuda.cufft_plan_cache
cufft_plan_cache caches the cuFFT plans
size
A readonly int that shows the number of plans currently in the cuFFT plan cache.
max_size
A int that controls cache capacity of cuFFT plan.
clear()
Clears the cuFFT plan cache.
torch.backends.cudnn
torch.backends.cudnn.version() [source]
Returns the version of cuDNN
torch.backends.cudnn.is_available() [source]
Returns a bool indicating if CUDNN is currently available.
torch.backends.cudnn.enabled
A bool that controls whether cuDNN is enabled.
torch.backends.cudnn.allow_tf32
A bool that controls where TensorFloat-32 tensor cores may be used in cuDNN convolutions on Ampere or newer GPUs. See TensorFloat-32(TF32) on Ampere devices.
torch.backends.cudnn.deterministic
A bool that, if True, causes cuDNN to only use deterministic convolution algorithms. See also torch.are_deterministic_algorithms_enabled() and torch.use_deterministic_algorithms().
torch.backends.cudnn.benchmark
A bool that, if True, causes cuDNN to benchmark multiple convolution algorithms and select the fastest.
torch.backends.mkl
torch.backends.mkl.is_available() [source]
Returns whether PyTorch is built with MKL support.
torch.backends.mkldnn
torch.backends.mkldnn.is_available() [source]
Returns whether PyTorch is built with MKL-DNN support.
torch.backends.openmp
torch.backends.openmp.is_available() [source]
Returns whether PyTorch is built with OpenMP support. | torch.backends |
torch.backends.cuda.cufft_plan_cache
cufft_plan_cache caches the cuFFT plans
size
A readonly int that shows the number of plans currently in the cuFFT plan cache.
max_size
A int that controls cache capacity of cuFFT plan.
clear()
Clears the cuFFT plan cache. | torch.backends#torch.backends.cuda.cufft_plan_cache |
torch.backends.cuda.is_built() [source]
Returns whether PyTorch is built with CUDA support. Note that this doesn’t necessarily mean CUDA is available; just that if this PyTorch binary were run a machine with working CUDA drivers and devices, we would be able to use it. | torch.backends#torch.backends.cuda.is_built |
torch.backends.cuda.matmul.allow_tf32
A bool that controls whether TensorFloat-32 tensor cores may be used in matrix multiplications on Ampere or newer GPUs. See TensorFloat-32(TF32) on Ampere devices. | torch.backends#torch.backends.cuda.matmul.allow_tf32 |
size
A readonly int that shows the number of plans currently in the cuFFT plan cache. | torch.backends#torch.backends.cuda.size |
torch.backends.cudnn.allow_tf32
A bool that controls where TensorFloat-32 tensor cores may be used in cuDNN convolutions on Ampere or newer GPUs. See TensorFloat-32(TF32) on Ampere devices. | torch.backends#torch.backends.cudnn.allow_tf32 |
torch.backends.cudnn.benchmark
A bool that, if True, causes cuDNN to benchmark multiple convolution algorithms and select the fastest. | torch.backends#torch.backends.cudnn.benchmark |
torch.backends.cudnn.deterministic
A bool that, if True, causes cuDNN to only use deterministic convolution algorithms. See also torch.are_deterministic_algorithms_enabled() and torch.use_deterministic_algorithms(). | torch.backends#torch.backends.cudnn.deterministic |
torch.backends.cudnn.enabled
A bool that controls whether cuDNN is enabled. | torch.backends#torch.backends.cudnn.enabled |
torch.backends.cudnn.is_available() [source]
Returns a bool indicating if CUDNN is currently available. | torch.backends#torch.backends.cudnn.is_available |
torch.backends.cudnn.version() [source]
Returns the version of cuDNN | torch.backends#torch.backends.cudnn.version |
torch.backends.mkl.is_available() [source]
Returns whether PyTorch is built with MKL support. | torch.backends#torch.backends.mkl.is_available |
torch.backends.mkldnn.is_available() [source]
Returns whether PyTorch is built with MKL-DNN support. | torch.backends#torch.backends.mkldnn.is_available |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.