Shortcuts

Attribute

class torch.jit.Attribute(value, type)[source]

This method is a pass-through function that returns value, mostly used to indicate to the TorchScript compiler that the left-hand side expression is a class instance attribute with type of type. Note that torch.jit.Attribute should only be used in __init__ method of nn.Module subclasses.

Though TorchScript can infer correct type for most Python expressions, there are some cases where type inference can be wrong, including:

  • Empty containers like [] and {}, which TorchScript assumes to be container of Tensor

  • Optional types like Optional[T] but assigned a valid value of type T, TorchScript would assume it is type T rather than Optional[T]

In eager mode, it is simply a pass-through function that returns value without other implications.

Example:

import torch
from typing import Dict

class AttributeModule(torch.nn.Module):
    def __init__(self):
        super(M, self).__init__()
        self.foo = torch.jit.Attribute(0.1, float)

        # we should be able to use self.foo as a float here
        assert 0.0 < self.foo

        self.names_ages = torch.jit.Attribute({}, Dict[str, int])
        self.names_ages["someone"] = 20
        assert isinstance(self.names_ages["someone"], int)

m = AttributeModule()
# m will contain two attributes
# 1. foo of type float
# 2. names_ages of type Dict[str, int]
Parameters
  • value – An initial value to be assigned to attribute.

  • type – A Python type

Returns

Returns value

count(value)integer return number of occurrences of value
index(value[, start[, stop]])integer return first index of value.

Raises ValueError if the value is not present.

property type

Alias for field number 1

property value

Alias for field number 0

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources