Skip to content

Support mark_unbacked in minimal_fx_tracer - #3046

Merged
tugsbayasgalan merged 1 commit into
mainfrom
tugsuu/dynamic_shapes
May 7, 2026
Merged

tugsbayasgalan merged 1 commit into
mainfrom
tugsuu/dynamic_shapes

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

minimal_fx_tracer now supports mark_unbacked() on plain tensor inputs.

Because this non-strict make_fx path fakeifies inputs directly, it must call
compute_unbacked_bindings() itself after fakeification; otherwise fresh
unbacked symbols remain pending and tracing fails.

Scope is intentionally narrow:

  • support plain-tensor mark_unbacked()
  • reject mark_dynamic()
  • reject wrapper-subclass mark_unbacked() such as DTensor

Tests cover replay, multiple inputs, shape_id/strict/min-max metadata,
data-dependent branching failure on unbacked dims, and DTensor rejection.

Co-authored-by: Codex [email protected]

Authored with Codex

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 21, 2026
@tugsbayasgalan
tugsbayasgalan marked this pull request as draft April 21, 2026 22:25
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Pls review

@claude

claude Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tugsbayasgalan's task in 3m 21s —— View job


Code Review: Support mark_dynamic in minimal_fx_tracer

  • Read the full diff and changed files
  • Review make_fx_tracer.py changes
  • Review test_trace_module.py changes
  • Post review feedback

Overall this is a clean, well-scoped addition that stays true to the minimal tracer philosophy. The PR description is excellent at calling out what's deliberately in/out of scope. A few items I'd want addressed:

Issues

1. Missing blank line before _symbolic_context_for_marked_dynamic_dims (style nit)
make_fx_tracer.py:120-121 — There's only one blank line between _unwrap_subclasses and the new _symbolic_context_for_marked_dynamic_dims. The rest of the file uses two blank lines between top-level functions. E302 is ignored in .flake8 so linting won't catch this, but it's inconsistent with the surrounding code.

Fix this →

2. DTensor + mark_dynamic: attribute propagation concern
make_fx_tracer.py:168-189 — In _fakeify_input, after _unwrap_subclasses has unwrapped a DTensor into its inner plain tensors, _symbolic_context_for_marked_dynamic_dims checks getattr(tensor, "_dynamo_dynamic_indices", None) on the inner tensor. But mark_dynamic sets this attribute on the outer DTensor only. The inner tensors extracted via __tensor_flatten__() in _unwrap_subclass don't automatically inherit this attribute.

The test test_dtensor_mark_dynamic_preserves_symbolic_local_dim asserts that the inner tensor placeholder has torch.SymInt shape. This will only work if PyTorch's mark_dynamic propagates the attribute to inner tensors for DTensors (or DTensor's __tensor_flatten__ propagates it). If this relies on a PyTorch-side behavior, it would be worth adding a brief comment explaining that assumption, since it's non-obvious.

If the attribute doesn't propagate, the inner tensor falls through to fake_mode.from_tensor(arg, static_shapes=True) silently, which violates the fail-fast principle described in the PR. Consider adding a _transfer_dynamic_metadata step after unwrapping, or at minimum an assertion that dynamic metadata wasn't lost.

3. dynamic_ranges KeyError risk
make_fx_tracer.py:153 — dynamic_ranges[dim] does a plain dict lookup. If _dynamo_dynamic_indices and _dynamo_dynamic_range are out of sync (e.g., mark_dynamic is called but somehow the range entry is missing), this will throw an opaque KeyError. A dict.get() with a clear error message would make debugging easier:

dim_range = dynamic_ranges.get(dim)
if dim_range is None:
    raise ValueError(
        f"Dimension {dim} is in _dynamo_dynamic_indices but missing "
        f"from _dynamo_dynamic_range. This likely indicates a "
        f"torch._dynamo.mark_dynamic() internal inconsistency."
    )

4. _produce_symbolic_input_guards placement
make_fx_tracer.py:515 — _produce_symbolic_input_guards is called after tracing but also after _remove_cpu_shadow_chains. The ordering comment says _copy_fwd_metadata_to_bw_nodes must run before DCE, but there's no corresponding comment explaining why guard production should happen after _remove_cpu_shadow_chains. Is this order-sensitive? A brief comment clarifying the ordering dependency (or lack thereof) would be helpful.

Test Feedback

5. Duplicated _graph_placeholder_fake_inputs helper and fake_mode extraction pattern
test_trace_module.py:86-94 and test_trace_module.py:119-126 — The fake_mode extraction pattern is duplicated between _apply_regional_inductor and _standalone_compile_graph. Consider extracting the mode-extraction into _graph_placeholder_fake_inputs or a thin wrapper, since both callers need the same thing.

6. Good: test_mark_dynamic_rejects_shape_branch_outside_range test
test_trace_module.py:224-237 — This is a well-designed test for the fail-fast guard behavior. The regex match on the ConstraintViolationError message is specific enough to be meaningful but not so brittle it'll break on minor message changes.

