ShapeEnv
- class torch.fx.experimental.symbolic_shapes.ShapeEnv(*, should_record_events=None, tracked_fakes=None, **kwargs)
- ,
Adds a new symbol to the symbolic environment.
Deprecated: use add_backed_var_to_val instead.
Given a paired list of placeholders (fake tensors with symbolic sizes) and concrete arguments (regular tensors with real sizes), returns a dictionary mapping each symbol to its real value. So for example, if you have a placeholder with size (s0, s1), binding (2, 4) to it will give you {s0: 2, s1: 4}. This is not guaranteed to bind ALL symbols in the ShapeEnv; we can’t bind a symbol if it doesn’t occur in any placeholder, and symbols that already have replacements won’t get bindings.
This is a little duplicative with evaluate_guards but it’s different enough that it seemed cleanest to make another copy. This assumes the guards are already checked, though if it’s cheap we’ll check for shenanigans
Given a sympy expression, computes a ValueRanges bound for what values it can be
ValueRanges[Expr]
Compare another ShapeEnv for equivalence
Break reference cycles.
This destroys the stacks. If you really want to keep them, we just need some way to break references on code objects.
Create a new symbol which is tracked by this ShapeEnv
sympy.Expr
Create symbolic sizes/strides/offset for a tensor.
If the tensor has symbolic sizes from a different ShapeEnv, delegates to transfer_symbols_from_foreign_shape_env.
Create a SymBool object from a sympy boolean expression
Create a SymFloat value from a symbolic expression
FloatLikeType
Create a SymInt value from a symbolic expression
If you know what the current hint value of the SymInt to be created is, pass it into hint. Otherwise, pass None and we will make our best guess
IntLikeType
Create a symbolic boolean without a hint value
Create a symbolic float without a hint value
Create a symbolic integer without a hint value
Create a symbol with an unspecified value
Compared to standard symbols we do not assume the value is positive, nor do we specialze on zero or one values.
Expr
Create a SymInt wrapping a new unspecified symbol
IntLikeType
Context manager that raises _ShapeEnvGuardError if a guard is attempted.
Temporarily freezes the ShapeEnv and makes _check_frozen raise instead of warn, so that guard-installing code paths produce an exception that is not cached by the _inner_evaluate_expr LRU cache.
Generator[None, None, None]
Given an expression, evaluates it, adding guards if necessary When fallback_value is not None the function return fallback_value instead of failing with data dependent error.
Basic
Expected to be used with produce_guards_expression(). Evaluates an expression generated by produce_guards_expression for the given concrete args.
Generate guards for a graph’s placeholder values and evaluate the guards with args
Given a SymNode, evaluates sym_node.expr, adding guards if necessary.
Basic
Format this shape env’s guard expressions with optional traceback info if verbose
Freeze this ShapeEnv to stop accumulating guards
A frozen ShapeEnv will ignore any further guards generated on it and only emit a warning which may lead to accuracy problems.
Freeze this ShapeEnv to stop adding deferred runtime asserts.
We will error if you try to install a new runtime assert when it is frozen. This would indicate a lowering violation, or perhaps something we know statically is already True but we are checking it again in a way that is not clearly dischargeable.
Given the symbols in an expression, it returns all the runtime asserts that have those symbols concatenated with all the guards. If symbols is None, it returns all the runtime asserts (and all the guards)
tuple[sympy.logic.boolalg.Boolean, …]
Returns a list of guard expressions that aren’t statically known (i.e. not trivial)
list[sympy.logic.boolalg.Boolean]
Get a list of guards, but pruned so it only provides guards that reference symints from the passed in input
list[ShapeGuard]
Adds a guard that orig_expr is True if we can or fall back to adding an assert that is checked at runtime.
orig_expr (sympy.Expr) – Boolean expression to assert is true
msg (str) – Message to display on assertion failure
fx_node (Optional, torch.fx.Node) – node in self.graph corresponding
to the expression, if applicable
Indicates that the newly allocated unbacked SymInts are being discarded
Generator[None, None, None]
Check if a sympy symbol matches the naming convention for unbacked symbols
Return a concrete integer hint for an expression.
This function should be used for non-guarding based optimizations. If you want a hint that you can guard on, use the guarding_hint API instead.
This function will hint unbacked symbols using user provided optimization hints. If not provided, fallback will be used along with some heuristics that try to maximize consistency with the shape environment.
Special cases:
Complex numbers (containing sympy.I): raises an error since tensor dimensions cannot be complex.
Infinity (int_oo, sympy.oo): returns sys.maxsize.
NaN (sympy.nan): returns the fallback value.
Temporarily add symbol-level axioms to the ShapeEnv. This is useful when you want to “fork” and have parallel universes of ShapeEnvs. For example, we use this when doing multi-graph compile so we can support various graphs with varying levels of specializations.
This context manager allows for temporarily adding constraints to the shape environment based on a specialization function applied to a symbol associated with a source.
Expected to be used with evaluate_guards_expression(). Produces the guards for the given placeholders and returns a string expression to be evaluated by evaluate_guards_expression given concrete values for the placeholders.
str | None
Generates a list of guards strings which, when evaluated in a context that defines tensors for all the sources, returns True or False depending on if the guards in the list evaluated to True or not. Primarily used by Dynamo, but this is also helpful for manual testing of guards (see evaluate_guards_for_args)
For convenience in testing, a source is allowed to be a str, in which case we will assume it is a LocalSource
simplified lets you omit duck sizing, equality and 0/1 guards. This is useful for testing when you don’t care about the boilerplate guards, and it may be helpful for user output too (be careful though; some equality guards are nontrivial! It would be nice to get simplified output to print them too). It’s private because it’s not intended for normal use
Returns guards in python and python with verbose comments (verbose) by default.
list[_ShapeGuardsHelper]
Apply symbol replacements to any symbols in the given expression.
IMPORTANT: The output of this method MUST depend only on self.replacements and the input expr. Do not add dependencies on other mutable state. SymNode.expr uses _replacements_version_counter (which tracks only replacement changes) to cache calls to this method, so depending on other state would cause stale cache results.
_SympyT
Used only when propagate_real_tensors; registers a value for an unbacked symbol, which can be used last resort to resolve hints.
Use known constraints and replacements to simplify the given expr
_SympyT
Gets a size hint for a given expression from the underlying shapes we had. Does not introduce a guard, so only use this when you can guarantee that your code is still valid for arbitrary shapes (such as optimization decisions)
Basic | None
Context manager to ignore all guards generated inside.
_GeneratorContextManager[None]
Transfer symbolic sizes/strides/offset from a foreign ShapeEnv into this one.
If symbolic_context is None, each dimension is auto-classified as STATIC, DUCK, or UNBACKED based on whether the foreign symbol has a guarding hint. If symbolic_context is provided (e.g. from _automatic_dynamic), its classification is used instead.
For unbacked dims, the underlying foreign unbacked symbols (and any user-provided optimization hints registered on the foreign ShapeEnv) are transferred into this env via _transfer_foreign_expr_as_unbacked.
use backed_var_to_val instead.
Deprecated