Skip to content

Commit d49c5c7

Browse files
Meghan Lelefacebook-github-bot
authored andcommitted
[docs] Add starter content for new TorchScript language reference (#52494)
Summary: **Summary** This commit adds a new .rst file to use for updating the language specification and prepopulates it with the updated content for the expressions section. **Test Plan** https://user-images.githubusercontent.com/4392003/110441235-638ee880-806e-11eb-83ae-3b908bf00d5b.mov Pull Request resolved: #52494 Reviewed By: nikithamalgifb Differential Revision: D26965463 Pulled By: SplitInfinity fbshipit-source-id: 246c76a56d911a8061e720abd200a44d7dfa1f35
1 parent ced91bb commit d49c5c7

2 files changed

Lines changed: 329 additions & 0 deletions

File tree

docs/source/jit.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ TorchScript
1616

1717
jit_language_reference
1818

19+
20+
.. toctree::
21+
:maxdepth: 1
22+
:caption: Language Reference V2
23+
24+
jit_language_reference_v2
25+
26+
1927
.. contents:: :local:
2028
:depth: 2
2129

Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
.. contents::
2+
:local:
3+
:depth: 2
4+
5+
6+
.. testsetup::
7+
8+
# These are hidden from the docs, but these are necessary for `doctest`
9+
# since the `inspect` module doesn't play nicely with the execution
10+
# environment for `doctest`
11+
import torch
12+
13+
original_script = torch.jit.script
14+
def script_wrapper(obj, *args, **kwargs):
15+
obj.__module__ = 'FakeMod'
16+
return original_script(obj, *args, **kwargs)
17+
18+
torch.jit.script = script_wrapper
19+
20+
original_trace = torch.jit.trace
21+
def trace_wrapper(obj, *args, **kwargs):
22+
obj.__module__ = 'FakeMod'
23+
return original_trace(obj, *args, **kwargs)
24+
25+
torch.jit.trace = trace_wrapper
26+
27+
.. _language-reference:
28+
29+
TorchScript Language Reference
30+
==============================
31+
32+
.. _expressions:
33+
34+
35+
Expressions
36+
~~~~~~~~~~~
37+
38+
The following section describes the grammar of expressions that are supported in TorchScript.
39+
It is modeled after `the expressions chapter of the Python language reference <https://docs.python.org/3/reference/expressions.html>`_.
40+
41+
Arithmetic Conversions
42+
^^^^^^^^^^^^^^^^^^^^^^
43+
There are a number of implicit type conversions that are performed in TorchScript:
44+
45+
46+
* a ``Tensor`` with a ``float`` or ``int`` datatype can be implicitly converted to an instance of ``FloatType`` or ``IntType`` provided that it has a size of 0, and does not have ``require_grad`` set to ``True`` and will not require narrowing.
47+
* instances of ``StringType`` can be implicitly converted to ``DeviceType``
48+
* the above implicit conversion rules can be applied to instances of ``TupleType`` to produce instances of ``ListType`` with the appropriate contained type
49+
50+
51+
Explicit conversions can be invoked using the ``float``, ``int``, ``bool``, ``str`` built-in functions
52+
that accept primitive data types as arguments and can accept user-defined types if they implement
53+
``__bool__``, ``__str__``, etc.
54+
55+
56+
Atoms
57+
^^^^^
58+
Atoms are the most basic elements of expressions.
59+
60+
::
61+
62+
atom ::= identifier | literal | enclosure
63+
enclosure ::= parenth_form | list_display | dict_display
64+
65+
Identifiers
66+
"""""""""""
67+
The rules that dictate what is a legal identifer in TorchScript are the same as
68+
their `Python counterparts <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>`_.
69+
70+
Literals
71+
""""""""
72+
73+
::
74+
75+
literal ::= stringliteral | integer | floatnumber
76+
77+
Evaluation of a literal yields an object of the appropriate type with the specific value
78+
(with approximations applied as necessary for floats). Literals are immutable, and multiple evaluations
79+
of identical literals may obtain the same object or distinct objects with the same value.
80+
`stringliteral <https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals>`_,
81+
`integer <https://docs.python.org/3/reference/lexical_analysis.html#integer-literals>`_, and
82+
`floatnumber <https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals>`_
83+
are defined in the same way as their Python counterparts.
84+
85+
Parenthesized Forms
86+
"""""""""""""""""""
87+
88+
::
89+
90+
parenth_form ::= '(' [expression_list] ')'
91+
92+
A parenthesized expression list yields whatever the expression list yields. If the list contains at least one
93+
comma, it yields a ``Tuple``; otherwise, it yields the single expression inside the expression list. An empty
94+
pair of parentheses yields an empty ``Tuple`` object (``Tuple[]``).
95+
96+
List and Dictionary Displays
97+
""""""""""""""""""""""""""""
98+
99+
::
100+
101+
list_comprehension ::= expression comp_for
102+
comp_for ::= 'for' target_list 'in' or_expr
103+
list_display ::= '[' [expression_list | list_comprehension] ']'
104+
dict_display ::= '{' [key_datum_list | dict_comprehension] '}'
105+
key_datum_list ::= key_datum (',' key_datum)*
106+
key_datum ::= expression ':' expression
107+
dict_comprehension ::= key_datum comp_for
108+
109+
Lists and dicts can be constructed by either listing the container contents explicitly or providing
110+
instructions on how to compute them via a set of looping instructions (i.e. a *comprehension*). A comprehension
111+
is semantically equivalent to using a for loop and appending to an ongoing list the expression of the comprehension.
112+
Comprehensions implicitly create their own scope to make sure the items of the target list do not leak into the
113+
enclosing scope. In the case that container items are explicitly listed, the expressions in the expression list
114+
are evaluated left-to-right. If a key is repeated in a ``dict_display`` that has a ``key_datum_list``, then, the
115+
resultant dictionary uses the value from the rightmost datum in the list that uses the repeated key.
116+
117+
Primaries
118+
^^^^^^^^^
119+
120+
::
121+
122+
primary ::= atom | attributeref | subscription | slicing | call
123+
124+
125+
Attribute References
126+
""""""""""""""""""""
127+
128+
::
129+
130+
attributeref ::= primary '.' identifier
131+
132+
133+
``primary`` must evaluate to an object of a type that supports attribute references that has an attribute named
134+
``identifier``.
135+
136+
Subscriptions
137+
"""""""""""""
138+
139+
::
140+
141+
subscription ::= primary '[' expression_list ']'
142+
143+
144+
The primary must evaluate to an object that supports subscription. If it is a ``List`` , ``Tuple``, or ``str``,
145+
the expression list must evaluate to an integer or slice. If it is a ``Dict``, the expression list must evaluate
146+
to an object of the same type as the key type of the ``Dict``. If the primary is a ``ModuleList``, the expression
147+
list must be an ``integer`` literal. If the primary is a ``ModuleDict``, the expression must be a ``stringliteral``.
148+
149+
150+
Slicings
151+
""""""""
152+
A slicing selects a range of items in a ``str``, ``Tuple``, ``List`` or ``Tensor``. Slicings may be used as
153+
expressions or targets in assignment or ``del`` statements.
154+
155+
::
156+
157+
slicing ::= primary '[' slice_list ']'
158+
slice_list ::= slice_item (',' slice_item)* [',']
159+
slice_item ::= expression | proper_slice
160+
proper_slice ::= [expression] ':' [expression] [':' [expression] ]
161+
162+
Slicings with more than one slice item in their slice lists can only be used with primaries that evaluate to an
163+
object of type ``Tensor``.
164+
165+
166+
Calls
167+
"""""
168+
169+
::
170+
171+
call ::= primary '(' argument_list ')'
172+
argument_list ::= args [',' kwargs] | kwargs
173+
args ::= [arg (',' arg)*]
174+
kwargs ::= [kwarg (',' kwarg)*]
175+
kwarg ::= arg '=' expression
176+
arg ::= identifier
177+
178+
179+
`primary` must desugar or evaluate to a callable object. All argument expressions are evaluated
180+
before the call is attempted.
181+
182+
Power Operator
183+
^^^^^^^^^^^^^^
184+
185+
::
186+
187+
power ::= primary ['**' u_expr]
188+
189+
190+
The power operator has the same semantics as the built-in pow function (not supported); it computes its
191+
left argument raised to the power of its right argument. It binds more tightly than unary operators on the
192+
left, but less tightly than unary operators on the right; i.e. ``-2 ** -3 == -(2 ** (-3))``. The left and right
193+
operands can be ``int``, ``float`` or ``Tensor``. Scalars are broadcast in the case of scalar-tensor/tensor-scalar
194+
exponentiation operations, and tensor-tensor exponentiation is done elementwise without any broadcasting.
195+
196+
Unary and Arithmetic Bitwise Operations
197+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
198+
199+
::
200+
201+
u_expr ::= power | '-' power | '~' power
202+
203+
The unary ``-`` operator yields the negation of its argument. The unary ``~`` operator yields the bitwise inversion
204+
of its argument. ``-`` can be used with ``int``, ``float``, and ``Tensor`` of ``int`` and ``float``.
205+
``~`` can only be used with ``int`` and ``Tensor`` of ``int``.
206+
207+
Binary Arithmetic Operations
208+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
209+
210+
::
211+
212+
m_expr ::= u_expr | m_expr '*' u_expr | m_expr '@' m_expr | m_expr '//' u_expr | m_expr '/' u_expr | m_expr '%' u_expr
213+
a_expr ::= m_expr | a_expr '+' m_expr | a_expr '-' m_expr
214+
215+
The binary arithmetic operators can operate on ``Tensor``, ``int``, and ``float``. For tensor-tensor ops, both arguments must
216+
have the same shape. For scalar-tensor or tensor-scalar ops, the scalar is usually broadcast to the size of the
217+
tensor. Division ops can only accept scalars as their right-hand side argument, and do not support broadcasting.
218+
The ``@ ``operator is for matrix multiplication and only operates on ``Tensor`` arguments. The multiplication operator
219+
(``*``) can be used with a list and integer in order to get a result that is the original list repeated a certain
220+
number of times.
221+
222+
Shifting Operations
223+
^^^^^^^^^^^^^^^^^^^
224+
225+
::
226+
227+
shift_expr ::= a_expr | shift_expr ( '<<' | '>>' ) a_expr
228+
229+
230+
These operators accept two ``int`` arguments, two ``Tensor`` arguments, or a ``Tensor`` argument and an ``int`` or
231+
``float`` argument. In all cases, a right shift by ``n`` is defined as floor division by ``pow(2, n)`` and a left shift
232+
by ``n`` is defined as multiplication by ``pow(2, n)``. When both arguments are ``Tensors``, they must have the same
233+
shape. When one is a scalar and the other is a ``Tensor``, the scalar is logically broadcast to match the size of
234+
the ``Tensor``.
235+
236+
Binary Bitwise Operations
237+
^^^^^^^^^^^^^^^^^^^^^^^^^
238+
239+
::
240+
241+
and_expr ::= shift_expr | and_expr '&' shift_expr
242+
xor_expr ::= and_expr | xor_expr '^' and_expr
243+
or_expr ::= xor_expr | or_expr '|' xor_expr
244+
245+
246+
The ``&`` operator computes the bitwise AND of its arguments, the ``^`` the bitwise XOR and ``|`` the bitwise OR.
247+
Both operands must be ``int`` or ``Tensor``, or the left operand must be ``Tensor`` and the right operand must be
248+
``int``. When both operands are ``Tensor``, they must have the same shape. When the right operand is ``int``, and
249+
the left operand is ``Tensor`` , the right operand is logically broadcast to match the shape of the ``Tensor``.
250+
251+
Comparisons
252+
^^^^^^^^^^^
253+
254+
::
255+
256+
comparison ::= or_expr (comp_operator or_expr)*
257+
comp_operator ::= '<' | '>' | '==' | '>=' | '<=' | '!=' | 'is' ['not'] | ['not'] 'in'
258+
259+
A comparison yields a boolean values (``True`` or ``False``) or, if one of the operands is a ``Tensor``, a boolean
260+
``Tensor``. Comparisons can be chained arbitrarily as long as they do not yield boolean ``Tensors`` that have more
261+
than one element. ``a op1 b op2 c ...`` is equivalent to ``a op1 b and b op2 c and ...``.
262+
263+
Value Comparisons
264+
"""""""""""""""""
265+
The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the values of two objects. The two objects generally need to be of
266+
the same type, unless there is an implicit type conversion available between the objects. User-defined types can
267+
be compared if rich comparison methods ( ``__lt__`` etc.) are defined on them. Built-in type comparison works like
268+
Python:
269+
270+
* numbers are compared mathematically
271+
* strings are compared lexicographically
272+
* lists, tuples, and dicts can be compared only to other lists, tuples, and dicts of the same type and are compared using the comparison operator of corresponding elements
273+
274+
Membership Test Operations
275+
""""""""""""""""""""""""""
276+
The operators ``in`` and ``not in`` test for membership. ``x in s`` evaluates to ``True`` if ``x`` is a member of ``s`` and ``False```` otherwise.
277+
``x not in s`` is equivalent to ``not x in s``. This operator is supported for lists, dicts, and tuples, and can be used with
278+
user-defined types if they implement the ``__contains__`` method.
279+
280+
Identity Comparisons
281+
""""""""""""""""""""
282+
For all types except ``int``, ``double``, ``bool``, and ``torch.device``, operators ``is`` and ``is not`` test for the object’s identity;
283+
``x is y`` is ``True`` if and and only if ``x`` and ``y`` are the same object. For all other types, ``is`` is equivalent to
284+
comparing them using ``==``. ``x is not y`` yields the inverse of ``x is y``.
285+
286+
Boolean Operations
287+
^^^^^^^^^^^^^^^^^^
288+
289+
::
290+
291+
or_test ::= and_test | or_test 'or' and_test
292+
and_test ::= not_test | and_test 'and' not_test
293+
not_test ::= 'bool' '(' or_expr ')' | comparison | 'not' not_test
294+
295+
User-defined objects can customize their conversion to ``bool`` by implementing a ``__bool__`` method. The operator ``not``
296+
yields ``True`` if its operand is false, ``False`` otherwise. The expression ``x`` and ``y`` first evaluates ``x``; if it is ``False``, its
297+
value (``False``) is returned; otherwise, ``y`` is evaluated and its value is returned (``False`` or ``True``). The expression ``x`` or ``y``
298+
first evaluates ``x``; if it is ``True``, its value (``True``) is returned; otherwise, ``y`` is evaluated and its value is returned
299+
(``False`` or ``True``).
300+
301+
Conditional Expressions
302+
^^^^^^^^^^^^^^^^^^^^^^^
303+
304+
::
305+
306+
conditional_expression ::= or_expr ['if' or_test 'else' conditional_expression]
307+
expression ::= conditional_expression
308+
309+
The expression ``x if c else y`` first evaluates the condition ``c`` rather than x. If ``c`` is ``True``, ``x`` is
310+
evaluated and its value is returned; otherwise, ``y`` is evaluated and its value is returned. As with if-statements,
311+
``x`` and ``y`` must evaluate to a value of the same type.
312+
313+
Expression Lists
314+
^^^^^^^^^^^^^^^^
315+
316+
::
317+
318+
expression_list ::= expression (',' expression)* [',']
319+
starred_item ::= '*' primary
320+
321+
A starred item can only appear on the left-hand side of an assignment statement, e.g. ``a, *b, c = ...``.

0 commit comments

Comments
 (0)