Attribute — PyTorch 2.7 documentation (original) (raw)

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 thattorch.jit.Attribute should only be used in __init__ method of jit.ScriptModulesubclasses.

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

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

Example:

import torch from typing import Dict

class AttributeModule(torch.jit.ScriptModule): def init(self) -> None: super().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]

Note: it’s now preferred to instead use type annotations instead of torch.jit.Attribute:

import torch from typing import Dict

class AttributeModule(torch.nn.Module): names: Dict[str, int]

def __init__(self) -> None:
    super().__init__()
    self.names = {}

m = AttributeModule()

Parameters

Returns

Returns value

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

type

Alias for field number 1

value

Alias for field number 0