7. test_mark_dynamic_without_symbolic_fake_input_crashes name is misleading
test_trace_module.py:165 — The test name says "crashes" but the test actually demonstrates that the old static approach crashes and the new dynamic approach succeeds. A name like test_mark_dynamic_avoids_static_shape_specialization_crash or test_static_fakeify_crashes_on_shape_change_but_dynamic_works would more accurately describe what's being tested.

Minor / Optional

  • make_fx_tracer.py:123 — The return type Any | None could be more specific (e.g., StatelessSymbolicContext | None) since the function only returns that type or None. This would improve IDE support for callers.
  • make_fx_tracer.py:142-145 — The _specialize_on handling reads from an attribute that mark_dynamic may or may not set. The getattr(..., {}) fallback is correct, but a comment noting when/why _specialize_on would be populated would help future readers.

Summary

The implementation is well-structured and the test coverage is thorough. The main concern is the DTensor attribute propagation path (#2) — I'd want to understand whether the test actually passes as-is, since the code path suggests dynamic metadata could be lost during subclass unwrapping. The KeyError risk (#3) and guard ordering (#4) are lower priority but worth addressing.


@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch from 00bd731 to af781fe Compare April 21, 2026 22:39
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Do another round

@claude

claude Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tugsbayasgalan's task in 4m 57s —— View job


Second Round Review: Support mark_dynamic in minimal_fx_tracer

  • Read the full diff and changed files
  • Review make_fx_tracer.py changes in detail
  • Review test_trace_module.py changes in detail
  • Check for issues from first review that are still present
  • Post second-round review feedback

This is a second pass with fresh eyes. The first round covered the broad strokes well; this round focuses on correctness subtleties and a few things the first round missed.

Status of First-Round Items

#1 (blank line style) — Still present but truly cosmetic. Not worth blocking on.

#2 (DTensor attribute propagation) — After deeper investigation, the comment at make_fx_tracer.py:178-180 explicitly documents the assumption that PyTorch propagates _dynamo_dynamic_indices to inner tensors during __tensor_flatten__(). The test test_dtensor_mark_dynamic_preserves_symbolic_local_dim validates this end-to-end. If PyTorch changes this behavior the test will catch it. The comment is sufficient; this is resolved.

#3 (KeyError risk) — Still present. dynamic_ranges[dim] at line 154 will throw an opaque KeyError if the metadata is inconsistent. This is a real, if unlikely, debuggability concern.

#4 (guard ordering) — Still applicable. No comment explaining why _produce_symbolic_input_guards runs after _remove_cpu_shadow_chains. See new item below.

#5 (duplicated fake_mode extraction) — Still present. Lines 87-94 and 119-126 are identical 8-line blocks.

New Observations

1. _produce_symbolic_input_guards runs outside the tracing context

make_fx_tracer.py:519 — _produce_symbolic_input_guards calls shape_env.produce_guards(...) at line 204, but this runs after the with fake_mode, tracing(ctx), ... block at lines 500-512 has exited. produce_guards reads from shape_env which persists on fake_mode, so the data is still there. However, produce_guards can internally call back into the shape environment and may expect an active tracing context to be present (for example, for logging or guard source resolution).

In practice this appears to work because produce_guards on a ShapeEnv doesn't require the tracing context — it just evaluates existing guards. But this is worth verifying in CI. If it does need the context, the fix is to move _produce_symbolic_input_guards(fake_mode) inside the with block, after make_fx returns.

2. _fakeify_input imports are inside the function body — every call

make_fx_tracer.py:173-174 — LocalSource and TrackedFake are imported inside _fakeify_input, which is called once per unwrapped input tensor. For graphs with many inputs (e.g., a model with hundreds of parameters), this adds overhead from repeated importlib lookups on every trace. The imports in _symbolic_context_for_marked_dynamic_dims (lines 133-139) have the same pattern, but that function short-circuits when there's no dynamic metadata, so it's less impactful.

Consider moving from torch._dynamo.source import LocalSource and from torch.fx.experimental.symbolic_shapes import TrackedFake to the top of the function body or module level to avoid repeated import overhead. The imports in _symbolic_context_for_marked_dynamic_dims are fine where they are since they're only hit when dynamic dims are present.

3. _fakeify_input always imports LocalSource and TrackedFake even for static tensors

make_fx_tracer.py:173-174 — The imports of LocalSource and TrackedFake happen before the symbolic_context is not None check at line 177, meaning they execute even for the common case of static-shape tensors (which fall through to line 193). Moving these two imports inside the if symbolic_context is not None: branch would avoid unnecessary work for the non-dynamic path:

def _fakeify_input(fake_mode, arg, *, input_name):
    if not isinstance(arg, torch.Tensor):
        return arg

    symbolic_context = _symbolic_context_for_marked_dynamic_dims(arg)
    if symbolic_context is not None:
        from torch._dynamo.source import LocalSource
        from torch.fx.experimental.symbolic_shapes import TrackedFake
        # ... rest of symbolic path
    return fake_mode.from_tensor(arg, static_shapes=True)

Fix this →

4. _standalone_compile_graph is test-only but not clearly scoped

test_trace_module.py:114-133 — This function is only used in TestMinimalFXTracerDynamicShapes tests and is a good utility, but it's defined at module level alongside _apply_regional_inductor (which is used by the model integration tests). Since standalone_compile with dynamic_shapes="from_tracing_context" is the key API for exercising the dynamic shapes path, a brief docstring explaining its purpose would help future test readers understand why it exists alongside _apply_regional_inductor.

5. Test: test_mark_dynamic_avoids_static_shape_specialization_crash mixes concerns

test_trace_module.py:165-192 — This test does three distinct things: (a) demonstrates that static fake inputs lock in shapes, (b) shows that compiled static graphs reject different shapes, and (c) shows that minimal_fx_tracer with mark_dynamic avoids this. The test name and structure read like a comparison/motivation test rather than a unit test for minimal_fx_tracer. The first-round review flagged the name; I'd additionally suggest splitting this into two tests: one that documents the static-shape failure as a regression test, and one that verifies dynamic shapes work. This improves failure diagnostics — if only part (c) breaks, the test name would be misleading about what failed.

6. Guard regex in test_mark_dynamic_rejects_shape_branch_outside_range may be fragile

test_trace_module.py:235 — The regex r"4 <= .*size\(\)\[2\].*<= 5" matches the current ConstraintViolationError message format. If PyTorch changes the error message formatting (e.g., using dim() instead of size(), or changing the range display), this test will fail for the wrong reason. Consider making the regex more lenient, e.g. just matching the constraint values: r"4.*5" or testing for the exception type only and checking the dimension number separately.

Summary

The implementation is solid and well-designed. None of the new findings are blocking. The most actionable items are:

  1. Move LocalSource/TrackedFake imports inside the dynamic branch (Add metrics to collect during training #3) — small perf improvement and cleaner code path separation.
  2. Add a brief comment at line 519 explaining that _produce_symbolic_input_guards intentionally runs after tracing exits and doesn't need the tracing context (Add profiler #1 / first-round Add lr scheduler for optimizer #4).
  3. Protect dynamic_ranges[dim] from opaque KeyError (first-round Add metrics to collect during training #3) — still the most impactful debuggability improvement.

The DTensor metadata propagation concern from the first round is adequately addressed by the existing comment and test coverage. Looks good overall.


View job

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch from af781fe to cc6221a Compare April 22, 2026 03:27
@tugsbayasgalan
tugsbayasgalan marked this pull request as ready for review April 22, 2026 03:36
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Do review

@claude

claude Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tugsbayasgalan's task in 3m 16s —— View job


Code Review: Support mark_dynamic in minimal_fx_tracer (Round 3)

  • Read the full PR diff
  • Review make_fx_tracer.py changes
  • Review test_trace_module.py changes
  • Post review feedback

The implementation is well-structured and stays deliberately minimal. The PR description does a good job calling out the four deliberate design choices. Here's what I found:

Correctness

1. dynamic_ranges[dim] can throw an opaque KeyError — make_fx_tracer.py:154

If _dynamo_dynamic_indices and _dynamo_dynamic_range are ever out of sync (e.g., a future PyTorch change modifies how mark_dynamic populates one but not the other), the plain dict lookup dynamic_ranges[dim] will produce an unhelpful KeyError: 0 traceback. Since this code mirrors Dynamo internals that could change independently, a defensive lookup with a descriptive error would make this more robust:

dim_range = dynamic_ranges.get(dim)
if dim_range is None:
    raise ValueError(
        f"Dimension {dim} is in _dynamo_dynamic_indices but has no "
        f"corresponding entry in _dynamo_dynamic_range."
    )

This aligns with the CLAUDE.md guidance: "ValueError for user-facing errors (bad config, invalid input)."

Fix this →

2. _produce_symbolic_input_guards ordering is undocumented — make_fx_tracer.py:519

_produce_symbolic_input_guards(fake_mode) runs after _remove_cpu_shadow_chains and outside the with fake_mode, tracing(ctx), ... block. The function reads from shape_env which persists on fake_mode, so the data survives context exit. However, the ordering relative to _remove_cpu_shadow_chains isn't obviously order-dependent — a one-line comment would help future readers understand this is intentional (and that guard production doesn't need the tracing context).

Fix this →

Performance (minor)

3. LocalSource and TrackedFake imported on every call to _fakeify_input — make_fx_tracer.py:173-174

These two imports execute unconditionally for every unwrapped input tensor, including the common static-shape path. For models with many parameters (hundreds of tensors), this adds unnecessary importlib overhead per trace. Moving them inside the if symbolic_context is not None: branch at line 177 would restrict the import cost to only tensors with dynamic metadata:

def _fakeify_input(fake_mode, arg, *, input_name):
    if not isinstance(arg, torch.Tensor):
        return arg

    symbolic_context = _symbolic_context_for_marked_dynamic_dims(arg)
    if symbolic_context is not None:
        from torch._dynamo.source import LocalSource
        from torch.fx.experimental.symbolic_shapes import TrackedFake
        # ... symbolic path
    return fake_mode.from_tensor(arg, static_shapes=True)

Fix this →

Type annotation

4. Return type Any | None could be more precise — make_fx_tracer.py:124

_symbolic_context_for_marked_dynamic_dims always returns StatelessSymbolicContext | None, but the annotation says Any | None. Using the concrete type would improve IDE support and self-documentation. (Minor since this is a private helper.)

Tests

5. Test coverage is thorough and well-designed

The five new tests cover the key behaviors well:

  • test_mark_dynamic_preserves_symbolic_placeholder_dim — verifies the fundamental sym-int plumbing
  • test_mark_dynamic_mixed_with_static_input — end-to-end through standalone_compile with both dynamic and static inputs, including a negative case for static shape mismatch
  • test_mark_dynamic_rejects_shape_branch_outside_range — validates the fail-fast guard behavior
  • test_mark_dynamic_preserves_min_max_constraints — verifies constraint metadata roundtrips through tracing
  • test_dtensor_mark_dynamic_preserves_symbolic_local_dim — validates the DTensor unwrapping path with dynamic shapes

6. DTensor attribute propagation reliance is documented

The comment at make_fx_tracer.py:178-180 correctly documents the assumption that PyTorch's DTensor preserves _dynamo_dynamic_indices on inner tensors during __tensor_flatten__(). The test at line 474 exercises this end-to-end. If PyTorch changes this behavior, the test will catch it. This is a reasonable approach.

7. Test helper refactoring cleans up _apply_regional_inductor

The extraction of _graph_placeholder_fake_inputs and _graph_fake_mode into standalone helpers (lines 95-115) is a good refactoring — it replaces the inline loop that was previously in _apply_regional_inductor and enables reuse in _standalone_compile_graph. These are well-scoped utility functions.

Summary

Implementation looks correct and intentionally minimal. The main actionable item is the KeyError risk (#1), which is a real debuggability concern. The import placement (#3) and ordering comment (#2) are lower priority. Test coverage is comprehensive and exercises the right edge cases.


View job

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch from cc6221a to 581d09e Compare April 27, 2026 15:28
@tugsbayasgalan tugsbayasgalan changed the title Support mark_dynamic in minimal_fx_tracer Support mark_unbacked in minimal_fx_tracer Apr 27, 2026
for node in traced.gm.graph.nodes
if node.op == "placeholder"
)
x_min = torch.randn(2, 4)

@laithsakka laithsakka Apr 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are you trying to test here in this test did you want to add
if (x.size()[0]>=2 and x.size()[0]<=5) int the forward and ensure it does not DDE?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated the test to be more rigorous

self.assertTrue(torch.equal(forward({}, x_max), run_traced(traced, {}, x_max)))

def test_mark_unbacked_preserves_unbacked_placeholder_dim(self):
from torch._dynamo.decorators import mark_unbacked

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test basically ensure when you call mark_unbacked dim is dynamic right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah


x = torch.randn(2, 4)
y = torch.randn(2, 4)
mark_unbacked(x, 0, shape_id="batch")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better you can add
if (x.size()[0]==y.size([0])) and ensure it does not DDE. but its fine as is also.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep added.

# binding logic, so bind them here explicitly. mark_unbacked() is
# only supported on plain tensor inputs, so binding after subclass
# unwrapping is sufficient.
torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc: @laithsakka does this make sense?

@laithsakka laithsakka Apr 30, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeh
since you are ignoring compute_unbacked_bindings result you can instead use

with shape_env.ignore_fresh_unbacked_symbols():
    fake_args = tuple(
    fakeify_input(fake_mode, a, input_name=f"minimal_fx_tracer_input{i}")
    for i, a in enumerate(unwrapped_args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since you are ignoring compute_unbacked_bindings result you can instead use
with shape_env.ignore_fresh_unbacked_symbols():
fake_args = tuple(
fakeify_input(fake_mode, a, input_name=f"minimal_fx_tracer_input{i}")
for i, a in enumerate(unwrapped_args)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm we shouldn;t ignore them, no?

return bool(
getattr(tensor, "_dynamo_unbacked_indices", None)
or getattr(tensor, "_dynamo_strict_unbacked_indices", None)
or getattr(tensor, "_dynamo_shape_ids", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not needed exisits iff _dynamo_unbacked_indices exisit

getattr(tensor, "_dynamo_unbacked_indices", None)
or getattr(tensor, "_dynamo_strict_unbacked_indices", None)
or getattr(tensor, "_dynamo_shape_ids", None)
or getattr(tensor, "_dynamo_unbacked_bounds", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto not needed

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch 3 times, most recently from 512b8c6 to 544c5a1 Compare April 29, 2026 01:12
@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch 2 times, most recently from 7f390d3 to 0039071 Compare April 29, 2026 21:05
def _symbolic_context_for_marked_dims(
tensor: torch.Tensor,
*,
source: Any,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is source used for?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is internally used for guard generation etc. @laithsakka would know more i think.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delketed now. we don't need guards

)


def _standalone_compile_graph(gm):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this function used?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch not needed.

traced_result.gm.recompile()


def _graph_placeholder_fake_inputs(gm):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does the new api support List[Tensor] ..etc? do we need to test that?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is just test api so it doens't matter i think

)
x_other = torch.randn(3, 4)

self.assertIsInstance(fake_x.size(0), torch.SymInt)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: check it has unbacked symbol? if you want.


maybe_register_blockmask_pytree_node()

def make_mask_fn(attn_regions, document_ids):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i will not review this test,

def _tensor_has_mark_unbacked(tensor: torch.Tensor) -> bool:
return bool(
getattr(tensor, "_dynamo_unbacked_indices", None)
or getattr(tensor, "_dynamo_strict_unbacked_indices", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeh this one when we do mark_ubacked(strict=True) you are not really testing it, but i guess thats fine.
I want to delete this mode, this only allow throwing compile time errors if traced code have
torch._check(u0== 100(any integr)

def _symbolic_context_for_marked_dims(
tensor: torch.Tensor,
*,
source: Any,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

source not used in this function, we shall remove it probably?


source = LocalSource(input_name, is_input=True)
symbolic_context = _symbolic_context_for_marked_dims(arg, source=source)
if symbolic_context is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: early exit first

if symbolic_context is None:
# nothing to make dynamic.
fake_mode.from_tensor(arg, static_shapes=True)

but i mean
...
https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code



def _produce_symbolic_input_guards(fake_mode: FakeTensorMode) -> None:
shape_env = fake_mode.shape_env

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do you need to produce guards do we have a path in the non strict API that evaluate guards. ?
also for unabcked there shall not be guards (well now we have some but its a bug).

if symbolic_context is not None:
fake = fake_mode.from_tensor(
arg,
source=source,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe if you dont care about guards you do not need the source at all you can pass none.
but you can keep it as is its ok also.

)
shape_env = fake_mode.shape_env
assert shape_env is not None and shape_env.tracked_fakes is not None
shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same thing here do you need to track if you are not calling _produce_symbolic_input_guards? probably not in theory.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep deleted.

# binding logic, so bind them here explicitly. mark_unbacked() is
# only supported on plain tensor inputs, so binding after subclass
# unwrapping is sufficient.
torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings(

@laithsakka laithsakka Apr 30, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeh
since you are ignoring compute_unbacked_bindings result you can instead use

with shape_env.ignore_fresh_unbacked_symbols():
    fake_args = tuple(
    fakeify_input(fake_mode, a, input_name=f"minimal_fx_tracer_input{i}")
    for i, a in enumerate(unwrapped_args)

)
shape_env = fake_mode.shape_env
assert shape_env is not None and shape_env.tracked_fakes is not None
shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably this is not needed also.

@SherlockNoMad
SherlockNoMad requested a review from ydwu4 May 4, 2026 16:43

@ydwu4 ydwu4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation looks reasonable.

)
shape_env = fake_mode.shape_env
assert shape_env is not None and shape_env.tracked_fakes is not None
shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need verify whether tracked_fakes are needed.

_copy_fwd_metadata_to_bw_nodes(traced)

_remove_cpu_shadow_chains(traced)
_insert_runtime_asserts(traced, fake_mode)

@SherlockNoMad SherlockNoMad May 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does this do to the graph if no dynamic shape is used?

we will need a pass to remove these runtime asserts.
In cudagraph setup, these nodes are not evaluate anyway.

I would have a flag to add runtime assert conditionally, and default to false.

fake_mode.from_tensor(a, static_shapes=True)
with fake_mode.shape_env.ignore_fresh_unbacked_symbols():
fake_args = tuple(
_fakeify_input(fake_mode, a, input_name=f"minimal_fx_tracer_input_{i}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would this name show up in graph?
can we make it shorter, more readable?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a dummy string that comes with LocalSource from dynamo as it requires string to be initialized. I think it is only used in debugging/logging in torch.compile context. This won't change the graph.

fake_args = tuple(
(
fake_mode.from_tensor(a, static_shapes=True)
with fake_mode.shape_env.ignore_fresh_unbacked_symbols():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this do when dynamic shape is not used?

Our principle for the tracer is, if a feature it not used, it cannot break the main code path.

@tugsbayasgalan tugsbayasgalan May 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it won't do anything but to be safer i made this ctx manager bit more explicit (check if we have unbacked)

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch from 275f0e7 to 8da2515 Compare May 6, 2026 21:35

def _wrap_to_subclass(
plain_tensors: list[torch.Tensor], meta: SubclassMeta
plain_tensors: list[torch.Tensor],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit, some new line changes seems linter config difference.

@SherlockNoMad SherlockNoMad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't read dynamic_shape.py, I assume you have the blessing from Laith.

minimal_fx_tracer now supports mark_unbacked() on plain tensor inputs.

Because this non-strict make_fx path fakeifies inputs directly, it must call
compute_unbacked_bindings() itself after fakeification; otherwise fresh
unbacked symbols remain pending and tracing fails.

Scope is intentionally narrow:
- support plain-tensor mark_unbacked()
- reject mark_dynamic()
- reject wrapper-subclass mark_unbacked() such as DTensor

Tests cover replay, multiple inputs, shape_id/strict/min-max metadata,
data-dependent branching failure on unbacked dims, and DTensor rejection.

Co-authored-by: Codex <[email protected]>
@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/dynamic_shapes branch from 8da2515 to 5587d8f Compare May 7, 2026 00:00
@tugsbayasgalan
tugsbayasgalan merged commit 046fdbb into main May 7, 2026
13 checks passed
jialei777 pushed a commit to jialei777/torchtitan that referenced this pull request Oct 19, 2026
… commit `659a0d`).

This CL imports TorchTitan head and stabilizes the build. Supporting feature gaps to be done in follow-up CLs. **For a summary of major changes and disabled tests see [internal link]**

In this CL, we bypass the [ban](https://github.com/pytorch/torchtitan/blob/1c40dd26a91b0489249011a53d1da69061b03d38/torchtitan/models/common/config_utils.py#L85) of SDPA backend for language models in `models/common/config_utils.py` so our monkey patch to apply splash attention kernel works. Deprecation of sdpa backend on TPU and supporting document packing in the SplashAttention kernel is handled in child cl/954755047

In OSS, torch>=2.12 is **required**. After this update several files import `DataParallelMeshDims` from `torch.distributed.fsdp` which is only available in torch >=2.12

It disables the following tests:

b/540005818 Disabled for numerical divergences:
- test_train_minimal_distributed llama3_fsdp
- test_train_minimal_distributed llama3_simplefsdp
- test_train_minimal_distributed qwen3_simplefsdp
- test_flux_qkv_split TestFluxSingleStreamUnbind

Disabled for other reasons:
- b/540119277 test_fused_swiglu_override - circular import issue with spmd_type
- b/540048441 graph trainer tests (upstream refactored trace_train_step into minimal_fx_tracer API):
- b/540049946 deepseek_v3_tp_dtensor - Linear: output DTensor has placements (Shard(dim=1),), but out_src_shardings expects (Shard(dim=2),)

Tested on OSS with image built from torch 2.12:
- redacted SimpleFSDP Compiled: [10,925 TPS]([internal link]) (10,0922 at head)
- FLUX SimpleFSDP Compiled (F32 + BF16 MP): [3,737 TPS]([internal link]) (3652 at head)
- Llama3 SimpleFSDP Compiled: [5,444 TPS]([internal link]) (5384 at head)

See the list of commits: pytorch/torchtitan@627126f...659a0d2

#MIGRATION_3P_PY_TORCHTITAN__DEFAULT

  - 95ae6a0 ci: regenerate qwen3_moe_rocm_mi350x.txt baseline with ac... by Rishi Sinha <[email protected]>
  - db5da4b Refactor pipeline parallel helpers for graph PP reuse (#2... by sanketpurandare <[email protected]>
  - 6065055 Revert precompile PRs (pytorch#3107, pytorch#3178) to fix CI (pytorch#3212) by Bob Ren <[email protected]>
  - 179d9e1 CP AllGather on the wrong dimension (pytorch#3206) by francesco-bertolotti <[email protected]>
  - f522db0 Fix commands in DSV3 readme (pytorch#3116) by Daniel Vega-Myhre <[email protected]>
  - 0b148a2 [CI] Run integration tests in parallel (pytorch#3144) by Yuankai Chen <[email protected]>
  - 080c1d4 [GraphTrainer] Annotate loss region with module_fqn (pytorch#3207) by Sherlock Huang <[email protected]>
  - b2cd149 Observability: structured logging + training instrumentat... by Felipe Mello <[email protected]>
  - 706ed8d [GraphTrainer] Annotate generated FX code with user sourc... by Aditya Venkataraman <[email protected]>
  - af8d243 [GraphTrainer] Skip identity-slice rewrite when start/end... by Aditya Venkataraman <[email protected]>
  - d3c96e8 [mxfp8] Fix MXFP8GroupedExpertsConverter to actually swap... by Aditya Venkataraman <[email protected]>
  - d341407 [MoE] Pad token count to a multiple of sp_size in AllToAl... by Jiani Wang <[email protected]>
  - 2ae1340 [rl] add import torch to provisioner bootstrap to avoid c... by Shuhua Yu <[email protected]>
  - 0b6a29e [rl] Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True... by Felipe Mello <[email protected]>
  - 2c237ae refactor get_attention_masks to use positions instead of ... by liangel-02 <[email protected]>
  - 74bac7e [graph_trainer] FSDP AG RS overlap (pytorch#3156) by Yiming Zhou <[email protected]>
  - b6830b2 Upgrades torchtitan-ubuntu docker image to 22.04 and CTK ... by Syed Tousif Ahmed <[email protected]>
  - 5fa7af6 [float8] Quantize GroupedExperts params during conversion... by Aditya Venkataraman <[email protected]>
  - e62ab09 [rl] Fix CI loss=0 and logprob=NaN (pytorch#3232) by Jiani Wang <[email protected]>
  - f32a5bb [GraphTrainer] Overhaul README for accuracy and clarity (... by Sherlock Huang <[email protected]>
  - e425316 [rl] Remove VLLMGenerator.__del__ cleanup method (pytorch#3224) by Danielle Pintz <[email protected]>
  - ef54395 [graph_trainer] Move all FSDP-specific passes to fsdp_pas... by Yiming Zhou <[email protected]>
  - 301384b [GraphTrainer] Register BlockMask pytree node in aot_fx_t... by Bob Ren <[email protected]>
  - a24b247 [graph_trainer] Disable cpu_offload_all CI test for upstr... by Sherlock Huang <[email protected]>
  - 2dfee86 [GraphTrainer] Update manifesto: hardware heterogeneity, ... by Sherlock Huang <[email protected]>
  - c6cfaa2 Re-land "Enable bucketing pass in precompile path" (pytorch#3107... by Bob Ren <[email protected]>
  - ae5ff10 [cpu-offloading] Implement prefetching for cpu offloading... by Michael Lazos <[email protected]>
  - 046fdbb Support mark_unbacked in minimal_fx_tracer (pytorch#3046) by Tugsbayasgalan Manlaibaatar <[email protected]>
  - 8599818 [rl] Add a tag to trigger RL CI runs (pytorch#3230) by Jiani Wang <[email protected]>
  - 466da8c [graph_trainer] Port remat_using_tags_for_fwd_loss_bwd_gr... by Sherlock Huang <[email protected]>
  - 94d5f59 Re-land "Fix FlexAttention precompile bitwise determinist... by Bob Ren <[email protected]>
  - e2fea3f Wrong token count in validation when CP>1 (pytorch#3257) by francesco-bertolotti <[email protected]>
  - 1d392ca [torchtitan][llama4_parallelize] fixing fsdp_mesh_info bu... by anshul-si <[email protected]>
  - d91a9fc [Qwen3VL] remove local_map for dtensor interpolation (pytorch#29... by Shuhua Yu <[email protected]>
  - 19f88a3 profiler: drop duplicate dataclass fields (pytorch#3227) by Felipe Mello <[email protected]>
  - 52f3142 [GraphTrainer] Log graph pass names and total time (pytorch#3261) by Sherlock Huang <[email protected]>
  - bf2842d [GraphTrainer] Add memory policy registry and extra graph... by Syed Tousif Ahmed <[email protected]>
  - 4ebb089 Tests HybridEP integration with GraphTrainer (pytorch#3184) by Syed Tousif Ahmed <[email protected]>
  - da6ff79 [rl] Graceful shutdown GRPO (pytorch#3238) by Felipe Mello <[email protected]>
  - 54887a3 [GraphTrainer] Add compile.disable_passes to selectively ... by Sherlock Huang <[email protected]>
  - 4ed3c53 [codex] Fix weight tying parameter accounting (pytorch#3225) by 岛石 <[email protected]>
  - 5638c49 [codex] Fix shared BOS and EOS token inference (pytorch#3279) by 岛石 <[email protected]>
  - ecd117e [graph_trainer] Pass global_valid_tokens into loss_fn ins... by Yidi Wu <[email protected]>
  - 0fae167 [graph_trainer] AutoParallel AOT FX Trace Integration (#2... by sanketpurandare <[email protected]>
  - 74181b1 [LoRA] Add LoRA converter and rename quantization to conv... by Yifan Mao <[email protected]>
  - 0d8f57c Remove unnecessary clone from ChunkedCELoss (pytorch#3272) by Jiani Wang <[email protected]>
  - 28b83bd Merge lora and float8 tests (pytorch#3310) by Yifan Mao <[email protected]>
  - e917ff4 Avoid repeat_interleave output-size sync (pytorch#3274) by Simon Fan <[email protected]>
  - acece3b [graph_trainer] Disable flexattn integration test due to ... by Sherlock Huang <[email protected]>
  - 8ba1c6b Support kwargs in minimal_fx_tracer (pytorch#3262) by Tugsbayasgalan Manlaibaatar <[email protected]>
  - d107aa4 [Quantization] Use class factory for MXFP8/Float8 Grouped... by Yifan Mao <[email protected]>
  - ca4c7f2 [rl] Register customized config parser to vllm + less vll... by Jiani Wang <[email protected]>
  - 0b5e899 Fix precompile tests (pytorch#3316) by Tugsbayasgalan Manlaibaatar <[email protected]>
  - 0fadde3 [graph_trainer] Fix AutoParallel input_fn to include posi... by Ivan Kobzarev <[email protected]>
  - 2ceff82 [graph_trainer] Add log_timer utility for tracing step ti... by Sherlock Huang <[email protected]>
  - e9dbff6 [graph_trainer] Refactor selective activation remat to in... by Tugsbayasgalan Manlaibaatar <[email protected]>
  - b301dfa Remove MoE expert for-loop fallback (pytorch#3308) by sanketpurandare <[email protected]>
  - 1a0fe3e [graph_trainer] Refactor passes.py into focused modules (... by Sherlock Huang <[email protected]>
  - d57df09 Make ChunkedCELoss support torch.autograd.grad (pytorch#3249) by Yidi Wu <[email protected]>
  - 5ca23a5 [GraphTrainer] Add Context Parallel support (pytorch#3305) by Aditya Venkataraman <[email protected]>
  - 7f070c9 Enhance Lychee Link Checker (Resiliency & Performance) (#... by Andrei-Aksionov <[email protected]>
  - 7f602b9 Add AGENTS.md symlinks for Codex usage (pytorch#3326) by sanketpurandare <[email protected]>
  - 34801c0 [graph_trainer] Improve SAC tagging and CPU offload pass ... by Sherlock Huang <[email protected]>
  - 1a22c2d [graph_trainer] Remove deprecated AOT compile mode (pytorch#3327) by Sherlock Huang <[email protected]>
  - 7b418ab Revert "Avoid repeat_interleave output-size sync (pytorch#3274)"... by Simon Fan <[email protected]>
  - 6f2fa2f [rl] switch to vllm v2 engine (pytorch#3330) by Jiani Wang <[email protected]>
  - 1690e0a [cpu-offloading] Encode last consumer as dep arg in ao.wa... by Michael Lazos <[email protected]>
  - cee4982 [graph_trainer] Fix SAC remat to produce fresh FakeTensor... by Ivan Kobzarev <[email protected]>
  - d4a3c63 [graph_trainer] Generalize minimal_fx_tracer to module + ... by Tugsbayasgalan Manlaibaatar <[email protected]>
  - 4614e30 [graph_trainer] Support multiple FSDP PGs in overlap_fsdp... by Sherlock Huang <[email protected]>
  - 3781d1d Back out "[graph_trainer] Fix SAC remat to produce fresh ... by Sherlock Huang <[email protected]>
  - a2a0d99 RL: observability spans across trainer/generator/controll... by Felipe Mello <[email protected]>
  - 8cdfdc2 [rl] Better initial weight loading (pytorch#3318) by Jiani Wang <[email protected]>
  - f0795f0 [RL] - Enable experiment metrics (pytorch#3237) by Felipe Mello <[email protected]>
  - b64292b [graph_trainer] Remove fsdp_reshard_after_fwd_pass (pytorch#3370) by Sherlock Huang <[email protected]>
  - a670699 [graph_trainer] Skip dense numerics tests due to upstream... by Sherlock Huang <[email protected]>
  - cb7bf09 ci: declare workflow-level `contents: read` on 2 workflow... by Arpit Jain <[email protected]>
  - d64eabc [Full DTensor] Config-based Full DTensor for Llama3 (pytorch#3159) by Chien-Chin Huang <[email protected]>
  - a866d04 Fix memory snapshot pickle protocol for compatibility wit... by francesco-bertolotti <[email protected]>
  - 9f9ae4d [graph_trainer] Fix H100 CI failure from DeepEP compilati... by Sherlock Huang <[email protected]>
  - c9126af [graph_trainer] Add bucketing ops to precompile serializa... by Ivan Kobzarev <[email protected]>
  - 013890b [graph_trainer] Defer cudagraph compatibility check to pa... by Ivan Kobzarev <[email protected]>
  - 6a1b334 Fix optimizer state and module state coupling (pytorch#3356) by Tugsbayasgalan Manlaibaatar <[email protected]>
  - 4238c35 Re-enable compile for gpt-oss integration tests (pytorch#3373) by Aditya Venkataraman <[email protected]>
  - ebfceeb [rl] Add TITO generator and gen metrics (pytorch#3391) by Felipe Mello <[email protected]>
  - cf3c431 [graph_trainer] Re-enable FlexAttention tests after upstr... by Sherlock Huang <[email protected]>
  - 8aa96ac [graph_trainer] Fix eager SAC policy mm counter to reset ... by Ivan Kobzarev <[email protected]>
  - 52a292d [graph_trainer] Gate overlap_fsdp_ag_rs_pass behind a con... by Yiming Zhou <[email protected]>
  - 2057b56 [rl] fix CI timeout issue by properly tear down for vllm ... by Jiani Wang <[email protected]>
  - cfe97c6 [rl] use wandb=False in CI (pytorch#3408) by Felipe Mello <[email protected]>
  - 83e4904 [graph_trainer] Rework full_inductor_compilation_pass via... by Tugsbayasgalan Manlaibaatar <[email protected]>
  - 963c20c [MoE][5/n] Refactor MoE to clean DTensor boundaries for s... by Jessica Zhong <[email protected]>
  - da38566 [MoE][6/n] Extract local_reorder, split DeepEP/HybridEP d... by Jessica Zhong <[email protected]>
  - 3f721b4 [graph_trainer] Fix fsdp_passes compat with BitsetAncesto... by Ivan Kobzarev <[email protected]>
  - b585282 Fix imports for latest DeepEP (pytorch#3414) by Steffen Hirschmann <[email protected]>
  - c2a3771 [loss] Fix ChunkedCELoss + TP gradient placement mismatch... by Chien-Chin Huang <[email protected]>
  - 19c567f Debug Numerics with DebugMode (pytorch#3323) by Shangdi Yu <[email protected]>
  - 78b08dd [graph_trainer] Add DeepSeek V3 16B SDPA config (pytorch#3361) by sanketpurandare <[email protected]>
  - af33f76 [Module] Replace from_nn_module with native Module subcla... by Chien-Chin Huang <[email protected]>
  - 58b0344 Add FSDP symmetric memory configuration and related tests... by Masaki <[email protected]>
  (And 259 more changes)

PiperOrigin-RevId: 956923721
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants