Rate this Page

Attribute#

classtorch.jit.Attribute(value,type)#

This method is a pass-through function that returnsvalue, mostlyused to indicate to the TorchScript compiler that the left-hand sideexpression is a class instance attribute with type oftype. Note thattorch.jit.Attribute should only be used in__init__ method ofjit.ScriptModulesubclasses.

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

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

  • Optional types likeOptional[T] but assigned a valid value of typeT, TorchScript would assumeit is typeT rather thanOptional[T]

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

Example:

importtorchfromtypingimportDictclassAttributeModule(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 hereassert0.0<self.fooself.names_ages=torch.jit.Attribute({},Dict[str,int])self.names_ages["someone"]=20assertisinstance(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 oftorch.jit.Attribute:

importtorchfromtypingimportDictclassAttributeModule(torch.nn.Module):names:Dict[str,int]def__init__(self)->None:super().__init__()self.names={}m=AttributeModule()
Parameters
  • value – An initial value to be assigned to attribute.

  • type – A Python type

Returns

Returnsvalue

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